feat: harden cron execution recovery and expose scheduling diagnostics

Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
whyour committed 2026-11-17 01:01:57 +08:00
1 parent 3b6a873520
commit 8a9e70e90b
166 files changed
+18942 -1800

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ check installs dependencies, repairs and reloads; inspect its before/after obser
On a panel containing the selection loader, set `QL_CLI_ROOT=/absolute/path/to/built/cli` to the internal build directory containing the full dist tree, **not an npm installation**. Restart to create private ~/bin ql/task/cron wrappers and prioritize them for panel processes. Independent terminals should use the selected absolute path. Unset the variable and restart to restore Shell entries. Invalid paths report errors without silent fallback. Original Shell entries remain the default.
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. Lifecycle fields follow the installed panel version; customized versions may select QL_CLI_LIFECYCLE=legacy|extended.
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. The CLI negotiates receipt fields with the running panel. Set `QL_CLI_LIFECYCLE=legacy` to force the legacy format.
The separate [qinglong-local skill](skills/qinglong-local/SKILL.md) covers execution and maintenance. Use qinglong-cli for remote API management. QL_LANG=en selects English help/messages while JSON fields remain stable.
+1 -1
View File
@@ -40,7 +40,7 @@ repo/raw 沿用位置参数,使用 QL_DIR/QL_DATA_DIR,不接受 --root/--jso
包含选择加载器的面板设置 `QL_CLI_ROOT=/absolute/path/to/built/cli`,指向包含完整 dist 的面板工具构建目录,**不能指向 npm 包**。重启后加载器在 ~/bin 创建私有 ql/task/cron 包装器,并为面板进程优先使用它们;独立终端应显式使用该路径。清除变量并重启恢复原 Shell 入口。无效路径报错,不静默降级。默认仍保留旧 Shell 入口。
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。生命周期根据已安装面板版本选择字段,定制版本可设置 QL_CLI_LIFECYCLE=legacy|extended。
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。CLI 根据运行中的面板对回执字段的校验结果选择协议。设置 `QL_CLI_LIFECYCLE=legacy` 可强制使用旧格式。
独立 Skill 位于 [skills/qinglong-local](skills/qinglong-local/SKILL.md),包含完整执行与维护参考。远程管理另用 qinglong-cli Skill。`QL_LANG=en` 切换帮助和执行提示;JSON 字段保持一致。
+2 -2
View File
@@ -43,7 +43,7 @@ Use command `--help` and `QL_LANG=en` for English. Command names and JSON fields
## Complete OpenAPI management
The CLI also supports task/subscription CRUD, application and secret management, environment variables, configuration, scripts, logs, dependencies, system, dashboard and user APIs. `ql api routes --json` lists all 143 active routes; three retired file-reading endpoints are excluded. CI compares the catalogue against backend routes. See the [complete bilingual reference](skills/qinglong-cli/references/openapi.md) for every command and payload.
The CLI also supports task/subscription CRUD, application and secret management, environment variables, configuration, scripts, logs, dependencies, system, dashboard and user APIs. `ql api routes --json` lists the active routes; three retired file-reading endpoints are excluded. CI compares the catalogue against backend routes. See the [complete bilingual reference](skills/qinglong-cli/references/openapi.md) for every command and payload.
```sh
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
@@ -68,7 +68,7 @@ Protected requests use `Authorization: Bearer <token>`. Two credential sources a
### Application login
Create a dedicated panel application with the required scopes. Existing scopes retain their original permissions. For read-only access, use `crons:read`, `subscriptions:read`, `envs:read`, `configs:read`, `scripts:read`, `dependencies:read`, `logs:read`, or `dashboard:read`. Script and log downloads use POST but are available to their read-only scopes. `GET /crons/import` writes tasks and is excluded from `crons:read`. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
Create a dedicated panel application with the required scopes. Existing scopes retain their original permissions. For read-only access, use `crons:read`, `subscriptions:read`, `envs:read`, `configs:read`, `scripts:read`, `dependencies:read`, `logs:read`, or `dashboard:read`. Script and log read-only scopes also allow downloads and directory version checks via POST. `GET /crons/import` writes tasks and is excluded from `crons:read`. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
```sh
ql login --url https://ql.example.com
+2 -2
View File
@@ -43,7 +43,7 @@ ql auth logout --json
## 全量 OpenAPI 管理
现在还支持任务/订阅创建、修改、删除,应用管理与密钥重置,以及环境变量、配置、脚本、日志、依赖、系统、仪表盘和用户管理。`ql api routes --json` 列出全部 143 条有效路由;3 条已下线文件读取接口不包含在内。新增命令在 [完整双语参考](skills/qinglong-cli/references/openapi.md) 中逐项列出,路由覆盖由 CI 与后端代码核对。
现在还支持任务/订阅创建、修改、删除,应用管理与密钥重置,以及环境变量、配置、脚本、日志、依赖、系统、仪表盘和用户管理。`ql api routes --json` 列出当前版本的有效路由;3 条已下线文件读取接口不包含在内。新增命令在 [完整双语参考](skills/qinglong-cli/references/openapi.md) 中逐项列出,路由覆盖由 CI 与后端代码核对。
```sh
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
@@ -68,7 +68,7 @@ ql api request PUT /open/crons/run --data '[12,13]' --json
### 应用凭据登录
在面板创建专用应用,按需授予 crons、subscriptions 等权限。旧 scope 保留原有权限;仅读取时可选用 `crons:read`、`subscriptions:read`、`envs:read`、`configs:read`、`scripts:read`、`dependencies:read`、`logs:read`、`dashboard:read`。脚本和日志下载虽使用 POST,也允许对应只读权限;`GET /crons/import` 会写入任务,不属于只读操作。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
在面板创建专用应用,按需授予 crons、subscriptions 等权限。旧 scope 保留原有权限;仅读取时可选用 `crons:read`、`subscriptions:read`、`envs:read`、`configs:read`、`scripts:read`、`dependencies:read`、`logs:read`、`dashboard:read`。脚本和日志的只读权限也允许通过 POST 下载文件和校验目录版本;`GET /crons/import` 会写入任务,不属于只读操作。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
```sh
ql login --url https://ql.example.com
+21 -4
View File
@@ -1,18 +1,28 @@
# OpenAPI 全量参考 / Complete OpenAPI reference
CLI 对应本版本后端的 151 条有效路由。通过 `ql api routes --json` 查看方法、路径、对应命令、位置参数、请求体与上传字段;CLI 测试与 back/api 路由逐项核对。GET configs/:file、scripts/:file、logs/:file 已返回 410,改用 detail 命令,不再暴露旧入口。旧版面板可能没有新路由,以服务端响应为准。
CLI 对应本版本后端的有效路由。通过 `ql api routes --json` 查看方法、路径、对应命令、位置参数、请求体与上传字段;CLI 测试与 back/api 路由逐项核对。GET configs/:file、scripts/:file、logs/:file 已返回 410,改用 detail 命令,不再暴露旧入口。旧版面板可能没有新路由,以服务端响应为准。
The catalogue covers 151 active routes in the current backend. `ql api routes --json` lists methods, paths, commands, positional parameters, bodies and upload fields. A route-coverage test detects drift. Three retired GET :file routes return 410; use detail-based commands. Older panel versions may not implement newer routes.
The catalogue covers the active routes in the current backend. `ql api routes --json` lists methods, paths, commands, positional parameters, bodies and upload fields. A route-coverage test detects drift. Three retired GET :file routes return 410; use detail-based commands. Older panel versions may not implement newer routes.
日志和脚本分页返回 `versions`。应用可将已浏览目录的版本按每组 1 到 128 项交给同一资源的 `entries-check --data`。返回 `current: false` 时,从第一页重新读取。
Log and script pages return `versions`. Pass the visited directories’ versions to the matching `entries-check --data` command in groups of 1 to 128. Restart pagination when it returns `current: false`.
`ql task instances <id>` 默认返回该任务的完整运行历史,按启动时间倒序。显式传 `--query '{"paged":true,"limit":25}'` 后按实例 ID 倒序分页(默认 25,最多 100),将返回的 `next` 作为下一页的 `before`,直到 `next` 为 `null`。刷新指定实例可传 `{"paged":true,"ids":"12,13"}`。触发记录使用独立的 `task triggers` 接口,日志和脚本目录分页使用 `log entries` 和 `script entries`。
`ql task instances <id>` returns the full history ordered by start time by default. Opt in with `--query '{"paged":true,"limit":25}'` to page by descending instance ID (default 25, maximum 100). Pass `next` as `before` until `next` is `null`. Use `{"paged":true,"ids":"12,13"}` to refresh specific rows. Trigger history and directory pagination use separate endpoints.
直接调用 `PUT /open/crons/stop` 时,请求体为任务 ID 数组。需要安全重试的调用方应在首次发送前生成 UUID,放入 `Idempotency-Key` 请求头,并在该操作的所有重试中复用。相同键只处理第一次受理时的实例和排队记录,换用不同任务集合会返回 409。主动发起新的停止操作时使用新键。未携带键的旧客户端每次调用都会停止当前任务实例。
## 认证与权限 / Authentication and permissions
常规使用 `ql login` 的应用凭据。scope 通常对应 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。旧 scope 保留原有权限;上述资源除 system 外可选用对应的 `:read` scope。`crons:read` 不包含会写入任务的 `GET /crons/import`;`scripts:read`、`logs:read` 包含使用 POST 的下载,不包含写入、删除或执行。`dashboard:read` 不允许 POST 统计上报。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;`GET /apps` 会返回 Client Secret,因此不提供 `apps:read`。user、health、update 等路由同样接受服务端权限校验。路由存在不代表现有应用已获授权。
常规使用 `ql login` 的应用凭据。scope 通常对应 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。旧 scope 保留原有权限;上述资源除 system 外可选用对应的 `:read` scope。`crons:read` 不包含会写入任务的 `GET /crons/import`;`scripts:read`、`logs:read` 包含使用 POST 的下载和目录版本校验,不包含写入、删除或执行。`dashboard:read` 不允许 POST 统计上报。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;`GET /apps` 会返回 Client Secret,因此不提供 `apps:read`。user、health、update 等路由同样接受服务端权限校验。路由存在不代表现有应用已获授权。
认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](panel.md#authentication)。应用管理可用已有 apps 权限的应用或授权面板会话;后端创建和更新应用时拒绝授予 apps 权限。QL_URL/QL_ACCESS_TOKEN 不保存、不刷新,不自动退回应用配置。
See the [authentication reference](panel.md#authentication) for application login, direct-token precedence, owner sessions/2FA and logout. App management accepts existing apps-scoped credentials or an authorized owner session; the backend rejects granting apps scope when creating or updating an application. Direct tokens are not saved/refreshed and never fall back to application configuration.
Existing scopes retain their original access. Use the resource's `:read` scope for read-only access to crons, subscriptions, envs, configs, scripts, dependencies, logs, or dashboard. `crons:read` excludes the mutating `GET /crons/import`; `scripts:read` and `logs:read` include downloads (POST), but exclude writes, deletion, and execution. `dashboard:read` excludes statistics reporting (POST). External `system` applications may only read system status and send notifications. `GET /apps` returns Client Secrets, so there is no `apps:read` scope.
Existing scopes retain their original access. Use the resource's `:read` scope for read-only access to crons, subscriptions, envs, configs, scripts, dependencies, logs, or dashboard. `crons:read` excludes the mutating `GET /crons/import`; `scripts:read` and `logs:read` include downloads and directory version checks (POST), but exclude writes, deletion, and execution. `dashboard:read` excludes statistics reporting (POST). External `system` applications may only read system status and send notifications. `GET /apps` returns Client Secrets, so there is no `apps:read` scope.
`auth status --scope <scope>` tests a representative read; update has no read endpoint and is not offered by status. This does not prove permission for every write. `app list/create/update/reset-secret` 默认隐藏 client_secret/tokens;只有明确需要凭据时才加 --show-secrets,并避免把输出记录到共享日志。其他资源/通用请求可能含环境值、配置、脚本、订阅凭据和会话,按敏感数据处理。
@@ -90,6 +100,7 @@ System/user operations below execute remotely through the panel API. They do not
| `ql task view-enable <id...>` | PUT | `crons/views/enable` | --query |
| `ql task list ` | GET | `crons` | --query via api request |
| `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 stop <id...>` | PUT | `crons/stop` | --query via api request |
@@ -105,6 +116,8 @@ System/user operations below execute remotely through the panel API. They do not
| `ql task import ` | GET | `crons/import` | --query |
| `ql task get <id>` | GET | `crons/:id` | --query via api request |
| `ql task status ` | PUT | `crons/status` | --data, --query |
| `ql task daily-results <id>` | GET | `crons/:id/daily-results` | Verified exits and booked results for the last seven days |
| `ql task triggers <id>` | GET | `crons/:id/triggers` | --query '{"offset":0}' |
| `ql task instances <id>` | GET | `crons/:id/instances` | --query |
| `ql task instance-stop <id> <instanceId>` | POST | `crons/:id/instances/:instanceId/stop` | --query |
| `ql task log-files <id>` | GET | `crons/:id/logs` | --query |
@@ -146,6 +159,8 @@ System/user operations below execute remotely through the panel API. They do not
| `ql config save ` | POST | `configs/save` | --data, --query |
| `ql script list ` | GET | `scripts` | --query |
| `ql script get ` | GET | `scripts/detail` | --query |
| `ql script entries ` | GET | `scripts/entries` | --query |
| `ql script entries-check ` | POST | `scripts/entries/check` | --data, --query |
| `ql script history-list ` | GET | `scripts/history` | --query |
| `ql script history-detail ` | GET | `scripts/history/detail` | --query |
| `ql script history-restore ` | PUT | `scripts/history/restore` | --data, --query |
@@ -158,6 +173,8 @@ System/user operations below execute remotely through the panel API. They do not
| `ql script rename ` | PUT | `scripts/rename` | --data, --query |
| `ql log list ` | GET | `logs` | --query |
| `ql log get ` | GET | `logs/detail` | --query |
| `ql log entries ` | GET | `logs/entries` | --query |
| `ql log entries-check ` | POST | `logs/entries/check` | --data, --query |
| `ql log delete ` | DELETE | `logs` | --data, --query |
| `ql log download ` | POST | `logs/download` | --data, --output, --query |
| `ql dependency list ` | GET | `dependencies` | --query |
@@ -18,9 +18,11 @@ export const nodePreloadSource: string = [
' return;',
' }',
'',
" const clientModule = require.cache[require.resolve('./client.js')];",
' const originalResolveFilename = Module._resolveFilename;',
' Module._resolveFilename = function (request, parent, isMain, options) {',
' if (',
' !clientModule.loadingPanelDependencies &&',
' !Module.builtinModules.includes(request) &&',
" !request.startsWith('node:') &&",
" !request.startsWith('.') &&",
+13 -23
View File
@@ -1,13 +1,12 @@
import { extendedLifecycle } from '../runtime/lifecycle';
import { LifecycleReceipt } from '../runtime/lifecycle';
import fs from 'node:fs/promises';
import { writeSync } from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { randomInt, randomUUID } from 'node:crypto';
import { randomInt } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import type { LocalContext } from '../runtime/context';
import { sourceEnvironment } from '../runtime/context';
import { LocalApi } from '../runtime/api';
import { cancellationExitCode, runProcess } from '../runtime/process';
import { within } from '../runtime/files';
import { fail } from '../../shared/errors';
@@ -207,11 +206,8 @@ export async function executeTask(
const started = Math.floor(start / 1000);
const first = options.argv[0]!;
const taskId = await taskIdentity(context, first);
const extended = await extendedLifecycle(context);
const executionId =
extended && context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
? `legacy-system:${started}:${randomUUID()}`
: undefined;
const receipt = new LifecycleReceipt(context, started);
const triggerId = receipt.triggerId;
const fileName = path.basename(first, path.extname(first));
const parent = first.includes('/') ? path.basename(path.dirname(first)) : '';
const folder =
@@ -221,7 +217,7 @@ export async function executeTask(
folder === '/dev/null'
? '/dev/null'
: context.env.real_log_path ||
path.join(folder, `${timestamp(new Date(start))}.log`);
path.join(folder, `${timestamp(new Date(start))}${triggerId ? "-" + triggerId : ""}.log`);
const fullLog =
logPath === '/dev/null'
? logPath
@@ -245,20 +241,17 @@ export async function executeTask(
process.stderr.write(value);
})
: undefined;
const api = new LocalApi(context);
const report = async (final: boolean, code = 0, duration = 0) => {
if (!taskId) return;
try {
await api.call('crons/status', 'PUT', {
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 && extended ? { exit_code: code } : {}),
...(executionId ? { execution_id: executionId } : {}),
});
}, final ? code : undefined);
} catch {
output(
Buffer.from(
@@ -266,13 +259,9 @@ export async function executeTask(
),
);
}
if (final && extended) {
if (final) {
try {
await api.call('dashboard/record', 'POST', {
ref_id: taskId,
code,
elapsed: duration,
});
await receipt.statistics(taskId, code, duration);
} catch {
output(
Buffer.from(
@@ -282,6 +271,7 @@ export async function executeTask(
}
}
};
let durationSeconds = 0;
let exitCode = 1,
timedOut = false;
let languageDirectory: string | undefined;
@@ -504,7 +494,7 @@ export async function executeTask(
} finally {
if (languageDirectory)
await fs.rm(languageDirectory, { recursive: true, force: true });
const durationSeconds = Math.max(
durationSeconds = Math.max(
1,
Math.floor((Date.now() - start) / 1000),
);
@@ -534,8 +524,8 @@ export async function executeTask(
return {
exitCode,
logPath,
durationSeconds: Math.max(1, Math.floor((Date.now() - start) / 1000)),
executionId,
durationSeconds,
executionId: taskId ? receipt.executionId : undefined,
taskId,
timedOut,
};
@@ -167,7 +167,7 @@ async function readState(tmp) {
}
async function getStatus(tmp) {
const state = await readState(tmp);
let state = await readState(tmp);
if (active.has(state.status)) {
let alive = false;
if (Number.isSafeInteger(state.pid) && state.pid > 0) {
@@ -179,8 +179,14 @@ async function getStatus(tmp) {
}
} else alive = Date.now() - state.startedAt < 10000;
if (!alive) {
state.status = 'failed';
state.error = '升级任务意外中断,请重试';
// The worker can publish its terminal state and exit after our first read.
const previous = state;
state = await readState(tmp);
if (active.has(state.status) && state.id === previous.id &&
state.pid === previous.pid && state.startedAt === previous.startedAt) {
state.status = 'failed';
state.error = '升级任务意外中断,请重试';
}
}
}
// Bound reads even when an installer produces a very large log.
@@ -45,6 +45,22 @@ function dependencyFailure(error) {
);
}
// Once the group has received its final signal, its numeric ID can be reused.
function childGroupSignaler(child) {
let finished = false;
return (signal) => {
if (finished) return;
try {
if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal);
else child.kill(signal);
if (signal === 'SIGKILL') finished = true;
} catch (error) {
if (error.code !== 'ESRCH') throw error;
finished = true;
}
};
}
async function prestartBackend(
selected,
{ target, signal, limits = probeLimits(target) },
@@ -136,14 +152,9 @@ async function prestartBackend(
try {
if (child.pid) os.setPriority(child.pid, 10);
} catch {}
const signalGroup = childGroupSignaler(child);
const kill = (signalName) => {
try {
if (process.platform !== 'win32' && child.pid)
process.kill(-child.pid, signalName);
else child.kill(signalName);
} catch (error) {
if (error.code !== 'ESRCH') failure ||= error;
}
try { signalGroup(signalName); } catch (error) { failure ||= error; }
};
const stop = (error) => {
failure ||= error;
@@ -179,8 +190,6 @@ async function prestartBackend(
// Reap the group on exit rather than waiting for those pipes to close.
child.once('exit', () => kill('SIGKILL'));
child.on('close', (code, exitSignal) => {
// Reap descendants even when the backend exits unexpectedly.
kill('SIGKILL');
if (failure) return finish(failure);
if (code !== 0 || !report?.ok)
return finish(
@@ -335,12 +344,9 @@ async function runRepair(program, args, options) {
detached: process.platform !== 'win32',
stdio: ['ignore', 'pipe', 'pipe'],
});
const signalGroup = childGroupSignaler(child);
const kill = (sig) => {
try {
if (child.pid && process.platform !== 'win32')
process.kill(-child.pid, sig);
else child.kill(sig);
} catch {}
try { signalGroup(sig); } catch {}
};
const stop = (error) => {
failure ||= error;
@@ -365,9 +371,9 @@ async function runRepair(program, args, options) {
clearTimeout(timer);
clearTimeout(killTimer);
options.signal?.removeEventListener('abort', abort);
kill('SIGKILL');
};
child.on('error', (error) => {
kill('SIGKILL');
cleanup();
reject(error);
});
+57 -30
View File
@@ -7,6 +7,12 @@ import { fail } from '../../shared/errors';
import { isRecord } from '../../shared/record';
import { operationSignal, requestCancellation } from './cancellation';
export class ReceiptValidationError extends Error {
constructor(readonly field: string) {
super('The running panel rejected the lifecycle field ' + field);
}
}
export class LocalApi {
private token?: string;
constructor(private readonly context: LocalContext) {}
@@ -65,50 +71,71 @@ export class LocalApi {
endpoint: string,
method = 'GET',
body?: unknown,
finishedAt?: number,
): Promise<Record<string, unknown>> {
operationSignal()?.throwIfAborted();
const token = await this.credential();
const port = this.context.env.QlPort || '5700';
if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535)
fail(translate(this.context.env, '本机面板端口无效。'), 2);
const request = requestCancellation(30000);
const retryReceipt = isRecord(body) && !!(body.execution_id || body.trigger_id) &&
((method === 'PUT' && endpoint === 'crons/status') ||
(method === 'POST' && endpoint === 'dashboard/record'));
const payload = body === undefined ? undefined : JSON.stringify(body);
let result: unknown;
try {
const response = await fetch(
`http://127.0.0.1:${port}/open/${endpoint}`,
{
method,
headers: {
Authorization: `Bearer ${token}`,
...(body !== undefined
? { 'Content-Type': 'application/json' }
: {}),
for (let attempt = 0; attempt < 2; attempt++) {
const request = requestCancellation(30000);
try {
const response = await fetch(
`http://127.0.0.1:${port}/open/${endpoint}`,
{
method,
headers: {
Authorization: `Bearer ${token}`,
...(finishedAt !== undefined && { 'X-QL-Finished-At': String(finishedAt) }),
...(body !== undefined
? { 'Content-Type': 'application/json' }
: {}),
},
body: payload,
redirect: 'error',
signal: request.signal,
},
body: body === undefined ? undefined : JSON.stringify(body),
redirect: 'error',
signal: request.signal,
},
);
if (!response.ok) {
await response.body?.cancel();
);
if (!response.ok) {
if (attempt === 0 && method === 'PUT' && endpoint === 'crons/status' && response.status === 400) {
const rejection: unknown = await response.json();
const validation = isRecord(rejection) && rejection.validation;
const detail = isRecord(validation) && validation.body;
if (isRecord(detail) && detail.source === 'body' && Array.isArray(detail.keys) &&
detail.keys.length === 1 && ['trigger_id', 'execution_id', 'exit_code'].includes(detail.keys[0])) {
throw new ReceiptValidationError(detail.keys[0]);
}
} else {
await response.body?.cancel();
}
fail(
translate(
this.context.env,
'本机 API 拒绝请求(HTTP %s)。',
response.status,
),
);
}
result = await response.json();
break;
} catch (error) {
if (error instanceof ReceiptValidationError) throw error;
if (attempt === 0 && retryReceipt && request.signal.aborted && !operationSignal()?.aborted) continue;
fail(
translate(
this.context.env,
'本机 API 拒绝请求(HTTP %s)。',
response.status,
'本机 API 请求失败;请先检查操作结果,不要直接重试写入。',
),
);
} finally {
request.dispose();
}
result = await response.json();
} catch {
fail(
translate(
this.context.env,
'本机 API 请求失败;请先检查操作结果,不要直接重试写入。',
),
);
} finally {
request.dispose();
}
if (!isRecord(result) || result.code !== 200)
fail(
+6 -14
View File
@@ -1,12 +1,10 @@
import { translate } from '../../shared/i18n/index';
import { extendedLifecycle } from './lifecycle';
import { LifecycleReceipt } from './lifecycle';
import { within } from './files';
import fs from 'node:fs/promises';
import { writeSync } from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import type { LocalContext } from './context';
import { LocalApi } from './api';
import { CliError } from '../../shared/errors';
import { withOperationOutput } from './output';
import { cancellableOperation, interruptedCode } from './cancellation';
@@ -32,7 +30,9 @@ export async function loggedOperation<T>(
]
.map((value) => String(value).padStart(2, '0'))
.join('-');
const logPath = context.env.real_log_path || `${action}/${stamp}.log`;
const receipt = new LifecycleReceipt(context, started);
const triggerId = receipt.triggerId;
const logPath = context.env.real_log_path || `${action}/${stamp}${triggerId ? '-' + triggerId : ''}.log`;
const file = within(context.paths.dir_log!, logPath, context.env);
const persist = context.env.real_time !== 'true';
if (persist) await fs.mkdir(path.dirname(file), { recursive: true });
@@ -45,25 +45,17 @@ export async function loggedOperation<T>(
process.stderr.write(chunk);
};
const id = Number(context.env.ID);
const extended = await extendedLifecycle(context);
const executionId =
extended && context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
? `legacy-system:${started}:${randomUUID()}`
: undefined;
const api = new LocalApi(context);
const report = async (final: boolean, code: number) => {
if (!Number.isSafeInteger(id) || id <= 0) return;
try {
await api.call('crons/status', 'PUT', {
await receipt.status({
ids: [id],
status: final ? '1' : '0',
pid: String(process.pid),
log_path: logPath,
last_execution_time: started,
last_running_time: final ? Math.floor((Date.now() - start) / 1000) : 0,
...(final && extended ? { exit_code: code } : {}),
...(executionId ? { execution_id: executionId } : {}),
});
}, final ? code : undefined);
} catch {
output(
Buffer.from(
+58 -46
View File
@@ -1,51 +1,63 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import type { LocalContext } from './context';
import { LocalApi, ReceiptValidationError } from './api';
// The released 2.20 API rejects unknown lifecycle fields and has no dashboard record API.
// Read the installed panel version, never the independently versioned CLI package.
export async function extendedLifecycle(
context: LocalContext,
): Promise<boolean> {
if (context.env.QL_CLI_LIFECYCLE === 'legacy') return false;
if (context.env.QL_CLI_LIFECYCLE === 'extended') return true;
let version: string | undefined;
try {
const manifest: unknown = JSON.parse(
await fs.readFile(path.join(context.root, 'package.json'), 'utf8'),
);
if (
manifest &&
typeof manifest === 'object' &&
'version' in manifest &&
typeof manifest.version === 'string'
)
version = manifest.version;
} catch {}
if (version === undefined) {
try {
// Official 2.x images may omit package.version. Read only the top-level
// scalar release field; no YAML dependency or expression evaluation.
const release = await fs.readFile(
path.join(context.root, 'version.yaml'),
'utf8',
);
const entries = release
.replace(/^\uFEFF/, '')
.split(/\r?\n/)
.filter((line) => /^version:/.test(line));
if (entries.length !== 1) return false;
const scalar =
/^version:[ \t]*(?:"([^"]+)"|'([^']+)'|([^\s#]+))[ \t]*(?:#.*)?$/.exec(
entries[0]!,
);
version = scalar?.[1] ?? scalar?.[2] ?? scalar?.[3];
} catch {
return false;
// Negotiate with the worker that validates the real receipt. Keep the agreed
// wire format for this execution, even if the panel changes before it exits.
export class LifecycleReceipt {
private readonly api: LocalApi;
private identity?: { trigger_id: string } | { execution_id: string };
private extended: boolean;
private startAttempted = false;
private acceptedStart = false;
private finishedAt?: number;
readonly triggerId?: string;
constructor(context: LocalContext, started: number) {
this.api = new LocalApi(context);
this.extended = context.env.QL_CLI_LIFECYCLE !== 'legacy';
const parent = context.env.QL_TRIGGER_ID;
if (!this.extended) return;
if (parent && /^[a-z0-9-]{1,120}$/.test(parent)) {
this.triggerId = parent;
this.identity = { trigger_id: parent };
} else {
const prefix = context.env.QL_EXECUTION_ORIGIN === 'scheduled_system'
? `legacy-system:${started}:` : 'client-';
this.identity = { execution_id: prefix + randomUUID() };
}
}
const match = /^2\.(\d+)\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(
version ?? '',
);
return !!match && Number(match[1]) >= 21;
get executionId() {
return this.identity && 'execution_id' in this.identity ? this.identity.execution_id : undefined;
}
async status(body: Record<string, unknown>, exitCode?: number) {
const starting = exitCode === undefined;
const firstStart = starting && !this.startAttempted;
if (starting) this.startAttempted = true;
if (!starting && this.identity) this.finishedAt ??= Date.now();
try {
await this.api.call('crons/status', 'PUT', {
...body, ...this.identity, ...(!starting && this.extended && { exit_code: exitCode }),
}, starting ? undefined : this.finishedAt);
} catch (error) {
if (!(error instanceof ReceiptValidationError)) throw error;
if (firstStart && this.identity && error.field in this.identity) {
// The old schema rejected this start before its handler could write.
this.identity = undefined;
} else if (!starting && !this.identity && this.extended && error.field === 'exit_code') {
this.extended = false;
} else {
throw error;
}
await this.api.call('crons/status', 'PUT', body);
}
if (starting) this.acceptedStart = true;
}
async statistics(refId: number, code: number, elapsed: number) {
if (this.extended && (this.identity || this.acceptedStart))
await this.api.call('dashboard/record', 'POST', { ref_id: refId, code, elapsed, ...this.identity }, this.finishedAt);
}
}
@@ -199,7 +199,8 @@ async function reconcile(
await api.call(
'crons',
'DELETE',
obsolete.map((row) => row.id),
obsolete.map((row) => ({ id: row.id, command: row.command, script: taskPath(row.command), sub_id: row.sub_id ?? null,
...(typeof row.recovery_from === 'number' && { revision: row.recovery_from }) })),
);
for (const row of obsolete) {
await fs.rm(
@@ -236,6 +237,22 @@ async function reconcile(
return { added, removed };
}
// Branches can contain slashes. Reject a linked namespace component before
// reading an old checkout or moving the staged tree into place.
async function checkNamespace(root: string, name: string, env: NodeJS.ProcessEnv) {
let current = root;
for (const part of name.split('/')) {
current = path.join(current, part);
try {
if ((await fs.lstat(current)).isSymbolicLink())
fail(translate(env, '路径必须位于其管理目录内部。'), 2);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
}
}
export async function syncRepository(
context: LocalContext,
input: SubscriptionInput,
@@ -243,6 +260,9 @@ export async function syncRepository(
const name = repositoryName(input.url, input.branch, context.env);
const destination = within(context.paths.dir_scripts!, name, context.env);
const repoDestination = within(context.paths.dir_repo!, name, context.env);
const checkPaths = () => Promise.all([context.paths.dir_scripts!, context.paths.dir_repo!]
.map(root => checkNamespace(root, name, context.env)));
await checkPaths();
const extensions = (
input.extensions ||
context.env.RepoFileExtensions ||
@@ -325,6 +345,7 @@ export async function syncRepository(
path.join(checkout, file),
within(scripts, file, context.env),
);
await checkPaths();
await replaceDirectory(scripts, destination);
await replaceDirectory(checkout, repoDestination);
const relativePaths = selected.map((file) =>
+12
View File
@@ -59,6 +59,7 @@ export const openOperations: readonly OpenOperation[] = [
},
{ name: 'task list', method: 'GET', path: 'crons', existing: true },
{ name: 'task detail', method: 'GET', path: 'crons/detail' },
{ name: 'task preview', method: 'GET', path: 'crons/preview' },
{ name: 'task create', method: 'POST', path: 'crons', body: 'json' },
{
name: 'task run',
@@ -114,6 +115,13 @@ export const openOperations: readonly OpenOperation[] = [
existing: true,
},
{ name: 'task status', method: 'PUT', path: 'crons/status', body: 'json' },
{ name: 'task daily-results', method: 'GET', path: 'crons/:id/daily-results', params: ['id'] },
{
name: 'task triggers',
method: 'GET',
path: 'crons/:id/triggers',
params: ['id'],
},
{
name: 'task instances',
method: 'GET',
@@ -282,6 +290,8 @@ export const openOperations: readonly OpenOperation[] = [
{ name: 'config save', method: 'POST', path: 'configs/save', body: 'json' },
{ name: 'script list', method: 'GET', path: 'scripts' },
{ name: 'script get', method: 'GET', path: 'scripts/detail' },
{ name: 'script entries', method: 'GET', path: 'scripts/entries' },
{ name: 'script entries-check', method: 'POST', path: 'scripts/entries/check', body: 'json' },
{ name: 'script history-list', method: 'GET', path: 'scripts/history' },
{
name: 'script history-detail',
@@ -326,6 +336,8 @@ export const openOperations: readonly OpenOperation[] = [
},
{ name: 'log list', method: 'GET', path: 'logs' },
{ name: 'log get', method: 'GET', path: 'logs/detail' },
{ name: 'log entries', method: 'GET', path: 'logs/entries' },
{ name: 'log entries-check', method: 'POST', path: 'logs/entries/check', body: 'json' },
{ name: 'log delete', method: 'DELETE', path: 'logs', body: 'json' },
{
name: 'log download',
+68 -96
View File
@@ -4,33 +4,8 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { createContext } = require('../../dist/internal/runtime/context');
const { extendedLifecycle } = require('../../dist/internal/runtime/lifecycle');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
test('installed panel version selects lifecycle schema and unknown versions stay conservative', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-lifecycle-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext({ root }, {});
assert.equal(await extendedLifecycle(context), false);
for (const [version, expected] of [
['2.20.1', false],
['2.19.0', false],
['2.21.0-14', true],
['3.0.0', false],
['invalid', false],
]) {
await fs.writeFile(
path.join(root, 'package.json'),
JSON.stringify({ version }),
);
assert.equal(await extendedLifecycle(context), expected);
}
context.env.QL_CLI_LIFECYCLE = 'extended';
assert.equal(await extendedLifecycle(context), true);
context.env.QL_CLI_LIFECYCLE = 'legacy';
assert.equal(await extendedLifecycle(context), false);
});
test('command log preserves scheduler path and rejects escaping the log directory', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-scheduler-log-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
@@ -50,85 +25,82 @@ test('command log preserves scheduler path and rejects escaping the log director
);
});
test('released version.yaml selects lifecycle only when package version is absent', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-version-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext({ root }, {});
await fs.writeFile(
path.join(root, 'package.json'),
'{"name":"released-panel"}',
);
for (const [release, expected] of [
['version: 2.20.1\nchangeLog: |\n version: 2.99.0\n', false],
['version: 2.21.0-14\npublishTime: 2026-09-25\n', true],
['version: "2.21.1" # release\n', true],
["\ufeffversion: '2.22.0'\r\n", true],
['version: 3.0.0\n', false],
['version: 2.21.invalid\n', false],
['version: 2.21.0\nversion: 2.20.1\n', false],
['changeLog: |\n version: 2.21.0\n', false],
['version: !custom 2.21.0\n', false],
]) {
await fs.writeFile(path.join(root, 'version.yaml'), release);
assert.equal(await extendedLifecycle(context), expected, release);
}
await fs.writeFile(path.join(root, 'version.yaml'), 'version: 2.21.1\n');
await fs.writeFile(path.join(root, 'package.json'), '{"version":"2.20.1"}');
assert.equal(await extendedLifecycle(context), false);
context.env.QL_CLI_LIFECYCLE = 'extended';
assert.equal(await extendedLifecycle(context), true);
context.env.QL_CLI_LIFECYCLE = 'legacy';
assert.equal(await extendedLifecycle(context), false);
delete context.env.QL_CLI_LIFECYCLE;
await fs.rm(path.join(root, 'package.json'));
assert.equal(await extendedLifecycle(context), true);
await fs.rm(path.join(root, 'version.yaml'));
assert.equal(await extendedLifecycle(context), false);
});
test('release-only version metadata controls actual task and maintenance status payloads', async (t) => {
test('managed CLI tasks and maintenance commands report against the parent receipt', async t => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-payload-'));
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-managed-cli-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext(
{ root },
{ PATH: process.env.PATH, ID: '7', no_tee: 'true' },
);
const id = 'parent-receipt-7';
const context = createContext({ root }, {
PATH: process.env.PATH, ID: '7', no_tee: 'true', QL_TRIGGER_ID: id,
QL_CLI_LIFECYCLE: 'extended', QL_EXECUTION_ORIGIN: 'scheduled_system',
});
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(
path.join(context.paths.dir_scripts, 'fixture.sh'),
'return 7',
);
await fs.writeFile(path.join(context.paths.dir_scripts, 'fixture.sh'), 'return 7');
const calls = [];
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
calls.push({ endpoint, body });
return { code: 200 };
});
for (const version of ['2.20.1', '2.21.0-14']) {
await fs.writeFile(
path.join(root, 'version.yaml'),
`version: ${version}\n`,
);
calls.length = 0;
const result = await executeTask(context, {
argv: ['fixture.sh'],
mode: 'now',
});
assert.equal(result.exitCode, 7);
const final = calls
.filter((row) => row.endpoint === 'crons/status')
.at(-1).body;
assert.equal(final.exit_code, version === '2.20.1' ? undefined : 7);
assert.equal(
calls.some((row) => row.endpoint === 'dashboard/record'),
version !== '2.20.1',
);
calls.length = 0;
await loggedOperation(context, 'extra', async () => true);
assert.equal(
calls.at(-1).body.exit_code,
version === '2.20.1' ? undefined : 0,
);
const result = await executeTask(context, { argv: ['fixture.sh'], mode: 'now' });
assert.equal(result.exitCode, 7);
assert.deepEqual(calls.map(r => r.endpoint), ['crons/status', 'crons/status', 'dashboard/record']);
await loggedOperation(context, 'extra', async () => true);
assert.equal(calls.length, 5);
for (const { body } of calls) {
assert.equal(body.trigger_id, id);
assert.equal(body.execution_id, undefined);
}
calls.length = 0;
context.env.QL_CLI_LIFECYCLE = 'legacy';
await loggedOperation(context, 'extra', async () => true);
assert.ok(calls.length);
assert.ok(calls.every(r => !('trigger_id' in r.body)));
});
test('distinct managed triggers in the same clock tick have separate maintenance and task logs', async t => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-same-tick-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const run = async id => {
const context = createContext({ root }, { QL_CLI_LIFECYCLE: 'extended', QL_TRIGGER_ID: id,
PATH: process.env.PATH, no_tee: 'true', log_name: 'shared' });
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(path.join(context.paths.dir_scripts, id + '.sh'), 'echo ' + id);
const command = await loggedOperation(context, 'extra', async () => {});
const task = await executeTask(context, { argv: [id + '.sh'], mode: 'now' });
return { command: command.logPath, file: task.logPath,
content: await fs.readFile(path.join(context.paths.dir_log, task.logPath), 'utf8') };
};
const [a, b] = await Promise.all([run('marker-alpha'), run('marker-bravo')]);
assert.notEqual(a.command, b.command);
assert.notEqual(a.file, b.file);
assert.match(a.content, /marker-alpha/);
assert.doesNotMatch(a.content, /marker-bravo/);
assert.match(b.content, /marker-bravo/);
assert.doesNotMatch(b.content, /marker-alpha/);
});
test('same-tick standalone tasks and commands share a receipt only within one invocation', async t => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-client-receipts-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const context = createContext({root}, {ID:'5', QL_CLI_LIFECYCLE:'extended', no_tee:'true',
real_log_path:'shared.log', PATH:process.env.PATH});
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts, 'receipt.sh'), 'exit 0');
const groups = new Map();
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
const id = body.execution_id;
assert.match(id, /^client-[0-9a-f-]{36}$/);
groups.set(id, [...(groups.get(id) || []), body.status ?? 'stat']);
return {code:200};
});
await Promise.all([executeTask(context, {argv:['receipt.sh'], mode:'now'}),
executeTask(context, {argv:['receipt.sh'], mode:'now'}),
loggedOperation(context, 'extra', async () => {})]);
assert.deepEqual([...groups.values()].map(sequence => sequence.join(',')).sort(), ['0,1','0,1,stat','0,1,stat']);
});
+1
View File
@@ -759,6 +759,7 @@ test('lifecycle reports share execution identity and statistics survive a reject
ref_id: 12,
code: 9,
elapsed: result.durationSeconds,
execution_id: result.executionId,
});
assert.match(
fs.readFileSync(path.join(context.paths.dir_log, result.logPath), 'utf8'),
+119
View File
@@ -287,3 +287,122 @@ for (const language of ['zh', 'en', 'unsupported']) {
assert.deepEqual(seen, ['/open/http', '/open/rejected']);
});
}
test('a lifecycle timeout retries the identical payload once and other writes are not retried', async t => {
const context = await fixture(t, () => {});
await token(context);
const requests = [];
const timer = global.setTimeout;
t.mock.method(global, 'setTimeout', (fn, ms, ...args) => timer(fn, ms === 30000 ? 5 : ms, ...args));
t.mock.method(global, 'fetch', async (_, {body, signal}) => {
requests.push(body);
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), {once:true}));
});
const api = new LocalApi(context);
for (const [endpoint, method, body, attempts] of [
['crons/status','PUT',{ execution_id:'client-' + require('node:crypto').randomUUID(), status:'0' },2],
['dashboard/record','POST',{ trigger_id:'managed-fixture', code:0 },2],
['crons/status','PUT',{ status:'0' },1],
['crons','POST',{ trigger_id:'unrelated' },1],
]) {
requests.length = 0;
await assert.rejects(api.call(endpoint, method, body));
assert.deepEqual(requests, Array(attempts).fill(JSON.stringify(body)));
}
});
test('the live status schema selects every receipt on old, intermediate and upgraded panels', async t => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
let protocol;
const written = [], rejected = [];
const context = await fixture(t, async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
const forbidden = req.url.endsWith('/status') && Object.keys(body).find(field =>
(protocol !== 'identified' && ['execution_id','trigger_id'].includes(field)) ||
(protocol === 'legacy' && field === 'exit_code'));
if (forbidden) {
rejected.push(forbidden);
res.writeHead(400).end(JSON.stringify({validation:{body:{source:'body',keys:[forbidden]}}}));
return;
}
written.push([req.url,body]);
res.end('{"code":200}');
});
await token(context);
Object.assign(context.env, { ID: '12', no_tee: 'true' });
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts,'probe.sh'), 'return 7');
// Even a full newer installation on disk cannot speak on behalf of the old process.
await fs.mkdir(path.join(context.root,'static/build/shared'), {recursive:true});
await fs.writeFile(path.join(context.root,'static/build/shared/executionIdentity.js'), '');
for (protocol of ['legacy', 'exit-code', 'identified']) {
await fs.writeFile(path.join(context.root,'package.json'), JSON.stringify({version:protocol === 'identified' ? '2.20.1' : '2.25.0'}));
for (const managed of [false,true]) {
if (managed) context.env.QL_TRIGGER_ID = 'parent-123';
else delete context.env.QL_TRIGGER_ID;
for (const task of [true,false]) {
written.length = rejected.length = 0;
if (task) assert.equal((await executeTask(context,{argv:['probe.sh'],mode:'now'})).exitCode,7);
else await loggedOperation(context,'extra',async()=>{});
const [start,end] = written.map(r=>r[1]);
const key = managed ? 'trigger_id' : 'execution_id';
assert.deepEqual(rejected, protocol === 'legacy' ? [key,'exit_code'] : protocol === 'exit-code' ? [key] : []);
assert.equal(start.status,'0'); assert.equal(end.status,'1');
assert.equal(end.exit_code, protocol === 'legacy' ? undefined : task ? 7 : 0);
assert.equal(written.length, task && protocol !== 'legacy' ? 3 : 2);
for (const [,body] of written) assert.equal(body[key],start[key]);
if (protocol === 'identified') assert.ok(managed ? start[key] === 'parent-123' : /^client-/.test(start[key]));
else assert.equal(start[key],undefined);
}
}
}
});
test('a missing start response or a non-schema failure never switches a receipt to anonymous', async t => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const calls = [];
let rejectedField;
const ctx = await fixture(t, async (req,res) => {
let raw=''; for await (const chunk of req) raw+=chunk;
calls.push(JSON.parse(raw));
if (!rejectedField) { res.destroy(); return; }
res.writeHead(400).end(JSON.stringify({ validation: {body: {source:'body',keys:[rejectedField]}} }));
});
await token(ctx);
const receipt = new LifecycleReceipt(ctx,10);
await assert.rejects(receipt.status({ids:[5],status:'0'}));
rejectedField = 'execution_id';
await assert.rejects(receipt.status({ids:[5],status:'1'},7));
assert.equal(calls.length,2);
assert.equal(calls[0].execution_id,calls[1].execution_id);
rejectedField = 'pid';
await assert.rejects(new LifecycleReceipt(ctx,11).status({ids:[5],status:'0'}));
assert.equal(calls.length,3);
});
test('dated status, statistics and retries share an exit instant without changing the identified body schema', async t => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const writes=[];
const ctx=await fixture(t,async(req,res)=>{
let raw=''; for await(const chunk of req)raw+=chunk;
const body=JSON.parse(raw);
writes.push({body, time:req.headers['x-ql-finished-at']});
res.end(JSON.stringify({code:200}));
});
await token(ctx);
const receipt=new LifecycleReceipt(ctx,Math.floor(Date.now()/1000));
await receipt.status({status:'0'});
await receipt.status({status:'1'},17);
await receipt.status({status:'1'},17);
await receipt.statistics(1,17,2);
assert.equal(writes[0].time,undefined);
assert.match(writes[1].time,/^\d{13}$/);
for (const {body,time} of writes.slice(1)) {
assert.equal(time,writes[1].time);
assert.equal(body.execution_id,writes[0].body.execution_id);
assert.equal(body.finished_at,undefined);
}
});
+21 -1
View File
@@ -164,7 +164,7 @@ test('subscription reconciliation scopes removals to canonical paths and the cur
});
assert.equal(result.added, 1);
assert.equal(result.removed, 1);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [1]);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [{ id: 1, script: 'owner_repository/old.js', command: rows[0].command, sub_id: 7 }]);
assert.deepEqual(requests.find((r) => r.method === 'POST').body, {
name: 'New task',
schedule: '0 9 * * *',
@@ -359,6 +359,7 @@ test('subscription copy precedence preserves local dependencies while selected s
env: {
...context.env,
SOURCE: source,
dir_shell: path.resolve(__dirname, '../../../shell'),
dir_scripts: legacyRoot,
dir_list_tmp: context.paths.dir_list_tmp,
dir_dep: context.paths.dir_dep,
@@ -431,3 +432,22 @@ test('cron metadata precedence agrees with unchanged legacy add_cron', (t) => {
});
}
});
test('a slash in a branch cannot publish through a linked namespace parent', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-nested-namespace-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const context = createContext({ root }, { PATH: process.env.PATH });
const outside = path.join(root, 'outside');
fs.mkdirSync(outside);
fs.writeFileSync(path.join(outside, 'sentinel'), 'untouched');
for (const dir of [context.paths.dir_repo, context.paths.dir_scripts]) {
fs.mkdirSync(dir, { recursive: true });
const link = path.join(dir, 'owner_repo_feature');
fs.symlinkSync(outside, link);
await assert.rejects(syncRepository(context, {
url: 'https://example.invalid/owner/repo.git', branch: 'feature/branch',
}), /管理目录|managed directory/);
assert.deepEqual(fs.readdirSync(outside), ['sentinel']);
fs.unlinkSync(link);
}
});
+14 -9
View File
@@ -24,11 +24,11 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
assert.equal(result.status, 0, `${action} failed: ${result.stderr}`);
assert.equal(JSON.parse(result.stdout).data.completed, true);
};
const login = async () => {
const login = async (password = credentials.password) => {
const response = await fetch('http://127.0.0.1:5700/api/user/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
body: JSON.stringify({ ...credentials, password }),
signal: AbortSignal.timeout(5000),
});
return response.json();
@@ -36,18 +36,23 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
local('resetname', credentials.username);
local('resetpwd', credentials.password);
assert.equal((await login()).code, 200, 'New credentials were not saved');
await api('system/auth/reset', 'PUT', { retries: 4 });
assert.notEqual(
const incorrect = randomUUID();
for (let attempt = 0; attempt < 3; attempt++) {
assert.equal((await login(incorrect)).code, 400, 'Expected a rejected password before throttling');
}
assert.equal(
(await login()).code,
200,
410,
'Fixture failed to activate login limit',
);
local('resetlet');
assert.equal((await login()).code, 200, 'Login limit was not cleared');
await api('system/auth/reset', 'PUT', { twoFactorActivated: true });
assert.notEqual(
const session = await login();
assert.equal(session.code, 200, 'Login limit was not cleared');
assert.ok(session.data.token, 'Fresh owner session required');
await api('system/auth/reset', 'PUT', { twoFactorActivated: true }, session.data.token);
assert.equal(
(await login()).code,
200,
420,
'Fixture failed to activate second factor',
);
local('resettfa');
+10 -1
View File
@@ -2,7 +2,8 @@ const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
const { spawn, spawnSync } = require('node:child_process');
const { once } = require('node:events');
exports.verifyOperator = async function verifyOperator(api) {
const ql = path.join(os.homedir(), 'bin/ql');
@@ -26,12 +27,18 @@ exports.verifyOperator = async function verifyOperator(api) {
schedule: '0 0 1 1 *',
})
).data;
const child = spawn('sleep', ['60']);
const ended = once(child, 'exit');
const start = Math.floor(Date.now() / 1000);
try {
await api('crons/status', 'PUT', {
ids: [task.id],
status: '0',
pid: String(child.pid),
last_execution_time: start,
log_path: 'cli-retention/2000-01-01-kept.log',
});
assert.equal((await api(`crons/${task.id}`)).data.log_path, 'cli-retention/2000-01-01-kept.log');
const result = invoke(['rmlog', '7']);
assert.ok(result.removed.includes('cli-retention/2000-01-01-unused.log'));
assert.ok(result.retained.includes('cli-retention/2000-01-01-kept.log'));
@@ -41,6 +48,8 @@ exports.verifyOperator = async function verifyOperator(api) {
'referenced',
);
} finally {
child.kill();
await ended;
await api('crons', 'DELETE', [task.id]);
}
const service = invoke(['reload']);
+2 -2
View File
@@ -16,12 +16,12 @@ let restoreEntrypoints;
);
const base = 'http://127.0.0.1:5700';
let token;
async function api(endpoint, method = 'GET', body) {
async function api(endpoint, method = 'GET', body, sessionToken = token) {
const response = await fetch(`${base}/api/${endpoint}`, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(sessionToken ? { Authorization: `Bearer ${sessionToken}` } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(10000),