mirror of
https://github.com/whyour/qinglong.git
synced 2026-11-30 16:27:21 +08:00
feat(cron): expose run receipts and modularize execution
Return committed trigger IDs and add CLI wait and trigger-specific logs while preserving API, CLI, transaction, deduplication and unknown-result semantics. Move scheduling, lifecycle, settlement, queries and legacy adapters into back/cron; remove obsolete internal import paths and circular dependencies. Apply project formatting across the repository, cover CJS/MJS in formatting hooks, add prettier:check and require formatting checks in AGENTS.md. Validation: backend build; 1398 backend/frontend tests passed (17 platform skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
1 parent
77ece406ac
commit
c5458596c8
346 files changed
+32133
-11556
No files matched your search
@@ -1,6 +1,6 @@
|
|||||||
name: "\U0001F680 New feature proposal"
|
name: "\U0001F680 New feature proposal"
|
||||||
description: Suggest an idea for this project
|
description: Suggest an idea for this project
|
||||||
labels: [":sparkles: feature request"]
|
labels: [':sparkles: feature request']
|
||||||
body:
|
body:
|
||||||
- type: markdown
|
- type: markdown
|
||||||
attributes:
|
attributes:
|
||||||
@@ -10,14 +10,14 @@ body:
|
|||||||
id: feature-description
|
id: feature-description
|
||||||
attributes:
|
attributes:
|
||||||
label: Clear and concise description of the problem
|
label: Clear and concise description of the problem
|
||||||
description: "Explain your use case, context, and rationale behind this feature request. More importantly, what is the **end user experience** you are trying to build that led to the need for this feature?"
|
description: 'Explain your use case, context, and rationale behind this feature request. More importantly, what is the **end user experience** you are trying to build that led to the need for this feature?'
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: suggested-solution
|
id: suggested-solution
|
||||||
attributes:
|
attributes:
|
||||||
label: Suggested solution
|
label: Suggested solution
|
||||||
description: "In module [xy] we could provide following implementation..."
|
description: 'In module [xy] we could provide following implementation...'
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
@@ -37,4 +37,4 @@ body:
|
|||||||
description: Before submitting the issue, please make sure you do the following
|
description: Before submitting the issue, please make sure you do the following
|
||||||
options:
|
options:
|
||||||
- label: Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
|
- label: Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
|
||||||
required: true
|
required: true
|
||||||
+1
-1
@@ -4,4 +4,4 @@ newPRWelcomeComment: |
|
|||||||
Please be patient and we will get back to you as soon as we can.
|
Please be patient and we will get back to you as soon as we can.
|
||||||
# Comment to be posted to on pull requests merged by a first time user
|
# Comment to be posted to on pull requests merged by a first time user
|
||||||
firstPRMergeComment: >
|
firstPRMergeComment: >
|
||||||
Congrats on merging your first pull request! 🎉🎉🎉
|
Congrats on merging your first pull request! 🎉🎉🎉
|
||||||
@@ -3,21 +3,21 @@ name: Build And Push Docker Image
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
paths:
|
paths:
|
||||||
- "**"
|
- '**'
|
||||||
- "!*.md"
|
- '!*.md'
|
||||||
# CLI is verified separately; its shared Bash upgrade engine ships in images.
|
# CLI is verified separately; its shared Bash upgrade engine ships in images.
|
||||||
- "!cli/**"
|
- '!cli/**'
|
||||||
- "cli/src/internal/maintenance/upgradeArtifacts.cjs"
|
- 'cli/src/internal/maintenance/upgradeArtifacts.cjs'
|
||||||
- "cli/src/internal/maintenance/platformBundle.cjs"
|
- 'cli/src/internal/maintenance/platformBundle.cjs'
|
||||||
- "cli/src/internal/maintenance/upgradePrestart.cjs"
|
- 'cli/src/internal/maintenance/upgradePrestart.cjs'
|
||||||
- "cli/src/internal/maintenance/panelUpgrade.cjs"
|
- 'cli/src/internal/maintenance/panelUpgrade.cjs'
|
||||||
- "cli/src/internal/maintenance/nodeRuntime.cjs"
|
- 'cli/src/internal/maintenance/nodeRuntime.cjs'
|
||||||
- "!.github/workflows/cli-package.yml"
|
- '!.github/workflows/cli-package.yml'
|
||||||
branches:
|
branches:
|
||||||
- "master"
|
- 'master'
|
||||||
- "develop"
|
- 'develop'
|
||||||
tags:
|
tags:
|
||||||
- "v*"
|
- 'v*'
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
static_sync_only:
|
static_sync_only:
|
||||||
@@ -85,12 +85,12 @@ jobs:
|
|||||||
run: echo "node-version=$(cat .nvmrc)" >> "$GITHUB_OUTPUT"
|
run: echo "node-version=$(cat .nvmrc)" >> "$GITHUB_OUTPUT"
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
with:
|
with:
|
||||||
version: "8.3.1"
|
version: '8.3.1'
|
||||||
|
|
||||||
- uses: actions/setup-node@v6
|
- uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version-file: ".nvmrc"
|
node-version-file: '.nvmrc'
|
||||||
cache: "pnpm"
|
cache: 'pnpm'
|
||||||
cache-dependency-path: pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: build front and back
|
- name: build front and back
|
||||||
@@ -253,11 +253,11 @@ jobs:
|
|||||||
path: static/
|
path: static/
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
with:
|
with:
|
||||||
version: "8.3.1"
|
version: '8.3.1'
|
||||||
- uses: actions/setup-node@v6
|
- uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version-file: ".nvmrc"
|
node-version-file: '.nvmrc'
|
||||||
cache: "pnpm"
|
cache: 'pnpm'
|
||||||
cache-dependency-path: pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: Read version from version.yaml
|
- name: Read version from version.yaml
|
||||||
@@ -342,11 +342,11 @@ jobs:
|
|||||||
path: static/
|
path: static/
|
||||||
- uses: pnpm/action-setup@v6
|
- uses: pnpm/action-setup@v6
|
||||||
with:
|
with:
|
||||||
version: "8.3.1"
|
version: '8.3.1'
|
||||||
- uses: actions/setup-node@v6
|
- uses: actions/setup-node@v6
|
||||||
with:
|
with:
|
||||||
node-version-file: ".nvmrc"
|
node-version-file: '.nvmrc'
|
||||||
cache: "pnpm"
|
cache: 'pnpm'
|
||||||
cache-dependency-path: pnpm-lock.yaml
|
cache-dependency-path: pnpm-lock.yaml
|
||||||
|
|
||||||
- name: Read version from version.yaml
|
- name: Read version from version.yaml
|
||||||
|
|||||||
+2
-1
@@ -12,6 +12,7 @@ npm-debug.log*
|
|||||||
yarn-error.log
|
yarn-error.log
|
||||||
yarn.lock
|
yarn.lock
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
pnpm-lock.yaml
|
||||||
/static
|
/static
|
||||||
/data
|
/data
|
||||||
DS_Store
|
DS_Store
|
||||||
@@ -21,4 +22,4 @@ DS_Store
|
|||||||
.env.local
|
.env.local
|
||||||
.env
|
.env
|
||||||
version.ts
|
version.ts
|
||||||
/.tmp
|
/.tmp
|
||||||
@@ -1,3 +1,9 @@
|
|||||||
|
# 代码格式
|
||||||
|
|
||||||
|
- 每次修改代码后,必须按项目的 `.prettierrc`、`.editorconfig` 和 `.prettierignore` 完成格式化,覆盖新增文件、静态及动态导入、`require()` 和测试代码。
|
||||||
|
- 在项目根目录执行 `npm run prettier`,随后执行 `npm run prettier:check`。检查必须通过;发现格式问题时须修复并重新检查,才能结束任务或提交代码。
|
||||||
|
- 检查通过后若再次修改代码,必须重新完成格式化和检查。不得以手动调整格式、编辑器设置或提交钩子代替上述验证。
|
||||||
|
|
||||||
<!-- gitnexus:start -->
|
<!-- gitnexus:start -->
|
||||||
# GitNexus — Code Intelligence
|
# GitNexus — Code Intelligence
|
||||||
|
|
||||||
|
|||||||
+6
-2
@@ -97,9 +97,13 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
// OpenAPI config scopes grant data-file access, not executable hooks.
|
// OpenAPI config scopes grant data-file access, not executable hooks.
|
||||||
if (/(?:^|\/)open\/configs(?:\/|\?|$)/.test(req.originalUrl || '')) {
|
if (/(?:^|\/)open\/configs(?:\/|\?|$)/.test(req.originalUrl || '')) {
|
||||||
const realPath = await fs.realpath(normalized).catch(() => normalized);
|
const realPath = await fs
|
||||||
|
.realpath(normalized)
|
||||||
|
.catch(() => normalized);
|
||||||
if (
|
if (
|
||||||
openApiProtectedFiles.has(path.basename(normalized).toLowerCase()) ||
|
openApiProtectedFiles.has(
|
||||||
|
path.basename(normalized).toLowerCase(),
|
||||||
|
) ||
|
||||||
openApiProtectedFiles.has(path.basename(realPath).toLowerCase())
|
openApiProtectedFiles.has(path.basename(realPath).toLowerCase())
|
||||||
) {
|
) {
|
||||||
return res.send({ code: 403, message: t('文件无法访问') });
|
return res.send({ code: 403, message: t('文件无法访问') });
|
||||||
|
|||||||
+208
-83
@@ -1,8 +1,12 @@
|
|||||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
import {
|
||||||
import { readDailyResults } from '../shared/legacyDailyStatistics';
|
executionIdPattern,
|
||||||
|
executionTriggerId,
|
||||||
|
receiptFinishTime,
|
||||||
|
} from '../cron/identity';
|
||||||
|
import { readDailyResults } from '../cron/settlement/legacyDailyStatistics';
|
||||||
import { PendingCronInstall } from '../shared/errors';
|
import { PendingCronInstall } from '../shared/errors';
|
||||||
import { triggerHistory } from '../shared/triggerHistory';
|
import { triggerHistory } from '../cron/history';
|
||||||
import { previewSchedule, withNextRun } from '../shared/cronPreview';
|
import { previewSchedule, withNextRun } from '../cron/queries/cronPreview';
|
||||||
import { Router, Request, Response, NextFunction } from 'express';
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
import { literal, Op } from 'sequelize';
|
import { literal, Op } from 'sequelize';
|
||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
@@ -11,10 +15,7 @@ import CronService from '../services/cron';
|
|||||||
import CronViewService from '../services/cronView';
|
import CronViewService from '../services/cronView';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import { commonCronSchema } from '../validation/schedule';
|
import { commonCronSchema } from '../validation/schedule';
|
||||||
import {
|
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||||
RunningInstanceModel,
|
|
||||||
InstanceStatus,
|
|
||||||
} from '../data/runningInstance';
|
|
||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import cronClient from '../schedule/client';
|
import cronClient from '../schedule/client';
|
||||||
|
|
||||||
@@ -25,8 +26,17 @@ export default (app: Router) => {
|
|||||||
|
|
||||||
route.use(async (req, res, next) => {
|
route.use(async (req, res, next) => {
|
||||||
// Keep stop/status callbacks available even when the scheduler is down.
|
// Keep stop/status callbacks available even when the scheduler is down.
|
||||||
if (['POST', 'PUT', 'DELETE'].includes(req.method) &&
|
if (
|
||||||
['/', '/run', '/enable', '/disable', '/views/enable', '/views/disable'].includes(req.path)) {
|
['POST', 'PUT', 'DELETE'].includes(req.method) &&
|
||||||
|
[
|
||||||
|
'/',
|
||||||
|
'/run',
|
||||||
|
'/enable',
|
||||||
|
'/disable',
|
||||||
|
'/views/enable',
|
||||||
|
'/views/disable',
|
||||||
|
].includes(req.path)
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
await cronClient.readiness.ensureReady();
|
await cronClient.readiness.ensureReady();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -171,23 +181,44 @@ export default (app: Router) => {
|
|||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const result = await cronService.crontabs(req.query as any, true);
|
const result = await cronService.crontabs(req.query as any, true);
|
||||||
return res.send({ code: 200, data: { ...result, data: result.data.map(withNextRun) } });
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: { ...result, data: result.data.map(withNextRun) },
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('🔥 error: %o', e);
|
logger.error('🔥 error: %o', e);
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
route.get('/preview', celebrate({ query: Joi.object({
|
route.get(
|
||||||
schedule: Joi.string().required(),
|
'/preview',
|
||||||
}).unknown(true) }), (req, res) => {
|
celebrate({
|
||||||
try {
|
query: Joi.object({
|
||||||
const times = previewSchedule(String(req.query.schedule), 3, Date.now());
|
schedule: Joi.string().required(),
|
||||||
return res.send({ code: 200, data: { times, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
|
}).unknown(true),
|
||||||
} catch {
|
}),
|
||||||
return res.status(400).send({ code: 400, message: t('Cron表达式格式有误') });
|
(req, res) => {
|
||||||
}
|
try {
|
||||||
});
|
const times = previewSchedule(
|
||||||
|
String(req.query.schedule),
|
||||||
|
3,
|
||||||
|
Date.now(),
|
||||||
|
);
|
||||||
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
times,
|
||||||
|
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return res
|
||||||
|
.status(400)
|
||||||
|
.send({ code: 400, message: t('Cron表达式格式有误') });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/detail',
|
'/detail',
|
||||||
@@ -218,7 +249,9 @@ export default (app: Router) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof PendingCronInstall) {
|
if (e instanceof PendingCronInstall) {
|
||||||
return res.status(e.status).send({
|
return res.status(e.status).send({
|
||||||
code: e.status, message: e.message, data: { id: e.cronId, saved: false },
|
code: e.status,
|
||||||
|
message: e.message,
|
||||||
|
data: { id: e.cronId, saved: false },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -246,14 +279,19 @@ export default (app: Router) => {
|
|||||||
route.put(
|
route.put(
|
||||||
'/stop',
|
'/stop',
|
||||||
celebrate({
|
celebrate({
|
||||||
headers: Joi.object({ 'idempotency-key': Joi.string().guid().optional() }).unknown(true),
|
headers: Joi.object({
|
||||||
|
'idempotency-key': Joi.string().guid().optional(),
|
||||||
|
}).unknown(true),
|
||||||
body: Joi.array().items(Joi.number().required()),
|
body: Joi.array().items(Joi.number().required()),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.stop(req.body, req.get('Idempotency-Key'));
|
const data = await cronService.stop(
|
||||||
|
req.body,
|
||||||
|
req.get('Idempotency-Key'),
|
||||||
|
);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -349,7 +387,9 @@ export default (app: Router) => {
|
|||||||
instanceId: Joi.number().integer().positive().optional(),
|
instanceId: Joi.number().integer().positive().optional(),
|
||||||
previousPath: Joi.string().optional(),
|
previousPath: Joi.string().optional(),
|
||||||
follow: Joi.boolean().optional(),
|
follow: Joi.boolean().optional(),
|
||||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
cursor: Joi.string()
|
||||||
|
.pattern(/^\d{1,16}\.[a-f0-9]{64}$/)
|
||||||
|
.optional(),
|
||||||
offset: Joi.number().integer().min(0).optional(),
|
offset: Joi.number().integer().min(0).optional(),
|
||||||
limit: Joi.number()
|
limit: Joi.number()
|
||||||
.integer()
|
.integer()
|
||||||
@@ -366,7 +406,10 @@ export default (app: Router) => {
|
|||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const result = await cronService.log(req.params.id, {
|
const result = await cronService.log(req.params.id, {
|
||||||
triggerId: req.query.triggerId as string | undefined,
|
triggerId: req.query.triggerId as string | undefined,
|
||||||
instanceId: req.query.instanceId === undefined ? undefined : Number(req.query.instanceId),
|
instanceId:
|
||||||
|
req.query.instanceId === undefined
|
||||||
|
? undefined
|
||||||
|
: Number(req.query.instanceId),
|
||||||
previousPath: req.query.previousPath as string | undefined,
|
previousPath: req.query.previousPath as string | undefined,
|
||||||
follow: req.query.follow as unknown as boolean,
|
follow: req.query.follow as unknown as boolean,
|
||||||
cursor: req.query.cursor as string | undefined,
|
cursor: req.query.cursor as string | undefined,
|
||||||
@@ -416,10 +459,18 @@ export default (app: Router) => {
|
|||||||
route.delete(
|
route.delete(
|
||||||
'/',
|
'/',
|
||||||
celebrate({
|
celebrate({
|
||||||
body: Joi.array().min(1).items(Joi.number().integer().positive(), Joi.object({
|
body: Joi.array()
|
||||||
id: Joi.number().integer().positive().required(), script: Joi.string().required(),
|
.min(1)
|
||||||
revision: Joi.number().integer(), command: Joi.string(), sub_id: Joi.number().integer().allow(null),
|
.items(
|
||||||
})),
|
Joi.number().integer().positive(),
|
||||||
|
Joi.object({
|
||||||
|
id: Joi.number().integer().positive().required(),
|
||||||
|
script: Joi.string().required(),
|
||||||
|
revision: Joi.number().integer(),
|
||||||
|
command: Joi.string(),
|
||||||
|
sub_id: Joi.number().integer().allow(null),
|
||||||
|
}),
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
@@ -513,7 +564,9 @@ export default (app: Router) => {
|
|||||||
exit_code: Joi.number().optional().allow(null),
|
exit_code: Joi.number().optional().allow(null),
|
||||||
trigger_stopped: Joi.boolean().optional(),
|
trigger_stopped: Joi.boolean().optional(),
|
||||||
execution_id: Joi.string().pattern(executionIdPattern).optional(),
|
execution_id: Joi.string().pattern(executionIdPattern).optional(),
|
||||||
trigger_id: Joi.string().pattern(/^[a-z0-9-]{1,120}$/).optional(),
|
trigger_id: Joi.string()
|
||||||
|
.pattern(/^[a-z0-9-]{1,120}$/)
|
||||||
|
.optional(),
|
||||||
}).oxor('execution_id', 'trigger_id'),
|
}).oxor('execution_id', 'trigger_id'),
|
||||||
}),
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
@@ -534,56 +587,100 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.get('/:id/daily-results', celebrate({
|
route.get(
|
||||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
'/:id/daily-results',
|
||||||
}), async (req, res, next) => {
|
celebrate({
|
||||||
try {
|
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||||
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
|
}),
|
||||||
return res.send({ code: 200, data });
|
async (req, res, next) => {
|
||||||
} catch (error) {
|
try {
|
||||||
return next(error);
|
const data = await readDailyResults(
|
||||||
}
|
RunningInstanceModel.sequelize!,
|
||||||
});
|
Number(req.params.id),
|
||||||
|
);
|
||||||
route.get('/:id/triggers', celebrate({
|
return res.send({ code: 200, data });
|
||||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
} catch (error) {
|
||||||
query: Joi.object({
|
return next(error);
|
||||||
offset: Joi.number().integer().min(0),
|
|
||||||
limit: Joi.number().integer().min(1).max(26).default(25),
|
|
||||||
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
|
|
||||||
beforeTime: Joi.number().integer().min(0),
|
|
||||||
beforeId: Joi.string().max(256),
|
|
||||||
}).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true),
|
|
||||||
}), async (req, res, next) => {
|
|
||||||
try {
|
|
||||||
const { offset, limit, beforeTime, beforeId, ids } = req.query;
|
|
||||||
const history = triggerHistory();
|
|
||||||
const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined;
|
|
||||||
const data = ids
|
|
||||||
? await history.visibleTriggers(Number(req.params.id), ids as string[])
|
|
||||||
: await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before);
|
|
||||||
if (req.query.withQueueWait === 'true') {
|
|
||||||
const now = Date.now();
|
|
||||||
return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null
|
|
||||||
? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) });
|
|
||||||
}
|
}
|
||||||
return res.send({ code: 200, data });
|
},
|
||||||
} catch (err) { next(err); }
|
);
|
||||||
});
|
|
||||||
|
route.get(
|
||||||
|
'/:id/triggers',
|
||||||
|
celebrate({
|
||||||
|
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||||
|
query: Joi.object({
|
||||||
|
offset: Joi.number().integer().min(0),
|
||||||
|
limit: Joi.number().integer().min(1).max(26).default(25),
|
||||||
|
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
|
||||||
|
beforeTime: Joi.number().integer().min(0),
|
||||||
|
beforeId: Joi.string().max(256),
|
||||||
|
})
|
||||||
|
.and('beforeTime', 'beforeId')
|
||||||
|
.oxor('offset', 'beforeTime', 'ids')
|
||||||
|
.unknown(true),
|
||||||
|
}),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { offset, limit, beforeTime, beforeId, ids } = req.query;
|
||||||
|
const history = triggerHistory();
|
||||||
|
const before = beforeId
|
||||||
|
? { time: Number(beforeTime), id: String(beforeId) }
|
||||||
|
: undefined;
|
||||||
|
const data = ids
|
||||||
|
? await history.visibleTriggers(
|
||||||
|
Number(req.params.id),
|
||||||
|
ids as string[],
|
||||||
|
)
|
||||||
|
: await history.recent(
|
||||||
|
Number(req.params.id),
|
||||||
|
Number(offset || 0),
|
||||||
|
Number(limit),
|
||||||
|
before,
|
||||||
|
);
|
||||||
|
if (req.query.withQueueWait === 'true') {
|
||||||
|
const now = Date.now();
|
||||||
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: data.map((row) =>
|
||||||
|
row.state === 'queued' && row.queued_at != null
|
||||||
|
? {
|
||||||
|
...row,
|
||||||
|
queue_wait_ms: Math.max(
|
||||||
|
0,
|
||||||
|
(row.dequeued_at ?? now) - row.queued_at,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: row,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return res.send({ code: 200, data });
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
route.get(
|
route.get(
|
||||||
'/:id/instances',
|
'/:id/instances',
|
||||||
celebrate({
|
celebrate({
|
||||||
// This route historically ignored query parameters. Only validate and
|
// This route historically ignored query parameters. Only validate and
|
||||||
// apply cursor options when the caller explicitly requests pagination.
|
// apply cursor options when the caller explicitly requests pagination.
|
||||||
query: Joi.alternatives().conditional(Joi.object({ paged: Joi.valid('true').required() }).unknown(), {
|
query: Joi.alternatives().conditional(
|
||||||
then: Joi.object({
|
Joi.object({ paged: Joi.valid('true').required() }).unknown(),
|
||||||
limit: Joi.number().integer().min(1).max(100),
|
{
|
||||||
before: Joi.number().integer().positive(),
|
then: Joi.object({
|
||||||
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
|
limit: Joi.number().integer().min(1).max(100),
|
||||||
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
|
before: Joi.number().integer().positive(),
|
||||||
otherwise: Joi.object().unknown(true),
|
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
|
||||||
}),
|
})
|
||||||
|
.unknown(true)
|
||||||
|
.oxor('ids', 'limit')
|
||||||
|
.oxor('ids', 'before'),
|
||||||
|
otherwise: Joi.object().unknown(true),
|
||||||
|
},
|
||||||
|
),
|
||||||
params: Joi.object({
|
params: Joi.object({
|
||||||
id: Joi.number().required(),
|
id: Joi.number().required(),
|
||||||
}),
|
}),
|
||||||
@@ -594,27 +691,48 @@ export default (app: Router) => {
|
|||||||
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
|
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
|
||||||
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
|
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
|
||||||
const paged = req.query.paged === 'true';
|
const paged = req.query.paged === 'true';
|
||||||
const ids = paged && req.query.ids ? String(req.query.ids).split(',').map(Number) : undefined;
|
const ids =
|
||||||
|
paged && req.query.ids
|
||||||
|
? String(req.query.ids).split(',').map(Number)
|
||||||
|
: undefined;
|
||||||
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
|
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
|
||||||
const instances = await RunningInstanceModel.findAll({
|
const instances = await RunningInstanceModel.findAll({
|
||||||
attributes: {
|
attributes: {
|
||||||
exclude: ['finished_at', 'exit_code'],
|
exclude: ['finished_at', 'exit_code'],
|
||||||
include: [
|
include: [
|
||||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`), 'finished_at'],
|
[
|
||||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`), 'exit_code'],
|
literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`),
|
||||||
|
'finished_at',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`),
|
||||||
|
'exit_code',
|
||||||
|
],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
where: {
|
where: {
|
||||||
cron_id: req.params.id,
|
cron_id: req.params.id,
|
||||||
...(ids && { id: { [Op.in]: ids } }),
|
...(ids && { id: { [Op.in]: ids } }),
|
||||||
...(paged && req.query.before && { id: { [Op.lt]: Number(req.query.before) } }),
|
...(paged &&
|
||||||
|
req.query.before && {
|
||||||
|
id: { [Op.lt]: Number(req.query.before) },
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
order: paged ? [['id', 'DESC']] : [['started_at', 'DESC'], ['id', 'DESC']],
|
order: paged
|
||||||
|
? [['id', 'DESC']]
|
||||||
|
: [
|
||||||
|
['started_at', 'DESC'],
|
||||||
|
['id', 'DESC'],
|
||||||
|
],
|
||||||
...(limit && { limit: limit + 1 }),
|
...(limit && { limit: limit + 1 }),
|
||||||
raw: true,
|
raw: true,
|
||||||
});
|
});
|
||||||
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
|
if (limit)
|
||||||
next: instances.length > limit ? instances[limit - 1].id : null });
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: instances.slice(0, limit),
|
||||||
|
next: instances.length > limit ? instances[limit - 1].id : null,
|
||||||
|
});
|
||||||
return res.send({ code: 200, data: instances });
|
return res.send({ code: 200, data: instances });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -630,10 +748,17 @@ export default (app: Router) => {
|
|||||||
instanceId: Joi.number().required(),
|
instanceId: Joi.number().required(),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
async (req: Request<{ id: number; instanceId: number }>, res: Response, next: NextFunction) => {
|
async (
|
||||||
|
req: Request<{ id: number; instanceId: number }>,
|
||||||
|
res: Response,
|
||||||
|
next: NextFunction,
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
const cronService = Container.get(CronService);
|
const cronService = Container.get(CronService);
|
||||||
const data = await cronService.stopInstance(Number(req.params.id), Number(req.params.instanceId));
|
const data = await cronService.stopInstance(
|
||||||
|
Number(req.params.id),
|
||||||
|
Number(req.params.instanceId),
|
||||||
|
);
|
||||||
return res.status(data.code).send(data);
|
return res.status(data.code).send(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
|
|||||||
+241
-97
@@ -1,23 +1,24 @@
|
|||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { stat } from 'fs/promises';
|
import { stat } from 'fs/promises';
|
||||||
import { resolveFileAccess } from '../shared/fileAccess';
|
import { resolveFileAccess } from '../shared/fileAccess';
|
||||||
import { AnomalyPage, AnomalyKind } from '../shared/scheduleAnomalies';
|
import { AnomalyPage, AnomalyKind } from '../cron/queries/scheduleAnomalies';
|
||||||
import { auditSchedule } from '../shared/scheduleAudit';
|
import { auditSchedule } from '../cron/scheduling/scheduleAudit';
|
||||||
import { systemScheduleAudit } from '../shared/systemScheduleAudit';
|
import { systemScheduleAudit } from '../cron/scheduling/systemScheduleAudit';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
import {
|
||||||
import { oldestQueued } from '../shared/queueDiagnostics';
|
executionIdPattern,
|
||||||
|
executionTriggerId,
|
||||||
|
receiptFinishTime,
|
||||||
|
} from '../cron/identity';
|
||||||
|
import { oldestQueued } from '../cron/queries/queueDiagnostics';
|
||||||
import { containerResources } from '../shared/containerResources';
|
import { containerResources } from '../shared/containerResources';
|
||||||
import { TriggerHistory } from '../shared/triggerHistory';
|
import { TriggerHistory } from '../cron/history';
|
||||||
import { Router, Request, Response, NextFunction } from 'express';
|
import { Router, Request, Response, NextFunction } from 'express';
|
||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import { fn, col, where, Op, QueryTypes } from 'sequelize';
|
import { fn, col, where, Op, QueryTypes } from 'sequelize';
|
||||||
import { CrontabModel } from '../data/cron';
|
import { CrontabModel } from '../data/cron';
|
||||||
import { CrontabStatModel } from '../data/cronStats';
|
import { CrontabStatModel } from '../data/cronStats';
|
||||||
import {
|
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||||
RunningInstanceModel,
|
|
||||||
InstanceStatus,
|
|
||||||
} from '../data/runningInstance';
|
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import { isEmpty } from 'lodash';
|
import { isEmpty } from 'lodash';
|
||||||
@@ -38,21 +39,49 @@ export default (app: Router) => {
|
|||||||
const { ref_id, code, elapsed, trigger_id, execution_id } = req.body;
|
const { ref_id, code, elapsed, trigger_id, execution_id } = req.body;
|
||||||
if (!ref_id) return res.send({ code: 400, message: 'ref_id required' });
|
if (!ref_id) return res.send({ code: 400, message: 'ref_id required' });
|
||||||
|
|
||||||
if (trigger_id != null && (typeof trigger_id !== 'string' || !/^[a-z0-9-]{1,120}$/.test(trigger_id))) {
|
if (
|
||||||
|
trigger_id != null &&
|
||||||
|
(typeof trigger_id !== 'string' ||
|
||||||
|
!/^[a-z0-9-]{1,120}$/.test(trigger_id))
|
||||||
|
) {
|
||||||
return res.send({ code: 400 });
|
return res.send({ code: 400 });
|
||||||
}
|
}
|
||||||
if (execution_id !== undefined && (trigger_id !== undefined ||
|
if (
|
||||||
typeof execution_id !== 'string' || !executionIdPattern.test(execution_id))) return res.send({ code: 400 });
|
execution_id !== undefined &&
|
||||||
|
(trigger_id !== undefined ||
|
||||||
|
typeof execution_id !== 'string' ||
|
||||||
|
!executionIdPattern.test(execution_id))
|
||||||
|
)
|
||||||
|
return res.send({ code: 400 });
|
||||||
const id = execution_id ? executionTriggerId(execution_id) : trigger_id;
|
const id = execution_id ? executionTriggerId(execution_id) : trigger_id;
|
||||||
// Old wrappers also send a status receipt with the process identity.
|
// Old wrappers also send a status receipt with the process identity.
|
||||||
// A stats-only retry cannot be distinguished from another identical run.
|
// A stats-only retry cannot be distinguished from another identical run.
|
||||||
if (!id) return res.send({ code: 200, data: { counted: false, reason: 'missing_execution_identity' } });
|
if (!id)
|
||||||
const exitCode = typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: { counted: false, reason: 'missing_execution_identity' },
|
||||||
|
});
|
||||||
|
const exitCode =
|
||||||
|
typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
|
||||||
const elapsedMs = Number(elapsed ?? 0) * 1000;
|
const elapsedMs = Number(elapsed ?? 0) * 1000;
|
||||||
if (!Number.isInteger(exitCode) || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0) {
|
if (
|
||||||
return res.send({ code: 400, message: 'invalid exit code or elapsed time' });
|
!Number.isInteger(exitCode) ||
|
||||||
|
!Number.isSafeInteger(elapsedMs) ||
|
||||||
|
elapsedMs < 0
|
||||||
|
) {
|
||||||
|
return res.send({
|
||||||
|
code: 400,
|
||||||
|
message: 'invalid exit code or elapsed time',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(id, Number(ref_id), exitCode, elapsedMs, Date.now(), receiptFinishTime(req.get('X-QL-Finished-At')));
|
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(
|
||||||
|
id,
|
||||||
|
Number(ref_id),
|
||||||
|
exitCode,
|
||||||
|
elapsedMs,
|
||||||
|
Date.now(),
|
||||||
|
receiptFinishTime(req.get('X-QL-Finished-At')),
|
||||||
|
);
|
||||||
res.send({ code: 200 });
|
res.send({ code: 200 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.send({ code: 500 });
|
res.send({ code: 500 });
|
||||||
@@ -82,7 +111,9 @@ export default (app: Router) => {
|
|||||||
where: { date: today },
|
where: { date: today },
|
||||||
raw: true,
|
raw: true,
|
||||||
}),
|
}),
|
||||||
new TriggerHistory(CrontabStatModel.sequelize!).metrics(day.valueOf()),
|
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
|
||||||
|
day.valueOf(),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const row = stats as any;
|
const row = stats as any;
|
||||||
@@ -104,8 +135,11 @@ export default (app: Router) => {
|
|||||||
todaySuccess: totalSuccess,
|
todaySuccess: totalSuccess,
|
||||||
todayFail: totalFail,
|
todayFail: totalFail,
|
||||||
todayStopped: totalRuns - totalSuccess - totalFail,
|
todayStopped: totalRuns - totalSuccess - totalFail,
|
||||||
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
|
successRate:
|
||||||
avgTime: averageElapsed(totalTime,totalRuns,row?.untimed_count),
|
totalRuns > 0
|
||||||
|
? ((totalSuccess / totalRuns) * 100).toFixed(1)
|
||||||
|
: '0',
|
||||||
|
avgTime: averageElapsed(totalTime, totalRuns, row?.untimed_count),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -114,55 +148,115 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.get('/schedule-anomalies', celebrate({ query: Joi.object({
|
route.get(
|
||||||
source: Joi.string().valid('panel', 'system').required(),
|
'/schedule-anomalies',
|
||||||
kind: Joi.string().valid('missing', 'skipped', 'unconfirmed').required(),
|
celebrate({
|
||||||
at: Joi.number().integer().positive().required(),
|
query: Joi.object({
|
||||||
page: Joi.number().integer().min(1).default(1),
|
source: Joi.string().valid('panel', 'system').required(),
|
||||||
revision: Joi.string().hex().length(64),
|
kind: Joi.string()
|
||||||
live: Joi.boolean().default(false),
|
.valid('missing', 'skipped', 'unconfirmed')
|
||||||
}).unknown(true) }), async (req, res, next) => {
|
.required(),
|
||||||
try {
|
at: Joi.number().integer().positive().required(),
|
||||||
const { source, kind, page, at, revision, live } = req.query;
|
page: Joi.number().integer().min(1).default(1),
|
||||||
const until = Number(at);
|
revision: Joi.string().hex().length(64),
|
||||||
const serverNow = Date.now();
|
live: Joi.boolean().default(false),
|
||||||
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
|
}).unknown(true),
|
||||||
if (live && serverNow >= expiresAt)
|
}),
|
||||||
return res.send({ code: 200, data: { status: 'expired' } });
|
async (req, res, next) => {
|
||||||
if (until > Date.now() || until < dayjs().subtract(1, 'day').startOf('day').valueOf())
|
try {
|
||||||
return res.status(400).send({ code: 400 });
|
const { source, kind, page, at, revision, live } = req.query;
|
||||||
const [snapshotRetention] = live ? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
|
const until = Number(at);
|
||||||
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
|
const serverNow = Date.now();
|
||||||
) : [];
|
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
|
||||||
const details = new AnomalyPage(kind as AnomalyKind, Number(page), revision as string | undefined);
|
if (live && serverNow >= expiresAt)
|
||||||
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
|
return res.send({ code: 200, data: { status: 'expired' } });
|
||||||
const summary = await audit(CrontabStatModel.sequelize!, dayjs(until).startOf('day').valueOf(), until, details);
|
if (
|
||||||
if (live && (!summary || summary.since > summary.through))
|
until > Date.now() ||
|
||||||
return res.send({ code: 200, data: { status: 'unavailable' } });
|
until < dayjs().subtract(1, 'day').startOf('day').valueOf()
|
||||||
if (!summary) return res.status(409).send({ code: 409 });
|
)
|
||||||
const result = details.result();
|
return res.status(400).send({ code: 400 });
|
||||||
const ids = [...new Set(result.rows.filter(row => !row.name).map(row => row.task))];
|
const [snapshotRetention] = live
|
||||||
const tasks = ids.length ? await CrontabModel.findAll({ where: { id: ids }, attributes: ['id','name','command'], raw: true }) : [];
|
? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
|
||||||
const names = new Map(tasks.map(task => [task.id, task.name || task.command]));
|
'SELECT cutoff FROM CronHistoryRetention WHERE id=1',
|
||||||
const rows = await Promise.all(result.rows.map(async ({ logPath, ...row }) => {
|
{ type: QueryTypes.SELECT },
|
||||||
const path = logPath && resolveFileAccess(config.logPath, [logPath]);
|
)
|
||||||
const hasLog = path ? await stat(path).then(file => file.isFile(), () => false) : false;
|
: [];
|
||||||
return { ...row, name: row.name || names.get(row.task), hasLog };
|
const details = new AnomalyPage(
|
||||||
}));
|
kind as AnomalyKind,
|
||||||
// Log checks can yield after the audit transaction. Do not publish that
|
Number(page),
|
||||||
// snapshot if history cleanup has since removed part of its plan window.
|
revision as string | undefined,
|
||||||
if (live) {
|
|
||||||
const [retention] = await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
|
|
||||||
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
|
|
||||||
);
|
);
|
||||||
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
|
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
|
||||||
|
const summary = await audit(
|
||||||
|
CrontabStatModel.sequelize!,
|
||||||
|
dayjs(until).startOf('day').valueOf(),
|
||||||
|
until,
|
||||||
|
details,
|
||||||
|
);
|
||||||
|
if (live && (!summary || summary.since > summary.through))
|
||||||
return res.send({ code: 200, data: { status: 'unavailable' } });
|
return res.send({ code: 200, data: { status: 'unavailable' } });
|
||||||
|
if (!summary) return res.status(409).send({ code: 409 });
|
||||||
|
const result = details.result();
|
||||||
|
const ids = [
|
||||||
|
...new Set(
|
||||||
|
result.rows.filter((row) => !row.name).map((row) => row.task),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
const tasks = ids.length
|
||||||
|
? await CrontabModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
attributes: ['id', 'name', 'command'],
|
||||||
|
raw: true,
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
const names = new Map(
|
||||||
|
tasks.map((task) => [task.id, task.name || task.command]),
|
||||||
|
);
|
||||||
|
const rows = await Promise.all(
|
||||||
|
result.rows.map(async ({ logPath, ...row }) => {
|
||||||
|
const path =
|
||||||
|
logPath && resolveFileAccess(config.logPath, [logPath]);
|
||||||
|
const hasLog = path
|
||||||
|
? await stat(path).then(
|
||||||
|
(file) => file.isFile(),
|
||||||
|
() => false,
|
||||||
|
)
|
||||||
|
: false;
|
||||||
|
return { ...row, name: row.name || names.get(row.task), hasLog };
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// Log checks can yield after the audit transaction. Do not publish that
|
||||||
|
// snapshot if history cleanup has since removed part of its plan window.
|
||||||
|
if (live) {
|
||||||
|
const [retention] = await CrontabStatModel.sequelize!.query<{
|
||||||
|
cutoff: number;
|
||||||
|
}>('SELECT cutoff FROM CronHistoryRetention WHERE id=1', {
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
});
|
||||||
|
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
|
||||||
|
return res.send({ code: 200, data: { status: 'unavailable' } });
|
||||||
|
}
|
||||||
|
if (live && Date.now() >= expiresAt)
|
||||||
|
return res.send({ code: 200, data: { status: 'expired' } });
|
||||||
|
return res.send({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
...result,
|
||||||
|
rows,
|
||||||
|
serverNow,
|
||||||
|
expiresAt,
|
||||||
|
summary:
|
||||||
|
source === 'panel'
|
||||||
|
? { audit: summary }
|
||||||
|
: { systemAudit: summary },
|
||||||
|
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
}
|
}
|
||||||
if (live && Date.now() >= expiresAt)
|
},
|
||||||
return res.send({ code: 200, data: { status: 'expired' } });
|
);
|
||||||
return res.send({ code: 200, data: { ...result, rows, serverNow, expiresAt, summary: source === 'panel' ? { audit: summary } : { systemAudit: summary }, zone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
|
|
||||||
} catch (error) { next(error); }
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const isSuccess of [false, true]) {
|
for (const isSuccess of [false, true]) {
|
||||||
route.get(
|
route.get(
|
||||||
@@ -171,17 +265,31 @@ export default (app: Router) => {
|
|||||||
try {
|
try {
|
||||||
const countColumn = isSuccess ? 'success_count' : 'fail_count';
|
const countColumn = isSuccess ? 'success_count' : 'fail_count';
|
||||||
const rows = (await CrontabStatModel.findAll({
|
const rows = (await CrontabStatModel.findAll({
|
||||||
attributes: ['ref_id', [fn('SUM', col(countColumn)), 'result_count']],
|
attributes: [
|
||||||
where: { date: dayjs().format('YYYY-MM-DD'), [countColumn]: { [Op.gt]: 0 } },
|
'ref_id',
|
||||||
|
[fn('SUM', col(countColumn)), 'result_count'],
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
date: dayjs().format('YYYY-MM-DD'),
|
||||||
|
[countColumn]: { [Op.gt]: 0 },
|
||||||
|
},
|
||||||
group: ['ref_id'],
|
group: ['ref_id'],
|
||||||
order: [[fn('SUM', col(countColumn)), 'DESC'], ['ref_id', 'ASC']],
|
order: [
|
||||||
|
[fn('SUM', col(countColumn)), 'DESC'],
|
||||||
|
['ref_id', 'ASC'],
|
||||||
|
],
|
||||||
raw: true,
|
raw: true,
|
||||||
})) as any[];
|
})) as any[];
|
||||||
const crons = rows.length > 0 ? await CrontabModel.findAll({
|
const crons =
|
||||||
attributes: ['id', 'name', 'command'],
|
rows.length > 0
|
||||||
where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } },
|
? await CrontabModel.findAll({
|
||||||
raw: true,
|
attributes: ['id', 'name', 'command'],
|
||||||
}) : [];
|
where: {
|
||||||
|
id: { [Op.in]: rows.map((row) => Number(row.ref_id)) },
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
})
|
||||||
|
: [];
|
||||||
const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
|
const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
|
||||||
res.send({
|
res.send({
|
||||||
code: 200,
|
code: 200,
|
||||||
@@ -192,7 +300,9 @@ export default (app: Router) => {
|
|||||||
id,
|
id,
|
||||||
name: cron?.name || cron?.command || tf('任务#%s', id),
|
name: cron?.name || cron?.command || tf('任务#%s', id),
|
||||||
command: cron?.command || '',
|
command: cron?.command || '',
|
||||||
[isSuccess ? 'successCount' : 'failCount']: Number(row.result_count),
|
[isSuccess ? 'successCount' : 'failCount']: Number(
|
||||||
|
row.result_count,
|
||||||
|
),
|
||||||
deleted: !cron,
|
deleted: !cron,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
@@ -212,9 +322,10 @@ export default (app: Router) => {
|
|||||||
const days =
|
const days =
|
||||||
requestedDays === undefined
|
requestedDays === undefined
|
||||||
? 7
|
? 7
|
||||||
: typeof requestedDays === 'string' && /^[1-9]\d{0,2}$/.test(requestedDays)
|
: typeof requestedDays === 'string' &&
|
||||||
? Number(requestedDays)
|
/^[1-9]\d{0,2}$/.test(requestedDays)
|
||||||
: NaN;
|
? Number(requestedDays)
|
||||||
|
: NaN;
|
||||||
if (!Number.isInteger(days) || days > 365) {
|
if (!Number.isInteger(days) || days > 365) {
|
||||||
return res.status(400).send({ code: 400, message: t('无效的天数') });
|
return res.status(400).send({ code: 400, message: t('无效的天数') });
|
||||||
}
|
}
|
||||||
@@ -286,12 +397,14 @@ export default (app: Router) => {
|
|||||||
raw: true,
|
raw: true,
|
||||||
});
|
});
|
||||||
const nameMap: Record<number, string> = {};
|
const nameMap: Record<number, string> = {};
|
||||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
crons.forEach((c: any) => {
|
||||||
|
nameMap[c.id] = c.name || c.command;
|
||||||
|
});
|
||||||
|
|
||||||
const data = rows.map((r: any, i) => ({
|
const data = rows.map((r: any, i) => ({
|
||||||
rank: i + 1,
|
rank: i + 1,
|
||||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count),
|
||||||
maxTime: Number(r.max_time),
|
maxTime: Number(r.max_time),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -329,16 +442,20 @@ export default (app: Router) => {
|
|||||||
raw: true,
|
raw: true,
|
||||||
});
|
});
|
||||||
const nameMap: Record<number, string> = {};
|
const nameMap: Record<number, string> = {};
|
||||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
crons.forEach((c: any) => {
|
||||||
|
nameMap[c.id] = c.name || c.command;
|
||||||
|
});
|
||||||
|
|
||||||
const data = rows.map((r: any, i) => ({
|
const data = rows.map((r: any, i) => ({
|
||||||
rank: i + 1,
|
rank: i + 1,
|
||||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||||
runCount: Number(r.run_count),
|
runCount: Number(r.run_count),
|
||||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count),
|
||||||
successRate:
|
successRate:
|
||||||
Number(r.run_count) > 0
|
Number(r.run_count) > 0
|
||||||
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(1)
|
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(
|
||||||
|
1,
|
||||||
|
)
|
||||||
: '0',
|
: '0',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -353,7 +470,9 @@ export default (app: Router) => {
|
|||||||
'/runtime',
|
'/runtime',
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const queued = await new TriggerHistory(CrontabModel.sequelize!).queueCounts();
|
const queued = await new TriggerHistory(
|
||||||
|
CrontabModel.sequelize!,
|
||||||
|
).queueCounts();
|
||||||
const runningInstances = await RunningInstanceModel.findAll({
|
const runningInstances = await RunningInstanceModel.findAll({
|
||||||
where: {
|
where: {
|
||||||
status: InstanceStatus.running,
|
status: InstanceStatus.running,
|
||||||
@@ -368,9 +487,9 @@ export default (app: Router) => {
|
|||||||
const crons =
|
const crons =
|
||||||
cronIds.length > 0
|
cronIds.length > 0
|
||||||
? await CrontabModel.findAll({
|
? await CrontabModel.findAll({
|
||||||
where: { id: cronIds },
|
where: { id: cronIds },
|
||||||
raw: true,
|
raw: true,
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
const cronMap = new Map(crons.map((c: any) => [c.id, c]));
|
const cronMap = new Map(crons.map((c: any) => [c.id, c]));
|
||||||
|
|
||||||
@@ -405,7 +524,9 @@ export default (app: Router) => {
|
|||||||
runningCount: running.length,
|
runningCount: running.length,
|
||||||
queuedCount: queued.triggers,
|
queuedCount: queued.triggers,
|
||||||
queuedTasks: queued.tasks,
|
queuedTasks: queued.tasks,
|
||||||
oldestQueued: queued.triggers ? await oldestQueued(CrontabModel.sequelize!) : [],
|
oldestQueued: queued.triggers
|
||||||
|
? await oldestQueued(CrontabModel.sequelize!)
|
||||||
|
: [],
|
||||||
running,
|
running,
|
||||||
idleTasks: idleTasks.map((c: any) => ({
|
idleTasks: idleTasks.map((c: any) => ({
|
||||||
id: c.id,
|
id: c.id,
|
||||||
@@ -427,27 +548,49 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const today = dayjs().format('YYYY-MM-DD');
|
const today = dayjs().format('YYYY-MM-DD');
|
||||||
const [crons, stats] = (await Promise.all([
|
const [crons, stats] = await Promise.all([
|
||||||
CrontabModel.findAll({ where: { isDisabled: 0 }, raw: true }),
|
CrontabModel.findAll({ where: { isDisabled: 0 }, raw: true }),
|
||||||
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
|
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
|
||||||
]));
|
]);
|
||||||
|
|
||||||
const statMap: Record<number, any> = {};
|
const statMap: Record<number, any> = {};
|
||||||
stats.forEach((s: any) => { statMap[s.ref_id] = s; });
|
stats.forEach((s: any) => {
|
||||||
|
statMap[s.ref_id] = s;
|
||||||
|
});
|
||||||
|
|
||||||
const labelMap: Record<string, { count: number; runs: number; success: number; untimed: number; totalTime: number }> = {};
|
const labelMap: Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
count: number;
|
||||||
|
runs: number;
|
||||||
|
success: number;
|
||||||
|
untimed: number;
|
||||||
|
totalTime: number;
|
||||||
|
}
|
||||||
|
> = {};
|
||||||
crons.forEach((c) => {
|
crons.forEach((c) => {
|
||||||
let rawLabels = c.labels;
|
let rawLabels = c.labels;
|
||||||
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
|
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
|
||||||
const labels: string[] = Array.isArray(rawLabels)
|
const labels: string[] = Array.isArray(rawLabels)
|
||||||
? [...new Set((rawLabels as string[]).filter((l: string) => !isEmpty(l)))]
|
? [
|
||||||
|
...new Set(
|
||||||
|
(rawLabels as string[]).filter((l: string) => !isEmpty(l)),
|
||||||
|
),
|
||||||
|
]
|
||||||
: [];
|
: [];
|
||||||
if (labels.length === 0) {
|
if (labels.length === 0) {
|
||||||
labels.push(t('未分类'));
|
labels.push(t('未分类'));
|
||||||
}
|
}
|
||||||
const st = statMap[c.id!];
|
const st = statMap[c.id!];
|
||||||
labels.forEach((label: string) => {
|
labels.forEach((label: string) => {
|
||||||
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, untimed: 0, totalTime: 0 };
|
if (!labelMap[label])
|
||||||
|
labelMap[label] = {
|
||||||
|
count: 0,
|
||||||
|
runs: 0,
|
||||||
|
success: 0,
|
||||||
|
untimed: 0,
|
||||||
|
totalTime: 0,
|
||||||
|
};
|
||||||
labelMap[label].count += 1;
|
labelMap[label].count += 1;
|
||||||
if (st) {
|
if (st) {
|
||||||
labelMap[label].runs += Number(st.run_count) || 0;
|
labelMap[label].runs += Number(st.run_count) || 0;
|
||||||
@@ -463,8 +606,9 @@ export default (app: Router) => {
|
|||||||
label,
|
label,
|
||||||
count: v.count,
|
count: v.count,
|
||||||
todayRuns: v.runs,
|
todayRuns: v.runs,
|
||||||
successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
|
successRate:
|
||||||
avgTime: averageElapsed(v.totalTime,v.runs,v.untimed),
|
v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
|
||||||
|
avgTime: averageElapsed(v.totalTime, v.runs, v.untimed),
|
||||||
}))
|
}))
|
||||||
.sort((a, b) => b.todayRuns - a.todayRuns);
|
.sort((a, b) => b.todayRuns - a.todayRuns);
|
||||||
|
|
||||||
|
|||||||
+14
-6
@@ -259,7 +259,10 @@ export default (app: Router) => {
|
|||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const envService = Container.get(EnvService);
|
const envService = Container.get(EnvService);
|
||||||
const data = await envService.removeLabels(req.body.ids, req.body.labels);
|
const data = await envService.removeLabels(
|
||||||
|
req.body.ids,
|
||||||
|
req.body.labels,
|
||||||
|
);
|
||||||
return res.send({ code: 200, data });
|
return res.send({ code: 200, data });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
@@ -285,10 +288,13 @@ export default (app: Router) => {
|
|||||||
: [parseContent];
|
: [parseContent];
|
||||||
if (
|
if (
|
||||||
data.length > 0 &&
|
data.length > 0 &&
|
||||||
data.every((x) =>
|
data.every(
|
||||||
x && typeof x.name === 'string' &&
|
(x) =>
|
||||||
/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) &&
|
x &&
|
||||||
typeof x.value === 'string' && x.value.length > 0,
|
typeof x.name === 'string' &&
|
||||||
|
/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) &&
|
||||||
|
typeof x.value === 'string' &&
|
||||||
|
x.value.length > 0,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
const result = await envService.create(
|
const result = await envService.create(
|
||||||
@@ -303,7 +309,9 @@ export default (app: Router) => {
|
|||||||
} else {
|
} else {
|
||||||
return res.send({
|
return res.send({
|
||||||
code: 400,
|
code: 400,
|
||||||
message: t('每条数据 name 或者 value 字段不能为空,参考导出文件格式'),
|
message: t(
|
||||||
|
'每条数据 name 或者 value 字段不能为空,参考导出文件格式',
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
+25
-19
@@ -1,15 +1,14 @@
|
|||||||
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
|
import {
|
||||||
|
directoryCheckHandler,
|
||||||
|
directoryPageHandler,
|
||||||
|
} from '../shared/directoryPageRoute';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import { NextFunction, Request, Response, Router } from 'express';
|
import { NextFunction, Request, Response, Router } from 'express';
|
||||||
import { Container } from 'typedi';
|
import { Container } from 'typedi';
|
||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import {
|
import { readDirs, removeAnsi, rmPath } from '../config/util';
|
||||||
readDirs,
|
|
||||||
removeAnsi,
|
|
||||||
rmPath,
|
|
||||||
} from '../config/util';
|
|
||||||
import LogService from '../services/log';
|
import LogService from '../services/log';
|
||||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||||
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
|
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
|
||||||
@@ -19,8 +18,14 @@ const blacklist = ['.tmp'];
|
|||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
app.use('/logs', route);
|
app.use('/logs', route);
|
||||||
route.get('/entries', ...directoryPageHandler(() => config.logPath, blacklist, true));
|
route.get(
|
||||||
route.post('/entries/check', ...directoryCheckHandler(() => config.logPath, blacklist));
|
'/entries',
|
||||||
|
...directoryPageHandler(() => config.logPath, blacklist, true),
|
||||||
|
);
|
||||||
|
route.post(
|
||||||
|
'/entries/check',
|
||||||
|
...directoryCheckHandler(() => config.logPath, blacklist),
|
||||||
|
);
|
||||||
|
|
||||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const logger: Logger = Container.get('logger');
|
const logger: Logger = Container.get('logger');
|
||||||
@@ -43,7 +48,9 @@ export default (app: Router) => {
|
|||||||
path: Joi.string().allow('').optional(),
|
path: Joi.string().allow('').optional(),
|
||||||
file: Joi.string().required(),
|
file: Joi.string().required(),
|
||||||
follow: Joi.boolean().optional(),
|
follow: Joi.boolean().optional(),
|
||||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
cursor: Joi.string()
|
||||||
|
.pattern(/^\d{1,16}\.[a-f0-9]{64}$/)
|
||||||
|
.optional(),
|
||||||
offset: Joi.number().integer().min(0).optional(),
|
offset: Joi.number().integer().min(0).optional(),
|
||||||
limit: Joi.number()
|
limit: Joi.number()
|
||||||
.integer()
|
.integer()
|
||||||
@@ -67,7 +74,9 @@ export default (app: Router) => {
|
|||||||
message: t('暂无权限'),
|
message: t('暂无权限'),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const logPath = `${req.query.path as string}/${req.query.file as string}`;
|
const logPath = `${req.query.path as string}/${
|
||||||
|
req.query.file as string
|
||||||
|
}`;
|
||||||
const runningInstance = await RunningInstanceModel.findOne({
|
const runningInstance = await RunningInstanceModel.findOne({
|
||||||
where: { log_path: logPath, status: InstanceStatus.running },
|
where: { log_path: logPath, status: InstanceStatus.running },
|
||||||
});
|
});
|
||||||
@@ -96,15 +105,12 @@ export default (app: Router) => {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
route.get(
|
route.get('/:file', (req: Request, res: Response) => {
|
||||||
'/:file',
|
return res.send({
|
||||||
(req: Request, res: Response) => {
|
code: 410,
|
||||||
return res.send({
|
message: t('接口已下线,请使用 /logs/detail 接口'),
|
||||||
code: 410,
|
});
|
||||||
message: t('接口已下线,请使用 /logs/detail 接口'),
|
});
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
route.delete(
|
route.delete(
|
||||||
'/',
|
'/',
|
||||||
|
|||||||
+10
-4
@@ -56,7 +56,8 @@ function writablePath(targetPath: string, req?: Request): string {
|
|||||||
if (
|
if (
|
||||||
/(?:^|\/)open\/scripts(?:\/|\?|$)/.test(req?.originalUrl || '') &&
|
/(?:^|\/)open\/scripts(?:\/|\?|$)/.test(req?.originalUrl || '') &&
|
||||||
!resolveFileAccess(config.scriptPath, [normalized])
|
!resolveFileAccess(config.scriptPath, [normalized])
|
||||||
) return '';
|
)
|
||||||
|
return '';
|
||||||
if (!isPathAllowed(normalized)) return '';
|
if (!isPathAllowed(normalized)) return '';
|
||||||
for (const writableRoot of config.writePathList) {
|
for (const writableRoot of config.writePathList) {
|
||||||
const root = resolve(writableRoot) + sep;
|
const root = resolve(writableRoot) + sep;
|
||||||
@@ -554,7 +555,8 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = writablePath(
|
const filePath = writablePath(
|
||||||
join(config.scriptPath, path, `${name}.swap${ext}`), req,
|
join(config.scriptPath, path, `${name}.swap${ext}`),
|
||||||
|
req,
|
||||||
);
|
);
|
||||||
if (!filePath) {
|
if (!filePath) {
|
||||||
return res.send({ code: 403, message: t('暂无权限') });
|
return res.send({ code: 403, message: t('暂无权限') });
|
||||||
@@ -587,7 +589,8 @@ export default (app: Router) => {
|
|||||||
}
|
}
|
||||||
const { name, ext } = parse(filename);
|
const { name, ext } = parse(filename);
|
||||||
const filePath = writablePath(
|
const filePath = writablePath(
|
||||||
join(config.scriptPath, path, `${name}.swap${ext}`), req,
|
join(config.scriptPath, path, `${name}.swap${ext}`),
|
||||||
|
req,
|
||||||
);
|
);
|
||||||
if (!filePath) {
|
if (!filePath) {
|
||||||
return res.send({ code: 403, message: t('暂无权限') });
|
return res.send({ code: 403, message: t('暂无权限') });
|
||||||
@@ -635,7 +638,10 @@ export default (app: Router) => {
|
|||||||
if (!path) {
|
if (!path) {
|
||||||
path = '';
|
path = '';
|
||||||
}
|
}
|
||||||
const filePath = writablePath(join(config.scriptPath, path, filename), req);
|
const filePath = writablePath(
|
||||||
|
join(config.scriptPath, path, filename),
|
||||||
|
req,
|
||||||
|
);
|
||||||
const newPath = writablePath(
|
const newPath = writablePath(
|
||||||
join(config.scriptPath, path, newFilename),
|
join(config.scriptPath, path, newFilename),
|
||||||
req,
|
req,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Container } from 'typedi';
|
|||||||
import { Logger } from 'winston';
|
import { Logger } from 'winston';
|
||||||
import SubscriptionService from '../services/subscription';
|
import SubscriptionService from '../services/subscription';
|
||||||
import { celebrate, Joi } from 'celebrate';
|
import { celebrate, Joi } from 'celebrate';
|
||||||
import { isValidCronSchedule } from '../shared/cronSchedule';
|
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
|
||||||
const route = Router();
|
const route = Router();
|
||||||
|
|
||||||
export default (app: Router) => {
|
export default (app: Router) => {
|
||||||
|
|||||||
+9
-3
@@ -10,7 +10,7 @@ import UserService from '../services/user';
|
|||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import { isDefaultAuthInfo } from '../shared/auth';
|
import { isDefaultAuthInfo } from '../shared/auth';
|
||||||
import { getUniqPath, handleLogPath, parseVersion } from '../config/util';
|
import { getUniqPath, handleLogPath, parseVersion } from '../config/util';
|
||||||
import { findCronId } from '../shared/cronCommand';
|
import { findCronId } from '../cron/execution/cronCommand';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
import { logStreamManager } from '../shared/logStreamManager';
|
import { logStreamManager } from '../shared/logStreamManager';
|
||||||
@@ -63,8 +63,14 @@ export default (app: Router) => {
|
|||||||
try {
|
try {
|
||||||
const systemService = Container.get(SystemService);
|
const systemService = Container.get(SystemService);
|
||||||
const data = await systemService.getSystemConfig();
|
const data = await systemService.getSystemConfig();
|
||||||
res.send({ code: 200, data: { ...data, effectiveCronConcurrency: systemService.cronConcurrency,
|
res.send({
|
||||||
availableCpus: containerResources().cpus } });
|
code: 200,
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
effectiveCronConcurrency: systemService.cronConcurrency,
|
||||||
|
availableCpus: containerResources().cpus,
|
||||||
|
},
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return next(e);
|
return next(e);
|
||||||
}
|
}
|
||||||
|
|||||||
+101
-42
@@ -49,13 +49,14 @@ class Application {
|
|||||||
process.env.NODE_ENV === 'development' ||
|
process.env.NODE_ENV === 'development' ||
|
||||||
(process.arch === 'arm' &&
|
(process.arch === 'arm' &&
|
||||||
Number(
|
Number(
|
||||||
(process.config.variables as { arm_version?: string | number }).arm_version,
|
(process.config.variables as { arm_version?: string | number })
|
||||||
|
.arm_version,
|
||||||
) === 6)
|
) === 6)
|
||||||
? 120000
|
? 120000
|
||||||
: 30000;
|
: 30000;
|
||||||
// Fork gRPC worker first and wait for it to be ready
|
// Fork gRPC worker first and wait for it to be ready
|
||||||
const grpcWorker = this.forkWorker('grpc');
|
const grpcWorker = this.forkWorker('grpc');
|
||||||
|
|
||||||
// Wait for gRPC worker to signal it's ready before starting HTTP worker
|
// Wait for gRPC worker to signal it's ready before starting HTTP worker
|
||||||
this.waitForWorkerReady(grpcWorker, readyTimeout)
|
this.waitForWorkerReady(grpcWorker, readyTimeout)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -63,7 +64,9 @@ class Application {
|
|||||||
this.httpWorker = this.forkWorker('http');
|
this.httpWorker = this.forkWorker('http');
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
Logger.error(`[boot] Failed to wait for gRPC worker:\n${errStack(error)}`);
|
Logger.error(
|
||||||
|
`[boot] Failed to wait for gRPC worker:\n${errStack(error)}`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -72,7 +75,8 @@ class Application {
|
|||||||
if (metadata) {
|
if (metadata) {
|
||||||
if (!this.isShuttingDown) {
|
if (!this.isShuttingDown) {
|
||||||
Logger.error(
|
Logger.error(
|
||||||
`${metadata.serviceType} worker ${worker.process.pid} died (${signal || code
|
`${metadata.serviceType} worker ${worker.process.pid} died (${
|
||||||
|
signal || code
|
||||||
}). Restarting...`,
|
}). Restarting...`,
|
||||||
);
|
);
|
||||||
// If gRPC worker died, restart it and wait for it to be ready
|
// If gRPC worker died, restart it and wait for it to be ready
|
||||||
@@ -92,19 +96,27 @@ class Application {
|
|||||||
this.httpWorker.send('reregister-crons');
|
this.httpWorker.send('reregister-crons');
|
||||||
Logger.info('Sent reregister-crons message to HTTP worker');
|
Logger.info('Sent reregister-crons message to HTTP worker');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error(`Failed to send reregister-crons message:\n${errStack(error)}`);
|
Logger.error(
|
||||||
|
`Failed to send reregister-crons message:\n${errStack(
|
||||||
|
error,
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
Logger.error(`Failed to restart gRPC worker:\n${errStack(error)}`);
|
Logger.error(
|
||||||
|
`Failed to restart gRPC worker:\n${errStack(error)}`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// For HTTP worker, just restart it
|
// For HTTP worker, just restart it
|
||||||
const newWorker = this.forkWorker(metadata.serviceType);
|
const newWorker = this.forkWorker(metadata.serviceType);
|
||||||
this.httpWorker = newWorker;
|
this.httpWorker = newWorker;
|
||||||
Logger.info(`Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`);
|
Logger.info(
|
||||||
|
`Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,11 +137,15 @@ class Application {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
worker.on('message', messageHandler);
|
worker.on('message', messageHandler);
|
||||||
|
|
||||||
// Timeout after specified milliseconds
|
// Timeout after specified milliseconds
|
||||||
const timeoutId = setTimeout(() => {
|
const timeoutId = setTimeout(() => {
|
||||||
worker.removeListener('message', messageHandler);
|
worker.removeListener('message', messageHandler);
|
||||||
reject(new Error(`Worker failed to start within ${timeoutMs / 1000} seconds`));
|
reject(
|
||||||
|
new Error(
|
||||||
|
`Worker failed to start within ${timeoutMs / 1000} seconds`,
|
||||||
|
),
|
||||||
|
);
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -139,23 +155,32 @@ class Application {
|
|||||||
// PM2's fork launcher is inherited by our own cluster workers. Their APM
|
// PM2's fork launcher is inherited by our own cluster workers. Their APM
|
||||||
// messages go to this primary, not PM2, and duplicate its sampling work.
|
// messages go to this primary, not PM2, and duplicate its sampling work.
|
||||||
// Keep primary monitoring and allow restoring the inherited worker APM.
|
// Keep primary monitoring and allow restoring the inherited worker APM.
|
||||||
if (process.env.pm_id !== undefined && process.env.QL_WORKER_APM !== 'true') {
|
if (
|
||||||
|
process.env.pm_id !== undefined &&
|
||||||
|
process.env.QL_WORKER_APM !== 'true'
|
||||||
|
) {
|
||||||
workerEnv.pmx = 'false';
|
workerEnv.pmx = 'false';
|
||||||
}
|
}
|
||||||
const worker = cluster.fork(workerEnv);
|
const worker = cluster.fork(workerEnv);
|
||||||
if (serviceType === 'grpc') worker.on('message', (msg) => {
|
if (serviceType === 'grpc')
|
||||||
if (msg === 'crontab-install-failed' && this.httpWorker?.isConnected()) {
|
worker.on('message', (msg) => {
|
||||||
this.httpWorker.send('reregister-crons');
|
if (
|
||||||
}
|
msg === 'crontab-install-failed' &&
|
||||||
});
|
this.httpWorker?.isConnected()
|
||||||
|
) {
|
||||||
|
this.httpWorker.send('reregister-crons');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (serviceType === 'http') worker.on('message', (msg) => {
|
if (serviceType === 'http')
|
||||||
if (msg?.type !== 'cancel-queued-triggers') return;
|
worker.on('message', (msg) => {
|
||||||
for (const [id, meta] of this.workerMetadataMap) {
|
if (msg?.type !== 'cancel-queued-triggers') return;
|
||||||
const target = cluster.workers?.[id];
|
for (const [id, meta] of this.workerMetadataMap) {
|
||||||
if (meta.serviceType === 'grpc' && target?.isConnected()) target.send(msg);
|
const target = cluster.workers?.[id];
|
||||||
}
|
if (meta.serviceType === 'grpc' && target?.isConnected())
|
||||||
});
|
target.send(msg);
|
||||||
|
}
|
||||||
|
});
|
||||||
this.workerMetadataMap.set(worker.id, {
|
this.workerMetadataMap.set(worker.id, {
|
||||||
id: worker.id,
|
id: worker.id,
|
||||||
pid: worker.process.pid!,
|
pid: worker.process.pid!,
|
||||||
@@ -195,7 +220,11 @@ class Application {
|
|||||||
try {
|
try {
|
||||||
worker.send('shutdown');
|
worker.send('shutdown');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.warn(`Failed to send shutdown to worker ${worker.process.pid}:\n${errStack(error)}`);
|
Logger.warn(
|
||||||
|
`Failed to send shutdown to worker ${
|
||||||
|
worker.process.pid
|
||||||
|
}:\n${errStack(error)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -234,16 +263,23 @@ class Application {
|
|||||||
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
|
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { triggerHistory } = await startupStage('history.import', () => import('./shared/triggerHistory'));
|
const { triggerHistory } = await startupStage(
|
||||||
|
'history.import',
|
||||||
|
() => import('./cron/history'),
|
||||||
|
);
|
||||||
const history = triggerHistory();
|
const history = triggerHistory();
|
||||||
await startupStage('history.recover', () => history.interrupt(serviceType));
|
await startupStage('history.recover', () =>
|
||||||
|
history.interrupt(serviceType),
|
||||||
|
);
|
||||||
if (serviceType === 'http') {
|
if (serviceType === 'http') {
|
||||||
await this.startHttpService();
|
await this.startHttpService();
|
||||||
const retryExits = async () => {
|
const retryExits = async () => {
|
||||||
try {
|
try {
|
||||||
await history.retryPendingExits();
|
await history.retryPendingExits();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error(`[scheduler] Exit receipt retry failed: ${errStack(error)}`);
|
Logger.error(
|
||||||
|
`[scheduler] Exit receipt retry failed: ${errStack(error)}`,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
if (!this.isShuttingDown) setTimeout(retryExits, 15000).unref();
|
if (!this.isShuttingDown) setTimeout(retryExits, 15000).unref();
|
||||||
}
|
}
|
||||||
@@ -262,21 +298,26 @@ class Application {
|
|||||||
|
|
||||||
private async startHttpService() {
|
private async startHttpService() {
|
||||||
// 在导入任何 gRPC 客户端模块之前初始化 mTLS 证书
|
// 在导入任何 gRPC 客户端模块之前初始化 mTLS 证书
|
||||||
const { initGrpcCerts } = await startupStage('certificates.import', () => import('./config/grpcCerts'));
|
const { initGrpcCerts } = await startupStage(
|
||||||
|
'certificates.import',
|
||||||
|
() => import('./config/grpcCerts'),
|
||||||
|
);
|
||||||
await startupStage('certificates.initialize', () => initGrpcCerts());
|
await startupStage('certificates.initialize', () => initGrpcCerts());
|
||||||
|
|
||||||
const app = await startupStage('http.middleware', () => this.setupMiddlewares());
|
const app = await startupStage('http.middleware', () =>
|
||||||
|
this.setupMiddlewares(),
|
||||||
|
);
|
||||||
|
|
||||||
const { HttpServerService } = await import('./services/http');
|
const { HttpServerService } = await import('./services/http');
|
||||||
this.httpServerService = Container.get(HttpServerService);
|
this.httpServerService = Container.get(HttpServerService);
|
||||||
|
|
||||||
const appLoader = await startupStage('http.import', () => import('./loaders/app'));
|
const appLoader = await startupStage(
|
||||||
|
'http.import',
|
||||||
|
() => import('./loaders/app'),
|
||||||
|
);
|
||||||
await startupStage('http.initialize', () => appLoader.default({ app }));
|
await startupStage('http.initialize', () => appLoader.default({ app }));
|
||||||
|
|
||||||
const server = await this.httpServerService.initialize(
|
const server = await this.httpServerService.initialize(app, config.port);
|
||||||
app,
|
|
||||||
config.port,
|
|
||||||
);
|
|
||||||
|
|
||||||
const serverLoader = await import('./loaders/server');
|
const serverLoader = await import('./loaders/server');
|
||||||
await (serverLoader.default as any)({ server });
|
await (serverLoader.default as any)({ server });
|
||||||
@@ -284,10 +325,15 @@ class Application {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async startGrpcService() {
|
private async startGrpcService() {
|
||||||
const { GrpcServerService } = await startupStage('grpc.import', () => import('./services/grpc'));
|
const { GrpcServerService } = await startupStage(
|
||||||
|
'grpc.import',
|
||||||
|
() => import('./services/grpc'),
|
||||||
|
);
|
||||||
this.grpcServerService = Container.get(GrpcServerService);
|
this.grpcServerService = Container.get(GrpcServerService);
|
||||||
|
|
||||||
await startupStage('grpc.initialize', () => this.grpcServerService!.initialize());
|
await startupStage('grpc.initialize', () =>
|
||||||
|
this.grpcServerService!.initialize(),
|
||||||
|
);
|
||||||
this.setupWorkerShutdown('grpc');
|
this.setupWorkerShutdown('grpc');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,12 +341,23 @@ class Application {
|
|||||||
process.on('message', async (msg) => {
|
process.on('message', async (msg) => {
|
||||||
if (msg === 'shutdown') {
|
if (msg === 'shutdown') {
|
||||||
this.gracefulShutdown(serviceType);
|
this.gracefulShutdown(serviceType);
|
||||||
} else if (serviceType === 'grpc' && typeof msg === 'object' && msg &&
|
} else if (
|
||||||
'type' in msg && msg.type === 'cancel-queued-triggers' && 'ids' in msg && Array.isArray(msg.ids)) {
|
serviceType === 'grpc' &&
|
||||||
const { cancelWaitingTriggers } = await import('./shared/runCron');
|
typeof msg === 'object' &&
|
||||||
|
msg &&
|
||||||
|
'type' in msg &&
|
||||||
|
msg.type === 'cancel-queued-triggers' &&
|
||||||
|
'ids' in msg &&
|
||||||
|
Array.isArray(msg.ids)
|
||||||
|
) {
|
||||||
|
const { cancelWaitingTriggers } = await import(
|
||||||
|
'./cron/execution/runCron'
|
||||||
|
);
|
||||||
cancelWaitingTriggers(msg.ids);
|
cancelWaitingTriggers(msg.ids);
|
||||||
} else if (serviceType === 'http' &&
|
} else if (
|
||||||
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')) {
|
serviceType === 'http' &&
|
||||||
|
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')
|
||||||
|
) {
|
||||||
const { default: cronClient } = await import('./schedule/client');
|
const { default: cronClient } = await import('./schedule/client');
|
||||||
cronClient.readiness.invalidate();
|
cronClient.readiness.invalidate();
|
||||||
}
|
}
|
||||||
@@ -316,7 +373,7 @@ class Application {
|
|||||||
this.isShuttingDown = true;
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { triggerHistory } = await import('./shared/triggerHistory');
|
const { triggerHistory } = await import('./cron/history');
|
||||||
await triggerHistory().interrupt(serviceType);
|
await triggerHistory().interrupt(serviceType);
|
||||||
if (serviceType === 'http') {
|
if (serviceType === 'http') {
|
||||||
await this.httpServerService?.shutdown();
|
await this.httpServerService?.shutdown();
|
||||||
@@ -325,7 +382,9 @@ class Application {
|
|||||||
}
|
}
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Logger.error(`[${serviceType}] Error during shutdown:\n${errStack(error)}`);
|
Logger.error(
|
||||||
|
`[${serviceType}] Error during shutdown:\n${errStack(error)}`,
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { storageFull, writeExit } from '../shared/managedExit.cjs';
|
import { storageFull, writeExit } from '../cron/settlement/exitReceipt.cjs';
|
||||||
import { QueryTypes } from 'sequelize';
|
import { QueryTypes } from 'sequelize';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
import { systemOwner, TriggerHistory } from '../shared/triggerHistory';
|
import { systemOwner, TriggerHistory } from '../cron/history';
|
||||||
|
|
||||||
async function receipt() {
|
async function receipt() {
|
||||||
const [action, task, pid, id, status, end] = process.argv.slice(2);
|
const [action, task, pid, id, status, end] = process.argv.slice(2);
|
||||||
@@ -15,36 +15,68 @@ async function receipt() {
|
|||||||
const at = Number(process.env.QL_SYSTEM_ENTERED);
|
const at = Number(process.env.QL_SYSTEM_ENTERED);
|
||||||
const rule = process.env.QL_SYSTEM_RULE;
|
const rule = process.env.QL_SYSTEM_RULE;
|
||||||
const dispatched = Number(process.env.QL_SYSTEM_DISPATCHED) * 1000;
|
const dispatched = Number(process.env.QL_SYSTEM_DISPATCHED) * 1000;
|
||||||
const dispatch = Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at ? dispatched : undefined;
|
const dispatch =
|
||||||
const wrapper = rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now() ? { rule, at, dispatch } : undefined;
|
Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at
|
||||||
const acquired = await history.startSystem(triggerId, Number(task), owner, command, wrapper);
|
? dispatched
|
||||||
|
: undefined;
|
||||||
|
const wrapper =
|
||||||
|
rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now()
|
||||||
|
? { rule, at, dispatch }
|
||||||
|
: undefined;
|
||||||
|
const acquired = await history.startSystem(
|
||||||
|
triggerId,
|
||||||
|
Number(task),
|
||||||
|
owner,
|
||||||
|
command,
|
||||||
|
wrapper,
|
||||||
|
);
|
||||||
if (!acquired) process.exitCode = 75;
|
if (!acquired) process.exitCode = 75;
|
||||||
else if (!id) process.stdout.write(triggerId);
|
else if (!id) process.stdout.write(triggerId);
|
||||||
} else if (action === 'finish') {
|
} else if (action === 'finish') {
|
||||||
// The live wrapper inherited both IDs from the start it just claimed. A
|
// The live wrapper inherited both IDs from the start it just claimed. A
|
||||||
// standalone retry must match the registered system task before writing.
|
// standalone retry must match the registered system task before writing.
|
||||||
const fromWrapper = process.env.QL_TRIGGER_ID === id && process.env.ID === task;
|
const fromWrapper =
|
||||||
|
process.env.QL_TRIGGER_ID === id && process.env.ID === task;
|
||||||
if (!fromWrapper || !id?.startsWith(`system-${Number(task)}-`)) {
|
if (!fromWrapper || !id?.startsWith(`system-${Number(task)}-`)) {
|
||||||
const [registered] = await sequelize.query(
|
const [registered] = await sequelize.query(
|
||||||
`SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$task AND source='system' AND owner LIKE 'crond:%'
|
`SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$task AND source='system' AND owner LIKE 'crond:%'
|
||||||
UNION ALL SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id AND cron_id=$task AND source='system' LIMIT 1`,
|
UNION ALL SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id AND cron_id=$task AND source='system' LIMIT 1`,
|
||||||
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT });
|
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
if (!registered) return;
|
if (!registered) return;
|
||||||
}
|
}
|
||||||
const code = Number(status);
|
const code = Number(status);
|
||||||
const finishedAt = end && /^\d{13}$/.test(end) && Number(end) <= Date.now() ? Number(end) : undefined;
|
const finishedAt =
|
||||||
|
end && /^\d{13}$/.test(end) && Number(end) <= Date.now()
|
||||||
|
? Number(end)
|
||||||
|
: undefined;
|
||||||
const bound = fromWrapper && finishedAt !== undefined;
|
const bound = fromWrapper && finishedAt !== undefined;
|
||||||
let journaled = false;
|
let journaled = false;
|
||||||
if (bound) {
|
if (bound) {
|
||||||
try { writeExit(id, code, null, finishedAt); journaled = true; }
|
try {
|
||||||
catch (error) {
|
writeExit(id, code, null, finishedAt);
|
||||||
|
journaled = true;
|
||||||
|
} catch (error) {
|
||||||
if (!storageFull(error)) throw error;
|
if (!storageFull(error)) throw error;
|
||||||
console.error('[crond] Receipt storage full; settling the observed exit in SQLite:', error);
|
console.error(
|
||||||
|
'[crond] Receipt storage full; settling the observed exit in SQLite:',
|
||||||
|
error,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await history.complete(id, code === 0 ? 'finished' : 'failed', null, code, finishedAt,
|
await history.complete(
|
||||||
bound ? { version: 1, code, signal: null, time: finishedAt } : finishedAt === undefined ? undefined : 'legacy');
|
id,
|
||||||
|
code === 0 ? 'finished' : 'failed',
|
||||||
|
null,
|
||||||
|
code,
|
||||||
|
finishedAt,
|
||||||
|
bound
|
||||||
|
? { version: 1, code, signal: null, time: finishedAt }
|
||||||
|
: finishedAt === undefined
|
||||||
|
? undefined
|
||||||
|
: 'legacy',
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!journaled || !storageFull(error)) throw error;
|
if (!journaled || !storageFull(error)) throw error;
|
||||||
// The regular recovery pass will settle the receipt after space returns.
|
// The regular recovery pass will settle the receipt after space returns.
|
||||||
@@ -54,8 +86,11 @@ async function receipt() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
receipt().catch((error) => {
|
receipt()
|
||||||
console.error('[crond] Failed to persist execution receipt:', error);
|
.catch((error) => {
|
||||||
// At start, 75 means that another execution already owns the slot.
|
console.error('[crond] Failed to persist execution receipt:', error);
|
||||||
process.exitCode = process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
|
// At start, 75 means that another execution already owns the slot.
|
||||||
}).finally(() => sequelize.close());
|
process.exitCode =
|
||||||
|
process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
|
||||||
|
})
|
||||||
|
.finally(() => sequelize.close());
|
||||||
@@ -165,13 +165,14 @@ async function loadExistingCerts(): Promise<GrpcTlsConfig | null> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const [caCert, serverCert, serverKey, clientCert, clientKey] = await Promise.all([
|
const [caCert, serverCert, serverKey, clientCert, clientKey] =
|
||||||
fs.readFile(caCertPath, 'utf-8'),
|
await Promise.all([
|
||||||
fs.readFile(serverCertPath, 'utf-8'),
|
fs.readFile(caCertPath, 'utf-8'),
|
||||||
fs.readFile(serverKeyPath, 'utf-8'),
|
fs.readFile(serverCertPath, 'utf-8'),
|
||||||
fs.readFile(clientCertPath, 'utf-8'),
|
fs.readFile(serverKeyPath, 'utf-8'),
|
||||||
fs.readFile(clientKeyPath, 'utf-8'),
|
fs.readFile(clientCertPath, 'utf-8'),
|
||||||
]);
|
fs.readFile(clientKeyPath, 'utf-8'),
|
||||||
|
]);
|
||||||
|
|
||||||
Logger.info('[boot] Loaded existing gRPC mTLS certificates from disk');
|
Logger.info('[boot] Loaded existing gRPC mTLS certificates from disk');
|
||||||
return { caCert, serverCert, serverKey, clientCert, clientKey };
|
return { caCert, serverCert, serverKey, clientCert, clientKey };
|
||||||
|
|||||||
+38
-21
@@ -1,5 +1,9 @@
|
|||||||
import { cronOperand } from '../shared/cronOperand';
|
import { cronOperand } from '../cron/execution/cronOperand';
|
||||||
import { finishStoppedTree, isProcessDescendant, systemOwner } from '../shared/cronProcess';
|
import {
|
||||||
|
finishStoppedTree,
|
||||||
|
isProcessDescendant,
|
||||||
|
systemOwner,
|
||||||
|
} from '../cron/execution/cronProcess';
|
||||||
import * as fs from 'fs/promises';
|
import * as fs from 'fs/promises';
|
||||||
import { statSync } from 'fs';
|
import { statSync } from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
@@ -10,7 +14,7 @@ import { load } from 'js-yaml';
|
|||||||
import config from './index';
|
import config from './index';
|
||||||
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR } from './const';
|
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR } from './const';
|
||||||
import Logger from '../loaders/logger';
|
import Logger from '../loaders/logger';
|
||||||
import { writeFileWithLock } from '../shared/utils';
|
import { fileExist, writeFileWithLock } from '../shared/utils';
|
||||||
import { DependenceTypes } from '../data/dependence';
|
import { DependenceTypes } from '../data/dependence';
|
||||||
import { FormData } from 'undici';
|
import { FormData } from 'undici';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
@@ -136,14 +140,7 @@ export function getPlatform(userAgent: string): 'mobile' | 'desktop' {
|
|||||||
return platform as 'mobile' | 'desktop';
|
return platform as 'mobile' | 'desktop';
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fileExist(file: any) {
|
export { fileExist } from '../shared/utils';
|
||||||
try {
|
|
||||||
await fs.access(file);
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createFile(file: string, data: string = '') {
|
export async function createFile(file: string, data: string = '') {
|
||||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||||
@@ -498,8 +495,15 @@ export function psTree(pid: number): Promise<number[]> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function killTask(pid: number, waitForExit = false, verifyOwner?: () => void,
|
export async function killTask(
|
||||||
withStopRequest?: (signalTree: () => Error | void, targets: string[]) => Promise<void | { targets: string[]; signalledAt: number | null }>) {
|
pid: number,
|
||||||
|
waitForExit = false,
|
||||||
|
verifyOwner?: () => void,
|
||||||
|
withStopRequest?: (
|
||||||
|
signalTree: () => Error | void,
|
||||||
|
targets: string[],
|
||||||
|
) => Promise<void | { targets: string[]; signalledAt: number | null }>,
|
||||||
|
) {
|
||||||
const descendants = await psTree(pid);
|
const descendants = await psTree(pid);
|
||||||
verifyOwner?.();
|
verifyOwner?.();
|
||||||
const signal = (target: number, sig: NodeJS.Signals) => {
|
const signal = (target: number, sig: NodeJS.Signals) => {
|
||||||
@@ -526,9 +530,13 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
|
|||||||
for (const target of pids) {
|
for (const target of pids) {
|
||||||
try {
|
try {
|
||||||
const birth = systemOwner(target);
|
const birth = systemOwner(target);
|
||||||
if (target === pid || isProcessDescendant(target, pid)) births.set(target, birth);
|
if (target === pid || isProcessDescendant(target, pid))
|
||||||
|
births.set(target, birth);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
if (
|
||||||
|
!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
|
||||||
|
)
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
verifyOwner();
|
verifyOwner();
|
||||||
@@ -536,9 +544,11 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
|
|||||||
const sameProcess = (target: number) => {
|
const sameProcess = (target: number) => {
|
||||||
if (!verifyOwner) return true;
|
if (!verifyOwner) return true;
|
||||||
if (!births.has(target)) return false;
|
if (!births.has(target)) return false;
|
||||||
try { return births.get(target) === systemOwner(target); }
|
try {
|
||||||
catch (error) {
|
return births.get(target) === systemOwner(target);
|
||||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) return false;
|
} catch (error) {
|
||||||
|
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!))
|
||||||
|
return false;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -547,7 +557,9 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
|
|||||||
// The root owns the command's result. An ESRCH here must roll back the
|
// The root owns the command's result. An ESRCH here must roll back the
|
||||||
// stop claim even if a descendant is still draining the output pipe.
|
// stop claim even if a descendant is still draining the output pipe.
|
||||||
if (verifyOwner && (!sameProcess(pid) || !signal(pid, 'SIGTERM'))) {
|
if (verifyOwner && (!sameProcess(pid) || !signal(pid, 'SIGTERM'))) {
|
||||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
throw Object.assign(new Error('Command already exited'), {
|
||||||
|
code: 'ESRCH',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
let deliveryError: Error | undefined;
|
let deliveryError: Error | undefined;
|
||||||
for (const target of pids) {
|
for (const target of pids) {
|
||||||
@@ -685,7 +697,9 @@ export async function getUniqPath(
|
|||||||
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
|
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const base = str.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5.-]+/g, '_').slice(0, 100 - suffix.length);
|
const base = str
|
||||||
|
.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5.-]+/g, '_')
|
||||||
|
.slice(0, 100 - suffix.length);
|
||||||
return `${base && !/^\.+$/.test(base) ? base : 'task'}${suffix}`;
|
return `${base && !/^\.+$/.test(base) ? base : 'task'}${suffix}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -917,7 +931,10 @@ export function getUninstallCommand(
|
|||||||
if ((linuxOsType || getOsTypeSync()) === 'Alpine') {
|
if ((linuxOsType || getOsTypeSync()) === 'Alpine') {
|
||||||
// apk del accepts package names, not the version constraints or repository
|
// apk del accepts package names, not the version constraints or repository
|
||||||
// tags accepted by apk add. Keep apt's version/architecture selectors intact.
|
// tags accepted by apk add. Keep apt's version/architecture selectors intact.
|
||||||
const packageName = name.trim().split(/[<>=~@]/, 1)[0].trim();
|
const packageName = name
|
||||||
|
.trim()
|
||||||
|
.split(/[<>=~@]/, 1)[0]
|
||||||
|
.trim();
|
||||||
const argument = /^[a-z0-9][a-z0-9+_.-]*$/i.test(packageName)
|
const argument = /^[a-z0-9][a-z0-9+_.-]*$/i.test(packageName)
|
||||||
? packageName
|
? packageName
|
||||||
: shellQuote(packageName);
|
: shellQuote(packageName);
|
||||||
|
|||||||
@@ -0,0 +1,637 @@
|
|||||||
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
|
import { createHash } from 'crypto';
|
||||||
|
import { executionIdPattern } from '../identity';
|
||||||
|
import {
|
||||||
|
isProcessDescendant,
|
||||||
|
legacyProcessOwner,
|
||||||
|
systemOwner,
|
||||||
|
} from '../execution/cronProcess';
|
||||||
|
import type { TriggerSource, TriggerState } from '../types';
|
||||||
|
import type { TriggerLifecycle } from '../execution/triggerLifecycle';
|
||||||
|
import type { TriggerSettlement } from '../settlement/triggerSettlement';
|
||||||
|
|
||||||
|
export type LegacyClientLifecycle = Pick<TriggerLifecycle, 'claimSummary'>;
|
||||||
|
export type LegacyClientSettlement = Pick<
|
||||||
|
TriggerSettlement,
|
||||||
|
| 'recordShellResult'
|
||||||
|
| 'hasBoundConflict'
|
||||||
|
| 'completeInTransaction'
|
||||||
|
| 'readScriptSample'
|
||||||
|
| 'saveScriptSample'
|
||||||
|
| 'settleInstance'
|
||||||
|
>;
|
||||||
|
|
||||||
|
// Adapt PID-only and identified Shell reports without treating a wrapper exit
|
||||||
|
// as the managed command's result. Every state/settlement write keeps its transaction.
|
||||||
|
export class LegacyClientAdapter {
|
||||||
|
constructor(
|
||||||
|
private database: Sequelize,
|
||||||
|
private lifecycle: LegacyClientLifecycle,
|
||||||
|
private settlement: LegacyClientSettlement,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// Old shell-only executions publish status and statistics independently.
|
||||||
|
// Either final receipt can settle that execution if the other was lost.
|
||||||
|
async recordShellResult(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
code: number,
|
||||||
|
elapsedMs: number,
|
||||||
|
now: number,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
return this.settlement.recordShellResult(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
code,
|
||||||
|
elapsedMs,
|
||||||
|
now,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async shellReport(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
system: boolean,
|
||||||
|
running: boolean,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
exitCode?: number,
|
||||||
|
stopped = false,
|
||||||
|
transaction?: Transaction,
|
||||||
|
elapsedMs?: number,
|
||||||
|
finishedAt?: number,
|
||||||
|
): Promise<void | false> {
|
||||||
|
if (!transaction)
|
||||||
|
return this.database.transaction((tx) =>
|
||||||
|
this.shellReport(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
system,
|
||||||
|
running,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
exitCode,
|
||||||
|
stopped,
|
||||||
|
tx,
|
||||||
|
elapsedMs,
|
||||||
|
finishedAt,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (await this.settlement.hasBoundConflict(id, transaction)) return false;
|
||||||
|
if (system || executionIdPattern.test(id)) {
|
||||||
|
// Standalone clients supply neither a scheduled instant nor a queue observation.
|
||||||
|
const dated = Number.isSafeInteger(seconds) && seconds > 0;
|
||||||
|
const start = dated ? seconds * 1000 : Date.now();
|
||||||
|
const standalone =
|
||||||
|
executionIdPattern.test(id) || id.startsWith('system-cli-');
|
||||||
|
const lastKnownTime =
|
||||||
|
standalone &&
|
||||||
|
!running &&
|
||||||
|
dated &&
|
||||||
|
finishedAt &&
|
||||||
|
finishedAt >= start &&
|
||||||
|
finishedAt <= Date.now()
|
||||||
|
? finishedAt
|
||||||
|
: start;
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT INTO CronTriggers(id,cron_id,source,state,started_at,observed_at)
|
||||||
|
SELECT $id,$cronId,$source,'running',$start,$start
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM CronHistoryRetention WHERE id=1 AND ($dated=0 OR cutoff>$lastKnownTime))
|
||||||
|
ON CONFLICT(id) DO NOTHING`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: {
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
start,
|
||||||
|
lastKnownTime,
|
||||||
|
dated: Number(dated),
|
||||||
|
source: system ? 'system' : 'client',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id AND cron_id=$cronId`,
|
||||||
|
{ transaction, bind: { id, cronId, log } },
|
||||||
|
);
|
||||||
|
if (!running) {
|
||||||
|
// For a managed command the wrapper may be only the first segment.
|
||||||
|
// Only its supervisor can report the whole command's exit.
|
||||||
|
const [legacy] = await this.database.query(
|
||||||
|
'SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$cronId AND owner IS NULL',
|
||||||
|
{ transaction, type: QueryTypes.SELECT, bind: { id, cronId } },
|
||||||
|
);
|
||||||
|
if (legacy) {
|
||||||
|
const state = stopped
|
||||||
|
? 'stopped'
|
||||||
|
: exitCode == null
|
||||||
|
? 'unknown'
|
||||||
|
: exitCode === 0
|
||||||
|
? 'finished'
|
||||||
|
: 'failed';
|
||||||
|
await this.settlement.completeInTransaction(
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
null,
|
||||||
|
exitCode ?? null,
|
||||||
|
transaction,
|
||||||
|
elapsedMs,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async reportLegacy(
|
||||||
|
cronId: number,
|
||||||
|
running: boolean,
|
||||||
|
pid: number,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
elapsed: number,
|
||||||
|
code?: number,
|
||||||
|
) {
|
||||||
|
return this.database.transaction((transaction) =>
|
||||||
|
this.applyLegacyReceipt(
|
||||||
|
cronId,
|
||||||
|
running,
|
||||||
|
pid,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
elapsed,
|
||||||
|
transaction,
|
||||||
|
code,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async applyLegacyReceipt(
|
||||||
|
cronId: number,
|
||||||
|
running: boolean,
|
||||||
|
pid: number,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
elapsed: number,
|
||||||
|
transaction: Transaction,
|
||||||
|
code?: number,
|
||||||
|
) {
|
||||||
|
const start = seconds * 1000;
|
||||||
|
const receipt =
|
||||||
|
'legacy-' +
|
||||||
|
createHash('sha256')
|
||||||
|
.update(JSON.stringify([cronId, pid, seconds, log || null]))
|
||||||
|
.digest('hex');
|
||||||
|
// A verified child stays attached to its supervisor even after the OS recycles its PID.
|
||||||
|
const [bound] = await this.database.query(
|
||||||
|
'SELECT 1 FROM CronShellBindings WHERE receipt=$receipt',
|
||||||
|
{ transaction, type: QueryTypes.SELECT, bind: { receipt } },
|
||||||
|
);
|
||||||
|
if (bound) return;
|
||||||
|
|
||||||
|
const rows = await this.database.query<{
|
||||||
|
instance: number;
|
||||||
|
status: number;
|
||||||
|
finished_at: number | null;
|
||||||
|
exit_code: number | null;
|
||||||
|
id: string | null;
|
||||||
|
source: TriggerSource | null;
|
||||||
|
log_path: string | null;
|
||||||
|
}>(
|
||||||
|
`SELECT i.id AS instance,i.status,i.finished_at,i.exit_code,i.log_path,t.id,t.source FROM RunningInstances i
|
||||||
|
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.cron_id=$cronId AND i.pid=$pid
|
||||||
|
AND (t.id IS NULL OR t.source='legacy' OR t.owner IS NOT NULL)
|
||||||
|
AND i.started_at=$seconds AND (i.log_path IS $log OR $log IS NULL OR i.log_path IS NULL) LIMIT 2`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
bind: { cronId, pid, seconds, log: log || null },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const [old] = rows;
|
||||||
|
if (rows.length > 1) return;
|
||||||
|
if (old) {
|
||||||
|
if (!old.id && old.status === 4) {
|
||||||
|
const [expired] = await this.database.query(
|
||||||
|
'SELECT 1 FROM CronHistoryRetention WHERE cutoff>$end',
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
bind: { end: (old.finished_at ?? seconds) * 1000 },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (expired) return;
|
||||||
|
}
|
||||||
|
if (old.status !== 0 && old.status !== 4) {
|
||||||
|
if (!old.id && old.finished_at != null) {
|
||||||
|
// The old panel owned the daily aggregate. Import its committed result
|
||||||
|
// without replaying an anonymous statistics increment.
|
||||||
|
const state =
|
||||||
|
old.status === 1
|
||||||
|
? 'finished'
|
||||||
|
: old.status === 2
|
||||||
|
? 'stopped'
|
||||||
|
: 'failed';
|
||||||
|
const inserted = await this.database.query(
|
||||||
|
`INSERT INTO CronTriggers
|
||||||
|
(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
|
||||||
|
SELECT $id,$cronId,'legacy',$state,$start,$start,$end,$instance,$log,$exit,1
|
||||||
|
WHERE $end >= $start AND $end>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
|
||||||
|
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
|
||||||
|
WHERE sibling.cron_id=$cronId
|
||||||
|
AND sibling.pid=$pid AND sibling.finished_at=$end/1000 AND sibling.id<>$instance
|
||||||
|
AND sibling.status IN (1,3) AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL)))
|
||||||
|
ON CONFLICT DO NOTHING`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.BULKUPDATE,
|
||||||
|
bind: {
|
||||||
|
id: receipt,
|
||||||
|
cronId,
|
||||||
|
pid,
|
||||||
|
state,
|
||||||
|
start,
|
||||||
|
end: old.finished_at * 1000,
|
||||||
|
instance: old.instance,
|
||||||
|
log: old.log_path,
|
||||||
|
exit: old.exit_code,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (inserted)
|
||||||
|
await this.lifecycle.claimSummary(
|
||||||
|
cronId,
|
||||||
|
old.instance,
|
||||||
|
seconds,
|
||||||
|
transaction,
|
||||||
|
true,
|
||||||
|
Math.max(0, old.finished_at - seconds),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (running && (old.id || old.status === 4)) return;
|
||||||
|
if (old.id && old.source !== 'legacy') return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let identity: string | undefined;
|
||||||
|
if (!old) {
|
||||||
|
const [prior] = await this.database.query(
|
||||||
|
'SELECT 1 FROM CronTriggers WHERE id=$receipt UNION ALL SELECT 1 FROM CronHistoryRetention WHERE cutoff>$start',
|
||||||
|
{ transaction, type: QueryTypes.SELECT, bind: { receipt, start } },
|
||||||
|
);
|
||||||
|
if (prior) return;
|
||||||
|
identity = legacyProcessOwner(pid, seconds);
|
||||||
|
const roots = await this.database.query<{
|
||||||
|
id: string;
|
||||||
|
command_identity: string;
|
||||||
|
}>(
|
||||||
|
`SELECT id,command_identity FROM CronTriggers WHERE cron_id=$cronId AND state='running'
|
||||||
|
AND command_identity IS NOT NULL AND started_at < $end`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
bind: { cronId, end: start + 1000 },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
for (const root of roots) {
|
||||||
|
if (!identity) break;
|
||||||
|
const parent = Number(root.command_identity.split(':')[1]);
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
!isProcessDescendant(pid, parent) ||
|
||||||
|
systemOwner(parent) !== root.command_identity
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await this.database.query(
|
||||||
|
'INSERT INTO CronShellBindings(receipt,trigger_id) VALUES ($receipt,$id)',
|
||||||
|
{ transaction, bind: { receipt, id: root.id } },
|
||||||
|
);
|
||||||
|
if (running)
|
||||||
|
await this.attachShellLog(root.id, cronId, log, transaction);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = old?.id ?? receipt;
|
||||||
|
if (!old?.id) {
|
||||||
|
// A later use of the same numeric PID proves the older process is gone.
|
||||||
|
const others = await this.database.query<{
|
||||||
|
id: string;
|
||||||
|
started_at: number;
|
||||||
|
}>(
|
||||||
|
`SELECT t.id,i.started_at FROM RunningInstances i LEFT JOIN CronTriggers t ON t.instance_id=i.id
|
||||||
|
WHERE i.cron_id=$cronId AND i.pid=$pid AND i.started_at<>$seconds
|
||||||
|
AND (i.started_at>$seconds OR (i.status=0 AND t.source='legacy'))`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
bind: { cronId, pid, seconds },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (running && old) identity = legacyProcessOwner(pid, seconds);
|
||||||
|
const historical =
|
||||||
|
!running ||
|
||||||
|
!identity ||
|
||||||
|
others.some((other) => other.started_at > seconds);
|
||||||
|
|
||||||
|
let instance = old?.instance;
|
||||||
|
if (!instance) {
|
||||||
|
[instance] = await this.database.query(
|
||||||
|
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,finished_at,createdAt,updatedAt)
|
||||||
|
VALUES ($cronId,$pid,$log,$seconds,$status,$finished,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.INSERT,
|
||||||
|
bind: {
|
||||||
|
cronId,
|
||||||
|
pid,
|
||||||
|
log: log || null,
|
||||||
|
seconds,
|
||||||
|
status: historical ? 4 : 0,
|
||||||
|
finished: historical ? Math.floor(Date.now() / 1000) : null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const unknown = historical || old?.status === 4;
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT INTO CronTriggers
|
||||||
|
(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,process_identity,reason)
|
||||||
|
VALUES ($id,$cronId,'legacy',$state,$start,$start,$end,$instance,$log,$identity,$reason)`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: {
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
start,
|
||||||
|
instance,
|
||||||
|
log: old?.log_path ?? (log || null),
|
||||||
|
identity: !unknown && running ? identity ?? null : null,
|
||||||
|
reason: old && running && !unknown ? 'restart' : null,
|
||||||
|
state: unknown ? 'unknown' : 'running',
|
||||||
|
end: unknown
|
||||||
|
? old?.finished_at
|
||||||
|
? old.finished_at * 1000
|
||||||
|
: Date.now()
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await this.lifecycle.claimSummary(
|
||||||
|
cronId,
|
||||||
|
instance!,
|
||||||
|
seconds,
|
||||||
|
transaction,
|
||||||
|
old?.status === 0 || (running && !unknown),
|
||||||
|
);
|
||||||
|
for (const other of others) {
|
||||||
|
if (other.started_at < seconds)
|
||||||
|
await this.settlement.completeInTransaction(
|
||||||
|
other.id,
|
||||||
|
'unknown',
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (running && !unknown)
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE Crontabs SET status=0,pid=$pid,log_path=$log
|
||||||
|
WHERE id=$cronId AND status IS NOT 3 AND $instance=(
|
||||||
|
SELECT id FROM RunningInstances WHERE cron_id=$cronId AND status=0 ORDER BY id DESC LIMIT 1)`,
|
||||||
|
{ transaction, bind: { cronId, pid, log: log || null, instance } },
|
||||||
|
);
|
||||||
|
if (unknown && old?.status === 0 && running)
|
||||||
|
await this.settlement.settleInstance(id, transaction);
|
||||||
|
}
|
||||||
|
if (!running) {
|
||||||
|
const state =
|
||||||
|
code == null ? 'unknown' : code === 0 ? 'finished' : 'failed';
|
||||||
|
await this.settlement.completeInTransaction(
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
null,
|
||||||
|
code ?? null,
|
||||||
|
transaction,
|
||||||
|
Math.max(0, elapsed) * 1000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async attachShellLog(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
log: string,
|
||||||
|
transaction: Transaction,
|
||||||
|
) {
|
||||||
|
const attached = await this.database.query(
|
||||||
|
`UPDATE RunningInstances SET log_path=$log WHERE status=0 AND log_path IS NULL
|
||||||
|
AND id=(SELECT instance_id FROM CronTriggers WHERE id=$id AND cron_id=$cronId AND state='running')`,
|
||||||
|
{ transaction, type: QueryTypes.BULKUPDATE, bind: { id, cronId, log } },
|
||||||
|
);
|
||||||
|
if (attached) {
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id',
|
||||||
|
{ transaction, bind: { id, log } },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE Crontabs SET log_path=$log WHERE id=$cronId AND status=0 AND pid=(
|
||||||
|
SELECT i.pid FROM RunningInstances i JOIN CronTriggers t ON t.instance_id=i.id WHERE t.id=$id)`,
|
||||||
|
{ transaction, bind: { id, cronId, log } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link the Shell instance and its trigger in the same IMMEDIATE write transaction.
|
||||||
|
async reportInstance(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
running: boolean,
|
||||||
|
pid: number,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
elapsed: number | undefined,
|
||||||
|
code?: number,
|
||||||
|
stopped = false,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
const sample = running
|
||||||
|
? undefined
|
||||||
|
: await this.settlement.readScriptSample(id);
|
||||||
|
await this.database.transaction(async (transaction) => {
|
||||||
|
const accepted = await this.shellReport(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
id.startsWith('system-'),
|
||||||
|
running,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
code,
|
||||||
|
stopped,
|
||||||
|
transaction,
|
||||||
|
elapsed == null ? undefined : elapsed * 1000,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
if (accepted === false) return;
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
state: TriggerState;
|
||||||
|
started_at: number | null;
|
||||||
|
instance_id: number | null;
|
||||||
|
command_identity: string | null;
|
||||||
|
owner: string | null;
|
||||||
|
}>(
|
||||||
|
'SELECT state,started_at,instance_id,command_identity,owner FROM CronTriggers WHERE id=$id AND cron_id=$cronId',
|
||||||
|
{ transaction, bind: { id, cronId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!row) return;
|
||||||
|
const startSeconds =
|
||||||
|
seconds > 0
|
||||||
|
? seconds
|
||||||
|
: Math.floor((row.started_at ?? Date.now()) / 1000);
|
||||||
|
if (
|
||||||
|
['finished', 'failed', 'stopped', 'unknown'].includes(row.state) &&
|
||||||
|
row.owner === null &&
|
||||||
|
row.instance_id === null
|
||||||
|
) {
|
||||||
|
// The CLI exit can commit before its first start. Link a terminal history
|
||||||
|
// row directly without ever publishing this PID as the current instance.
|
||||||
|
const [instance] = await this.database.query(
|
||||||
|
`INSERT INTO RunningInstances
|
||||||
|
(cron_id,pid,log_path,started_at,finished_at,status,exit_code,createdAt,updatedAt)
|
||||||
|
SELECT cron_id,$pid,log_path,CAST(started_at/1000 AS INTEGER),CAST(finished_at/1000 AS INTEGER),
|
||||||
|
CASE state WHEN 'finished' THEN 1 WHEN 'stopped' THEN 2 WHEN 'failed' THEN 3 ELSE 4 END,
|
||||||
|
exit_code,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP FROM CronTriggers
|
||||||
|
WHERE id=$id AND state IN ('finished','failed','stopped','unknown')`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.INSERT,
|
||||||
|
bind: { id, pid: pid || null },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (instance) {
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET instance_id=$instance WHERE id=$id',
|
||||||
|
{ transaction, bind: { instance, id } },
|
||||||
|
);
|
||||||
|
await this.lifecycle.claimSummary(
|
||||||
|
cronId,
|
||||||
|
instance,
|
||||||
|
startSeconds,
|
||||||
|
transaction,
|
||||||
|
false,
|
||||||
|
row.state === 'unknown' ? null : elapsed ?? null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (running && row.state !== 'running') return;
|
||||||
|
if (running && row.instance_id === null) {
|
||||||
|
let identity = row.command_identity;
|
||||||
|
if (identity?.startsWith('crond:')) {
|
||||||
|
pid = Number(identity.split(':')[1]);
|
||||||
|
} else if (pid) {
|
||||||
|
try {
|
||||||
|
identity = systemOwner(pid);
|
||||||
|
} catch {
|
||||||
|
/* A short child may have exited. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [instance] = await this.database.query(
|
||||||
|
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
|
||||||
|
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.INSERT,
|
||||||
|
bind: { cronId, pid, log, seconds: startSeconds },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET instance_id=$instance,process_identity=$identity WHERE id=$id',
|
||||||
|
{ transaction, bind: { instance, identity, id } },
|
||||||
|
);
|
||||||
|
await this.lifecycle.claimSummary(
|
||||||
|
cronId,
|
||||||
|
instance,
|
||||||
|
startSeconds,
|
||||||
|
transaction,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE Crontabs SET status=0,pid=$pid,log_path=$log
|
||||||
|
WHERE id=$cronId AND (status IS NOT 3 OR queued_token || '-' || id=$id)`,
|
||||||
|
{ transaction, bind: { cronId, id, pid, log } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (running && row.instance_id !== null) {
|
||||||
|
await this.attachShellLog(id, cronId, log, transaction);
|
||||||
|
}
|
||||||
|
if (!running)
|
||||||
|
await this.settlement.saveScriptSample(id, sample, transaction);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async reconcileInstances() {
|
||||||
|
await this.database.transaction(async (transaction) => {
|
||||||
|
// Released panels created instance rows before trigger IDs existed. Link
|
||||||
|
// their outstanding starts before cleanup so the original CLI can finish.
|
||||||
|
const unlinked = await this.database.query<{
|
||||||
|
cron_id: number;
|
||||||
|
pid: number;
|
||||||
|
log_path: string | null;
|
||||||
|
started_at: number;
|
||||||
|
}>(
|
||||||
|
`WITH outstanding AS (SELECT DISTINCT cron_id,started_at FROM RunningInstances WHERE status=0)
|
||||||
|
SELECT i.cron_id,i.pid,i.log_path,i.started_at FROM outstanding o
|
||||||
|
JOIN RunningInstances i ON i.cron_id=o.cron_id AND i.started_at=o.started_at
|
||||||
|
JOIN Crontabs c ON c.id=i.cron_id WHERE i.pid>0 AND i.started_at>0
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=i.id)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=i.id)
|
||||||
|
ORDER BY i.started_at,i.id`,
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
for (const row of unlinked) {
|
||||||
|
await this.applyLegacyReceipt(
|
||||||
|
row.cron_id,
|
||||||
|
true,
|
||||||
|
row.pid,
|
||||||
|
row.log_path || '',
|
||||||
|
row.started_at,
|
||||||
|
0,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Older versions mapped an unknown exit to error or stopped in instance history.
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE RunningInstances SET status=4,finished_at=COALESCE(finished_at,$now),updatedAt=CURRENT_TIMESTAMP
|
||||||
|
WHERE status IN (0,2,3) AND id IN
|
||||||
|
(SELECT instance_id FROM CronTriggers WHERE state='unknown' AND instance_id IS NOT NULL)`,
|
||||||
|
{ transaction, bind: { now: Math.floor(Date.now() / 1000) } },
|
||||||
|
);
|
||||||
|
// HTTP and gRPC restart independently. Another worker or crond may still own the run.
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE RunningInstances SET status=2,finished_at=$now,updatedAt=CURRENT_TIMESTAMP
|
||||||
|
WHERE status=0 AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=RunningInstances.id)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstances.id AND t.state='running')`,
|
||||||
|
{ transaction, bind: { now: Math.floor(Date.now() / 1000) } },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE Crontabs SET status=1,pid=NULL,queued_token=NULL
|
||||||
|
WHERE status IN (0,3) AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.cron_id=Crontabs.id)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronTriggers t
|
||||||
|
WHERE t.cron_id=Crontabs.id AND t.state IN ('running','queued'))`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -0,0 +1,61 @@
|
|||||||
|
import { join } from 'path';
|
||||||
|
import { existsSync } from 'fs';
|
||||||
|
import { receiptPath } from '../settlement/exitReceipt.cjs';
|
||||||
|
import { spawn } from 'cross-spawn';
|
||||||
|
import type { ChildProcessWithoutNullStreams } from 'child_process';
|
||||||
|
import type { Readable } from 'stream';
|
||||||
|
|
||||||
|
// A managed command waits on its parent's pipe. EOF before authorization exits
|
||||||
|
// without interpreting the command, even when the worker is killed by SIGKILL.
|
||||||
|
export function spawnCronCommand(
|
||||||
|
command: string,
|
||||||
|
triggerId?: string,
|
||||||
|
onCommandStart?: (at: number) => void,
|
||||||
|
outputPath?: string,
|
||||||
|
) {
|
||||||
|
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
|
||||||
|
const sourceScript = join(__dirname, '../../../shell/cron-command.py');
|
||||||
|
const supervisor = existsSync(sourceScript)
|
||||||
|
? sourceScript
|
||||||
|
: join(process.env.QL_DIR!, 'shell/cron-command.py');
|
||||||
|
const args = [
|
||||||
|
'-I',
|
||||||
|
'-S',
|
||||||
|
supervisor,
|
||||||
|
command,
|
||||||
|
String(process.pid),
|
||||||
|
receiptPath(triggerId) || '',
|
||||||
|
process.execPath,
|
||||||
|
join(__dirname, '../../shared/managedExit.cjs'),
|
||||||
|
];
|
||||||
|
if (onCommandStart) args.push('report-start');
|
||||||
|
if (outputPath) args.push('log-output', outputPath);
|
||||||
|
const child = spawn('python3', args, {
|
||||||
|
env: { ...process.env, QL_TRIGGER_ID: triggerId },
|
||||||
|
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe',
|
||||||
|
}) as ChildProcessWithoutNullStreams;
|
||||||
|
if (onCommandStart && child.stdio[3]) {
|
||||||
|
const timing = child.stdio[3] as Readable;
|
||||||
|
let stamp = '';
|
||||||
|
timing.setEncoding('ascii').on('data', (chunk) => {
|
||||||
|
stamp += chunk;
|
||||||
|
});
|
||||||
|
timing.once('end', () => {
|
||||||
|
if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp));
|
||||||
|
});
|
||||||
|
timing.on('error', () => {}); // Missing telemetry must not change the command result.
|
||||||
|
}
|
||||||
|
// A concurrent stop can close the pipe before the authorization write.
|
||||||
|
child.stdin.on('error', () => {});
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function releaseCronCommand(
|
||||||
|
child: ChildProcessWithoutNullStreams,
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) =>
|
||||||
|
child.stdin.end('run\n', (error?: Error) =>
|
||||||
|
error ? reject(error) : resolve(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,930 @@
|
|||||||
|
import type { Logger } from 'winston';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import {
|
||||||
|
Op,
|
||||||
|
where,
|
||||||
|
col as colFn,
|
||||||
|
FindOptions,
|
||||||
|
QueryTypes,
|
||||||
|
Transaction,
|
||||||
|
} from 'sequelize';
|
||||||
|
import config from '../../config/index';
|
||||||
|
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
|
||||||
|
import {
|
||||||
|
RunningInstanceModel,
|
||||||
|
InstanceStatus,
|
||||||
|
} from '../../data/runningInstance';
|
||||||
|
import { TriggerHistory, TriggerState } from '../history';
|
||||||
|
import {
|
||||||
|
finishStoppedTree,
|
||||||
|
hasLiveCronProcess,
|
||||||
|
pidNamespaceOwner,
|
||||||
|
systemOwner,
|
||||||
|
verifyCronProcess,
|
||||||
|
} from './cronProcess';
|
||||||
|
import { killTask, getUniqPath } from '../../config/util';
|
||||||
|
import { resolveLogPath } from '../../shared/logPath';
|
||||||
|
import { resolveFileAccess } from '../../shared/fileAccess';
|
||||||
|
import { shellValue } from '../scheduling/cronScheduling';
|
||||||
|
import taskLimit from './cronLimit';
|
||||||
|
import { logStreamManager } from '../../shared/logStreamManager';
|
||||||
|
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||||
|
import { observeChildProcess, asError } from '../../shared/childProcess';
|
||||||
|
import { t } from '../../shared/i18n';
|
||||||
|
import fs from 'fs/promises';
|
||||||
|
import path from 'path';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
|
type BatchStopSnapshot = {
|
||||||
|
docs: Array<
|
||||||
|
Pick<
|
||||||
|
Crontab,
|
||||||
|
| 'id'
|
||||||
|
| 'status'
|
||||||
|
| 'pid'
|
||||||
|
| 'log_path'
|
||||||
|
| 'queued_token'
|
||||||
|
| 'last_execution_time'
|
||||||
|
>
|
||||||
|
>;
|
||||||
|
instances: Array<{ id?: number; cron_id: number; pid?: number }>;
|
||||||
|
cancelled: string[];
|
||||||
|
missingPids?: number[];
|
||||||
|
missingTargets?: string[];
|
||||||
|
identityConflict: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type StopResult = { code: number; message: string; data?: { outcome: string } };
|
||||||
|
|
||||||
|
// Boundary to the existing service facade; no dependency on CronService itself.
|
||||||
|
export interface CronExecutionHost {
|
||||||
|
getDb(query: FindOptions<Crontab>['where']): Promise<Crontab>;
|
||||||
|
makeCommand(tab: Crontab, realTime?: boolean): string;
|
||||||
|
runSingle(
|
||||||
|
cronId: number,
|
||||||
|
expectedToken?: string,
|
||||||
|
triggerId?: string,
|
||||||
|
submitted?: Crontab,
|
||||||
|
): Promise<number | void>;
|
||||||
|
stopInstance(cronId: number, instanceId: number): Promise<StopResult>;
|
||||||
|
stop(ids: number[], requestId?: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CronExecution {
|
||||||
|
constructor(private logger: Logger, private host: CronExecutionHost) {}
|
||||||
|
|
||||||
|
public async run(ids: number[], source: 'manual' | 'boot' = 'manual') {
|
||||||
|
const token = randomUUID();
|
||||||
|
const database = CrontabModel.sequelize!;
|
||||||
|
const history = new TriggerHistory(database);
|
||||||
|
const submission = await database.transaction(async (transaction) => {
|
||||||
|
const rows = await CrontabModel.findAll({
|
||||||
|
where: { id: ids },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
const accepted: Crontab[] = [];
|
||||||
|
const triggers: Array<{
|
||||||
|
taskId: number;
|
||||||
|
triggerId: string;
|
||||||
|
state: 'queued' | 'skipped';
|
||||||
|
reason: 'overlap' | null;
|
||||||
|
}> = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const id = row.id!;
|
||||||
|
const trigger = token + '-' + id;
|
||||||
|
await history.enqueue(
|
||||||
|
trigger,
|
||||||
|
id,
|
||||||
|
source,
|
||||||
|
null,
|
||||||
|
Date.now(),
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!row.allow_multiple_instances &&
|
||||||
|
(hasLiveCronProcess(row.status, row.pid) ||
|
||||||
|
(await history.isRunning(id, transaction)))
|
||||||
|
) {
|
||||||
|
await history.finish(
|
||||||
|
trigger,
|
||||||
|
'skipped',
|
||||||
|
'overlap',
|
||||||
|
null,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
triggers.push({
|
||||||
|
taskId: id,
|
||||||
|
triggerId: trigger,
|
||||||
|
state: 'skipped',
|
||||||
|
reason: 'overlap',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
accepted.push(row.get({ plain: true }));
|
||||||
|
triggers.push({
|
||||||
|
taskId: id,
|
||||||
|
triggerId: trigger,
|
||||||
|
state: 'queued',
|
||||||
|
reason: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.queued, queued_token: token },
|
||||||
|
{
|
||||||
|
where: { id: accepted.map((row) => row.id!) },
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return { queued: accepted, triggers };
|
||||||
|
});
|
||||||
|
for (const row of submission.queued) {
|
||||||
|
const id = row.id!;
|
||||||
|
void this.host
|
||||||
|
.runSingle(id, token, token + '-' + id, row)
|
||||||
|
.catch((err) => this.logger.error(String(err)));
|
||||||
|
}
|
||||||
|
return submission.triggers;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly stoppingBatches = new Map<string, Promise<void>>();
|
||||||
|
|
||||||
|
public async stop(ids: number[], requestId?: string) {
|
||||||
|
if (!ids.length && !requestId) return;
|
||||||
|
const targets = [...new Set(ids)].sort((a, b) => a - b);
|
||||||
|
const cronIds = JSON.stringify(targets);
|
||||||
|
if (!requestId) return this.stopBatch(targets, cronIds);
|
||||||
|
const key = requestId + '/' + cronIds;
|
||||||
|
const pending = this.stoppingBatches.get(key);
|
||||||
|
if (pending) return pending;
|
||||||
|
// The database arbitrates different payloads and competing workers.
|
||||||
|
const done = this.stopBatch(targets, cronIds, requestId).finally(() =>
|
||||||
|
this.stoppingBatches.delete(key),
|
||||||
|
);
|
||||||
|
this.stoppingBatches.set(key, done);
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async stopBatch(ids: number[], cronIds: string, requestId?: string) {
|
||||||
|
const database = CrontabModel.sequelize!;
|
||||||
|
const history = new TriggerHistory(database);
|
||||||
|
const snapshot = await database.transaction(
|
||||||
|
{ type: Transaction.TYPES.IMMEDIATE },
|
||||||
|
async (transaction): Promise<BatchStopSnapshot | null> => {
|
||||||
|
if (requestId) {
|
||||||
|
const [existing] = await database.query<{
|
||||||
|
cron_ids: string;
|
||||||
|
snapshot: string | null;
|
||||||
|
status_code: number;
|
||||||
|
}>(
|
||||||
|
'SELECT cron_ids,snapshot,status_code FROM CronStopBatches WHERE request_id=$requestId',
|
||||||
|
{ transaction, bind: { requestId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
if (existing.cron_ids !== cronIds)
|
||||||
|
throw Object.assign(
|
||||||
|
new Error('Idempotency-Key already used for different tasks'),
|
||||||
|
{ status: 409 },
|
||||||
|
);
|
||||||
|
if (existing.status_code === 409)
|
||||||
|
throw Object.assign(new Error(t('实例不存在或已停止')), {
|
||||||
|
status: 409,
|
||||||
|
});
|
||||||
|
return existing.snapshot ? JSON.parse(existing.snapshot) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const docs = await CrontabModel.findAll({
|
||||||
|
attributes: [
|
||||||
|
'id',
|
||||||
|
'status',
|
||||||
|
'pid',
|
||||||
|
'log_path',
|
||||||
|
'queued_token',
|
||||||
|
'last_execution_time',
|
||||||
|
],
|
||||||
|
where: { id: ids },
|
||||||
|
transaction,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const cancelled = await history.cancelQueuedInTransaction(
|
||||||
|
ids,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
const instances = await RunningInstanceModel.findAll({
|
||||||
|
attributes: ['id', 'cron_id', 'pid'],
|
||||||
|
where: { cron_id: ids, status: InstanceStatus.running },
|
||||||
|
transaction,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const { missingTargets, identityConflict } =
|
||||||
|
await this.attachLegacyStopTargets(
|
||||||
|
docs,
|
||||||
|
instances,
|
||||||
|
history,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
for (const instance of instances) {
|
||||||
|
if (instance.pid)
|
||||||
|
await history.queueInstanceStop(
|
||||||
|
instance.id!,
|
||||||
|
instance.cron_id,
|
||||||
|
instance.pid,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const doc of docs) {
|
||||||
|
if (doc.status === CrontabStatus.queued) {
|
||||||
|
await CrontabModel.update(
|
||||||
|
{
|
||||||
|
status: CrontabStatus.idle,
|
||||||
|
pid: null,
|
||||||
|
queued_token: null,
|
||||||
|
} as any,
|
||||||
|
{
|
||||||
|
where: { id: doc.id, status: CrontabStatus.queued },
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const batch = {
|
||||||
|
docs,
|
||||||
|
cancelled,
|
||||||
|
instances,
|
||||||
|
missingTargets,
|
||||||
|
identityConflict,
|
||||||
|
};
|
||||||
|
if (requestId) {
|
||||||
|
await database.query(
|
||||||
|
'INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($requestId,$cronIds,$snapshot)',
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { requestId, cronIds, snapshot: JSON.stringify(batch) },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return batch;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!snapshot) return;
|
||||||
|
const {
|
||||||
|
docs,
|
||||||
|
cancelled,
|
||||||
|
instances,
|
||||||
|
missingPids,
|
||||||
|
missingTargets,
|
||||||
|
identityConflict,
|
||||||
|
} = snapshot;
|
||||||
|
if (cancelled.length)
|
||||||
|
process.send?.({ type: 'cancel-queued-triggers', ids: cancelled });
|
||||||
|
const stopped = new Set(missingTargets);
|
||||||
|
let failure: Error | undefined;
|
||||||
|
for (const instance of instances) {
|
||||||
|
try {
|
||||||
|
const result = await this.host.stopInstance(
|
||||||
|
instance.cron_id,
|
||||||
|
instance.id!,
|
||||||
|
);
|
||||||
|
if (result.code === 409)
|
||||||
|
failure ??= Object.assign(new Error(result.message), { status: 409 });
|
||||||
|
if (
|
||||||
|
instance.pid &&
|
||||||
|
'data' in result &&
|
||||||
|
result.data?.outcome === 'stopped'
|
||||||
|
)
|
||||||
|
stopped.add(instance.cron_id + '/' + instance.pid);
|
||||||
|
} catch (error) {
|
||||||
|
failure ??= asError(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const doc of docs) {
|
||||||
|
if (
|
||||||
|
doc.status !== CrontabStatus.running ||
|
||||||
|
(doc.pid &&
|
||||||
|
!missingPids?.includes(doc.pid) &&
|
||||||
|
!stopped.has(doc.id + '/' + doc.pid))
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
const remaining = await RunningInstanceModel.count({
|
||||||
|
where: { cron_id: doc.id, status: InstanceStatus.running },
|
||||||
|
});
|
||||||
|
if (remaining) continue;
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle, pid: null, queued_token: null } as any,
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
id: doc.id,
|
||||||
|
status: CrontabStatus.running,
|
||||||
|
[Op.and]: [
|
||||||
|
where(colFn('queued_token'), {
|
||||||
|
[Op.eq]: doc.queued_token ?? null,
|
||||||
|
}),
|
||||||
|
where(colFn('pid'), { [Op.eq]: doc.pid ?? null }),
|
||||||
|
where(colFn('log_path'), { [Op.eq]: doc.log_path ?? null }),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (failure) throw failure;
|
||||||
|
// Retain the key after success. Even a much later retry must never take a new snapshot.
|
||||||
|
if (requestId)
|
||||||
|
await database.query(
|
||||||
|
'UPDATE CronStopBatches SET snapshot=NULL,status_code=$status WHERE request_id=$requestId AND snapshot IS NOT NULL',
|
||||||
|
{ bind: { requestId, status: identityConflict ? 409 : 200 } },
|
||||||
|
);
|
||||||
|
if (identityConflict)
|
||||||
|
throw Object.assign(new Error(t('实例不存在或已停止')), { status: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Older databases may have a PID or command receipt without an instance.
|
||||||
|
// Attach verified targets before releasing the stop snapshot transaction.
|
||||||
|
private async attachLegacyStopTargets(
|
||||||
|
docs: BatchStopSnapshot['docs'],
|
||||||
|
instances: BatchStopSnapshot['instances'],
|
||||||
|
history: TriggerHistory,
|
||||||
|
transaction: Transaction,
|
||||||
|
) {
|
||||||
|
const commands = await history.activeCommands(
|
||||||
|
docs.map((doc) => doc.id!),
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
const registered = new Set(
|
||||||
|
instances.map((row) => row.cron_id + '/' + row.pid),
|
||||||
|
);
|
||||||
|
const registeredPids = new Set(instances.map((row) => row.pid));
|
||||||
|
const legacy = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
pid: number;
|
||||||
|
cronId: number;
|
||||||
|
trigger?: string;
|
||||||
|
identity?: string;
|
||||||
|
started?: number;
|
||||||
|
log?: string;
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
for (const doc of docs) {
|
||||||
|
const key = doc.id + '/' + doc.pid;
|
||||||
|
if (
|
||||||
|
doc.status === CrontabStatus.running &&
|
||||||
|
doc.pid &&
|
||||||
|
!registered.has(key)
|
||||||
|
)
|
||||||
|
legacy.set(key, {
|
||||||
|
pid: doc.pid,
|
||||||
|
cronId: doc.id!,
|
||||||
|
started: doc.last_execution_time,
|
||||||
|
log: doc.log_path,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const command of commands) {
|
||||||
|
const pid = Number(command.command_identity.split(':')[1]);
|
||||||
|
const key = command.cron_id + '/' + pid;
|
||||||
|
if (!registered.has(key))
|
||||||
|
legacy.set(key, {
|
||||||
|
pid,
|
||||||
|
cronId: command.cron_id,
|
||||||
|
trigger: command.id,
|
||||||
|
identity: command.command_identity,
|
||||||
|
started: Math.floor(command.started_at / 1000),
|
||||||
|
log: command.log_path,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let identityConflict = false;
|
||||||
|
const missingTargets: string[] = [];
|
||||||
|
for (const target of legacy.values()) {
|
||||||
|
const { pid } = target;
|
||||||
|
// A different task already owns this PID in the snapshot.
|
||||||
|
if (registeredPids.has(pid)) {
|
||||||
|
identityConflict = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let identity: string;
|
||||||
|
try {
|
||||||
|
identity = systemOwner(pid);
|
||||||
|
verifyCronProcess(pid, target.cronId, target.identity, target.started);
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
|
||||||
|
)
|
||||||
|
missingTargets.push(target.cronId + '/' + pid);
|
||||||
|
else if ((error as { status?: number }).status === 409)
|
||||||
|
identityConflict = true;
|
||||||
|
else throw error;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const row = await RunningInstanceModel.create(
|
||||||
|
{
|
||||||
|
cron_id: target.cronId,
|
||||||
|
pid,
|
||||||
|
status: InstanceStatus.running,
|
||||||
|
started_at: target.started || dayjs().unix(),
|
||||||
|
log_path: target.log,
|
||||||
|
},
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
if (target.trigger)
|
||||||
|
await CrontabModel.sequelize!.query(
|
||||||
|
"UPDATE CronTriggers SET instance_id=$id,process_identity=$identity WHERE id=$trigger AND state='running'",
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { id: row.id, identity, trigger: target.trigger },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await history.queueInstanceStop(
|
||||||
|
row.id!,
|
||||||
|
target.cronId,
|
||||||
|
pid,
|
||||||
|
transaction,
|
||||||
|
identity,
|
||||||
|
);
|
||||||
|
instances.push({ id: row.id, cron_id: target.cronId, pid });
|
||||||
|
}
|
||||||
|
return { missingTargets, identityConflict };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async resumePendingStops(
|
||||||
|
history: TriggerHistory,
|
||||||
|
requests: Awaited<ReturnType<TriggerHistory['pendingStops']>>,
|
||||||
|
batches: Awaited<ReturnType<TriggerHistory['pendingStopBatches']>> = [],
|
||||||
|
) {
|
||||||
|
for (const row of requests) {
|
||||||
|
try {
|
||||||
|
const result = await this.host.stopInstance(
|
||||||
|
row.cron_id,
|
||||||
|
row.instance_id,
|
||||||
|
);
|
||||||
|
if (result.code !== 200) this.logger.warn(result.message);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
|
||||||
|
row.instance_id,
|
||||||
|
row.pid,
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const batch of batches) {
|
||||||
|
try {
|
||||||
|
await this.host.stop(JSON.parse(batch.cron_ids), batch.request_id);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(asError(error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await history.recoverSystemOwners();
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly stoppingInstances = new Map<
|
||||||
|
string,
|
||||||
|
Promise<{ code: number; message: string; data?: { outcome: string } }>
|
||||||
|
>();
|
||||||
|
|
||||||
|
public stopInstance(cronId: number, instanceId: number) {
|
||||||
|
const key = `${cronId}/${instanceId}`;
|
||||||
|
const pending = this.stoppingInstances.get(key);
|
||||||
|
if (pending) return pending;
|
||||||
|
const stop = this.stopOneInstance(cronId, instanceId).finally(() =>
|
||||||
|
this.stoppingInstances.delete(key),
|
||||||
|
);
|
||||||
|
this.stoppingInstances.set(key, stop);
|
||||||
|
return stop;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async stopOneInstance(cronId: number, instanceId: number) {
|
||||||
|
const ended = {
|
||||||
|
code: 200,
|
||||||
|
data: { outcome: 'ended' },
|
||||||
|
message: t('实例已结束'),
|
||||||
|
};
|
||||||
|
const stopped = {
|
||||||
|
code: 200,
|
||||||
|
data: { outcome: 'stopped' },
|
||||||
|
message: t('实例已停止'),
|
||||||
|
};
|
||||||
|
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||||
|
const instance = await RunningInstanceModel.findOne({
|
||||||
|
where: { id: instanceId, cron_id: cronId },
|
||||||
|
});
|
||||||
|
if (!instance) {
|
||||||
|
await CrontabModel.sequelize!.query(
|
||||||
|
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND cron_id=$cronId',
|
||||||
|
{ bind: { instanceId, cronId } },
|
||||||
|
);
|
||||||
|
return { code: 404, message: t('实例不存在或已停止') };
|
||||||
|
}
|
||||||
|
const pending = await history.pendingStop(instanceId);
|
||||||
|
const savedTargets: string[] = pending?.targets
|
||||||
|
? JSON.parse(pending.targets)
|
||||||
|
: [];
|
||||||
|
const settle = () =>
|
||||||
|
history.stopVerifiedInstance(instanceId, (transaction) =>
|
||||||
|
this.settleLegacyStop(instanceId, cronId, instance.pid, transaction),
|
||||||
|
);
|
||||||
|
const finishClaim = async (claim: NonNullable<typeof pending>) => {
|
||||||
|
await finishStoppedTree(
|
||||||
|
claim.targets ? JSON.parse(claim.targets) : [],
|
||||||
|
claim.signalled_at,
|
||||||
|
);
|
||||||
|
return (await settle()) ? stopped : ended;
|
||||||
|
};
|
||||||
|
const releaseUnsignalled = async (recoverEnded = false) => {
|
||||||
|
const claimed = await history.forgetStop(
|
||||||
|
instanceId,
|
||||||
|
recoverEnded
|
||||||
|
? async (tx) => {
|
||||||
|
await history.recoverSystemOwners(cronId, tx, instanceId);
|
||||||
|
if (
|
||||||
|
(await history.instanceStopRequested(instanceId, tx)) ===
|
||||||
|
undefined
|
||||||
|
)
|
||||||
|
await this.settleLegacyStop(
|
||||||
|
instanceId,
|
||||||
|
cronId,
|
||||||
|
instance.pid,
|
||||||
|
tx,
|
||||||
|
InstanceStatus.unknown,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
if (claimed) return finishClaim(claimed);
|
||||||
|
};
|
||||||
|
if (pending?.signalled) return finishClaim(pending);
|
||||||
|
if (instance.status !== InstanceStatus.running) {
|
||||||
|
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||||
|
const claimed = pending && (await releaseUnsignalled());
|
||||||
|
return (
|
||||||
|
claimed ??
|
||||||
|
(instance.status === InstanceStatus.stopped ? stopped : ended)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A cold restart destroys the old process tree. The same numeric PIDs
|
||||||
|
// may already belong to another execution, even when script and log match.
|
||||||
|
if (
|
||||||
|
pending?.namespace_owner &&
|
||||||
|
pending.namespace_owner !== pidNamespaceOwner()
|
||||||
|
) {
|
||||||
|
return (await releaseUnsignalled(true)) ?? ended;
|
||||||
|
}
|
||||||
|
if (!instance.pid || instance.pid < 1) {
|
||||||
|
return { code: 409, message: t('实例不存在或已停止') };
|
||||||
|
}
|
||||||
|
let identity =
|
||||||
|
pending?.root_identity ||
|
||||||
|
(await history.instanceIdentity(instanceId)) ||
|
||||||
|
savedTargets.find((birth) => birth.startsWith(`crond:${instance.pid}:`));
|
||||||
|
const verify = () =>
|
||||||
|
verifyCronProcess(instance.pid!, cronId, identity, instance.started_at, {
|
||||||
|
logPath: instance.log_path,
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
!identity &&
|
||||||
|
(await RunningInstanceModel.count({
|
||||||
|
where: {
|
||||||
|
id: { [Op.ne]: instanceId },
|
||||||
|
status: InstanceStatus.running,
|
||||||
|
pid: instance.pid,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
) {
|
||||||
|
const claimed = await releaseUnsignalled();
|
||||||
|
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
identity = verify() ?? identity;
|
||||||
|
// Traversing the process tree is asynchronous. Persist the individual
|
||||||
|
// request before traversal so a restart here also resumes this stop.
|
||||||
|
if (!pending || (!pending.root_identity && identity))
|
||||||
|
await history.queueInstanceStop(
|
||||||
|
instanceId,
|
||||||
|
cronId,
|
||||||
|
instance.pid,
|
||||||
|
undefined,
|
||||||
|
identity ?? undefined,
|
||||||
|
);
|
||||||
|
await killTask(instance.pid, true, verify, (signal, targets) =>
|
||||||
|
history.requestInstanceStop(instanceId, instance.pid!, signal, targets),
|
||||||
|
);
|
||||||
|
return (await settle()) ? stopped : ended;
|
||||||
|
} catch (error) {
|
||||||
|
const cause = (error as NodeJS.ErrnoException).code;
|
||||||
|
if (cause === 'ESRCH' || cause === 'PID_REUSED') {
|
||||||
|
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||||
|
const claimed = await releaseUnsignalled(true);
|
||||||
|
if (claimed) return claimed;
|
||||||
|
const latest = await RunningInstanceModel.findOne({
|
||||||
|
where: { id: instanceId, cron_id: cronId },
|
||||||
|
});
|
||||||
|
if (latest?.status === InstanceStatus.stopped) return stopped;
|
||||||
|
if (latest?.status === InstanceStatus.running) {
|
||||||
|
const requested = await history.instanceStopRequested(instanceId);
|
||||||
|
if (requested) return stopped;
|
||||||
|
if (cause === 'PID_REUSED' || requested === undefined)
|
||||||
|
return { code: 409, message: t('实例不存在或已停止') };
|
||||||
|
}
|
||||||
|
return ended;
|
||||||
|
}
|
||||||
|
if ((error as { status?: number }).status === 409) {
|
||||||
|
if (savedTargets.length) await finishStoppedTree(savedTargets);
|
||||||
|
const claimed = await releaseUnsignalled();
|
||||||
|
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
|
||||||
|
}
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
|
||||||
|
instanceId,
|
||||||
|
instance.pid,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async settleLegacyStop(
|
||||||
|
instanceId: number,
|
||||||
|
cronId: number,
|
||||||
|
pid: number | undefined,
|
||||||
|
transaction: Transaction,
|
||||||
|
status = InstanceStatus.stopped,
|
||||||
|
) {
|
||||||
|
const [updated] = await RunningInstanceModel.update(
|
||||||
|
{ status, finished_at: dayjs().unix() },
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
id: instanceId,
|
||||||
|
cron_id: cronId,
|
||||||
|
status: InstanceStatus.running,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!updated) {
|
||||||
|
const latest = await RunningInstanceModel.findOne({
|
||||||
|
where: { id: instanceId, cron_id: cronId },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
return latest?.status === InstanceStatus.stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are still other running instances for this cron
|
||||||
|
const otherRunning = await RunningInstanceModel.count({
|
||||||
|
where: { cron_id: cronId, status: InstanceStatus.running },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
if (otherRunning === 0) {
|
||||||
|
await CrontabModel.update(
|
||||||
|
{ status: CrontabStatus.idle, pid: null } as any,
|
||||||
|
{
|
||||||
|
where: { id: cronId, status: CrontabStatus.running, pid },
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return status === InstanceStatus.stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async runSingle(
|
||||||
|
cronId: number,
|
||||||
|
expectedToken?: string,
|
||||||
|
triggerId?: string,
|
||||||
|
submitted?: Crontab,
|
||||||
|
): Promise<number | void> {
|
||||||
|
return taskLimit.manualRunWithCronLimit(
|
||||||
|
async () => {
|
||||||
|
let absolutePath: string | undefined;
|
||||||
|
let logPath: string | undefined;
|
||||||
|
let queuedLogPath: string | null | undefined;
|
||||||
|
let queuedToken: string | null = null;
|
||||||
|
let claimed = false;
|
||||||
|
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||||
|
let state: TriggerState = 'skipped';
|
||||||
|
let reason: string | null = 'changed';
|
||||||
|
let exitCode: number | null = null;
|
||||||
|
try {
|
||||||
|
const cron = await this.host.getDb({ id: cronId });
|
||||||
|
const independent = Boolean(
|
||||||
|
triggerId &&
|
||||||
|
submitted?.allow_multiple_instances &&
|
||||||
|
cron.allow_multiple_instances,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!independent &&
|
||||||
|
(cron.status !== CrontabStatus.queued ||
|
||||||
|
(expectedToken !== undefined &&
|
||||||
|
cron.queued_token !== expectedToken))
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
queuedLogPath = cron.log_path ?? null;
|
||||||
|
if (
|
||||||
|
submitted &&
|
||||||
|
(submitted.recovery_from !== cron.recovery_from ||
|
||||||
|
submitted.isDisabled !== cron.isDisabled ||
|
||||||
|
submitted.command !== cron.command)
|
||||||
|
) {
|
||||||
|
queuedToken = expectedToken ?? null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
queuedToken = cron.queued_token ?? null;
|
||||||
|
const { id, command, log_name } = cron;
|
||||||
|
if (log_name === '/dev/null') {
|
||||||
|
logPath = '/dev/null';
|
||||||
|
} else {
|
||||||
|
const uniqPath = log_name
|
||||||
|
? path.relative(
|
||||||
|
config.logPath,
|
||||||
|
resolveLogPath(config.logPath, log_name),
|
||||||
|
)
|
||||||
|
: await getUniqPath(command, `${id}`);
|
||||||
|
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
|
||||||
|
logPath = `${uniqPath}/${logTime}${
|
||||||
|
independent ? '-' + expectedToken : ''
|
||||||
|
}.log`;
|
||||||
|
absolutePath = resolveFileAccess(config.logPath, [logPath]);
|
||||||
|
if (!absolutePath)
|
||||||
|
throw new Error('Log path is outside the log directory');
|
||||||
|
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
|
||||||
|
}
|
||||||
|
const outputPath = absolutePath;
|
||||||
|
if (triggerId && submitted) {
|
||||||
|
const claim = await history.claimManual(
|
||||||
|
triggerId,
|
||||||
|
submitted,
|
||||||
|
expectedToken!,
|
||||||
|
independent,
|
||||||
|
);
|
||||||
|
if (claim !== 'started') {
|
||||||
|
reason = claim;
|
||||||
|
queuedToken = expectedToken!;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const launchCommand = `real_log_path=${shellValue(
|
||||||
|
logPath,
|
||||||
|
)} no_delay=true ${this.host.makeCommand(cron, true)}`;
|
||||||
|
// Let the independent supervisor own the log, while the command keeps
|
||||||
|
// writing to a drained pipe even if the worker dies or the log fills up.
|
||||||
|
const supervisedLog = Boolean(triggerId && outputPath);
|
||||||
|
const cp = spawnCronCommand(
|
||||||
|
launchCommand,
|
||||||
|
triggerId,
|
||||||
|
undefined,
|
||||||
|
outputPath,
|
||||||
|
);
|
||||||
|
// Install observers before the first await: very short children may already exit.
|
||||||
|
const { completed } = observeChildProcess(cp, {
|
||||||
|
onStart: async () => {
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
triggerId &&
|
||||||
|
!(await history.bindCommand(triggerId, cp.pid!, logPath))
|
||||||
|
)
|
||||||
|
throw new Error('Task was cancelled before startup');
|
||||||
|
const [count] = await CrontabModel.update(
|
||||||
|
{
|
||||||
|
status: CrontabStatus.running,
|
||||||
|
pid: cp.pid,
|
||||||
|
log_path: logPath,
|
||||||
|
...(!triggerId && {
|
||||||
|
last_execution_time: dayjs().unix(),
|
||||||
|
last_running_time: null,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
...(independent
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
status: CrontabStatus.queued,
|
||||||
|
[Op.and]: [
|
||||||
|
where(colFn('queued_token'), {
|
||||||
|
[Op.eq]: queuedToken,
|
||||||
|
}),
|
||||||
|
where(colFn('log_path'), {
|
||||||
|
[Op.eq]: queuedLogPath,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (count !== 1)
|
||||||
|
throw new Error(
|
||||||
|
'Task was stopped or superseded before startup',
|
||||||
|
);
|
||||||
|
claimed = true;
|
||||||
|
if (triggerId) {
|
||||||
|
if (await history.shouldStop(triggerId)) cp.stdin.end();
|
||||||
|
else await releaseCronCommand(cp);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (triggerId) cp.stdin.destroy();
|
||||||
|
else if (cp.pid) await killTask(cp.pid, true);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onStdout:
|
||||||
|
outputPath && !supervisedLog
|
||||||
|
? (message) => logStreamManager.write(outputPath, message)
|
||||||
|
: undefined,
|
||||||
|
onStderr: supervisedLog
|
||||||
|
? async (message) => {
|
||||||
|
this.logger.error(
|
||||||
|
'[panel][Command supervisor] Task ID: %s, %s',
|
||||||
|
id,
|
||||||
|
message.trim(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
: outputPath
|
||||||
|
? (message) => logStreamManager.write(outputPath, message)
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
const result = await completed;
|
||||||
|
state = result.signal
|
||||||
|
? 'stopped'
|
||||||
|
: result.error || result.code !== 0
|
||||||
|
? 'failed'
|
||||||
|
: 'finished';
|
||||||
|
reason = result.error ? 'spawn' : result.signal || null;
|
||||||
|
exitCode = result.code;
|
||||||
|
if (result.error) {
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][执行任务失败] 任务ID: %s, 错误: %s'),
|
||||||
|
id,
|
||||||
|
result.error.message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.logger.info(
|
||||||
|
t('[panel][执行任务结束] 任务ID: %s, 退出码: %j'),
|
||||||
|
id,
|
||||||
|
result.code,
|
||||||
|
);
|
||||||
|
return { ...cron, pid: cp.pid, ...result } as any;
|
||||||
|
} catch (error) {
|
||||||
|
state = 'failed';
|
||||||
|
reason = 'spawn';
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][创建任务失败] 任务ID: %s, 错误: %s'),
|
||||||
|
cronId,
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
if (absolutePath) await logStreamManager.closeStream(absolutePath);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][关闭任务日志失败] %s'),
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Do not overwrite a newer run's state or its script-reported exit code.
|
||||||
|
await CrontabModel.update(
|
||||||
|
{
|
||||||
|
status: CrontabStatus.idle,
|
||||||
|
pid: null,
|
||||||
|
queued_token: null,
|
||||||
|
} as any,
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
id: cronId,
|
||||||
|
[Op.and]: where(colFn('queued_token'), {
|
||||||
|
[Op.eq]: queuedToken,
|
||||||
|
}),
|
||||||
|
[Op.or]: [
|
||||||
|
...(queuedLogPath !== undefined && !claimed
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
status: CrontabStatus.queued,
|
||||||
|
[Op.and]: where(colFn('log_path'), {
|
||||||
|
[Op.eq]: queuedLogPath,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(claimed && logPath
|
||||||
|
? [{ log_path: logPath, status: CrontabStatus.running }]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
t('[panel][清理任务状态失败] %s'),
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (triggerId)
|
||||||
|
await history.complete(triggerId, state, reason, exitCode);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
|
id: triggerId,
|
||||||
|
name: submitted?.name || submitted?.command || String(cronId),
|
||||||
|
},
|
||||||
|
CrontabModel.sequelize,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import { EventEmitter } from 'events';
|
||||||
|
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||||
|
import os from 'os';
|
||||||
|
import type { Sequelize } from 'sequelize';
|
||||||
|
import {
|
||||||
|
QueueOccupants,
|
||||||
|
recordQueueAdmission,
|
||||||
|
} from '../queries/queueDiagnostics';
|
||||||
|
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
||||||
|
import { AuthDataType, SystemModel } from '../../data/system';
|
||||||
|
import Logger from '../../loaders/logger';
|
||||||
|
import { t, tf } from '../../shared/i18n';
|
||||||
|
import type { ICronFn, TCron } from '../../shared/interface';
|
||||||
|
import config from '../../config';
|
||||||
|
import { credentials } from '@grpc/grpc-js';
|
||||||
|
import { ApiClient } from '../../protos/api';
|
||||||
|
import { getGrpcCerts } from '../../config/grpcCerts';
|
||||||
|
|
||||||
|
// One scheduler/manual queue owner per process; services and execution share it.
|
||||||
|
class CronLimit {
|
||||||
|
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
||||||
|
private repeatCronNotifyMap = new Map<string, number>();
|
||||||
|
private warnSampling = (error: Error) =>
|
||||||
|
Logger.warn('[queue] Could not save occupancy: %s', error.message);
|
||||||
|
private scheduledOccupants = new QueueOccupants(
|
||||||
|
'scheduled',
|
||||||
|
() => this.cronLimit.concurrency,
|
||||||
|
this.warnSampling,
|
||||||
|
);
|
||||||
|
private manualOccupants = new QueueOccupants(
|
||||||
|
'manual',
|
||||||
|
() => this.manualCronoLimit.concurrency,
|
||||||
|
this.warnSampling,
|
||||||
|
);
|
||||||
|
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
|
||||||
|
queueClass: CronWaitQueue,
|
||||||
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
|
});
|
||||||
|
private manualCronoLimit = new PQueue({
|
||||||
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
|
});
|
||||||
|
private _client: ApiClient | null = null;
|
||||||
|
|
||||||
|
private get client(): ApiClient {
|
||||||
|
if (!this._client) {
|
||||||
|
const tlsConfig = getGrpcCerts();
|
||||||
|
const creds = tlsConfig
|
||||||
|
? credentials.createSsl(
|
||||||
|
Buffer.from(tlsConfig.caCert),
|
||||||
|
Buffer.from(tlsConfig.clientKey),
|
||||||
|
Buffer.from(tlsConfig.clientCert),
|
||||||
|
)
|
||||||
|
: credentials.createInsecure();
|
||||||
|
this._client = new ApiClient(`localhost:${config.grpcPort}`, creds, {
|
||||||
|
'grpc.enable_http_proxy': 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this._client;
|
||||||
|
}
|
||||||
|
|
||||||
|
get cronLimitActiveCount() {
|
||||||
|
return this.cronLimit.pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
get cronLimitPendingCount() {
|
||||||
|
return this.cronLimit.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.setCustomLimit();
|
||||||
|
this.handleEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleEvents() {
|
||||||
|
this.cronLimit.on('add', () => {
|
||||||
|
Logger.info(
|
||||||
|
t('[schedule][任务加入队列] 运行中任务数: %s, 等待中任务数: %s'),
|
||||||
|
this.cronLimitActiveCount,
|
||||||
|
this.cronLimitPendingCount,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this.cronLimit.on('active', () => {
|
||||||
|
Logger.info(
|
||||||
|
t('[schedule][开始处理任务] 运行中任务数: %s, 等待中任务数: %s'),
|
||||||
|
this.cronLimitActiveCount + 1,
|
||||||
|
this.cronLimitPendingCount,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this.cronLimit.on('completed', (param) => {
|
||||||
|
Logger.info(t('[schedule][任务处理成功] 参数 %s'), JSON.stringify(param));
|
||||||
|
});
|
||||||
|
this.cronLimit.on('error', (error) => {
|
||||||
|
Logger.error(
|
||||||
|
t('[schedule][任务处理错误] 参数 %s'),
|
||||||
|
JSON.stringify(error),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this.cronLimit.on('next', () => {
|
||||||
|
Logger.info(
|
||||||
|
t('[schedule][任务处理结束] 运行中任务数: %s, 等待中任务数: %s'),
|
||||||
|
this.cronLimitActiveCount,
|
||||||
|
this.cronLimitPendingCount,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
this.cronLimit.on('idle', () => {
|
||||||
|
Logger.info(t(`[schedule][任务队列] 空闲中...`));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public removeQueuedCron(id: string, completed?: ICronFn<any>) {
|
||||||
|
if (this.queuedCrons.has(id)) {
|
||||||
|
const runs = this.queuedCrons.get(id);
|
||||||
|
if (runs && runs.length > 0) {
|
||||||
|
const remaining = completed
|
||||||
|
? runs.filter((run) => run !== completed)
|
||||||
|
: runs.slice(0, -1);
|
||||||
|
if (remaining.length) this.queuedCrons.set(id, remaining);
|
||||||
|
else this.queuedCrons.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public get cronConcurrency() {
|
||||||
|
return this.manualCronoLimit.concurrency;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async setCustomLimit(limit?: number) {
|
||||||
|
if (limit) {
|
||||||
|
this.cronLimit.concurrency = limit;
|
||||||
|
this.manualCronoLimit.concurrency = limit;
|
||||||
|
this.scheduledOccupants.refresh();
|
||||||
|
this.manualOccupants.refresh();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await SystemModel.sync();
|
||||||
|
const doc = await SystemModel.findOne({
|
||||||
|
where: { type: AuthDataType.systemConfig },
|
||||||
|
});
|
||||||
|
if (doc?.info?.cronConcurrency) {
|
||||||
|
await this.setCustomLimit(doc.info.cronConcurrency);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async runWithCronLimit<T>(
|
||||||
|
cron: TCron,
|
||||||
|
fn: ICronFn<T>,
|
||||||
|
options?: Partial<QueueAddOptions>,
|
||||||
|
isCurrent: () => boolean = () => true,
|
||||||
|
onPending?: () => void,
|
||||||
|
waitingSignal?: EventEmitter,
|
||||||
|
triggerId?: string,
|
||||||
|
db?: Sequelize,
|
||||||
|
): Promise<T | void> {
|
||||||
|
if (!isCurrent()) return;
|
||||||
|
fn.cron = cron;
|
||||||
|
fn.isCurrent = isCurrent;
|
||||||
|
// Invalidated snapshots must not consume the new revision's repeat budget.
|
||||||
|
const runs = this.queuedCrons
|
||||||
|
.get(cron.id)
|
||||||
|
?.filter((run) => run.isCurrent?.() !== false);
|
||||||
|
if (cron.skip_if_pending && runs?.length) {
|
||||||
|
onPending?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = runs?.length ? [...runs, fn] : [fn];
|
||||||
|
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
|
||||||
|
if (result?.length > 5) {
|
||||||
|
if (repeatTimes < 3) {
|
||||||
|
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
||||||
|
this.client.systemNotify(
|
||||||
|
{
|
||||||
|
title: t('任务重复运行'),
|
||||||
|
content: tf(
|
||||||
|
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
|
||||||
|
cron.name || '',
|
||||||
|
cron.command || '',
|
||||||
|
cron.schedule || '',
|
||||||
|
5,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
(err, res) => {
|
||||||
|
if (err) {
|
||||||
|
Logger.error(
|
||||||
|
t('[schedule][任务重复运行] 通知失败 %s'),
|
||||||
|
JSON.stringify(err),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Logger.warn(t('[schedule][任务重复运行] 参数 %s'), JSON.stringify(cron));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.queuedCrons.set(cron.id, result);
|
||||||
|
const run = this.trackAdmission(
|
||||||
|
this.scheduledOccupants,
|
||||||
|
this.cronLimit.concurrency,
|
||||||
|
fn,
|
||||||
|
{ id: triggerId, name: cron.name || cron.id },
|
||||||
|
db,
|
||||||
|
);
|
||||||
|
if (!waitingSignal) return this.cronLimit.add(run, options);
|
||||||
|
return new Promise<T | void>((resolve, reject) => {
|
||||||
|
this.cronLimit
|
||||||
|
.add(run, {
|
||||||
|
...options,
|
||||||
|
waitingSignal,
|
||||||
|
onRemoved: () => {
|
||||||
|
this.scheduledOccupants.forget(triggerId);
|
||||||
|
resolve();
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.then(resolve, reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private trackAdmission<T>(
|
||||||
|
pool: QueueOccupants,
|
||||||
|
limit: number,
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
occupant: { id?: string; name: string },
|
||||||
|
db?: Sequelize,
|
||||||
|
) {
|
||||||
|
const admission = pool.admission(limit);
|
||||||
|
if (occupant.id && admission && db) {
|
||||||
|
pool.watch(occupant.id, db);
|
||||||
|
void recordQueueAdmission(db, occupant.id, admission).catch((error) =>
|
||||||
|
Logger.warn('[queue] Failed to record wait reason: %s', error.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return pool.track(fn, occupant, db);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async manualRunWithCronLimit<T>(
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
options?: Partial<QueueAddOptions>,
|
||||||
|
occupant: { id?: string; name: string } = { name: '—' },
|
||||||
|
db?: Sequelize,
|
||||||
|
): Promise<T | void> {
|
||||||
|
return this.manualCronoLimit.add(
|
||||||
|
this.trackAdmission(
|
||||||
|
this.manualOccupants,
|
||||||
|
this.manualCronoLimit.concurrency,
|
||||||
|
fn,
|
||||||
|
occupant,
|
||||||
|
db,
|
||||||
|
),
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new CronLimit();
|
||||||
@@ -2,38 +2,62 @@
|
|||||||
// path. Adjacent quoted/unquoted fragments belong to the same argument.
|
// path. Adjacent quoted/unquoted fragments belong to the same argument.
|
||||||
function words(command: string): string[] {
|
function words(command: string): string[] {
|
||||||
const result: string[] = [];
|
const result: string[] = [];
|
||||||
let value = '', quote = '', active = false;
|
let value = '',
|
||||||
|
quote = '',
|
||||||
|
active = false;
|
||||||
for (let i = 0; i < command.length; i++) {
|
for (let i = 0; i < command.length; i++) {
|
||||||
const c = command[i];
|
const c = command[i];
|
||||||
if (quote && c === quote) { quote = ''; continue; }
|
if (quote && c === quote) {
|
||||||
if (!quote && (c === "'" || c === '"')) { quote = c; active = true; continue; }
|
quote = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!quote && (c === "'" || c === '"')) {
|
||||||
|
quote = c;
|
||||||
|
active = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (c === '\\' && quote !== "'") {
|
if (c === '\\' && quote !== "'") {
|
||||||
const next = command[++i];
|
const next = command[++i];
|
||||||
if (next === undefined) return [];
|
if (next === undefined) return [];
|
||||||
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
|
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
|
||||||
if (next !== '\n') { value += next; active = true; }
|
if (next !== '\n') {
|
||||||
|
value += next;
|
||||||
|
active = true;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!quote && /[;&|<>()\n]/.test(c)) break;
|
if (!quote && /[;&|<>()\n]/.test(c)) break;
|
||||||
if (!quote && /\s/.test(c)) {
|
if (!quote && /\s/.test(c)) {
|
||||||
if (active) result.push(value);
|
if (active) result.push(value);
|
||||||
value = ''; active = false; continue;
|
value = '';
|
||||||
|
active = false;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
if (!active && !quote && c === '#') break;
|
if (!active && !quote && c === '#') break;
|
||||||
value += c; active = true;
|
value += c;
|
||||||
|
active = true;
|
||||||
}
|
}
|
||||||
if (quote) return [];
|
if (quote) return [];
|
||||||
if (active) result.push(value);
|
if (active) result.push(value);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function cronOperand(command: string, taskOnly = false): string | undefined {
|
export function cronOperand(
|
||||||
|
command: string,
|
||||||
|
taskOnly = false,
|
||||||
|
): string | undefined {
|
||||||
const args = words(command.trim());
|
const args = words(command.trim());
|
||||||
if (args[0] === 'task') args.shift();
|
if (args[0] === 'task') args.shift();
|
||||||
else if (taskOnly && args[0] === 'ql') return;
|
else if (taskOnly && args[0] === 'ql') return;
|
||||||
while (args[0] === '-l' || args[0] === '-m') {
|
while (args[0] === '-l' || args[0] === '-m') {
|
||||||
if (args.shift() === '-m') args.shift();
|
if (args.shift() === '-m') args.shift();
|
||||||
}
|
}
|
||||||
if (args.length > 1 && /^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(args[0])) args.shift();
|
if (
|
||||||
|
args.length > 1 &&
|
||||||
|
/^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(
|
||||||
|
args[0],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
args.shift();
|
||||||
return args[0];
|
return args[0];
|
||||||
}
|
}
|
||||||
@@ -17,16 +17,24 @@ export function hasLiveCronProcess(status?: number, pid?: number | null) {
|
|||||||
|
|
||||||
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
|
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
|
||||||
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
|
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
|
||||||
encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
encoding: 'utf8',
|
||||||
|
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
||||||
});
|
});
|
||||||
// ENOENT from spawning ps refers to the executable, not the target PID.
|
// ENOENT from spawning ps refers to the executable, not the target PID.
|
||||||
if (result.error) throw new Error('Cannot run ps: ' + result.error.message, { cause: result.error });
|
if (result.error)
|
||||||
|
throw new Error('Cannot run ps: ' + result.error.message, {
|
||||||
|
cause: result.error,
|
||||||
|
});
|
||||||
const value = result.stdout.trim();
|
const value = result.stdout.trim();
|
||||||
if (result.status === 0 && value) return value;
|
if (result.status === 0 && value) return value;
|
||||||
// BSD ps exits 1 without output when the selected PID has already exited.
|
// BSD ps exits 1 without output when the selected PID has already exited.
|
||||||
if (result.status === 1 && !value && !result.stderr.trim())
|
if (result.status === 1 && !value && !result.stderr.trim())
|
||||||
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||||
throw new Error(`Cannot read ${field} for PID ${pid}: ${result.stderr.trim() || result.signal || 'ps status ' + result.status}`);
|
throw new Error(
|
||||||
|
`Cannot read ${field} for PID ${pid}: ${
|
||||||
|
result.stderr.trim() || result.signal || 'ps status ' + result.status
|
||||||
|
}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function systemOwner(pid: number) {
|
export function systemOwner(pid: number) {
|
||||||
@@ -38,7 +46,8 @@ export function systemOwner(pid: number) {
|
|||||||
}
|
}
|
||||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||||
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
||||||
if (['Z', 'X', 'x'].includes(fields[0])) throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
if (['Z', 'X', 'x'].includes(fields[0]))
|
||||||
|
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||||
const startTicks = fields[19];
|
const startTicks = fields[19];
|
||||||
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
||||||
return `crond:${pid}:${startTicks}:${boot}`;
|
return `crond:${pid}:${startTicks}:${boot}`;
|
||||||
@@ -47,15 +56,21 @@ export function systemOwner(pid: number) {
|
|||||||
let linuxClockTicks: number | undefined;
|
let linuxClockTicks: number | undefined;
|
||||||
|
|
||||||
// A start packet may arrive after its PID was recycled, before the replacement reports.
|
// A start packet may arrive after its PID was recycled, before the replacement reports.
|
||||||
export function legacyProcessOwner(pid: number, started: number): string | undefined {
|
export function legacyProcessOwner(
|
||||||
|
pid: number,
|
||||||
|
started: number,
|
||||||
|
): string | undefined {
|
||||||
try {
|
try {
|
||||||
const identity = systemOwner(pid);
|
const identity = systemOwner(pid);
|
||||||
const birth = identity.slice(`crond:${pid}:`.length);
|
const birth = identity.slice(`crond:${pid}:`.length);
|
||||||
let bornAt: number;
|
let bornAt: number;
|
||||||
if (process.platform === 'linux') {
|
if (process.platform === 'linux') {
|
||||||
linuxClockTicks ??= Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
linuxClockTicks ??= Number(
|
||||||
|
execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }),
|
||||||
|
);
|
||||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||||
if (!boot || !(linuxClockTicks > 0)) throw new Error('Cannot read process birth time');
|
if (!boot || !(linuxClockTicks > 0))
|
||||||
|
throw new Error('Cannot read process birth time');
|
||||||
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
|
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
|
||||||
} else {
|
} else {
|
||||||
bornAt = Date.parse(birth + ' UTC') / 1000;
|
bornAt = Date.parse(birth + ' UTC') / 1000;
|
||||||
@@ -63,7 +78,8 @@ export function legacyProcessOwner(pid: number, started: number): string | undef
|
|||||||
// Both the callback and Linux boot time have one-second precision.
|
// Both the callback and Linux boot time have one-second precision.
|
||||||
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
|
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return undefined;
|
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
|
||||||
|
return undefined;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,44 +107,77 @@ export function isProcessDescendant(pid: number, root: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// For an individual legacy instance the task ID alone also matches its siblings.
|
// For an individual legacy instance the task ID alone also matches its siblings.
|
||||||
export function verifyCronProcess(pid: number, cronId: number, identity?: string | null, started?: number,
|
export function verifyCronProcess(
|
||||||
instance?: { logPath?: string }) {
|
pid: number,
|
||||||
const conflict = () => Object.assign(new Error('Task process identity could not be verified'), { status: 409 });
|
cronId: number,
|
||||||
|
identity?: string | null,
|
||||||
|
started?: number,
|
||||||
|
instance?: { logPath?: string },
|
||||||
|
) {
|
||||||
|
const conflict = () =>
|
||||||
|
Object.assign(new Error('Task process identity could not be verified'), {
|
||||||
|
status: 409,
|
||||||
|
});
|
||||||
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
|
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
|
||||||
if (identity) {
|
if (identity) {
|
||||||
// A birth token for this PID proves the original process is gone if the
|
// A birth token for this PID proves the original process is gone if the
|
||||||
// kernel now reports a different birth. Access errors remain retryable.
|
// kernel now reports a different birth. Access errors remain retryable.
|
||||||
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
|
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
|
||||||
let current: string;
|
let current: string;
|
||||||
try { current = systemOwner(pid); }
|
try {
|
||||||
catch (error) {
|
current = systemOwner(pid);
|
||||||
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
||||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
throw Object.assign(new Error('Command already exited'), {
|
||||||
|
code: 'ESRCH',
|
||||||
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
if (current !== identity) throw Object.assign(new Error('Command PID was reused'), { code: 'PID_REUSED', status: 409 });
|
if (current !== identity)
|
||||||
|
throw Object.assign(new Error('Command PID was reused'), {
|
||||||
|
code: 'PID_REUSED',
|
||||||
|
status: 409,
|
||||||
|
});
|
||||||
return current;
|
return current;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (process.platform === 'linux') {
|
if (process.platform === 'linux') {
|
||||||
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
|
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
|
||||||
if (instance && (!instance.logPath || instance.logPath === '/dev/null' ||
|
if (
|
||||||
!env.includes('real_log_path=' + instance.logPath))) throw conflict();
|
instance &&
|
||||||
|
(!instance.logPath ||
|
||||||
|
instance.logPath === '/dev/null' ||
|
||||||
|
!env.includes('real_log_path=' + instance.logPath))
|
||||||
|
)
|
||||||
|
throw conflict();
|
||||||
if (env.includes('ID=' + cronId) && started) {
|
if (env.includes('ID=' + cronId) && started) {
|
||||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||||
const birth = systemOwner(pid);
|
const birth = systemOwner(pid);
|
||||||
const ticks = Number(birth.split(':')[2]);
|
const ticks = Number(birth.split(':')[2]);
|
||||||
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
const hz = Number(
|
||||||
if (boot && hz > 0 && Math.floor(Number(boot[1]) + ticks / hz) <= started + 1) return birth;
|
execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }),
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
boot &&
|
||||||
|
hz > 0 &&
|
||||||
|
Math.floor(Number(boot[1]) + ticks / hz) <= started + 1
|
||||||
|
)
|
||||||
|
return birth;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
|
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
|
||||||
// Distinguish a completed child whose receipt is still being written
|
// Distinguish a completed child whose receipt is still being written
|
||||||
// from a live PID with an unverifiable identity.
|
// from a live PID with an unverifiable identity.
|
||||||
try { systemOwner(pid); } catch (probe) {
|
try {
|
||||||
if (['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!))
|
systemOwner(pid);
|
||||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
} catch (probe) {
|
||||||
|
if (
|
||||||
|
['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!)
|
||||||
|
)
|
||||||
|
throw Object.assign(new Error('Command already exited'), {
|
||||||
|
code: 'ESRCH',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,22 +186,36 @@ export function verifyCronProcess(pid: number, cronId: number, identity?: string
|
|||||||
|
|
||||||
// After a stop worker exits, descendants may already have been adopted by PID 1.
|
// After a stop worker exits, descendants may already have been adopted by PID 1.
|
||||||
// A saved birth identity still identifies them; walking the dead root no longer can.
|
// A saved birth identity still identifies them; walking the dead root no longer can.
|
||||||
export async function finishStoppedTree(identities: string[], signalledAt?: number | null) {
|
export async function finishStoppedTree(
|
||||||
const surviving = () => identities.flatMap(identity => {
|
identities: string[],
|
||||||
const pid = Number(identity.split(':')[1]);
|
signalledAt?: number | null,
|
||||||
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('Invalid saved process identity');
|
) {
|
||||||
try { return systemOwner(pid) === identity ? [pid] : []; }
|
const surviving = () =>
|
||||||
catch (error) {
|
identities.flatMap((identity) => {
|
||||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return [];
|
const pid = Number(identity.split(':')[1]);
|
||||||
throw error;
|
if (!Number.isSafeInteger(pid) || pid <= 1)
|
||||||
}
|
throw new Error('Invalid saved process identity');
|
||||||
});
|
try {
|
||||||
const remainingGrace = Math.min(1000, Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()));
|
return systemOwner(pid) === identity ? [pid] : [];
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)
|
||||||
|
)
|
||||||
|
return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const remainingGrace = Math.min(
|
||||||
|
1000,
|
||||||
|
Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()),
|
||||||
|
);
|
||||||
const graceDeadline = Date.now() + remainingGrace;
|
const graceDeadline = Date.now() + remainingGrace;
|
||||||
while (surviving().length) {
|
while (surviving().length) {
|
||||||
const remaining = graceDeadline - Date.now();
|
const remaining = graceDeadline - Date.now();
|
||||||
if (remaining <= 0) break;
|
if (remaining <= 0) break;
|
||||||
await new Promise(resolve => setTimeout(resolve, Math.min(20, remaining)));
|
await new Promise((resolve) =>
|
||||||
|
setTimeout(resolve, Math.min(20, remaining)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!surviving().length) return;
|
if (!surviving().length) return;
|
||||||
// Revalidate each PID immediately before signalling, including after the grace period.
|
// Revalidate each PID immediately before signalling, including after the grace period.
|
||||||
@@ -161,12 +224,14 @@ export async function finishStoppedTree(identities: string[], signalledAt?: numb
|
|||||||
try {
|
try {
|
||||||
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
|
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const deadline = Date.now() + 1000;
|
const deadline = Date.now() + 1000;
|
||||||
while (surviving().length) {
|
while (surviving().length) {
|
||||||
if (Date.now() >= deadline) throw new Error('Stopped process tree did not exit');
|
if (Date.now() >= deadline)
|
||||||
await new Promise(resolve => setTimeout(resolve, 20));
|
throw new Error('Stopped process tree did not exit');
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,9 @@ export interface CronQueueOptions extends QueueAddOptions {
|
|||||||
export class CronWaitQueue {
|
export class CronWaitQueue {
|
||||||
private entries: { run: Job; priority: number; detach: () => void }[] = [];
|
private entries: { run: Job; priority: number; detach: () => void }[] = [];
|
||||||
|
|
||||||
get size() { return this.entries.length; }
|
get size() {
|
||||||
|
return this.entries.length;
|
||||||
|
}
|
||||||
|
|
||||||
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
|
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
|
||||||
const { priority = 0, waitingSignal, onRemoved } = options;
|
const { priority = 0, waitingSignal, onRemoved } = options;
|
||||||
@@ -22,10 +24,19 @@ export class CronWaitQueue {
|
|||||||
this.entries.splice(index, 1);
|
this.entries.splice(index, 1);
|
||||||
onRemoved?.();
|
onRemoved?.();
|
||||||
};
|
};
|
||||||
const entry = { run, priority, detach: () => waitingSignal?.off('expired', remove) };
|
const entry = {
|
||||||
|
run,
|
||||||
|
priority,
|
||||||
|
detach: () => waitingSignal?.off('expired', remove),
|
||||||
|
};
|
||||||
const last = this.entries[this.size - 1];
|
const last = this.entries[this.size - 1];
|
||||||
if (!last || last.priority >= priority) this.entries.push(entry);
|
if (!last || last.priority >= priority) this.entries.push(entry);
|
||||||
else this.entries.splice(this.entries.findIndex((job) => job.priority < priority), 0, entry);
|
else
|
||||||
|
this.entries.splice(
|
||||||
|
this.entries.findIndex((job) => job.priority < priority),
|
||||||
|
0,
|
||||||
|
entry,
|
||||||
|
);
|
||||||
waitingSignal?.once('expired', remove);
|
waitingSignal?.once('expired', remove);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +47,8 @@ export class CronWaitQueue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
filter(options: Partial<CronQueueOptions>) {
|
filter(options: Partial<CronQueueOptions>) {
|
||||||
return this.entries.filter((entry) => entry.priority === options.priority).map((entry) => entry.run);
|
return this.entries
|
||||||
|
.filter((entry) => entry.priority === options.priority)
|
||||||
|
.map((entry) => entry.run);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,19 @@
|
|||||||
import { hasLiveCronProcess } from './cronProcess';
|
import { hasLiveCronProcess } from './cronProcess';
|
||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import PQueue from 'p-queue-cjs';
|
import PQueue from 'p-queue-cjs';
|
||||||
import { triggerHistory, TriggerState } from './triggerHistory';
|
import { triggerHistory, TriggerState } from '../history';
|
||||||
import { t } from './i18n';
|
import { t } from '../../shared/i18n';
|
||||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||||
import taskLimit from './pLimit';
|
import taskLimit from './cronLimit';
|
||||||
import Logger from '../loaders/logger';
|
import Logger from '../../loaders/logger';
|
||||||
import { ICron } from '../protos/cron';
|
import { ICron } from '../../protos/cron';
|
||||||
import { CrontabModel, CrontabStatus } from '../data/cron';
|
import { CrontabModel, CrontabStatus } from '../../data/cron';
|
||||||
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
import {
|
||||||
|
RunningInstanceModel,
|
||||||
|
InstanceStatus,
|
||||||
|
} from '../../data/runningInstance';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { observeChildProcess, asError } from './childProcess';
|
import { observeChildProcess, asError } from '../../shared/childProcess';
|
||||||
|
|
||||||
const waiting = new Map<string, () => void>();
|
const waiting = new Map<string, () => void>();
|
||||||
// A backlog of missed timers can otherwise open hundreds of competing SQLite
|
// A backlog of missed timers can otherwise open hundreds of competing SQLite
|
||||||
@@ -30,16 +33,33 @@ export async function runCron(
|
|||||||
const queuedAt = Date.now();
|
const queuedAt = Date.now();
|
||||||
if (trigger && history) {
|
if (trigger && history) {
|
||||||
const cronId = Number(cron.id);
|
const cronId = Number(cron.id);
|
||||||
const admitted = await historyWrites.add(() => cron.skip_if_pending
|
const admitted = await historyWrites.add(() =>
|
||||||
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
|
cron.skip_if_pending
|
||||||
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
|
? history.enqueueUnlessPending(
|
||||||
|
trigger.id,
|
||||||
|
cronId,
|
||||||
|
trigger.source,
|
||||||
|
trigger.time,
|
||||||
|
queuedAt,
|
||||||
|
cron.recovery_from,
|
||||||
|
)
|
||||||
|
: history.enqueue(
|
||||||
|
trigger.id,
|
||||||
|
cronId,
|
||||||
|
trigger.source,
|
||||||
|
trigger.time,
|
||||||
|
queuedAt,
|
||||||
|
),
|
||||||
|
);
|
||||||
if (!admitted) return;
|
if (!admitted) return;
|
||||||
}
|
}
|
||||||
let reason = 'capacity';
|
let reason = 'capacity';
|
||||||
let state: TriggerState = 'skipped';
|
let state: TriggerState = 'skipped';
|
||||||
let exitCode: number | null = null;
|
let exitCode: number | null = null;
|
||||||
let claimed = false;
|
let claimed = false;
|
||||||
const deadline = cron.max_queue_wait ? queuedAt + cron.max_queue_wait * 1000 : Infinity;
|
const deadline = cron.max_queue_wait
|
||||||
|
? queuedAt + cron.max_queue_wait * 1000
|
||||||
|
: Infinity;
|
||||||
let timer: NodeJS.Timeout | undefined;
|
let timer: NodeJS.Timeout | undefined;
|
||||||
const expiry = trigger ? new EventEmitter() : undefined;
|
const expiry = trigger ? new EventEmitter() : undefined;
|
||||||
const alive = () => isCurrent() && Date.now() < deadline;
|
const alive = () => isCurrent() && Date.now() < deadline;
|
||||||
@@ -55,7 +75,10 @@ export async function runCron(
|
|||||||
if (trigger) waiting.delete(trigger.id);
|
if (trigger) waiting.delete(trigger.id);
|
||||||
reason = 'changed';
|
reason = 'changed';
|
||||||
try {
|
try {
|
||||||
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
|
if (!alive()) {
|
||||||
|
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
||||||
|
return;
|
||||||
|
}
|
||||||
let multiple = false;
|
let multiple = false;
|
||||||
// A single-instance trigger must not interrupt work already in progress.
|
// A single-instance trigger must not interrupt work already in progress.
|
||||||
try {
|
try {
|
||||||
@@ -176,25 +199,42 @@ export async function runCron(
|
|||||||
}
|
}
|
||||||
if (trigger) {
|
if (trigger) {
|
||||||
claimed = await history!.start(trigger.id, Date.now(), multiple);
|
claimed = await history!.start(trigger.id, Date.now(), multiple);
|
||||||
if (!claimed) { reason = 'overlap'; return; }
|
if (!claimed) {
|
||||||
|
reason = 'overlap';
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!isCurrent() || Date.now() >= deadline) {
|
if (!isCurrent() || Date.now() >= deadline) {
|
||||||
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let saveStart: Promise<void> | undefined;
|
let saveStart: Promise<void> | undefined;
|
||||||
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
|
const cp = spawnCronCommand(
|
||||||
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
|
cmd,
|
||||||
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
|
trigger?.id,
|
||||||
});
|
trigger && history
|
||||||
} : undefined);
|
? (at) => {
|
||||||
|
saveStart = history
|
||||||
|
.recordCommandStart(trigger.id, at)
|
||||||
|
.catch((error) => {
|
||||||
|
Logger.warn(
|
||||||
|
'[schedule] Could not record command start: %s',
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
|
||||||
let denied: string | undefined;
|
let denied: string | undefined;
|
||||||
const { completed } = observeChildProcess(cp, {
|
const { completed } = observeChildProcess(cp, {
|
||||||
onStart: async () => {
|
onStart: async () => {
|
||||||
if (!trigger) return;
|
if (!trigger) return;
|
||||||
try {
|
try {
|
||||||
if (await history!.bindCommand(trigger.id, cp.pid!) && !await history!.shouldStop(trigger.id)) {
|
if (
|
||||||
|
(await history!.bindCommand(trigger.id, cp.pid!)) &&
|
||||||
|
!(await history!.shouldStop(trigger.id))
|
||||||
|
) {
|
||||||
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
|
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
|
||||||
else await releaseCronCommand(cp);
|
else await releaseCronCommand(cp);
|
||||||
}
|
}
|
||||||
@@ -212,8 +252,15 @@ export async function runCron(
|
|||||||
});
|
});
|
||||||
const result = await completed;
|
const result = await completed;
|
||||||
await saveStart;
|
await saveStart;
|
||||||
if (denied) { reason = denied; return; }
|
if (denied) {
|
||||||
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
|
reason = denied;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state = result.signal
|
||||||
|
? 'stopped'
|
||||||
|
: result.error || result.code !== 0
|
||||||
|
? 'failed'
|
||||||
|
: 'finished';
|
||||||
reason = result.error ? 'spawn' : result.signal || '';
|
reason = result.error ? 'spawn' : result.signal || '';
|
||||||
exitCode = result.code;
|
exitCode = result.code;
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
@@ -242,21 +289,43 @@ export async function runCron(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
if (trigger && expiry) waiting.set(trigger.id, () => {
|
if (trigger && expiry)
|
||||||
taskLimit.removeQueuedCron(cron.id, execute);
|
waiting.set(trigger.id, () => {
|
||||||
expiry.emit('expired');
|
taskLimit.removeQueuedCron(cron.id, execute);
|
||||||
});
|
expiry.emit('expired');
|
||||||
return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize);
|
});
|
||||||
|
return await taskLimit.runWithCronLimit(
|
||||||
|
cron,
|
||||||
|
execute,
|
||||||
|
undefined,
|
||||||
|
isCurrent,
|
||||||
|
() => {
|
||||||
|
reason = 'pending';
|
||||||
|
},
|
||||||
|
expiry,
|
||||||
|
trigger?.id,
|
||||||
|
CrontabModel.sequelize,
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
if (trigger) waiting.delete(trigger.id);
|
if (trigger) waiting.delete(trigger.id);
|
||||||
if (trigger && history) {
|
if (trigger && history) {
|
||||||
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
|
const outcomeReason =
|
||||||
|
state === 'skipped' && !isCurrent() ? 'changed' : reason;
|
||||||
const finishedAt = Date.now();
|
const finishedAt = Date.now();
|
||||||
await historyWrites.add(() => state === 'skipped' && !claimed
|
await historyWrites.add(
|
||||||
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
|
() =>
|
||||||
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
|
state === 'skipped' && !claimed
|
||||||
{ priority: 1 });
|
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
|
||||||
|
: history.complete(
|
||||||
|
trigger.id,
|
||||||
|
state,
|
||||||
|
outcomeReason || null,
|
||||||
|
exitCode,
|
||||||
|
finishedAt,
|
||||||
|
),
|
||||||
|
{ priority: 1 },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,806 @@
|
|||||||
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
|
import type { Crontab } from '../../data/cron';
|
||||||
|
import type {
|
||||||
|
TriggerSource,
|
||||||
|
TriggerState,
|
||||||
|
VerifiedSupervisorExit,
|
||||||
|
} from '../types';
|
||||||
|
import type { readExit } from '../settlement/exitReceipt.cjs';
|
||||||
|
import {
|
||||||
|
hasLiveCronProcess,
|
||||||
|
pidNamespaceOwner,
|
||||||
|
systemOwner,
|
||||||
|
} from './cronProcess';
|
||||||
|
|
||||||
|
type ExitReceipt = Awaited<ReturnType<typeof readExit>>;
|
||||||
|
|
||||||
|
// Evidence inspection and settlement remain in the existing ledger. Callers must
|
||||||
|
// use the supplied transaction so state, stop claims and statistics commit together.
|
||||||
|
export interface TriggerLifecycleEvidence {
|
||||||
|
exitBeforeStop(id: string): Promise<{
|
||||||
|
canonical: ExitReceipt;
|
||||||
|
recovered: ExitReceipt[];
|
||||||
|
published: boolean;
|
||||||
|
unreadable: boolean;
|
||||||
|
}>;
|
||||||
|
completeCommandExit(
|
||||||
|
id: string,
|
||||||
|
state: TriggerState,
|
||||||
|
reason: string | null,
|
||||||
|
code: number | null,
|
||||||
|
transaction: Transaction,
|
||||||
|
receipt?: ExitReceipt,
|
||||||
|
finishedAt?: number,
|
||||||
|
report?: VerifiedSupervisorExit | 'legacy',
|
||||||
|
recoveredCopies?: ExitReceipt[],
|
||||||
|
): Promise<void>;
|
||||||
|
recoverScriptSample(id: string, transaction: Transaction): Promise<void>;
|
||||||
|
replayPublishedExits(transaction: Transaction): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persisted transitions shared by manual, Node and system-crond executions.
|
||||||
|
// In particular, recovery may reclaim an unstarted slot, never an unknown result.
|
||||||
|
export class TriggerLifecycle {
|
||||||
|
constructor(
|
||||||
|
private database: Sequelize,
|
||||||
|
private evidence: TriggerLifecycleEvidence,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// Only unclaimed scheduler work can expire; its owner controls claimed runs.
|
||||||
|
async skipQueued(id: string, reason: string, finishedAt: number) {
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET state='skipped', reason=$reason, finished_at=$finishedAt
|
||||||
|
WHERE id=$id AND source IN ('node','recovery') AND state='queued' AND started_at IS NULL`,
|
||||||
|
{ bind: { id, reason, finishedAt }, type: QueryTypes.BULKUPDATE },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async enqueue(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
source: TriggerSource,
|
||||||
|
scheduledAt: number | null,
|
||||||
|
now = Date.now(),
|
||||||
|
transaction?: Transaction,
|
||||||
|
) {
|
||||||
|
// The SQLite driver returns changes on the statement that claimed this slot.
|
||||||
|
const changed = await this.database.query(
|
||||||
|
`INSERT INTO CronTriggers(id, cron_id, source, scheduled_at, queued_at, observed_at, owner, state)
|
||||||
|
VALUES ($id,$cronId,$source,$scheduledAt,$now,$now,$owner,'queued')
|
||||||
|
ON CONFLICT(id) DO UPDATE SET state='queued', reason=NULL, finished_at=NULL,
|
||||||
|
queued_at=excluded.queued_at, dequeued_at=NULL, queue_context=NULL, queue_live_context=NULL,
|
||||||
|
source=excluded.source, owner=excluded.owner
|
||||||
|
WHERE excluded.source='recovery' AND state='skipped' AND reason='restart' AND started_at IS NULL`,
|
||||||
|
{
|
||||||
|
bind: {
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
source,
|
||||||
|
scheduledAt,
|
||||||
|
now,
|
||||||
|
owner: process.env.SERVICE_TYPE || 'http',
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.BULKUPDATE,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return changed === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admission and competing pending runs share one write transaction.
|
||||||
|
async enqueueUnlessPending(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
source: 'node' | 'recovery',
|
||||||
|
scheduledAt: number,
|
||||||
|
now: number,
|
||||||
|
revision = 0,
|
||||||
|
) {
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
if (
|
||||||
|
!(await this.enqueue(id, cronId, source, scheduledAt, now, transaction))
|
||||||
|
)
|
||||||
|
return false;
|
||||||
|
await this.recoverSystemOwners(cronId, transaction);
|
||||||
|
const pending = await this.database.query(
|
||||||
|
`SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND id<>$id
|
||||||
|
AND source IN ('node','recovery','system')
|
||||||
|
AND (state='running' OR (state='queued' AND queued_at >= $revision)) LIMIT 1`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { cronId, id, revision },
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!pending.length) return true;
|
||||||
|
await this.finish(id, 'skipped', 'pending', null, transaction);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(
|
||||||
|
id: string,
|
||||||
|
now = Date.now(),
|
||||||
|
multiple = false,
|
||||||
|
transaction?: Transaction,
|
||||||
|
) {
|
||||||
|
const claim = () =>
|
||||||
|
this.database.query(
|
||||||
|
`UPDATE CronTriggers SET state='running', started_at=$now WHERE id=$id AND state='queued'
|
||||||
|
AND ($multiple OR NOT EXISTS (SELECT 1 FROM CronTriggers AS active
|
||||||
|
WHERE active.cron_id=CronTriggers.cron_id AND active.state='running'))`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { id, now, multiple: Number(multiple) },
|
||||||
|
type: QueryTypes.BULKUPDATE,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let changed = await claim();
|
||||||
|
if (!changed && !multiple && !transaction) {
|
||||||
|
const [task] = await this.database.query<{ cron_id: number }>(
|
||||||
|
"SELECT cron_id FROM CronTriggers WHERE id=$id AND state='queued'",
|
||||||
|
{ bind: { id }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (task && (await this.recoverSystemOwners(task.cron_id)))
|
||||||
|
changed = await claim();
|
||||||
|
}
|
||||||
|
return changed === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async claimManual(
|
||||||
|
id: string,
|
||||||
|
snapshot: Crontab,
|
||||||
|
token: string,
|
||||||
|
independent: boolean,
|
||||||
|
) {
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
// The write transaction orders a configuration save and a manual claim.
|
||||||
|
const rows = await this.database.query(
|
||||||
|
`SELECT 1 FROM Crontabs WHERE id=$cronId AND recovery_from IS $revision
|
||||||
|
AND command=$command AND COALESCE(isDisabled,0)=$disabled
|
||||||
|
AND COALESCE(allow_multiple_instances,0)=$multiple
|
||||||
|
AND ($independent OR (status=3 AND queued_token=$token))`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
bind: {
|
||||||
|
cronId: snapshot.id,
|
||||||
|
revision: snapshot.recovery_from ?? null,
|
||||||
|
command: snapshot.command,
|
||||||
|
disabled: snapshot.isDisabled || 0,
|
||||||
|
multiple: snapshot.allow_multiple_instances || 0,
|
||||||
|
independent: Number(independent),
|
||||||
|
token,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!rows.length) return 'changed';
|
||||||
|
if (!independent)
|
||||||
|
await this.recoverSystemOwners(snapshot.id, transaction);
|
||||||
|
return (await this.start(id, Date.now(), independent, transaction))
|
||||||
|
? 'started'
|
||||||
|
: 'overlap';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async finish(
|
||||||
|
id: string,
|
||||||
|
state: TriggerState,
|
||||||
|
reason: string | null = null,
|
||||||
|
code: number | null = null,
|
||||||
|
transaction?: Transaction,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
// A managed supervisor can observe the clock moving backwards during a run.
|
||||||
|
// Clients supply their own timestamps; validate those against the recorded start.
|
||||||
|
return this.database.query(
|
||||||
|
`UPDATE CronTriggers SET state=$state, reason=$reason, exit_code=$code,
|
||||||
|
started_at=CASE WHEN $state='skipped' THEN NULL ELSE started_at END,
|
||||||
|
finished_at=COALESCE(CASE WHEN owner IS NOT NULL OR $finishedAt >= started_at THEN $finishedAt END,CASE WHEN state='unknown' THEN finished_at END,$now)
|
||||||
|
WHERE id=$id AND (state IN ('running','queued') OR
|
||||||
|
(state='unknown' AND $state IN ('finished','failed','stopped')))`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.BULKUPDATE,
|
||||||
|
bind: {
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
reason,
|
||||||
|
code,
|
||||||
|
finishedAt: finishedAt ?? null,
|
||||||
|
now: Date.now(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async claimSummary(
|
||||||
|
cronId: number,
|
||||||
|
instance: number,
|
||||||
|
seconds: number,
|
||||||
|
transaction: Transaction,
|
||||||
|
observedStart: boolean,
|
||||||
|
duration: number | null = null,
|
||||||
|
) {
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE Crontabs SET last_instance_id=$instance,
|
||||||
|
last_execution_time=$seconds,last_running_time=$duration WHERE id=$cronId AND
|
||||||
|
(last_execution_time IS NULL OR last_execution_time<$seconds OR
|
||||||
|
(last_execution_time=$seconds AND (last_instance_id IS NULL OR
|
||||||
|
($observedStart AND last_instance_id<$instance))))`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: {
|
||||||
|
cronId,
|
||||||
|
instance,
|
||||||
|
seconds,
|
||||||
|
duration,
|
||||||
|
observedStart: Number(observedStart),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async isRunning(cronId: number, transaction: Transaction) {
|
||||||
|
await this.recoverSystemOwners(cronId, transaction);
|
||||||
|
const rows = await this.database.query(
|
||||||
|
"SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND state='running' LIMIT 1",
|
||||||
|
{ bind: { cronId }, transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return rows.length !== 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelQueued(ids: number[]) {
|
||||||
|
if (!ids.length) return [];
|
||||||
|
return this.database.transaction((tx) =>
|
||||||
|
this.cancelQueuedInTransaction(ids, tx),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
|
||||||
|
await this.database.query(
|
||||||
|
"UPDATE CronTriggers SET stop_requested=1 WHERE cron_id IN (:ids) AND state='running' AND command_identity IS NULL AND instance_id IS NULL",
|
||||||
|
{ replacements: { ids }, transaction },
|
||||||
|
);
|
||||||
|
const rows = await this.database.query<{ id: string }>(
|
||||||
|
"SELECT id FROM CronTriggers WHERE cron_id IN (:ids) AND state='queued'",
|
||||||
|
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET state='stopped',reason='cancelled',finished_at=:now
|
||||||
|
WHERE cron_id IN (:ids) AND state='queued'`,
|
||||||
|
{ replacements: { ids, now: Date.now() }, transaction },
|
||||||
|
);
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async queueInstanceStop(
|
||||||
|
instanceId: number,
|
||||||
|
cronId: number,
|
||||||
|
pid: number,
|
||||||
|
transaction?: Transaction,
|
||||||
|
identity?: string,
|
||||||
|
) {
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,root_identity,namespace_owner)
|
||||||
|
VALUES ($instanceId,$cronId,$pid,$identity,$namespace)
|
||||||
|
ON CONFLICT(instance_id) DO UPDATE SET root_identity=excluded.root_identity
|
||||||
|
WHERE root_identity IS NULL AND excluded.root_identity IS NOT NULL AND pid=excluded.pid AND signalled=0`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: {
|
||||||
|
instanceId,
|
||||||
|
cronId,
|
||||||
|
pid,
|
||||||
|
identity: identity ?? null,
|
||||||
|
namespace: pidNamespaceOwner(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStop(instanceId: number, transaction?: Transaction) {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
targets: string | null;
|
||||||
|
signalled: number;
|
||||||
|
signalled_at: number | null;
|
||||||
|
root_identity: string | null;
|
||||||
|
namespace_owner: string | null;
|
||||||
|
}>(
|
||||||
|
'SELECT targets,signalled,signalled_at,root_identity,namespace_owner FROM CronStopRequests WHERE instance_id=$instanceId',
|
||||||
|
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStopBatches() {
|
||||||
|
return this.database.query<{ request_id: string; cron_ids: string }>(
|
||||||
|
'SELECT request_id,cron_ids FROM CronStopBatches WHERE snapshot IS NOT NULL',
|
||||||
|
{ type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStops() {
|
||||||
|
return this.database.query<{
|
||||||
|
instance_id: number;
|
||||||
|
cron_id: number;
|
||||||
|
pid: number;
|
||||||
|
targets: string | null;
|
||||||
|
}>(
|
||||||
|
'SELECT instance_id,cron_id,pid,targets FROM CronStopRequests ORDER BY instance_id',
|
||||||
|
{ type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async forgetStop(
|
||||||
|
instanceId: number,
|
||||||
|
onEnded?: (tx: Transaction) => Promise<void>,
|
||||||
|
) {
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
await this.database.query(
|
||||||
|
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND signalled=0',
|
||||||
|
{ transaction, bind: { instanceId } },
|
||||||
|
);
|
||||||
|
const claimed = await this.pendingStop(instanceId, transaction);
|
||||||
|
if (!claimed && onEnded) await onEnded(transaction);
|
||||||
|
return claimed;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async shouldStop(id: string, transaction?: Transaction) {
|
||||||
|
const rows = await this.database.query(
|
||||||
|
'SELECT 1 FROM CronTriggers WHERE id=$id AND stop_requested=1',
|
||||||
|
{ transaction, bind: { id }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return rows.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The outer command can outlive any of its task wrappers.
|
||||||
|
async recordCommandStart(id: string, at: number) {
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET command_started_at=$at
|
||||||
|
WHERE id=$id AND command_started_at IS NULL AND started_at IS NOT NULL`,
|
||||||
|
{ bind: { id, at } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bindCommand(id: string, pid: number, log?: string) {
|
||||||
|
let identity: string;
|
||||||
|
try {
|
||||||
|
identity = systemOwner(pid);
|
||||||
|
} catch (error) {
|
||||||
|
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
|
||||||
|
return false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
instance_id: number | null;
|
||||||
|
cron_id: number;
|
||||||
|
started_at: number;
|
||||||
|
}>(
|
||||||
|
"SELECT instance_id,cron_id,started_at FROM CronTriggers WHERE id=$id AND state='running'",
|
||||||
|
{ transaction, bind: { id }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!row) return false;
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET command_identity=$identity WHERE id=$id',
|
||||||
|
{ transaction, bind: { identity, id } },
|
||||||
|
);
|
||||||
|
if (row.instance_id) {
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE RunningInstances SET pid=$pid WHERE id=$instance AND status=0',
|
||||||
|
{ transaction, bind: { pid, instance: row.instance_id } },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET process_identity=$identity WHERE id=$id',
|
||||||
|
{ transaction, bind: { identity, id } },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE Crontabs SET pid=$pid WHERE id=$cronId AND log_path=(SELECT log_path FROM CronTriggers WHERE id=$id) AND status=0',
|
||||||
|
{ transaction, bind: { pid, cronId: row.cron_id, id } },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await this.registerCommandInstance(
|
||||||
|
id,
|
||||||
|
row.cron_id,
|
||||||
|
pid,
|
||||||
|
identity,
|
||||||
|
row.started_at,
|
||||||
|
log,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async registerCommandInstance(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
pid: number,
|
||||||
|
identity: string,
|
||||||
|
started: number,
|
||||||
|
log: string | undefined,
|
||||||
|
transaction: Transaction,
|
||||||
|
) {
|
||||||
|
const seconds = Math.floor(started / 1000);
|
||||||
|
const [instance] = await this.database.query(
|
||||||
|
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
|
||||||
|
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
type: QueryTypes.INSERT,
|
||||||
|
bind: { cronId, pid, log: log ?? null, seconds },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET log_path=$log,instance_id=$instance,process_identity=$identity WHERE id=$id',
|
||||||
|
{ transaction, bind: { id, log: log ?? null, instance, identity } },
|
||||||
|
);
|
||||||
|
await this.claimSummary(cronId, instance, seconds, transaction, true);
|
||||||
|
if (log === undefined)
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE Crontabs SET status=0,pid=$pid,log_path=NULL WHERE id=$cronId AND status IS NOT 3',
|
||||||
|
{ transaction, bind: { cronId, pid } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async activeCommands(ids: number[], transaction?: Transaction) {
|
||||||
|
if (!ids.length) return [];
|
||||||
|
return this.database.query<{
|
||||||
|
id: string;
|
||||||
|
cron_id: number;
|
||||||
|
command_identity: string;
|
||||||
|
started_at: number;
|
||||||
|
log_path: string;
|
||||||
|
}>(
|
||||||
|
"SELECT id,cron_id,command_identity,started_at,log_path FROM CronTriggers WHERE cron_id IN (:ids) AND state='running' AND instance_id IS NULL AND command_identity IS NOT NULL",
|
||||||
|
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async instanceIdentity(instanceId: number) {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
process_identity: string | null;
|
||||||
|
}>(
|
||||||
|
'SELECT process_identity FROM CronTriggers WHERE instance_id=$instanceId',
|
||||||
|
{ bind: { instanceId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return row?.process_identity;
|
||||||
|
}
|
||||||
|
|
||||||
|
async requestInstanceStop(
|
||||||
|
instanceId: number,
|
||||||
|
pid: number,
|
||||||
|
signalTree: () => void | Error,
|
||||||
|
targets?: string[],
|
||||||
|
) {
|
||||||
|
// Commit the verified tree BEFORE the first signal. If this worker dies even
|
||||||
|
// inside the following transaction, its replacement still has the original PIDs.
|
||||||
|
if (targets)
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,targets)
|
||||||
|
SELECT i.id,i.cron_id,i.pid,$targets FROM RunningInstances i WHERE i.id=$instanceId AND i.pid=$pid AND i.status=0
|
||||||
|
ON CONFLICT(instance_id) DO UPDATE SET targets=(
|
||||||
|
SELECT json_group_array(value) FROM (SELECT value FROM json_each(CronStopRequests.targets)
|
||||||
|
UNION SELECT value FROM json_each(excluded.targets))) WHERE CronStopRequests.signalled=0`,
|
||||||
|
{ bind: { instanceId, pid, targets: JSON.stringify(targets) } },
|
||||||
|
);
|
||||||
|
const result = await this.database.transaction(
|
||||||
|
{ type: Transaction.TYPES.IMMEDIATE },
|
||||||
|
async (transaction) => {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
id: string | null;
|
||||||
|
pid: number;
|
||||||
|
status: number;
|
||||||
|
state: TriggerState | null;
|
||||||
|
stop_requested: number | null;
|
||||||
|
}>(
|
||||||
|
`SELECT t.id,i.pid,i.status,t.state,t.stop_requested FROM RunningInstances i
|
||||||
|
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.id=$instanceId`,
|
||||||
|
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!row ||
|
||||||
|
row.status !== 0 ||
|
||||||
|
(row.state && row.state !== 'running')
|
||||||
|
) {
|
||||||
|
throw Object.assign(new Error('Instance already ended'), {
|
||||||
|
code: 'ESRCH',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (row.pid !== pid)
|
||||||
|
throw Object.assign(new Error('Instance process changed'), {
|
||||||
|
status: 409,
|
||||||
|
});
|
||||||
|
if (row.stop_requested && !targets) return;
|
||||||
|
const existing = await this.pendingStop(instanceId, transaction);
|
||||||
|
const savedTargets: string[] = existing?.targets
|
||||||
|
? JSON.parse(existing.targets)
|
||||||
|
: [];
|
||||||
|
if (existing?.signalled)
|
||||||
|
return { targets: savedTargets, signalledAt: existing.signalled_at };
|
||||||
|
// The supervisor can still be draining output after the command has exited.
|
||||||
|
if (row.id) {
|
||||||
|
const exit = await this.evidence.exitBeforeStop(row.id);
|
||||||
|
// An I/O error alone cannot prove a live process has already exited.
|
||||||
|
if (!exit.published && exit.unreadable)
|
||||||
|
throw Object.assign(
|
||||||
|
new Error('Cannot verify command exit. Retry the stop request.'),
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
if (exit.published) {
|
||||||
|
await this.evidence.completeCommandExit(
|
||||||
|
row.id,
|
||||||
|
'unknown',
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
transaction,
|
||||||
|
exit.canonical,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
exit.recovered,
|
||||||
|
);
|
||||||
|
return { ended: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targets && !existing?.targets) {
|
||||||
|
// Another worker released the prepared tree. Retry from a durable
|
||||||
|
// snapshot before issuing an irreversible signal.
|
||||||
|
throw Object.assign(
|
||||||
|
new Error('Stop target snapshot changed. Retry the stop request.'),
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const signalledAt = Date.now();
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronStopRequests SET signalled=1,signalled_at=$signalledAt WHERE instance_id=$instanceId',
|
||||||
|
{ transaction, bind: { instanceId, signalledAt } },
|
||||||
|
);
|
||||||
|
if (row.state)
|
||||||
|
await this.database.query(
|
||||||
|
"UPDATE CronTriggers SET stop_requested=1 WHERE instance_id=$instanceId AND state='running'",
|
||||||
|
{ bind: { instanceId }, transaction },
|
||||||
|
);
|
||||||
|
// Root delivery failure rolls back. After successful root delivery, retain
|
||||||
|
// the stop marker even if some descendants still need recovery.
|
||||||
|
const error = signalTree();
|
||||||
|
return { targets: savedTargets, signalledAt, error };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (result && 'ended' in result)
|
||||||
|
throw Object.assign(new Error('Instance already ended'), {
|
||||||
|
code: 'ESRCH',
|
||||||
|
});
|
||||||
|
if (result && 'error' in result && result.error instanceof Error)
|
||||||
|
throw result.error;
|
||||||
|
if (targets && result)
|
||||||
|
return { targets: result.targets, signalledAt: result.signalledAt };
|
||||||
|
}
|
||||||
|
|
||||||
|
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
|
||||||
|
const [row] = await this.database.query<{ stop_requested: number | null }>(
|
||||||
|
'SELECT stop_requested FROM CronTriggers WHERE instance_id=$instanceId',
|
||||||
|
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return row && Boolean(row.stop_requested);
|
||||||
|
}
|
||||||
|
|
||||||
|
async stopVerifiedInstance(
|
||||||
|
instanceId: number,
|
||||||
|
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
|
||||||
|
) {
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
id: string;
|
||||||
|
owner: string | null;
|
||||||
|
command_identity: string | null;
|
||||||
|
reason: string | null;
|
||||||
|
state: TriggerState;
|
||||||
|
stop_exit_at: number | null;
|
||||||
|
exit_code: number | null;
|
||||||
|
exit_pending: number | null;
|
||||||
|
}>(
|
||||||
|
'SELECT id,owner,command_identity,reason,state,stop_exit_at,exit_code,exit_pending FROM CronTriggers WHERE instance_id=$instanceId',
|
||||||
|
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId',
|
||||||
|
{ transaction, bind: { instanceId } },
|
||||||
|
);
|
||||||
|
if (!row) return settleLegacy ? settleLegacy(transaction) : false;
|
||||||
|
if (row.state !== 'running') return row.state === 'stopped';
|
||||||
|
const legacyCrond =
|
||||||
|
row.owner?.startsWith('crond:') &&
|
||||||
|
(!row.command_identity || row.owner === row.command_identity);
|
||||||
|
// A live scheduler drains its log and reports the actual exit. If the
|
||||||
|
// callback already arrived or its owner is gone, settle in this transaction.
|
||||||
|
const exit = await this.evidence.exitBeforeStop(row.id);
|
||||||
|
if (
|
||||||
|
exit.published ||
|
||||||
|
exit.unreadable ||
|
||||||
|
row.exit_pending ||
|
||||||
|
row.stop_exit_at !== null ||
|
||||||
|
!row.owner ||
|
||||||
|
legacyCrond ||
|
||||||
|
row.reason === 'restart'
|
||||||
|
) {
|
||||||
|
await this.evidence.recoverScriptSample(row.id, transaction);
|
||||||
|
await this.evidence.completeCommandExit(
|
||||||
|
row.id,
|
||||||
|
'stopped',
|
||||||
|
'cancelled',
|
||||||
|
row.exit_code,
|
||||||
|
transaction,
|
||||||
|
exit.canonical,
|
||||||
|
row.stop_exit_at ?? undefined,
|
||||||
|
undefined,
|
||||||
|
exit.recovered,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async queueCounts() {
|
||||||
|
await this.recoverSystemOwners();
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
triggers: number;
|
||||||
|
tasks: number;
|
||||||
|
}>(
|
||||||
|
"SELECT COUNT(*) AS triggers, COUNT(DISTINCT cron_id) AS tasks FROM CronTriggers WHERE state='queued' AND dequeued_at IS NULL",
|
||||||
|
{ type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
async startSystem(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
owner: string,
|
||||||
|
commandIdentity = owner,
|
||||||
|
wrapper?: { rule: string; at: number; dispatch?: number },
|
||||||
|
) {
|
||||||
|
// crond only tells us when the wrapper starts. It supplies no scheduled or queued time.
|
||||||
|
return this.database.transaction(async (transaction) => {
|
||||||
|
const [task] = await this.database.query<{
|
||||||
|
allow_multiple_instances: number;
|
||||||
|
status: number;
|
||||||
|
pid: number | null;
|
||||||
|
isDisabled: number;
|
||||||
|
}>(
|
||||||
|
'SELECT allow_multiple_instances, status, pid, isDisabled FROM Crontabs WHERE id=$cronId',
|
||||||
|
{ bind: { cronId }, type: QueryTypes.SELECT, transaction },
|
||||||
|
);
|
||||||
|
if (!task || (task.isDisabled && !wrapper?.dispatch)) return false;
|
||||||
|
const now = Date.now();
|
||||||
|
const inserted = await this.database.query(
|
||||||
|
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,command_identity,observed_at,system_rule,system_dispatch_at)
|
||||||
|
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch) ON CONFLICT(id) DO NOTHING`,
|
||||||
|
{
|
||||||
|
bind: {
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
owner,
|
||||||
|
commandIdentity,
|
||||||
|
observed: wrapper?.at ?? now,
|
||||||
|
rule: wrapper?.rule ?? null,
|
||||||
|
dispatch: wrapper?.dispatch ?? null,
|
||||||
|
},
|
||||||
|
type: QueryTypes.BULKUPDATE,
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!inserted) return false;
|
||||||
|
if (task.isDisabled) {
|
||||||
|
await this.finish(id, 'skipped', 'changed', null, transaction);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const multiple = task.allow_multiple_instances === 1;
|
||||||
|
const claimed =
|
||||||
|
(multiple || !hasLiveCronProcess(task.status, task.pid)) &&
|
||||||
|
(await this.start(id, now, multiple, transaction));
|
||||||
|
if (claimed && wrapper)
|
||||||
|
await this.database.query(
|
||||||
|
'UPDATE CronTriggers SET command_started_at=$now WHERE id=$id',
|
||||||
|
{ transaction, bind: { id, now } },
|
||||||
|
);
|
||||||
|
if (claimed && owner.startsWith('crond:')) {
|
||||||
|
await this.registerCommandInstance(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
Number(commandIdentity.split(':')[1]),
|
||||||
|
commandIdentity,
|
||||||
|
now,
|
||||||
|
undefined,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!claimed)
|
||||||
|
await this.finish(id, 'skipped', 'overlap', null, transaction);
|
||||||
|
return claimed;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async recoverSystemOwners(
|
||||||
|
cronId?: number,
|
||||||
|
transaction?: Transaction,
|
||||||
|
instanceId?: number,
|
||||||
|
) {
|
||||||
|
// HTTP may restart while crond children keep running. Match process birth, including across reboots.
|
||||||
|
const active = await this.database.query<{ id: string; owner: string }>(
|
||||||
|
`SELECT id,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE state='running' AND (owner LIKE 'crond:%' OR reason='restart')
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)
|
||||||
|
AND ($cronId IS NULL OR cron_id=$cronId) AND ($instanceId IS NULL OR instance_id=$instanceId)`,
|
||||||
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { cronId: cronId ?? null, instanceId: instanceId ?? null },
|
||||||
|
type: QueryTypes.SELECT,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let reclaimed = false;
|
||||||
|
for (const row of active) {
|
||||||
|
const pid = Number(row.owner.split(':')[1]);
|
||||||
|
try {
|
||||||
|
if (systemOwner(pid) === row.owner) continue;
|
||||||
|
} catch (error) {
|
||||||
|
const code = (error as NodeJS.ErrnoException).code;
|
||||||
|
if (code !== 'ENOENT' && code !== 'ESRCH') throw error;
|
||||||
|
}
|
||||||
|
const close = async (tx: Transaction) => {
|
||||||
|
const [current] = await this.database.query<{
|
||||||
|
stop_requested: number;
|
||||||
|
exit_code: number | null;
|
||||||
|
stop_exit_at: number | null;
|
||||||
|
}>(
|
||||||
|
`SELECT stop_requested,exit_code,stop_exit_at FROM CronTriggers WHERE id=$id AND state='running'
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)`,
|
||||||
|
{ transaction: tx, bind: { id: row.id }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!current) return;
|
||||||
|
await this.evidence.recoverScriptSample(row.id, tx);
|
||||||
|
await this.evidence.completeCommandExit(
|
||||||
|
row.id,
|
||||||
|
current.stop_requested ? 'stopped' : 'unknown',
|
||||||
|
current.stop_requested ? 'cancelled' : 'restart',
|
||||||
|
current.exit_code,
|
||||||
|
tx,
|
||||||
|
undefined,
|
||||||
|
current.stop_exit_at ?? undefined,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
if (transaction) await close(transaction);
|
||||||
|
else await this.database.transaction(close);
|
||||||
|
reclaimed = true;
|
||||||
|
}
|
||||||
|
return reclaimed;
|
||||||
|
}
|
||||||
|
|
||||||
|
async interrupt(owner: string) {
|
||||||
|
await this.database.transaction(async (transaction) => {
|
||||||
|
await this.evidence.replayPublishedExits(transaction);
|
||||||
|
if (owner === 'http')
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT OR IGNORE INTO CronStopRequests(instance_id,cron_id,pid)
|
||||||
|
SELECT instance_id,cron_id,CAST(substr(process_identity,7) AS INTEGER) FROM CronTriggers
|
||||||
|
WHERE state='running' AND stop_requested=1 AND instance_id IS NOT NULL AND process_identity LIKE 'crond:%'`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
// No process was bound and its launch gate closed when the worker exited.
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET state='stopped',reason='cancelled',started_at=NULL,finished_at=$now
|
||||||
|
WHERE owner=$owner AND state='running' AND stop_requested=1 AND instance_id IS NULL AND command_identity IS NULL`,
|
||||||
|
{ transaction, bind: { owner, now: Date.now() } },
|
||||||
|
);
|
||||||
|
await this.database.query(
|
||||||
|
`UPDATE CronTriggers SET reason='restart',
|
||||||
|
state=CASE WHEN state='queued' THEN 'skipped' WHEN COALESCE(command_identity,process_identity) IS NOT NULL THEN 'running' ELSE 'unknown' END,
|
||||||
|
finished_at=CASE WHEN state='running' AND COALESCE(command_identity,process_identity) IS NOT NULL THEN NULL ELSE $now END
|
||||||
|
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')`,
|
||||||
|
{ transaction, bind: { owner, now: Date.now() } },
|
||||||
|
);
|
||||||
|
await this.recoverSystemOwners(undefined, transaction);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
import { LegacyClientAdapter } from './compatibility/legacyClient';
|
||||||
|
import type { readExit } from './settlement/exitReceipt.cjs';
|
||||||
|
export { slotId } from './identity';
|
||||||
|
import type { Crontab } from '../data/cron';
|
||||||
|
export { systemOwner } from './execution/cronProcess';
|
||||||
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
|
import type {
|
||||||
|
TriggerSource,
|
||||||
|
TriggerState,
|
||||||
|
VerifiedSupervisorExit,
|
||||||
|
} from './types';
|
||||||
|
import { TriggerLifecycle } from './execution/triggerLifecycle';
|
||||||
|
import { TriggerSettlement } from './settlement/triggerSettlement';
|
||||||
|
export type { Trigger, TriggerSource, TriggerState } from './types';
|
||||||
|
import { TriggerQueries } from './queries/triggerQueries';
|
||||||
|
|
||||||
|
export { installTriggerHistory } from './schema';
|
||||||
|
|
||||||
|
export class TriggerHistory {
|
||||||
|
constructor(private database: Sequelize) {}
|
||||||
|
|
||||||
|
// Compatibility callers share the same lifecycle and settlement transaction paths.
|
||||||
|
private readonly settlement: TriggerSettlement = new TriggerSettlement(
|
||||||
|
this.database,
|
||||||
|
{
|
||||||
|
finish: (...args) => this.finish(...args),
|
||||||
|
shouldStop: (id, transaction) => this.shouldStop(id, transaction),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
private readonly lifecycle: TriggerLifecycle = new TriggerLifecycle(
|
||||||
|
this.database,
|
||||||
|
{
|
||||||
|
exitBeforeStop: (id) => this.exitBeforeStop(id),
|
||||||
|
completeCommandExit: (...args) => this.completeCommandExit(...args),
|
||||||
|
recoverScriptSample: (id, transaction) =>
|
||||||
|
this.recoverScriptSample(id, transaction),
|
||||||
|
replayPublishedExits: (transaction) =>
|
||||||
|
this.replayPublishedExits(transaction),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
private readonly clients: LegacyClientAdapter = new LegacyClientAdapter(
|
||||||
|
this.database,
|
||||||
|
this.lifecycle,
|
||||||
|
this.settlement,
|
||||||
|
);
|
||||||
|
|
||||||
|
// No command or instance exists before the scheduler claims the trigger.
|
||||||
|
// A cancelled or already claimed row must keep the outcome recorded by its owner.
|
||||||
|
async skipQueued(id: string, reason: string, finishedAt: number) {
|
||||||
|
return this.lifecycle.skipQueued(id, reason, finishedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
async enqueue(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
source: TriggerSource,
|
||||||
|
scheduledAt: number | null,
|
||||||
|
now = Date.now(),
|
||||||
|
transaction?: Transaction,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.enqueue(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
source,
|
||||||
|
scheduledAt,
|
||||||
|
now,
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize admission with the receipt so simultaneous timers and recovered
|
||||||
|
// workers agree on which scheduled run owns the slot. Edits invalidate old waits.
|
||||||
|
async enqueueUnlessPending(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
source: 'node' | 'recovery',
|
||||||
|
scheduledAt: number,
|
||||||
|
now: number,
|
||||||
|
revision = 0,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.enqueueUnlessPending(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
source,
|
||||||
|
scheduledAt,
|
||||||
|
now,
|
||||||
|
revision,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(
|
||||||
|
id: string,
|
||||||
|
now = Date.now(),
|
||||||
|
multiple = false,
|
||||||
|
transaction?: Transaction,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.start(id, now, multiple, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async claimManual(
|
||||||
|
id: string,
|
||||||
|
snapshot: Crontab,
|
||||||
|
token: string,
|
||||||
|
independent: boolean,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.claimManual(id, snapshot, token, independent);
|
||||||
|
}
|
||||||
|
|
||||||
|
async finish(
|
||||||
|
id: string,
|
||||||
|
state: TriggerState,
|
||||||
|
reason: string | null = null,
|
||||||
|
code: number | null = null,
|
||||||
|
transaction?: Transaction,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.finish(
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
reason,
|
||||||
|
code,
|
||||||
|
transaction,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A child close is an independent receipt when either Shell callback is lost.
|
||||||
|
async complete(
|
||||||
|
id: string,
|
||||||
|
state: TriggerState,
|
||||||
|
reason: string | null,
|
||||||
|
code: number | null,
|
||||||
|
finishedAt?: number,
|
||||||
|
report?: VerifiedSupervisorExit | 'legacy',
|
||||||
|
) {
|
||||||
|
return this.settlement.complete(
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
reason,
|
||||||
|
code,
|
||||||
|
finishedAt,
|
||||||
|
report,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async completeCommandExit(
|
||||||
|
id: string,
|
||||||
|
state: TriggerState,
|
||||||
|
reason: string | null,
|
||||||
|
code: number | null,
|
||||||
|
transaction: Transaction,
|
||||||
|
receipt?: Awaited<ReturnType<typeof readExit>>,
|
||||||
|
finishedAt?: number,
|
||||||
|
report?: VerifiedSupervisorExit | 'legacy',
|
||||||
|
recoveredCopies?: Awaited<ReturnType<typeof readExit>>[],
|
||||||
|
) {
|
||||||
|
return this.settlement.completeCommandExit(
|
||||||
|
id,
|
||||||
|
state,
|
||||||
|
reason,
|
||||||
|
code,
|
||||||
|
transaction,
|
||||||
|
receipt,
|
||||||
|
finishedAt,
|
||||||
|
report,
|
||||||
|
recoveredCopies,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async retryPendingExits() {
|
||||||
|
return this.settlement.retryPendingExits();
|
||||||
|
}
|
||||||
|
|
||||||
|
async replayPublishedExits(transaction: Transaction) {
|
||||||
|
return this.settlement.replayPublishedExits(transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old shell-only executions publish status and statistics independently.
|
||||||
|
// Either final receipt can settle that execution if the other was lost.
|
||||||
|
async recordShellResult(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
code: number,
|
||||||
|
elapsedMs: number,
|
||||||
|
now: number,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
return this.clients.recordShellResult(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
code,
|
||||||
|
elapsedMs,
|
||||||
|
now,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async recoverScriptSample(id: string, transaction: Transaction) {
|
||||||
|
return this.settlement.recoverScriptSample(id, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async isRunning(cronId: number, transaction: Transaction) {
|
||||||
|
return this.lifecycle.isRunning(cronId, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async shellReport(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
system: boolean,
|
||||||
|
running: boolean,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
exitCode?: number,
|
||||||
|
stopped = false,
|
||||||
|
transaction?: Transaction,
|
||||||
|
elapsedMs?: number,
|
||||||
|
finishedAt?: number,
|
||||||
|
): Promise<void | false> {
|
||||||
|
return this.clients.shellReport(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
system,
|
||||||
|
running,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
exitCode,
|
||||||
|
stopped,
|
||||||
|
transaction,
|
||||||
|
elapsedMs,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async reportLegacy(
|
||||||
|
cronId: number,
|
||||||
|
running: boolean,
|
||||||
|
pid: number,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
elapsed: number,
|
||||||
|
code?: number,
|
||||||
|
) {
|
||||||
|
return this.clients.reportLegacy(
|
||||||
|
cronId,
|
||||||
|
running,
|
||||||
|
pid,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
elapsed,
|
||||||
|
code,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link the Shell instance and its trigger in the same IMMEDIATE write transaction.
|
||||||
|
async reportInstance(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
running: boolean,
|
||||||
|
pid: number,
|
||||||
|
log: string,
|
||||||
|
seconds: number,
|
||||||
|
elapsed: number | undefined,
|
||||||
|
code?: number,
|
||||||
|
stopped = false,
|
||||||
|
finishedAt?: number,
|
||||||
|
) {
|
||||||
|
return this.clients.reportInstance(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
running,
|
||||||
|
pid,
|
||||||
|
log,
|
||||||
|
seconds,
|
||||||
|
elapsed,
|
||||||
|
code,
|
||||||
|
stopped,
|
||||||
|
finishedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelQueued(ids: number[]) {
|
||||||
|
return this.lifecycle.cancelQueued(ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
|
||||||
|
return this.lifecycle.cancelQueuedInTransaction(ids, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async queueInstanceStop(
|
||||||
|
instanceId: number,
|
||||||
|
cronId: number,
|
||||||
|
pid: number,
|
||||||
|
transaction?: Transaction,
|
||||||
|
identity?: string,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.queueInstanceStop(
|
||||||
|
instanceId,
|
||||||
|
cronId,
|
||||||
|
pid,
|
||||||
|
transaction,
|
||||||
|
identity,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStop(instanceId: number, transaction?: Transaction) {
|
||||||
|
return this.lifecycle.pendingStop(instanceId, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStopBatches() {
|
||||||
|
return this.lifecycle.pendingStopBatches();
|
||||||
|
}
|
||||||
|
|
||||||
|
async pendingStops() {
|
||||||
|
return this.lifecycle.pendingStops();
|
||||||
|
}
|
||||||
|
|
||||||
|
async forgetStop(
|
||||||
|
instanceId: number,
|
||||||
|
onEnded?: (tx: Transaction) => Promise<void>,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.forgetStop(instanceId, onEnded);
|
||||||
|
}
|
||||||
|
|
||||||
|
async shouldStop(id: string, transaction?: Transaction) {
|
||||||
|
return this.lifecycle.shouldStop(id, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The outer command can outlive any of its task wrappers.
|
||||||
|
async recordCommandStart(id: string, at: number) {
|
||||||
|
return this.lifecycle.recordCommandStart(id, at);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bindCommand(id: string, pid: number, log?: string) {
|
||||||
|
return this.lifecycle.bindCommand(id, pid, log);
|
||||||
|
}
|
||||||
|
|
||||||
|
async activeCommands(ids: number[], transaction?: Transaction) {
|
||||||
|
return this.lifecycle.activeCommands(ids, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async instanceIdentity(instanceId: number) {
|
||||||
|
return this.lifecycle.instanceIdentity(instanceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async requestInstanceStop(
|
||||||
|
instanceId: number,
|
||||||
|
pid: number,
|
||||||
|
signalTree: () => void | Error,
|
||||||
|
targets?: string[],
|
||||||
|
) {
|
||||||
|
return this.lifecycle.requestInstanceStop(
|
||||||
|
instanceId,
|
||||||
|
pid,
|
||||||
|
signalTree,
|
||||||
|
targets,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async exitBeforeStop(id: string) {
|
||||||
|
return this.settlement.exitBeforeStop(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
|
||||||
|
return this.lifecycle.instanceStopRequested(instanceId, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
async stopVerifiedInstance(
|
||||||
|
instanceId: number,
|
||||||
|
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.stopVerifiedInstance(instanceId, settleLegacy);
|
||||||
|
}
|
||||||
|
|
||||||
|
async queueCounts() {
|
||||||
|
return this.lifecycle.queueCounts();
|
||||||
|
}
|
||||||
|
|
||||||
|
async startSystem(
|
||||||
|
id: string,
|
||||||
|
cronId: number,
|
||||||
|
owner: string,
|
||||||
|
commandIdentity = owner,
|
||||||
|
wrapper?: { rule: string; at: number; dispatch?: number },
|
||||||
|
) {
|
||||||
|
return this.lifecycle.startSystem(
|
||||||
|
id,
|
||||||
|
cronId,
|
||||||
|
owner,
|
||||||
|
commandIdentity,
|
||||||
|
wrapper,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async recoverSystemOwners(
|
||||||
|
cronId?: number,
|
||||||
|
transaction?: Transaction,
|
||||||
|
instanceId?: number,
|
||||||
|
) {
|
||||||
|
return this.lifecycle.recoverSystemOwners(cronId, transaction, instanceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async interrupt(owner: string) {
|
||||||
|
return this.lifecycle.interrupt(owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
async reconcileInstances() {
|
||||||
|
return this.clients.reconcileInstances();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static expired = `state NOT IN ('queued','running') AND exit_pending IS NOT 1 AND finished_at IS NOT NULL AND observed_at < $cutoff AND finished_at < $cutoff
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.id=CronTriggers.instance_id AND i.status=0)`;
|
||||||
|
|
||||||
|
async countExpired(cutoff: number) {
|
||||||
|
const [row] = await this.database.query<{ count: number }>(
|
||||||
|
`SELECT COUNT(*) AS count FROM CronTriggers WHERE ${TriggerHistory.expired}`,
|
||||||
|
{ bind: { cutoff }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return row.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteExpired(cutoff: number, transaction: Transaction) {
|
||||||
|
// Once both histories have expired, old packets must not recreate their rows.
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT INTO CronHistoryRetention(id,cutoff) VALUES (1,$cutoff)
|
||||||
|
ON CONFLICT(id) DO UPDATE SET cutoff=MAX(cutoff,excluded.cutoff)`,
|
||||||
|
{ transaction, bind: { cutoff } },
|
||||||
|
);
|
||||||
|
// The visible histories can expire before statistics. Keep just enough to
|
||||||
|
// credit a verified receipt to its task without recreating either history.
|
||||||
|
await this.database.query(
|
||||||
|
`INSERT OR IGNORE INTO CronPrunedUnknownRuns(trigger_id,cron_id,source,started_at,last_possible_day)
|
||||||
|
SELECT id,cron_id,source,started_at,date(finished_at/1000,'unixepoch','localtime') FROM CronTriggers
|
||||||
|
WHERE ${TriggerHistory.expired} AND state='unknown' AND reason='restart' AND counted=0 AND owner IS NOT NULL
|
||||||
|
AND started_at IS NOT NULL AND EXISTS (SELECT 1 FROM Crontabs WHERE id=CronTriggers.cron_id)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=CronTriggers.id)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE first_day>date(finished_at/1000,'unixepoch','localtime'))`,
|
||||||
|
{ bind: { cutoff }, transaction },
|
||||||
|
);
|
||||||
|
return this.database.query(
|
||||||
|
`DELETE FROM CronTriggers WHERE ${TriggerHistory.expired}`,
|
||||||
|
{ bind: { cutoff }, transaction, type: QueryTypes.BULKDELETE },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compatibility entry points for existing scheduler, API and extension callers.
|
||||||
|
async visibleTriggers(cronId: number, ids: string[]) {
|
||||||
|
return new TriggerQueries(this.database).visibleTriggers(cronId, ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
async recent(
|
||||||
|
cronId: number,
|
||||||
|
offset: number,
|
||||||
|
limit = 25,
|
||||||
|
before?: { time: number; id: string },
|
||||||
|
) {
|
||||||
|
return new TriggerQueries(this.database).recent(
|
||||||
|
cronId,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
before,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async metrics(since: number) {
|
||||||
|
return new TriggerQueries(this.database).metrics(since);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function triggerHistory(): TriggerHistory {
|
||||||
|
return new TriggerHistory(require('../data/index').sequelize);
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
import { createHash } from 'crypto';
|
||||||
|
|
||||||
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
|
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
|
||||||
export const executionIdPattern = /^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
export const executionIdPattern =
|
||||||
|
/^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
||||||
export function executionTriggerId(id: string) {
|
export function executionTriggerId(id: string) {
|
||||||
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
|
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
|
||||||
}
|
}
|
||||||
@@ -11,3 +14,15 @@ export function receiptFinishTime(header?: string) {
|
|||||||
if (time > 0 && time <= Date.now()) return time;
|
if (time > 0 && time <= Date.now()) return time;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A scheduled slot keeps the same identity across retries and diagnostics.
|
||||||
|
export function slotId(
|
||||||
|
task: string,
|
||||||
|
ruleIndex: number,
|
||||||
|
rule: string,
|
||||||
|
time: number,
|
||||||
|
) {
|
||||||
|
return createHash('sha256')
|
||||||
|
.update(JSON.stringify([task, ruleIndex, rule, time]))
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import { FindOptions } from 'sequelize';
|
||||||
|
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
|
||||||
|
import {
|
||||||
|
RunningInstanceModel,
|
||||||
|
InstanceStatus,
|
||||||
|
} from '../../data/runningInstance';
|
||||||
|
import config from '../../config/index';
|
||||||
|
import { fileExist } from '../../shared/utils';
|
||||||
|
import fs from 'fs/promises';
|
||||||
|
import path from 'path';
|
||||||
|
import { logAttributes } from './cronViews';
|
||||||
|
import { TriggerQueries } from './triggerQueries';
|
||||||
|
import { resolveLogPath } from '../../shared/logPath';
|
||||||
|
import { LogChunk, LogReadOptions, readLogChunk } from '../../shared/logReader';
|
||||||
|
import { t } from '../../shared/i18n';
|
||||||
|
|
||||||
|
export type CronLogOptions = LogReadOptions & {
|
||||||
|
previousPath?: string;
|
||||||
|
triggerId?: string;
|
||||||
|
instanceId?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CronLogResult = LogChunk & {
|
||||||
|
status: string;
|
||||||
|
logPath?: string;
|
||||||
|
triggerId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The caller supplies its existing task lookup so missing-task behavior stays
|
||||||
|
// compatible. Trigger and instance reads are scoped to the requested task.
|
||||||
|
export class CronLogReader {
|
||||||
|
constructor(
|
||||||
|
private loadCron: (
|
||||||
|
id: number,
|
||||||
|
attributes?: FindOptions['attributes'],
|
||||||
|
) => Promise<Crontab>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async log(
|
||||||
|
id: number,
|
||||||
|
options: CronLogOptions = {},
|
||||||
|
): Promise<CronLogResult> {
|
||||||
|
let doc: Pick<Crontab, 'status' | 'log_path' | 'log_name'> & {
|
||||||
|
logTriggerId?: string;
|
||||||
|
};
|
||||||
|
if (options.instanceId !== undefined) {
|
||||||
|
const instance = await RunningInstanceModel.findOne({
|
||||||
|
where: { id: options.instanceId, cron_id: id },
|
||||||
|
attributes: ['status', 'log_path'],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
doc = {
|
||||||
|
status:
|
||||||
|
instance?.status === InstanceStatus.running
|
||||||
|
? CrontabStatus.running
|
||||||
|
: CrontabStatus.idle,
|
||||||
|
log_path: instance?.log_path,
|
||||||
|
};
|
||||||
|
} else if (options.triggerId) {
|
||||||
|
const [trigger] = await new TriggerQueries(
|
||||||
|
CrontabModel.sequelize!,
|
||||||
|
).visibleTriggers(id, [options.triggerId]);
|
||||||
|
// A retained viewer must never fall back to a sibling if its receipt was removed.
|
||||||
|
doc = {
|
||||||
|
logTriggerId: options.triggerId,
|
||||||
|
log_path: trigger?.log_path ?? undefined,
|
||||||
|
status:
|
||||||
|
trigger?.state === 'running'
|
||||||
|
? CrontabStatus.running
|
||||||
|
: trigger?.state === 'queued'
|
||||||
|
? CrontabStatus.queued
|
||||||
|
: CrontabStatus.idle,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
doc = await this.loadCron(id, logAttributes);
|
||||||
|
}
|
||||||
|
const triggerId = doc.logTriggerId ?? undefined;
|
||||||
|
if (doc.log_name === '/dev/null' || doc.log_path === '/dev/null') {
|
||||||
|
return {
|
||||||
|
content: t('日志设置为忽略'),
|
||||||
|
status: 'ignored',
|
||||||
|
triggerId,
|
||||||
|
offset: 0,
|
||||||
|
nextOffset: 0,
|
||||||
|
total: 0,
|
||||||
|
truncated: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (typeof doc.status === 'number' && doc.status === CrontabStatus.queued) {
|
||||||
|
// The next run has reserved a slot but has not published its own path yet.
|
||||||
|
return {
|
||||||
|
triggerId,
|
||||||
|
content: '',
|
||||||
|
status: 'running',
|
||||||
|
offset: 0,
|
||||||
|
nextOffset: 0,
|
||||||
|
total: 0,
|
||||||
|
truncated: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const absolutePath = doc.log_path
|
||||||
|
? resolveLogPath(config.logPath, doc.log_path)
|
||||||
|
: '';
|
||||||
|
const logFileExist = doc.log_path && (await fileExist(absolutePath));
|
||||||
|
if (logFileExist) {
|
||||||
|
const changed =
|
||||||
|
options.previousPath !== undefined &&
|
||||||
|
options.previousPath !== doc.log_path;
|
||||||
|
const chunk = await readLogChunk(
|
||||||
|
absolutePath,
|
||||||
|
changed
|
||||||
|
? { ...options, cursor: undefined, offset: 0, tail: !options.follow }
|
||||||
|
: options,
|
||||||
|
);
|
||||||
|
const isRunning =
|
||||||
|
typeof doc.status === 'number' &&
|
||||||
|
[CrontabStatus.running, CrontabStatus.queued].includes(doc.status);
|
||||||
|
return {
|
||||||
|
...chunk,
|
||||||
|
triggerId,
|
||||||
|
logPath: doc.log_path,
|
||||||
|
status: isRunning ? 'running' : 'completed',
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const status =
|
||||||
|
typeof doc.status === 'number' &&
|
||||||
|
[CrontabStatus.queued, CrontabStatus.running].includes(doc.status)
|
||||||
|
? 'running'
|
||||||
|
: 'notFound';
|
||||||
|
return {
|
||||||
|
triggerId,
|
||||||
|
content: status === 'running' ? t('运行中...') : t('日志不存在...'),
|
||||||
|
status,
|
||||||
|
offset: 0,
|
||||||
|
nextOffset: 0,
|
||||||
|
total: 0,
|
||||||
|
truncated: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async logs(id: number) {
|
||||||
|
const doc = await this.loadCron(id);
|
||||||
|
if (!doc || !doc.log_path || doc.log_path === '/dev/null') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||||
|
const dir = path.dirname(resolveLogPath(config.logPath, doc.log_path));
|
||||||
|
const dirExist = await fileExist(dir);
|
||||||
|
if (dirExist) {
|
||||||
|
let files = await fs.readdir(dir);
|
||||||
|
return (
|
||||||
|
await Promise.all(
|
||||||
|
files.map(async (x) => ({
|
||||||
|
filename: x,
|
||||||
|
directory: relativeDir.replace(config.logPath, ''),
|
||||||
|
time: (await fs.lstat(`${dir}/${x}`)).birthtimeMs,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
).sort((a, b) => b.time - a.time);
|
||||||
|
} else {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { upcomingSlots } from './cronScheduler';
|
import { upcomingSlots } from '../scheduling/cronScheduler';
|
||||||
|
|
||||||
type Definition = {
|
type Definition = {
|
||||||
schedule?: string;
|
schedule?: string;
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { literal, FindOptions } from 'sequelize';
|
||||||
|
|
||||||
|
// Queue membership belongs to the trigger. Expose it for list/detail reads
|
||||||
|
// without writing it into the manual-run reservation used by the scheduler.
|
||||||
|
export const visibleStatus = literal(`CASE
|
||||||
|
WHEN EXISTS (SELECT 1 FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'running') THEN 0
|
||||||
|
WHEN "Crontab"."status" = 1 AND EXISTS (
|
||||||
|
SELECT 1 FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'queued'
|
||||||
|
) THEN 3
|
||||||
|
ELSE "Crontab"."status" END`);
|
||||||
|
export const visibleAttributes: FindOptions['attributes'] = {
|
||||||
|
exclude: ['status'],
|
||||||
|
include: [[visibleStatus, 'status']],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Resolve status and log ownership in one SQLite snapshot. A running trigger
|
||||||
|
// can be visible before its shell has published the file for this execution.
|
||||||
|
const activeLogTrigger = `FROM CronTriggers WHERE cron_id = "Crontab"."id"
|
||||||
|
AND state = 'running' ORDER BY started_at DESC, rowid DESC LIMIT 1`;
|
||||||
|
export const logAttributes: FindOptions['attributes'] = [
|
||||||
|
'log_name',
|
||||||
|
[visibleStatus, 'status'],
|
||||||
|
[
|
||||||
|
literal(`CASE WHEN EXISTS (SELECT 1 ${activeLogTrigger})
|
||||||
|
THEN (SELECT log_path ${activeLogTrigger}) ELSE "Crontab"."log_path" END`),
|
||||||
|
'log_path',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
literal(`CASE WHEN allow_multiple_instances = 1 THEN COALESCE(
|
||||||
|
(SELECT id ${activeLogTrigger}),
|
||||||
|
(SELECT id FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'queued'
|
||||||
|
ORDER BY observed_at DESC, rowid DESC LIMIT 1)
|
||||||
|
) END`),
|
||||||
|
'logTriggerId',
|
||||||
|
],
|
||||||
|
];
|
||||||
File renamed without changes.
@@ -23,7 +23,11 @@ export class AnomalyPage {
|
|||||||
private selected: ScheduleAnomaly[] = [];
|
private selected: ScheduleAnomaly[] = [];
|
||||||
static readonly size = 25;
|
static readonly size = 25;
|
||||||
|
|
||||||
constructor(readonly kind: AnomalyKind, private page: number, private previous?: string) {}
|
constructor(
|
||||||
|
readonly kind: AnomalyKind,
|
||||||
|
private page: number,
|
||||||
|
private previous?: string,
|
||||||
|
) {}
|
||||||
|
|
||||||
add(row: ScheduleAnomaly) {
|
add(row: ScheduleAnomaly) {
|
||||||
this.hash.update(JSON.stringify(row)).update('\n');
|
this.hash.update(JSON.stringify(row)).update('\n');
|
||||||
@@ -36,7 +40,13 @@ export class AnomalyPage {
|
|||||||
const revision = this.hash.digest('hex');
|
const revision = this.hash.digest('hex');
|
||||||
const changed = !!this.previous && revision !== this.previous;
|
const changed = !!this.previous && revision !== this.previous;
|
||||||
const reset = changed || (this.page > 1 && !this.selected.length);
|
const reset = changed || (this.page > 1 && !this.selected.length);
|
||||||
return { rows: reset ? this.first : this.selected, total: this.total,
|
return {
|
||||||
page: reset ? 1 : this.page, pageSize: AnomalyPage.size, revision, changed };
|
rows: reset ? this.first : this.selected,
|
||||||
|
total: this.total,
|
||||||
|
page: reset ? 1 : this.page,
|
||||||
|
pageSize: AnomalyPage.size,
|
||||||
|
revision,
|
||||||
|
changed,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { QueryTypes, Sequelize } from 'sequelize';
|
||||||
|
import type { Trigger } from '../types';
|
||||||
|
import { auditSchedule } from '../scheduling/scheduleAudit';
|
||||||
|
import { systemScheduleAudit } from '../scheduling/systemScheduleAudit';
|
||||||
|
|
||||||
|
// Keep uncertain exits unresolved in every history view. These projections
|
||||||
|
// describe evidence; they never settle a run or book statistics.
|
||||||
|
const historyColumns = `id,cron_id,source,state,queue_context,queue_live_context,dequeued_at,scheduled_at,queued_at,started_at,command_started_at,script_started_at,
|
||||||
|
CASE WHEN exit_pending=1 OR (state='unknown' AND reason='restart') THEN NULL ELSE finished_at END AS finished_at,
|
||||||
|
CASE WHEN exit_pending=1 THEN CASE WHEN EXISTS (SELECT 1 FROM CronExitObservations
|
||||||
|
WHERE trigger_id=CronTriggers.id LIMIT 1 OFFSET 1) OR EXISTS (SELECT 1 FROM CronBoundExitConflicts
|
||||||
|
WHERE trigger_id=CronTriggers.id) THEN 'exit_conflict' ELSE 'exit_pending' END ELSE reason END AS reason,
|
||||||
|
EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=CronTriggers.id) AS legacy_exit_booking,
|
||||||
|
CASE WHEN exit_pending=1 OR (state='unknown' AND reason='restart') THEN NULL ELSE exit_code END AS exit_code,log_path,observed_at`;
|
||||||
|
|
||||||
|
// Read-only execution history and diagnostics, independent of lifecycle writes.
|
||||||
|
export class TriggerQueries {
|
||||||
|
constructor(private database: Sequelize) {}
|
||||||
|
|
||||||
|
async visibleTriggers(cronId: number, ids: string[]) {
|
||||||
|
return this.database.query<Trigger & { observed_at: number }>(
|
||||||
|
`SELECT ${historyColumns} FROM CronTriggers WHERE cron_id=:cronId AND id IN (:ids)`,
|
||||||
|
{ replacements: { cronId, ids }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async recent(
|
||||||
|
cronId: number,
|
||||||
|
offset: number,
|
||||||
|
limit = 25,
|
||||||
|
before?: { time: number; id: string },
|
||||||
|
) {
|
||||||
|
return this.database.query<Trigger & { observed_at: number }>(
|
||||||
|
`SELECT ${historyColumns}
|
||||||
|
FROM CronTriggers WHERE cron_id=$cronId
|
||||||
|
${before ? 'AND (observed_at,id) < ($time,$id)' : ''}
|
||||||
|
ORDER BY observed_at DESC,id DESC LIMIT $limit OFFSET $offset`,
|
||||||
|
{ bind: { cronId, offset, limit, ...before }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async metrics(since: number) {
|
||||||
|
const [row] = await this.database.query<{
|
||||||
|
observed: number;
|
||||||
|
skipped: number;
|
||||||
|
samples: number;
|
||||||
|
waitP95: number | null;
|
||||||
|
onTime: number;
|
||||||
|
planned: number;
|
||||||
|
triggerOnTime: number;
|
||||||
|
triggerDeviationP95: number | null;
|
||||||
|
scriptSamples: number;
|
||||||
|
scriptStartP95: number | null;
|
||||||
|
scriptOnTime: number;
|
||||||
|
}>(
|
||||||
|
`WITH today AS (SELECT * FROM CronTriggers WHERE observed_at >= $since),
|
||||||
|
triggers AS (SELECT ABS(observed_at - scheduled_at) AS deviation FROM today WHERE scheduled_at IS NOT NULL),
|
||||||
|
scripts AS (SELECT script_started_at - scheduled_at AS delay FROM today
|
||||||
|
WHERE scheduled_at IS NOT NULL AND script_started_at >= scheduled_at),
|
||||||
|
waits AS (SELECT COALESCE(dequeued_at,started_at) - queued_at AS delay FROM today WHERE COALESCE(dequeued_at,started_at) >= queued_at)
|
||||||
|
SELECT COUNT(*) AS observed, COUNT(CASE WHEN state='skipped' THEN 1 END) AS skipped,
|
||||||
|
COUNT(scheduled_at) AS planned, COUNT(CASE WHEN started_at <= scheduled_at + 5000 THEN 1 END) AS onTime,
|
||||||
|
(SELECT COUNT(*) FROM triggers WHERE deviation <= 5000) AS triggerOnTime,
|
||||||
|
(SELECT deviation FROM triggers ORDER BY deviation LIMIT 1 OFFSET (SELECT MAX(0,(95*COUNT(*)+99)/100-1) FROM triggers)) AS triggerDeviationP95,
|
||||||
|
(SELECT COUNT(*) FROM scripts) AS scriptSamples,
|
||||||
|
(SELECT COUNT(*) FROM scripts WHERE delay <= 5000) AS scriptOnTime,
|
||||||
|
(SELECT delay FROM scripts ORDER BY delay LIMIT 1 OFFSET (SELECT MAX(0,(95*COUNT(*)+99)/100-1) FROM scripts)) AS scriptStartP95,
|
||||||
|
(SELECT COUNT(*) FROM waits) AS samples,
|
||||||
|
(SELECT delay FROM waits ORDER BY delay LIMIT 1 OFFSET (SELECT MAX(0, (95*COUNT(*)+99)/100-1) FROM waits)) AS waitP95
|
||||||
|
FROM today`,
|
||||||
|
{ bind: { since }, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...row,
|
||||||
|
audit: await auditSchedule(this.database, since),
|
||||||
|
systemAudit: await systemScheduleAudit(this.database, since),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -1,6 +1,6 @@
|
|||||||
import CronExpressionParser from 'cron-parser';
|
import CronExpressionParser from 'cron-parser';
|
||||||
import { validate } from 'node-cron';
|
import { validate } from 'node-cron';
|
||||||
import { ScheduleType } from '../interface/schedule';
|
import { ScheduleType } from '../../interface/schedule';
|
||||||
|
|
||||||
const aliases: Record<string, string> = {
|
const aliases: Record<string, string> = {
|
||||||
'@yearly': '0 0 0 1 1 *',
|
'@yearly': '0 0 0 1 1 *',
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { t } from './i18n';
|
import { t } from '../../shared/i18n';
|
||||||
import { createTask, ScheduledTask } from 'node-cron';
|
import { createTask, ScheduledTask } from 'node-cron';
|
||||||
import { parseCronSchedule } from './cronSchedule';
|
import { parseCronSchedule } from './cronSchedule';
|
||||||
|
|
||||||
@@ -12,7 +12,12 @@ export interface CronJob {
|
|||||||
cancel(): void;
|
cancel(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function acceptsSlot(parsed: ReturnType<typeof parseCronSchedule>, tasks: ScheduledTask[], index: number, date: Date) {
|
function acceptsSlot(
|
||||||
|
parsed: ReturnType<typeof parseCronSchedule>,
|
||||||
|
tasks: ScheduledTask[],
|
||||||
|
index: number,
|
||||||
|
date: Date,
|
||||||
|
) {
|
||||||
if (tasks.length === 1) return true;
|
if (tasks.length === 1) return true;
|
||||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||||
// month-dependent full-day range and the global nth-week constraint.
|
// month-dependent full-day range and the global nth-week constraint.
|
||||||
@@ -35,7 +40,8 @@ export function createCronJob(
|
|||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
let started = false;
|
let started = false;
|
||||||
const dispatch = async (index: number, date: Date, missed: boolean) => {
|
const dispatch = async (index: number, date: Date, missed: boolean) => {
|
||||||
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date)) return;
|
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date))
|
||||||
|
return;
|
||||||
if (missed) {
|
if (missed) {
|
||||||
options.logger.warn(
|
options.logger.warn(
|
||||||
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
|
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
|
||||||
@@ -90,30 +96,45 @@ export function createCronJob(
|
|||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
|
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
|
||||||
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
|
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
|
||||||
export function upcomingSlots(schedule: string, after: number, count = 1, through?: number): number[] {
|
export function upcomingSlots(
|
||||||
|
schedule: string,
|
||||||
|
after: number,
|
||||||
|
count = 1,
|
||||||
|
through?: number,
|
||||||
|
): number[] {
|
||||||
const parsed = parseCronSchedule(schedule);
|
const parsed = parseCronSchedule(schedule);
|
||||||
const tasks: ScheduledTask[] = [];
|
const tasks: ScheduledTask[] = [];
|
||||||
try {
|
try {
|
||||||
const matchers = parsed.patterns.map((pattern) => {
|
const matchers = parsed.patterns.map((pattern) => {
|
||||||
const task = createTask(pattern, () => {});
|
const task = createTask(pattern, () => {});
|
||||||
tasks.push(task);
|
tasks.push(task);
|
||||||
return (task as ScheduledTask & {
|
return (
|
||||||
timeMatcher: { getNextMatch(date: Date): Date; expressions: number[][] };
|
task as ScheduledTask & {
|
||||||
}).timeMatcher;
|
timeMatcher: {
|
||||||
|
getNextMatch(date: Date): Date;
|
||||||
|
expressions: number[][];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
).timeMatcher;
|
||||||
});
|
});
|
||||||
const next = matchers.map((matcher) => matcher.getNextMatch(new Date(after)));
|
const next = matchers.map((matcher) =>
|
||||||
|
matcher.getNextMatch(new Date(after)),
|
||||||
|
);
|
||||||
// All calendar branches share their clock fields. For bounded audit ranges,
|
// All calendar branches share their clock fields. For bounded audit ranges,
|
||||||
// resolve each matching minute once, including the matcher's DST choice.
|
// resolve each matching minute once, including the matcher's DST choice.
|
||||||
const seconds = through == null ? [] : [...new Set(matchers[0].expressions[0])].sort((a,b) => a-b);
|
const seconds =
|
||||||
|
through == null
|
||||||
|
? []
|
||||||
|
: [...new Set(matchers[0].expressions[0])].sort((a, b) => a - b);
|
||||||
const slots: number[] = [];
|
const slots: number[] = [];
|
||||||
let horizon = after + 366 * 100 * 86400000;
|
let horizon = after + 366 * 100 * 86400000;
|
||||||
while (slots.length < count) {
|
while (slots.length < count) {
|
||||||
const time = Math.min(...next.map(Number));
|
const time = Math.min(...next.map(Number));
|
||||||
if (through != null && time > through) break;
|
if (through != null && time > through) break;
|
||||||
if (!Number.isFinite(time) || time > horizon) throw new Error('No matching calendar date');
|
if (!Number.isFinite(time) || time > horizon)
|
||||||
|
throw new Error('No matching calendar date');
|
||||||
let accepted = false;
|
let accepted = false;
|
||||||
next.forEach((date, index) => {
|
next.forEach((date, index) => {
|
||||||
if (+date !== time) return;
|
if (+date !== time) return;
|
||||||
@@ -123,15 +144,17 @@ export function upcomingSlots(schedule: string, after: number, count = 1, throug
|
|||||||
// entire local day, including schedules that fire every second.
|
// entire local day, including schedules that fire every second.
|
||||||
const cursor = new Date(time);
|
const cursor = new Date(time);
|
||||||
if (!valid) cursor.setHours(23, 59, 59, 999);
|
if (!valid) cursor.setHours(23, 59, 59, 999);
|
||||||
else if (through != null) cursor.setTime(time - time % 60000 + 59999);
|
else if (through != null) cursor.setTime(time - (time % 60000) + 59999);
|
||||||
next[index] = matchers[index].getNextMatch(cursor);
|
next[index] = matchers[index].getNextMatch(cursor);
|
||||||
});
|
});
|
||||||
if (accepted) {
|
if (accepted) {
|
||||||
if (through == null) slots.push(time);
|
if (through == null) slots.push(time);
|
||||||
else for (const second of seconds) {
|
else
|
||||||
const slot = time - time % 60000 + second * 1000;
|
for (const second of seconds) {
|
||||||
if (slot >= time && slot <= through && slots.length < count) slots.push(slot);
|
const slot = time - (time % 60000) + second * 1000;
|
||||||
}
|
if (slot >= time && slot <= through && slots.length < count)
|
||||||
|
slots.push(slot);
|
||||||
|
}
|
||||||
horizon = time + 366 * 100 * 86400000;
|
horizon = time + 366 * 100 * 86400000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import type { Crontab } from '../../data/cron';
|
||||||
|
import type { ICron } from '../../protos/cron';
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
import { ScheduleType } from '../../interface/schedule';
|
||||||
|
import { TASK_PREFIX, QL_PREFIX } from '../../config/const';
|
||||||
|
import { shellQuote } from '../../shared/shellQuote';
|
||||||
|
|
||||||
|
export type SchedulerMode = 'system' | 'node';
|
||||||
|
|
||||||
|
// Adapt persisted task definitions without reserving or starting an execution.
|
||||||
|
export function isNodeCron(cron: Crontab) {
|
||||||
|
const { schedule, extra_schedules } = cron;
|
||||||
|
const fields = schedule?.trim().split(/\s+/) || [];
|
||||||
|
// System crontab only receives portable numeric five-field expressions.
|
||||||
|
// Extended syntax, macros and legacy shorthand use the Node scheduler.
|
||||||
|
return (
|
||||||
|
Boolean(
|
||||||
|
cron.max_queue_wait || cron.catchup_seconds || cron.skip_if_pending,
|
||||||
|
) ||
|
||||||
|
fields.length !== 5 ||
|
||||||
|
/[^\d\s*,/\-]/.test(schedule || '') ||
|
||||||
|
Boolean(extra_schedules?.length) ||
|
||||||
|
// BusyBox treats N/step as a single value and doesn't support Sunday=7.
|
||||||
|
fields.some((field) =>
|
||||||
|
field.split(',').some((part) => /^\d+\//.test(part)),
|
||||||
|
) ||
|
||||||
|
fields[4].includes('7') ||
|
||||||
|
// BusyBox steps DOM from zero; its full-range day/week wildcard
|
||||||
|
// handling also differs from the legacy Node parser's OR semantics.
|
||||||
|
fields[2].includes('/') ||
|
||||||
|
(fields[2] !== '*' && fields[4] !== '*')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function schedulerMode(): SchedulerMode {
|
||||||
|
const env = process.env.QL_SCHEDULER;
|
||||||
|
if (env === 'system') return 'system';
|
||||||
|
if (env === 'node') return 'node';
|
||||||
|
try {
|
||||||
|
execSync('which crond', { stdio: 'ignore' });
|
||||||
|
return 'system';
|
||||||
|
} catch {
|
||||||
|
return 'node';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldUseCronClient(cron: Crontab, mode: SchedulerMode) {
|
||||||
|
if (mode === 'node') {
|
||||||
|
return !isSpecialSchedule(cron.schedule);
|
||||||
|
}
|
||||||
|
return isNodeCron(cron) && !isSpecialSchedule(cron.schedule);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isOnceSchedule(schedule?: string) {
|
||||||
|
return schedule?.startsWith(ScheduleType.ONCE);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isBootSchedule(schedule?: string) {
|
||||||
|
return schedule?.startsWith(ScheduleType.BOOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSpecialSchedule(schedule?: string) {
|
||||||
|
return isOnceSchedule(schedule) || isBootSchedule(schedule);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shellValue(value: string) {
|
||||||
|
return /^[a-zA-Z0-9_./-]+$/.test(value) ? value : shellQuote(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manual, Node and system-crond launches share the existing shell wire format.
|
||||||
|
export function makeCommand(tab: Crontab, realTime?: boolean) {
|
||||||
|
let command = tab.command.trim();
|
||||||
|
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
|
||||||
|
command = `${TASK_PREFIX}${tab.command}`;
|
||||||
|
}
|
||||||
|
let commandVariable = `${
|
||||||
|
tab.recovery_from ? `QL_CRON_REVISION=${Number(tab.recovery_from)} ` : ''
|
||||||
|
}real_time=${Boolean(realTime)} no_tee=true ID=${tab.id} `;
|
||||||
|
// Only include log_name if it has a truthy value to avoid passing null/undefined to shell
|
||||||
|
if (tab.log_name) {
|
||||||
|
commandVariable += `log_name=${shellValue(tab.log_name)} `;
|
||||||
|
}
|
||||||
|
if (tab.task_before) {
|
||||||
|
commandVariable += `task_before='${tab.task_before
|
||||||
|
.replace(/'/g, "'\\''")
|
||||||
|
.replace(/;? *\n/g, ';')
|
||||||
|
.trim()}' `;
|
||||||
|
}
|
||||||
|
if (tab.task_after) {
|
||||||
|
commandVariable += `task_after='${tab.task_after
|
||||||
|
.replace(/'/g, "'\\''")
|
||||||
|
.replace(/;? *\n/g, ';')
|
||||||
|
.trim()}' `;
|
||||||
|
}
|
||||||
|
if (tab.work_dir) {
|
||||||
|
commandVariable += `work_dir='${tab.work_dir.replace(/'/g, "'\\''")}' `;
|
||||||
|
}
|
||||||
|
|
||||||
|
const crontab_job_string = `${commandVariable}${command}`;
|
||||||
|
return crontab_job_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function nodeCron(doc: Crontab, command: string): ICron {
|
||||||
|
return {
|
||||||
|
name: doc.name || '',
|
||||||
|
id: String(doc.id),
|
||||||
|
schedule: doc.schedule!,
|
||||||
|
command,
|
||||||
|
extra_schedules: doc.extra_schedules || [],
|
||||||
|
max_queue_wait: doc.max_queue_wait,
|
||||||
|
skip_if_pending: Boolean(doc.skip_if_pending),
|
||||||
|
catchup_seconds: doc.catchup_seconds,
|
||||||
|
recovery_from: doc.recovery_from,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { AnomalyPage } from './scheduleAnomalies';
|
import { AnomalyPage } from '../queries/scheduleAnomalies';
|
||||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
|
import { AddCronRequest, DeleteCronRequest } from '../../protos/cron';
|
||||||
import { upcomingSlots } from './cronScheduler';
|
import { upcomingSlots } from './cronScheduler';
|
||||||
import { slotId } from './triggerHistory';
|
import { slotId } from '../identity';
|
||||||
|
|
||||||
type Rule = {
|
type Rule = {
|
||||||
cron_id: string;
|
cron_id: string;
|
||||||
@@ -189,10 +189,14 @@ export async function auditSchedule(
|
|||||||
{ transaction, bind, type: QueryTypes.SELECT },
|
{ transaction, bind, type: QueryTypes.SELECT },
|
||||||
);
|
);
|
||||||
const receipts = await db.query<Receipt>(
|
const receipts = await db.query<Receipt>(
|
||||||
`SELECT id,cron_id,scheduled_at,observed_at,state,${details ? 'source,reason,log_path,' : ''}
|
`SELECT id,cron_id,scheduled_at,observed_at,state,${
|
||||||
|
details ? 'source,reason,log_path,' : ''
|
||||||
|
}
|
||||||
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
|
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
|
||||||
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
|
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
|
||||||
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${details ? 'ORDER BY cron_id,scheduled_at,id' : ''}`,
|
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${
|
||||||
|
details ? 'ORDER BY cron_id,scheduled_at,id' : ''
|
||||||
|
}`,
|
||||||
{ transaction, bind, type: QueryTypes.SELECT },
|
{ transaction, bind, type: QueryTypes.SELECT },
|
||||||
);
|
);
|
||||||
return { since: coverage.since, rules, receipts };
|
return { since: coverage.since, rules, receipts };
|
||||||
@@ -240,7 +244,8 @@ export async function auditSchedule(
|
|||||||
);
|
);
|
||||||
if (certain < possible) partial = true;
|
if (certain < possible) partial = true;
|
||||||
expected += certain;
|
expected += certain;
|
||||||
const received = details?.kind === 'missing' && certain ? new Set<number>() : null;
|
const received =
|
||||||
|
details?.kind === 'missing' && certain ? new Set<number>() : null;
|
||||||
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
|
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
|
||||||
const time = row.scheduled_at;
|
const time = row.scheduled_at;
|
||||||
if (
|
if (
|
||||||
@@ -267,21 +272,46 @@ export async function auditSchedule(
|
|||||||
} else {
|
} else {
|
||||||
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
||||||
if (kind === 'skipped') skipped++;
|
if (kind === 'skipped') skipped++;
|
||||||
if (details?.kind === kind) details.add({
|
if (details?.kind === kind)
|
||||||
task: row.cron_id, rule: rule.schedule, ruleIndex: rule.rule_index, time, source: row.source,
|
details.add({
|
||||||
trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path,
|
task: row.cron_id,
|
||||||
});
|
rule: rule.schedule,
|
||||||
|
ruleIndex: rule.rule_index,
|
||||||
|
time,
|
||||||
|
source: row.source,
|
||||||
|
trigger: row.id,
|
||||||
|
observed: row.observed_at,
|
||||||
|
reason: row.reason,
|
||||||
|
logPath: row.log_path,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (row.script_started_at != null && row.script_started_at >= time)
|
if (row.script_started_at != null && row.script_started_at >= time)
|
||||||
entries.push(row.script_started_at - time);
|
entries.push(row.script_started_at - time);
|
||||||
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
|
if (
|
||||||
|
row.started_at != null &&
|
||||||
|
row.queued_at != null &&
|
||||||
|
row.started_at >= row.queued_at
|
||||||
|
)
|
||||||
waits.push(row.started_at - row.queued_at);
|
waits.push(row.started_at - row.queued_at);
|
||||||
}
|
}
|
||||||
if (details && received && received.size < certain) {
|
if (details && received && received.size < certain) {
|
||||||
for (let i = lowerBound(times, certainFirst); i < times.length && times[i] <= certainLast; i++) {
|
for (
|
||||||
if (!received.has(times[i])) details.add({ task: Number(rule.cron_id), rule: rule.schedule,
|
let i = lowerBound(times, certainFirst);
|
||||||
ruleIndex: rule.rule_index, time: times[i], source: 'node', trigger: null,
|
i < times.length && times[i] <= certainLast;
|
||||||
observed: null, reason: null, logPath: null });
|
i++
|
||||||
|
) {
|
||||||
|
if (!received.has(times[i]))
|
||||||
|
details.add({
|
||||||
|
task: Number(rule.cron_id),
|
||||||
|
rule: rule.schedule,
|
||||||
|
ruleIndex: rule.rule_index,
|
||||||
|
time: times[i],
|
||||||
|
source: 'node',
|
||||||
|
trigger: null,
|
||||||
|
observed: null,
|
||||||
|
reason: null,
|
||||||
|
logPath: null,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
import lockfile from 'proper-lockfile';
|
import lockfile from 'proper-lockfile';
|
||||||
import config from '../config';
|
import config from '../../config/index';
|
||||||
|
|
||||||
// HTTP and gRPC both mutate cron definitions. Hold one shared lock from the
|
// HTTP and gRPC both mutate cron definitions. Hold one shared lock from the
|
||||||
// initial DB read/write through scheduler registration (including rollback).
|
// initial DB read/write through scheduler registration (including rollback).
|
||||||
@@ -66,9 +66,12 @@ export class SchedulerReadiness {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
if (!available) {
|
if (!available) {
|
||||||
throw Object.assign(new Error('Scheduler is recovering; try again later'), {
|
throw Object.assign(
|
||||||
status: 503,
|
new Error('Scheduler is recovering; try again later'),
|
||||||
});
|
{
|
||||||
|
status: 503,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import type { Crontab } from '../../data/cron';
|
||||||
|
import { CrontabModel } from '../../data/cron';
|
||||||
|
import type { Logger } from 'winston';
|
||||||
|
import config from '../../config/index';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import cronClient from '../../schedule/client';
|
||||||
|
import {
|
||||||
|
confirmSystemPlan,
|
||||||
|
stageSystemPlan,
|
||||||
|
suspendSystemPlan,
|
||||||
|
SystemRule,
|
||||||
|
} from './systemScheduleAudit';
|
||||||
|
import {
|
||||||
|
isNodeCron,
|
||||||
|
isSpecialSchedule,
|
||||||
|
makeCommand,
|
||||||
|
schedulerMode,
|
||||||
|
SchedulerMode,
|
||||||
|
} from './cronScheduling';
|
||||||
|
import { shellQuote } from '../../shared/shellQuote';
|
||||||
|
import { writeFileWithLock } from '../../shared/utils';
|
||||||
|
import { asError } from '../../shared/childProcess';
|
||||||
|
import { t } from '../../shared/i18n';
|
||||||
|
|
||||||
|
// Publication is called under the service's scheduler mutation lock. Staging,
|
||||||
|
// installation and confirmation keep their existing order and failure semantics.
|
||||||
|
export class SystemCronAdapter {
|
||||||
|
constructor(private logger: Logger) {}
|
||||||
|
|
||||||
|
async publish(
|
||||||
|
crons: Crontab[],
|
||||||
|
mode: () => SchedulerMode = schedulerMode,
|
||||||
|
command: (cron: Crontab) => string = makeCommand,
|
||||||
|
) {
|
||||||
|
const rules: SystemRule[] = [];
|
||||||
|
var crontab_string = '';
|
||||||
|
crons.forEach((tab) => {
|
||||||
|
if (
|
||||||
|
tab.isDisabled === 1 ||
|
||||||
|
isNodeCron(tab) ||
|
||||||
|
isSpecialSchedule(tab.schedule)
|
||||||
|
) {
|
||||||
|
crontab_string += '# ';
|
||||||
|
crontab_string += tab.schedule;
|
||||||
|
crontab_string += ' ';
|
||||||
|
crontab_string += command(tab);
|
||||||
|
crontab_string += '\n';
|
||||||
|
} else {
|
||||||
|
crontab_string += tab.schedule;
|
||||||
|
crontab_string += ' ';
|
||||||
|
rules.push({
|
||||||
|
id: tab.id!,
|
||||||
|
schedule: tab.schedule!,
|
||||||
|
name: tab.name || tab.command,
|
||||||
|
});
|
||||||
|
crontab_string += `QL_SYSTEM_DISPATCHED=$(date +\\%s) QL_SYSTEM_RULE=${shellQuote(
|
||||||
|
tab.schedule!,
|
||||||
|
)} ID=${
|
||||||
|
tab.id
|
||||||
|
} QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ${shellQuote(
|
||||||
|
command(tab),
|
||||||
|
)}`;
|
||||||
|
crontab_string += '\n';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const system = mode() === 'system';
|
||||||
|
const db = CrontabModel.sequelize!;
|
||||||
|
const plan = system ? await stageSystemPlan(db, rules) : undefined;
|
||||||
|
if (!system) await suspendSystemPlan(db);
|
||||||
|
await writeFileWithLock(config.crontabFile, crontab_string);
|
||||||
|
if (plan !== undefined) {
|
||||||
|
execFileSync('crontab', [config.crontabFile]);
|
||||||
|
await confirmSystemPlan(db, plan);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
'[crontab] Failed to publish crontab:',
|
||||||
|
asError(error).message,
|
||||||
|
);
|
||||||
|
cronClient.readiness.invalidate();
|
||||||
|
if (process.env.SERVICE_TYPE === 'grpc')
|
||||||
|
process.send?.('crontab-install-failed');
|
||||||
|
// A fresh host may have no installed crontab at all. A previous boot's
|
||||||
|
// saved flag does not confirm any portable rule in the failed snapshot.
|
||||||
|
if (mode() === 'system') {
|
||||||
|
const ids = crons
|
||||||
|
.filter((row) => !isNodeCron(row) && !isSpecialSchedule(row.schedule))
|
||||||
|
.map((row) => row.id!);
|
||||||
|
if (ids.length)
|
||||||
|
await CrontabModel.update({ saved: false }, { where: { id: ids } });
|
||||||
|
}
|
||||||
|
throw Object.assign(
|
||||||
|
new Error(t('系统定时规则安装失败,旧规则可能仍在运行,正在重试')),
|
||||||
|
{ status: 503 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { AnomalyPage } from './scheduleAnomalies';
|
import { AnomalyPage } from '../queries/scheduleAnomalies';
|
||||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
import { blockSize, blockSlots } from './scheduleAudit';
|
import { blockSize, blockSlots } from './scheduleAudit';
|
||||||
|
|
||||||
@@ -105,7 +105,9 @@ export async function systemScheduleAudit(
|
|||||||
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
|
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
|
||||||
);
|
);
|
||||||
const receipts = await db.query<Receipt>(
|
const receipts = await db.query<Receipt>(
|
||||||
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${details ? 'reason,log_path,' : ''}
|
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${
|
||||||
|
details ? 'reason,log_path,' : ''
|
||||||
|
}
|
||||||
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
|
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
|
||||||
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
|
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
|
||||||
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
|
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
|
||||||
@@ -137,7 +139,10 @@ export async function systemScheduleAudit(
|
|||||||
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
|
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
|
||||||
),
|
),
|
||||||
}));
|
}));
|
||||||
const matched = details && details.kind !== 'missing' ? new Map<string, { time: number; name?: string }>() : null;
|
const matched =
|
||||||
|
details && details.kind !== 'missing'
|
||||||
|
? new Map<string, { time: number; name?: string }>()
|
||||||
|
: null;
|
||||||
const groups = new Map<string, Receipt[]>();
|
const groups = new Map<string, Receipt[]>();
|
||||||
const dispatchedTasks = new Set<string>();
|
const dispatchedTasks = new Set<string>();
|
||||||
const legacyThrough = new Map<string, number>();
|
const legacyThrough = new Map<string, number>();
|
||||||
@@ -252,11 +257,14 @@ export async function systemScheduleAudit(
|
|||||||
);
|
);
|
||||||
let status: string;
|
let status: string;
|
||||||
const launched = group.find((row) => row.launched === 1);
|
const launched = group.find((row) => row.launched === 1);
|
||||||
const skip = group.find((row) => !row.launched && row.state === 'skipped');
|
const skip = group.find(
|
||||||
|
(row) => !row.launched && row.state === 'skipped',
|
||||||
|
);
|
||||||
if (group.length) {
|
if (group.length) {
|
||||||
++expected;
|
++expected;
|
||||||
++observed;
|
++observed;
|
||||||
if (matched) for (const row of group) matched.set(row.id, { time, name });
|
if (matched)
|
||||||
|
for (const row of group) matched.set(row.id, { time, name });
|
||||||
matchedReceipts += group.length;
|
matchedReceipts += group.length;
|
||||||
duplicates += group.length - 1;
|
duplicates += group.length - 1;
|
||||||
if (launched) ++dispatched;
|
if (launched) ++dispatched;
|
||||||
@@ -283,8 +291,18 @@ export async function systemScheduleAudit(
|
|||||||
status = 'awaiting';
|
status = 'awaiting';
|
||||||
} else {
|
} else {
|
||||||
++missing;
|
++missing;
|
||||||
if (details?.kind === 'missing') details.add({ task, name, rule: schedule, time, source: 'system',
|
if (details?.kind === 'missing')
|
||||||
trigger: null, observed: null, reason: null, logPath: null });
|
details.add({
|
||||||
|
task,
|
||||||
|
name,
|
||||||
|
rule: schedule,
|
||||||
|
time,
|
||||||
|
source: 'system',
|
||||||
|
trigger: null,
|
||||||
|
observed: null,
|
||||||
|
reason: null,
|
||||||
|
logPath: null,
|
||||||
|
});
|
||||||
status = 'missing';
|
status = 'missing';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -295,8 +313,12 @@ export async function systemScheduleAudit(
|
|||||||
status,
|
status,
|
||||||
triggerCount: group.length,
|
triggerCount: group.length,
|
||||||
startCount: group.filter((row) => row.launched === 1).length,
|
startCount: group.filter((row) => row.launched === 1).length,
|
||||||
skipCount: group.filter((row) => !row.launched && row.state === 'skipped').length,
|
skipCount: group.filter(
|
||||||
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
|
(row) => !row.launched && row.state === 'skipped',
|
||||||
|
).length,
|
||||||
|
unknownExitCount: group.filter(
|
||||||
|
(row) => row.launched === 1 && row.state === 'unknown',
|
||||||
|
).length,
|
||||||
id: (launched || skip || group[0])?.id,
|
id: (launched || skip || group[0])?.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -304,7 +326,8 @@ export async function systemScheduleAudit(
|
|||||||
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
|
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
|
||||||
recent.splice(25);
|
recent.splice(25);
|
||||||
}
|
}
|
||||||
let actualSkips = 0, actualUnconfirmed = 0;
|
let actualSkips = 0,
|
||||||
|
actualUnconfirmed = 0;
|
||||||
for (const row of receipts) {
|
for (const row of receipts) {
|
||||||
if (row.launched === 1) continue;
|
if (row.launched === 1) continue;
|
||||||
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
||||||
@@ -312,8 +335,17 @@ export async function systemScheduleAudit(
|
|||||||
else actualUnconfirmed++;
|
else actualUnconfirmed++;
|
||||||
if (details?.kind === kind) {
|
if (details?.kind === kind) {
|
||||||
const slot = matched?.get(row.id);
|
const slot = matched?.get(row.id);
|
||||||
details.add({ task: row.cron_id, name: slot?.name, rule: row.system_rule, time: slot?.time ?? null,
|
details.add({
|
||||||
source: 'system', trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path });
|
task: row.cron_id,
|
||||||
|
name: slot?.name,
|
||||||
|
rule: row.system_rule,
|
||||||
|
time: slot?.time ?? null,
|
||||||
|
source: 'system',
|
||||||
|
trigger: row.id,
|
||||||
|
observed: row.observed_at,
|
||||||
|
reason: row.reason,
|
||||||
|
logPath: row.log_path,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -332,7 +364,8 @@ export async function systemScheduleAudit(
|
|||||||
uncertain,
|
uncertain,
|
||||||
awaiting,
|
awaiting,
|
||||||
switchSlots,
|
switchSlots,
|
||||||
actualSkips, actualUnconfirmed,
|
actualSkips,
|
||||||
|
actualUnconfirmed,
|
||||||
actualStarts: receipts.filter((row) => row.launched === 1).length,
|
actualStarts: receipts.filter((row) => row.launched === 1).length,
|
||||||
unmatched: receipts.length - matchedReceipts,
|
unmatched: receipts.length - matchedReceipts,
|
||||||
recent,
|
recent,
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||||
|
|
||||||
|
export async function installTriggerHistory(
|
||||||
|
database: Sequelize,
|
||||||
|
transaction: Transaction,
|
||||||
|
) {
|
||||||
|
const conflictTable = `CREATE TABLE IF NOT EXISTS CronBoundExitConflicts (
|
||||||
|
trigger_id TEXT NOT NULL, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`;
|
||||||
|
const statements = [
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronPlanSwitches (seq INTEGER PRIMARY KEY, token TEXT UNIQUE NOT NULL,
|
||||||
|
staged_at INTEGER NOT NULL, first_at INTEGER, last_at INTEGER)`,
|
||||||
|
'CREATE TABLE IF NOT EXISTS CronPlanCoverage (id INTEGER PRIMARY KEY CHECK(id=1), since INTEGER NOT NULL)',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronPlanRules (
|
||||||
|
cron_id TEXT NOT NULL, rule_index INTEGER NOT NULL, schedule TEXT NOT NULL, zone TEXT NOT NULL,
|
||||||
|
since INTEGER NOT NULL, until INTEGER)`,
|
||||||
|
'CREATE UNIQUE INDEX IF NOT EXISTS cron_plan_active ON CronPlanRules(cron_id,rule_index) WHERE until IS NULL',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronTriggers (
|
||||||
|
id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, state TEXT NOT NULL,
|
||||||
|
scheduled_at INTEGER, queued_at INTEGER, started_at INTEGER, finished_at INTEGER,
|
||||||
|
reason TEXT, exit_code INTEGER, log_path TEXT, counted INTEGER NOT NULL DEFAULT 0,
|
||||||
|
owner TEXT, observed_at INTEGER NOT NULL)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronShellBindings (
|
||||||
|
receipt TEXT PRIMARY KEY, trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE)`,
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_shell_binding_trigger ON CronShellBindings(trigger_id)',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronExitObservations (
|
||||||
|
trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE,
|
||||||
|
outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronLegacyExitBookings (
|
||||||
|
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, started_at INTEGER NOT NULL,
|
||||||
|
finished_at INTEGER NOT NULL, outcome TEXT NOT NULL, day TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0,
|
||||||
|
stat_id INTEGER REFERENCES CrontabStats(id) ON DELETE SET NULL, disputed INTEGER NOT NULL DEFAULT 0)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronPrunedUnknownRuns (
|
||||||
|
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL REFERENCES Crontabs(id) ON DELETE CASCADE,
|
||||||
|
source TEXT NOT NULL, started_at INTEGER NOT NULL, last_possible_day TEXT NOT NULL) WITHOUT ROWID`,
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_pruned_unknown_day ON CronPrunedUnknownRuns(last_possible_day)',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronSystemPlans (id INTEGER PRIMARY KEY, staged INTEGER NOT NULL, confirmed INTEGER, zone TEXT NOT NULL, rules TEXT NOT NULL)`,
|
||||||
|
conflictTable,
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronUnmatchedBoundExits (
|
||||||
|
trigger_id TEXT PRIMARY KEY, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL) WITHOUT ROWID`,
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_legacy_booking_stat ON CronLegacyExitBookings(stat_id) WHERE stat_id IS NOT NULL',
|
||||||
|
'CREATE TABLE IF NOT EXISTS CronStatRetention (id INTEGER PRIMARY KEY CHECK(id=1), first_day TEXT NOT NULL)',
|
||||||
|
'CREATE TABLE IF NOT EXISTS CronHistoryRetention (id INTEGER PRIMARY KEY CHECK(id=1), cutoff INTEGER NOT NULL)',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronStopBatches (
|
||||||
|
request_id TEXT PRIMARY KEY, cron_ids TEXT NOT NULL, snapshot TEXT)`,
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_stop_batch_pending ON CronStopBatches(request_id) WHERE snapshot IS NOT NULL',
|
||||||
|
`CREATE TABLE IF NOT EXISTS CronStopRequests (
|
||||||
|
instance_id INTEGER PRIMARY KEY, cron_id INTEGER NOT NULL, pid INTEGER NOT NULL, targets TEXT, signalled INTEGER NOT NULL DEFAULT 0)`,
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_trigger_recent ON CronTriggers(cron_id, observed_at DESC)',
|
||||||
|
"CREATE INDEX IF NOT EXISTS cron_trigger_running_task ON CronTriggers(cron_id) WHERE state='running'",
|
||||||
|
"CREATE INDEX IF NOT EXISTS cron_trigger_queued_task ON CronTriggers(cron_id) WHERE state='queued'",
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_trigger_day ON CronTriggers(observed_at)',
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_trigger_slot ON CronTriggers(scheduled_at) WHERE scheduled_at IS NOT NULL',
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_trigger_active ON CronTriggers(source, state) WHERE finished_at IS NULL',
|
||||||
|
];
|
||||||
|
for (const sql of statements) await database.query(sql, { transaction });
|
||||||
|
const planFields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronPlanRules)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
for (const column of ['opened_by', 'closed_by']) {
|
||||||
|
if (!planFields.some((field) => field.name === column))
|
||||||
|
await database.query(
|
||||||
|
`ALTER TABLE CronPlanRules ADD COLUMN ${column} TEXT`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const conflictFields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronBoundExitConflicts)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (conflictFields.some((field) => field.name === 'other_outcome')) {
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronBoundExitConflicts RENAME TO CronBoundExitConflictPairs',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
await database.query(conflictTable, { transaction });
|
||||||
|
await database.query(
|
||||||
|
`INSERT INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
|
||||||
|
SELECT trigger_id,outcome,finished_at FROM CronBoundExitConflictPairs UNION
|
||||||
|
SELECT trigger_id,other_outcome,other_finished_at FROM CronBoundExitConflictPairs`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
await database.query('DROP TABLE CronBoundExitConflictPairs', {
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const bookingFields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronLegacyExitBookings)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!bookingFields.some((field) => field.name === 'bound'))
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronLegacyExitBookings ADD COLUMN bound INTEGER NOT NULL DEFAULT 0',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
const batchFields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronStopBatches)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!batchFields.some((column) => column.name === 'status_code'))
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronStopBatches ADD COLUMN status_code INTEGER NOT NULL DEFAULT 200',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
const stopFields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronStopRequests)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
if (!stopFields.some((column) => column.name === 'signalled_at'))
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronStopRequests ADD COLUMN signalled_at INTEGER',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
if (!stopFields.some((column) => column.name === 'root_identity'))
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronStopRequests ADD COLUMN root_identity TEXT',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
if (!stopFields.some((column) => column.name === 'namespace_owner'))
|
||||||
|
await database.query(
|
||||||
|
'ALTER TABLE CronStopRequests ADD COLUMN namespace_owner TEXT',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
const fields = await database.query<{ name: string }>(
|
||||||
|
'PRAGMA table_info(CronTriggers)',
|
||||||
|
{ transaction, type: QueryTypes.SELECT },
|
||||||
|
);
|
||||||
|
for (const [column, type] of [
|
||||||
|
['queue_live_context', 'TEXT'],
|
||||||
|
['dequeued_at', 'INTEGER'],
|
||||||
|
['system_dispatch_at', 'INTEGER'],
|
||||||
|
['queue_context', 'TEXT'],
|
||||||
|
['system_rule', 'TEXT'],
|
||||||
|
['command_started_at', 'INTEGER'],
|
||||||
|
['instance_id', 'INTEGER'],
|
||||||
|
['script_started_at', 'INTEGER'],
|
||||||
|
['stop_requested', 'INTEGER'],
|
||||||
|
['process_identity', 'TEXT'],
|
||||||
|
['command_identity', 'TEXT'],
|
||||||
|
['stop_exit_at', 'INTEGER'],
|
||||||
|
['stop_exit_verified', 'INTEGER'],
|
||||||
|
['exit_pending', 'INTEGER'],
|
||||||
|
]) {
|
||||||
|
if (!fields.some((field) => field.name === column))
|
||||||
|
await database.query(
|
||||||
|
`ALTER TABLE CronTriggers ADD COLUMN ${column} ${type}`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await database.query(
|
||||||
|
`CREATE TRIGGER IF NOT EXISTS cron_exit_observations_settled AFTER UPDATE OF counted ON CronTriggers
|
||||||
|
WHEN OLD.exit_pending=1 AND OLD.counted=0 AND NEW.counted=1 BEGIN
|
||||||
|
DELETE FROM CronExitObservations WHERE trigger_id=NEW.id;
|
||||||
|
END`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
await database.query(
|
||||||
|
"CREATE INDEX IF NOT EXISTS cron_system_dispatch ON CronTriggers(COALESCE(system_dispatch_at,observed_at)) WHERE source='system'",
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
await database.query(
|
||||||
|
'CREATE INDEX IF NOT EXISTS cron_trigger_pending_exit ON CronTriggers(id) WHERE exit_pending=1',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
await database.query(
|
||||||
|
'CREATE UNIQUE INDEX IF NOT EXISTS cron_trigger_instance ON CronTriggers(instance_id) WHERE instance_id IS NOT NULL',
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,13 +3,27 @@ import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
|||||||
|
|
||||||
// Hold the receipt claim and the daily increment in the same write transaction.
|
// Hold the receipt claim and the daily increment in the same write transaction.
|
||||||
export async function recordCronResult(
|
export async function recordCronResult(
|
||||||
database: Sequelize, cronId: number, _code: number, elapsedMs: number,
|
database: Sequelize,
|
||||||
finishedAt: number, triggerId: string, transaction?: Transaction,
|
cronId: number,
|
||||||
|
_code: number,
|
||||||
|
elapsedMs: number,
|
||||||
|
finishedAt: number,
|
||||||
|
triggerId: string,
|
||||||
|
transaction?: Transaction,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (!triggerId) throw new Error('Execution identity required');
|
if (!triggerId) throw new Error('Execution identity required');
|
||||||
if (!transaction) {
|
if (!transaction) {
|
||||||
return database.transaction((tx) =>
|
return database.transaction((tx) =>
|
||||||
recordCronResult(database, cronId, _code, elapsedMs, finishedAt, triggerId, tx));
|
recordCronResult(
|
||||||
|
database,
|
||||||
|
cronId,
|
||||||
|
_code,
|
||||||
|
elapsedMs,
|
||||||
|
finishedAt,
|
||||||
|
triggerId,
|
||||||
|
tx,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const bind = { ref: cronId, id: triggerId };
|
const bind = { ref: cronId, id: triggerId };
|
||||||
const claimed = await database.query(
|
const claimed = await database.query(
|
||||||
@@ -17,27 +31,55 @@ export async function recordCronResult(
|
|||||||
{ bind, type: QueryTypes.BULKUPDATE, transaction },
|
{ bind, type: QueryTypes.BULKUPDATE, transaction },
|
||||||
);
|
);
|
||||||
if (!claimed) {
|
if (!claimed) {
|
||||||
const rows = await database.query('SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
|
const rows = await database.query(
|
||||||
{ bind, type: QueryTypes.SELECT, transaction });
|
'SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
|
||||||
|
{ bind, type: QueryTypes.SELECT, transaction },
|
||||||
|
);
|
||||||
if (!rows.length) throw new Error('Unknown trigger');
|
if (!rows.length) throw new Error('Unknown trigger');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const [receipt] = await database.query<{ state: string; finished_at: number; reversible: number }>(
|
const [receipt] = await database.query<{
|
||||||
|
state: string;
|
||||||
|
finished_at: number;
|
||||||
|
reversible: number;
|
||||||
|
}>(
|
||||||
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
|
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
|
||||||
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
|
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
|
||||||
{ bind, type: QueryTypes.SELECT, transaction });
|
{ bind, type: QueryTypes.SELECT, transaction },
|
||||||
|
);
|
||||||
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
|
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
|
||||||
await addDailyExit(database, cronId, day, receipt.state, elapsedMs, Boolean(receipt.reversible), transaction);
|
await addDailyExit(
|
||||||
|
database,
|
||||||
|
cronId,
|
||||||
|
day,
|
||||||
|
receipt.state,
|
||||||
|
elapsedMs,
|
||||||
|
Boolean(receipt.reversible),
|
||||||
|
transaction,
|
||||||
|
);
|
||||||
if (receipt.reversible) {
|
if (receipt.reversible) {
|
||||||
await database.query(`UPDATE CronLegacyExitBookings SET stopped=$stopped,
|
await database.query(
|
||||||
|
`UPDATE CronLegacyExitBookings SET stopped=$stopped,
|
||||||
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
|
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
|
||||||
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
|
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
|
||||||
WHERE trigger_id=$id`, { bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') }, transaction });
|
WHERE trigger_id=$id`,
|
||||||
|
{
|
||||||
|
bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') },
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addDailyExit(database: Sequelize, cronId: number, day: string, state: string,
|
export async function addDailyExit(
|
||||||
elapsedMs: number, reversible: boolean, transaction: Transaction) {
|
database: Sequelize,
|
||||||
|
cronId: number,
|
||||||
|
day: string,
|
||||||
|
state: string,
|
||||||
|
elapsedMs: number,
|
||||||
|
reversible: boolean,
|
||||||
|
transaction: Transaction,
|
||||||
|
) {
|
||||||
await database.query(
|
await database.query(
|
||||||
`INSERT INTO "CrontabStats"
|
`INSERT INTO "CrontabStats"
|
||||||
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
|
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
|
||||||
@@ -51,7 +93,16 @@ export async function addDailyExit(database: Sequelize, cronId: number, day: str
|
|||||||
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
|
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
|
||||||
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
|
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
|
||||||
updatedAt = excluded.updatedAt`,
|
updatedAt = excluded.updatedAt`,
|
||||||
{ transaction, bind: { id: cronId, date: day, fixedMax: reversible ? 0 : elapsedMs,
|
{
|
||||||
success: Number(state === 'finished'), fail: Number(state === 'failed'), elapsed: elapsedMs } },
|
transaction,
|
||||||
|
bind: {
|
||||||
|
id: cronId,
|
||||||
|
date: day,
|
||||||
|
fixedMax: reversible ? 0 : elapsedMs,
|
||||||
|
success: Number(state === 'finished'),
|
||||||
|
fail: Number(state === 'failed'),
|
||||||
|
elapsed: elapsedMs,
|
||||||
|
},
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,519 @@
|
|||||||
|
// Keep the command's actual exit available until its SQLite transaction commits.
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { createHash, randomUUID } = require('node:crypto');
|
||||||
|
|
||||||
|
const idPattern = /^[a-z0-9-]{1,120}$/;
|
||||||
|
|
||||||
|
// A full data volume can still have room for a directory entry. In this format
|
||||||
|
// the empty file publishes the tuple atomically, including its execution-bound
|
||||||
|
// checksum. Keep the encoded name when moving it into a collector-private slot.
|
||||||
|
const metadataName =
|
||||||
|
/^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
|
||||||
|
|
||||||
|
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
|
||||||
|
const legacyCapture =
|
||||||
|
/^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
|
||||||
|
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
|
||||||
|
|
||||||
|
function metadataReceipt(file) {
|
||||||
|
const name = path.basename(file);
|
||||||
|
return metadataName.exec(
|
||||||
|
name === '.pending.claimed' ? path.basename(path.dirname(file)) : name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function storageFull(error) {
|
||||||
|
const codes = [error?.code, error?.original?.code, error?.parent?.code];
|
||||||
|
if (codes.some((code) => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code)))
|
||||||
|
return true;
|
||||||
|
const directory = receiptDirectory();
|
||||||
|
if (directory && codes.includes('SQLITE_CANTOPEN')) {
|
||||||
|
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
|
||||||
|
// reported ENOSPC. Other open failures keep their normal error semantics.
|
||||||
|
try {
|
||||||
|
const capacity = fs.statfsSync(path.dirname(directory));
|
||||||
|
return (
|
||||||
|
capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0)
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function receiptDirectory() {
|
||||||
|
const data =
|
||||||
|
process.env.QL_DATA_DIR ||
|
||||||
|
(process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
|
||||||
|
if (data) return path.join(data, 'db', 'cron-exits');
|
||||||
|
}
|
||||||
|
|
||||||
|
function receiptPath(id) {
|
||||||
|
const directory = receiptDirectory();
|
||||||
|
if (directory && typeof id === 'string' && idPattern.test(id))
|
||||||
|
return path.join(directory, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listReceiptFiles(directory, prefix) {
|
||||||
|
if (!directory) return [];
|
||||||
|
try {
|
||||||
|
const entries = await fs.promises.readdir(directory, {
|
||||||
|
withFileTypes: true,
|
||||||
|
});
|
||||||
|
const files = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
|
||||||
|
const id = entry.name.slice(prefix.length);
|
||||||
|
if (idPattern.test(id))
|
||||||
|
files.push({ id, file: path.join(directory, entry.name) });
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishedExits() {
|
||||||
|
return (await listReceiptFiles(receiptDirectory(), '')).map(
|
||||||
|
(entry) => entry.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// flock attaches to the open file description. The child inherits fd 3 and
|
||||||
|
// exits immediately. Closing the panel's handle (including on SIGKILL)
|
||||||
|
// releases the lock without leaving a lock file on a full volume.
|
||||||
|
async function lockClaim(handle, shared) {
|
||||||
|
const run = (program, args) =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const child = require('node:child_process').spawn(program, args, {
|
||||||
|
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
|
||||||
|
});
|
||||||
|
child.once('error', reject);
|
||||||
|
child.once('exit', (code, signal) => {
|
||||||
|
if (code === 0 || code === 1) resolve(code === 0);
|
||||||
|
else
|
||||||
|
reject(
|
||||||
|
new Error(`Receipt directory lock failed (${signal || code})`),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'ENOENT') throw error;
|
||||||
|
// Python is also shipped with the task supervisor on minimal Linux images.
|
||||||
|
const program =
|
||||||
|
'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
|
||||||
|
(shared ? 'SH' : 'EX') +
|
||||||
|
')\nexcept BlockingIOError: sys.exit(1)';
|
||||||
|
return run('python3', ['-c', program]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move the current directory entry to a fresh, recoverable name outside the
|
||||||
|
// reusable claim directory. A writer can replace that entry without flock.
|
||||||
|
// Only the bytes actually captured by this attempt authorize its final unlink.
|
||||||
|
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
|
||||||
|
async function retireLegacyFile(id, file, booked) {
|
||||||
|
const directory = receiptDirectory();
|
||||||
|
const sourceDir = path.dirname(file);
|
||||||
|
const slot = path.basename(file);
|
||||||
|
const bound =
|
||||||
|
/^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
|
||||||
|
const metadata = metadataReceipt(file);
|
||||||
|
const parent = claimName.exec(path.basename(sourceDir));
|
||||||
|
const privateSlot =
|
||||||
|
path.dirname(sourceDir) === directory &&
|
||||||
|
((parent?.[2] === id &&
|
||||||
|
slot === (parent[1] ? '.pending.claimed' : 'receipt')) ||
|
||||||
|
(metadata?.[1] === id && slot === '.pending.claimed'));
|
||||||
|
if (!directory || !idPattern.test(id)) return;
|
||||||
|
const dbDir = path.dirname(directory);
|
||||||
|
const localBin = path.join(directory, '.reclaim');
|
||||||
|
const fromBin = sourceDir === dbDir || sourceDir === localBin;
|
||||||
|
if (
|
||||||
|
sourceDir !== directory &&
|
||||||
|
!privateSlot &&
|
||||||
|
!(fromBin && captureId(slot) === id)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const matches = (exit) =>
|
||||||
|
exit &&
|
||||||
|
!exit.namedExit &&
|
||||||
|
(exit.version === 1
|
||||||
|
? booked &&
|
||||||
|
exit.time === booked.time &&
|
||||||
|
(exit.signal ?? String(exit.code)) === booked.outcome
|
||||||
|
: !bound);
|
||||||
|
let handle, binHandle;
|
||||||
|
try {
|
||||||
|
if (
|
||||||
|
(privateSlot || sourceDir === localBin) &&
|
||||||
|
process.platform === 'linux'
|
||||||
|
) {
|
||||||
|
handle = await fs.promises.open(
|
||||||
|
sourceDir,
|
||||||
|
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
|
||||||
|
);
|
||||||
|
if (privateSlot && !(await lockClaim(handle, true))) return;
|
||||||
|
}
|
||||||
|
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
|
||||||
|
// A canonical publication may only be readable after the move. For a
|
||||||
|
// recovered copy, first avoid moving an unsettled witness on every scan.
|
||||||
|
const previous = await readExit(id, source, file);
|
||||||
|
if (slot !== id && !matches(previous)) return;
|
||||||
|
const nonce = randomUUID();
|
||||||
|
let name;
|
||||||
|
if (metadata) {
|
||||||
|
name =
|
||||||
|
metadata[0].slice(0, -metadata[5].length) +
|
||||||
|
'r_' +
|
||||||
|
nonce.replace(/-/g, '').slice(0, 16);
|
||||||
|
} else if (bound || !previous || previous.version === 1) {
|
||||||
|
name = `.pending.${id}.r-${nonce}`;
|
||||||
|
} else {
|
||||||
|
const digest = exitChecksum(
|
||||||
|
id,
|
||||||
|
previous.code,
|
||||||
|
previous.signal,
|
||||||
|
previous.time,
|
||||||
|
).slice(0, 32);
|
||||||
|
name = `.pending.${id}.l-${digest}-${nonce
|
||||||
|
.replace(/-/g, '')
|
||||||
|
.slice(0, 24)}`;
|
||||||
|
}
|
||||||
|
// The database directory is outside the writers' receipt namespace and
|
||||||
|
// already exists even at zero free inodes. A separately mounted journal
|
||||||
|
// requires a disposal directory on its own filesystem.
|
||||||
|
let bin = sourceDir === localBin ? localBin : dbDir;
|
||||||
|
const pinBin = async () => {
|
||||||
|
binHandle = await fs.promises.open(
|
||||||
|
localBin,
|
||||||
|
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
|
||||||
|
);
|
||||||
|
return process.platform === 'linux'
|
||||||
|
? `/proc/self/fd/${binHandle.fd}/${name}`
|
||||||
|
: path.join(localBin, name);
|
||||||
|
};
|
||||||
|
let captured = path.join(bin, name);
|
||||||
|
if (bin === localBin)
|
||||||
|
captured = handle
|
||||||
|
? path.join(path.dirname(source), name)
|
||||||
|
: await pinBin();
|
||||||
|
try {
|
||||||
|
await fs.promises.rename(source, captured);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'EXDEV' || bin === localBin) throw error;
|
||||||
|
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
|
||||||
|
bin = localBin;
|
||||||
|
captured = await pinBin();
|
||||||
|
await fs.promises.rename(source, captured);
|
||||||
|
}
|
||||||
|
const actual = await readExit(id, captured, path.join(bin, name));
|
||||||
|
// An unreadable source offers no authority to discard unbound bytes.
|
||||||
|
const sameExit =
|
||||||
|
previous &&
|
||||||
|
actual &&
|
||||||
|
actual.version === previous.version &&
|
||||||
|
actual.code === previous.code &&
|
||||||
|
actual.signal === previous.signal &&
|
||||||
|
actual.time === previous.time;
|
||||||
|
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
|
||||||
|
await fs.promises.unlink(captured);
|
||||||
|
} else if (actual !== undefined) {
|
||||||
|
// A differing, torn or unreadable file is evidence for another pass.
|
||||||
|
// Persist its new directory entry before releasing the original directory.
|
||||||
|
if (binHandle) await binHandle.sync();
|
||||||
|
else if (bin !== sourceDir || !handle) syncDirectory(bin);
|
||||||
|
if (bin === localBin) syncDirectory(directory);
|
||||||
|
if (handle) await handle.sync();
|
||||||
|
else if (sourceDir !== bin) syncDirectory(sourceDir);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'ENOENT') throw error;
|
||||||
|
} finally {
|
||||||
|
if (binHandle) await binHandle.close();
|
||||||
|
if (handle) await handle.close();
|
||||||
|
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function captureId(name) {
|
||||||
|
const marker = metadataName.exec(name);
|
||||||
|
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
|
||||||
|
const match =
|
||||||
|
legacyCapture.exec(name) ??
|
||||||
|
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
|
||||||
|
return match?.[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function receiptEntries(directory) {
|
||||||
|
try {
|
||||||
|
return await fs.promises.readdir(directory, { withFileTypes: true });
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retiringExits() {
|
||||||
|
const dir = receiptDirectory();
|
||||||
|
if (!dir) return [];
|
||||||
|
const files = [];
|
||||||
|
const bins = [path.dirname(dir)];
|
||||||
|
for (const entry of await receiptEntries(dir)) {
|
||||||
|
if (entry.isDirectory() && entry.name === '.reclaim') {
|
||||||
|
bins.push(path.join(dir, entry.name));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const claim = claimName.exec(entry.name);
|
||||||
|
const metadata = metadataName.exec(entry.name);
|
||||||
|
if ((claim || metadata) && entry.isDirectory()) {
|
||||||
|
const directory = path.join(dir, entry.name);
|
||||||
|
try {
|
||||||
|
await fs.promises.rmdir(directory);
|
||||||
|
continue;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') continue;
|
||||||
|
}
|
||||||
|
files.push({
|
||||||
|
id: metadata ? metadata[1] : claim[2],
|
||||||
|
file: path.join(
|
||||||
|
directory,
|
||||||
|
metadata || claim[1] ? '.pending.claimed' : 'receipt',
|
||||||
|
),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const match =
|
||||||
|
metadata ??
|
||||||
|
/^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(
|
||||||
|
entry.name,
|
||||||
|
) ??
|
||||||
|
/^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name) ??
|
||||||
|
/^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
|
||||||
|
if (entry.isFile() && match)
|
||||||
|
files.push({ id: match[1], file: path.join(dir, entry.name) });
|
||||||
|
}
|
||||||
|
for (const bin of bins) {
|
||||||
|
for (const entry of await receiptEntries(bin)) {
|
||||||
|
const id = entry.isFile() && captureId(entry.name);
|
||||||
|
if (id) files.push({ id, file: path.join(bin, entry.name) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishedScriptStarts() {
|
||||||
|
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
|
||||||
|
try {
|
||||||
|
return await listReceiptFiles(directory, 'cron-start-');
|
||||||
|
} catch {
|
||||||
|
// Optional entry instrumentation must not prevent exit recovery.
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validExit(code, signal, time) {
|
||||||
|
return (
|
||||||
|
Number.isSafeInteger(time) &&
|
||||||
|
time > 0 &&
|
||||||
|
Number.isFinite(new Date(time).getTime()) &&
|
||||||
|
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
|
||||||
|
(code === null &&
|
||||||
|
typeof signal === 'string' &&
|
||||||
|
/^SIG[A-Z0-9]+$/.test(signal)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Python supervisor uses the same compact JSON array of ASCII values.
|
||||||
|
function exitChecksum(id, code, signal, time) {
|
||||||
|
return createHash('sha256')
|
||||||
|
.update(JSON.stringify([id, code, signal, time]))
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncDirectory(directory) {
|
||||||
|
const fd = fs.openSync(
|
||||||
|
directory,
|
||||||
|
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
fs.fsyncSync(fd);
|
||||||
|
} finally {
|
||||||
|
fs.closeSync(fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeExit(id, code, signal, time) {
|
||||||
|
if (!validExit(code, signal, time))
|
||||||
|
throw new TypeError('Invalid command exit receipt');
|
||||||
|
const file = receiptPath(id);
|
||||||
|
if (!file) return;
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||||
|
const checksum = exitChecksum(id, code, signal, time);
|
||||||
|
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
|
||||||
|
// Creation is the first durable observation. No data block is needed for
|
||||||
|
// this witness. Keep the regular JSON publication for earlier readers.
|
||||||
|
const directory = path.dirname(file);
|
||||||
|
const prefix = '.pending.' + id + '.';
|
||||||
|
const marker =
|
||||||
|
prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
|
||||||
|
const publish = (name, content) => {
|
||||||
|
for (;;) {
|
||||||
|
const target = path.join(
|
||||||
|
directory,
|
||||||
|
name + randomUUID().replace(/-/g, '').slice(0, 16),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(target, content, {
|
||||||
|
flag: 'wx',
|
||||||
|
mode: 0o600,
|
||||||
|
flush: Boolean(content),
|
||||||
|
});
|
||||||
|
return target;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'EEXIST') throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
publish(marker, '');
|
||||||
|
// ext4 journals the empty inode and directory entry together. Also fence the
|
||||||
|
// directory's own entry: another publisher may just have created it.
|
||||||
|
syncDirectory(directory);
|
||||||
|
syncDirectory(path.dirname(directory));
|
||||||
|
try {
|
||||||
|
if (fs.statfsSync(directory).bavail === 0) return;
|
||||||
|
const source = publish(marker, receipt);
|
||||||
|
try {
|
||||||
|
fs.linkSync(source, file);
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return;
|
||||||
|
if (error.code !== 'EEXIST') throw error;
|
||||||
|
// A panel from before metadata receipts can still discover this retry.
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
fs.linkSync(source, path.join(directory, prefix + randomUUID()));
|
||||||
|
break;
|
||||||
|
} catch (linkError) {
|
||||||
|
if (linkError.code === 'ENOENT') break;
|
||||||
|
if (linkError.code !== 'EEXIST') throw linkError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Older panels find the JSON only through this newly created link.
|
||||||
|
syncDirectory(directory);
|
||||||
|
} catch (error) {
|
||||||
|
if (!storageFull(error)) throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseExit(id, value) {
|
||||||
|
if (!value || !validExit(value.code, value.signal, value.time)) return null;
|
||||||
|
const { code, signal, time, checksum, version } = value;
|
||||||
|
if (version !== undefined || checksum !== undefined) {
|
||||||
|
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time))
|
||||||
|
return null;
|
||||||
|
} else if (Object.keys(value).length !== 3) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { code, signal, time, version };
|
||||||
|
}
|
||||||
|
|
||||||
|
// undefined means no publication. null means a result cannot yet be trusted.
|
||||||
|
async function readExit(id, file = receiptPath(id), publication = file) {
|
||||||
|
if (!file) return;
|
||||||
|
try {
|
||||||
|
const handle = await fs.promises.open(
|
||||||
|
file,
|
||||||
|
fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
// Bound CPU and memory even if the damaged file is growing.
|
||||||
|
const buffer = Buffer.alloc(1025);
|
||||||
|
let size = 0;
|
||||||
|
while (size < buffer.length) {
|
||||||
|
const { bytesRead } = await handle.read(
|
||||||
|
buffer,
|
||||||
|
size,
|
||||||
|
buffer.length - size,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
if (!bytesRead) break;
|
||||||
|
size += bytesRead;
|
||||||
|
}
|
||||||
|
if (size === buffer.length) return null;
|
||||||
|
const metadata = metadataReceipt(publication);
|
||||||
|
const bytes = buffer.toString('utf8', 0, size);
|
||||||
|
let namedExit;
|
||||||
|
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
|
||||||
|
const [, , outcome, end, checksum] = metadata;
|
||||||
|
const signal = outcome.startsWith('SIG') ? outcome : null;
|
||||||
|
const value = {
|
||||||
|
code: signal ? null : Number(outcome),
|
||||||
|
signal,
|
||||||
|
time: Number(end),
|
||||||
|
version: 1,
|
||||||
|
checksum,
|
||||||
|
};
|
||||||
|
// Both current publishers serialize in this order. Accept a torn body
|
||||||
|
// only when every byte matches the tuple independently published by
|
||||||
|
// the filename. Validate replacement files on their own bytes below.
|
||||||
|
namedExit = parseExit(id, value);
|
||||||
|
const json = JSON.stringify(value);
|
||||||
|
if (json.startsWith(bytes)) {
|
||||||
|
return namedExit && { ...namedExit, file, namedExit: undefined };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const exit = parseExit(id, JSON.parse(bytes));
|
||||||
|
const guard = legacyCapture.exec(path.basename(publication));
|
||||||
|
if (
|
||||||
|
guard &&
|
||||||
|
exit &&
|
||||||
|
exit.version !== 1 &&
|
||||||
|
(guard[1] !== id ||
|
||||||
|
guard[2] !==
|
||||||
|
exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))
|
||||||
|
)
|
||||||
|
return null;
|
||||||
|
const conflictingName =
|
||||||
|
exit?.version === 1 &&
|
||||||
|
namedExit &&
|
||||||
|
(exit.time !== namedExit.time ||
|
||||||
|
exit.code !== namedExit.code ||
|
||||||
|
exit.signal !== namedExit.signal);
|
||||||
|
return (
|
||||||
|
exit && {
|
||||||
|
...exit,
|
||||||
|
file,
|
||||||
|
namedExit: conflictingName ? namedExit : undefined,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await handle.close();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') return;
|
||||||
|
if (error.code || error instanceof SyntaxError) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
parseExit,
|
||||||
|
isLegacyCapture: (file) => legacyCapture.test(path.basename(file)),
|
||||||
|
isMetadataReceipt: (file) => Boolean(metadataReceipt(file)),
|
||||||
|
receiptPath,
|
||||||
|
publishedExits,
|
||||||
|
publishedScriptStarts,
|
||||||
|
readExit,
|
||||||
|
writeExit,
|
||||||
|
validExit,
|
||||||
|
storageFull,
|
||||||
|
retireLegacyFile,
|
||||||
|
retiringExits,
|
||||||
|
};
|
||||||
+90
-27
@@ -15,11 +15,19 @@ type DayCounts = {
|
|||||||
|
|
||||||
// Process one outcome, newest day first. Same-day receipts can only cover
|
// Process one outcome, newest day first. Same-day receipts can only cover
|
||||||
// eligible exits. Surplus becomes available to earlier days after this match.
|
// eligible exits. Surplus becomes available to earlier days after this match.
|
||||||
function matchDailyCounts(exits: number, saved: number, laterCredits: number, afterLastBooking = 0) {
|
function matchDailyCounts(
|
||||||
|
exits: number,
|
||||||
|
saved: number,
|
||||||
|
laterCredits: number,
|
||||||
|
afterLastBooking = 0,
|
||||||
|
) {
|
||||||
const localMatches = Math.min(saved, exits - afterLastBooking);
|
const localMatches = Math.min(saved, exits - afterLastBooking);
|
||||||
const deficit = exits - localMatches;
|
const deficit = exits - localMatches;
|
||||||
const borrowed = Math.min(deficit, laterCredits);
|
const borrowed = Math.min(deficit, laterCredits);
|
||||||
return { missing: deficit - borrowed, remaining: laterCredits - borrowed + saved - localMatches };
|
return {
|
||||||
|
missing: deficit - borrowed,
|
||||||
|
remaining: laterCredits - borrowed + saved - localMatches,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// A legacy terminal status needs a matching exit code. An identified supervisor
|
// A legacy terminal status needs a matching exit code. An identified supervisor
|
||||||
@@ -41,9 +49,14 @@ export function readDailyResults(database: Sequelize, cronId: number) {
|
|||||||
const first = today.subtract(6, 'day');
|
const first = today.subtract(6, 'day');
|
||||||
const next = today.add(1, 'day');
|
const next = today.add(1, 'day');
|
||||||
return database.query<{
|
return database.query<{
|
||||||
day: string; exitSuccess: number; exitFail: number;
|
day: string;
|
||||||
bookedSuccess: number; bookedFail: number; supplement: number;
|
exitSuccess: number;
|
||||||
}>(`WITH results AS (
|
exitFail: number;
|
||||||
|
bookedSuccess: number;
|
||||||
|
bookedFail: number;
|
||||||
|
supplement: number;
|
||||||
|
}>(
|
||||||
|
`WITH results AS (
|
||||||
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||||
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
|
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
|
||||||
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
|
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
|
||||||
@@ -55,17 +68,30 @@ export function readDailyResults(database: Sequelize, cronId: number) {
|
|||||||
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
|
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
|
||||||
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
|
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
|
||||||
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
|
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
|
||||||
FROM results GROUP BY day ORDER BY day DESC`, { type: QueryTypes.SELECT, bind: {
|
FROM results GROUP BY day ORDER BY day DESC`,
|
||||||
id: cronId, start: first.valueOf(), end: next.valueOf(),
|
{
|
||||||
first: first.format('YYYY-MM-DD'), next: next.format('YYYY-MM-DD'),
|
type: QueryTypes.SELECT,
|
||||||
} });
|
bind: {
|
||||||
|
id: cronId,
|
||||||
|
start: first.valueOf(),
|
||||||
|
end: next.valueOf(),
|
||||||
|
first: first.format('YYYY-MM-DD'),
|
||||||
|
next: next.format('YYYY-MM-DD'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run under the schema migration's write lock, before accepting new receipts.
|
// Run under the schema migration's write lock, before accepting new receipts.
|
||||||
export async function repairLegacyDailyStatistics(database: Sequelize, transaction: Transaction, priorVersion: 0 | 1 | 2) {
|
export async function repairLegacyDailyStatistics(
|
||||||
|
database: Sequelize,
|
||||||
|
transaction: Transaction,
|
||||||
|
priorVersion: 0 | 1 | 2,
|
||||||
|
) {
|
||||||
// Old panels updated every outstanding start with the reported PID. Identical
|
// Old panels updated every outstanding start with the reported PID. Identical
|
||||||
// copies of a start prove only one exit; conflicting rows cannot identify it.
|
// copies of a start prove only one exit; conflicting rows cannot identify it.
|
||||||
const imported = await database.query(`WITH exits AS (
|
const imported = await database.query(
|
||||||
|
`WITH exits AS (
|
||||||
SELECT MIN(i.id) AS instance FROM RunningInstances i
|
SELECT MIN(i.id) AS instance FROM RunningInstances i
|
||||||
JOIN Crontabs c ON c.id=i.cron_id
|
JOIN Crontabs c ON c.id=i.cron_id
|
||||||
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
|
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
|
||||||
@@ -83,11 +109,14 @@ export async function repairLegacyDailyStatistics(database: Sequelize, transacti
|
|||||||
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
|
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
|
||||||
FROM exits JOIN RunningInstances i ON i.id=exits.instance
|
FROM exits JOIN RunningInstances i ON i.id=exits.instance
|
||||||
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
|
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
|
||||||
{ transaction, type: QueryTypes.BULKUPDATE });
|
{ transaction, type: QueryTypes.BULKUPDATE },
|
||||||
|
);
|
||||||
|
|
||||||
// A newly imported last run must have the same owner it would acquire through
|
// A newly imported last run must have the same owner it would acquire through
|
||||||
// the normal handoff. An older exit must never replace a more recent start.
|
// the normal handoff. An older exit must never replace a more recent start.
|
||||||
if (imported) await database.query(`WITH ranked AS (
|
if (imported)
|
||||||
|
await database.query(
|
||||||
|
`WITH ranked AS (
|
||||||
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
|
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
|
||||||
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
|
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
|
||||||
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
|
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
|
||||||
@@ -99,12 +128,14 @@ export async function repairLegacyDailyStatistics(database: Sequelize, transacti
|
|||||||
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
|
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
|
||||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
|
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
|
||||||
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
|
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
|
||||||
{ transaction });
|
{ transaction },
|
||||||
|
);
|
||||||
|
|
||||||
// Statistics retention removes whole dates across tasks. When the old panel
|
// Statistics retention removes whole dates across tasks. When the old panel
|
||||||
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
|
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
|
||||||
const yesterday = dayjs().subtract(1,'day').format('YYYY-MM-DD');
|
const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
|
||||||
const days = await database.query<DayCounts>(`WITH exits AS (
|
const days = await database.query<DayCounts>(
|
||||||
|
`WITH exits AS (
|
||||||
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||||
t.started_at,i.createdAt,t.id
|
t.started_at,i.createdAt,t.id
|
||||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||||
@@ -127,28 +158,55 @@ export async function repairLegacyDailyStatistics(database: Sequelize, transacti
|
|||||||
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
|
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
|
||||||
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
|
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
|
||||||
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
|
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
|
||||||
GROUP BY cron_id,day ORDER BY cron_id,day DESC`, { type: QueryTypes.SELECT, transaction, bind:{ yesterday } });
|
GROUP BY cron_id,day ORDER BY cron_id,day DESC`,
|
||||||
|
{ type: QueryTypes.SELECT, transaction, bind: { yesterday } },
|
||||||
|
);
|
||||||
|
|
||||||
// Anonymous receipts cannot identify a particular exit. Match nearest
|
// Anonymous receipts cannot identify a particular exit. Match nearest
|
||||||
// eligible days first; never move already booked counts or elapsed samples.
|
// eligible days first; never move already booked counts or elapsed samples.
|
||||||
let task: number | undefined;
|
let task: number | undefined;
|
||||||
let successCredit = 0, failureCredit = 0;
|
let successCredit = 0,
|
||||||
let priorSuccessCredit = 0, priorFailureCredit = 0;
|
failureCredit = 0;
|
||||||
|
let priorSuccessCredit = 0,
|
||||||
|
priorFailureCredit = 0;
|
||||||
for (const day of days) {
|
for (const day of days) {
|
||||||
if (day.cron_id !== task) {
|
if (day.cron_id !== task) {
|
||||||
task = day.cron_id;
|
task = day.cron_id;
|
||||||
successCredit = failureCredit = priorSuccessCredit = priorFailureCredit = 0;
|
successCredit =
|
||||||
|
failureCredit =
|
||||||
|
priorSuccessCredit =
|
||||||
|
priorFailureCredit =
|
||||||
|
0;
|
||||||
}
|
}
|
||||||
const successes = matchDailyCounts(day.successes, day.saved_successes, successCredit, day.later_successes);
|
const successes = matchDailyCounts(
|
||||||
const failures = matchDailyCounts(day.failures, day.saved_failures, failureCredit, day.later_failures);
|
day.successes,
|
||||||
|
day.saved_successes,
|
||||||
|
successCredit,
|
||||||
|
day.later_successes,
|
||||||
|
);
|
||||||
|
const failures = matchDailyCounts(
|
||||||
|
day.failures,
|
||||||
|
day.saved_failures,
|
||||||
|
failureCredit,
|
||||||
|
day.later_failures,
|
||||||
|
);
|
||||||
successCredit = successes.remaining;
|
successCredit = successes.remaining;
|
||||||
failureCredit = failures.remaining;
|
failureCredit = failures.remaining;
|
||||||
let success = successes.missing, failure = failures.missing;
|
let success = successes.missing,
|
||||||
|
failure = failures.missing;
|
||||||
if (priorVersion === 2) {
|
if (priorVersion === 2) {
|
||||||
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
|
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
|
||||||
// Only the extra lower bound established by v3 is new evidence.
|
// Only the extra lower bound established by v3 is new evidence.
|
||||||
const priorSuccess = matchDailyCounts(day.successes, day.saved_successes, priorSuccessCredit);
|
const priorSuccess = matchDailyCounts(
|
||||||
const priorFailure = matchDailyCounts(day.failures, day.saved_failures, priorFailureCredit);
|
day.successes,
|
||||||
|
day.saved_successes,
|
||||||
|
priorSuccessCredit,
|
||||||
|
);
|
||||||
|
const priorFailure = matchDailyCounts(
|
||||||
|
day.failures,
|
||||||
|
day.saved_failures,
|
||||||
|
priorFailureCredit,
|
||||||
|
);
|
||||||
priorSuccessCredit = priorSuccess.remaining;
|
priorSuccessCredit = priorSuccess.remaining;
|
||||||
priorFailureCredit = priorFailure.remaining;
|
priorFailureCredit = priorFailure.remaining;
|
||||||
success = Math.max(0, success - priorSuccess.missing);
|
success = Math.max(0, success - priorSuccess.missing);
|
||||||
@@ -160,13 +218,18 @@ export async function repairLegacyDailyStatistics(database: Sequelize, transacti
|
|||||||
if (!success && !failure) continue;
|
if (!success && !failure) continue;
|
||||||
// Anonymous elapsed samples have no execution identity. Preserve measured
|
// Anonymous elapsed samples have no execution identity. Preserve measured
|
||||||
// times; adding instance wall times here could count the same sample twice.
|
// times; adding instance wall times here could count the same sample twice.
|
||||||
await database.query(`INSERT INTO CrontabStats
|
await database.query(
|
||||||
|
`INSERT INTO CrontabStats
|
||||||
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
|
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
|
||||||
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||||
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
|
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
|
||||||
success_count=COALESCE(success_count,0)+excluded.success_count,
|
success_count=COALESCE(success_count,0)+excluded.success_count,
|
||||||
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
|
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
|
||||||
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
|
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
|
||||||
{ transaction, bind: { task,day:day.day,runs:success+failure,success,failure } });
|
{
|
||||||
|
transaction,
|
||||||
|
bind: { task, day: day.day, runs: success + failure, success, failure },
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
|||||||
|
export type TriggerSource =
|
||||||
|
| 'node'
|
||||||
|
| 'manual'
|
||||||
|
| 'boot'
|
||||||
|
| 'system'
|
||||||
|
| 'recovery'
|
||||||
|
| 'legacy'
|
||||||
|
| 'client';
|
||||||
|
export type TriggerState =
|
||||||
|
| 'queued'
|
||||||
|
| 'running'
|
||||||
|
| 'finished'
|
||||||
|
| 'failed'
|
||||||
|
| 'skipped'
|
||||||
|
| 'stopped'
|
||||||
|
| 'unknown';
|
||||||
|
|
||||||
|
export type Trigger = {
|
||||||
|
id: string;
|
||||||
|
cron_id: number;
|
||||||
|
source: TriggerSource;
|
||||||
|
state: TriggerState;
|
||||||
|
scheduled_at: number | null;
|
||||||
|
queued_at: number | null;
|
||||||
|
dequeued_at?: number | null;
|
||||||
|
started_at: number | null;
|
||||||
|
script_started_at: number | null;
|
||||||
|
command_started_at: number | null;
|
||||||
|
finished_at: number | null;
|
||||||
|
reason: string | null;
|
||||||
|
exit_code: number | null;
|
||||||
|
log_path: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type VerifiedSupervisorExit = {
|
||||||
|
code: number | null;
|
||||||
|
signal: string | null;
|
||||||
|
time: number;
|
||||||
|
version: 1;
|
||||||
|
};
|
||||||
@@ -26,7 +26,9 @@ export class CrontabStat {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CrontabStatInstance extends Model<CrontabStat, CrontabStat>, CrontabStat {}
|
export interface CrontabStatInstance
|
||||||
|
extends Model<CrontabStat, CrontabStat>,
|
||||||
|
CrontabStat {}
|
||||||
|
|
||||||
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
|
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
|
||||||
'CrontabStat',
|
'CrontabStat',
|
||||||
|
|||||||
+4
-2
@@ -29,8 +29,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => {
|
|||||||
let ready = initialized.get(connection);
|
let ready = initialized.get(connection);
|
||||||
if (!ready) {
|
if (!ready) {
|
||||||
ready = new Promise<void>((resolve, reject) => {
|
ready = new Promise<void>((resolve, reject) => {
|
||||||
connection.run('PRAGMA synchronous=EXTRA', error => error ? reject(error) : resolve());
|
connection.run('PRAGMA synchronous=EXTRA', (error) =>
|
||||||
}).catch(error => {
|
error ? reject(error) : resolve(),
|
||||||
|
);
|
||||||
|
}).catch((error) => {
|
||||||
initialized.delete(connection);
|
initialized.delete(connection);
|
||||||
throw error;
|
throw error;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { AuthDataType, SystemModel } from './system';
|
||||||
|
import type { NotificationInfo } from './notify';
|
||||||
|
|
||||||
|
// Keep the same lookup and missing-row semantics as UserService.getDb.
|
||||||
|
export async function readNotificationMode(): Promise<NotificationInfo> {
|
||||||
|
const query = { type: AuthDataType.notification };
|
||||||
|
const doc = await SystemModel.findOne({ where: { ...query } });
|
||||||
|
if (!doc) {
|
||||||
|
throw new Error(`${JSON.stringify(query)} not found`);
|
||||||
|
}
|
||||||
|
return (doc.get({ plain: true }).info || {}) as NotificationInfo;
|
||||||
|
}
|
||||||
@@ -79,5 +79,10 @@ export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
|
|||||||
allowNull: true,
|
allowNull: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ indexes: [{ fields: ['cron_id', 'pid', 'started_at'] }, { fields: ['cron_id', 'id'] }] },
|
{
|
||||||
|
indexes: [
|
||||||
|
{ fields: ['cron_id', 'pid', 'started_at'] },
|
||||||
|
{ fields: ['cron_id', 'id'] },
|
||||||
|
],
|
||||||
|
},
|
||||||
);
|
);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { installTriggerHistory } from './triggerHistory';
|
import { installTriggerHistory } from '../cron/schema';
|
||||||
import { repairLegacyDailyStatistics } from './legacyDailyStatistics';
|
import { repairLegacyDailyStatistics } from '../cron/settlement/legacyDailyStatistics';
|
||||||
import { QueryTypes, Sequelize } from 'sequelize';
|
import { QueryTypes, Sequelize } from 'sequelize';
|
||||||
|
|
||||||
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
|
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
|
||||||
@@ -35,7 +35,11 @@ const columns = [
|
|||||||
{ table: 'Crontabs', column: 'skip_if_pending', type: 'BOOLEAN' },
|
{ table: 'Crontabs', column: 'skip_if_pending', type: 'BOOLEAN' },
|
||||||
{ table: 'Crontabs', column: 'recovery_from', type: 'BIGINT' },
|
{ table: 'Crontabs', column: 'recovery_from', type: 'BIGINT' },
|
||||||
{ table: 'Crontabs', column: 'last_instance_id', type: 'INTEGER' },
|
{ table: 'Crontabs', column: 'last_instance_id', type: 'INTEGER' },
|
||||||
{ table: 'CrontabStats', column: 'untimed_count', type: 'INTEGER NOT NULL DEFAULT 0' },
|
{
|
||||||
|
table: 'CrontabStats',
|
||||||
|
column: 'untimed_count',
|
||||||
|
type: 'INTEGER NOT NULL DEFAULT 0',
|
||||||
|
},
|
||||||
{ table: 'CrontabStats', column: 'fixed_max_time', type: 'NUMBER' },
|
{ table: 'CrontabStats', column: 'fixed_max_time', type: 'NUMBER' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -81,39 +85,58 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const repairId = 'repair-legacy-daily-statistics-v3';
|
const repairId = 'repair-legacy-daily-statistics-v3';
|
||||||
const prior = appliedIds.has('repair-legacy-daily-statistics-v2') ? 2
|
const prior = appliedIds.has('repair-legacy-daily-statistics-v2')
|
||||||
: appliedIds.has('repair-legacy-daily-statistics-v1') ? 1 : 0;
|
? 2
|
||||||
|
: appliedIds.has('repair-legacy-daily-statistics-v1')
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
const retentionId = 'preserve-cron-stat-retention-v1';
|
const retentionId = 'preserve-cron-stat-retention-v1';
|
||||||
if (!appliedIds.has(retentionId)) {
|
if (!appliedIds.has(retentionId)) {
|
||||||
if (prior || appliedIds.has(repairId)) {
|
if (prior || appliedIds.has(repairId)) {
|
||||||
// Old cleanup removed complete date prefixes but kept no cutoff. Every
|
// Old cleanup removed complete date prefixes but kept no cutoff. Every
|
||||||
// surviving date and yesterday (the minimum supported retention) is
|
// surviving date and yesterday (the minimum supported retention) is
|
||||||
// safe to keep. Older empty dates cannot be distinguished from deletions.
|
// safe to keep. Older empty dates cannot be distinguished from deletions.
|
||||||
await database.query(`INSERT OR IGNORE INTO CronStatRetention(id,first_day)
|
await database.query(
|
||||||
|
`INSERT OR IGNORE INTO CronStatRetention(id,first_day)
|
||||||
SELECT 1, MIN(COALESCE(MIN(date),$yesterday),$yesterday) FROM CrontabStats`,
|
SELECT 1, MIN(COALESCE(MIN(date),$yesterday),$yesterday) FROM CrontabStats`,
|
||||||
{ bind: { yesterday: dayjs().subtract(1,'day').format('YYYY-MM-DD') }, transaction });
|
{
|
||||||
|
bind: {
|
||||||
|
yesterday: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
await database.query(
|
||||||
{ bind: { id: retentionId }, transaction });
|
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||||
|
{ bind: { id: retentionId }, transaction },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!appliedIds.has(repairId)) {
|
if (!appliedIds.has(repairId)) {
|
||||||
await repairLegacyDailyStatistics(database, transaction, prior);
|
await repairLegacyDailyStatistics(database, transaction, prior);
|
||||||
// This reconciliation includes v1 and v2. Record all on fresh installations
|
// This reconciliation includes v1 and v2. Record all on fresh installations
|
||||||
// so rolling back and upgrading again cannot replay the superseded repair.
|
// so rolling back and upgrading again cannot replay the superseded repair.
|
||||||
await database.query(`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
|
await database.query(
|
||||||
|
`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
|
||||||
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
|
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
|
||||||
{ transaction, bind: { id: repairId } });
|
{ transaction, bind: { id: repairId } },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!appliedIds.has(prunedExitMigrationId)) {
|
if (!appliedIds.has(prunedExitMigrationId)) {
|
||||||
// Earlier versions could reclaim the last file before upgrading. The
|
// Earlier versions could reclaim the last file before upgrading. The
|
||||||
// surviving bound booking still identifies the original exit exactly.
|
// surviving bound booking still identifies the original exit exactly.
|
||||||
await database.query(`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at)
|
await database.query(
|
||||||
|
`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at)
|
||||||
SELECT b.trigger_id,b.outcome,b.finished_at FROM CronLegacyExitBookings b
|
SELECT b.trigger_id,b.outcome,b.finished_at FROM CronLegacyExitBookings b
|
||||||
WHERE b.bound=1 AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=b.trigger_id)
|
WHERE b.bound=1 AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=b.trigger_id)
|
||||||
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`, { transaction });
|
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`,
|
||||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
{ transaction },
|
||||||
{ bind: { id: prunedExitMigrationId }, transaction });
|
);
|
||||||
|
await database.query(
|
||||||
|
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||||
|
{ bind: { id: prunedExitMigrationId }, transaction },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Older databases can contain non-JSON values in Envs.labels. Sequelize
|
// Older databases can contain non-JSON values in Envs.labels. Sequelize
|
||||||
+1
-1
@@ -9,7 +9,7 @@ import { CrontabViewModel } from '../data/cronView';
|
|||||||
import { CrontabStatModel } from '../data/cronStats';
|
import { CrontabStatModel } from '../data/cronStats';
|
||||||
import { RunningInstanceModel } from '../data/runningInstance';
|
import { RunningInstanceModel } from '../data/runningInstance';
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
import { migrateSchema } from '../shared/schemaMigrations';
|
import { migrateSchema } from '../data/schemaMigrations';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -120,7 +120,9 @@ export default ({ app }: { app: Application }) => {
|
|||||||
)) ||
|
)) ||
|
||||||
(['scripts', 'logs'].includes(key || '') &&
|
(['scripts', 'logs'].includes(key || '') &&
|
||||||
req.method === 'POST' &&
|
req.method === 'POST' &&
|
||||||
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(pathLower));
|
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(
|
||||||
|
pathLower,
|
||||||
|
));
|
||||||
const hasNamespaceScope =
|
const hasNamespaceScope =
|
||||||
doc.scopes.includes(key as AppScope) ||
|
doc.scopes.includes(key as AppScope) ||
|
||||||
([
|
([
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import OpenService from '../services/open';
|
|||||||
import { shareStore } from '../shared/store';
|
import { shareStore } from '../shared/store';
|
||||||
import Logger from './logger';
|
import Logger from './logger';
|
||||||
import cronClient from '../schedule/client';
|
import cronClient from '../schedule/client';
|
||||||
import { TriggerHistory } from '../shared/triggerHistory';
|
import { TriggerHistory } from '../cron/history';
|
||||||
import { setLang, systemLang } from '../shared/i18n';
|
import { setLang, systemLang } from '../shared/i18n';
|
||||||
|
|
||||||
export default async () => {
|
export default async () => {
|
||||||
@@ -124,7 +124,8 @@ export default async () => {
|
|||||||
const history = new TriggerHistory(CrontabModel.sequelize!);
|
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||||
const pendingStops = await history.pendingStops();
|
const pendingStops = await history.pendingStops();
|
||||||
const pendingBatches = await history.pendingStopBatches();
|
const pendingBatches = await history.pendingStopBatches();
|
||||||
if (pendingStops.length || pendingBatches.length) await cronService.resumePendingStops(history, pendingStops, pendingBatches);
|
if (pendingStops.length || pendingBatches.length)
|
||||||
|
await cronService.resumePendingStops(history, pendingStops, pendingBatches);
|
||||||
await history.reconcileInstances();
|
await history.reconcileInstances();
|
||||||
|
|
||||||
// 初始化时执行一次所有的 ql repo 任务
|
// 初始化时执行一次所有的 ql repo 任务
|
||||||
@@ -213,7 +214,7 @@ export default async () => {
|
|||||||
if (!langEnvExist) {
|
if (!langEnvExist) {
|
||||||
await writeFile(config.langEnvFile, `export QL_LANG='${lang}'\n`);
|
await writeFile(config.langEnvFile, `export QL_LANG='${lang}'\n`);
|
||||||
}
|
}
|
||||||
} catch { }
|
} catch {}
|
||||||
|
|
||||||
// Replace legacy task environment files before recovered tasks can run.
|
// Replace legacy task environment files before recovered tasks can run.
|
||||||
await envService.set_envs();
|
await envService.set_envs();
|
||||||
|
|||||||
@@ -10,8 +10,7 @@ export default function protectedPathCase(
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
originalPath !== normalizedPath &&
|
originalPath !== normalizedPath &&
|
||||||
(normalizedPath.startsWith('/api/') ||
|
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))
|
||||||
normalizedPath.startsWith('/open/'))
|
|
||||||
) {
|
) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
code: 400,
|
code: 400,
|
||||||
|
|||||||
+1058
-435
File diff suppressed because it is too large.
Load diff
+214
-93
@@ -5,7 +5,7 @@
|
|||||||
// source: back/protos/cron.proto
|
// source: back/protos/cron.proto
|
||||||
|
|
||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
import { BinaryReader, BinaryWriter } from '@bufbuild/protobuf/wire';
|
||||||
import {
|
import {
|
||||||
type CallOptions,
|
type CallOptions,
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
@@ -17,9 +17,9 @@ import {
|
|||||||
Metadata,
|
Metadata,
|
||||||
type ServiceError,
|
type ServiceError,
|
||||||
type UntypedServiceImplementation,
|
type UntypedServiceImplementation,
|
||||||
} from "@grpc/grpc-js";
|
} from '@grpc/grpc-js';
|
||||||
|
|
||||||
export const protobufPackage = "com.ql.cron";
|
export const protobufPackage = 'com.ql.cron';
|
||||||
|
|
||||||
export interface ISchedule {
|
export interface ISchedule {
|
||||||
schedule: string;
|
schedule: string;
|
||||||
@@ -42,15 +42,13 @@ export interface AddCronRequest {
|
|||||||
replace: boolean;
|
replace: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AddCronResponse {
|
export interface AddCronResponse {}
|
||||||
}
|
|
||||||
|
|
||||||
export interface DeleteCronRequest {
|
export interface DeleteCronRequest {
|
||||||
ids: string[];
|
ids: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DeleteCronResponse {
|
export interface DeleteCronResponse {}
|
||||||
}
|
|
||||||
|
|
||||||
/** Zero restores the default limit. */
|
/** Zero restores the default limit. */
|
||||||
export interface SetConcurrencyRequest {
|
export interface SetConcurrencyRequest {
|
||||||
@@ -58,19 +56,23 @@ export interface SetConcurrencyRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createBaseISchedule(): ISchedule {
|
function createBaseISchedule(): ISchedule {
|
||||||
return { schedule: "" };
|
return { schedule: '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ISchedule: MessageFns<ISchedule> = {
|
export const ISchedule: MessageFns<ISchedule> = {
|
||||||
encode(message: ISchedule, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
if (message.schedule !== "") {
|
message: ISchedule,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
|
if (message.schedule !== '') {
|
||||||
writer.uint32(10).string(message.schedule);
|
writer.uint32(10).string(message.schedule);
|
||||||
}
|
}
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): ISchedule {
|
decode(input: BinaryReader | Uint8Array, length?: number): ISchedule {
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseISchedule();
|
const message = createBaseISchedule();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -94,12 +96,16 @@ export const ISchedule: MessageFns<ISchedule> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): ISchedule {
|
fromJSON(object: any): ISchedule {
|
||||||
return { schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "" };
|
return {
|
||||||
|
schedule: isSet(object.schedule)
|
||||||
|
? globalThis.String(object.schedule)
|
||||||
|
: '',
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: ISchedule): unknown {
|
toJSON(message: ISchedule): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
if (message.schedule !== "") {
|
if (message.schedule !== '') {
|
||||||
obj.schedule = message.schedule;
|
obj.schedule = message.schedule;
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
@@ -108,20 +114,22 @@ export const ISchedule: MessageFns<ISchedule> = {
|
|||||||
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
|
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
|
||||||
return ISchedule.fromPartial(base ?? ({} as any));
|
return ISchedule.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<ISchedule>, I>>(object: I): ISchedule {
|
fromPartial<I extends Exact<DeepPartial<ISchedule>, I>>(
|
||||||
|
object: I,
|
||||||
|
): ISchedule {
|
||||||
const message = createBaseISchedule();
|
const message = createBaseISchedule();
|
||||||
message.schedule = object.schedule ?? "";
|
message.schedule = object.schedule ?? '';
|
||||||
return message;
|
return message;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function createBaseICron(): ICron {
|
function createBaseICron(): ICron {
|
||||||
return {
|
return {
|
||||||
id: "",
|
id: '',
|
||||||
schedule: "",
|
schedule: '',
|
||||||
command: "",
|
command: '',
|
||||||
extra_schedules: [],
|
extra_schedules: [],
|
||||||
name: "",
|
name: '',
|
||||||
max_queue_wait: undefined,
|
max_queue_wait: undefined,
|
||||||
catchup_seconds: undefined,
|
catchup_seconds: undefined,
|
||||||
recovery_from: undefined,
|
recovery_from: undefined,
|
||||||
@@ -130,20 +138,23 @@ function createBaseICron(): ICron {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const ICron: MessageFns<ICron> = {
|
export const ICron: MessageFns<ICron> = {
|
||||||
encode(message: ICron, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
if (message.id !== "") {
|
message: ICron,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
|
if (message.id !== '') {
|
||||||
writer.uint32(10).string(message.id);
|
writer.uint32(10).string(message.id);
|
||||||
}
|
}
|
||||||
if (message.schedule !== "") {
|
if (message.schedule !== '') {
|
||||||
writer.uint32(18).string(message.schedule);
|
writer.uint32(18).string(message.schedule);
|
||||||
}
|
}
|
||||||
if (message.command !== "") {
|
if (message.command !== '') {
|
||||||
writer.uint32(26).string(message.command);
|
writer.uint32(26).string(message.command);
|
||||||
}
|
}
|
||||||
for (const v of message.extra_schedules) {
|
for (const v of message.extra_schedules) {
|
||||||
ISchedule.encode(v!, writer.uint32(34).fork()).join();
|
ISchedule.encode(v!, writer.uint32(34).fork()).join();
|
||||||
}
|
}
|
||||||
if (message.name !== "") {
|
if (message.name !== '') {
|
||||||
writer.uint32(42).string(message.name);
|
writer.uint32(42).string(message.name);
|
||||||
}
|
}
|
||||||
if (message.max_queue_wait !== undefined) {
|
if (message.max_queue_wait !== undefined) {
|
||||||
@@ -162,7 +173,8 @@ export const ICron: MessageFns<ICron> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): ICron {
|
decode(input: BinaryReader | Uint8Array, length?: number): ICron {
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseICron();
|
const message = createBaseICron();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -197,7 +209,9 @@ export const ICron: MessageFns<ICron> = {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
message.extra_schedules.push(ISchedule.decode(reader, reader.uint32()));
|
message.extra_schedules.push(
|
||||||
|
ISchedule.decode(reader, reader.uint32()),
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
case 5: {
|
case 5: {
|
||||||
@@ -251,35 +265,47 @@ export const ICron: MessageFns<ICron> = {
|
|||||||
|
|
||||||
fromJSON(object: any): ICron {
|
fromJSON(object: any): ICron {
|
||||||
return {
|
return {
|
||||||
id: isSet(object.id) ? globalThis.String(object.id) : "",
|
id: isSet(object.id) ? globalThis.String(object.id) : '',
|
||||||
schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "",
|
schedule: isSet(object.schedule)
|
||||||
command: isSet(object.command) ? globalThis.String(object.command) : "",
|
? globalThis.String(object.schedule)
|
||||||
|
: '',
|
||||||
|
command: isSet(object.command) ? globalThis.String(object.command) : '',
|
||||||
extra_schedules: globalThis.Array.isArray(object?.extra_schedules)
|
extra_schedules: globalThis.Array.isArray(object?.extra_schedules)
|
||||||
? object.extra_schedules.map((e: any) => ISchedule.fromJSON(e))
|
? object.extra_schedules.map((e: any) => ISchedule.fromJSON(e))
|
||||||
: [],
|
: [],
|
||||||
name: isSet(object.name) ? globalThis.String(object.name) : "",
|
name: isSet(object.name) ? globalThis.String(object.name) : '',
|
||||||
max_queue_wait: isSet(object.max_queue_wait) ? globalThis.Number(object.max_queue_wait) : undefined,
|
max_queue_wait: isSet(object.max_queue_wait)
|
||||||
catchup_seconds: isSet(object.catchup_seconds) ? globalThis.Number(object.catchup_seconds) : undefined,
|
? globalThis.Number(object.max_queue_wait)
|
||||||
recovery_from: isSet(object.recovery_from) ? globalThis.Number(object.recovery_from) : undefined,
|
: undefined,
|
||||||
skip_if_pending: isSet(object.skip_if_pending) ? globalThis.Boolean(object.skip_if_pending) : undefined,
|
catchup_seconds: isSet(object.catchup_seconds)
|
||||||
|
? globalThis.Number(object.catchup_seconds)
|
||||||
|
: undefined,
|
||||||
|
recovery_from: isSet(object.recovery_from)
|
||||||
|
? globalThis.Number(object.recovery_from)
|
||||||
|
: undefined,
|
||||||
|
skip_if_pending: isSet(object.skip_if_pending)
|
||||||
|
? globalThis.Boolean(object.skip_if_pending)
|
||||||
|
: undefined,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: ICron): unknown {
|
toJSON(message: ICron): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
if (message.id !== "") {
|
if (message.id !== '') {
|
||||||
obj.id = message.id;
|
obj.id = message.id;
|
||||||
}
|
}
|
||||||
if (message.schedule !== "") {
|
if (message.schedule !== '') {
|
||||||
obj.schedule = message.schedule;
|
obj.schedule = message.schedule;
|
||||||
}
|
}
|
||||||
if (message.command !== "") {
|
if (message.command !== '') {
|
||||||
obj.command = message.command;
|
obj.command = message.command;
|
||||||
}
|
}
|
||||||
if (message.extra_schedules?.length) {
|
if (message.extra_schedules?.length) {
|
||||||
obj.extra_schedules = message.extra_schedules.map((e) => ISchedule.toJSON(e));
|
obj.extra_schedules = message.extra_schedules.map((e) =>
|
||||||
|
ISchedule.toJSON(e),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (message.name !== "") {
|
if (message.name !== '') {
|
||||||
obj.name = message.name;
|
obj.name = message.name;
|
||||||
}
|
}
|
||||||
if (message.max_queue_wait !== undefined) {
|
if (message.max_queue_wait !== undefined) {
|
||||||
@@ -302,11 +328,12 @@ export const ICron: MessageFns<ICron> = {
|
|||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
|
fromPartial<I extends Exact<DeepPartial<ICron>, I>>(object: I): ICron {
|
||||||
const message = createBaseICron();
|
const message = createBaseICron();
|
||||||
message.id = object.id ?? "";
|
message.id = object.id ?? '';
|
||||||
message.schedule = object.schedule ?? "";
|
message.schedule = object.schedule ?? '';
|
||||||
message.command = object.command ?? "";
|
message.command = object.command ?? '';
|
||||||
message.extra_schedules = object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
|
message.extra_schedules =
|
||||||
message.name = object.name ?? "";
|
object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
|
||||||
|
message.name = object.name ?? '';
|
||||||
message.max_queue_wait = object.max_queue_wait ?? undefined;
|
message.max_queue_wait = object.max_queue_wait ?? undefined;
|
||||||
message.catchup_seconds = object.catchup_seconds ?? undefined;
|
message.catchup_seconds = object.catchup_seconds ?? undefined;
|
||||||
message.recovery_from = object.recovery_from ?? undefined;
|
message.recovery_from = object.recovery_from ?? undefined;
|
||||||
@@ -320,7 +347,10 @@ function createBaseAddCronRequest(): AddCronRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const AddCronRequest: MessageFns<AddCronRequest> = {
|
export const AddCronRequest: MessageFns<AddCronRequest> = {
|
||||||
encode(message: AddCronRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
message: AddCronRequest,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
for (const v of message.crons) {
|
for (const v of message.crons) {
|
||||||
ICron.encode(v!, writer.uint32(10).fork()).join();
|
ICron.encode(v!, writer.uint32(10).fork()).join();
|
||||||
}
|
}
|
||||||
@@ -331,7 +361,8 @@ export const AddCronRequest: MessageFns<AddCronRequest> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): AddCronRequest {
|
decode(input: BinaryReader | Uint8Array, length?: number): AddCronRequest {
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseAddCronRequest();
|
const message = createBaseAddCronRequest();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -364,8 +395,12 @@ export const AddCronRequest: MessageFns<AddCronRequest> = {
|
|||||||
|
|
||||||
fromJSON(object: any): AddCronRequest {
|
fromJSON(object: any): AddCronRequest {
|
||||||
return {
|
return {
|
||||||
crons: globalThis.Array.isArray(object?.crons) ? object.crons.map((e: any) => ICron.fromJSON(e)) : [],
|
crons: globalThis.Array.isArray(object?.crons)
|
||||||
replace: isSet(object.replace) ? globalThis.Boolean(object.replace) : false,
|
? object.crons.map((e: any) => ICron.fromJSON(e))
|
||||||
|
: [],
|
||||||
|
replace: isSet(object.replace)
|
||||||
|
? globalThis.Boolean(object.replace)
|
||||||
|
: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -380,10 +415,14 @@ export const AddCronRequest: MessageFns<AddCronRequest> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(base?: I): AddCronRequest {
|
create<I extends Exact<DeepPartial<AddCronRequest>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): AddCronRequest {
|
||||||
return AddCronRequest.fromPartial(base ?? ({} as any));
|
return AddCronRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(object: I): AddCronRequest {
|
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(
|
||||||
|
object: I,
|
||||||
|
): AddCronRequest {
|
||||||
const message = createBaseAddCronRequest();
|
const message = createBaseAddCronRequest();
|
||||||
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
|
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
|
||||||
message.replace = object.replace ?? false;
|
message.replace = object.replace ?? false;
|
||||||
@@ -396,12 +435,16 @@ function createBaseAddCronResponse(): AddCronResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const AddCronResponse: MessageFns<AddCronResponse> = {
|
export const AddCronResponse: MessageFns<AddCronResponse> = {
|
||||||
encode(_: AddCronResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
_: AddCronResponse,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): AddCronResponse {
|
decode(input: BinaryReader | Uint8Array, length?: number): AddCronResponse {
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseAddCronResponse();
|
const message = createBaseAddCronResponse();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -425,10 +468,14 @@ export const AddCronResponse: MessageFns<AddCronResponse> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(base?: I): AddCronResponse {
|
create<I extends Exact<DeepPartial<AddCronResponse>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): AddCronResponse {
|
||||||
return AddCronResponse.fromPartial(base ?? ({} as any));
|
return AddCronResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(_: I): AddCronResponse {
|
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(
|
||||||
|
_: I,
|
||||||
|
): AddCronResponse {
|
||||||
const message = createBaseAddCronResponse();
|
const message = createBaseAddCronResponse();
|
||||||
return message;
|
return message;
|
||||||
},
|
},
|
||||||
@@ -439,7 +486,10 @@ function createBaseDeleteCronRequest(): DeleteCronRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
|
export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
|
||||||
encode(message: DeleteCronRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
message: DeleteCronRequest,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
for (const v of message.ids) {
|
for (const v of message.ids) {
|
||||||
writer.uint32(10).string(v!);
|
writer.uint32(10).string(v!);
|
||||||
}
|
}
|
||||||
@@ -447,7 +497,8 @@ export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): DeleteCronRequest {
|
decode(input: BinaryReader | Uint8Array, length?: number): DeleteCronRequest {
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseDeleteCronRequest();
|
const message = createBaseDeleteCronRequest();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -471,7 +522,11 @@ export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): DeleteCronRequest {
|
fromJSON(object: any): DeleteCronRequest {
|
||||||
return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.String(e)) : [] };
|
return {
|
||||||
|
ids: globalThis.Array.isArray(object?.ids)
|
||||||
|
? object.ids.map((e: any) => globalThis.String(e))
|
||||||
|
: [],
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: DeleteCronRequest): unknown {
|
toJSON(message: DeleteCronRequest): unknown {
|
||||||
@@ -482,10 +537,14 @@ export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(base?: I): DeleteCronRequest {
|
create<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): DeleteCronRequest {
|
||||||
return DeleteCronRequest.fromPartial(base ?? ({} as any));
|
return DeleteCronRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(object: I): DeleteCronRequest {
|
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(
|
||||||
|
object: I,
|
||||||
|
): DeleteCronRequest {
|
||||||
const message = createBaseDeleteCronRequest();
|
const message = createBaseDeleteCronRequest();
|
||||||
message.ids = object.ids?.map((e) => e) || [];
|
message.ids = object.ids?.map((e) => e) || [];
|
||||||
return message;
|
return message;
|
||||||
@@ -497,12 +556,19 @@ function createBaseDeleteCronResponse(): DeleteCronResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const DeleteCronResponse: MessageFns<DeleteCronResponse> = {
|
export const DeleteCronResponse: MessageFns<DeleteCronResponse> = {
|
||||||
encode(_: DeleteCronResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
_: DeleteCronResponse,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): DeleteCronResponse {
|
decode(
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
input: BinaryReader | Uint8Array,
|
||||||
|
length?: number,
|
||||||
|
): DeleteCronResponse {
|
||||||
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseDeleteCronResponse();
|
const message = createBaseDeleteCronResponse();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -526,10 +592,14 @@ export const DeleteCronResponse: MessageFns<DeleteCronResponse> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(base?: I): DeleteCronResponse {
|
create<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): DeleteCronResponse {
|
||||||
return DeleteCronResponse.fromPartial(base ?? ({} as any));
|
return DeleteCronResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(_: I): DeleteCronResponse {
|
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(
|
||||||
|
_: I,
|
||||||
|
): DeleteCronResponse {
|
||||||
const message = createBaseDeleteCronResponse();
|
const message = createBaseDeleteCronResponse();
|
||||||
return message;
|
return message;
|
||||||
},
|
},
|
||||||
@@ -540,15 +610,22 @@ function createBaseSetConcurrencyRequest(): SetConcurrencyRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
|
export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
|
||||||
encode(message: SetConcurrencyRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
message: SetConcurrencyRequest,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
if (message.concurrency !== 0) {
|
if (message.concurrency !== 0) {
|
||||||
writer.uint32(8).int32(message.concurrency);
|
writer.uint32(8).int32(message.concurrency);
|
||||||
}
|
}
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): SetConcurrencyRequest {
|
decode(
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
input: BinaryReader | Uint8Array,
|
||||||
|
length?: number,
|
||||||
|
): SetConcurrencyRequest {
|
||||||
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseSetConcurrencyRequest();
|
const message = createBaseSetConcurrencyRequest();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -572,7 +649,11 @@ export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): SetConcurrencyRequest {
|
fromJSON(object: any): SetConcurrencyRequest {
|
||||||
return { concurrency: isSet(object.concurrency) ? globalThis.Number(object.concurrency) : 0 };
|
return {
|
||||||
|
concurrency: isSet(object.concurrency)
|
||||||
|
? globalThis.Number(object.concurrency)
|
||||||
|
: 0,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: SetConcurrencyRequest): unknown {
|
toJSON(message: SetConcurrencyRequest): unknown {
|
||||||
@@ -583,10 +664,14 @@ export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(base?: I): SetConcurrencyRequest {
|
create<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): SetConcurrencyRequest {
|
||||||
return SetConcurrencyRequest.fromPartial(base ?? ({} as any));
|
return SetConcurrencyRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(object: I): SetConcurrencyRequest {
|
fromPartial<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(
|
||||||
|
object: I,
|
||||||
|
): SetConcurrencyRequest {
|
||||||
const message = createBaseSetConcurrencyRequest();
|
const message = createBaseSetConcurrencyRequest();
|
||||||
message.concurrency = object.concurrency ?? 0;
|
message.concurrency = object.concurrency ?? 0;
|
||||||
return message;
|
return message;
|
||||||
@@ -596,30 +681,36 @@ export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
|
|||||||
export type CronService = typeof CronService;
|
export type CronService = typeof CronService;
|
||||||
export const CronService = {
|
export const CronService = {
|
||||||
addCron: {
|
addCron: {
|
||||||
path: "/com.ql.cron.Cron/addCron",
|
path: '/com.ql.cron.Cron/addCron',
|
||||||
requestStream: false,
|
requestStream: false,
|
||||||
responseStream: false,
|
responseStream: false,
|
||||||
requestSerialize: (value: AddCronRequest) => Buffer.from(AddCronRequest.encode(value).finish()),
|
requestSerialize: (value: AddCronRequest) =>
|
||||||
|
Buffer.from(AddCronRequest.encode(value).finish()),
|
||||||
requestDeserialize: (value: Buffer) => AddCronRequest.decode(value),
|
requestDeserialize: (value: Buffer) => AddCronRequest.decode(value),
|
||||||
responseSerialize: (value: AddCronResponse) => Buffer.from(AddCronResponse.encode(value).finish()),
|
responseSerialize: (value: AddCronResponse) =>
|
||||||
|
Buffer.from(AddCronResponse.encode(value).finish()),
|
||||||
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
|
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
|
||||||
},
|
},
|
||||||
delCron: {
|
delCron: {
|
||||||
path: "/com.ql.cron.Cron/delCron",
|
path: '/com.ql.cron.Cron/delCron',
|
||||||
requestStream: false,
|
requestStream: false,
|
||||||
responseStream: false,
|
responseStream: false,
|
||||||
requestSerialize: (value: DeleteCronRequest) => Buffer.from(DeleteCronRequest.encode(value).finish()),
|
requestSerialize: (value: DeleteCronRequest) =>
|
||||||
|
Buffer.from(DeleteCronRequest.encode(value).finish()),
|
||||||
requestDeserialize: (value: Buffer) => DeleteCronRequest.decode(value),
|
requestDeserialize: (value: Buffer) => DeleteCronRequest.decode(value),
|
||||||
responseSerialize: (value: DeleteCronResponse) => Buffer.from(DeleteCronResponse.encode(value).finish()),
|
responseSerialize: (value: DeleteCronResponse) =>
|
||||||
|
Buffer.from(DeleteCronResponse.encode(value).finish()),
|
||||||
responseDeserialize: (value: Buffer) => DeleteCronResponse.decode(value),
|
responseDeserialize: (value: Buffer) => DeleteCronResponse.decode(value),
|
||||||
},
|
},
|
||||||
setConcurrency: {
|
setConcurrency: {
|
||||||
path: "/com.ql.cron.Cron/setConcurrency",
|
path: '/com.ql.cron.Cron/setConcurrency',
|
||||||
requestStream: false,
|
requestStream: false,
|
||||||
responseStream: false,
|
responseStream: false,
|
||||||
requestSerialize: (value: SetConcurrencyRequest) => Buffer.from(SetConcurrencyRequest.encode(value).finish()),
|
requestSerialize: (value: SetConcurrencyRequest) =>
|
||||||
|
Buffer.from(SetConcurrencyRequest.encode(value).finish()),
|
||||||
requestDeserialize: (value: Buffer) => SetConcurrencyRequest.decode(value),
|
requestDeserialize: (value: Buffer) => SetConcurrencyRequest.decode(value),
|
||||||
responseSerialize: (value: AddCronResponse) => Buffer.from(AddCronResponse.encode(value).finish()),
|
responseSerialize: (value: AddCronResponse) =>
|
||||||
|
Buffer.from(AddCronResponse.encode(value).finish()),
|
||||||
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
|
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
@@ -648,18 +739,27 @@ export interface CronClient extends Client {
|
|||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
delCron(
|
delCron(
|
||||||
request: DeleteCronRequest,
|
request: DeleteCronRequest,
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: DeleteCronResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
delCron(
|
delCron(
|
||||||
request: DeleteCronRequest,
|
request: DeleteCronRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: DeleteCronResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
delCron(
|
delCron(
|
||||||
request: DeleteCronRequest,
|
request: DeleteCronRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
options: Partial<CallOptions>,
|
options: Partial<CallOptions>,
|
||||||
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: DeleteCronResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
setConcurrency(
|
setConcurrency(
|
||||||
request: SetConcurrencyRequest,
|
request: SetConcurrencyRequest,
|
||||||
@@ -678,31 +778,52 @@ export interface CronClient extends Client {
|
|||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CronClient = makeGenericClientConstructor(CronService, "com.ql.cron.Cron") as unknown as {
|
export const CronClient = makeGenericClientConstructor(
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CronClient;
|
CronService,
|
||||||
|
'com.ql.cron.Cron',
|
||||||
|
) as unknown as {
|
||||||
|
new (
|
||||||
|
address: string,
|
||||||
|
credentials: ChannelCredentials,
|
||||||
|
options?: Partial<ClientOptions>,
|
||||||
|
): CronClient;
|
||||||
service: typeof CronService;
|
service: typeof CronService;
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
type Builtin =
|
||||||
|
| Date
|
||||||
|
| Function
|
||||||
|
| Uint8Array
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| boolean
|
||||||
|
| undefined;
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
export type DeepPartial<T> = T extends Builtin
|
||||||
: T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
|
? T
|
||||||
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
: T extends globalThis.Array<infer U>
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
? globalThis.Array<DeepPartial<U>>
|
||||||
|
: T extends ReadonlyArray<infer U>
|
||||||
|
? ReadonlyArray<DeepPartial<U>>
|
||||||
|
: T extends {}
|
||||||
|
? { [K in keyof T]?: DeepPartial<T[K]> }
|
||||||
: Partial<T>;
|
: Partial<T>;
|
||||||
|
|
||||||
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
||||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
export type Exact<P, I extends P> = P extends Builtin
|
||||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
? P
|
||||||
|
: P & { [K in keyof P]: Exact<P[K], I[K]> } & {
|
||||||
|
[K in Exclude<keyof I, KeysOfUnion<P>>]: never;
|
||||||
|
};
|
||||||
|
|
||||||
function longToNumber(int64: { toString(): string }): number {
|
function longToNumber(int64: { toString(): string }): number {
|
||||||
const num = globalThis.Number(int64.toString());
|
const num = globalThis.Number(int64.toString());
|
||||||
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
||||||
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
|
throw new globalThis.Error('Value is larger than Number.MAX_SAFE_INTEGER');
|
||||||
}
|
}
|
||||||
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
||||||
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
|
throw new globalThis.Error('Value is smaller than Number.MIN_SAFE_INTEGER');
|
||||||
}
|
}
|
||||||
return num;
|
return num;
|
||||||
}
|
}
|
||||||
|
|||||||
+119
-50
@@ -5,7 +5,7 @@
|
|||||||
// source: back/protos/health.proto
|
// source: back/protos/health.proto
|
||||||
|
|
||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
|
import { BinaryReader, BinaryWriter } from '@bufbuild/protobuf/wire';
|
||||||
import {
|
import {
|
||||||
type CallOptions,
|
type CallOptions,
|
||||||
ChannelCredentials,
|
ChannelCredentials,
|
||||||
@@ -19,9 +19,9 @@ import {
|
|||||||
Metadata,
|
Metadata,
|
||||||
type ServiceError,
|
type ServiceError,
|
||||||
type UntypedServiceImplementation,
|
type UntypedServiceImplementation,
|
||||||
} from "@grpc/grpc-js";
|
} from '@grpc/grpc-js';
|
||||||
|
|
||||||
export const protobufPackage = "com.ql.health";
|
export const protobufPackage = 'com.ql.health';
|
||||||
|
|
||||||
export interface HealthCheckRequest {
|
export interface HealthCheckRequest {
|
||||||
service: string;
|
service: string;
|
||||||
@@ -39,57 +39,68 @@ export enum HealthCheckResponse_ServingStatus {
|
|||||||
UNRECOGNIZED = -1,
|
UNRECOGNIZED = -1,
|
||||||
}
|
}
|
||||||
|
|
||||||
export function healthCheckResponse_ServingStatusFromJSON(object: any): HealthCheckResponse_ServingStatus {
|
export function healthCheckResponse_ServingStatusFromJSON(
|
||||||
|
object: any,
|
||||||
|
): HealthCheckResponse_ServingStatus {
|
||||||
switch (object) {
|
switch (object) {
|
||||||
case 0:
|
case 0:
|
||||||
case "UNKNOWN":
|
case 'UNKNOWN':
|
||||||
return HealthCheckResponse_ServingStatus.UNKNOWN;
|
return HealthCheckResponse_ServingStatus.UNKNOWN;
|
||||||
case 1:
|
case 1:
|
||||||
case "SERVING":
|
case 'SERVING':
|
||||||
return HealthCheckResponse_ServingStatus.SERVING;
|
return HealthCheckResponse_ServingStatus.SERVING;
|
||||||
case 2:
|
case 2:
|
||||||
case "NOT_SERVING":
|
case 'NOT_SERVING':
|
||||||
return HealthCheckResponse_ServingStatus.NOT_SERVING;
|
return HealthCheckResponse_ServingStatus.NOT_SERVING;
|
||||||
case 3:
|
case 3:
|
||||||
case "SERVICE_UNKNOWN":
|
case 'SERVICE_UNKNOWN':
|
||||||
return HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
|
return HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
|
||||||
case -1:
|
case -1:
|
||||||
case "UNRECOGNIZED":
|
case 'UNRECOGNIZED':
|
||||||
default:
|
default:
|
||||||
return HealthCheckResponse_ServingStatus.UNRECOGNIZED;
|
return HealthCheckResponse_ServingStatus.UNRECOGNIZED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function healthCheckResponse_ServingStatusToJSON(object: HealthCheckResponse_ServingStatus): string {
|
export function healthCheckResponse_ServingStatusToJSON(
|
||||||
|
object: HealthCheckResponse_ServingStatus,
|
||||||
|
): string {
|
||||||
switch (object) {
|
switch (object) {
|
||||||
case HealthCheckResponse_ServingStatus.UNKNOWN:
|
case HealthCheckResponse_ServingStatus.UNKNOWN:
|
||||||
return "UNKNOWN";
|
return 'UNKNOWN';
|
||||||
case HealthCheckResponse_ServingStatus.SERVING:
|
case HealthCheckResponse_ServingStatus.SERVING:
|
||||||
return "SERVING";
|
return 'SERVING';
|
||||||
case HealthCheckResponse_ServingStatus.NOT_SERVING:
|
case HealthCheckResponse_ServingStatus.NOT_SERVING:
|
||||||
return "NOT_SERVING";
|
return 'NOT_SERVING';
|
||||||
case HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN:
|
case HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN:
|
||||||
return "SERVICE_UNKNOWN";
|
return 'SERVICE_UNKNOWN';
|
||||||
case HealthCheckResponse_ServingStatus.UNRECOGNIZED:
|
case HealthCheckResponse_ServingStatus.UNRECOGNIZED:
|
||||||
default:
|
default:
|
||||||
return "UNRECOGNIZED";
|
return 'UNRECOGNIZED';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function createBaseHealthCheckRequest(): HealthCheckRequest {
|
function createBaseHealthCheckRequest(): HealthCheckRequest {
|
||||||
return { service: "" };
|
return { service: '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HealthCheckRequest: MessageFns<HealthCheckRequest> = {
|
export const HealthCheckRequest: MessageFns<HealthCheckRequest> = {
|
||||||
encode(message: HealthCheckRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
if (message.service !== "") {
|
message: HealthCheckRequest,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
|
if (message.service !== '') {
|
||||||
writer.uint32(10).string(message.service);
|
writer.uint32(10).string(message.service);
|
||||||
}
|
}
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): HealthCheckRequest {
|
decode(
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
input: BinaryReader | Uint8Array,
|
||||||
|
length?: number,
|
||||||
|
): HealthCheckRequest {
|
||||||
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseHealthCheckRequest();
|
const message = createBaseHealthCheckRequest();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -113,23 +124,29 @@ export const HealthCheckRequest: MessageFns<HealthCheckRequest> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): HealthCheckRequest {
|
fromJSON(object: any): HealthCheckRequest {
|
||||||
return { service: isSet(object.service) ? globalThis.String(object.service) : "" };
|
return {
|
||||||
|
service: isSet(object.service) ? globalThis.String(object.service) : '',
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: HealthCheckRequest): unknown {
|
toJSON(message: HealthCheckRequest): unknown {
|
||||||
const obj: any = {};
|
const obj: any = {};
|
||||||
if (message.service !== "") {
|
if (message.service !== '') {
|
||||||
obj.service = message.service;
|
obj.service = message.service;
|
||||||
}
|
}
|
||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(base?: I): HealthCheckRequest {
|
create<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): HealthCheckRequest {
|
||||||
return HealthCheckRequest.fromPartial(base ?? ({} as any));
|
return HealthCheckRequest.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(object: I): HealthCheckRequest {
|
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(
|
||||||
|
object: I,
|
||||||
|
): HealthCheckRequest {
|
||||||
const message = createBaseHealthCheckRequest();
|
const message = createBaseHealthCheckRequest();
|
||||||
message.service = object.service ?? "";
|
message.service = object.service ?? '';
|
||||||
return message;
|
return message;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -139,15 +156,22 @@ function createBaseHealthCheckResponse(): HealthCheckResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
|
export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
|
||||||
encode(message: HealthCheckResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
|
encode(
|
||||||
|
message: HealthCheckResponse,
|
||||||
|
writer: BinaryWriter = new BinaryWriter(),
|
||||||
|
): BinaryWriter {
|
||||||
if (message.status !== 0) {
|
if (message.status !== 0) {
|
||||||
writer.uint32(8).int32(message.status);
|
writer.uint32(8).int32(message.status);
|
||||||
}
|
}
|
||||||
return writer;
|
return writer;
|
||||||
},
|
},
|
||||||
|
|
||||||
decode(input: BinaryReader | Uint8Array, length?: number): HealthCheckResponse {
|
decode(
|
||||||
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
|
input: BinaryReader | Uint8Array,
|
||||||
|
length?: number,
|
||||||
|
): HealthCheckResponse {
|
||||||
|
const reader =
|
||||||
|
input instanceof BinaryReader ? input : new BinaryReader(input);
|
||||||
let end = length === undefined ? reader.len : reader.pos + length;
|
let end = length === undefined ? reader.len : reader.pos + length;
|
||||||
const message = createBaseHealthCheckResponse();
|
const message = createBaseHealthCheckResponse();
|
||||||
while (reader.pos < end) {
|
while (reader.pos < end) {
|
||||||
@@ -171,7 +195,11 @@ export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
fromJSON(object: any): HealthCheckResponse {
|
fromJSON(object: any): HealthCheckResponse {
|
||||||
return { status: isSet(object.status) ? healthCheckResponse_ServingStatusFromJSON(object.status) : 0 };
|
return {
|
||||||
|
status: isSet(object.status)
|
||||||
|
? healthCheckResponse_ServingStatusFromJSON(object.status)
|
||||||
|
: 0,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
toJSON(message: HealthCheckResponse): unknown {
|
toJSON(message: HealthCheckResponse): unknown {
|
||||||
@@ -182,10 +210,14 @@ export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
|
|||||||
return obj;
|
return obj;
|
||||||
},
|
},
|
||||||
|
|
||||||
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(base?: I): HealthCheckResponse {
|
create<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(
|
||||||
|
base?: I,
|
||||||
|
): HealthCheckResponse {
|
||||||
return HealthCheckResponse.fromPartial(base ?? ({} as any));
|
return HealthCheckResponse.fromPartial(base ?? ({} as any));
|
||||||
},
|
},
|
||||||
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(object: I): HealthCheckResponse {
|
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(
|
||||||
|
object: I,
|
||||||
|
): HealthCheckResponse {
|
||||||
const message = createBaseHealthCheckResponse();
|
const message = createBaseHealthCheckResponse();
|
||||||
message.status = object.status ?? 0;
|
message.status = object.status ?? 0;
|
||||||
return message;
|
return message;
|
||||||
@@ -195,21 +227,25 @@ export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
|
|||||||
export type HealthService = typeof HealthService;
|
export type HealthService = typeof HealthService;
|
||||||
export const HealthService = {
|
export const HealthService = {
|
||||||
check: {
|
check: {
|
||||||
path: "/com.ql.health.Health/Check",
|
path: '/com.ql.health.Health/Check',
|
||||||
requestStream: false,
|
requestStream: false,
|
||||||
responseStream: false,
|
responseStream: false,
|
||||||
requestSerialize: (value: HealthCheckRequest) => Buffer.from(HealthCheckRequest.encode(value).finish()),
|
requestSerialize: (value: HealthCheckRequest) =>
|
||||||
|
Buffer.from(HealthCheckRequest.encode(value).finish()),
|
||||||
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
||||||
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
|
responseSerialize: (value: HealthCheckResponse) =>
|
||||||
|
Buffer.from(HealthCheckResponse.encode(value).finish()),
|
||||||
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
path: "/com.ql.health.Health/Watch",
|
path: '/com.ql.health.Health/Watch',
|
||||||
requestStream: false,
|
requestStream: false,
|
||||||
responseStream: true,
|
responseStream: true,
|
||||||
requestSerialize: (value: HealthCheckRequest) => Buffer.from(HealthCheckRequest.encode(value).finish()),
|
requestSerialize: (value: HealthCheckRequest) =>
|
||||||
|
Buffer.from(HealthCheckRequest.encode(value).finish()),
|
||||||
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
requestDeserialize: (value: Buffer) => HealthCheckRequest.decode(value),
|
||||||
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
|
responseSerialize: (value: HealthCheckResponse) =>
|
||||||
|
Buffer.from(HealthCheckResponse.encode(value).finish()),
|
||||||
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
@@ -222,20 +258,32 @@ export interface HealthServer extends UntypedServiceImplementation {
|
|||||||
export interface HealthClient extends Client {
|
export interface HealthClient extends Client {
|
||||||
check(
|
check(
|
||||||
request: HealthCheckRequest,
|
request: HealthCheckRequest,
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: HealthCheckResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
check(
|
check(
|
||||||
request: HealthCheckRequest,
|
request: HealthCheckRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: HealthCheckResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
check(
|
check(
|
||||||
request: HealthCheckRequest,
|
request: HealthCheckRequest,
|
||||||
metadata: Metadata,
|
metadata: Metadata,
|
||||||
options: Partial<CallOptions>,
|
options: Partial<CallOptions>,
|
||||||
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
|
callback: (
|
||||||
|
error: ServiceError | null,
|
||||||
|
response: HealthCheckResponse,
|
||||||
|
) => void,
|
||||||
): ClientUnaryCall;
|
): ClientUnaryCall;
|
||||||
watch(request: HealthCheckRequest, options?: Partial<CallOptions>): ClientReadableStream<HealthCheckResponse>;
|
watch(
|
||||||
|
request: HealthCheckRequest,
|
||||||
|
options?: Partial<CallOptions>,
|
||||||
|
): ClientReadableStream<HealthCheckResponse>;
|
||||||
watch(
|
watch(
|
||||||
request: HealthCheckRequest,
|
request: HealthCheckRequest,
|
||||||
metadata?: Metadata,
|
metadata?: Metadata,
|
||||||
@@ -243,23 +291,44 @@ export interface HealthClient extends Client {
|
|||||||
): ClientReadableStream<HealthCheckResponse>;
|
): ClientReadableStream<HealthCheckResponse>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as {
|
export const HealthClient = makeGenericClientConstructor(
|
||||||
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): HealthClient;
|
HealthService,
|
||||||
|
'com.ql.health.Health',
|
||||||
|
) as unknown as {
|
||||||
|
new (
|
||||||
|
address: string,
|
||||||
|
credentials: ChannelCredentials,
|
||||||
|
options?: Partial<ClientOptions>,
|
||||||
|
): HealthClient;
|
||||||
service: typeof HealthService;
|
service: typeof HealthService;
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
|
type Builtin =
|
||||||
|
| Date
|
||||||
|
| Function
|
||||||
|
| Uint8Array
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| boolean
|
||||||
|
| undefined;
|
||||||
|
|
||||||
export type DeepPartial<T> = T extends Builtin ? T
|
export type DeepPartial<T> = T extends Builtin
|
||||||
: T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
|
? T
|
||||||
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
|
: T extends globalThis.Array<infer U>
|
||||||
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
|
? globalThis.Array<DeepPartial<U>>
|
||||||
|
: T extends ReadonlyArray<infer U>
|
||||||
|
? ReadonlyArray<DeepPartial<U>>
|
||||||
|
: T extends {}
|
||||||
|
? { [K in keyof T]?: DeepPartial<T[K]> }
|
||||||
: Partial<T>;
|
: Partial<T>;
|
||||||
|
|
||||||
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
type KeysOfUnion<T> = T extends T ? keyof T : never;
|
||||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
export type Exact<P, I extends P> = P extends Builtin
|
||||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
? P
|
||||||
|
: P & { [K in keyof P]: Exact<P[K], I[K]> } & {
|
||||||
|
[K in Exclude<keyof I, KeysOfUnion<P>>]: never;
|
||||||
|
};
|
||||||
|
|
||||||
function isSet(value: any): boolean {
|
function isSet(value: any): boolean {
|
||||||
return value !== null && value !== undefined;
|
return value !== null && value !== undefined;
|
||||||
|
|||||||
+51
-28
@@ -1,11 +1,11 @@
|
|||||||
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
|
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
|
||||||
import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
||||||
import { createCronJob, CronJob } from '../shared/cronScheduler';
|
import { createCronJob, CronJob } from '../cron/scheduling/cronScheduler';
|
||||||
import { isValidCronSchedule } from '../shared/cronSchedule';
|
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
|
||||||
import { scheduleStacks } from './data';
|
import { scheduleStacks } from './data';
|
||||||
import { latestMissedSlot } from '../shared/cronRecovery';
|
import { latestMissedSlot } from '../cron/scheduling/cronRecovery';
|
||||||
import { slotId } from '../shared/triggerHistory';
|
import { slotId } from '../cron/history';
|
||||||
import { runCron } from '../shared/runCron';
|
import { runCron } from '../cron/execution/runCron';
|
||||||
import Logger from '../loaders/logger';
|
import Logger from '../loaders/logger';
|
||||||
import { t, tf } from '../shared/i18n';
|
import { t, tf } from '../shared/i18n';
|
||||||
|
|
||||||
@@ -63,9 +63,15 @@ const addCron = (
|
|||||||
const recoveries: (() => Promise<void>)[] = [];
|
const recoveries: (() => Promise<void>)[] = [];
|
||||||
try {
|
try {
|
||||||
for (const item of desired.values()) {
|
for (const item of desired.values()) {
|
||||||
const signature = JSON.stringify([item.schedule, item.command,
|
const signature = JSON.stringify([
|
||||||
(item.extra_schedules || []).map((s) => s.schedule), item.max_queue_wait || 0,
|
item.schedule,
|
||||||
!!item.skip_if_pending, item.catchup_seconds || 0, item.catchup_seconds || item.skip_if_pending ? item.recovery_from : 0]);
|
item.command,
|
||||||
|
(item.extra_schedules || []).map((s) => s.schedule),
|
||||||
|
item.max_queue_wait || 0,
|
||||||
|
!!item.skip_if_pending,
|
||||||
|
item.catchup_seconds || 0,
|
||||||
|
item.catchup_seconds || item.skip_if_pending ? item.recovery_from : 0,
|
||||||
|
]);
|
||||||
const current = scheduleStacks.get(item.id);
|
const current = scheduleStacks.get(item.id);
|
||||||
if (current && definitions.get(current) === signature) continue;
|
if (current && definitions.get(current) === signature) continue;
|
||||||
const jobs: CronJob[] = [];
|
const jobs: CronJob[] = [];
|
||||||
@@ -75,31 +81,44 @@ const addCron = (
|
|||||||
item.schedule,
|
item.schedule,
|
||||||
...(item.extra_schedules || []).map((x) => x.schedule),
|
...(item.extra_schedules || []).map((x) => x.schedule),
|
||||||
].entries()) {
|
].entries()) {
|
||||||
const fire = async (date: Date, source: 'node' | 'recovery' = 'node') => {
|
const fire = async (
|
||||||
|
date: Date,
|
||||||
|
source: 'node' | 'recovery' = 'node',
|
||||||
|
) => {
|
||||||
const isCurrent = () => scheduleStacks.get(item.id) === jobs;
|
const isCurrent = () => scheduleStacks.get(item.id) === jobs;
|
||||||
if (!isCurrent()) return;
|
if (!isCurrent()) return;
|
||||||
await runCron(item.command, item, isCurrent, date && {
|
await runCron(
|
||||||
id: slotId(item.id, ruleIndex, schedule, +date), time: +date, source,
|
item.command,
|
||||||
});
|
item,
|
||||||
|
isCurrent,
|
||||||
|
date && {
|
||||||
|
id: slotId(item.id, ruleIndex, schedule, +date),
|
||||||
|
time: +date,
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
);
|
||||||
};
|
};
|
||||||
if (call.request.replace && item.catchup_seconds && item.recovery_from) {
|
if (
|
||||||
|
call.request.replace &&
|
||||||
|
item.catchup_seconds &&
|
||||||
|
item.recovery_from
|
||||||
|
) {
|
||||||
recoveries.push(async () => {
|
recoveries.push(async () => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const since = Math.max(item.recovery_from!, now - item.catchup_seconds! * 1000);
|
const since = Math.max(
|
||||||
|
item.recovery_from!,
|
||||||
|
now - item.catchup_seconds! * 1000,
|
||||||
|
);
|
||||||
const time = latestMissedSlot(schedule, since, now);
|
const time = latestMissedSlot(schedule, since, now);
|
||||||
if (time !== null) await fire(new Date(time), 'recovery');
|
if (time !== null) await fire(new Date(time), 'recovery');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
jobs.push(
|
jobs.push(
|
||||||
createCronJob(
|
createCronJob(schedule, fire, {
|
||||||
schedule,
|
name: `${item.id}: ${item.name || ''}`,
|
||||||
fire,
|
logger: Logger,
|
||||||
{
|
start: false,
|
||||||
name: `${item.id}: ${item.name || ''}`,
|
}),
|
||||||
logger: Logger,
|
|
||||||
start: false,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,13 +153,17 @@ const addCron = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
callback(null, null);
|
callback(null, null);
|
||||||
for (const recover of recoveries) setImmediate(() => recover().catch((err) => Logger.error(String(err))));
|
for (const recover of recoveries)
|
||||||
|
setImmediate(() => recover().catch((err) => Logger.error(String(err))));
|
||||||
};
|
};
|
||||||
if (savePlan) {
|
if (savePlan) {
|
||||||
savePlan().then(activate).catch(error => {
|
savePlan()
|
||||||
for (const jobs of prepared.values()) jobs.forEach(job => job.cancel());
|
.then(activate)
|
||||||
callback(error);
|
.catch((error) => {
|
||||||
});
|
for (const jobs of prepared.values())
|
||||||
|
jobs.forEach((job) => job.cancel());
|
||||||
|
callback(error);
|
||||||
|
});
|
||||||
} else activate();
|
} else activate();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+42
-19
@@ -10,7 +10,7 @@ import config from '../config';
|
|||||||
import { getGrpcCerts } from '../config/grpcCerts';
|
import { getGrpcCerts } from '../config/grpcCerts';
|
||||||
|
|
||||||
import { HealthService } from '../protos/health';
|
import { HealthService } from '../protos/health';
|
||||||
import { SchedulerReadiness } from '../shared/schedulerReadiness';
|
import { SchedulerReadiness } from '../cron/scheduling/schedulerReadiness';
|
||||||
|
|
||||||
class Client {
|
class Client {
|
||||||
readonly readiness = new SchedulerReadiness(() => this.probe());
|
readonly readiness = new SchedulerReadiness(() => this.probe());
|
||||||
@@ -19,14 +19,14 @@ class Client {
|
|||||||
try {
|
try {
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
this.client.waitForReady(Date.now() + timeoutMs, (err) =>
|
this.client.waitForReady(Date.now() + timeoutMs, (err) =>
|
||||||
err ? reject(err) : resolve()
|
err ? reject(err) : resolve(),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.readiness.invalidate();
|
this.readiness.invalidate();
|
||||||
throw Object.assign(
|
throw Object.assign(
|
||||||
error instanceof Error ? error : new Error(String(error)),
|
error instanceof Error ? error : new Error(String(error)),
|
||||||
{ status: 503 }
|
{ status: 503 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,12 @@ class Client {
|
|||||||
HealthService.check.responseDeserialize,
|
HealthService.check.responseDeserialize,
|
||||||
{ service: 'scheduler' },
|
{ service: 'scheduler' },
|
||||||
{ deadline: Date.now() + 1000 },
|
{ deadline: Date.now() + 1000 },
|
||||||
(err, res) => err ? reject(err) : res?.status === 1 ? resolve() : reject(new Error('Scheduler unavailable')),
|
(err, res) =>
|
||||||
|
err
|
||||||
|
? reject(err)
|
||||||
|
: res?.status === 1
|
||||||
|
? resolve()
|
||||||
|
: reject(new Error('Scheduler unavailable')),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -66,10 +71,15 @@ class Client {
|
|||||||
await this.waitForReady(2000);
|
await this.waitForReady(2000);
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.client.setConcurrency(
|
this.client.setConcurrency(
|
||||||
{ concurrency }, new Metadata(), { deadline: Date.now() + 5000 },
|
{ concurrency },
|
||||||
|
new Metadata(),
|
||||||
|
{ deadline: Date.now() + 5000 },
|
||||||
(err) => {
|
(err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
if (err.code === status.UNAVAILABLE || err.code === status.DEADLINE_EXCEEDED) {
|
if (
|
||||||
|
err.code === status.UNAVAILABLE ||
|
||||||
|
err.code === status.DEADLINE_EXCEEDED
|
||||||
|
) {
|
||||||
this.readiness.invalidate();
|
this.readiness.invalidate();
|
||||||
Object.assign(err, { status: 503 });
|
Object.assign(err, { status: 503 });
|
||||||
}
|
}
|
||||||
@@ -83,7 +93,7 @@ class Client {
|
|||||||
|
|
||||||
async addCron(
|
async addCron(
|
||||||
request: AddCronRequest['crons'],
|
request: AddCronRequest['crons'],
|
||||||
replace = false
|
replace = false,
|
||||||
): Promise<AddCronResponse> {
|
): Promise<AddCronResponse> {
|
||||||
await this.waitForReady(2000);
|
await this.waitForReady(2000);
|
||||||
// Include every rule in a recovery snapshot, but bound a stuck worker.
|
// Include every rule in a recovery snapshot, but bound a stuck worker.
|
||||||
@@ -99,7 +109,10 @@ class Client {
|
|||||||
{ deadline: Date.now() + registrationTimeoutMs },
|
{ deadline: Date.now() + registrationTimeoutMs },
|
||||||
(err, res) => {
|
(err, res) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
if (err.code === status.UNAVAILABLE || err.code === status.DEADLINE_EXCEEDED) {
|
if (
|
||||||
|
err.code === status.UNAVAILABLE ||
|
||||||
|
err.code === status.DEADLINE_EXCEEDED
|
||||||
|
) {
|
||||||
// A timed-out write may already have reached the scheduler.
|
// A timed-out write may already have reached the scheduler.
|
||||||
// Reconcile its state from the DB instead of replaying the RPC.
|
// Reconcile its state from the DB instead of replaying the RPC.
|
||||||
this.readiness.invalidate();
|
this.readiness.invalidate();
|
||||||
@@ -108,24 +121,34 @@ class Client {
|
|||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
resolve(res);
|
resolve(res);
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async delCron(request: DeleteCronRequest['ids']): Promise<DeleteCronResponse> {
|
async delCron(
|
||||||
|
request: DeleteCronRequest['ids'],
|
||||||
|
): Promise<DeleteCronResponse> {
|
||||||
await this.waitForReady(2000);
|
await this.waitForReady(2000);
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.client.delCron({ ids: request }, new Metadata(), { deadline: Date.now() + 5000 }, (err, res) => {
|
this.client.delCron(
|
||||||
if (err) {
|
{ ids: request },
|
||||||
if (err.code === status.UNAVAILABLE || err.code === status.DEADLINE_EXCEEDED) {
|
new Metadata(),
|
||||||
this.readiness.invalidate();
|
{ deadline: Date.now() + 5000 },
|
||||||
Object.assign(err, { status: 503 });
|
(err, res) => {
|
||||||
|
if (err) {
|
||||||
|
if (
|
||||||
|
err.code === status.UNAVAILABLE ||
|
||||||
|
err.code === status.DEADLINE_EXCEEDED
|
||||||
|
) {
|
||||||
|
this.readiness.invalidate();
|
||||||
|
Object.assign(err, { status: 503 });
|
||||||
|
}
|
||||||
|
return reject(err);
|
||||||
}
|
}
|
||||||
return reject(err);
|
resolve(res);
|
||||||
}
|
},
|
||||||
resolve(res);
|
);
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { CronJob } from '../shared/cronScheduler';
|
import { CronJob } from '../cron/scheduling/cronScheduler';
|
||||||
import { ToadScheduler } from 'toad-scheduler';
|
import { ToadScheduler } from 'toad-scheduler';
|
||||||
|
|
||||||
export const scheduleStacks = new Map<string, CronJob[]>();
|
export const scheduleStacks = new Map<string, CronJob[]>();
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ import {
|
|||||||
import { addCron } from './addCron';
|
import { addCron } from './addCron';
|
||||||
import { delCron } from './delCron';
|
import { delCron } from './delCron';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { saveSchedulePlan, confirmSchedulePlan } from '../shared/scheduleAudit';
|
import {
|
||||||
|
saveSchedulePlan,
|
||||||
|
confirmSchedulePlan,
|
||||||
|
} from '../cron/scheduling/scheduleAudit';
|
||||||
|
|
||||||
// Keep acknowledgement, publication and timer replacement in request order,
|
// Keep acknowledgement, publication and timer replacement in request order,
|
||||||
// even if the client times out and sends a replacement snapshot.
|
// even if the client times out and sends a replacement snapshot.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
|
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import { AddCronResponse, SetConcurrencyRequest } from '../protos/cron';
|
import { AddCronResponse, SetConcurrencyRequest } from '../protos/cron';
|
||||||
import taskLimit from '../shared/pLimit';
|
import taskLimit from '../cron/execution/cronLimit';
|
||||||
|
|
||||||
export async function setConcurrency(
|
export async function setConcurrency(
|
||||||
call: ServerUnaryCall<SetConcurrencyRequest, AddCronResponse>,
|
call: ServerUnaryCall<SetConcurrencyRequest, AddCronResponse>,
|
||||||
|
|||||||
+281
-859
File diff suppressed because it is too large.
Load diff
@@ -21,7 +21,7 @@ import {
|
|||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class EnvService {
|
export default class EnvService {
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public async create(payloads: Env[]): Promise<Env[]> {
|
public async create(payloads: Env[]): Promise<Env[]> {
|
||||||
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
||||||
@@ -277,9 +277,9 @@ export default class EnvService {
|
|||||||
.replace(/'/g, "'\\''")
|
.replace(/'/g, "'\\''")
|
||||||
.trim();
|
.trim();
|
||||||
env_string += `export ${key}='${value}'\n`;
|
env_string += `export ${key}='${value}'\n`;
|
||||||
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
|
js_env_string += `process.env[${JSON.stringify(
|
||||||
group.map((x) => x.value).join('&'),
|
key,
|
||||||
)};\n`;
|
)}]=${JSON.stringify(group.map((x) => x.value).join('&'))};\n`;
|
||||||
// Serialize data instead of constructing an escaped Python literal.
|
// Serialize data instead of constructing an escaped Python literal.
|
||||||
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
|
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
|
||||||
JSON.stringify(group.map((x) => x.value).join('&')),
|
JSON.stringify(group.map((x) => x.value).join('&')),
|
||||||
|
|||||||
+20
-6
@@ -27,20 +27,29 @@ export class GrpcServerService {
|
|||||||
async initialize() {
|
async initialize() {
|
||||||
try {
|
try {
|
||||||
this.server.addService(HealthService, { check });
|
this.server.addService(HealthService, { check });
|
||||||
this.server.addService(CronService, { addCron: registeredAdd, delCron: registeredDelete, setConcurrency });
|
this.server.addService(CronService, {
|
||||||
|
addCron: registeredAdd,
|
||||||
|
delCron: registeredDelete,
|
||||||
|
setConcurrency,
|
||||||
|
});
|
||||||
this.server.addService(ApiService, Api);
|
this.server.addService(ApiService, Api);
|
||||||
|
|
||||||
const tlsConfig = await initGrpcCerts();
|
const tlsConfig = await initGrpcCerts();
|
||||||
const credentials = ServerCredentials.createSsl(
|
const credentials = ServerCredentials.createSsl(
|
||||||
Buffer.from(tlsConfig.caCert),
|
Buffer.from(tlsConfig.caCert),
|
||||||
[{ cert_chain: Buffer.from(tlsConfig.serverCert), private_key: Buffer.from(tlsConfig.serverKey) }],
|
[
|
||||||
|
{
|
||||||
|
cert_chain: Buffer.from(tlsConfig.serverCert),
|
||||||
|
private_key: Buffer.from(tlsConfig.serverKey),
|
||||||
|
},
|
||||||
|
],
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
const grpcPort = config.grpcPort;
|
const grpcPort = config.grpcPort;
|
||||||
const hostsToTry = [
|
const hostsToTry = [
|
||||||
config.bindHostGrpc,
|
config.bindHostGrpc,
|
||||||
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : [])
|
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : []),
|
||||||
];
|
];
|
||||||
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
|
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
|
||||||
|
|
||||||
@@ -50,15 +59,20 @@ export class GrpcServerService {
|
|||||||
try {
|
try {
|
||||||
const address = this.formatGrpcAddress(host, grpcPort);
|
const address = this.formatGrpcAddress(host, grpcPort);
|
||||||
const boundPort = await bindAsync(address, credentials);
|
const boundPort = await bindAsync(address, credentials);
|
||||||
Logger.debug(`[boot] gRPC service started successfully on ${address}`);
|
Logger.debug(
|
||||||
|
`[boot] gRPC service started successfully on ${address}`,
|
||||||
|
);
|
||||||
metricsService.record('grpc_service_start', 1, {
|
metricsService.record('grpc_service_start', 1, {
|
||||||
port: grpcPort.toString(),
|
port: grpcPort.toString(),
|
||||||
host
|
host,
|
||||||
});
|
});
|
||||||
return boundPort;
|
return boundPort;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
lastError = err as Error;
|
lastError = err as Error;
|
||||||
Logger.warn(`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`, err);
|
Logger.warn(
|
||||||
|
`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`,
|
||||||
|
err,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-12
@@ -12,7 +12,7 @@ export class HttpServerService {
|
|||||||
async initialize(expressApp: express.Application, port: number) {
|
async initialize(expressApp: express.Application, port: number) {
|
||||||
const hostsToTry = [
|
const hostsToTry = [
|
||||||
config.bindHost,
|
config.bindHost,
|
||||||
...(config.bindHost === '::' ? ['0.0.0.0'] : [])
|
...(config.bindHost === '::' ? ['0.0.0.0'] : []),
|
||||||
];
|
];
|
||||||
|
|
||||||
let lastError: Error | null = null;
|
let lastError: Error | null = null;
|
||||||
@@ -20,16 +20,21 @@ export class HttpServerService {
|
|||||||
for (const host of hostsToTry) {
|
for (const host of hostsToTry) {
|
||||||
try {
|
try {
|
||||||
const server = await this.tryListen(expressApp, port, host);
|
const server = await this.tryListen(expressApp, port, host);
|
||||||
Logger.debug(`[boot] HTTP service started successfully on ${host}:${port}`);
|
Logger.debug(
|
||||||
|
`[boot] HTTP service started successfully on ${host}:${port}`,
|
||||||
|
);
|
||||||
metricsService.record('http_service_start', 1, {
|
metricsService.record('http_service_start', 1, {
|
||||||
port: port.toString(),
|
port: port.toString(),
|
||||||
host
|
host,
|
||||||
});
|
});
|
||||||
this.server = server;
|
this.server = server;
|
||||||
return server;
|
return server;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
lastError = err as Error;
|
lastError = err as Error;
|
||||||
Logger.warn(`Failed to bind HTTP on ${host}:${port}, trying next...`, err);
|
Logger.warn(
|
||||||
|
`Failed to bind HTTP on ${host}:${port}, trying next...`,
|
||||||
|
err,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,17 +42,24 @@ export class HttpServerService {
|
|||||||
throw lastError || new Error('Failed to start HTTP service');
|
throw lastError || new Error('Failed to start HTTP service');
|
||||||
}
|
}
|
||||||
|
|
||||||
private async tryListen(expressApp: express.Application, port: number, host: string): Promise<Server> {
|
private async tryListen(
|
||||||
|
expressApp: express.Application,
|
||||||
|
port: number,
|
||||||
|
host: string,
|
||||||
|
): Promise<Server> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// There is one HTTP worker; accepting here avoids primary IPC handoff
|
// There is one HTTP worker; accepting here avoids primary IPC handoff
|
||||||
// for every connection. Restore shared listening for custom clusters.
|
// for every connection. Restore shared listening for custom clusters.
|
||||||
const server = expressApp.listen({
|
const server = expressApp.listen(
|
||||||
port,
|
{
|
||||||
host,
|
port,
|
||||||
exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true',
|
host,
|
||||||
}, () => {
|
exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true',
|
||||||
resolve(server);
|
},
|
||||||
});
|
() => {
|
||||||
|
resolve(server);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
server.on('error', (err: Error) => {
|
server.on('error', (err: Error) => {
|
||||||
server.close();
|
server.close();
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ export default class LogService {
|
|||||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public checkFilePath(filePath: string, fileName: string) {
|
public checkFilePath(filePath: string, fileName: string) {
|
||||||
return resolveFileAccess(config.logPath, [filePath || '', fileName], ['.tmp']);
|
return resolveFileAccess(
|
||||||
|
config.logPath,
|
||||||
|
[filePath || '', fileName],
|
||||||
|
['.tmp'],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,16 @@
|
|||||||
import { persistNotificationAudit } from '../shared/notificationAudit';
|
import { persistNotificationAudit } from '../shared/notificationAudit';
|
||||||
import crypto from 'crypto';
|
import crypto from 'crypto';
|
||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
import { Inject, Service } from 'typedi';
|
import { Service } from 'typedi';
|
||||||
import { parseBody, parseHeaders } from '../config/util';
|
import { parseBody, parseHeaders } from '../config/util';
|
||||||
import { NotificationInfo } from '../data/notify';
|
import { NotificationInfo } from '../data/notify';
|
||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import UserService from './user';
|
import { readNotificationMode } from '../data/notificationSettings';
|
||||||
import { httpClient } from '../config/http';
|
import { httpClient } from '../config/http';
|
||||||
import { ProxyAgent } from 'undici';
|
import { ProxyAgent } from 'undici';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class NotificationService {
|
export default class NotificationService {
|
||||||
@Inject((type) => UserService)
|
|
||||||
private userService!: UserService;
|
|
||||||
|
|
||||||
private modeMap = new Map([
|
private modeMap = new Map([
|
||||||
['gotify', this.gotify],
|
['gotify', this.gotify],
|
||||||
['goCqHttpBot', this.goCqHttpBot],
|
['goCqHttpBot', this.goCqHttpBot],
|
||||||
@@ -59,7 +56,7 @@ export default class NotificationService {
|
|||||||
let type: string | undefined;
|
let type: string | undefined;
|
||||||
let success = false;
|
let success = false;
|
||||||
try {
|
try {
|
||||||
const saved = await this.userService.getNotificationMode();
|
const saved = await readNotificationMode();
|
||||||
type = notificationInfo?.type || saved.type;
|
type = notificationInfo?.type || saved.type;
|
||||||
if (type) {
|
if (type) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
|
|||||||
+71
-42
@@ -6,8 +6,8 @@ import { Service } from 'typedi';
|
|||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { CrontabStatModel } from '../data/cronStats';
|
import { CrontabStatModel } from '../data/cronStats';
|
||||||
import { sequelize } from '../data';
|
import { sequelize } from '../data';
|
||||||
import { TriggerHistory } from '../shared/triggerHistory';
|
import { TriggerHistory } from '../cron/history';
|
||||||
import { prunedExitMigrationId } from '../shared/schemaMigrations';
|
import { prunedExitMigrationId } from '../data/schemaMigrations';
|
||||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||||
import { AuthDataType, SystemModel } from '../data/system';
|
import { AuthDataType, SystemModel } from '../data/system';
|
||||||
import {
|
import {
|
||||||
@@ -27,8 +27,11 @@ function runningInstanceWhere(cutoffMs: number) {
|
|||||||
const cutoff = cutoffMs / 1000;
|
const cutoff = cutoffMs / 1000;
|
||||||
return {
|
return {
|
||||||
status: { [Op.ne]: InstanceStatus.running },
|
status: { [Op.ne]: InstanceStatus.running },
|
||||||
id: { [Op.notIn]: literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
id: {
|
||||||
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`) },
|
[Op.notIn]:
|
||||||
|
literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
||||||
|
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`),
|
||||||
|
},
|
||||||
[Op.or]: [
|
[Op.or]: [
|
||||||
{ finished_at: { [Op.lt]: cutoff } },
|
{ finished_at: { [Op.lt]: cutoff } },
|
||||||
{
|
{
|
||||||
@@ -42,8 +45,13 @@ function runningInstanceWhere(cutoffMs: number) {
|
|||||||
function retentionCutoffs(policy: RetentionPolicy) {
|
function retentionCutoffs(policy: RetentionPolicy) {
|
||||||
const now = dayjs();
|
const now = dayjs();
|
||||||
return {
|
return {
|
||||||
history: now.subtract(policy.runningInstanceRetentionDays, 'day').startOf('second').valueOf(),
|
history: now
|
||||||
firstDay: now.subtract(policy.cronStatRetentionDays, 'day').format('YYYY-MM-DD'),
|
.subtract(policy.runningInstanceRetentionDays, 'day')
|
||||||
|
.startOf('second')
|
||||||
|
.valueOf(),
|
||||||
|
firstDay: now
|
||||||
|
.subtract(policy.cronStatRetentionDays, 'day')
|
||||||
|
.format('YYYY-MM-DD'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,34 +77,38 @@ export default class RetentionService {
|
|||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async preview(request: StorageCleanupRequest, cutoffs = retentionCutoffs(normalizeRetentionPolicy(request))) {
|
public async preview(
|
||||||
|
request: StorageCleanupRequest,
|
||||||
|
cutoffs = retentionCutoffs(normalizeRetentionPolicy(request)),
|
||||||
|
) {
|
||||||
const policy = normalizeRetentionPolicy(request);
|
const policy = normalizeRetentionPolicy(request);
|
||||||
const dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
|
const dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
|
||||||
isDependenceCacheType,
|
isDependenceCacheType,
|
||||||
);
|
);
|
||||||
const [runningInstances, cronStats, dependenceCaches, triggers] = await Promise.all([
|
const [runningInstances, cronStats, dependenceCaches, triggers] =
|
||||||
policy.runningInstanceRetentionDays > 0
|
await Promise.all([
|
||||||
? RunningInstanceModel.count({
|
policy.runningInstanceRetentionDays > 0
|
||||||
where: runningInstanceWhere(cutoffs.history),
|
? RunningInstanceModel.count({
|
||||||
})
|
where: runningInstanceWhere(cutoffs.history),
|
||||||
: 0,
|
})
|
||||||
policy.cronStatRetentionDays > 0
|
: 0,
|
||||||
? CrontabStatModel.count({
|
policy.cronStatRetentionDays > 0
|
||||||
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
? CrontabStatModel.count({
|
||||||
})
|
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
||||||
: 0,
|
})
|
||||||
Promise.all(
|
: 0,
|
||||||
dependenceCacheTypes.map(async (type) => ({
|
Promise.all(
|
||||||
type,
|
dependenceCacheTypes.map(async (type) => ({
|
||||||
bytes: await getDirectorySize(
|
type,
|
||||||
path.join(config.dependenceCachePath, type),
|
bytes: await getDirectorySize(
|
||||||
),
|
path.join(config.dependenceCachePath, type),
|
||||||
})),
|
),
|
||||||
),
|
})),
|
||||||
policy.runningInstanceRetentionDays > 0
|
),
|
||||||
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
policy.runningInstanceRetentionDays > 0
|
||||||
: 0,
|
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
||||||
]);
|
: 0,
|
||||||
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
policy,
|
policy,
|
||||||
@@ -117,7 +129,10 @@ export default class RetentionService {
|
|||||||
const preview = await this.preview(request, cutoffs);
|
const preview = await this.preview(request, cutoffs);
|
||||||
const deleted = await sequelize.transaction(async (transaction) => {
|
const deleted = await sequelize.transaction(async (transaction) => {
|
||||||
const history = new TriggerHistory(sequelize);
|
const history = new TriggerHistory(sequelize);
|
||||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
if (
|
||||||
|
preview.policy.runningInstanceRetentionDays ||
|
||||||
|
preview.policy.cronStatRetentionDays
|
||||||
|
) {
|
||||||
await history.replayPublishedExits(transaction);
|
await history.replayPublishedExits(transaction);
|
||||||
}
|
}
|
||||||
const runningInstances =
|
const runningInstances =
|
||||||
@@ -130,27 +145,41 @@ export default class RetentionService {
|
|||||||
let cronStats = 0;
|
let cronStats = 0;
|
||||||
if (preview.policy.cronStatRetentionDays > 0) {
|
if (preview.policy.cronStatRetentionDays > 0) {
|
||||||
const firstDay = cutoffs.firstDay;
|
const firstDay = cutoffs.firstDay;
|
||||||
cronStats = await CrontabStatModel.destroy({ where: { date: { [Op.lt]: firstDay } }, transaction });
|
cronStats = await CrontabStatModel.destroy({
|
||||||
await sequelize.query(`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
where: { date: { [Op.lt]: firstDay } },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
await sequelize.query(
|
||||||
|
`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
||||||
ON CONFLICT(id) DO UPDATE SET first_day=MAX(first_day,excluded.first_day)`,
|
ON CONFLICT(id) DO UPDATE SET first_day=MAX(first_day,excluded.first_day)`,
|
||||||
{ bind: { firstDay }, transaction });
|
{ bind: { firstDay }, transaction },
|
||||||
await sequelize.query(`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
);
|
||||||
(SELECT first_day FROM CronStatRetention WHERE id=1)`, { transaction });
|
await sequelize.query(
|
||||||
|
`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
||||||
|
(SELECT first_day FROM CronStatRetention WHERE id=1)`,
|
||||||
|
{ transaction },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const triggers = preview.policy.runningInstanceRetentionDays > 0
|
const triggers =
|
||||||
? await history.deleteExpired(cutoffs.history, transaction)
|
preview.policy.runningInstanceRetentionDays > 0
|
||||||
: 0;
|
? await history.deleteExpired(cutoffs.history, transaction)
|
||||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
: 0;
|
||||||
|
if (
|
||||||
|
preview.policy.runningInstanceRetentionDays ||
|
||||||
|
preview.policy.cronStatRetentionDays
|
||||||
|
) {
|
||||||
// An unbound receipt's day can be wrong. A later bound receipt still
|
// An unbound receipt's day can be wrong. A later bound receipt still
|
||||||
// needs the execution-to-task link even after both visible histories expire.
|
// needs the execution-to-task link even after both visible histories expire.
|
||||||
// A writer can also win the lock before an interrupted upgrade retries.
|
// A writer can also win the lock before an interrupted upgrade retries.
|
||||||
// Keep its bound bookings until the proof-copy transaction has committed.
|
// Keep its bound bookings until the proof-copy transaction has committed.
|
||||||
await sequelize.query(`DELETE FROM CronLegacyExitBookings WHERE day <
|
await sequelize.query(
|
||||||
|
`DELETE FROM CronLegacyExitBookings WHERE day <
|
||||||
(SELECT first_day FROM CronStatRetention WHERE id=1)
|
(SELECT first_day FROM CronStatRetention WHERE id=1)
|
||||||
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
|
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
|
||||||
AND ((bound=1 AND EXISTS (SELECT 1 FROM SchemaMigrations WHERE id=$proofMigration))
|
AND ((bound=1 AND EXISTS (SELECT 1 FROM SchemaMigrations WHERE id=$proofMigration))
|
||||||
OR (bound=0 AND NOT EXISTS (SELECT 1 FROM Crontabs WHERE id=CronLegacyExitBookings.cron_id)))`,
|
OR (bound=0 AND NOT EXISTS (SELECT 1 FROM Crontabs WHERE id=CronLegacyExitBookings.cron_id)))`,
|
||||||
{ bind: { proofMigration: prunedExitMigrationId }, transaction });
|
{ bind: { proofMigration: prunedExitMigrationId }, transaction },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return { runningInstances, cronStats, triggers };
|
return { runningInstances, cronStats, triggers };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { t } from '../shared/i18n';
|
import { t } from '../shared/i18n';
|
||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import winston from 'winston';
|
import winston from 'winston';
|
||||||
import { createCronJob, CronJob } from '../shared/cronScheduler';
|
import { createCronJob, CronJob } from '../cron/scheduling/cronScheduler';
|
||||||
import { ChildProcessWithoutNullStreams } from 'child_process';
|
import { ChildProcessWithoutNullStreams } from 'child_process';
|
||||||
import {
|
import {
|
||||||
ToadScheduler,
|
ToadScheduler,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import ScheduleService, { TaskCallbacks } from './schedule';
|
|||||||
import config from '../config';
|
import config from '../config';
|
||||||
import { TASK_COMMAND } from '../config/const';
|
import { TASK_COMMAND } from '../config/const';
|
||||||
import { getFileContentByName, getPid, killTask, rmPath } from '../config/util';
|
import { getFileContentByName, getPid, killTask, rmPath } from '../config/util';
|
||||||
import taskLimit from '../shared/pLimit';
|
import taskLimit from '../cron/execution/cronLimit';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class ScriptService {
|
export default class ScriptService {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { SockMessage } from '../data/sock';
|
|||||||
export default class SockService {
|
export default class SockService {
|
||||||
private clients: Connection[] = [];
|
private clients: Connection[] = [];
|
||||||
|
|
||||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||||
|
|
||||||
public getClients() {
|
public getClients() {
|
||||||
return this.clients;
|
return this.clients;
|
||||||
|
|||||||
@@ -149,7 +149,10 @@ export default class SubscriptionService {
|
|||||||
let beforeStr = '';
|
let beforeStr = '';
|
||||||
try {
|
try {
|
||||||
if (doc.sub_before) {
|
if (doc.sub_before) {
|
||||||
await logStreamManager.write(absolutePath, `\n## ${t('执行before命令...')}\n\n`);
|
await logStreamManager.write(
|
||||||
|
absolutePath,
|
||||||
|
`\n## ${t('执行before命令...')}\n\n`,
|
||||||
|
);
|
||||||
beforeStr = await promiseExec(doc.sub_before);
|
beforeStr = await promiseExec(doc.sub_before);
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -186,7 +189,8 @@ export default class SubscriptionService {
|
|||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
afterStr =
|
afterStr =
|
||||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
(error.stderr && error.stderr.toString()) ||
|
||||||
|
JSON.stringify(error);
|
||||||
}
|
}
|
||||||
if (afterStr) {
|
if (afterStr) {
|
||||||
await logStreamManager.write(absolutePath, `${afterStr}\n`);
|
await logStreamManager.write(absolutePath, `${afterStr}\n`);
|
||||||
@@ -321,7 +325,9 @@ export default class SubscriptionService {
|
|||||||
// A URL accepted by one engine can produce an invalid name in another.
|
// A URL accepted by one engine can produce an invalid name in another.
|
||||||
// Validate each candidate independently, retaining the safe candidate.
|
// Validate each candidate independently, retaining the safe candidate.
|
||||||
if (!Object.values(names).every(isSubscriptionStorageName)) continue;
|
if (!Object.values(names).every(isSubscriptionStorageName)) continue;
|
||||||
const resolve = deleting ? resolveSubscriptionStoragePath : path.resolve;
|
const resolve = deleting
|
||||||
|
? resolveSubscriptionStoragePath
|
||||||
|
: path.resolve;
|
||||||
const scriptPath = resolve(config.scriptPath, names.script);
|
const scriptPath = resolve(config.scriptPath, names.script);
|
||||||
if (scriptPath) targets.push(scriptPath);
|
if (scriptPath) targets.push(scriptPath);
|
||||||
if (names.repo) {
|
if (names.repo) {
|
||||||
@@ -329,7 +335,10 @@ export default class SubscriptionService {
|
|||||||
if (repoPath) targets.push(repoPath);
|
if (repoPath) targets.push(repoPath);
|
||||||
}
|
}
|
||||||
if (names.raw) {
|
if (names.raw) {
|
||||||
const rawPath = resolve(path.join(config.dataPath, 'raw'), names.raw);
|
const rawPath = resolve(
|
||||||
|
path.join(config.dataPath, 'raw'),
|
||||||
|
names.raw,
|
||||||
|
);
|
||||||
if (rawPath) targets.push(rawPath);
|
if (rawPath) targets.push(rawPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -364,10 +373,11 @@ export default class SubscriptionService {
|
|||||||
for (const storagePath of new Set(storagePaths)) {
|
for (const storagePath of new Set(storagePaths)) {
|
||||||
// rm is recursive: an ancestor must also be retained if a surviving
|
// rm is recursive: an ancestor must also be retained if a surviving
|
||||||
// subscription uses a nested branch, and vice versa.
|
// subscription uses a nested branch, and vice versa.
|
||||||
const shared = retainedPaths.some((retained) =>
|
const shared = retainedPaths.some(
|
||||||
retained === storagePath ||
|
(retained) =>
|
||||||
retained.startsWith(`${storagePath}${path.sep}`) ||
|
retained === storagePath ||
|
||||||
storagePath.startsWith(`${retained}${path.sep}`),
|
retained.startsWith(`${storagePath}${path.sep}`) ||
|
||||||
|
storagePath.startsWith(`${retained}${path.sep}`),
|
||||||
);
|
);
|
||||||
if (!shared) await rmPath(storagePath);
|
if (!shared) await rmPath(storagePath);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ import {
|
|||||||
NotifyStatus,
|
NotifyStatus,
|
||||||
NotifyLogInfo,
|
NotifyLogInfo,
|
||||||
} from '../data/system';
|
} from '../data/system';
|
||||||
import taskLimit from '../shared/pLimit';
|
import taskLimit from '../cron/execution/cronLimit';
|
||||||
import cronClient from '../schedule/client';
|
import cronClient from '../schedule/client';
|
||||||
import { withSchedulerMutation } from '../shared/schedulerMutationLock';
|
import { withSchedulerMutation } from '../cron/scheduling/schedulerMutationLock';
|
||||||
import NotificationService from './notify';
|
import NotificationService from './notify';
|
||||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||||
import SockService from './sock';
|
import SockService from './sock';
|
||||||
|
|||||||
@@ -3,11 +3,18 @@ import { readFileSync } from 'fs';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
function read(file: string): string {
|
function read(file: string): string {
|
||||||
try { return readFileSync(file, 'utf8').trim(); } catch { return ''; }
|
try {
|
||||||
|
return readFileSync(file, 'utf8').trim();
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Walk ancestors too: a nested cgroup can inherit a tighter parent quota.
|
// Walk ancestors too: a nested cgroup can inherit a tighter parent quota.
|
||||||
export function containerResources(readValue = read, platform = process.platform) {
|
export function containerResources(
|
||||||
|
readValue = read,
|
||||||
|
platform = process.platform,
|
||||||
|
) {
|
||||||
const hostCpus = os.cpus().length;
|
const hostCpus = os.cpus().length;
|
||||||
const hostMemory = os.totalmem();
|
const hostMemory = os.totalmem();
|
||||||
let cpus = hostCpus;
|
let cpus = hostCpus;
|
||||||
@@ -22,17 +29,25 @@ export function containerResources(readValue = read, platform = process.platform
|
|||||||
const unified = !match[1];
|
const unified = !match[1];
|
||||||
for (const kind of ['cpu', 'memory', 'cpuset']) {
|
for (const kind of ['cpu', 'memory', 'cpuset']) {
|
||||||
if (!unified && !controllers.includes(kind)) continue;
|
if (!unified && !controllers.includes(kind)) continue;
|
||||||
const roots = unified ? ['/sys/fs/cgroup'] : [...new Set([kind, match[1]].map(k => '/sys/fs/cgroup/' + k))];
|
const roots = unified
|
||||||
|
? ['/sys/fs/cgroup']
|
||||||
|
: [...new Set([kind, match[1]].map((k) => '/sys/fs/cgroup/' + k))];
|
||||||
for (const root of roots) {
|
for (const root of roots) {
|
||||||
let dir = path.join(root, path.normalize(match[2]));
|
let dir = path.join(root, path.normalize(match[2]));
|
||||||
while (dir === root || dir.startsWith(root + '/')) {
|
while (dir === root || dir.startsWith(root + '/')) {
|
||||||
const value = (file: string) => readValue(path.join(dir, file));
|
const value = (file: string) => readValue(path.join(dir, file));
|
||||||
if (kind === 'cpu') {
|
if (kind === 'cpu') {
|
||||||
const [quota, period] = (unified ? value('cpu.max').split(/\s+/) :
|
const [quota, period] = (
|
||||||
[value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]).map(Number);
|
unified
|
||||||
if (quota > 0 && period > 0) cpus = Math.min(cpus, quota / period);
|
? value('cpu.max').split(/\s+/)
|
||||||
|
: [value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]
|
||||||
|
).map(Number);
|
||||||
|
if (quota > 0 && period > 0)
|
||||||
|
cpus = Math.min(cpus, quota / period);
|
||||||
} else if (kind === 'cpuset') {
|
} else if (kind === 'cpuset') {
|
||||||
const set = value(unified ? 'cpuset.cpus.effective' : 'cpuset.cpus');
|
const set = value(
|
||||||
|
unified ? 'cpuset.cpus.effective' : 'cpuset.cpus',
|
||||||
|
);
|
||||||
if (/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(set)) {
|
if (/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(set)) {
|
||||||
const count = set.split(',').reduce((n, range) => {
|
const count = set.split(',').reduce((n, range) => {
|
||||||
const [lo, hi] = range.split('-').map(Number);
|
const [lo, hi] = range.split('-').map(Number);
|
||||||
@@ -41,9 +56,13 @@ export function containerResources(readValue = read, platform = process.platform
|
|||||||
if (count > 0) cpus = Math.min(cpus, count);
|
if (count > 0) cpus = Math.min(cpus, count);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const limit = Number(value(unified ? 'memory.max' : 'memory.limit_in_bytes'));
|
const limit = Number(
|
||||||
|
value(unified ? 'memory.max' : 'memory.limit_in_bytes'),
|
||||||
|
);
|
||||||
if (limit > 0 && limit <= memTotal) {
|
if (limit > 0 && limit <= memTotal) {
|
||||||
const usage = value(unified ? 'memory.current' : 'memory.usage_in_bytes');
|
const usage = value(
|
||||||
|
unified ? 'memory.current' : 'memory.usage_in_bytes',
|
||||||
|
);
|
||||||
if (usage && Number.isFinite(Number(usage))) {
|
if (usage && Number.isFinite(Number(usage))) {
|
||||||
memTotal = limit;
|
memTotal = limit;
|
||||||
memFree = Math.max(0, limit - Number(usage));
|
memFree = Math.max(0, limit - Number(usage));
|
||||||
@@ -57,6 +76,12 @@ export function containerResources(readValue = read, platform = process.platform
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { cpus, memTotal, memFree, hostCpus, hostMemory,
|
return {
|
||||||
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1) };
|
cpus,
|
||||||
|
memTotal,
|
||||||
|
memFree,
|
||||||
|
hostCpus,
|
||||||
|
hostMemory,
|
||||||
|
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import { join } from 'path';
|
|
||||||
import { existsSync } from 'fs';
|
|
||||||
import { receiptPath } from './managedExit.cjs';
|
|
||||||
import { spawn } from 'cross-spawn';
|
|
||||||
import type { ChildProcessWithoutNullStreams } from 'child_process';
|
|
||||||
import type { Readable } from 'stream';
|
|
||||||
|
|
||||||
// A managed command waits on its parent's pipe. EOF before authorization exits
|
|
||||||
// without interpreting the command, even when the worker is killed by SIGKILL.
|
|
||||||
export function spawnCronCommand(command: string, triggerId?: string, onCommandStart?: (at: number) => void, outputPath?: string) {
|
|
||||||
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
|
|
||||||
const sourceScript = join(__dirname, '../../shell/cron-command.py');
|
|
||||||
const supervisor = existsSync(sourceScript) ? sourceScript : join(process.env.QL_DIR!, 'shell/cron-command.py');
|
|
||||||
const args = ['-I', '-S', supervisor, command, String(process.pid),
|
|
||||||
receiptPath(triggerId) || '', process.execPath, join(__dirname, 'managedExit.cjs'),
|
|
||||||
];
|
|
||||||
if (onCommandStart) args.push('report-start');
|
|
||||||
if (outputPath) args.push('log-output', outputPath);
|
|
||||||
const child = spawn('python3', args, { env: { ...process.env, QL_TRIGGER_ID: triggerId },
|
|
||||||
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe' }) as ChildProcessWithoutNullStreams;
|
|
||||||
if (onCommandStart && child.stdio[3]) {
|
|
||||||
const timing = child.stdio[3] as Readable;
|
|
||||||
let stamp = '';
|
|
||||||
timing.setEncoding('ascii').on('data', chunk => { stamp += chunk; });
|
|
||||||
timing.once('end', () => { if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp)); });
|
|
||||||
timing.on('error', () => {}); // Missing telemetry must not change the command result.
|
|
||||||
}
|
|
||||||
// A concurrent stop can close the pipe before the authorization write.
|
|
||||||
child.stdin.on('error', () => {});
|
|
||||||
return child;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function releaseCronCommand(child: ChildProcessWithoutNullStreams): Promise<void> {
|
|
||||||
return new Promise((resolve, reject) =>
|
|
||||||
child.stdin.end('run\n', (error?: Error) => error ? reject(error) : resolve()));
|
|
||||||
}
|
|
||||||
@@ -9,37 +9,60 @@ function isGone(error: unknown) {
|
|||||||
return code === 'ENOENT' || code === 'ENOTDIR';
|
return code === 'ENOENT' || code === 'ENOTDIR';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function directoryVersion(root: string, parent: string, blacklist: string[]) {
|
async function directoryVersion(
|
||||||
|
root: string,
|
||||||
|
parent: string,
|
||||||
|
blacklist: string[],
|
||||||
|
) {
|
||||||
const dir = parent ? resolveFileAccess(root, [parent], blacklist) : root;
|
const dir = parent ? resolveFileAccess(root, [parent], blacklist) : root;
|
||||||
const denied = () => Object.assign(new Error('Invalid directory'), { status: 403 });
|
const denied = () =>
|
||||||
|
Object.assign(new Error('Invalid directory'), { status: 403 });
|
||||||
if (!dir) throw denied();
|
if (!dir) throw denied();
|
||||||
try {
|
try {
|
||||||
if (await fs.realpath(dir) !== path.join(root, parent)) throw denied();
|
if ((await fs.realpath(dir)) !== path.join(root, parent)) throw denied();
|
||||||
const stat = await fs.lstat(dir, { bigint: true });
|
const stat = await fs.lstat(dir, { bigint: true });
|
||||||
return stat.isDirectory() ? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':') : null;
|
return stat.isDirectory()
|
||||||
|
? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':')
|
||||||
|
: null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isGone(error)) return null;
|
if (isGone(error)) return null;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function checkDirectoryVersions(root: string, blacklist: string[], versions: DirectoryVersion[]) {
|
export async function checkDirectoryVersions(
|
||||||
|
root: string,
|
||||||
|
blacklist: string[],
|
||||||
|
versions: DirectoryVersion[],
|
||||||
|
) {
|
||||||
const realRoot = await fs.realpath(root);
|
const realRoot = await fs.realpath(root);
|
||||||
const matches = await Promise.all(versions.map(async ([parent, expected]) => {
|
const matches = await Promise.all(
|
||||||
try {
|
versions.map(async ([parent, expected]) => {
|
||||||
return await directoryVersion(realRoot, parent, blacklist) === expected;
|
try {
|
||||||
} catch (error) {
|
return (
|
||||||
// A formerly accessible directory may now be a symlink outside the root.
|
(await directoryVersion(realRoot, parent, blacklist)) === expected
|
||||||
if ((error as { status?: number }).status === 403) return false;
|
);
|
||||||
throw error;
|
} catch (error) {
|
||||||
}
|
// A formerly accessible directory may now be a symlink outside the root.
|
||||||
}));
|
if ((error as { status?: number }).status === 403) return false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
return matches.every(Boolean);
|
return matches.every(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readDirectoryPage(root: string, blacklist: string[], directory: string, after: string,
|
export async function readDirectoryPage(
|
||||||
search: string, foldersOnly: boolean, newestFirst: boolean, limit = 50) {
|
root: string,
|
||||||
const blocked = new Set(blacklist.map(name => name.toLowerCase()));
|
blacklist: string[],
|
||||||
|
directory: string,
|
||||||
|
after: string,
|
||||||
|
search: string,
|
||||||
|
foldersOnly: boolean,
|
||||||
|
newestFirst: boolean,
|
||||||
|
limit = 50,
|
||||||
|
) {
|
||||||
|
const blocked = new Set(blacklist.map((name) => name.toLowerCase()));
|
||||||
const realRoot = await fs.realpath(root);
|
const realRoot = await fs.realpath(root);
|
||||||
const versions: DirectoryVersion[] = [];
|
const versions: DirectoryVersion[] = [];
|
||||||
async function entries(parent: string) {
|
async function entries(parent: string) {
|
||||||
@@ -47,36 +70,63 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
|||||||
versions.push([parent, version]);
|
versions.push([parent, version]);
|
||||||
if (version === null) return [];
|
if (version === null) return [];
|
||||||
try {
|
try {
|
||||||
return (await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })).filter(e =>
|
return (
|
||||||
!blocked.has(e.name.toLowerCase()) && (e.isDirectory() || (!foldersOnly && e.isFile())));
|
await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })
|
||||||
|
).filter(
|
||||||
|
(e) =>
|
||||||
|
!blocked.has(e.name.toLowerCase()) &&
|
||||||
|
(e.isDirectory() || (!foldersOnly && e.isFile())),
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (isGone(error)) return [];
|
if (isGone(error)) return [];
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
|
const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
||||||
const rows = [];
|
const rows = [];
|
||||||
let next: string | null = null;
|
let next: string | null = null;
|
||||||
async function row(parent: string, title: string, directory: boolean) {
|
async function row(parent: string, title: string, directory: boolean) {
|
||||||
const key = path.join(parent, title);
|
const key = path.join(parent, title);
|
||||||
if (directory) return { title, parent, key, type: 'directory', isLeaf: false };
|
if (directory)
|
||||||
|
return { title, parent, key, type: 'directory', isLeaf: false };
|
||||||
try {
|
try {
|
||||||
const stat = await fs.lstat(path.join(root, key));
|
const stat = await fs.lstat(path.join(root, key));
|
||||||
if (stat.isFile()) return { title, parent, key, type: 'file', isLeaf: true, size: stat.size };
|
if (stat.isFile())
|
||||||
} catch (error) { if (!isGone(error)) throw error; }
|
return {
|
||||||
|
title,
|
||||||
|
parent,
|
||||||
|
key,
|
||||||
|
type: 'file',
|
||||||
|
isLeaf: true,
|
||||||
|
size: stat.size,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (!isGone(error)) throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!search) {
|
if (!search) {
|
||||||
const sorted = (await entries(directory)).sort((a,b) =>
|
const sorted = (await entries(directory)).sort(
|
||||||
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
(a, b) =>
|
||||||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1));
|
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
||||||
const selected = sorted.filter(e => {
|
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1),
|
||||||
|
);
|
||||||
|
const selected = sorted.filter((e) => {
|
||||||
if (!after) return true;
|
if (!after) return true;
|
||||||
const group = e.isDirectory() ? '0' : '1';
|
const group = e.isDirectory() ? '0' : '1';
|
||||||
return group > after[0] || (group === after[0] &&
|
return (
|
||||||
compare(e.name, after.slice(1)) * (newestFirst && !e.isDirectory() ? -1 : 1) > 0);
|
group > after[0] ||
|
||||||
|
(group === after[0] &&
|
||||||
|
compare(e.name, after.slice(1)) *
|
||||||
|
(newestFirst && !e.isDirectory() ? -1 : 1) >
|
||||||
|
0)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
const page = selected.slice(0, limit);
|
const page = selected.slice(0, limit);
|
||||||
const data = (await Promise.all(page.map(e => row(directory, e.name, e.isDirectory())))).filter(Boolean);
|
const data = (
|
||||||
|
await Promise.all(
|
||||||
|
page.map((e) => row(directory, e.name, e.isDirectory())),
|
||||||
|
)
|
||||||
|
).filter(Boolean);
|
||||||
if (selected.length > limit) {
|
if (selected.length > limit) {
|
||||||
const last = page[page.length - 1];
|
const last = page[page.length - 1];
|
||||||
next = (last.isDirectory() ? '0' : '1') + last.name;
|
next = (last.isDirectory() ? '0' : '1') + last.name;
|
||||||
@@ -84,16 +134,26 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
|||||||
return { data, next, versions };
|
return { data, next, versions };
|
||||||
}
|
}
|
||||||
// Resume a depth-first search at the last visited entry, including on pages with zero matches.
|
// Resume a depth-first search at the last visited entry, including on pages with zero matches.
|
||||||
async function* walk(parent: string, resume: string[]): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
async function* walk(
|
||||||
const items = (await entries(parent)).sort((a,b) => compare(a.name,b.name));
|
parent: string,
|
||||||
|
resume: string[],
|
||||||
|
): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
||||||
|
const items = (await entries(parent)).sort((a, b) =>
|
||||||
|
compare(a.name, b.name),
|
||||||
|
);
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
if (resume.length && item.name < resume[0]) continue;
|
if (resume.length && item.name < resume[0]) continue;
|
||||||
const same = item.name === resume[0];
|
const same = item.name === resume[0];
|
||||||
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
|
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
|
||||||
if (item.isDirectory()) {
|
if (item.isDirectory()) {
|
||||||
try { yield* walk(path.join(parent, item.name), same ? resume.slice(1) : []); }
|
try {
|
||||||
catch (error) {
|
yield* walk(
|
||||||
if (!isGone(error) && (error as { status?: number }).status !== 403) throw error;
|
path.join(parent, item.name),
|
||||||
|
same ? resume.slice(1) : [],
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isGone(error) && (error as { status?: number }).status !== 403)
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,7 +165,10 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
|||||||
const item = await row(entry.parent, entry.name, entry.dir);
|
const item = await row(entry.parent, entry.name, entry.dir);
|
||||||
if (item) rows.push(item);
|
if (item) rows.push(item);
|
||||||
}
|
}
|
||||||
if (++visited >= 512 || rows.length === limit) { next = key; break; }
|
if (++visited >= 512 || rows.length === limit) {
|
||||||
|
next = key;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return { data: rows, next, versions };
|
return { data: rows, next, versions };
|
||||||
}
|
}
|
||||||
@@ -4,31 +4,66 @@ import { checkDirectoryVersions, readDirectoryPage } from './directoryPage';
|
|||||||
|
|
||||||
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
|
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
|
||||||
return [
|
return [
|
||||||
celebrate({ body: Joi.array().items(Joi.array().ordered(
|
celebrate({
|
||||||
Joi.string().allow('').max(4096).required(), Joi.string().max(128).allow(null).required(),
|
body: Joi.array()
|
||||||
).length(2)).min(1).max(128).required() }),
|
.items(
|
||||||
|
Joi.array()
|
||||||
|
.ordered(
|
||||||
|
Joi.string().allow('').max(4096).required(),
|
||||||
|
Joi.string().max(128).allow(null).required(),
|
||||||
|
)
|
||||||
|
.length(2),
|
||||||
|
)
|
||||||
|
.min(1)
|
||||||
|
.max(128)
|
||||||
|
.required(),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const current = await checkDirectoryVersions(root(), blacklist, req.body);
|
const current = await checkDirectoryVersions(
|
||||||
|
root(),
|
||||||
|
blacklist,
|
||||||
|
req.body,
|
||||||
|
);
|
||||||
res.send({ code: 200, current });
|
res.send({ code: 200, current });
|
||||||
} catch (error) { next(error); }
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function directoryPageHandler(root: () => string, blacklist: string[], newestFirst: boolean) {
|
export function directoryPageHandler(
|
||||||
|
root: () => string,
|
||||||
|
blacklist: string[],
|
||||||
|
newestFirst: boolean,
|
||||||
|
) {
|
||||||
return [
|
return [
|
||||||
celebrate({ query: Joi.object({
|
celebrate({
|
||||||
path: Joi.string().allow(''), after: Joi.string().allow(''), search: Joi.string().allow(''),
|
query: Joi.object({
|
||||||
folders: Joi.boolean(), t: Joi.string(),
|
path: Joi.string().allow(''),
|
||||||
}) }),
|
after: Joi.string().allow(''),
|
||||||
|
search: Joi.string().allow(''),
|
||||||
|
folders: Joi.boolean(),
|
||||||
|
t: Joi.string(),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
async (req: Request, res: Response, next: NextFunction) => {
|
async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const { path = '', after = '', search = '', folders } = req.query;
|
const { path = '', after = '', search = '', folders } = req.query;
|
||||||
const page = await readDirectoryPage(root(), blacklist, String(path), String(after),
|
const page = await readDirectoryPage(
|
||||||
String(search), String(folders) === 'true', newestFirst);
|
root(),
|
||||||
|
blacklist,
|
||||||
|
String(path),
|
||||||
|
String(after),
|
||||||
|
String(search),
|
||||||
|
String(folders) === 'true',
|
||||||
|
newestFirst,
|
||||||
|
);
|
||||||
res.send({ code: 200, ...page });
|
res.send({ code: 200, ...page });
|
||||||
} catch (error) { next(error); }
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -28,7 +28,9 @@ export function resolveFileAccess(
|
|||||||
// of the same entry. Check every protected name without case sensitivity.
|
// of the same entry. Check every protected name without case sensitivity.
|
||||||
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
|
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
|
||||||
const isBlocked = (relative: string) =>
|
const isBlocked = (relative: string) =>
|
||||||
relative.split(path.sep).some((part) => blockedNames.has(part.toLowerCase()));
|
relative
|
||||||
|
.split(path.sep)
|
||||||
|
.some((part) => blockedNames.has(part.toLowerCase()));
|
||||||
if (isBlocked(path.relative(resolvedRoot, target))) return '';
|
if (isBlocked(path.relative(resolvedRoot, target))) return '';
|
||||||
try {
|
try {
|
||||||
const realRoot = fs.realpathSync(resolvedRoot);
|
const realRoot = fs.realpathSync(resolvedRoot);
|
||||||
|
|||||||
+5
-3
@@ -1,8 +1,9 @@
|
|||||||
const messages: Record<string, Record<string, string>> = {
|
const messages: Record<string, Record<string, string>> = {
|
||||||
zh: {},
|
zh: {},
|
||||||
en: {
|
en: {
|
||||||
'系统定时规则安装失败,旧规则可能仍在运行,正在重试': 'System crontab installation failed. The previous rules may still run. Retrying.',
|
'系统定时规则安装失败,旧规则可能仍在运行,正在重试':
|
||||||
'Cron表达式格式有误': 'Invalid cron expression',
|
'System crontab installation failed. The previous rules may still run. Retrying.',
|
||||||
|
Cron表达式格式有误: 'Invalid cron expression',
|
||||||
'升级任务启动失败,请检查日志后重试':
|
'升级任务启动失败,请检查日志后重试':
|
||||||
'Failed to start the update. Check the logs and try again.',
|
'Failed to start the update. Check the logs and try again.',
|
||||||
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
|
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
|
||||||
@@ -264,7 +265,8 @@ const messages: Record<string, Record<string, string>> = {
|
|||||||
'执行after命令...': 'Execute after command...',
|
'执行after命令...': 'Execute after command...',
|
||||||
'## 执行结束... %s 耗时 %s 秒':
|
'## 执行结束... %s 耗时 %s 秒':
|
||||||
'## Execution finished... %s elapsed %s seconds',
|
'## Execution finished... %s elapsed %s seconds',
|
||||||
'原调度未能恢复,正在重试': 'Could not restore the previous schedule. Retrying.',
|
'原调度未能恢复,正在重试':
|
||||||
|
'Could not restore the previous schedule. Retrying.',
|
||||||
'任务已修改,请刷新后重试': 'The task has changed. Refresh and try again.',
|
'任务已修改,请刷新后重试': 'The task has changed. Refresh and try again.',
|
||||||
'调度器注册失败,任务创建已回滚':
|
'调度器注册失败,任务创建已回滚':
|
||||||
'Scheduler registration failed, task creation rolled back',
|
'Scheduler registration failed, task creation rolled back',
|
||||||
|
|||||||
+31
-19
@@ -47,18 +47,15 @@ function completeUtf8End(buffer: Buffer, start: number, end: number) {
|
|||||||
|
|
||||||
const firstByte = buffer[sequenceStart];
|
const firstByte = buffer[sequenceStart];
|
||||||
const expectedLength =
|
const expectedLength =
|
||||||
firstByte < 0x80
|
firstByte < 0x80 ? 1 : firstByte < 0xe0 ? 2 : firstByte < 0xf0 ? 3 : 4;
|
||||||
? 1
|
|
||||||
: firstByte < 0xe0
|
|
||||||
? 2
|
|
||||||
: firstByte < 0xf0
|
|
||||||
? 3
|
|
||||||
: 4;
|
|
||||||
return end - sequenceStart < expectedLength ? sequenceStart : end;
|
return end - sequenceStart < expectedLength ? sequenceStart : end;
|
||||||
}
|
}
|
||||||
|
|
||||||
function logDigest(identity: string, from: number, bytes: Buffer) {
|
function logDigest(identity: string, from: number, bytes: Buffer) {
|
||||||
return createHash('sha256').update(`${identity}:${from}:`).update(bytes).digest('hex');
|
return createHash('sha256')
|
||||||
|
.update(`${identity}:${from}:`)
|
||||||
|
.update(bytes)
|
||||||
|
.digest('hex');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readLogChunk(
|
export async function readLogChunk(
|
||||||
@@ -75,16 +72,22 @@ export async function readLogChunk(
|
|||||||
const requestedOffset = Number.isFinite(options.offset)
|
const requestedOffset = Number.isFinite(options.offset)
|
||||||
? Math.max(0, Math.trunc(options.offset!))
|
? Math.max(0, Math.trunc(options.offset!))
|
||||||
: undefined;
|
: undefined;
|
||||||
let start = options.tail || requestedOffset === undefined
|
let start =
|
||||||
? Math.max(total - limit, 0)
|
options.tail || requestedOffset === undefined
|
||||||
: Math.min(requestedOffset, total);
|
? Math.max(total - limit, 0)
|
||||||
const resume = options.cursor && !options.tail && requestedOffset !== undefined;
|
: Math.min(requestedOffset, total);
|
||||||
|
const resume =
|
||||||
|
options.cursor && !options.tail && requestedOffset !== undefined;
|
||||||
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
|
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
|
||||||
let from = resume ? Number(fromText) : start;
|
let from = resume ? Number(fromText) : start;
|
||||||
let reset = Boolean(resume && (
|
let reset = Boolean(
|
||||||
requestedOffset !== start || !Number.isSafeInteger(from) ||
|
resume &&
|
||||||
from < 0 || from > start || start - from > CURSOR_WINDOW_BYTES
|
(requestedOffset !== start ||
|
||||||
));
|
!Number.isSafeInteger(from) ||
|
||||||
|
from < 0 ||
|
||||||
|
from > start ||
|
||||||
|
start - from > CURSOR_WINDOW_BYTES),
|
||||||
|
);
|
||||||
if (reset) from = start = 0;
|
if (reset) from = start = 0;
|
||||||
|
|
||||||
// Read the previously displayed bytes and their continuation together.
|
// Read the previously displayed bytes and their continuation together.
|
||||||
@@ -97,7 +100,10 @@ export async function readLogChunk(
|
|||||||
let window = await readWindow(from, start + limit + 3);
|
let window = await readWindow(from, start + limit + 3);
|
||||||
if (resume && !reset) {
|
if (resume && !reset) {
|
||||||
const prefix = window.subarray(0, start - from);
|
const prefix = window.subarray(0, start - from);
|
||||||
if (prefix.length !== start - from || logDigest(identity, from, prefix) !== digest) {
|
if (
|
||||||
|
prefix.length !== start - from ||
|
||||||
|
logDigest(identity, from, prefix) !== digest
|
||||||
|
) {
|
||||||
reset = true;
|
reset = true;
|
||||||
start = from = 0;
|
start = from = 0;
|
||||||
window = await readWindow(0, limit + 3);
|
window = await readWindow(0, limit + 3);
|
||||||
@@ -120,8 +126,14 @@ export async function readLogChunk(
|
|||||||
let cursor: string | undefined;
|
let cursor: string | undefined;
|
||||||
if (options.follow || options.cursor) {
|
if (options.follow || options.cursor) {
|
||||||
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
|
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
|
||||||
cursor = resume && !reset && nextOffset === start ? options.cursor :
|
cursor =
|
||||||
`${retainedFrom}.${logDigest(identity, retainedFrom, window.subarray(retainedFrom - from, nextOffset - from))}`;
|
resume && !reset && nextOffset === start
|
||||||
|
? options.cursor
|
||||||
|
: `${retainedFrom}.${logDigest(
|
||||||
|
identity,
|
||||||
|
retainedFrom,
|
||||||
|
window.subarray(retainedFrom - from, nextOffset - from),
|
||||||
|
)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
+32
-371
@@ -1,390 +1,51 @@
|
|||||||
// Keep the command's actual exit available until its SQLite transaction commits.
|
// Stable supervisor entry point. Receipt storage is a separate, service-free module.
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { createHash, randomUUID } = require('node:crypto');
|
const {
|
||||||
|
parseExit,
|
||||||
|
writeExit,
|
||||||
|
receiptPath,
|
||||||
|
storageFull,
|
||||||
|
} = require('../cron/settlement/exitReceipt.cjs');
|
||||||
const idPattern = /^[a-z0-9-]{1,120}$/;
|
const idPattern = /^[a-z0-9-]{1,120}$/;
|
||||||
|
|
||||||
// A full data volume can still have room for a directory entry. In this format
|
|
||||||
// the empty file publishes the tuple atomically, including its execution-bound
|
|
||||||
// checksum. Keep the encoded name when moving it into a collector-private slot.
|
|
||||||
const metadataName = /^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
|
|
||||||
|
|
||||||
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
|
|
||||||
const legacyCapture = /^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
|
|
||||||
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
|
|
||||||
|
|
||||||
function metadataReceipt(file) {
|
|
||||||
const name = path.basename(file);
|
|
||||||
return metadataName.exec(name === '.pending.claimed' ? path.basename(path.dirname(file)) : name);
|
|
||||||
}
|
|
||||||
|
|
||||||
function storageFull(error) {
|
|
||||||
const codes = [error?.code, error?.original?.code, error?.parent?.code];
|
|
||||||
if (codes.some(code => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code))) return true;
|
|
||||||
const directory = receiptDirectory();
|
|
||||||
if (directory && codes.includes('SQLITE_CANTOPEN')) {
|
|
||||||
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
|
|
||||||
// reported ENOSPC. Other open failures keep their normal error semantics.
|
|
||||||
try {
|
|
||||||
const capacity = fs.statfsSync(path.dirname(directory));
|
|
||||||
return capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0);
|
|
||||||
} catch { return false; }
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function receiptDirectory() {
|
|
||||||
const data = process.env.QL_DATA_DIR || (process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
|
|
||||||
if (data) return path.join(data, 'db', 'cron-exits');
|
|
||||||
}
|
|
||||||
|
|
||||||
function receiptPath(id) {
|
|
||||||
const directory = receiptDirectory();
|
|
||||||
if (directory && typeof id === 'string' && idPattern.test(id)) return path.join(directory, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function listReceiptFiles(directory, prefix) {
|
|
||||||
if (!directory) return [];
|
|
||||||
try {
|
|
||||||
const entries = await fs.promises.readdir(directory, { withFileTypes: true });
|
|
||||||
const files = [];
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
|
|
||||||
const id = entry.name.slice(prefix.length);
|
|
||||||
if (idPattern.test(id)) files.push({ id, file: path.join(directory, entry.name) });
|
|
||||||
}
|
|
||||||
return files;
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code === 'ENOENT') return [];
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function publishedExits() {
|
|
||||||
return (await listReceiptFiles(receiptDirectory(), '')).map(entry => entry.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
// flock attaches to the open file description. The child inherits fd 3 and
|
|
||||||
// exits immediately. Closing the panel's handle (including on SIGKILL)
|
|
||||||
// releases the lock without leaving a lock file on a full volume.
|
|
||||||
async function lockClaim(handle, shared) {
|
|
||||||
const run = (program, args) => new Promise((resolve, reject) => {
|
|
||||||
const child = require('node:child_process').spawn(program, args, {
|
|
||||||
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
|
|
||||||
});
|
|
||||||
child.once('error', reject);
|
|
||||||
child.once('exit', (code, signal) => {
|
|
||||||
if (code === 0 || code === 1) resolve(code === 0);
|
|
||||||
else reject(new Error(`Receipt directory lock failed (${signal || code})`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code !== 'ENOENT') throw error;
|
|
||||||
// Python is also shipped with the task supervisor on minimal Linux images.
|
|
||||||
const program = 'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
|
|
||||||
(shared ? 'SH' : 'EX') + ')\nexcept BlockingIOError: sys.exit(1)';
|
|
||||||
return run('python3', ['-c', program]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move the current directory entry to a fresh, recoverable name outside the
|
|
||||||
// reusable claim directory. A writer can replace that entry without flock.
|
|
||||||
// Only the bytes actually captured by this attempt authorize its final unlink.
|
|
||||||
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
|
|
||||||
async function retireLegacyFile(id, file, booked) {
|
|
||||||
const directory = receiptDirectory();
|
|
||||||
const sourceDir = path.dirname(file);
|
|
||||||
const slot = path.basename(file);
|
|
||||||
const bound = /^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
|
|
||||||
const metadata = metadataReceipt(file);
|
|
||||||
const parent = claimName.exec(path.basename(sourceDir));
|
|
||||||
const privateSlot = path.dirname(sourceDir) === directory &&
|
|
||||||
(parent?.[2] === id && slot === (parent[1] ? '.pending.claimed' : 'receipt') ||
|
|
||||||
metadata?.[1] === id && slot === '.pending.claimed');
|
|
||||||
if (!directory || !idPattern.test(id)) return;
|
|
||||||
const dbDir = path.dirname(directory);
|
|
||||||
const localBin = path.join(directory, '.reclaim');
|
|
||||||
const fromBin = sourceDir === dbDir || sourceDir === localBin;
|
|
||||||
if (sourceDir !== directory && !privateSlot && !(fromBin && captureId(slot) === id)) return;
|
|
||||||
|
|
||||||
const matches = exit => exit && !exit.namedExit && (exit.version === 1
|
|
||||||
? booked && exit.time === booked.time && (exit.signal ?? String(exit.code)) === booked.outcome
|
|
||||||
: !bound);
|
|
||||||
let handle, binHandle;
|
|
||||||
try {
|
|
||||||
if ((privateSlot || sourceDir === localBin) && process.platform === 'linux') {
|
|
||||||
handle = await fs.promises.open(sourceDir, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
||||||
if (privateSlot && !await lockClaim(handle, true)) return;
|
|
||||||
}
|
|
||||||
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
|
|
||||||
// A canonical publication may only be readable after the move. For a
|
|
||||||
// recovered copy, first avoid moving an unsettled witness on every scan.
|
|
||||||
const previous = await readExit(id, source, file);
|
|
||||||
if (slot !== id && !matches(previous)) return;
|
|
||||||
const nonce = randomUUID();
|
|
||||||
let name;
|
|
||||||
if (metadata) {
|
|
||||||
name = metadata[0].slice(0, -metadata[5].length) + 'r_' + nonce.replace(/-/g, '').slice(0, 16);
|
|
||||||
} else if (bound || !previous || previous.version === 1) {
|
|
||||||
name = `.pending.${id}.r-${nonce}`;
|
|
||||||
} else {
|
|
||||||
const digest = exitChecksum(id, previous.code, previous.signal, previous.time).slice(0, 32);
|
|
||||||
name = `.pending.${id}.l-${digest}-${nonce.replace(/-/g, '').slice(0, 24)}`;
|
|
||||||
}
|
|
||||||
// The database directory is outside the writers' receipt namespace and
|
|
||||||
// already exists even at zero free inodes. A separately mounted journal
|
|
||||||
// requires a disposal directory on its own filesystem.
|
|
||||||
let bin = sourceDir === localBin ? localBin : dbDir;
|
|
||||||
const pinBin = async () => {
|
|
||||||
binHandle = await fs.promises.open(localBin, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
||||||
return process.platform === 'linux' ? `/proc/self/fd/${binHandle.fd}/${name}` : path.join(localBin, name);
|
|
||||||
};
|
|
||||||
let captured = path.join(bin, name);
|
|
||||||
if (bin === localBin) captured = handle ? path.join(path.dirname(source), name) : await pinBin();
|
|
||||||
try {
|
|
||||||
await fs.promises.rename(source, captured);
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code !== 'EXDEV' || bin === localBin) throw error;
|
|
||||||
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
|
|
||||||
bin = localBin;
|
|
||||||
captured = await pinBin();
|
|
||||||
await fs.promises.rename(source, captured);
|
|
||||||
}
|
|
||||||
const actual = await readExit(id, captured, path.join(bin, name));
|
|
||||||
// An unreadable source offers no authority to discard unbound bytes.
|
|
||||||
const sameExit = previous && actual && actual.version === previous.version &&
|
|
||||||
actual.code === previous.code && actual.signal === previous.signal && actual.time === previous.time;
|
|
||||||
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
|
|
||||||
await fs.promises.unlink(captured);
|
|
||||||
} else if (actual !== undefined) {
|
|
||||||
// A differing, torn or unreadable file is evidence for another pass.
|
|
||||||
// Persist its new directory entry before releasing the original directory.
|
|
||||||
if (binHandle) await binHandle.sync();
|
|
||||||
else if (bin !== sourceDir || !handle) syncDirectory(bin);
|
|
||||||
if (bin === localBin) syncDirectory(directory);
|
|
||||||
if (handle) await handle.sync();
|
|
||||||
else if (sourceDir !== bin) syncDirectory(sourceDir);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code !== 'ENOENT') throw error;
|
|
||||||
} finally {
|
|
||||||
if (binHandle) await binHandle.close();
|
|
||||||
if (handle) await handle.close();
|
|
||||||
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function captureId(name) {
|
|
||||||
const marker = metadataName.exec(name);
|
|
||||||
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
|
|
||||||
const match = legacyCapture.exec(name) ??
|
|
||||||
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
|
|
||||||
return match?.[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
async function receiptEntries(directory) {
|
|
||||||
try { return await fs.promises.readdir(directory, { withFileTypes: true }); }
|
|
||||||
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function retiringExits() {
|
|
||||||
const dir = receiptDirectory();
|
|
||||||
if (!dir) return [];
|
|
||||||
const files = [];
|
|
||||||
const bins = [path.dirname(dir)];
|
|
||||||
for (const entry of await receiptEntries(dir)) {
|
|
||||||
if (entry.isDirectory() && entry.name === '.reclaim') {
|
|
||||||
bins.push(path.join(dir, entry.name));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const claim = claimName.exec(entry.name);
|
|
||||||
const metadata = metadataName.exec(entry.name);
|
|
||||||
if ((claim || metadata) && entry.isDirectory()) {
|
|
||||||
const directory = path.join(dir, entry.name);
|
|
||||||
try { await fs.promises.rmdir(directory); continue; } catch (error) {
|
|
||||||
if (error.code === 'ENOENT') continue;
|
|
||||||
}
|
|
||||||
files.push({ id: metadata ? metadata[1] : claim[2], file: path.join(directory, metadata || claim[1] ? '.pending.claimed' : 'receipt') });
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const match = metadata ?? /^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(entry.name)
|
|
||||||
?? /^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name)
|
|
||||||
?? /^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
|
|
||||||
if (entry.isFile() && match) files.push({ id:match[1], file:path.join(dir,entry.name) });
|
|
||||||
}
|
|
||||||
for (const bin of bins) {
|
|
||||||
for (const entry of await receiptEntries(bin)) {
|
|
||||||
const id = entry.isFile() && captureId(entry.name);
|
|
||||||
if (id) files.push({ id, file:path.join(bin,entry.name) });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return files;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function publishedScriptStarts() {
|
|
||||||
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
|
|
||||||
try {
|
|
||||||
return await listReceiptFiles(directory, 'cron-start-');
|
|
||||||
} catch {
|
|
||||||
// Optional entry instrumentation must not prevent exit recovery.
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function validExit(code, signal, time) {
|
|
||||||
return Number.isSafeInteger(time) && time > 0 && Number.isFinite(new Date(time).getTime()) &&
|
|
||||||
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
|
|
||||||
(code === null && typeof signal === 'string' && /^SIG[A-Z0-9]+$/.test(signal)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Python supervisor uses the same compact JSON array of ASCII values.
|
|
||||||
function exitChecksum(id, code, signal, time) {
|
|
||||||
return createHash('sha256').update(JSON.stringify([id, code, signal, time])).digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function syncDirectory(directory) {
|
|
||||||
const fd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
|
|
||||||
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeExit(id, code, signal, time) {
|
|
||||||
if (!validExit(code, signal, time)) throw new TypeError('Invalid command exit receipt');
|
|
||||||
const file = receiptPath(id);
|
|
||||||
if (!file) return;
|
|
||||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
||||||
const checksum = exitChecksum(id, code, signal, time);
|
|
||||||
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
|
|
||||||
// Creation is the first durable observation. No data block is needed for
|
|
||||||
// this witness. Keep the regular JSON publication for earlier readers.
|
|
||||||
const directory = path.dirname(file);
|
|
||||||
const prefix = '.pending.' + id + '.';
|
|
||||||
const marker = prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
|
|
||||||
const publish = (name, content) => {
|
|
||||||
for (;;) {
|
|
||||||
const target = path.join(directory, name + randomUUID().replace(/-/g, '').slice(0, 16));
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(target, content, { flag: 'wx', mode: 0o600, flush: Boolean(content) });
|
|
||||||
return target;
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code !== 'EEXIST') throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
publish(marker, '');
|
|
||||||
// ext4 journals the empty inode and directory entry together. Also fence the
|
|
||||||
// directory's own entry: another publisher may just have created it.
|
|
||||||
syncDirectory(directory);
|
|
||||||
syncDirectory(path.dirname(directory));
|
|
||||||
try {
|
|
||||||
if (fs.statfsSync(directory).bavail === 0) return;
|
|
||||||
const source = publish(marker, receipt);
|
|
||||||
try { fs.linkSync(source, file); }
|
|
||||||
catch (error) {
|
|
||||||
if (error.code === 'ENOENT') return;
|
|
||||||
if (error.code !== 'EEXIST') throw error;
|
|
||||||
// A panel from before metadata receipts can still discover this retry.
|
|
||||||
for (;;) {
|
|
||||||
try { fs.linkSync(source, path.join(directory, prefix + randomUUID())); break; }
|
|
||||||
catch (linkError) {
|
|
||||||
if (linkError.code === 'ENOENT') break;
|
|
||||||
if (linkError.code !== 'EEXIST') throw linkError;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Older panels find the JSON only through this newly created link.
|
|
||||||
syncDirectory(directory);
|
|
||||||
} catch (error) {
|
|
||||||
if (!storageFull(error)) throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseExit(id, value) {
|
|
||||||
if (!value || !validExit(value.code, value.signal, value.time)) return null;
|
|
||||||
const { code, signal, time, checksum, version } = value;
|
|
||||||
if (version !== undefined || checksum !== undefined) {
|
|
||||||
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time)) return null;
|
|
||||||
} else if (Object.keys(value).length !== 3) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return { code, signal, time, version };
|
|
||||||
}
|
|
||||||
|
|
||||||
// undefined means no publication. null means a result cannot yet be trusted.
|
|
||||||
async function readExit(id, file = receiptPath(id), publication = file) {
|
|
||||||
if (!file) return;
|
|
||||||
try {
|
|
||||||
const handle = await fs.promises.open(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
|
|
||||||
try {
|
|
||||||
// Bound CPU and memory even if the damaged file is growing.
|
|
||||||
const buffer = Buffer.alloc(1025);
|
|
||||||
let size = 0;
|
|
||||||
while (size < buffer.length) {
|
|
||||||
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
|
||||||
if (!bytesRead) break;
|
|
||||||
size += bytesRead;
|
|
||||||
}
|
|
||||||
if (size === buffer.length) return null;
|
|
||||||
const metadata = metadataReceipt(publication);
|
|
||||||
const bytes = buffer.toString('utf8', 0, size);
|
|
||||||
let namedExit;
|
|
||||||
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
|
|
||||||
const [, , outcome, end, checksum] = metadata;
|
|
||||||
const signal = outcome.startsWith('SIG') ? outcome : null;
|
|
||||||
const value = { code: signal ? null : Number(outcome), signal, time: Number(end), version: 1, checksum };
|
|
||||||
// Both current publishers serialize in this order. Accept a torn body
|
|
||||||
// only when every byte matches the tuple independently published by
|
|
||||||
// the filename. Validate replacement files on their own bytes below.
|
|
||||||
namedExit = parseExit(id, value);
|
|
||||||
const json = JSON.stringify(value);
|
|
||||||
if (json.startsWith(bytes)) {
|
|
||||||
return namedExit && { ...namedExit, file, namedExit: undefined };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const exit = parseExit(id, JSON.parse(bytes));
|
|
||||||
const guard = legacyCapture.exec(path.basename(publication));
|
|
||||||
if (guard && exit && exit.version !== 1 && (guard[1] !== id ||
|
|
||||||
guard[2] !== exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))) return null;
|
|
||||||
const conflictingName = exit?.version === 1 && namedExit && (exit.time !== namedExit.time ||
|
|
||||||
exit.code !== namedExit.code || exit.signal !== namedExit.signal);
|
|
||||||
return exit && { ...exit, file, namedExit: conflictingName ? namedExit : undefined };
|
|
||||||
} finally {
|
|
||||||
await handle.close();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code === 'ENOENT') return;
|
|
||||||
if (error.code || error instanceof SyntaxError) return null;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { isLegacyCapture: file => legacyCapture.test(path.basename(file)), isMetadataReceipt: file => Boolean(metadataReceipt(file)), receiptPath, publishedExits, publishedScriptStarts, readExit, writeExit, validExit, storageFull, retireLegacyFile, retiringExits };
|
|
||||||
|
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
const id = process.env.QL_TRIGGER_ID;
|
const id = process.env.QL_TRIGGER_ID;
|
||||||
const exit = parseExit(id, JSON.parse(process.argv[2]));
|
const exit = parseExit(id, JSON.parse(process.argv[2]));
|
||||||
if (!idPattern.test(id || '') || !exit) throw new Error('Invalid supervisor exit receipt');
|
if (!idPattern.test(id || '') || !exit)
|
||||||
|
throw new Error('Invalid supervisor exit receipt');
|
||||||
const { code, signal, time } = exit;
|
const { code, signal, time } = exit;
|
||||||
// An older supervisor may only have delivered this tuple in its message.
|
// An older supervisor may only have delivered this tuple in its message.
|
||||||
// Journal it before waiting for the SQLite writer or loading the panel.
|
// Journal it before waiting for the SQLite writer or loading the panel.
|
||||||
let journaled = false;
|
let journaled = false;
|
||||||
if (exit.version === 1) {
|
if (exit.version === 1) {
|
||||||
try { writeExit(id, code, signal, time); journaled = Boolean(receiptPath(id)); }
|
try {
|
||||||
catch (error) { console.error('[scheduler] Could not journal supervisor message:', error); }
|
writeExit(id, code, signal, time);
|
||||||
|
journaled = Boolean(receiptPath(id));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[scheduler] Could not journal supervisor message:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Development workers run TypeScript directly. Released panels load the
|
// Development workers run TypeScript directly. Released panels load the
|
||||||
// compiled module without starting another runtime on ordinary exits.
|
// compiled module without starting another runtime on ordinary exits.
|
||||||
if (!fs.existsSync(path.join(__dirname, 'triggerHistory.js'))) {
|
if (!fs.existsSync(path.join(__dirname, '../cron/history.js'))) {
|
||||||
process.env.TS_NODE_PROJECT = path.join(__dirname, '../tsconfig.json');
|
process.env.TS_NODE_PROJECT = path.join(__dirname, '../tsconfig.json');
|
||||||
require('ts-node/register/transpile-only');
|
require('ts-node/register/transpile-only');
|
||||||
}
|
}
|
||||||
const { triggerHistory } = require('./triggerHistory');
|
const { triggerHistory } = require('../cron/history');
|
||||||
triggerHistory().complete(id, signal || code !== 0 ? 'failed' : 'finished',
|
triggerHistory()
|
||||||
signal, code, time, exit.version === 1 ? exit : 'legacy').catch(error => {
|
.complete(
|
||||||
if (journaled && storageFull(error)) return;
|
id,
|
||||||
console.error('[scheduler] Failed to settle orphaned command:', error);
|
signal || code !== 0 ? 'failed' : 'finished',
|
||||||
process.exitCode = storageFull(error) ? 75 : 1;
|
signal,
|
||||||
}).finally(() => require('../data').sequelize.close());
|
code,
|
||||||
|
time,
|
||||||
|
exit.version === 1 ? exit : 'legacy',
|
||||||
|
)
|
||||||
|
.catch((error) => {
|
||||||
|
if (journaled && storageFull(error)) return;
|
||||||
|
console.error('[scheduler] Failed to settle orphaned command:', error);
|
||||||
|
process.exitCode = storageFull(error) ? 75 : 1;
|
||||||
|
})
|
||||||
|
.finally(() => require('../data').sequelize.close());
|
||||||
}
|
}
|
||||||
+2
-213
@@ -1,42 +1,12 @@
|
|||||||
import { EventEmitter } from 'events';
|
|
||||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import type { Sequelize } from 'sequelize';
|
import type { Dependence } from '../data/dependence';
|
||||||
import { QueueOccupants, recordQueueAdmission } from './queueDiagnostics';
|
import type { IDependencyFn, ISchedule, IScheduleFn, TCron } from './interface';
|
||||||
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
|
||||||
import { AuthDataType, SystemModel } from '../data/system';
|
|
||||||
import Logger from '../loaders/logger';
|
|
||||||
import { Dependence } from '../data/dependence';
|
|
||||||
import NotificationService from '../services/notify';
|
|
||||||
import { t, tf } from '../shared/i18n';
|
|
||||||
import {
|
|
||||||
ICronFn,
|
|
||||||
IDependencyFn,
|
|
||||||
ISchedule,
|
|
||||||
IScheduleFn,
|
|
||||||
TCron,
|
|
||||||
} from './interface';
|
|
||||||
import config from '../config';
|
|
||||||
import { credentials } from '@grpc/grpc-js';
|
|
||||||
import { ApiClient } from '../protos/api';
|
|
||||||
import { getGrpcCerts } from '../config/grpcCerts';
|
|
||||||
|
|
||||||
class TaskLimit {
|
class TaskLimit {
|
||||||
private dependenyLimit = new PQueue({ concurrency: 1 });
|
private dependenyLimit = new PQueue({ concurrency: 1 });
|
||||||
private queuedDependencyIds = new Set<number>([]);
|
private queuedDependencyIds = new Set<number>([]);
|
||||||
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
|
||||||
private repeatCronNotifyMap = new Map<string, number>();
|
|
||||||
private updateLogLimit = new PQueue({ concurrency: 1 });
|
private updateLogLimit = new PQueue({ concurrency: 1 });
|
||||||
private warnSampling = (error: Error) => Logger.warn('[queue] Could not save occupancy: %s', error.message);
|
|
||||||
private scheduledOccupants = new QueueOccupants('scheduled', () => this.cronLimit.concurrency, this.warnSampling);
|
|
||||||
private manualOccupants = new QueueOccupants('manual', () => this.manualCronoLimit.concurrency, this.warnSampling);
|
|
||||||
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
|
|
||||||
queueClass: CronWaitQueue,
|
|
||||||
concurrency: Math.max(os.cpus().length, 4),
|
|
||||||
});
|
|
||||||
private manualCronoLimit = new PQueue({
|
|
||||||
concurrency: Math.max(os.cpus().length, 4),
|
|
||||||
});
|
|
||||||
private subscriptionLimit = new PQueue({
|
private subscriptionLimit = new PQueue({
|
||||||
concurrency: Math.max(os.cpus().length, 4),
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
});
|
});
|
||||||
@@ -46,198 +16,17 @@ class TaskLimit {
|
|||||||
private systemLimit = new PQueue({
|
private systemLimit = new PQueue({
|
||||||
concurrency: Math.max(os.cpus().length, 4),
|
concurrency: Math.max(os.cpus().length, 4),
|
||||||
});
|
});
|
||||||
private _client: ApiClient | null = null;
|
|
||||||
|
|
||||||
private get client(): ApiClient {
|
|
||||||
if (!this._client) {
|
|
||||||
const tlsConfig = getGrpcCerts();
|
|
||||||
const creds = tlsConfig
|
|
||||||
? credentials.createSsl(
|
|
||||||
Buffer.from(tlsConfig.caCert),
|
|
||||||
Buffer.from(tlsConfig.clientKey),
|
|
||||||
Buffer.from(tlsConfig.clientCert),
|
|
||||||
)
|
|
||||||
: credentials.createInsecure();
|
|
||||||
this._client = new ApiClient(`localhost:${config.grpcPort}`, creds, {
|
|
||||||
'grpc.enable_http_proxy': 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return this._client;
|
|
||||||
}
|
|
||||||
|
|
||||||
get cronLimitActiveCount() {
|
|
||||||
return this.cronLimit.pending;
|
|
||||||
}
|
|
||||||
|
|
||||||
get cronLimitPendingCount() {
|
|
||||||
return this.cronLimit.size;
|
|
||||||
}
|
|
||||||
|
|
||||||
get firstDependencyId() {
|
get firstDependencyId() {
|
||||||
return [...this.queuedDependencyIds.values()][0];
|
return [...this.queuedDependencyIds.values()][0];
|
||||||
}
|
}
|
||||||
|
|
||||||
private notificationService: NotificationService = new NotificationService();
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.setCustomLimit();
|
|
||||||
this.handleEvents();
|
|
||||||
}
|
|
||||||
|
|
||||||
private handleEvents() {
|
|
||||||
this.cronLimit.on('add', () => {
|
|
||||||
Logger.info(
|
|
||||||
t('[schedule][任务加入队列] 运行中任务数: %s, 等待中任务数: %s'),
|
|
||||||
this.cronLimitActiveCount,
|
|
||||||
this.cronLimitPendingCount,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('active', () => {
|
|
||||||
Logger.info(
|
|
||||||
t('[schedule][开始处理任务] 运行中任务数: %s, 等待中任务数: %s'),
|
|
||||||
this.cronLimitActiveCount + 1,
|
|
||||||
this.cronLimitPendingCount,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('completed', (param) => {
|
|
||||||
Logger.info(t('[schedule][任务处理成功] 参数 %s'), JSON.stringify(param));
|
|
||||||
});
|
|
||||||
this.cronLimit.on('error', (error) => {
|
|
||||||
Logger.error(
|
|
||||||
t('[schedule][任务处理错误] 参数 %s'),
|
|
||||||
JSON.stringify(error),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('next', () => {
|
|
||||||
Logger.info(
|
|
||||||
t('[schedule][任务处理结束] 运行中任务数: %s, 等待中任务数: %s'),
|
|
||||||
this.cronLimitActiveCount,
|
|
||||||
this.cronLimitPendingCount,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
this.cronLimit.on('idle', () => {
|
|
||||||
Logger.info(t(`[schedule][任务队列] 空闲中...`));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public removeQueuedDependency(dependency: Dependence) {
|
public removeQueuedDependency(dependency: Dependence) {
|
||||||
if (this.queuedDependencyIds.has(dependency.id!)) {
|
if (this.queuedDependencyIds.has(dependency.id!)) {
|
||||||
this.queuedDependencyIds.delete(dependency.id!);
|
this.queuedDependencyIds.delete(dependency.id!);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public removeQueuedCron(id: string, completed?: ICronFn<any>) {
|
|
||||||
if (this.queuedCrons.has(id)) {
|
|
||||||
const runs = this.queuedCrons.get(id);
|
|
||||||
if (runs && runs.length > 0) {
|
|
||||||
const remaining = completed
|
|
||||||
? runs.filter((run) => run !== completed)
|
|
||||||
: runs.slice(0, -1);
|
|
||||||
if (remaining.length) this.queuedCrons.set(id, remaining);
|
|
||||||
else this.queuedCrons.delete(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public get cronConcurrency() {
|
|
||||||
return this.manualCronoLimit.concurrency;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async setCustomLimit(limit?: number) {
|
|
||||||
if (limit) {
|
|
||||||
this.cronLimit.concurrency = limit;
|
|
||||||
this.manualCronoLimit.concurrency = limit;
|
|
||||||
this.scheduledOccupants.refresh();
|
|
||||||
this.manualOccupants.refresh();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await SystemModel.sync();
|
|
||||||
const doc = await SystemModel.findOne({
|
|
||||||
where: { type: AuthDataType.systemConfig },
|
|
||||||
});
|
|
||||||
if (doc?.info?.cronConcurrency) {
|
|
||||||
await this.setCustomLimit(doc.info.cronConcurrency);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async runWithCronLimit<T>(
|
|
||||||
cron: TCron,
|
|
||||||
fn: ICronFn<T>,
|
|
||||||
options?: Partial<QueueAddOptions>,
|
|
||||||
isCurrent: () => boolean = () => true,
|
|
||||||
onPending?: () => void,
|
|
||||||
waitingSignal?: EventEmitter,
|
|
||||||
triggerId?: string,
|
|
||||||
db?: Sequelize,
|
|
||||||
): Promise<T | void> {
|
|
||||||
if (!isCurrent()) return;
|
|
||||||
fn.cron = cron;
|
|
||||||
fn.isCurrent = isCurrent;
|
|
||||||
// Invalidated snapshots must not consume the new revision's repeat budget.
|
|
||||||
const runs = this.queuedCrons
|
|
||||||
.get(cron.id)
|
|
||||||
?.filter((run) => run.isCurrent?.() !== false);
|
|
||||||
if (cron.skip_if_pending && runs?.length) {
|
|
||||||
onPending?.();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const result = runs?.length ? [...runs, fn] : [fn];
|
|
||||||
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
|
|
||||||
if (result?.length > 5) {
|
|
||||||
if (repeatTimes < 3) {
|
|
||||||
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
|
||||||
this.client.systemNotify(
|
|
||||||
{
|
|
||||||
title: t('任务重复运行'),
|
|
||||||
content: tf(
|
|
||||||
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
|
|
||||||
cron.name || '',
|
|
||||||
cron.command || '',
|
|
||||||
cron.schedule || '',
|
|
||||||
5,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
(err, res) => {
|
|
||||||
if (err) {
|
|
||||||
Logger.error(
|
|
||||||
t('[schedule][任务重复运行] 通知失败 %s'),
|
|
||||||
JSON.stringify(err),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Logger.warn(t('[schedule][任务重复运行] 参数 %s'), JSON.stringify(cron));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.queuedCrons.set(cron.id, result);
|
|
||||||
const run = this.trackAdmission(this.scheduledOccupants, this.cronLimit.concurrency, fn,
|
|
||||||
{ id: triggerId, name: cron.name || cron.id }, db);
|
|
||||||
if (!waitingSignal) return this.cronLimit.add(run, options);
|
|
||||||
return new Promise<T | void>((resolve, reject) => {
|
|
||||||
this.cronLimit.add(run, { ...options, waitingSignal, onRemoved: () => { this.scheduledOccupants.forget(triggerId); resolve(); } }).then(resolve, reject);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private trackAdmission<T>(pool: QueueOccupants, limit: number, fn: () => Promise<T>, occupant: { id?: string; name: string }, db?: Sequelize) {
|
|
||||||
const admission = pool.admission(limit);
|
|
||||||
if (occupant.id && admission && db) {
|
|
||||||
pool.watch(occupant.id, db);
|
|
||||||
void recordQueueAdmission(db, occupant.id, admission)
|
|
||||||
.catch(error => Logger.warn('[queue] Failed to record wait reason: %s', error.message));
|
|
||||||
}
|
|
||||||
return pool.track(fn, occupant, db);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async manualRunWithCronLimit<T>(
|
|
||||||
fn: () => Promise<T>,
|
|
||||||
options?: Partial<QueueAddOptions>,
|
|
||||||
occupant: { id?: string; name: string } = { name: '—' },
|
|
||||||
db?: Sequelize,
|
|
||||||
): Promise<T | void> {
|
|
||||||
return this.manualCronoLimit.add(this.trackAdmission(this.manualOccupants, this.manualCronoLimit.concurrency, fn, occupant, db), options);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async runWithSubscriptionLimit<T>(
|
public async runWithSubscriptionLimit<T>(
|
||||||
schedule: TCron,
|
schedule: TCron,
|
||||||
fn: IScheduleFn<T>,
|
fn: IScheduleFn<T>,
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ const backend = read(path.resolve(__dirname, '../app.js'));
|
|||||||
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
|
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
|
||||||
const version = read(path.join(root, 'version.yaml'))
|
const version = read(path.join(root, 'version.yaml'))
|
||||||
?.toString()
|
?.toString()
|
||||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m)?.[1];
|
.match(
|
||||||
|
/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m,
|
||||||
|
)?.[1];
|
||||||
|
|
||||||
export const runtimeBuild = Object.freeze({
|
export const runtimeBuild = Object.freeze({
|
||||||
instanceId: randomUUID(),
|
instanceId: randomUUID(),
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
import Logger from '../loaders/logger';
|
import Logger from '../loaders/logger';
|
||||||
import { performance } from 'perf_hooks';
|
import { performance } from 'perf_hooks';
|
||||||
|
|
||||||
export async function startupStage<T>(name: string, operation: () => Promise<T>): Promise<T> {
|
export async function startupStage<T>(
|
||||||
|
name: string,
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
if (process.env.QL_STARTUP_TIMING !== '1') return operation();
|
if (process.env.QL_STARTUP_TIMING !== '1') return operation();
|
||||||
const started = performance.now();
|
const started = performance.now();
|
||||||
try {
|
try {
|
||||||
return await operation();
|
return await operation();
|
||||||
} finally {
|
} finally {
|
||||||
const role = process.env.SERVICE_TYPE || 'primary';
|
const role = process.env.SERVICE_TYPE || 'primary';
|
||||||
Logger.info(`[boot:timing] ${role}:${name} ${Math.round(performance.now() - started)}ms (PID: ${process.pid})`);
|
Logger.info(
|
||||||
|
`[boot:timing] ${role}:${name} ${Math.round(
|
||||||
|
performance.now() - started,
|
||||||
|
)}ms (PID: ${process.pid})`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,9 @@ export function isAllowedTaskEnvName(name: unknown): name is string {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assertAllowedTaskEnvName(name: unknown): asserts name is string {
|
export function assertAllowedTaskEnvName(
|
||||||
|
name: unknown,
|
||||||
|
): asserts name is string {
|
||||||
if (!isAllowedTaskEnvName(name)) {
|
if (!isAllowedTaskEnvName(name)) {
|
||||||
throw Object.assign(new Error(t('环境变量名称不可使用')), {
|
throw Object.assign(new Error(t('环境变量名称不可使用')), {
|
||||||
status: 400,
|
status: 400,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,15 @@
|
|||||||
import { lock } from 'proper-lockfile';
|
import { lock } from 'proper-lockfile';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { writeFile, open, chmod } from 'fs/promises';
|
import { writeFile, open, chmod, access } from 'fs/promises';
|
||||||
import { fileExist } from '../config/util';
|
export async function fileExist(file: any) {
|
||||||
|
try {
|
||||||
|
await access(file);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function getUniqueLockPath(filePath: string) {
|
export function getUniqueLockPath(filePath: string) {
|
||||||
const sanitizedPath = filePath
|
const sanitizedPath = filePath
|
||||||
|
|||||||
Vendored
+1
-1
@@ -8,4 +8,4 @@ declare global {
|
|||||||
platform: 'desktop' | 'mobile';
|
platform: 'desktop' | 'mobile';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Joi } from 'celebrate';
|
import { Joi } from 'celebrate';
|
||||||
import { isValidCronSchedule } from '../shared/cronSchedule';
|
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
|
||||||
import { ScheduleType } from '../interface/schedule';
|
import { ScheduleType } from '../interface/schedule';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import config from '../config';
|
import config from '../config';
|
||||||
@@ -71,7 +71,12 @@ export const commonCronSchema = {
|
|||||||
|
|
||||||
// For other absolute paths, ensure they are within the safe log directory
|
// For other absolute paths, ensure they are within the safe log directory
|
||||||
const relative = path.relative(config.logPath, value);
|
const relative = path.relative(config.logPath, value);
|
||||||
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
|
if (
|
||||||
|
!relative ||
|
||||||
|
relative === '..' ||
|
||||||
|
relative.startsWith('..' + path.sep) ||
|
||||||
|
path.isAbsolute(relative)
|
||||||
|
) {
|
||||||
return helpers.error('string.unsafePath');
|
return helpers.error('string.unsafePath');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -89,7 +94,8 @@ export const commonCronSchema = {
|
|||||||
return value;
|
return value;
|
||||||
})
|
})
|
||||||
.messages({
|
.messages({
|
||||||
'string.pattern.base': '日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符',
|
'string.pattern.base':
|
||||||
|
'日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符',
|
||||||
'string.max': '日志名称不能超过100个字符',
|
'string.max': '日志名称不能超过100个字符',
|
||||||
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
||||||
}),
|
}),
|
||||||
|
|||||||
+15
-2
@@ -111,9 +111,22 @@ Commands output pretty-printed JSON by default; `--json` produces a single line.
|
|||||||
- Task run/stop: `{code:200,data:{taskId:12,action:"run",accepted:true}}`. Subscription run/stop/enable/disable use `subscriptionId`; CRUD and raw API operations retain their server response instead. Acceptance does not mean execution succeeded.
|
- Task run/stop: `{code:200,data:{taskId:12,action:"run",accepted:true}}`. Subscription run/stop/enable/disable use `subscriptionId`; CRUD and raw API operations retain their server response instead. Acceptance does not mean execution succeeded.
|
||||||
- Errors: `{code:1,message:"..."}`. Exit codes: 0 success, 1 API/network/configuration failure, 2 invalid arguments, 3 missing authentication, HTTP/API 401/403 or a two-factor challenge.
|
- Errors: `{code:1,message:"..."}`. Exit codes: 0 success, 1 API/network/configuration failure, 2 invalid arguments, 3 missing authentication, HTTP/API 401/403 or a two-factor challenge.
|
||||||
|
|
||||||
IDs must be positive integers. Each task run/stop request addresses one task. The 2.x API provides no separate run ID or idempotency key: an error may leave the outcome unknown. Inspect status before retrying. The CLI does not automatically retry HTTP requests.
|
IDs must be positive integers. Each task run/stop request addresses one task. New panels add this run's `triggerId`, admission `state` (queued/skipped) and `reason`, preserving `taskId/action/accepted`. Immediate run keeps its original output on older panels without trigger IDs. Run requests do not have idempotency keys: an error may leave the outcome unknown. Inspect status before retrying. The CLI does not automatically retry HTTP requests.
|
||||||
|
|
||||||
Logs may belong to an earlier run; `completed` does not imply success. `--tail` truncates on the client and does not reduce server reads or network traffic. Neither task fields nor logs are automatically redacted.
|
### Wait for one run and read its logs
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ql task run 12 --wait --timeout 300 --json
|
||||||
|
# Use the returned triggerId; waiting again does not rerun the task
|
||||||
|
ql task wait 12 --trigger-id <triggerId> --timeout 300 --json
|
||||||
|
ql task logs 12 --trigger-id <triggerId> --tail 200 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
`run --wait` submits once and polls that trigger every second. `task wait` only reads an existing trigger and supports `crons:read`. The wait timeout defaults to 300 seconds (1–86400), starting after the run response; run's `--timeout` requires `--wait`. Each query is bounded by 30 seconds and the remaining wait time. Timeout, authentication or network failure ends waiting without stopping or rerunning the task. Resume with `task wait` and the returned ID. Token expiry during waiting ends the command; the next invocation obtains a session using the existing authentication rules.
|
||||||
|
|
||||||
|
Only `finished` with exit code 0 succeeds, returning `{code:200,data:{taskId,action,triggerId,state,reason,exitCode}}` on stdout; a run-initiated wait also retains `accepted:true`. Failed, skipped, stopped and unknown outcomes exit 1. JSON errors go to stderr with the existing `{code,message}` plus `data` containing the trigger ID and observed outcome. Timeout/query errors use `waitStatus` (timeout/interrupted/notFound/invalidResponse), without inventing a task outcome. Authentication failures retain exit code 3.
|
||||||
|
|
||||||
|
If an old panel returns no triggerId, `run --wait` explicitly fails after submission, without guessing the latest run or retrying. Selected log responses must confirm the same triggerId or the CLI refuses to print their content. Pruned triggers/logs never fall back to sibling runs. Plain `task logs` still reads the latest log, which may belong to an earlier run; `completed` does not imply success. `--tail` truncates on the client and does not reduce server reads or network traffic. Neither task fields nor logs are automatically redacted.
|
||||||
|
|
||||||
## Skill, build and validation
|
## Skill, build and validation
|
||||||
|
|
||||||
|
|||||||
+15
-2
@@ -111,9 +111,22 @@ URL 使用面板根地址,可包含代理路径前缀,不附加 `/open`。
|
|||||||
- `task run/stop`:`{code:200,data:{taskId:12,action:"run",accepted:true}}`。仅表示请求被接受,不表示任务成功完成。
|
- `task run/stop`:`{code:200,data:{taskId:12,action:"run",accepted:true}}`。仅表示请求被接受,不表示任务成功完成。
|
||||||
- 错误:`{code:1,message:"..."}`;退出码 1 为 API/网络/配置错误,2 为参数错误,3 为未登录、HTTP/API 401/403 或需要双因素验证;成功退出码 0。
|
- 错误:`{code:1,message:"..."}`;退出码 1 为 API/网络/配置错误,2 为参数错误,3 为未登录、HTTP/API 401/403 或需要双因素验证;成功退出码 0。
|
||||||
|
|
||||||
ID 必须为正整数,运行/停止一次操作一个任务。2.x 没有为此提供独立运行 ID 或幂等键,失败响应可能意味着执行结果未知,应先查询状态,禁止盲目重试。CLI 不自动重试 HTTP 请求。
|
ID 必须为正整数,运行/停止一次操作一个任务。新面板的运行响应附带本轮 `triggerId`、受理时的 `state`(queued/skipped)和 `reason`,原 `taskId/action/accepted` 字段保留。旧面板不返回触发 ID 时,普通 run 保持原输出。运行请求尚无幂等键,失败响应可能意味着执行结果未知,应先查询状态,禁止盲目重试。CLI 不自动重试 HTTP 请求。
|
||||||
|
|
||||||
日志是该任务最新日志,可能属于先前运行;`completed` 不代表成功。`--tail` 在客户端截取,不减少服务端读取量或网络传输量。日志与任务字段不自动脱敏,应按需读取并避免向聊天中暴露敏感信息。
|
### 等待本轮执行与指定日志
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ql task run 12 --wait --timeout 300 --json
|
||||||
|
# 使用上述输出中的 triggerId;继续等待不会重新运行任务
|
||||||
|
ql task wait 12 --trigger-id <triggerId> --timeout 300 --json
|
||||||
|
ql task logs 12 --trigger-id <triggerId> --tail 200 --json
|
||||||
|
```
|
||||||
|
|
||||||
|
`run --wait` 只提交一次运行请求,随后每秒查询该触发。`task wait` 只读取已有触发,支持 `crons:read` 权限。等待超时默认 300 秒,范围 1–86400 秒,从取得运行响应后开始计算;run 的 `--timeout` 需与 `--wait` 同用。每次查询至多等待 30 秒,并受剩余等待时间限制。超时、鉴权或网络失败只结束本次等待,不会停止任务或重放运行;可凭输出中的触发 ID 再次调用 wait。等待期间令牌失效会退出,下次调用按原认证规则重新取得会话。
|
||||||
|
|
||||||
|
成功确认 `finished` 且退出码为 0 时,stdout 返回 `{code:200,data:{taskId,action,triggerId,state,reason,exitCode}}`;run 发起的等待还保留 `accepted:true`。失败、跳过、停止或结果未知返回退出码 1;`--json` 错误写 stderr,原 `{code,message}` 外附 `data`,保留同一触发 ID、状态与退出码。等待超时或查询异常的 data 使用 `waitStatus`(timeout/interrupted/notFound/invalidResponse),不会编造任务终态;鉴权失败仍使用退出码 3。
|
||||||
|
|
||||||
|
旧面板若未返回 triggerId,`run --wait` 在提交后明确报错,不会猜测最新一轮或重试。指定日志的响应必须确认相同 triggerId,否则拒绝输出;触发或日志被清理后也不会回退到其他轮次。普通 `task logs` 仍读取最新日志,可能属于先前运行;`completed` 不代表成功。`--tail` 在客户端截取,不减少服务端读取量或网络传输量。日志与任务字段不自动脱敏,应按需读取并避免向聊天中暴露敏感信息。
|
||||||
|
|
||||||
## Skill、构建与验证
|
## Skill、构建与验证
|
||||||
|
|
||||||
|
|||||||
@@ -30,9 +30,23 @@ try {
|
|||||||
{ cwd: root },
|
{ cwd: root },
|
||||||
),
|
),
|
||||||
)[0];
|
)[0];
|
||||||
for (const name of ['README.md', 'README.en.md', 'LICENSE', 'dist/npm/commander-LICENSE'])
|
for (const name of [
|
||||||
assert.ok(manifest.files.some((file) => file.path === name), name);
|
'README.md',
|
||||||
assert.ok(manifest.files.every((file) => /^(dist\/npm\/|skills\/qinglong-cli\/|README(?:\.en)?\.md$|LICENSE$|package\.json$)/.test(file.path)));
|
'README.en.md',
|
||||||
|
'LICENSE',
|
||||||
|
'dist/npm/commander-LICENSE',
|
||||||
|
])
|
||||||
|
assert.ok(
|
||||||
|
manifest.files.some((file) => file.path === name),
|
||||||
|
name,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
manifest.files.every((file) =>
|
||||||
|
/^(dist\/npm\/|skills\/qinglong-cli\/|README(?:\.en)?\.md$|LICENSE$|package\.json$)/.test(
|
||||||
|
file.path,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
assert.ok(
|
assert.ok(
|
||||||
manifest.files.some((file) => file.path === 'skills/qinglong-cli/SKILL.md'),
|
manifest.files.some((file) => file.path === 'skills/qinglong-cli/SKILL.md'),
|
||||||
);
|
);
|
||||||
@@ -64,10 +78,16 @@ try {
|
|||||||
);
|
);
|
||||||
assert.equal(Object.keys(metadata.dependencies || {}).length, 0);
|
assert.equal(Object.keys(metadata.dependencies || {}).length, 0);
|
||||||
assert.equal(metadata.bin['ql-dev-cli'], undefined);
|
assert.equal(metadata.bin['ql-dev-cli'], undefined);
|
||||||
assert.ok(!manifest.files.some(file => /^dist\/developer(?:\/|\.)/.test(file.path)));
|
assert.ok(
|
||||||
|
!manifest.files.some((file) => /^dist\/developer(?:\/|\.)/.test(file.path)),
|
||||||
|
);
|
||||||
assert.deepEqual(metadata.bin, { ql: 'dist/npm/ql.js' });
|
assert.deepEqual(metadata.bin, { ql: 'dist/npm/ql.js' });
|
||||||
for (const reference of ['panel.md', 'openapi.md'])
|
for (const reference of ['panel.md', 'openapi.md'])
|
||||||
assert.ok(fs.existsSync(path.join(installed, 'skills/qinglong-cli/references', reference)));
|
assert.ok(
|
||||||
|
fs.existsSync(
|
||||||
|
path.join(installed, 'skills/qinglong-cli/references', reference),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
assert.equal(
|
assert.equal(
|
||||||
fs.readFileSync(
|
fs.readFileSync(
|
||||||
@@ -90,12 +110,32 @@ try {
|
|||||||
assert.match(output, /Usage:|用法|usage/i);
|
assert.match(output, /Usage:|用法|usage/i);
|
||||||
entries.push(name);
|
entries.push(name);
|
||||||
}
|
}
|
||||||
assert.ok(!manifest.files.some(file => file.path.includes('qinglong-local')));
|
assert.ok(
|
||||||
for (const args of [['reload'], ['resetpwd', 'fixture'], ['local', 'check'], ['task', 'exec', 'fixture.js'], ['task', 'fixture.js'], ['repo', 'fixture'], ['dev', 'release']]) {
|
!manifest.files.some((file) => file.path.includes('qinglong-local')),
|
||||||
const result = spawnSync(process.execPath, [path.join(installed, metadata.bin.ql), ...args, '--json'], {
|
);
|
||||||
cwd: temp, encoding: 'utf8', timeout: 10000,
|
for (const args of [
|
||||||
env: { PATH: process.env.PATH, QL_CLI_CONFIG: path.join(temp, 'missing.json'), QL_DIR: '/nonexistent-panel' },
|
['reload'],
|
||||||
});
|
['resetpwd', 'fixture'],
|
||||||
|
['local', 'check'],
|
||||||
|
['task', 'exec', 'fixture.js'],
|
||||||
|
['task', 'fixture.js'],
|
||||||
|
['repo', 'fixture'],
|
||||||
|
['dev', 'release'],
|
||||||
|
]) {
|
||||||
|
const result = spawnSync(
|
||||||
|
process.execPath,
|
||||||
|
[path.join(installed, metadata.bin.ql), ...args, '--json'],
|
||||||
|
{
|
||||||
|
cwd: temp,
|
||||||
|
encoding: 'utf8',
|
||||||
|
timeout: 10000,
|
||||||
|
env: {
|
||||||
|
PATH: process.env.PATH,
|
||||||
|
QL_CLI_CONFIG: path.join(temp, 'missing.json'),
|
||||||
|
QL_DIR: '/nonexistent-panel',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
assert.equal(result.status, 2, JSON.stringify(args) + result.stderr);
|
assert.equal(result.status, 2, JSON.stringify(args) + result.stderr);
|
||||||
assert.equal(result.stdout, '');
|
assert.equal(result.stdout, '');
|
||||||
assert.equal(JSON.parse(result.stderr).code, 2);
|
assert.equal(JSON.parse(result.stderr).code, 2);
|
||||||
@@ -104,7 +144,10 @@ try {
|
|||||||
if (process.env.QL_CLI_PACKAGE_OUTPUT) {
|
if (process.env.QL_CLI_PACKAGE_OUTPUT) {
|
||||||
const output = path.resolve(process.env.QL_CLI_PACKAGE_OUTPUT);
|
const output = path.resolve(process.env.QL_CLI_PACKAGE_OUTPUT);
|
||||||
fs.mkdirSync(output, { recursive: true });
|
fs.mkdirSync(output, { recursive: true });
|
||||||
fs.copyFileSync(path.join(temp, manifest.filename), path.join(output, manifest.filename));
|
fs.copyFileSync(
|
||||||
|
path.join(temp, manifest.filename),
|
||||||
|
path.join(output, manifest.filename),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
process.stdout.write(
|
process.stdout.write(
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
|
|||||||
@@ -34,6 +34,12 @@ App results omit client_secret/tokens unless --show-secrets is explicit. Other r
|
|||||||
|
|
||||||
## 输入和输出 / Inputs and outputs
|
## 输入和输出 / Inputs and outputs
|
||||||
|
|
||||||
|
`PUT /open/crons/run` 保留任务 ID 数组请求体和 `code:200` 响应,新增 `data:[{taskId,triggerId,state,reason}]`。每个存在的任务返回本次事务已落库的触发 ID,state 是受理时的 queued 或 skipped(例如 reason=overlap);重复 ID 合并,不存在的任务不生成记录。提交不代表执行成功;后续通过 `GET /open/crons/:id/triggers?ids=<triggerId>` 查询,日志通过 `GET /open/crons/:id/log?triggerId=<triggerId>` 读取。触发记录受保留期约束,运行请求没有幂等键。
|
||||||
|
|
||||||
|
The run API retains its array request and code:200 envelope, adding `data:[{taskId,triggerId,state,reason}]` for existing tasks. Receipts are committed before returning; queued/skipped is the admission snapshot, not the final outcome. Duplicate IDs are deduplicated; missing tasks produce no receipt. Query the exact trigger via `crons/:id/triggers?ids=<triggerId>` and its log via `crons/:id/log?triggerId=<triggerId>`. History retention still applies; run requests are not idempotent.
|
||||||
|
|
||||||
|
`ql task run <id> --wait --timeout 300 --json` 等待本轮;`ql task wait <id> --trigger-id <triggerId> --timeout 300 --json` 仅等待已有轮次;`ql task logs <id> --trigger-id <triggerId> --tail 200 --json` 读取对应日志。此处 timeout 是总等待秒数(默认 300,最多 86400),超时不停止任务。具体退出码和旧面板行为见 [任务参考](panel.md)。These wait commands poll an exact trigger without replaying execution. Their timeout is the total wait budget, distinct from the per-request timeout below; see the task reference for outcome errors and older-panel compatibility.
|
||||||
|
|
||||||
- `--data '<JSON>'` / `--data @file.json` / `--data -`:完整请求体,保留所有后端字段;query 同样支持这三种输入。
|
- `--data '<JSON>'` / `--data @file.json` / `--data -`:完整请求体,保留所有后端字段;query 同样支持这三种输入。
|
||||||
- `--query '{"searchValue":"demo","page":1}'`:查询对象,值为标量或标量数组,CLI 编码为 URL 参数;不要拼接 URL 查询字符串。
|
- `--query '{"searchValue":"demo","page":1}'`:查询对象,值为标量或标量数组,CLI 编码为 URL 参数;不要拼接 URL 查询字符串。
|
||||||
- `create/update` 常用字段可用选项;同一字段不能同时在 --data 和选项中提供。update 的位置 ID 注入请求体,拒绝与 body.id 冲突;它提交完整更新对象,不会先读取后盲目合并。
|
- `create/update` 常用字段可用选项;同一字段不能同时在 --data 和选项中提供。update 的位置 ID 注入请求体,拒绝与 body.id 冲突;它提交完整更新对象,不会先读取后盲目合并。
|
||||||
@@ -106,13 +112,13 @@ System/user operations below execute remotely through the panel API. They do not
|
|||||||
| `ql task detail ` | GET | `crons/detail` | --query |
|
| `ql task detail ` | GET | `crons/detail` | --query |
|
||||||
| `ql task preview` | GET | `crons/preview` | --query '{"schedule":"0 6 * * *"}' |
|
| `ql task preview` | GET | `crons/preview` | --query '{"schedule":"0 6 * * *"}' |
|
||||||
| `ql task create ` | POST | `crons` | --data, --query |
|
| `ql task create ` | POST | `crons` | --data, --query |
|
||||||
| `ql task run <id...>` | PUT | `crons/run` | --query via api request |
|
| `ql task run <id>` | PUT | `crons/run` | --wait --timeout 300 |
|
||||||
| `ql task stop <id...>` | PUT | `crons/stop` | --query via api request |
|
| `ql task stop <id...>` | PUT | `crons/stop` | --query via api request |
|
||||||
| `ql task labels-delete ` | DELETE | `crons/labels` | --data, --query |
|
| `ql task labels-delete ` | DELETE | `crons/labels` | --data, --query |
|
||||||
| `ql task labels-create ` | POST | `crons/labels` | --data, --query |
|
| `ql task labels-create ` | POST | `crons/labels` | --data, --query |
|
||||||
| `ql task disable <id...>` | PUT | `crons/disable` | --query |
|
| `ql task disable <id...>` | PUT | `crons/disable` | --query |
|
||||||
| `ql task enable <id...>` | PUT | `crons/enable` | --query |
|
| `ql task enable <id...>` | PUT | `crons/enable` | --query |
|
||||||
| `ql task logs <id>` | GET | `crons/:id/log` | --query via api request |
|
| `ql task logs <id>` | GET | `crons/:id/log` | --trigger-id --tail |
|
||||||
| `ql task update <id>` | PUT | `crons` | --data, --query |
|
| `ql task update <id>` | PUT | `crons` | --data, --query |
|
||||||
| `ql task delete <id...>` | DELETE | `crons` | --query |
|
| `ql task delete <id...>` | DELETE | `crons` | --query |
|
||||||
| `ql task pin <id...>` | PUT | `crons/pin` | --query |
|
| `ql task pin <id...>` | PUT | `crons/pin` | --query |
|
||||||
|
|||||||
@@ -36,7 +36,9 @@ Remote URLs require HTTPS; loopback HTTP is allowed. Use the panel root URL with
|
|||||||
|
|
||||||
Use `<cli> task run <id> --json` or `<cli> task stop <id> --json` when the user authorizes that operation on the identified task. A request to diagnose does not authorize a rerun. Respect authorization already given; clarify only unresolved targets or scope.
|
Use `<cli> task run <id> --json` or `<cli> task stop <id> --json` when the user authorizes that operation on the identified task. A request to diagnose does not authorize a rerun. Respect authorization already given; clarify only unresolved targets or scope.
|
||||||
|
|
||||||
`accepted: true` means the API accepted the request, not that the task finished successfully. Follow with `task get` and, when needed, `task logs`; report what is observable. On a timeout or uncertain response, inspect status before considering another operation. Never blindly retry run/stop: 2.x does not provide CLI execution idempotency.
|
`accepted: true` means the API accepted the request, not that the task finished successfully. New panels return `triggerId`, admission `state` and `reason`. Use `task run <id> --wait --timeout 300 --json` to submit once and wait for that run, or `task wait <id> --trigger-id <triggerId> --timeout 300 --json` to resume waiting without executing again. Read its log with `task logs <id> --trigger-id <triggerId> --tail 200 --json`. Only `finished` with exit code 0 succeeds; other terminal outcomes exit 1, with observed outcome and triggerId in JSON stderr `data`. Wait timeouts and interrupted reads retain the trigger ID and `waitStatus`, and never stop or rerun the task. A 401/403 still exits 3. The wait timeout defaults to 300 seconds (maximum 86400); on run it requires --wait.
|
||||||
|
|
||||||
|
Older panels without a run triggerId keep the immediate-run contract; --wait fails explicitly after submission, without guessing the newest trigger or replaying the run. Selected logs must confirm their triggerId or the CLI refuses to print them. Plain task logs retains latest-log behavior. On a timeout or uncertain response, inspect status before considering another operation. Never blindly retry run/stop: the CLI does not provide execution idempotency.
|
||||||
|
|
||||||
## Subscriptions
|
## Subscriptions
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user