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:
whyour committed 2026-11-22 12:24:29 +08:00
1 parent 77ece406ac
commit c5458596c8
341 files changed
+30051 -9474

No files matched your search

+3 -3
View File
@@ -1,6 +1,6 @@
name: "\U0001F680 New feature proposal"
description: Suggest an idea for this project
labels: [":sparkles: feature request"]
labels: [':sparkles: feature request']
body:
- type: markdown
attributes:
@@ -10,14 +10,14 @@ body:
id: feature-description
attributes:
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:
required: true
- type: textarea
id: suggested-solution
attributes:
label: Suggested solution
description: "In module [xy] we could provide following implementation..."
description: 'In module [xy] we could provide following implementation...'
validations:
required: true
- type: textarea
+21 -21
View File
@@ -3,21 +3,21 @@ name: Build And Push Docker Image
on:
push:
paths:
- "**"
- "!*.md"
- '**'
- '!*.md'
# CLI is verified separately; its shared Bash upgrade engine ships in images.
- "!cli/**"
- "cli/src/internal/maintenance/upgradeArtifacts.cjs"
- "cli/src/internal/maintenance/platformBundle.cjs"
- "cli/src/internal/maintenance/upgradePrestart.cjs"
- "cli/src/internal/maintenance/panelUpgrade.cjs"
- "cli/src/internal/maintenance/nodeRuntime.cjs"
- "!.github/workflows/cli-package.yml"
- '!cli/**'
- 'cli/src/internal/maintenance/upgradeArtifacts.cjs'
- 'cli/src/internal/maintenance/platformBundle.cjs'
- 'cli/src/internal/maintenance/upgradePrestart.cjs'
- 'cli/src/internal/maintenance/panelUpgrade.cjs'
- 'cli/src/internal/maintenance/nodeRuntime.cjs'
- '!.github/workflows/cli-package.yml'
branches:
- "master"
- "develop"
- 'master'
- 'develop'
tags:
- "v*"
- 'v*'
workflow_dispatch:
inputs:
static_sync_only:
@@ -85,12 +85,12 @@ jobs:
run: echo "node-version=$(cat .nvmrc)" >> "$GITHUB_OUTPUT"
- uses: pnpm/action-setup@v6
with:
version: "8.3.1"
version: '8.3.1'
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
cache: "pnpm"
node-version-file: '.nvmrc'
cache: 'pnpm'
cache-dependency-path: pnpm-lock.yaml
- name: build front and back
@@ -253,11 +253,11 @@ jobs:
path: static/
- uses: pnpm/action-setup@v6
with:
version: "8.3.1"
version: '8.3.1'
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
cache: "pnpm"
node-version-file: '.nvmrc'
cache: 'pnpm'
cache-dependency-path: pnpm-lock.yaml
- name: Read version from version.yaml
@@ -342,11 +342,11 @@ jobs:
path: static/
- uses: pnpm/action-setup@v6
with:
version: "8.3.1"
version: '8.3.1'
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
cache: "pnpm"
node-version-file: '.nvmrc'
cache: 'pnpm'
cache-dependency-path: pnpm-lock.yaml
- name: Read version from version.yaml
+1
View File
@@ -12,6 +12,7 @@ npm-debug.log*
yarn-error.log
yarn.lock
package-lock.json
pnpm-lock.yaml
/static
/data
DS_Store
+6
View File
@@ -1,3 +1,9 @@
# 代码格式
- 每次修改代码后,必须按项目的 `.prettierrc`、`.editorconfig` 和 `.prettierignore` 完成格式化,覆盖新增文件、静态及动态导入、`require()` 和测试代码。
- 在项目根目录执行 `npm run prettier`,随后执行 `npm run prettier:check`。检查必须通过;发现格式问题时须修复并重新检查,才能结束任务或提交代码。
- 检查通过后若再次修改代码,必须重新完成格式化和检查。不得以手动调整格式、编辑器设置或提交钩子代替上述验证。
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
+6 -2
View File
@@ -97,9 +97,13 @@ export default (app: Router) => {
}
// OpenAPI config scopes grant data-file access, not executable hooks.
if (/(?:^|\/)open\/configs(?:\/|\?|$)/.test(req.originalUrl || '')) {
const realPath = await fs.realpath(normalized).catch(() => normalized);
const realPath = await fs
.realpath(normalized)
.catch(() => normalized);
if (
openApiProtectedFiles.has(path.basename(normalized).toLowerCase()) ||
openApiProtectedFiles.has(
path.basename(normalized).toLowerCase(),
) ||
openApiProtectedFiles.has(path.basename(realPath).toLowerCase())
) {
return res.send({ code: 403, message: t('文件无法访问') });
+179 -54
View File
@@ -1,8 +1,12 @@
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
import { readDailyResults } from '../shared/legacyDailyStatistics';
import {
executionIdPattern,
executionTriggerId,
receiptFinishTime,
} from '../cron/identity';
import { readDailyResults } from '../cron/settlement/legacyDailyStatistics';
import { PendingCronInstall } from '../shared/errors';
import { triggerHistory } from '../shared/triggerHistory';
import { previewSchedule, withNextRun } from '../shared/cronPreview';
import { triggerHistory } from '../cron/history';
import { previewSchedule, withNextRun } from '../cron/queries/cronPreview';
import { Router, Request, Response, NextFunction } from 'express';
import { literal, Op } from 'sequelize';
import { Container } from 'typedi';
@@ -11,10 +15,7 @@ import CronService from '../services/cron';
import CronViewService from '../services/cronView';
import { celebrate, Joi } from 'celebrate';
import { commonCronSchema } from '../validation/schedule';
import {
RunningInstanceModel,
InstanceStatus,
} from '../data/runningInstance';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import { t } from '../shared/i18n';
import cronClient from '../schedule/client';
@@ -25,8 +26,17 @@ export default (app: Router) => {
route.use(async (req, res, next) => {
// Keep stop/status callbacks available even when the scheduler is down.
if (['POST', 'PUT', 'DELETE'].includes(req.method) &&
['/', '/run', '/enable', '/disable', '/views/enable', '/views/disable'].includes(req.path)) {
if (
['POST', 'PUT', 'DELETE'].includes(req.method) &&
[
'/',
'/run',
'/enable',
'/disable',
'/views/enable',
'/views/disable',
].includes(req.path)
) {
try {
await cronClient.readiness.ensureReady();
} catch (error) {
@@ -171,23 +181,44 @@ export default (app: Router) => {
try {
const cronService = Container.get(CronService);
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) {
logger.error('🔥 error: %o', e);
return next(e);
}
});
route.get('/preview', celebrate({ query: Joi.object({
route.get(
'/preview',
celebrate({
query: Joi.object({
schedule: Joi.string().required(),
}).unknown(true) }), (req, res) => {
}).unknown(true),
}),
(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表达式格式有误') });
}
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(
'/detail',
@@ -218,7 +249,9 @@ export default (app: Router) => {
} catch (e) {
if (e instanceof PendingCronInstall) {
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);
@@ -246,14 +279,19 @@ export default (app: Router) => {
route.put(
'/stop',
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()),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
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 });
} catch (e) {
return next(e);
@@ -349,7 +387,9 @@ export default (app: Router) => {
instanceId: Joi.number().integer().positive().optional(),
previousPath: Joi.string().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(),
limit: Joi.number()
.integer()
@@ -366,7 +406,10 @@ export default (app: Router) => {
const cronService = Container.get(CronService);
const result = await cronService.log(req.params.id, {
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,
follow: req.query.follow as unknown as boolean,
cursor: req.query.cursor as string | undefined,
@@ -416,10 +459,18 @@ export default (app: Router) => {
route.delete(
'/',
celebrate({
body: Joi.array().min(1).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),
})),
body: Joi.array()
.min(1)
.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) => {
const logger: Logger = Container.get('logger');
@@ -513,7 +564,9 @@ export default (app: Router) => {
exit_code: Joi.number().optional().allow(null),
trigger_stopped: Joi.boolean().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'),
}),
async (req: Request, res: Response, next: NextFunction) => {
@@ -534,18 +587,27 @@ export default (app: Router) => {
},
);
route.get('/:id/daily-results', celebrate({
route.get(
'/:id/daily-results',
celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
}), async (req, res, next) => {
}),
async (req, res, next) => {
try {
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
const data = await readDailyResults(
RunningInstanceModel.sequelize!,
Number(req.params.id),
);
return res.send({ code: 200, data });
} catch (error) {
return next(error);
}
});
},
);
route.get('/:id/triggers', celebrate({
route.get(
'/:id/triggers',
celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
query: Joi.object({
offset: Joi.number().integer().min(0),
@@ -553,37 +615,72 @@ export default (app: Router) => {
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) => {
})
.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 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);
? 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: 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); }
});
} catch (err) {
next(err);
}
},
);
route.get(
'/:id/instances',
celebrate({
// This route historically ignored query parameters. Only validate and
// 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(
Joi.object({ paged: Joi.valid('true').required() }).unknown(),
{
then: Joi.object({
limit: Joi.number().integer().min(1).max(100),
before: Joi.number().integer().positive(),
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
})
.unknown(true)
.oxor('ids', 'limit')
.oxor('ids', 'before'),
otherwise: Joi.object().unknown(true),
}),
},
),
params: Joi.object({
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
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
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 instances = await RunningInstanceModel.findAll({
attributes: {
exclude: ['finished_at', 'exit_code'],
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: {
cron_id: req.params.id,
...(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 }),
raw: true,
});
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
next: instances.length > limit ? instances[limit - 1].id : null });
if (limit)
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 });
} catch (e) {
return next(e);
@@ -630,10 +748,17 @@ export default (app: Router) => {
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 {
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);
} catch (e) {
return next(e);
+205 -61
View File
@@ -1,23 +1,24 @@
import config from '../config';
import { stat } from 'fs/promises';
import { resolveFileAccess } from '../shared/fileAccess';
import { AnomalyPage, AnomalyKind } from '../shared/scheduleAnomalies';
import { auditSchedule } from '../shared/scheduleAudit';
import { systemScheduleAudit } from '../shared/systemScheduleAudit';
import { AnomalyPage, AnomalyKind } from '../cron/queries/scheduleAnomalies';
import { auditSchedule } from '../cron/scheduling/scheduleAudit';
import { systemScheduleAudit } from '../cron/scheduling/systemScheduleAudit';
import { celebrate, Joi } from 'celebrate';
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
import { oldestQueued } from '../shared/queueDiagnostics';
import {
executionIdPattern,
executionTriggerId,
receiptFinishTime,
} from '../cron/identity';
import { oldestQueued } from '../cron/queries/queueDiagnostics';
import { containerResources } from '../shared/containerResources';
import { TriggerHistory } from '../shared/triggerHistory';
import { TriggerHistory } from '../cron/history';
import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi';
import { fn, col, where, Op, QueryTypes } from 'sequelize';
import { CrontabModel } from '../data/cron';
import { CrontabStatModel } from '../data/cronStats';
import {
RunningInstanceModel,
InstanceStatus,
} from '../data/runningInstance';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import dayjs from 'dayjs';
import os from 'os';
import { isEmpty } from 'lodash';
@@ -38,21 +39,49 @@ export default (app: Router) => {
const { ref_id, code, elapsed, trigger_id, execution_id } = req.body;
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 });
}
if (execution_id !== undefined && (trigger_id !== undefined ||
typeof execution_id !== 'string' || !executionIdPattern.test(execution_id))) return res.send({ code: 400 });
if (
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;
// Old wrappers also send a status receipt with the process identity.
// 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' } });
const exitCode = typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
if (!id)
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;
if (!Number.isInteger(exitCode) || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0) {
return res.send({ code: 400, message: 'invalid exit code or elapsed time' });
if (
!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 });
} catch (e) {
res.send({ code: 500 });
@@ -82,7 +111,9 @@ export default (app: Router) => {
where: { date: today },
raw: true,
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(day.valueOf()),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]);
const row = stats as any;
@@ -104,7 +135,10 @@ export default (app: Router) => {
todaySuccess: totalSuccess,
todayFail: totalFail,
todayStopped: totalRuns - totalSuccess - totalFail,
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
successRate:
totalRuns > 0
? ((totalSuccess / totalRuns) * 100).toFixed(1)
: '0',
avgTime: averageElapsed(totalTime, totalRuns, row?.untimed_count),
},
});
@@ -114,14 +148,21 @@ export default (app: Router) => {
},
);
route.get('/schedule-anomalies', celebrate({ query: Joi.object({
route.get(
'/schedule-anomalies',
celebrate({
query: Joi.object({
source: Joi.string().valid('panel', 'system').required(),
kind: Joi.string().valid('missing', 'skipped', 'unconfirmed').required(),
kind: Joi.string()
.valid('missing', 'skipped', 'unconfirmed')
.required(),
at: Joi.number().integer().positive().required(),
page: Joi.number().integer().min(1).default(1),
revision: Joi.string().hex().length(64),
live: Joi.boolean().default(false),
}).unknown(true) }), async (req, res, next) => {
}).unknown(true),
}),
async (req, res, next) => {
try {
const { source, kind, page, at, revision, live } = req.query;
const until = Number(at);
@@ -129,40 +170,93 @@ export default (app: Router) => {
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
if (live && serverNow >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
if (until > Date.now() || until < dayjs().subtract(1, 'day').startOf('day').valueOf())
if (
until > Date.now() ||
until < dayjs().subtract(1, 'day').startOf('day').valueOf()
)
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live ? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
) : [];
const details = new AnomalyPage(kind as AnomalyKind, Number(page), revision as string | undefined);
const [snapshotRetention] = live
? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1',
{ type: QueryTypes.SELECT },
)
: [];
const details = new AnomalyPage(
kind as AnomalyKind,
Number(page),
revision as string | undefined,
);
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
const summary = await audit(CrontabStatModel.sequelize!, dayjs(until).startOf('day').valueOf(), until, details);
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' } });
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;
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 },
);
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); }
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]) {
route.get(
@@ -171,17 +265,31 @@ export default (app: Router) => {
try {
const countColumn = isSuccess ? 'success_count' : 'fail_count';
const rows = (await CrontabStatModel.findAll({
attributes: ['ref_id', [fn('SUM', col(countColumn)), 'result_count']],
where: { date: dayjs().format('YYYY-MM-DD'), [countColumn]: { [Op.gt]: 0 } },
attributes: [
'ref_id',
[fn('SUM', col(countColumn)), 'result_count'],
],
where: {
date: dayjs().format('YYYY-MM-DD'),
[countColumn]: { [Op.gt]: 0 },
},
group: ['ref_id'],
order: [[fn('SUM', col(countColumn)), 'DESC'], ['ref_id', 'ASC']],
order: [
[fn('SUM', col(countColumn)), 'DESC'],
['ref_id', 'ASC'],
],
raw: true,
})) as any[];
const crons = rows.length > 0 ? await CrontabModel.findAll({
const crons =
rows.length > 0
? await CrontabModel.findAll({
attributes: ['id', 'name', 'command'],
where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } },
where: {
id: { [Op.in]: rows.map((row) => Number(row.ref_id)) },
},
raw: true,
}) : [];
})
: [];
const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
res.send({
code: 200,
@@ -192,7 +300,9 @@ export default (app: Router) => {
id,
name: cron?.name || cron?.command || tf('任务#%s', id),
command: cron?.command || '',
[isSuccess ? 'successCount' : 'failCount']: Number(row.result_count),
[isSuccess ? 'successCount' : 'failCount']: Number(
row.result_count,
),
deleted: !cron,
};
}),
@@ -212,7 +322,8 @@ export default (app: Router) => {
const days =
requestedDays === undefined
? 7
: typeof requestedDays === 'string' && /^[1-9]\d{0,2}$/.test(requestedDays)
: typeof requestedDays === 'string' &&
/^[1-9]\d{0,2}$/.test(requestedDays)
? Number(requestedDays)
: NaN;
if (!Number.isInteger(days) || days > 365) {
@@ -286,7 +397,9 @@ export default (app: Router) => {
raw: true,
});
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) => ({
rank: i + 1,
@@ -329,7 +442,9 @@ export default (app: Router) => {
raw: true,
});
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) => ({
rank: i + 1,
@@ -338,7 +453,9 @@ export default (app: Router) => {
avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count),
successRate:
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',
}));
@@ -353,7 +470,9 @@ export default (app: Router) => {
'/runtime',
async (req: Request, res: Response, next: NextFunction) => {
try {
const queued = await new TriggerHistory(CrontabModel.sequelize!).queueCounts();
const queued = await new TriggerHistory(
CrontabModel.sequelize!,
).queueCounts();
const runningInstances = await RunningInstanceModel.findAll({
where: {
status: InstanceStatus.running,
@@ -405,7 +524,9 @@ export default (app: Router) => {
runningCount: running.length,
queuedCount: queued.triggers,
queuedTasks: queued.tasks,
oldestQueued: queued.triggers ? await oldestQueued(CrontabModel.sequelize!) : [],
oldestQueued: queued.triggers
? await oldestQueued(CrontabModel.sequelize!)
: [],
running,
idleTasks: idleTasks.map((c: any) => ({
id: c.id,
@@ -427,27 +548,49 @@ export default (app: Router) => {
async (req: Request, res: Response, next: NextFunction) => {
try {
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 }),
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
]));
]);
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) => {
let rawLabels = c.labels;
if (typeof rawLabels === 'string') rawLabels = JSON.parse(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) {
labels.push(t('未分类'));
}
const st = statMap[c.id!];
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;
if (st) {
labelMap[label].runs += Number(st.run_count) || 0;
@@ -463,7 +606,8 @@ export default (app: Router) => {
label,
count: v.count,
todayRuns: v.runs,
successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
successRate:
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);
+13 -5
View File
@@ -259,7 +259,10 @@ export default (app: Router) => {
async (req: Request, res: Response, next: NextFunction) => {
try {
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 });
} catch (e) {
return next(e);
@@ -285,10 +288,13 @@ export default (app: Router) => {
: [parseContent];
if (
data.length > 0 &&
data.every((x) =>
x && typeof x.name === 'string' &&
data.every(
(x) =>
x &&
typeof x.name === 'string' &&
/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) &&
typeof x.value === 'string' && x.value.length > 0,
typeof x.value === 'string' &&
x.value.length > 0,
)
) {
const result = await envService.create(
@@ -303,7 +309,9 @@ export default (app: Router) => {
} else {
return res.send({
code: 400,
message: t('每条数据 name 或者 value 字段不能为空,参考导出文件格式'),
message: t(
'每条数据 name 或者 value 字段不能为空,参考导出文件格式',
),
});
}
} catch (e) {
+21 -15
View File
@@ -1,15 +1,14 @@
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
import {
directoryCheckHandler,
directoryPageHandler,
} from '../shared/directoryPageRoute';
import { celebrate, Joi } from 'celebrate';
import { NextFunction, Request, Response, Router } from 'express';
import { Container } from 'typedi';
import { Logger } from 'winston';
import config from '../config';
import { t } from '../shared/i18n';
import {
readDirs,
removeAnsi,
rmPath,
} from '../config/util';
import { readDirs, removeAnsi, rmPath } from '../config/util';
import LogService from '../services/log';
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
@@ -19,8 +18,14 @@ const blacklist = ['.tmp'];
export default (app: Router) => {
app.use('/logs', route);
route.get('/entries', ...directoryPageHandler(() => config.logPath, blacklist, true));
route.post('/entries/check', ...directoryCheckHandler(() => config.logPath, blacklist));
route.get(
'/entries',
...directoryPageHandler(() => config.logPath, blacklist, true),
);
route.post(
'/entries/check',
...directoryCheckHandler(() => config.logPath, blacklist),
);
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
@@ -43,7 +48,9 @@ export default (app: Router) => {
path: Joi.string().allow('').optional(),
file: Joi.string().required(),
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(),
limit: Joi.number()
.integer()
@@ -67,7 +74,9 @@ export default (app: Router) => {
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({
where: { log_path: logPath, status: InstanceStatus.running },
});
@@ -96,15 +105,12 @@ export default (app: Router) => {
},
);
route.get(
'/:file',
(req: Request, res: Response) => {
route.get('/:file', (req: Request, res: Response) => {
return res.send({
code: 410,
message: t('接口已下线,请使用 /logs/detail 接口'),
});
},
);
});
route.delete(
'/',
+10 -4
View File
@@ -56,7 +56,8 @@ function writablePath(targetPath: string, req?: Request): string {
if (
/(?:^|\/)open\/scripts(?:\/|\?|$)/.test(req?.originalUrl || '') &&
!resolveFileAccess(config.scriptPath, [normalized])
) return '';
)
return '';
if (!isPathAllowed(normalized)) return '';
for (const writableRoot of config.writePathList) {
const root = resolve(writableRoot) + sep;
@@ -554,7 +555,8 @@ export default (app: Router) => {
}
const { name, ext } = parse(filename);
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`), req,
join(config.scriptPath, path, `${name}.swap${ext}`),
req,
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
@@ -587,7 +589,8 @@ export default (app: Router) => {
}
const { name, ext } = parse(filename);
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`), req,
join(config.scriptPath, path, `${name}.swap${ext}`),
req,
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
@@ -635,7 +638,10 @@ export default (app: Router) => {
if (!path) {
path = '';
}
const filePath = writablePath(join(config.scriptPath, path, filename), req);
const filePath = writablePath(
join(config.scriptPath, path, filename),
req,
);
const newPath = writablePath(
join(config.scriptPath, path, newFilename),
req,
+1 -1
View File
@@ -3,7 +3,7 @@ import { Container } from 'typedi';
import { Logger } from 'winston';
import SubscriptionService from '../services/subscription';
import { celebrate, Joi } from 'celebrate';
import { isValidCronSchedule } from '../shared/cronSchedule';
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
const route = Router();
export default (app: Router) => {
+9 -3
View File
@@ -10,7 +10,7 @@ import UserService from '../services/user';
import { t } from '../shared/i18n';
import { isDefaultAuthInfo } from '../shared/auth';
import { getUniqPath, handleLogPath, parseVersion } from '../config/util';
import { findCronId } from '../shared/cronCommand';
import { findCronId } from '../cron/execution/cronCommand';
import dayjs from 'dayjs';
import multer from 'multer';
import { logStreamManager } from '../shared/logStreamManager';
@@ -63,8 +63,14 @@ export default (app: Router) => {
try {
const systemService = Container.get(SystemService);
const data = await systemService.getSystemConfig();
res.send({ code: 200, data: { ...data, effectiveCronConcurrency: systemService.cronConcurrency,
availableCpus: containerResources().cpus } });
res.send({
code: 200,
data: {
...data,
effectiveCronConcurrency: systemService.cronConcurrency,
availableCpus: containerResources().cpus,
},
});
} catch (e) {
return next(e);
}
+91 -32
View File
@@ -49,7 +49,8 @@ class Application {
process.env.NODE_ENV === 'development' ||
(process.arch === 'arm' &&
Number(
(process.config.variables as { arm_version?: string | number }).arm_version,
(process.config.variables as { arm_version?: string | number })
.arm_version,
) === 6)
? 120000
: 30000;
@@ -63,7 +64,9 @@ class Application {
this.httpWorker = this.forkWorker('http');
})
.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);
});
@@ -72,7 +75,8 @@ class Application {
if (metadata) {
if (!this.isShuttingDown) {
Logger.error(
`${metadata.serviceType} worker ${worker.process.pid} died (${signal || code
`${metadata.serviceType} worker ${worker.process.pid} died (${
signal || code
}). Restarting...`,
);
// If gRPC worker died, restart it and wait for it to be ready
@@ -92,19 +96,27 @@ class Application {
this.httpWorker.send('reregister-crons');
Logger.info('Sent reregister-crons message to HTTP worker');
} 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) => {
Logger.error(`Failed to restart gRPC worker:\n${errStack(error)}`);
Logger.error(
`Failed to restart gRPC worker:\n${errStack(error)}`,
);
process.exit(1);
});
} else {
// For HTTP worker, just restart it
const newWorker = this.forkWorker(metadata.serviceType);
this.httpWorker = newWorker;
Logger.info(`Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`);
Logger.info(
`Restarted ${metadata.serviceType} worker (PID: ${newWorker.process.pid})`,
);
}
}
@@ -129,7 +141,11 @@ class Application {
// Timeout after specified milliseconds
const timeoutId = setTimeout(() => {
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);
});
}
@@ -139,21 +155,30 @@ class Application {
// 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.
// 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';
}
const worker = cluster.fork(workerEnv);
if (serviceType === 'grpc') worker.on('message', (msg) => {
if (msg === 'crontab-install-failed' && this.httpWorker?.isConnected()) {
if (serviceType === 'grpc')
worker.on('message', (msg) => {
if (
msg === 'crontab-install-failed' &&
this.httpWorker?.isConnected()
) {
this.httpWorker.send('reregister-crons');
}
});
if (serviceType === 'http') worker.on('message', (msg) => {
if (serviceType === 'http')
worker.on('message', (msg) => {
if (msg?.type !== 'cancel-queued-triggers') return;
for (const [id, meta] of this.workerMetadataMap) {
const target = cluster.workers?.[id];
if (meta.serviceType === 'grpc' && target?.isConnected()) target.send(msg);
if (meta.serviceType === 'grpc' && target?.isConnected())
target.send(msg);
}
});
this.workerMetadataMap.set(worker.id, {
@@ -195,7 +220,11 @@ class Application {
try {
worker.send('shutdown');
} 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})`);
try {
const { triggerHistory } = await startupStage('history.import', () => import('./shared/triggerHistory'));
const { triggerHistory } = await startupStage(
'history.import',
() => import('./cron/history'),
);
const history = triggerHistory();
await startupStage('history.recover', () => history.interrupt(serviceType));
await startupStage('history.recover', () =>
history.interrupt(serviceType),
);
if (serviceType === 'http') {
await this.startHttpService();
const retryExits = async () => {
try {
await history.retryPendingExits();
} catch (error) {
Logger.error(`[scheduler] Exit receipt retry failed: ${errStack(error)}`);
Logger.error(
`[scheduler] Exit receipt retry failed: ${errStack(error)}`,
);
} finally {
if (!this.isShuttingDown) setTimeout(retryExits, 15000).unref();
}
@@ -262,21 +298,26 @@ class Application {
private async startHttpService() {
// 在导入任何 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());
const app = await startupStage('http.middleware', () => this.setupMiddlewares());
const app = await startupStage('http.middleware', () =>
this.setupMiddlewares(),
);
const { HttpServerService } = await import('./services/http');
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 }));
const server = await this.httpServerService.initialize(
app,
config.port,
);
const server = await this.httpServerService.initialize(app, config.port);
const serverLoader = await import('./loaders/server');
await (serverLoader.default as any)({ server });
@@ -284,10 +325,15 @@ class Application {
}
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);
await startupStage('grpc.initialize', () => this.grpcServerService!.initialize());
await startupStage('grpc.initialize', () =>
this.grpcServerService!.initialize(),
);
this.setupWorkerShutdown('grpc');
}
@@ -295,12 +341,23 @@ class Application {
process.on('message', async (msg) => {
if (msg === 'shutdown') {
this.gracefulShutdown(serviceType);
} else if (serviceType === 'grpc' && typeof msg === 'object' && msg &&
'type' in msg && msg.type === 'cancel-queued-triggers' && 'ids' in msg && Array.isArray(msg.ids)) {
const { cancelWaitingTriggers } = await import('./shared/runCron');
} else if (
serviceType === 'grpc' &&
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);
} else if (serviceType === 'http' &&
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')) {
} else if (
serviceType === 'http' &&
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')
) {
const { default: cronClient } = await import('./schedule/client');
cronClient.readiness.invalidate();
}
@@ -316,7 +373,7 @@ class Application {
this.isShuttingDown = true;
try {
const { triggerHistory } = await import('./shared/triggerHistory');
const { triggerHistory } = await import('./cron/history');
await triggerHistory().interrupt(serviceType);
if (serviceType === 'http') {
await this.httpServerService?.shutdown();
@@ -325,7 +382,9 @@ class Application {
}
process.exit(0);
} catch (error) {
Logger.error(`[${serviceType}] Error during shutdown:\n${errStack(error)}`);
Logger.error(
`[${serviceType}] Error during shutdown:\n${errStack(error)}`,
);
process.exit(1);
}
}
+51 -16
View File
@@ -1,8 +1,8 @@
import { storageFull, writeExit } from '../shared/managedExit.cjs';
import { storageFull, writeExit } from '../cron/settlement/exitReceipt.cjs';
import { QueryTypes } from 'sequelize';
import { randomUUID } from 'crypto';
import { sequelize } from '../data';
import { systemOwner, TriggerHistory } from '../shared/triggerHistory';
import { systemOwner, TriggerHistory } from '../cron/history';
async function receipt() {
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 rule = process.env.QL_SYSTEM_RULE;
const dispatched = Number(process.env.QL_SYSTEM_DISPATCHED) * 1000;
const dispatch = Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at ? 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);
const dispatch =
Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at
? 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;
else if (!id) process.stdout.write(triggerId);
} else if (action === 'finish') {
// The live wrapper inherited both IDs from the start it just claimed. A
// 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)}-`)) {
const [registered] = await sequelize.query(
`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`,
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT });
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT },
);
if (!registered) return;
}
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;
let journaled = false;
if (bound) {
try { writeExit(id, code, null, finishedAt); journaled = true; }
catch (error) {
try {
writeExit(id, code, null, finishedAt);
journaled = true;
} catch (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 {
await history.complete(id, code === 0 ? 'finished' : 'failed', null, code, finishedAt,
bound ? { version: 1, code, signal: null, time: finishedAt } : finishedAt === undefined ? undefined : 'legacy');
await history.complete(
id,
code === 0 ? 'finished' : 'failed',
null,
code,
finishedAt,
bound
? { version: 1, code, signal: null, time: finishedAt }
: finishedAt === undefined
? undefined
: 'legacy',
);
} catch (error) {
if (!journaled || !storageFull(error)) throw error;
// The regular recovery pass will settle the receipt after space returns.
@@ -54,8 +86,11 @@ async function receipt() {
}
}
receipt().catch((error) => {
receipt()
.catch((error) => {
console.error('[crond] Failed to persist execution receipt:', error);
// At start, 75 means that another execution already owns the slot.
process.exitCode = process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
}).finally(() => sequelize.close());
process.exitCode =
process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
})
.finally(() => sequelize.close());
+2 -1
View File
@@ -165,7 +165,8 @@ async function loadExistingCerts(): Promise<GrpcTlsConfig | null> {
return null;
}
const [caCert, serverCert, serverKey, clientCert, clientKey] = await Promise.all([
const [caCert, serverCert, serverKey, clientCert, clientKey] =
await Promise.all([
fs.readFile(caCertPath, 'utf-8'),
fs.readFile(serverCertPath, 'utf-8'),
fs.readFile(serverKeyPath, 'utf-8'),
+38 -21
View File
@@ -1,5 +1,9 @@
import { cronOperand } from '../shared/cronOperand';
import { finishStoppedTree, isProcessDescendant, systemOwner } from '../shared/cronProcess';
import { cronOperand } from '../cron/execution/cronOperand';
import {
finishStoppedTree,
isProcessDescendant,
systemOwner,
} from '../cron/execution/cronProcess';
import * as fs from 'fs/promises';
import { statSync } from 'fs';
import * as path from 'path';
@@ -10,7 +14,7 @@ import { load } from 'js-yaml';
import config from './index';
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR } from './const';
import Logger from '../loaders/logger';
import { writeFileWithLock } from '../shared/utils';
import { fileExist, writeFileWithLock } from '../shared/utils';
import { DependenceTypes } from '../data/dependence';
import { FormData } from 'undici';
import os from 'os';
@@ -136,14 +140,7 @@ export function getPlatform(userAgent: string): 'mobile' | 'desktop' {
return platform as 'mobile' | 'desktop';
}
export async function fileExist(file: any) {
try {
await fs.access(file);
return true;
} catch (error) {
return false;
}
}
export { fileExist } from '../shared/utils';
export async function createFile(file: string, data: string = '') {
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,
withStopRequest?: (signalTree: () => Error | void, targets: string[]) => Promise<void | { targets: string[]; signalledAt: number | null }>) {
export async function killTask(
pid: number,
waitForExit = false,
verifyOwner?: () => void,
withStopRequest?: (
signalTree: () => Error | void,
targets: string[],
) => Promise<void | { targets: string[]; signalledAt: number | null }>,
) {
const descendants = await psTree(pid);
verifyOwner?.();
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) {
try {
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) {
if (!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) throw error;
if (
!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
)
throw error;
}
}
verifyOwner();
@@ -536,9 +544,11 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
const sameProcess = (target: number) => {
if (!verifyOwner) return true;
if (!births.has(target)) return false;
try { return births.get(target) === systemOwner(target); }
catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) return false;
try {
return births.get(target) === systemOwner(target);
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!))
return false;
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
// stop claim even if a descendant is still draining the output pipe.
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;
for (const target of pids) {
@@ -685,7 +697,9 @@ export async function getUniqPath(
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}`;
}
@@ -917,7 +931,10 @@ export function getUninstallCommand(
if ((linuxOsType || getOsTypeSync()) === 'Alpine') {
// apk del accepts package names, not the version constraints or repository
// 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)
? packageName
: shellQuote(packageName);
+637
View File
@@ -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.
+61
View File
@@ -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(),
),
);
}
+930
View File
@@ -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,
);
}
}
+253
View File
@@ -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.
function words(command: string): string[] {
const result: string[] = [];
let value = '', quote = '', active = false;
let value = '',
quote = '',
active = false;
for (let i = 0; i < command.length; i++) {
const c = command[i];
if (quote && c === quote) { quote = ''; continue; }
if (!quote && (c === "'" || c === '"')) { quote = c; active = true; continue; }
if (quote && c === quote) {
quote = '';
continue;
}
if (!quote && (c === "'" || c === '"')) {
quote = c;
active = true;
continue;
}
if (c === '\\' && quote !== "'") {
const next = command[++i];
if (next === undefined) return [];
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
if (next !== '\n') { value += next; active = true; }
if (next !== '\n') {
value += next;
active = true;
}
continue;
}
if (!quote && /[;&|<>()\n]/.test(c)) break;
if (!quote && /\s/.test(c)) {
if (active) result.push(value);
value = ''; active = false; continue;
value = '';
active = false;
continue;
}
if (!active && !quote && c === '#') break;
value += c; active = true;
value += c;
active = true;
}
if (quote) return [];
if (active) result.push(value);
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());
if (args[0] === 'task') args.shift();
else if (taskOnly && args[0] === 'ql') return;
while (args[0] === '-l' || args[0] === '-m') {
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];
}
@@ -17,16 +17,24 @@ export function hasLiveCronProcess(status?: number, pid?: number | null) {
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
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.
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();
if (result.status === 0 && value) return value;
// BSD ps exits 1 without output when the selected PID has already exited.
if (result.status === 1 && !value && !result.stderr.trim())
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) {
@@ -38,7 +46,8 @@ export function systemOwner(pid: number) {
}
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
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 boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
return `crond:${pid}:${startTicks}:${boot}`;
@@ -47,15 +56,21 @@ export function systemOwner(pid: number) {
let linuxClockTicks: number | undefined;
// 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 {
const identity = systemOwner(pid);
const birth = identity.slice(`crond:${pid}:`.length);
let bornAt: number;
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'));
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;
} else {
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.
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
} 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;
}
}
@@ -91,44 +107,77 @@ export function isProcessDescendant(pid: number, root: number) {
}
// 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,
instance?: { logPath?: string }) {
const conflict = () => Object.assign(new Error('Task process identity could not be verified'), { status: 409 });
export function verifyCronProcess(
pid: number,
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 (identity) {
// A birth token for this PID proves the original process is gone if the
// kernel now reports a different birth. Access errors remain retryable.
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
let current: string;
try { current = systemOwner(pid); }
catch (error) {
try {
current = systemOwner(pid);
} catch (error) {
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;
}
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;
}
try {
if (process.platform === 'linux') {
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
if (instance && (!instance.logPath || instance.logPath === '/dev/null' ||
!env.includes('real_log_path=' + instance.logPath))) throw conflict();
if (
instance &&
(!instance.logPath ||
instance.logPath === '/dev/null' ||
!env.includes('real_log_path=' + instance.logPath))
)
throw conflict();
if (env.includes('ID=' + cronId) && started) {
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
const birth = systemOwner(pid);
const ticks = Number(birth.split(':')[2]);
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
if (boot && hz > 0 && Math.floor(Number(boot[1]) + ticks / hz) <= started + 1) return birth;
const hz = Number(
execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }),
);
if (
boot &&
hz > 0 &&
Math.floor(Number(boot[1]) + ticks / hz) <= started + 1
)
return birth;
}
}
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
// Distinguish a completed child whose receipt is still being written
// from a live PID with an unverifiable identity.
try { systemOwner(pid); } catch (probe) {
if (['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!))
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
try {
systemOwner(pid);
} 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.
// A saved birth identity still identifies them; walking the dead root no longer can.
export async function finishStoppedTree(identities: string[], signalledAt?: number | null) {
const surviving = () => identities.flatMap(identity => {
export async function finishStoppedTree(
identities: string[],
signalledAt?: number | null,
) {
const surviving = () =>
identities.flatMap((identity) => {
const pid = Number(identity.split(':')[1]);
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('Invalid saved process identity');
try { return systemOwner(pid) === identity ? [pid] : []; }
catch (error) {
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return [];
if (!Number.isSafeInteger(pid) || pid <= 1)
throw new Error('Invalid saved process identity');
try {
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 remainingGrace = Math.min(
1000,
Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()),
);
const graceDeadline = Date.now() + remainingGrace;
while (surviving().length) {
const remaining = graceDeadline - Date.now();
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;
// Revalidate each PID immediately before signalling, including after the grace period.
@@ -161,12 +224,14 @@ export async function finishStoppedTree(identities: string[], signalledAt?: numb
try {
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
} 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;
while (surviving().length) {
if (Date.now() >= deadline) throw new Error('Stopped process tree did not exit');
await new Promise(resolve => setTimeout(resolve, 20));
if (Date.now() >= deadline)
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 {
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> = {}) {
const { priority = 0, waitingSignal, onRemoved } = options;
@@ -22,10 +24,19 @@ export class CronWaitQueue {
this.entries.splice(index, 1);
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];
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);
}
@@ -36,6 +47,8 @@ export class CronWaitQueue {
}
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 { EventEmitter } from 'events';
import PQueue from 'p-queue-cjs';
import { triggerHistory, TriggerState } from './triggerHistory';
import { t } from './i18n';
import { triggerHistory, TriggerState } from '../history';
import { t } from '../../shared/i18n';
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
import taskLimit from './pLimit';
import Logger from '../loaders/logger';
import { ICron } from '../protos/cron';
import { CrontabModel, CrontabStatus } from '../data/cron';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import taskLimit from './cronLimit';
import Logger from '../../loaders/logger';
import { ICron } from '../../protos/cron';
import { CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
InstanceStatus,
} from '../../data/runningInstance';
import dayjs from 'dayjs';
import { observeChildProcess, asError } from './childProcess';
import { observeChildProcess, asError } from '../../shared/childProcess';
const waiting = new Map<string, () => void>();
// A backlog of missed timers can otherwise open hundreds of competing SQLite
@@ -30,16 +33,33 @@ export async function runCron(
const queuedAt = Date.now();
if (trigger && history) {
const cronId = Number(cron.id);
const admitted = await historyWrites.add(() => cron.skip_if_pending
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
const admitted = await historyWrites.add(() =>
cron.skip_if_pending
? 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;
}
let reason = 'capacity';
let state: TriggerState = 'skipped';
let exitCode: number | null = null;
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;
const expiry = trigger ? new EventEmitter() : undefined;
const alive = () => isCurrent() && Date.now() < deadline;
@@ -55,7 +75,10 @@ export async function runCron(
if (trigger) waiting.delete(trigger.id);
reason = 'changed';
try {
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
if (!alive()) {
reason = isCurrent() ? 'queue_timeout' : 'changed';
return;
}
let multiple = false;
// A single-instance trigger must not interrupt work already in progress.
try {
@@ -176,25 +199,42 @@ export async function runCron(
}
if (trigger) {
claimed = await history!.start(trigger.id, Date.now(), multiple);
if (!claimed) { reason = 'overlap'; return; }
if (!claimed) {
reason = 'overlap';
return;
}
}
if (!isCurrent() || Date.now() >= deadline) {
reason = isCurrent() ? 'queue_timeout' : 'changed';
return;
}
let saveStart: Promise<void> | undefined;
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
const cp = spawnCronCommand(
cmd,
trigger?.id,
trigger && history
? (at) => {
saveStart = history
.recordCommandStart(trigger.id, at)
.catch((error) => {
Logger.warn(
'[schedule] Could not record command start: %s',
asError(error).message,
);
});
} : undefined);
}
: undefined,
);
let denied: string | undefined;
const { completed } = observeChildProcess(cp, {
onStart: async () => {
if (!trigger) return;
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';
else await releaseCronCommand(cp);
}
@@ -212,8 +252,15 @@ export async function runCron(
});
const result = await completed;
await saveStart;
if (denied) { reason = denied; return; }
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
if (denied) {
reason = denied;
return;
}
state = result.signal
? 'stopped'
: result.error || result.code !== 0
? 'failed'
: 'finished';
reason = result.error ? 'spawn' : result.signal || '';
exitCode = result.code;
if (result.error) {
@@ -242,21 +289,43 @@ export async function runCron(
}
};
try {
if (trigger && expiry) waiting.set(trigger.id, () => {
if (trigger && expiry)
waiting.set(trigger.id, () => {
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 {
clearTimeout(timer);
if (trigger) waiting.delete(trigger.id);
if (trigger && history) {
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
const outcomeReason =
state === 'skipped' && !isCurrent() ? 'changed' : reason;
const finishedAt = Date.now();
await historyWrites.add(() => state === 'skipped' && !claimed
await historyWrites.add(
() =>
state === 'skipped' && !claimed
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
{ priority: 1 });
: history.complete(
trigger.id,
state,
outcomeReason || null,
exitCode,
finishedAt,
),
{ priority: 1 },
);
}
}
}
+806
View File
@@ -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);
});
}
}
+473
View File
@@ -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.
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) {
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;
}
}
// 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');
}
+166
View File
@@ -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 = {
schedule?: string;
+36
View File
@@ -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[] = [];
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) {
this.hash.update(JSON.stringify(row)).update('\n');
@@ -36,7 +40,13 @@ export class AnomalyPage {
const revision = this.hash.digest('hex');
const changed = !!this.previous && revision !== this.previous;
const reset = changed || (this.page > 1 && !this.selected.length);
return { rows: reset ? this.first : this.selected, total: this.total,
page: reset ? 1 : this.page, pageSize: AnomalyPage.size, revision, changed };
return {
rows: reset ? this.first : this.selected,
total: this.total,
page: reset ? 1 : this.page,
pageSize: AnomalyPage.size,
revision,
changed,
};
}
}
+79
View File
@@ -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 { validate } from 'node-cron';
import { ScheduleType } from '../interface/schedule';
import { ScheduleType } from '../../interface/schedule';
const aliases: Record<string, string> = {
'@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 { parseCronSchedule } from './cronSchedule';
@@ -12,7 +12,12 @@ export interface CronJob {
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;
// Preserve cron-parser 4's day/weekday OR semantics, including its
// month-dependent full-day range and the global nth-week constraint.
@@ -35,7 +40,8 @@ export function createCronJob(
let cancelled = false;
let started = false;
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) {
options.logger.warn(
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
@@ -90,30 +96,45 @@ export function createCronJob(
return job;
}
// 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.
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 tasks: ScheduledTask[] = [];
try {
const matchers = parsed.patterns.map((pattern) => {
const task = createTask(pattern, () => {});
tasks.push(task);
return (task as ScheduledTask & {
timeMatcher: { getNextMatch(date: Date): Date; expressions: number[][] };
}).timeMatcher;
return (
task as ScheduledTask & {
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,
// 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[] = [];
let horizon = after + 366 * 100 * 86400000;
while (slots.length < count) {
const time = Math.min(...next.map(Number));
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;
next.forEach((date, index) => {
if (+date !== time) return;
@@ -123,14 +144,16 @@ export function upcomingSlots(schedule: string, after: number, count = 1, throug
// entire local day, including schedules that fire every second.
const cursor = new Date(time);
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);
});
if (accepted) {
if (through == null) slots.push(time);
else for (const second of seconds) {
const slot = time - time % 60000 + second * 1000;
if (slot >= time && slot <= through && slots.length < count) slots.push(slot);
else
for (const second of seconds) {
const slot = time - (time % 60000) + second * 1000;
if (slot >= time && slot <= through && slots.length < count)
slots.push(slot);
}
horizon = time + 366 * 100 * 86400000;
}
+115
View File
@@ -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 { AddCronRequest, DeleteCronRequest } from '../protos/cron';
import { AddCronRequest, DeleteCronRequest } from '../../protos/cron';
import { upcomingSlots } from './cronScheduler';
import { slotId } from './triggerHistory';
import { slotId } from '../identity';
type Rule = {
cron_id: string;
@@ -189,10 +189,14 @@ export async function auditSchedule(
{ transaction, bind, type: QueryTypes.SELECT },
);
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,
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 },
);
return { since: coverage.since, rules, receipts };
@@ -240,7 +244,8 @@ export async function auditSchedule(
);
if (certain < possible) partial = true;
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) ?? []) {
const time = row.scheduled_at;
if (
@@ -267,21 +272,46 @@ export async function auditSchedule(
} else {
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') skipped++;
if (details?.kind === kind) details.add({
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 (details?.kind === kind)
details.add({
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)
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);
}
if (details && received && received.size < certain) {
for (let i = lowerBound(times, certainFirst); i < times.length && times[i] <= certainLast; 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 });
for (
let i = lowerBound(times, certainFirst);
i < times.length && times[i] <= certainLast;
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,5 +1,5 @@
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
// initial DB read/write through scheduler registration (including rollback).
@@ -66,9 +66,12 @@ export class SchedulerReadiness {
}),
]);
if (!available) {
throw Object.assign(new Error('Scheduler is recovering; try again later'), {
throw Object.assign(
new Error('Scheduler is recovering; try again later'),
{
status: 503,
});
},
);
}
} finally {
clearTimeout(timer);
+100
View File
@@ -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 { blockSize, blockSlots } from './scheduleAudit';
@@ -105,7 +105,9 @@ export async function systemScheduleAudit(
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
);
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
(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
@@ -137,7 +139,10 @@ export async function systemScheduleAudit(
(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 dispatchedTasks = new Set<string>();
const legacyThrough = new Map<string, number>();
@@ -252,11 +257,14 @@ export async function systemScheduleAudit(
);
let status: string;
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) {
++expected;
++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;
duplicates += group.length - 1;
if (launched) ++dispatched;
@@ -283,8 +291,18 @@ export async function systemScheduleAudit(
status = 'awaiting';
} else {
++missing;
if (details?.kind === 'missing') details.add({ task, name, rule: schedule, time, source: 'system',
trigger: null, observed: null, reason: null, logPath: null });
if (details?.kind === 'missing')
details.add({
task,
name,
rule: schedule,
time,
source: 'system',
trigger: null,
observed: null,
reason: null,
logPath: null,
});
status = 'missing';
}
}
@@ -295,8 +313,12 @@ export async function systemScheduleAudit(
status,
triggerCount: group.length,
startCount: group.filter((row) => row.launched === 1).length,
skipCount: group.filter((row) => !row.launched && row.state === 'skipped').length,
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
skipCount: group.filter(
(row) => !row.launched && row.state === 'skipped',
).length,
unknownExitCount: group.filter(
(row) => row.launched === 1 && row.state === 'unknown',
).length,
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.splice(25);
}
let actualSkips = 0, actualUnconfirmed = 0;
let actualSkips = 0,
actualUnconfirmed = 0;
for (const row of receipts) {
if (row.launched === 1) continue;
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
@@ -312,8 +335,17 @@ export async function systemScheduleAudit(
else actualUnconfirmed++;
if (details?.kind === kind) {
const slot = matched?.get(row.id);
details.add({ 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 });
details.add({
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 {
@@ -332,7 +364,8 @@ export async function systemScheduleAudit(
uncertain,
awaiting,
switchSlots,
actualSkips, actualUnconfirmed,
actualSkips,
actualUnconfirmed,
actualStarts: receipts.filter((row) => row.launched === 1).length,
unmatched: receipts.length - matchedReceipts,
recent,
+171
View File
@@ -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.
export async function recordCronResult(
database: Sequelize, cronId: number, _code: number, elapsedMs: number,
finishedAt: number, triggerId: string, transaction?: Transaction,
database: Sequelize,
cronId: number,
_code: number,
elapsedMs: number,
finishedAt: number,
triggerId: string,
transaction?: Transaction,
): Promise<void> {
if (!triggerId) throw new Error('Execution identity required');
if (!transaction) {
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 claimed = await database.query(
@@ -17,27 +31,55 @@ export async function recordCronResult(
{ bind, type: QueryTypes.BULKUPDATE, transaction },
);
if (!claimed) {
const rows = await database.query('SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
{ bind, type: QueryTypes.SELECT, transaction });
const rows = await database.query(
'SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
{ bind, type: QueryTypes.SELECT, transaction },
);
if (!rows.length) throw new Error('Unknown trigger');
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
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');
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) {
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
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,
elapsedMs: number, reversible: boolean, transaction: Transaction) {
export async function addDailyExit(
database: Sequelize,
cronId: number,
day: string,
state: string,
elapsedMs: number,
reversible: boolean,
transaction: Transaction,
) {
await database.query(
`INSERT INTO "CrontabStats"
(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),
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
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,
},
},
);
}
+519
View File
@@ -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,
};
@@ -15,11 +15,19 @@ type DayCounts = {
// Process one outcome, newest day first. Same-day receipts can only cover
// 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 deficit = exits - localMatches;
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
@@ -41,9 +49,14 @@ export function readDailyResults(database: Sequelize, cronId: number) {
const first = today.subtract(6, 'day');
const next = today.add(1, 'day');
return database.query<{
day: string; exitSuccess: number; exitFail: number;
bookedSuccess: number; bookedFail: number; supplement: number;
}>(`WITH results AS (
day: string;
exitSuccess: number;
exitFail: number;
bookedSuccess: number;
bookedFail: number;
supplement: number;
}>(
`WITH results AS (
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
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
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
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: {
id: cronId, start: first.valueOf(), end: next.valueOf(),
first: first.format('YYYY-MM-DD'), next: next.format('YYYY-MM-DD'),
} });
FROM results GROUP BY day ORDER BY day DESC`,
{
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.
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
// 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
JOIN Crontabs c ON c.id=i.cron_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
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)`,
{ transaction, type: QueryTypes.BULKUPDATE });
{ transaction, type: QueryTypes.BULKUPDATE },
);
// 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.
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,
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-%'
@@ -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)))
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))))`,
{ transaction });
{ transaction },
);
// 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.
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,
t.started_at,i.createdAt,t.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
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
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
// eligible days first; never move already booked counts or elapsed samples.
let task: number | undefined;
let successCredit = 0, failureCredit = 0;
let priorSuccessCredit = 0, priorFailureCredit = 0;
let successCredit = 0,
failureCredit = 0;
let priorSuccessCredit = 0,
priorFailureCredit = 0;
for (const day of days) {
if (day.cron_id !== task) {
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 failures = matchDailyCounts(day.failures, day.saved_failures, failureCredit, day.later_failures);
const successes = matchDailyCounts(
day.successes,
day.saved_successes,
successCredit,
day.later_successes,
);
const failures = matchDailyCounts(
day.failures,
day.saved_failures,
failureCredit,
day.later_failures,
);
successCredit = successes.remaining;
failureCredit = failures.remaining;
let success = successes.missing, failure = failures.missing;
let success = successes.missing,
failure = failures.missing;
if (priorVersion === 2) {
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
// Only the extra lower bound established by v3 is new evidence.
const priorSuccess = matchDailyCounts(day.successes, day.saved_successes, priorSuccessCredit);
const priorFailure = matchDailyCounts(day.failures, day.saved_failures, priorFailureCredit);
const priorSuccess = matchDailyCounts(
day.successes,
day.saved_successes,
priorSuccessCredit,
);
const priorFailure = matchDailyCounts(
day.failures,
day.saved_failures,
priorFailureCredit,
);
priorSuccessCredit = priorSuccess.remaining;
priorFailureCredit = priorFailure.remaining;
success = Math.max(0, success - priorSuccess.missing);
@@ -160,13 +218,18 @@ export async function repairLegacyDailyStatistics(database: Sequelize, transacti
if (!success && !failure) continue;
// Anonymous elapsed samples have no execution identity. Preserve measured
// 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)
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,
success_count=COALESCE(success_count,0)+excluded.success_count,
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
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
+40
View File
@@ -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;
};
+3 -1
View File
@@ -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>(
'CrontabStat',
+4 -2
View File
@@ -29,8 +29,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => {
let ready = initialized.get(connection);
if (!ready) {
ready = new Promise<void>((resolve, reject) => {
connection.run('PRAGMA synchronous=EXTRA', error => error ? reject(error) : resolve());
}).catch(error => {
connection.run('PRAGMA synchronous=EXTRA', (error) =>
error ? reject(error) : resolve(),
);
}).catch((error) => {
initialized.delete(connection);
throw error;
});
+12
View File
@@ -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;
}
+6 -1
View File
@@ -79,5 +79,10 @@ export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
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 { installTriggerHistory } from './triggerHistory';
import { repairLegacyDailyStatistics } from './legacyDailyStatistics';
import { installTriggerHistory } from '../cron/schema';
import { repairLegacyDailyStatistics } from '../cron/settlement/legacyDailyStatistics';
import { QueryTypes, Sequelize } from 'sequelize';
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: 'recovery_from', type: 'BIGINT' },
{ 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' },
];
@@ -81,39 +85,58 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
}
const repairId = 'repair-legacy-daily-statistics-v3';
const prior = appliedIds.has('repair-legacy-daily-statistics-v2') ? 2
: appliedIds.has('repair-legacy-daily-statistics-v1') ? 1 : 0;
const prior = appliedIds.has('repair-legacy-daily-statistics-v2')
? 2
: appliedIds.has('repair-legacy-daily-statistics-v1')
? 1
: 0;
const retentionId = 'preserve-cron-stat-retention-v1';
if (!appliedIds.has(retentionId)) {
if (prior || appliedIds.has(repairId)) {
// Old cleanup removed complete date prefixes but kept no cutoff. Every
// surviving date and yesterday (the minimum supported retention) is
// 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`,
{ 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)',
{ bind: { id: retentionId }, transaction });
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: retentionId }, transaction },
);
}
if (!appliedIds.has(repairId)) {
await repairLegacyDailyStatistics(database, transaction, prior);
// This reconciliation includes v1 and v2. Record all on fresh installations
// 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)`,
{ transaction, bind: { id: repairId } });
{ transaction, bind: { id: repairId } },
);
}
if (!appliedIds.has(prunedExitMigrationId)) {
// Earlier versions could reclaim the last file before upgrading. The
// 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
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 });
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: prunedExitMigrationId }, transaction });
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`,
{ 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
+1 -1
View File
@@ -9,7 +9,7 @@ import { CrontabViewModel } from '../data/cronView';
import { CrontabStatModel } from '../data/cronStats';
import { RunningInstanceModel } from '../data/runningInstance';
import { sequelize } from '../data';
import { migrateSchema } from '../shared/schemaMigrations';
import { migrateSchema } from '../data/schemaMigrations';
export default async () => {
try {
+3 -1
View File
@@ -120,7 +120,9 @@ export default ({ app }: { app: Application }) => {
)) ||
(['scripts', 'logs'].includes(key || '') &&
req.method === 'POST' &&
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(pathLower));
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(
pathLower,
));
const hasNamespaceScope =
doc.scopes.includes(key as AppScope) ||
([
+3 -2
View File
@@ -18,7 +18,7 @@ import OpenService from '../services/open';
import { shareStore } from '../shared/store';
import Logger from './logger';
import cronClient from '../schedule/client';
import { TriggerHistory } from '../shared/triggerHistory';
import { TriggerHistory } from '../cron/history';
import { setLang, systemLang } from '../shared/i18n';
export default async () => {
@@ -124,7 +124,8 @@ export default async () => {
const history = new TriggerHistory(CrontabModel.sequelize!);
const pendingStops = await history.pendingStops();
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();
// 初始化时执行一次所有的 ql repo 任务
+1 -2
View File
@@ -10,8 +10,7 @@ export default function protectedPathCase(
if (
originalPath !== normalizedPath &&
(normalizedPath.startsWith('/api/') ||
normalizedPath.startsWith('/open/'))
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))
) {
return res.status(400).json({
code: 400,
+1056 -433
View File
File diff suppressed because it is too large. Load diff
+214 -93
View File
@@ -5,7 +5,7 @@
// source: back/protos/cron.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
import { BinaryReader, BinaryWriter } from '@bufbuild/protobuf/wire';
import {
type CallOptions,
ChannelCredentials,
@@ -17,9 +17,9 @@ import {
Metadata,
type ServiceError,
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 {
schedule: string;
@@ -42,15 +42,13 @@ export interface AddCronRequest {
replace: boolean;
}
export interface AddCronResponse {
}
export interface AddCronResponse {}
export interface DeleteCronRequest {
ids: string[];
}
export interface DeleteCronResponse {
}
export interface DeleteCronResponse {}
/** Zero restores the default limit. */
export interface SetConcurrencyRequest {
@@ -58,19 +56,23 @@ export interface SetConcurrencyRequest {
}
function createBaseISchedule(): ISchedule {
return { schedule: "" };
return { schedule: '' };
}
export const ISchedule: MessageFns<ISchedule> = {
encode(message: ISchedule, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.schedule !== "") {
encode(
message: ISchedule,
writer: BinaryWriter = new BinaryWriter(),
): BinaryWriter {
if (message.schedule !== '') {
writer.uint32(10).string(message.schedule);
}
return writer;
},
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;
const message = createBaseISchedule();
while (reader.pos < end) {
@@ -94,12 +96,16 @@ export const ISchedule: MessageFns<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 {
const obj: any = {};
if (message.schedule !== "") {
if (message.schedule !== '') {
obj.schedule = message.schedule;
}
return obj;
@@ -108,20 +114,22 @@ export const ISchedule: MessageFns<ISchedule> = {
create<I extends Exact<DeepPartial<ISchedule>, I>>(base?: I): ISchedule {
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();
message.schedule = object.schedule ?? "";
message.schedule = object.schedule ?? '';
return message;
},
};
function createBaseICron(): ICron {
return {
id: "",
schedule: "",
command: "",
id: '',
schedule: '',
command: '',
extra_schedules: [],
name: "",
name: '',
max_queue_wait: undefined,
catchup_seconds: undefined,
recovery_from: undefined,
@@ -130,20 +138,23 @@ function createBaseICron(): ICron {
}
export const ICron: MessageFns<ICron> = {
encode(message: ICron, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.id !== "") {
encode(
message: ICron,
writer: BinaryWriter = new BinaryWriter(),
): BinaryWriter {
if (message.id !== '') {
writer.uint32(10).string(message.id);
}
if (message.schedule !== "") {
if (message.schedule !== '') {
writer.uint32(18).string(message.schedule);
}
if (message.command !== "") {
if (message.command !== '') {
writer.uint32(26).string(message.command);
}
for (const v of message.extra_schedules) {
ISchedule.encode(v!, writer.uint32(34).fork()).join();
}
if (message.name !== "") {
if (message.name !== '') {
writer.uint32(42).string(message.name);
}
if (message.max_queue_wait !== undefined) {
@@ -162,7 +173,8 @@ export const ICron: MessageFns<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;
const message = createBaseICron();
while (reader.pos < end) {
@@ -197,7 +209,9 @@ export const ICron: MessageFns<ICron> = {
break;
}
message.extra_schedules.push(ISchedule.decode(reader, reader.uint32()));
message.extra_schedules.push(
ISchedule.decode(reader, reader.uint32()),
);
continue;
}
case 5: {
@@ -251,35 +265,47 @@ export const ICron: MessageFns<ICron> = {
fromJSON(object: any): ICron {
return {
id: isSet(object.id) ? globalThis.String(object.id) : "",
schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "",
command: isSet(object.command) ? globalThis.String(object.command) : "",
id: isSet(object.id) ? globalThis.String(object.id) : '',
schedule: isSet(object.schedule)
? globalThis.String(object.schedule)
: '',
command: isSet(object.command) ? globalThis.String(object.command) : '',
extra_schedules: globalThis.Array.isArray(object?.extra_schedules)
? object.extra_schedules.map((e: any) => ISchedule.fromJSON(e))
: [],
name: isSet(object.name) ? globalThis.String(object.name) : "",
max_queue_wait: isSet(object.max_queue_wait) ? globalThis.Number(object.max_queue_wait) : 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,
name: isSet(object.name) ? globalThis.String(object.name) : '',
max_queue_wait: isSet(object.max_queue_wait)
? globalThis.Number(object.max_queue_wait)
: 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 {
const obj: any = {};
if (message.id !== "") {
if (message.id !== '') {
obj.id = message.id;
}
if (message.schedule !== "") {
if (message.schedule !== '') {
obj.schedule = message.schedule;
}
if (message.command !== "") {
if (message.command !== '') {
obj.command = message.command;
}
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;
}
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 {
const message = createBaseICron();
message.id = object.id ?? "";
message.schedule = object.schedule ?? "";
message.command = object.command ?? "";
message.extra_schedules = object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
message.name = object.name ?? "";
message.id = object.id ?? '';
message.schedule = object.schedule ?? '';
message.command = object.command ?? '';
message.extra_schedules =
object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
message.name = object.name ?? '';
message.max_queue_wait = object.max_queue_wait ?? undefined;
message.catchup_seconds = object.catchup_seconds ?? undefined;
message.recovery_from = object.recovery_from ?? undefined;
@@ -320,7 +347,10 @@ function createBaseAddCronRequest(): 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) {
ICron.encode(v!, writer.uint32(10).fork()).join();
}
@@ -331,7 +361,8 @@ export const AddCronRequest: MessageFns<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;
const message = createBaseAddCronRequest();
while (reader.pos < end) {
@@ -364,8 +395,12 @@ export const AddCronRequest: MessageFns<AddCronRequest> = {
fromJSON(object: any): AddCronRequest {
return {
crons: globalThis.Array.isArray(object?.crons) ? object.crons.map((e: any) => ICron.fromJSON(e)) : [],
replace: isSet(object.replace) ? globalThis.Boolean(object.replace) : false,
crons: globalThis.Array.isArray(object?.crons)
? 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;
},
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));
},
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(object: I): AddCronRequest {
fromPartial<I extends Exact<DeepPartial<AddCronRequest>, I>>(
object: I,
): AddCronRequest {
const message = createBaseAddCronRequest();
message.crons = object.crons?.map((e) => ICron.fromPartial(e)) || [];
message.replace = object.replace ?? false;
@@ -396,12 +435,16 @@ function createBaseAddCronResponse(): AddCronResponse {
}
export const AddCronResponse: MessageFns<AddCronResponse> = {
encode(_: AddCronResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
encode(
_: AddCronResponse,
writer: BinaryWriter = new BinaryWriter(),
): BinaryWriter {
return writer;
},
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;
const message = createBaseAddCronResponse();
while (reader.pos < end) {
@@ -425,10 +468,14 @@ export const AddCronResponse: MessageFns<AddCronResponse> = {
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));
},
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(_: I): AddCronResponse {
fromPartial<I extends Exact<DeepPartial<AddCronResponse>, I>>(
_: I,
): AddCronResponse {
const message = createBaseAddCronResponse();
return message;
},
@@ -439,7 +486,10 @@ function createBaseDeleteCronRequest(): 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) {
writer.uint32(10).string(v!);
}
@@ -447,7 +497,8 @@ export const DeleteCronRequest: MessageFns<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;
const message = createBaseDeleteCronRequest();
while (reader.pos < end) {
@@ -471,7 +522,11 @@ export const DeleteCronRequest: MessageFns<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 {
@@ -482,10 +537,14 @@ export const DeleteCronRequest: MessageFns<DeleteCronRequest> = {
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));
},
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(object: I): DeleteCronRequest {
fromPartial<I extends Exact<DeepPartial<DeleteCronRequest>, I>>(
object: I,
): DeleteCronRequest {
const message = createBaseDeleteCronRequest();
message.ids = object.ids?.map((e) => e) || [];
return message;
@@ -497,12 +556,19 @@ function createBaseDeleteCronResponse(): DeleteCronResponse {
}
export const DeleteCronResponse: MessageFns<DeleteCronResponse> = {
encode(_: DeleteCronResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
encode(
_: DeleteCronResponse,
writer: BinaryWriter = new BinaryWriter(),
): BinaryWriter {
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): DeleteCronResponse {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
decode(
input: BinaryReader | Uint8Array,
length?: number,
): DeleteCronResponse {
const reader =
input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseDeleteCronResponse();
while (reader.pos < end) {
@@ -526,10 +592,14 @@ export const DeleteCronResponse: MessageFns<DeleteCronResponse> = {
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));
},
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(_: I): DeleteCronResponse {
fromPartial<I extends Exact<DeepPartial<DeleteCronResponse>, I>>(
_: I,
): DeleteCronResponse {
const message = createBaseDeleteCronResponse();
return message;
},
@@ -540,15 +610,22 @@ function createBaseSetConcurrencyRequest(): 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) {
writer.uint32(8).int32(message.concurrency);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): SetConcurrencyRequest {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
decode(
input: BinaryReader | Uint8Array,
length?: number,
): SetConcurrencyRequest {
const reader =
input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseSetConcurrencyRequest();
while (reader.pos < end) {
@@ -572,7 +649,11 @@ export const SetConcurrencyRequest: MessageFns<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 {
@@ -583,10 +664,14 @@ export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
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));
},
fromPartial<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(object: I): SetConcurrencyRequest {
fromPartial<I extends Exact<DeepPartial<SetConcurrencyRequest>, I>>(
object: I,
): SetConcurrencyRequest {
const message = createBaseSetConcurrencyRequest();
message.concurrency = object.concurrency ?? 0;
return message;
@@ -596,30 +681,36 @@ export const SetConcurrencyRequest: MessageFns<SetConcurrencyRequest> = {
export type CronService = typeof CronService;
export const CronService = {
addCron: {
path: "/com.ql.cron.Cron/addCron",
path: '/com.ql.cron.Cron/addCron',
requestStream: 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),
responseSerialize: (value: AddCronResponse) => Buffer.from(AddCronResponse.encode(value).finish()),
responseSerialize: (value: AddCronResponse) =>
Buffer.from(AddCronResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
},
delCron: {
path: "/com.ql.cron.Cron/delCron",
path: '/com.ql.cron.Cron/delCron',
requestStream: 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),
responseSerialize: (value: DeleteCronResponse) => Buffer.from(DeleteCronResponse.encode(value).finish()),
responseSerialize: (value: DeleteCronResponse) =>
Buffer.from(DeleteCronResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => DeleteCronResponse.decode(value),
},
setConcurrency: {
path: "/com.ql.cron.Cron/setConcurrency",
path: '/com.ql.cron.Cron/setConcurrency',
requestStream: 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),
responseSerialize: (value: AddCronResponse) => Buffer.from(AddCronResponse.encode(value).finish()),
responseSerialize: (value: AddCronResponse) =>
Buffer.from(AddCronResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => AddCronResponse.decode(value),
},
} as const;
@@ -648,18 +739,27 @@ export interface CronClient extends Client {
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
metadata: Metadata,
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
delCron(
request: DeleteCronRequest,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (error: ServiceError | null, response: DeleteCronResponse) => void,
callback: (
error: ServiceError | null,
response: DeleteCronResponse,
) => void,
): ClientUnaryCall;
setConcurrency(
request: SetConcurrencyRequest,
@@ -678,31 +778,52 @@ export interface CronClient extends Client {
): ClientUnaryCall;
}
export const CronClient = makeGenericClientConstructor(CronService, "com.ql.cron.Cron") as unknown as {
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): CronClient;
export const CronClient = makeGenericClientConstructor(
CronService,
'com.ql.cron.Cron',
) as unknown as {
new (
address: string,
credentials: ChannelCredentials,
options?: Partial<ClientOptions>,
): CronClient;
service: typeof CronService;
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
: T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
export type DeepPartial<T> = T extends Builtin
? T
: T extends globalThis.Array<infer U>
? globalThis.Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
type KeysOfUnion<T> = T extends T ? keyof T : never;
export type Exact<P, I extends P> = P extends Builtin ? P
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
export type Exact<P, I extends P> = P extends Builtin
? 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 {
const num = globalThis.Number(int64.toString());
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) {
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;
}
+119 -50
View File
@@ -5,7 +5,7 @@
// source: back/protos/health.proto
/* eslint-disable */
import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
import { BinaryReader, BinaryWriter } from '@bufbuild/protobuf/wire';
import {
type CallOptions,
ChannelCredentials,
@@ -19,9 +19,9 @@ import {
Metadata,
type ServiceError,
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 {
service: string;
@@ -39,57 +39,68 @@ export enum HealthCheckResponse_ServingStatus {
UNRECOGNIZED = -1,
}
export function healthCheckResponse_ServingStatusFromJSON(object: any): HealthCheckResponse_ServingStatus {
export function healthCheckResponse_ServingStatusFromJSON(
object: any,
): HealthCheckResponse_ServingStatus {
switch (object) {
case 0:
case "UNKNOWN":
case 'UNKNOWN':
return HealthCheckResponse_ServingStatus.UNKNOWN;
case 1:
case "SERVING":
case 'SERVING':
return HealthCheckResponse_ServingStatus.SERVING;
case 2:
case "NOT_SERVING":
case 'NOT_SERVING':
return HealthCheckResponse_ServingStatus.NOT_SERVING;
case 3:
case "SERVICE_UNKNOWN":
case 'SERVICE_UNKNOWN':
return HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
case -1:
case "UNRECOGNIZED":
case 'UNRECOGNIZED':
default:
return HealthCheckResponse_ServingStatus.UNRECOGNIZED;
}
}
export function healthCheckResponse_ServingStatusToJSON(object: HealthCheckResponse_ServingStatus): string {
export function healthCheckResponse_ServingStatusToJSON(
object: HealthCheckResponse_ServingStatus,
): string {
switch (object) {
case HealthCheckResponse_ServingStatus.UNKNOWN:
return "UNKNOWN";
return 'UNKNOWN';
case HealthCheckResponse_ServingStatus.SERVING:
return "SERVING";
return 'SERVING';
case HealthCheckResponse_ServingStatus.NOT_SERVING:
return "NOT_SERVING";
return 'NOT_SERVING';
case HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN:
return "SERVICE_UNKNOWN";
return 'SERVICE_UNKNOWN';
case HealthCheckResponse_ServingStatus.UNRECOGNIZED:
default:
return "UNRECOGNIZED";
return 'UNRECOGNIZED';
}
}
function createBaseHealthCheckRequest(): HealthCheckRequest {
return { service: "" };
return { service: '' };
}
export const HealthCheckRequest: MessageFns<HealthCheckRequest> = {
encode(message: HealthCheckRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {
if (message.service !== "") {
encode(
message: HealthCheckRequest,
writer: BinaryWriter = new BinaryWriter(),
): BinaryWriter {
if (message.service !== '') {
writer.uint32(10).string(message.service);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): HealthCheckRequest {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
decode(
input: BinaryReader | Uint8Array,
length?: number,
): HealthCheckRequest {
const reader =
input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHealthCheckRequest();
while (reader.pos < end) {
@@ -113,23 +124,29 @@ export const HealthCheckRequest: MessageFns<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 {
const obj: any = {};
if (message.service !== "") {
if (message.service !== '') {
obj.service = message.service;
}
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));
},
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(object: I): HealthCheckRequest {
fromPartial<I extends Exact<DeepPartial<HealthCheckRequest>, I>>(
object: I,
): HealthCheckRequest {
const message = createBaseHealthCheckRequest();
message.service = object.service ?? "";
message.service = object.service ?? '';
return message;
},
};
@@ -139,15 +156,22 @@ function createBaseHealthCheckResponse(): 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) {
writer.uint32(8).int32(message.status);
}
return writer;
},
decode(input: BinaryReader | Uint8Array, length?: number): HealthCheckResponse {
const reader = input instanceof BinaryReader ? input : new BinaryReader(input);
decode(
input: BinaryReader | Uint8Array,
length?: number,
): HealthCheckResponse {
const reader =
input instanceof BinaryReader ? input : new BinaryReader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseHealthCheckResponse();
while (reader.pos < end) {
@@ -171,7 +195,11 @@ export const HealthCheckResponse: MessageFns<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 {
@@ -182,10 +210,14 @@ export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
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));
},
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(object: I): HealthCheckResponse {
fromPartial<I extends Exact<DeepPartial<HealthCheckResponse>, I>>(
object: I,
): HealthCheckResponse {
const message = createBaseHealthCheckResponse();
message.status = object.status ?? 0;
return message;
@@ -195,21 +227,25 @@ export const HealthCheckResponse: MessageFns<HealthCheckResponse> = {
export type HealthService = typeof HealthService;
export const HealthService = {
check: {
path: "/com.ql.health.Health/Check",
path: '/com.ql.health.Health/Check',
requestStream: 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),
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
responseSerialize: (value: HealthCheckResponse) =>
Buffer.from(HealthCheckResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
},
watch: {
path: "/com.ql.health.Health/Watch",
path: '/com.ql.health.Health/Watch',
requestStream: false,
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),
responseSerialize: (value: HealthCheckResponse) => Buffer.from(HealthCheckResponse.encode(value).finish()),
responseSerialize: (value: HealthCheckResponse) =>
Buffer.from(HealthCheckResponse.encode(value).finish()),
responseDeserialize: (value: Buffer) => HealthCheckResponse.decode(value),
},
} as const;
@@ -222,20 +258,32 @@ export interface HealthServer extends UntypedServiceImplementation {
export interface HealthClient extends Client {
check(
request: HealthCheckRequest,
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
check(
request: HealthCheckRequest,
metadata: Metadata,
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
check(
request: HealthCheckRequest,
metadata: Metadata,
options: Partial<CallOptions>,
callback: (error: ServiceError | null, response: HealthCheckResponse) => void,
callback: (
error: ServiceError | null,
response: HealthCheckResponse,
) => void,
): ClientUnaryCall;
watch(request: HealthCheckRequest, options?: Partial<CallOptions>): ClientReadableStream<HealthCheckResponse>;
watch(
request: HealthCheckRequest,
options?: Partial<CallOptions>,
): ClientReadableStream<HealthCheckResponse>;
watch(
request: HealthCheckRequest,
metadata?: Metadata,
@@ -243,23 +291,44 @@ export interface HealthClient extends Client {
): ClientReadableStream<HealthCheckResponse>;
}
export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as {
new (address: string, credentials: ChannelCredentials, options?: Partial<ClientOptions>): HealthClient;
export const HealthClient = makeGenericClientConstructor(
HealthService,
'com.ql.health.Health',
) as unknown as {
new (
address: string,
credentials: ChannelCredentials,
options?: Partial<ClientOptions>,
): HealthClient;
service: typeof HealthService;
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
: T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>
: T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }
export type DeepPartial<T> = T extends Builtin
? T
: T extends globalThis.Array<infer U>
? globalThis.Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
type KeysOfUnion<T> = T extends T ? keyof T : never;
export type Exact<P, I extends P> = P extends Builtin ? P
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
export type Exact<P, I extends P> = P extends Builtin
? P
: P & { [K in keyof P]: Exact<P[K], I[K]> } & {
[K in Exclude<keyof I, KeysOfUnion<P>>]: never;
};
function isSet(value: any): boolean {
return value !== null && value !== undefined;
+46 -23
View File
@@ -1,11 +1,11 @@
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
import { AddCronRequest, AddCronResponse } from '../protos/cron';
import { createCronJob, CronJob } from '../shared/cronScheduler';
import { isValidCronSchedule } from '../shared/cronSchedule';
import { createCronJob, CronJob } from '../cron/scheduling/cronScheduler';
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
import { scheduleStacks } from './data';
import { latestMissedSlot } from '../shared/cronRecovery';
import { slotId } from '../shared/triggerHistory';
import { runCron } from '../shared/runCron';
import { latestMissedSlot } from '../cron/scheduling/cronRecovery';
import { slotId } from '../cron/history';
import { runCron } from '../cron/execution/runCron';
import Logger from '../loaders/logger';
import { t, tf } from '../shared/i18n';
@@ -63,9 +63,15 @@ const addCron = (
const recoveries: (() => Promise<void>)[] = [];
try {
for (const item of desired.values()) {
const signature = JSON.stringify([item.schedule, 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 signature = JSON.stringify([
item.schedule,
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);
if (current && definitions.get(current) === signature) continue;
const jobs: CronJob[] = [];
@@ -75,31 +81,44 @@ const addCron = (
item.schedule,
...(item.extra_schedules || []).map((x) => x.schedule),
].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;
if (!isCurrent()) return;
await runCron(item.command, item, isCurrent, date && {
id: slotId(item.id, ruleIndex, schedule, +date), time: +date, source,
});
await runCron(
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 () => {
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);
if (time !== null) await fire(new Date(time), 'recovery');
});
}
jobs.push(
createCronJob(
schedule,
fire,
{
createCronJob(schedule, fire, {
name: `${item.id}: ${item.name || ''}`,
logger: Logger,
start: false,
},
),
}),
);
}
}
@@ -134,11 +153,15 @@ const addCron = (
}
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) {
savePlan().then(activate).catch(error => {
for (const jobs of prepared.values()) jobs.forEach(job => job.cancel());
savePlan()
.then(activate)
.catch((error) => {
for (const jobs of prepared.values())
jobs.forEach((job) => job.cancel());
callback(error);
});
} else activate();
+36 -13
View File
@@ -10,7 +10,7 @@ import config from '../config';
import { getGrpcCerts } from '../config/grpcCerts';
import { HealthService } from '../protos/health';
import { SchedulerReadiness } from '../shared/schedulerReadiness';
import { SchedulerReadiness } from '../cron/scheduling/schedulerReadiness';
class Client {
readonly readiness = new SchedulerReadiness(() => this.probe());
@@ -19,14 +19,14 @@ class Client {
try {
await new Promise<void>((resolve, reject) => {
this.client.waitForReady(Date.now() + timeoutMs, (err) =>
err ? reject(err) : resolve()
err ? reject(err) : resolve(),
);
});
} catch (error) {
this.readiness.invalidate();
throw Object.assign(
error instanceof Error ? error : new Error(String(error)),
{ status: 503 }
{ status: 503 },
);
}
}
@@ -40,7 +40,12 @@ class Client {
HealthService.check.responseDeserialize,
{ service: 'scheduler' },
{ 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);
return new Promise((resolve, reject) => {
this.client.setConcurrency(
{ concurrency }, new Metadata(), { deadline: Date.now() + 5000 },
{ concurrency },
new Metadata(),
{ deadline: Date.now() + 5000 },
(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();
Object.assign(err, { status: 503 });
}
@@ -83,7 +93,7 @@ class Client {
async addCron(
request: AddCronRequest['crons'],
replace = false
replace = false,
): Promise<AddCronResponse> {
await this.waitForReady(2000);
// Include every rule in a recovery snapshot, but bound a stuck worker.
@@ -99,7 +109,10 @@ class Client {
{ deadline: Date.now() + registrationTimeoutMs },
(err, res) => {
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.
// Reconcile its state from the DB instead of replaying the RPC.
this.readiness.invalidate();
@@ -108,24 +121,34 @@ class Client {
return reject(err);
}
resolve(res);
}
},
);
});
}
async delCron(request: DeleteCronRequest['ids']): Promise<DeleteCronResponse> {
async delCron(
request: DeleteCronRequest['ids'],
): Promise<DeleteCronResponse> {
await this.waitForReady(2000);
return new Promise((resolve, reject) => {
this.client.delCron({ ids: request }, new Metadata(), { deadline: Date.now() + 5000 }, (err, res) => {
this.client.delCron(
{ ids: request },
new Metadata(),
{ deadline: Date.now() + 5000 },
(err, res) => {
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();
Object.assign(err, { status: 503 });
}
return reject(err);
}
resolve(res);
});
},
);
});
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { CronJob } from '../shared/cronScheduler';
import { CronJob } from '../cron/scheduling/cronScheduler';
import { ToadScheduler } from 'toad-scheduler';
export const scheduleStacks = new Map<string, CronJob[]>();
+4 -1
View File
@@ -8,7 +8,10 @@ import {
import { addCron } from './addCron';
import { delCron } from './delCron';
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,
// even if the client times out and sends a replacement snapshot.
+1 -1
View File
@@ -1,7 +1,7 @@
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
import os from 'os';
import { AddCronResponse, SetConcurrencyRequest } from '../protos/cron';
import taskLimit from '../shared/pLimit';
import taskLimit from '../cron/execution/cronLimit';
export async function setConcurrency(
call: ServerUnaryCall<SetConcurrencyRequest, AddCronResponse>,
+271 -849
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -277,9 +277,9 @@ export default class EnvService {
.replace(/'/g, "'\\''")
.trim();
env_string += `export ${key}='${value}'\n`;
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
group.map((x) => x.value).join('&'),
)};\n`;
js_env_string += `process.env[${JSON.stringify(
key,
)}]=${JSON.stringify(group.map((x) => x.value).join('&'))};\n`;
// Serialize data instead of constructing an escaped Python literal.
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
JSON.stringify(group.map((x) => x.value).join('&')),
+20 -6
View File
@@ -27,20 +27,29 @@ export class GrpcServerService {
async initialize() {
try {
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);
const tlsConfig = await initGrpcCerts();
const credentials = ServerCredentials.createSsl(
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,
);
const grpcPort = config.grpcPort;
const hostsToTry = [
config.bindHostGrpc,
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : [])
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : []),
];
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
@@ -50,15 +59,20 @@ export class GrpcServerService {
try {
const address = this.formatGrpcAddress(host, grpcPort);
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, {
port: grpcPort.toString(),
host
host,
});
return boundPort;
} catch (err) {
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,
);
}
}
+20 -8
View File
@@ -12,7 +12,7 @@ export class HttpServerService {
async initialize(expressApp: express.Application, port: number) {
const hostsToTry = [
config.bindHost,
...(config.bindHost === '::' ? ['0.0.0.0'] : [])
...(config.bindHost === '::' ? ['0.0.0.0'] : []),
];
let lastError: Error | null = null;
@@ -20,16 +20,21 @@ export class HttpServerService {
for (const host of hostsToTry) {
try {
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, {
port: port.toString(),
host
host,
});
this.server = server;
return server;
} catch (err) {
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');
}
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) => {
// There is one HTTP worker; accepting here avoids primary IPC handoff
// for every connection. Restore shared listening for custom clusters.
const server = expressApp.listen({
const server = expressApp.listen(
{
port,
host,
exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true',
}, () => {
},
() => {
resolve(server);
});
},
);
server.on('error', (err: Error) => {
server.close();
+5 -1
View File
@@ -8,6 +8,10 @@ export default class LogService {
constructor(@Inject('logger') private logger: winston.Logger) {}
public checkFilePath(filePath: string, fileName: string) {
return resolveFileAccess(config.logPath, [filePath || '', fileName], ['.tmp']);
return resolveFileAccess(
config.logPath,
[filePath || '', fileName],
['.tmp'],
);
}
}
+3 -6
View File
@@ -1,19 +1,16 @@
import { persistNotificationAudit } from '../shared/notificationAudit';
import crypto from 'crypto';
import nodemailer from 'nodemailer';
import { Inject, Service } from 'typedi';
import { Service } from 'typedi';
import { parseBody, parseHeaders } from '../config/util';
import { NotificationInfo } from '../data/notify';
import { t } from '../shared/i18n';
import UserService from './user';
import { readNotificationMode } from '../data/notificationSettings';
import { httpClient } from '../config/http';
import { ProxyAgent } from 'undici';
@Service()
export default class NotificationService {
@Inject((type) => UserService)
private userService!: UserService;
private modeMap = new Map([
['gotify', this.gotify],
['goCqHttpBot', this.goCqHttpBot],
@@ -59,7 +56,7 @@ export default class NotificationService {
let type: string | undefined;
let success = false;
try {
const saved = await this.userService.getNotificationMode();
const saved = await readNotificationMode();
type = notificationInfo?.type || saved.type;
if (type) {
this.title = title;
+47 -18
View File
@@ -6,8 +6,8 @@ import { Service } from 'typedi';
import config from '../config';
import { CrontabStatModel } from '../data/cronStats';
import { sequelize } from '../data';
import { TriggerHistory } from '../shared/triggerHistory';
import { prunedExitMigrationId } from '../shared/schemaMigrations';
import { TriggerHistory } from '../cron/history';
import { prunedExitMigrationId } from '../data/schemaMigrations';
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
import { AuthDataType, SystemModel } from '../data/system';
import {
@@ -27,8 +27,11 @@ function runningInstanceWhere(cutoffMs: number) {
const cutoff = cutoffMs / 1000;
return {
status: { [Op.ne]: InstanceStatus.running },
id: { [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}))`) },
id: {
[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]: [
{ finished_at: { [Op.lt]: cutoff } },
{
@@ -42,8 +45,13 @@ function runningInstanceWhere(cutoffMs: number) {
function retentionCutoffs(policy: RetentionPolicy) {
const now = dayjs();
return {
history: now.subtract(policy.runningInstanceRetentionDays, 'day').startOf('second').valueOf(),
firstDay: now.subtract(policy.cronStatRetentionDays, 'day').format('YYYY-MM-DD'),
history: now
.subtract(policy.runningInstanceRetentionDays, 'day')
.startOf('second')
.valueOf(),
firstDay: now
.subtract(policy.cronStatRetentionDays, 'day')
.format('YYYY-MM-DD'),
};
}
@@ -69,12 +77,16 @@ export default class RetentionService {
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 dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
isDependenceCacheType,
);
const [runningInstances, cronStats, dependenceCaches, triggers] = await Promise.all([
const [runningInstances, cronStats, dependenceCaches, triggers] =
await Promise.all([
policy.runningInstanceRetentionDays > 0
? RunningInstanceModel.count({
where: runningInstanceWhere(cutoffs.history),
@@ -117,7 +129,10 @@ export default class RetentionService {
const preview = await this.preview(request, cutoffs);
const deleted = await sequelize.transaction(async (transaction) => {
const history = new TriggerHistory(sequelize);
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
if (
preview.policy.runningInstanceRetentionDays ||
preview.policy.cronStatRetentionDays
) {
await history.replayPublishedExits(transaction);
}
const runningInstances =
@@ -130,27 +145,41 @@ export default class RetentionService {
let cronStats = 0;
if (preview.policy.cronStatRetentionDays > 0) {
const firstDay = cutoffs.firstDay;
cronStats = await CrontabStatModel.destroy({ where: { date: { [Op.lt]: firstDay } }, transaction });
await sequelize.query(`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
cronStats = await CrontabStatModel.destroy({
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)`,
{ bind: { firstDay }, transaction });
await sequelize.query(`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
(SELECT first_day FROM CronStatRetention WHERE id=1)`, { transaction });
{ bind: { firstDay }, 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 =
preview.policy.runningInstanceRetentionDays > 0
? await history.deleteExpired(cutoffs.history, transaction)
: 0;
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
if (
preview.policy.runningInstanceRetentionDays ||
preview.policy.cronStatRetentionDays
) {
// 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.
// A writer can also win the lock before an interrupted upgrade retries.
// 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)
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
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)))`,
{ bind: { proofMigration: prunedExitMigrationId }, transaction });
{ bind: { proofMigration: prunedExitMigrationId }, transaction },
);
}
return { runningInstances, cronStats, triggers };
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { t } from '../shared/i18n';
import { Service, Inject } from 'typedi';
import winston from 'winston';
import { createCronJob, CronJob } from '../shared/cronScheduler';
import { createCronJob, CronJob } from '../cron/scheduling/cronScheduler';
import { ChildProcessWithoutNullStreams } from 'child_process';
import {
ToadScheduler,
+1 -1
View File
@@ -8,7 +8,7 @@ import ScheduleService, { TaskCallbacks } from './schedule';
import config from '../config';
import { TASK_COMMAND } from '../config/const';
import { getFileContentByName, getPid, killTask, rmPath } from '../config/util';
import taskLimit from '../shared/pLimit';
import taskLimit from '../cron/execution/cronLimit';
@Service()
export default class ScriptService {
+15 -5
View File
@@ -149,7 +149,10 @@ export default class SubscriptionService {
let beforeStr = '';
try {
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);
}
} catch (error: any) {
@@ -186,7 +189,8 @@ export default class SubscriptionService {
}
} catch (error: any) {
afterStr =
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
(error.stderr && error.stderr.toString()) ||
JSON.stringify(error);
}
if (afterStr) {
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.
// Validate each candidate independently, retaining the safe candidate.
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);
if (scriptPath) targets.push(scriptPath);
if (names.repo) {
@@ -329,7 +335,10 @@ export default class SubscriptionService {
if (repoPath) targets.push(repoPath);
}
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);
}
}
@@ -364,7 +373,8 @@ export default class SubscriptionService {
for (const storagePath of new Set(storagePaths)) {
// rm is recursive: an ancestor must also be retained if a surviving
// subscription uses a nested branch, and vice versa.
const shared = retainedPaths.some((retained) =>
const shared = retainedPaths.some(
(retained) =>
retained === storagePath ||
retained.startsWith(`${storagePath}${path.sep}`) ||
storagePath.startsWith(`${retained}${path.sep}`),
+2 -2
View File
@@ -36,9 +36,9 @@ import {
NotifyStatus,
NotifyLogInfo,
} from '../data/system';
import taskLimit from '../shared/pLimit';
import taskLimit from '../cron/execution/cronLimit';
import cronClient from '../schedule/client';
import { withSchedulerMutation } from '../shared/schedulerMutationLock';
import { withSchedulerMutation } from '../cron/scheduling/schedulerMutationLock';
import NotificationService from './notify';
import ScheduleService, { TaskCallbacks } from './schedule';
import SockService from './sock';
+36 -11
View File
@@ -3,11 +3,18 @@ import { readFileSync } from 'fs';
import path from 'path';
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.
export function containerResources(readValue = read, platform = process.platform) {
export function containerResources(
readValue = read,
platform = process.platform,
) {
const hostCpus = os.cpus().length;
const hostMemory = os.totalmem();
let cpus = hostCpus;
@@ -22,17 +29,25 @@ export function containerResources(readValue = read, platform = process.platform
const unified = !match[1];
for (const kind of ['cpu', 'memory', 'cpuset']) {
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) {
let dir = path.join(root, path.normalize(match[2]));
while (dir === root || dir.startsWith(root + '/')) {
const value = (file: string) => readValue(path.join(dir, file));
if (kind === 'cpu') {
const [quota, period] = (unified ? 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);
const [quota, period] = (
unified
? 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') {
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)) {
const count = set.split(',').reduce((n, range) => {
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);
}
} 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) {
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))) {
memTotal = limit;
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,
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1) };
return {
cpus,
memTotal,
memFree,
hostCpus,
hostMemory,
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1),
};
}
-36
View File
@@ -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()));
}
+92 -29
View File
@@ -9,37 +9,60 @@ function isGone(error: unknown) {
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 denied = () => Object.assign(new Error('Invalid directory'), { status: 403 });
const denied = () =>
Object.assign(new Error('Invalid directory'), { status: 403 });
if (!dir) throw denied();
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 });
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) {
if (isGone(error)) return null;
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 matches = await Promise.all(versions.map(async ([parent, expected]) => {
const matches = await Promise.all(
versions.map(async ([parent, expected]) => {
try {
return await directoryVersion(realRoot, parent, blacklist) === expected;
return (
(await directoryVersion(realRoot, parent, blacklist)) === expected
);
} 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);
}
export async function readDirectoryPage(root: string, blacklist: string[], directory: string, after: string,
search: string, foldersOnly: boolean, newestFirst: boolean, limit = 50) {
const blocked = new Set(blacklist.map(name => name.toLowerCase()));
export async function readDirectoryPage(
root: string,
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 versions: DirectoryVersion[] = [];
async function entries(parent: string) {
@@ -47,36 +70,63 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
versions.push([parent, version]);
if (version === null) return [];
try {
return (await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })).filter(e =>
!blocked.has(e.name.toLowerCase()) && (e.isDirectory() || (!foldersOnly && e.isFile())));
return (
await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })
).filter(
(e) =>
!blocked.has(e.name.toLowerCase()) &&
(e.isDirectory() || (!foldersOnly && e.isFile())),
);
} catch (error) {
if (isGone(error)) return [];
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 = [];
let next: string | null = null;
async function row(parent: string, title: string, directory: boolean) {
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 {
const stat = await fs.lstat(path.join(root, key));
if (stat.isFile()) return { title, parent, key, type: 'file', isLeaf: true, size: stat.size };
} catch (error) { if (!isGone(error)) throw error; }
if (stat.isFile())
return {
title,
parent,
key,
type: 'file',
isLeaf: true,
size: stat.size,
};
} catch (error) {
if (!isGone(error)) throw error;
}
}
if (!search) {
const sorted = (await entries(directory)).sort((a,b) =>
const sorted = (await entries(directory)).sort(
(a, b) =>
Number(b.isDirectory()) - Number(a.isDirectory()) ||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1));
const selected = sorted.filter(e => {
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1),
);
const selected = sorted.filter((e) => {
if (!after) return true;
const group = e.isDirectory() ? '0' : '1';
return group > after[0] || (group === after[0] &&
compare(e.name, after.slice(1)) * (newestFirst && !e.isDirectory() ? -1 : 1) > 0);
return (
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 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) {
const last = page[page.length - 1];
next = (last.isDirectory() ? '0' : '1') + last.name;
@@ -84,16 +134,26 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
return { data, next, versions };
}
// 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 }> {
const items = (await entries(parent)).sort((a,b) => compare(a.name,b.name));
async function* walk(
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) {
if (resume.length && item.name < resume[0]) continue;
const same = item.name === resume[0];
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
if (item.isDirectory()) {
try { yield* walk(path.join(parent, item.name), same ? resume.slice(1) : []); }
catch (error) {
if (!isGone(error) && (error as { status?: number }).status !== 403) throw error;
try {
yield* walk(
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);
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 };
}
+48 -13
View File
@@ -4,31 +4,66 @@ import { checkDirectoryVersions, readDirectoryPage } from './directoryPage';
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
return [
celebrate({ body: Joi.array().items(Joi.array().ordered(
Joi.string().allow('').max(4096).required(), Joi.string().max(128).allow(null).required(),
).length(2)).min(1).max(128).required() }),
celebrate({
body: Joi.array()
.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) => {
try {
const current = await checkDirectoryVersions(root(), blacklist, req.body);
const current = await checkDirectoryVersions(
root(),
blacklist,
req.body,
);
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 [
celebrate({ query: Joi.object({
path: Joi.string().allow(''), after: Joi.string().allow(''), search: Joi.string().allow(''),
folders: Joi.boolean(), t: Joi.string(),
}) }),
celebrate({
query: Joi.object({
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) => {
try {
const { path = '', after = '', search = '', folders } = req.query;
const page = await readDirectoryPage(root(), blacklist, String(path), String(after),
String(search), String(folders) === 'true', newestFirst);
const page = await readDirectoryPage(
root(),
blacklist,
String(path),
String(after),
String(search),
String(folders) === 'true',
newestFirst,
);
res.send({ code: 200, ...page });
} catch (error) { next(error); }
} catch (error) {
next(error);
}
},
];
}
+3 -1
View File
@@ -28,7 +28,9 @@ export function resolveFileAccess(
// of the same entry. Check every protected name without case sensitivity.
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
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 '';
try {
const realRoot = fs.realpathSync(resolvedRoot);
+5 -3
View File
@@ -1,8 +1,9 @@
const messages: Record<string, Record<string, string>> = {
zh: {},
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.',
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
@@ -264,7 +265,8 @@ const messages: Record<string, Record<string, string>> = {
'执行after命令...': 'Execute after command...',
'## 执行结束... %s 耗时 %s 秒':
'## 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.',
'调度器注册失败,任务创建已回滚':
'Scheduler registration failed, task creation rolled back',
+29 -17
View File
@@ -47,18 +47,15 @@ function completeUtf8End(buffer: Buffer, start: number, end: number) {
const firstByte = buffer[sequenceStart];
const expectedLength =
firstByte < 0x80
? 1
: firstByte < 0xe0
? 2
: firstByte < 0xf0
? 3
: 4;
firstByte < 0x80 ? 1 : firstByte < 0xe0 ? 2 : firstByte < 0xf0 ? 3 : 4;
return end - sequenceStart < expectedLength ? sequenceStart : end;
}
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(
@@ -75,16 +72,22 @@ export async function readLogChunk(
const requestedOffset = Number.isFinite(options.offset)
? Math.max(0, Math.trunc(options.offset!))
: undefined;
let start = options.tail || requestedOffset === undefined
let start =
options.tail || requestedOffset === undefined
? Math.max(total - limit, 0)
: Math.min(requestedOffset, total);
const resume = options.cursor && !options.tail && requestedOffset !== undefined;
const resume =
options.cursor && !options.tail && requestedOffset !== undefined;
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
let from = resume ? Number(fromText) : start;
let reset = Boolean(resume && (
requestedOffset !== start || !Number.isSafeInteger(from) ||
from < 0 || from > start || start - from > CURSOR_WINDOW_BYTES
));
let reset = Boolean(
resume &&
(requestedOffset !== start ||
!Number.isSafeInteger(from) ||
from < 0 ||
from > start ||
start - from > CURSOR_WINDOW_BYTES),
);
if (reset) from = start = 0;
// 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);
if (resume && !reset) {
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;
start = from = 0;
window = await readWindow(0, limit + 3);
@@ -120,8 +126,14 @@ export async function readLogChunk(
let cursor: string | undefined;
if (options.follow || options.cursor) {
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
cursor = resume && !reset && nextOffset === start ? options.cursor :
`${retainedFrom}.${logDigest(identity, retainedFrom, window.subarray(retainedFrom - from, nextOffset - from))}`;
cursor =
resume && !reset && nextOffset === start
? options.cursor
: `${retainedFrom}.${logDigest(
identity,
retainedFrom,
window.subarray(retainedFrom - from, nextOffset - from),
)}`;
}
return {
+29 -368
View File
@@ -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 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}$/;
// 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) {
const id = process.env.QL_TRIGGER_ID;
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;
// An older supervisor may only have delivered this tuple in its message.
// Journal it before waiting for the SQLite writer or loading the panel.
let journaled = false;
if (exit.version === 1) {
try { writeExit(id, code, signal, time); journaled = Boolean(receiptPath(id)); }
catch (error) { console.error('[scheduler] Could not journal supervisor message:', error); }
try {
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
// 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');
require('ts-node/register/transpile-only');
}
const { triggerHistory } = require('./triggerHistory');
triggerHistory().complete(id, signal || code !== 0 ? 'failed' : 'finished',
signal, code, time, exit.version === 1 ? exit : 'legacy').catch(error => {
const { triggerHistory } = require('../cron/history');
triggerHistory()
.complete(
id,
signal || code !== 0 ? 'failed' : 'finished',
signal,
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());
})
.finally(() => require('../data').sequelize.close());
}
+2 -213
View File
@@ -1,42 +1,12 @@
import { EventEmitter } from 'events';
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
import os from 'os';
import type { Sequelize } from 'sequelize';
import { QueueOccupants, recordQueueAdmission } from './queueDiagnostics';
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';
import type { Dependence } from '../data/dependence';
import type { IDependencyFn, ISchedule, IScheduleFn, TCron } from './interface';
class TaskLimit {
private dependenyLimit = new PQueue({ concurrency: 1 });
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 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({
concurrency: Math.max(os.cpus().length, 4),
});
@@ -46,198 +16,17 @@ class TaskLimit {
private systemLimit = 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;
}
get firstDependencyId() {
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) {
if (this.queuedDependencyIds.has(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>(
schedule: TCron,
fn: IScheduleFn<T>,
+3 -1
View File
@@ -28,7 +28,9 @@ const backend = read(path.resolve(__dirname, '../app.js'));
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
const version = read(path.join(root, 'version.yaml'))
?.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({
instanceId: randomUUID(),
+9 -2
View File
@@ -1,13 +1,20 @@
import Logger from '../loaders/logger';
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();
const started = performance.now();
try {
return await operation();
} finally {
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})`,
);
}
}
+3 -1
View File
@@ -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)) {
throw Object.assign(new Error(t('环境变量名称不可使用')), {
status: 400,
File diff suppressed because it is too large. Load diff
+9 -2
View File
@@ -1,8 +1,15 @@
import { lock } from 'proper-lockfile';
import os from 'os';
import path from 'path';
import { writeFile, open, chmod } from 'fs/promises';
import { fileExist } from '../config/util';
import { writeFile, open, chmod, access } from 'fs/promises';
export async function fileExist(file: any) {
try {
await access(file);
return true;
} catch (error) {
return false;
}
}
export function getUniqueLockPath(filePath: string) {
const sanitizedPath = filePath
+9 -3
View File
@@ -1,5 +1,5 @@
import { Joi } from 'celebrate';
import { isValidCronSchedule } from '../shared/cronSchedule';
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
import { ScheduleType } from '../interface/schedule';
import path from 'path';
import config from '../config';
@@ -71,7 +71,12 @@ export const commonCronSchema = {
// For other absolute paths, ensure they are within the safe log directory
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');
}
}
@@ -89,7 +94,8 @@ export const commonCronSchema = {
return value;
})
.messages({
'string.pattern.base': '日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符',
'string.pattern.base':
'日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符',
'string.max': '日志名称不能超过100个字符',
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
}),
+15 -2
View File
@@ -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.
- 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
+15 -2
View File
@@ -111,9 +111,22 @@ URL 使用面板根地址,可包含代理路径前缀,不附加 `/open`。
- `task run/stop`:`{code:200,data:{taskId:12,action:"run",accepted:true}}`。仅表示请求被接受,不表示任务成功完成。
- 错误:`{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、构建与验证
+55 -12
View File
@@ -30,9 +30,23 @@ try {
{ cwd: root },
),
)[0];
for (const name of ['README.md', '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)));
for (const name of [
'README.md',
'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(
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(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' });
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(
fs.readFileSync(
@@ -90,12 +110,32 @@ try {
assert.match(output, /Usage:|用法|usage/i);
entries.push(name);
}
assert.ok(!manifest.files.some(file => file.path.includes('qinglong-local')));
for (const args of [['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.ok(
!manifest.files.some((file) => file.path.includes('qinglong-local')),
);
for (const args of [
['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.stdout, '');
assert.equal(JSON.parse(result.stderr).code, 2);
@@ -104,7 +144,10 @@ try {
if (process.env.QL_CLI_PACKAGE_OUTPUT) {
const output = path.resolve(process.env.QL_CLI_PACKAGE_OUTPUT);
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(
JSON.stringify(
@@ -34,6 +34,12 @@ App results omit client_secret/tokens unless --show-secrets is explicit. Other r
## 输入和输出 / 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 同样支持这三种输入。
- `--query '{"searchValue":"demo","page":1}'`:查询对象,值为标量或标量数组,CLI 编码为 URL 参数;不要拼接 URL 查询字符串。
- `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 preview` | GET | `crons/preview` | --query '{"schedule":"0 6 * * *"}' |
| `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 labels-delete ` | DELETE | `crons/labels` | --data, --query |
| `ql task labels-create ` | POST | `crons/labels` | --data, --query |
| `ql task disable <id...>` | PUT | `crons/disable` | --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 delete <id...>` | DELETE | `crons` | --query |
| `ql task pin <id...>` | PUT | `crons/pin` | --query |
+3 -1
View File
@@ -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.
`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
+1
View File
@@ -33,6 +33,7 @@ const remoteTaskActions = new Set([
'list',
'get',
'run',
'wait',
'stop',
'logs',
]);
+3 -1
View File
@@ -3,4 +3,6 @@ import { taskMain } from './ql';
export { taskMain } from './ql';
if (require.main === module)
void taskMain().then(code => { process.exitCode = code; });
void taskMain().then((code) => {
process.exitCode = code;
});
+39 -14
View File
@@ -188,7 +188,15 @@ async function prepareProgram(
// Keep command/arguments as argv data, never interpolate or eval them.
args: program
? adjusted
: ['--noprofile', '--norc', '-c', '"$@"', 'ql-command', executable, ...adjusted.slice(1)],
: [
'--noprofile',
'--norc',
'-c',
'"$@"',
'ql-command',
executable,
...adjusted.slice(1),
],
cwd,
languagePreload,
shellScript,
@@ -217,7 +225,12 @@ export async function executeTask(
folder === '/dev/null'
? '/dev/null'
: context.env.real_log_path ||
path.join(folder, `${timestamp(new Date(start))}${triggerId ? "-" + triggerId : ""}.log`);
path.join(
folder,
`${timestamp(new Date(start))}${
triggerId ? '-' + triggerId : ''
}.log`,
);
const fullLog =
logPath === '/dev/null'
? logPath
@@ -244,14 +257,17 @@ export async function executeTask(
const report = async (final: boolean, code = 0, duration = 0) => {
if (!taskId) return;
try {
await receipt.status({
await receipt.status(
{
ids: [taskId],
status: final ? '1' : '0',
pid: String(process.pid),
log_path: logPath,
last_execution_time: started,
last_running_time: duration,
}, final ? code : undefined);
},
final ? code : undefined,
);
} catch {
output(
Buffer.from(
@@ -401,11 +417,17 @@ export async function executeTask(
}
}
}
const timeoutMs = durationMs(options.timeout ?? env.CommandTimeoutTime, env);
const timeoutDirectory = sharedShell && timeoutMs
const timeoutMs = durationMs(
options.timeout ?? env.CommandTimeoutTime,
env,
);
const timeoutDirectory =
sharedShell && timeoutMs
? await fs.mkdtemp(path.join(os.tmpdir(), 'ql-task-timeout-'))
: undefined;
const timeoutMarker = timeoutDirectory ? path.join(timeoutDirectory, 'expired') : '';
const timeoutMarker = timeoutDirectory
? path.join(timeoutDirectory, 'expired')
: '';
try {
return await runProcess(
program.program,
@@ -427,12 +449,15 @@ export async function executeTask(
// Legacy concurrent children merge stderr into their per-account log.
stderrOutput: mode === 'conc' ? undefined : stderrOutput,
timeoutMs,
...(timeoutMarker ? { timeoutControl: { marker: timeoutMarker } } : {}),
...(timeoutMarker
? { timeoutControl: { marker: timeoutMarker } }
: {}),
signal: options.signal,
},
);
} finally {
if (timeoutDirectory) await fs.rm(timeoutDirectory, { recursive: true, force: true });
if (timeoutDirectory)
await fs.rm(timeoutDirectory, { recursive: true, force: true });
}
};
const results =
@@ -446,7 +471,10 @@ export async function executeTask(
: [await invoke(mode === 'desi' ? accounts : undefined)];
exitCode = results.find((result) => result.code !== 0)?.code ?? 0;
timedOut = results.some((result) => result.timedOut);
if (!sharedShell || results.some((result) => result.timedOut && !result.cleanupStarted)) {
if (
!sharedShell ||
results.some((result) => result.timedOut && !result.cleanupStarted)
) {
// JS/Python pre-task hooks run inside the preloader; after hooks run once per task.
const afterEnv: NodeJS.ProcessEnv = {
...env,
@@ -494,10 +522,7 @@ export async function executeTask(
} finally {
if (languageDirectory)
await fs.rm(languageDirectory, { recursive: true, force: true });
durationSeconds = Math.max(
1,
Math.floor((Date.now() - start) / 1000),
);
durationSeconds = Math.max(1, Math.floor((Date.now() - start) / 1000));
await report(true, exitCode, durationSeconds);
output(
Buffer.from(
Loaded 100 of 341 files, more files were not shown because too many files have changed in this diff. Show more