From c5458596c884ccf62460515a49c21535c9c183b9 Mon Sep 17 00:00:00 2001 From: whyour Date: Sun, 22 Nov 2026 12:24:29 +0800 Subject: [PATCH] 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. --- .github/ISSUE_TEMPLATE/feature_request.yml | 8 +- .github/config.yml | 2 +- .github/workflows/build-docker-image.yml | 42 +- .prettierignore | 3 +- AGENTS.md | 6 + back/api/config.ts | 8 +- back/api/cron.ts | 291 +- back/api/dashboard.ts | 338 +- back/api/env.ts | 20 +- back/api/log.ts | 44 +- back/api/script.ts | 14 +- back/api/subscription.ts | 2 +- back/api/system.ts | 12 +- back/app.ts | 143 +- back/bootstrap/systemCron.ts | 73 +- back/config/grpcCerts.ts | 15 +- back/config/util.ts | 59 +- back/cron/compatibility/legacyClient.ts | 637 + .../{shared => cron/execution}/cronCommand.ts | 0 back/cron/execution/cronCommandProcess.ts | 61 + back/cron/execution/cronExecution.ts | 930 ++ back/cron/execution/cronLimit.ts | 253 + .../{shared => cron/execution}/cronOperand.ts | 40 +- .../{shared => cron/execution}/cronProcess.ts | 139 +- .../execution}/cronWaitQueue.ts | 21 +- back/{shared => cron/execution}/runCron.ts | 133 +- back/cron/execution/triggerLifecycle.ts | 806 ++ back/cron/history.ts | 473 + .../executionIdentity.ts => cron/identity.ts} | 17 +- back/cron/queries/cronLog.ts | 166 + back/{shared => cron/queries}/cronPreview.ts | 2 +- back/cron/queries/cronViews.ts | 36 + .../queries}/queueDiagnostics.ts | 0 .../queries}/scheduleAnomalies.ts | 16 +- back/cron/queries/triggerQueries.ts | 79 + .../scheduling}/cronRecovery.ts | 0 .../scheduling}/cronSchedule.ts | 2 +- .../scheduling}/cronScheduler.ts | 55 +- back/cron/scheduling/cronScheduling.ts | 115 + .../scheduling}/scheduleAudit.ts | 60 +- .../scheduling}/schedulerMutationLock.ts | 2 +- .../scheduling}/schedulerReadiness.ts | 9 +- back/cron/scheduling/systemCron.ts | 100 + .../scheduling}/systemScheduleAudit.ts | 59 +- back/cron/schema.ts | 171 + .../settlement}/cronStatistics.ts | 79 +- back/cron/settlement/exitReceipt.cjs | 519 + .../settlement}/legacyDailyStatistics.ts | 117 +- back/cron/settlement/triggerSettlement.ts | 1228 ++ back/cron/types.ts | 40 + back/data/cronStats.ts | 4 +- back/data/index.ts | 6 +- back/data/notificationSettings.ts | 12 + back/data/runningInstance.ts | 7 +- back/{shared => data}/schemaMigrations.ts | 53 +- back/loaders/db.ts | 2 +- back/loaders/express.ts | 4 +- back/loaders/initData.ts | 7 +- back/middlewares/protectedPathCase.ts | 3 +- back/protos/api.ts | 1493 ++- back/protos/cron.ts | 307 +- back/protos/health.ts | 169 +- back/schedule/addCron.ts | 79 +- back/schedule/client.ts | 61 +- back/schedule/data.ts | 2 +- back/schedule/registeredPlans.ts | 5 +- back/schedule/setConcurrency.ts | 2 +- back/services/cron.ts | 1140 +- back/services/env.ts | 8 +- back/services/grpc.ts | 26 +- back/services/http.ts | 36 +- back/services/log.ts | 6 +- back/services/notify.ts | 9 +- back/services/retention.ts | 113 +- back/services/schedule.ts | 2 +- back/services/script.ts | 2 +- back/services/sock.ts | 2 +- back/services/subscription.ts | 26 +- back/services/system.ts | 4 +- back/shared/containerResources.ts | 47 +- back/shared/cronCommandProcess.ts | 36 - back/shared/directoryPage.ts | 135 +- back/shared/directoryPageRoute.ts | 61 +- back/shared/fileAccess.ts | 4 +- back/shared/i18n.ts | 8 +- back/shared/logReader.ts | 50 +- back/shared/managedExit.cjs | 403 +- back/shared/pLimit.ts | 215 +- back/shared/runtimeBuild.ts | 4 +- back/shared/startupTiming.ts | 11 +- back/shared/taskEnvName.ts | 4 +- back/shared/triggerHistory.ts | 1563 --- back/shared/utils.ts | 11 +- back/types/express.d.ts | 2 +- back/validation/schedule.ts | 12 +- cli/README.en.md | 17 +- cli/README.md | 17 +- cli/scripts/verify-package.cjs | 67 +- cli/skills/qinglong-cli/references/openapi.md | 10 +- cli/skills/qinglong-cli/references/panel.md | 4 +- cli/src/entrypoints/ql.ts | 1 + cli/src/entrypoints/task.ts | 4 +- cli/src/internal/execution/taskRunner.ts | 69 +- cli/src/internal/maintenance/check.ts | 38 +- cli/src/internal/maintenance/panelUpgrade.cjs | 8 +- .../internal/maintenance/platformBundle.cjs | 20 +- .../internal/maintenance/upgradePrestart.cjs | 19 +- cli/src/internal/runtime/api.ts | 36 +- cli/src/internal/runtime/commandLog.ts | 25 +- cli/src/internal/runtime/lifecycle.ts | 37 +- cli/src/internal/runtime/process.ts | 28 +- .../subscription/subscriptionRunner.ts | 25 +- cli/src/internal/subscription/worker.ts | 5 +- cli/src/remote/api/download.ts | 5 +- cli/src/remote/api/openOperations.ts | 21 +- cli/src/remote/auth/store.ts | 10 +- cli/src/remote/commands/dispatch.ts | 23 +- cli/src/remote/commands/open.ts | 6 +- cli/src/remote/commands/registry.ts | 54 +- cli/src/remote/commands/subscription.ts | 1 - cli/src/remote/commands/task.ts | 54 +- cli/src/remote/commands/taskRun.ts | 151 + cli/src/remote/trigger.ts | 3 + cli/src/remote/types.ts | 6 +- cli/src/shared/cli/invoke.ts | 11 +- cli/src/shared/cli/options.ts | 28 +- cli/src/shared/cli/router.ts | 27 +- cli/src/shared/i18n/en.ts | 18 + cli/src/shared/i18n/help.ts | 18 +- cli/src/shared/resultError.ts | 12 + cli/src/shared/types.ts | 1 + cli/test/integration/differential.test.cjs | 23 +- cli/test/integration/entrypointPaths.test.cjs | 31 +- cli/test/integration/executablePaths.test.cjs | 176 +- cli/test/integration/loadingBoundary.test.cjs | 12 +- cli/test/integration/operatorRouting.test.cjs | 113 +- cli/test/integration/stdin.test.cjs | 75 +- cli/test/internal/armv6-startup.test.cjs | 5 +- cli/test/internal/bootstrap.test.cjs | 4 +- cli/test/internal/botDiagnostics.test.cjs | 20 +- cli/test/internal/containerRuntime.test.cjs | 8 +- .../internal/environmentTransport.test.cjs | 25 +- cli/test/internal/hostServices.test.cjs | 4 +- cli/test/internal/lifecycle.test.cjs | 106 +- cli/test/internal/local.test.cjs | 18 +- cli/test/internal/localApi.test.cjs | 197 +- cli/test/internal/networkRepository.test.cjs | 4 +- .../internal/operatorDiagnostics.test.cjs | 5 +- cli/test/internal/pathDiagnostics.test.cjs | 5 +- cli/test/internal/processDiagnostics.test.cjs | 5 +- cli/test/internal/scriptInventory.test.cjs | 4 +- cli/test/internal/subscriptionFilter.test.cjs | 4 +- cli/test/internal/subscriptionRunner.test.cjs | 33 +- cli/test/internal/taskDelay.test.cjs | 4 +- cli/test/internal/taskLifecycle.test.cjs | 221 +- cli/test/linux/bot-install.cjs | 4 +- cli/test/linux/container-bot.test.cjs | 8 +- cli/test/linux/host-boot.cjs | 7 +- cli/test/linux/image-selection.cjs | 4 +- cli/test/linux/interrupted-reload.cjs | 5 +- cli/test/linux/mounted-data.test.cjs | 5 +- cli/test/linux/openapi.cjs | 213 +- cli/test/linux/panel-account.cjs | 13 +- cli/test/linux/panel-operator.cjs | 5 +- cli/test/linux/panel-upgrade.cjs | 4 +- cli/test/linux/panel.cjs | 21 +- cli/test/linux/published-archive.test.cjs | 8 +- cli/test/linux/ssh-repository.test.cjs | 4 +- cli/test/linux/upgrade.test.cjs | 5 +- cli/test/remote/cli.test.cjs | 26 +- cli/test/remote/logTruncation.test.cjs | 35 +- cli/test/remote/openapi.test.cjs | 512 +- cli/test/remote/platformSmoke.test.cjs | 39 +- cli/test/remote/rawCredentials.test.cjs | 4 +- cli/test/remote/requestBodyCoverage.test.cjs | 42 +- cli/test/remote/scope.test.cjs | 52 +- cli/test/remote/subscription.test.cjs | 7 +- cli/test/remote/taskRun.test.cjs | 320 + cli/test/shared/commander.test.cjs | 87 +- cli/test/shared/i18n.test.cjs | 10 +- deploy/kubernetes/base/qinglong.yaml | 2 +- docker/docker-compose.yml | 4 +- docs/development/execution-modules.md | 106 + docs/development/node-cron-migration.md | 2 +- docs/development/scheduler-reliability-v1.md | 6 +- nodemon.json | 5 +- package.json | 8 +- sample/ql_sample.js | 12 +- scripts/format.cjs | 47 + scripts/prepare-npm-package.cjs | 12 +- scripts/verify-panel-package.cjs | 567 +- scripts/verify-runtime-dependencies.cjs | 33 +- shell/install-package.cjs | 49 +- shell/preload/client.js | 21 +- shell/preload/esm-loader.mjs | 36 +- shell/preload/script-start.cjs | 36 +- shell/preload/sitecustomize.js | 23 +- shell/upgrade.cjs | 4 +- src/app.ts | 16 +- src/components/UpgradeNotice.tsx | 3 +- src/components/fileBrowser/index.less | 119 +- src/components/fileBrowser/index.tsx | 328 +- src/components/fileBrowser/name.ts | 5 +- src/pages/crontab/dailyResults.tsx | 99 +- src/pages/crontab/detail.tsx | 382 +- src/pages/crontab/index.less | 4 +- src/pages/crontab/index.tsx | 136 +- src/pages/crontab/instanceHistory.tsx | 167 +- src/pages/crontab/logModal.tsx | 223 +- src/pages/crontab/modal.tsx | 60 +- src/pages/crontab/stopRequest.ts | 6 +- src/pages/crontab/triggerList.tsx | 40 +- src/pages/crontab/triggerTiming.tsx | 246 +- src/pages/crontab/triggerUpdates.ts | 36 +- src/pages/dashboard/index.less | 73 +- src/pages/dashboard/index.tsx | 1075 +- src/pages/dashboard/scheduleAnomalies.tsx | 310 +- src/pages/dashboard/taskResultModal.tsx | 6 +- src/pages/dashboard/timingStatistic.tsx | 19 +- src/pages/dependence/logModal.tsx | 5 +- src/pages/dependence/type.ts | 2 +- src/pages/diff/index.tsx | 4 +- src/pages/env/editNameModal.tsx | 6 +- src/pages/env/index.tsx | 28 +- src/pages/log/index.tsx | 57 +- src/pages/login/index.tsx | 4 +- .../UnsupportedFilePreview/index.module.less | 2 +- .../UnsupportedFilePreview/index.tsx | 10 +- src/pages/script/editModal.tsx | 36 +- src/pages/script/editNameModal.tsx | 10 +- src/pages/script/index.tsx | 71 +- src/pages/setting/notification.tsx | 8 +- src/pages/setting/other.tsx | 25 +- src/pages/setting/security.tsx | 4 +- src/pages/subscription/index.tsx | 11 +- src/pages/subscription/modal.tsx | 32 +- src/utils/init.ts | 3 +- src/utils/monaco/index.ts | 112 +- test/back/advisory-input-security.test.cjs | 49 +- test/back/api-fallback.test.cjs | 2 +- test/back/armv6-worker-readiness.test.cjs | 6 +- test/back/build-provenance.test.cjs | 9 +- test/back/code-scanning-security.test.cjs | 23 +- test/back/cron-calendar-boundaries.test.cjs | 6 +- test/back/cron-dependencies.test.cjs | 47 + test/back/cron-first-version.test.cjs | 10604 +++++++++++----- test/back/cron-macros.test.cjs | 71 +- test/back/cron-module-paths.test.cjs | 58 + test/back/cron-parser-compatibility.test.cjs | 6 +- test/back/cron-run-receipt.test.cjs | 184 + .../back/cron-schedule-compatibility.test.cjs | 66 +- test/back/cron-scheduler-routing.test.cjs | 278 +- test/back/cron-supervisor-log.test.cjs | 140 +- test/back/cron-validation.test.cjs | 41 +- test/back/database-bootstrap.test.cjs | 339 +- test/back/dev-startup.test.cjs | 88 +- test/back/directory-page.test.cjs | 136 +- test/back/draft-path-security.test.cjs | 24 +- test/back/execution-lifecycle.test.cjs | 12 +- test/back/http-exclusive-listen.test.cjs | 69 +- test/back/http-security.test.cjs | 164 +- test/back/legacy-client-adapter.test.cjs | 288 + test/back/legacy-cron-recovery.test.cjs | 28 +- test/back/linux-dependency-uninstall.test.cjs | 56 +- test/back/linux-mirror-result.test.cjs | 6 +- test/back/log-path-security.test.cjs | 84 +- test/back/logReader.test.cjs | 10 +- test/back/manual-execution.test.cjs | 2 +- test/back/manual-log-survival.test.cjs | 107 +- test/back/manual-stop-claim.test.cjs | 15 +- test/back/mirror-status.test.cjs | 26 +- test/back/node-cron-migration.test.cjs | 85 +- test/back/node-dependency-uninstall.test.cjs | 13 +- test/back/node-path-cache.test.cjs | 23 +- test/back/node-runtime-probe.test.cjs | 21 +- test/back/notification-audit.test.cjs | 9 +- test/back/notification-settings.test.cjs | 33 + test/back/npm-package.test.cjs | 593 +- test/back/npm-publication.test.cjs | 24 +- test/back/offline-upgrade-recovery.test.cjs | 30 +- test/back/panel-upgrade.test.cjs | 7 +- test/back/preload-lazy-notify.test.cjs | 145 +- test/back/primary-apm.test.cjs | 76 +- test/back/process-stop-signal.test.cjs | 122 +- test/back/protected-path-case.test.cjs | 5 +- test/back/qlServiceLogCommand.test.cjs | 4 +- test/back/queued-cron-invalidation.test.cjs | 262 +- test/back/release-runtime-alignment.test.cjs | 131 +- test/back/restart-instance-recovery.test.cjs | 63 +- test/back/retention.test.cjs | 3 +- test/back/scheduler-bulk-recovery.test.cjs | 120 +- test/back/scheduler-concurrency.test.cjs | 28 +- test/back/scheduler-file-lock.test.cjs | 4 +- test/back/scheduler-mutation.test.cjs | 30 +- test/back/scheduler-readiness.test.cjs | 328 +- test/back/scheduler-reconciliation.test.cjs | 81 +- test/back/scheduler-rpc-timeout.test.cjs | 19 +- test/back/schema-migrations.test.cjs | 356 +- test/back/script-file-access.test.cjs | 2 +- test/back/script-notification-rpc.test.cjs | 6 +- test/back/shell-api-parsing.test.cjs | 48 +- test/back/shell-compatibility.test.cjs | 104 +- test/back/shell-translation-output.test.cjs | 17 +- test/back/shell-upgrade.test.cjs | 5 +- test/back/shellApiToken.test.cjs | 173 +- test/back/single-instance-skip.test.cjs | 14 +- .../start-certificate-preparation.test.cjs | 13 +- test/back/stop-failure-feedback.test.cjs | 2 +- test/back/stop-race.test.cjs | 199 +- .../subscription-review-regression.test.cjs | 300 +- .../subscription-storage-regression.test.cjs | 21 +- test/back/system-dependence-cache.test.cjs | 2 +- test/back/system-export-history.test.cjs | 2 +- test/back/system-log-clear.test.cjs | 7 +- test/back/systemTokenRenewal.test.cjs | 375 +- test/back/task-shell-lifecycle.test.cjs | 233 +- test/back/task-time.test.cjs | 9 +- test/back/trigger-lifecycle.test.cjs | 187 + test/back/trigger-queries.test.cjs | 86 + test/back/trigger-settlement.test.cjs | 275 + test/back/update-check.test.cjs | 2 +- test/back/upgrade-download-fallback.test.cjs | 5 +- test/back/upgrade-guards.test.cjs | 15 +- test/back/upgrade-prestart.test.cjs | 26 +- test/back/upgrade-readiness.test.cjs | 262 +- test/back/wpush-grpc.test.cjs | 21 +- test/front/cron-list-polling.test.cjs | 130 +- test/front/cron-log-pagination.test.cjs | 177 +- test/front/dashboard-polling.test.cjs | 619 +- test/front/file-history-races.test.cjs | 333 +- test/front/http-auth.test.cjs | 27 +- test/front/script-history-save.test.cjs | 39 +- test/front/trigger-history-refresh.test.cjs | 1567 ++- test/front/trigger-timing.test.cjs | 233 +- test/front/update-progress.test.cjs | 5 +- test/helpers/load-security-module.cjs | 27 +- test/helpers/manual-log-worker.cjs | 59 +- .../helpers/receipt-allocation-reuse-ext4.cjs | 113 +- test/helpers/receipt-boundary-worker.cjs | 48 +- test/helpers/receipt-claim-reuse-worker.cjs | 68 +- test/helpers/receipt-migration-worker.cjs | 46 +- test/helpers/receipt-publisher-barrier.cjs | 2 +- test/helpers/receipt-reclaim-ext4.cjs | 115 +- test/helpers/receipt-volume-full.cjs | 141 +- test/helpers/runtime-module-graph.cjs | 90 + version.yaml | 2 +- 346 files changed, 32133 insertions(+), 11556 deletions(-) create mode 100644 back/cron/compatibility/legacyClient.ts rename back/{shared => cron/execution}/cronCommand.ts (100%) create mode 100644 back/cron/execution/cronCommandProcess.ts create mode 100644 back/cron/execution/cronExecution.ts create mode 100644 back/cron/execution/cronLimit.ts rename back/{shared => cron/execution}/cronOperand.ts (60%) rename back/{shared => cron/execution}/cronProcess.ts (63%) rename back/{shared => cron/execution}/cronWaitQueue.ts (72%) rename back/{shared => cron/execution}/runCron.ts (73%) create mode 100644 back/cron/execution/triggerLifecycle.ts create mode 100644 back/cron/history.ts rename back/{shared/executionIdentity.ts => cron/identity.ts} (52%) create mode 100644 back/cron/queries/cronLog.ts rename back/{shared => cron/queries}/cronPreview.ts (95%) create mode 100644 back/cron/queries/cronViews.ts rename back/{shared => cron/queries}/queueDiagnostics.ts (100%) rename back/{shared => cron/queries}/scheduleAnomalies.ts (79%) create mode 100644 back/cron/queries/triggerQueries.ts rename back/{shared => cron/scheduling}/cronRecovery.ts (100%) rename back/{shared => cron/scheduling}/cronSchedule.ts (99%) rename back/{shared => cron/scheduling}/cronScheduler.ts (78%) create mode 100644 back/cron/scheduling/cronScheduling.ts rename back/{shared => cron/scheduling}/scheduleAudit.ts (87%) rename back/{shared => cron/scheduling}/schedulerMutationLock.ts (96%) rename back/{shared => cron/scheduling}/schedulerReadiness.ts (92%) create mode 100644 back/cron/scheduling/systemCron.ts rename back/{shared => cron/scheduling}/systemScheduleAudit.ts (88%) create mode 100644 back/cron/schema.ts rename back/{shared => cron/settlement}/cronStatistics.ts (59%) create mode 100644 back/cron/settlement/exitReceipt.cjs rename back/{shared => cron/settlement}/legacyDailyStatistics.ts (78%) create mode 100644 back/cron/settlement/triggerSettlement.ts create mode 100644 back/cron/types.ts create mode 100644 back/data/notificationSettings.ts rename back/{shared => data}/schemaMigrations.ts (79%) delete mode 100644 back/shared/cronCommandProcess.ts delete mode 100644 back/shared/triggerHistory.ts create mode 100644 cli/src/remote/commands/taskRun.ts create mode 100644 cli/src/remote/trigger.ts create mode 100644 cli/src/shared/resultError.ts create mode 100644 cli/test/remote/taskRun.test.cjs create mode 100644 docs/development/execution-modules.md create mode 100644 scripts/format.cjs create mode 100644 test/back/cron-dependencies.test.cjs create mode 100644 test/back/cron-module-paths.test.cjs create mode 100644 test/back/cron-run-receipt.test.cjs create mode 100644 test/back/legacy-client-adapter.test.cjs create mode 100644 test/back/notification-settings.test.cjs create mode 100644 test/back/trigger-lifecycle.test.cjs create mode 100644 test/back/trigger-queries.test.cjs create mode 100644 test/back/trigger-settlement.test.cjs create mode 100644 test/helpers/runtime-module-graph.cjs diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 44630cd3..faa802bf 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -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 @@ -37,4 +37,4 @@ body: description: Before submitting the issue, please make sure you do the following options: - label: Check that there isn't already an issue that request the same feature to avoid creating a duplicate. - required: true \ No newline at end of file + required: true diff --git a/.github/config.yml b/.github/config.yml index 6e3fa563..b6bbbead 100644 --- a/.github/config.yml +++ b/.github/config.yml @@ -4,4 +4,4 @@ newPRWelcomeComment: | Please be patient and we will get back to you as soon as we can. # Comment to be posted to on pull requests merged by a first time user firstPRMergeComment: > - Congrats on merging your first pull request! 🎉🎉🎉 \ No newline at end of file + Congrats on merging your first pull request! 🎉🎉🎉 diff --git a/.github/workflows/build-docker-image.yml b/.github/workflows/build-docker-image.yml index b7349be7..312fe18f 100644 --- a/.github/workflows/build-docker-image.yml +++ b/.github/workflows/build-docker-image.yml @@ -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 diff --git a/.prettierignore b/.prettierignore index 596be03a..07495c43 100644 --- a/.prettierignore +++ b/.prettierignore @@ -12,6 +12,7 @@ npm-debug.log* yarn-error.log yarn.lock package-lock.json +pnpm-lock.yaml /static /data DS_Store @@ -21,4 +22,4 @@ DS_Store .env.local .env version.ts -/.tmp \ No newline at end of file +/.tmp diff --git a/AGENTS.md b/AGENTS.md index 3fdc476b..b9ef3d7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,9 @@ +# 代码格式 + +- 每次修改代码后,必须按项目的 `.prettierrc`、`.editorconfig` 和 `.prettierignore` 完成格式化,覆盖新增文件、静态及动态导入、`require()` 和测试代码。 +- 在项目根目录执行 `npm run prettier`,随后执行 `npm run prettier:check`。检查必须通过;发现格式问题时须修复并重新检查,才能结束任务或提交代码。 +- 检查通过后若再次修改代码,必须重新完成格式化和检查。不得以手动调整格式、编辑器设置或提交钩子代替上述验证。 + # GitNexus — Code Intelligence diff --git a/back/api/config.ts b/back/api/config.ts index 11a3d920..6c41062b 100644 --- a/back/api/config.ts +++ b/back/api/config.ts @@ -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('文件无法访问') }); diff --git a/back/api/cron.ts b/back/api/cron.ts index f69a4a97..1c99d579 100644 --- a/back/api/cron.ts +++ b/back/api/cron.ts @@ -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({ - schedule: Joi.string().required(), - }).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表达式格式有误') }); - } - }); + route.get( + '/preview', + celebrate({ + query: Joi.object({ + schedule: Joi.string().required(), + }).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表达式格式有误') }); + } + }, + ); 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,56 +587,100 @@ export default (app: Router) => { }, ); - route.get('/:id/daily-results', celebrate({ - params: Joi.object({ id: Joi.number().integer().positive().required() }), - }), async (req, res, next) => { - try { - 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({ - params: Joi.object({ id: Joi.number().integer().positive().required() }), - query: Joi.object({ - offset: Joi.number().integer().min(0), - limit: Joi.number().integer().min(1).max(26).default(25), - ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(), - beforeTime: Joi.number().integer().min(0), - beforeId: Joi.string().max(256), - }).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true), - }), async (req, res, next) => { - try { - const { offset, limit, beforeTime, beforeId, ids } = req.query; - const history = triggerHistory(); - const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined; - const data = ids - ? await history.visibleTriggers(Number(req.params.id), ids as string[]) - : await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before); - if (req.query.withQueueWait === 'true') { - const now = Date.now(); - return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null - ? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) }); + route.get( + '/:id/daily-results', + celebrate({ + params: Joi.object({ id: Joi.number().integer().positive().required() }), + }), + async (req, res, next) => { + try { + const data = await readDailyResults( + RunningInstanceModel.sequelize!, + Number(req.params.id), + ); + return res.send({ code: 200, data }); + } catch (error) { + return next(error); } - return res.send({ code: 200, data }); - } catch (err) { next(err); } - }); + }, + ); + + route.get( + '/:id/triggers', + celebrate({ + params: Joi.object({ id: Joi.number().integer().positive().required() }), + query: Joi.object({ + offset: Joi.number().integer().min(0), + limit: Joi.number().integer().min(1).max(26).default(25), + ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(), + beforeTime: Joi.number().integer().min(0), + beforeId: Joi.string().max(256), + }) + .and('beforeTime', 'beforeId') + .oxor('offset', 'beforeTime', 'ids') + .unknown(true), + }), + async (req, res, next) => { + try { + const { offset, limit, beforeTime, beforeId, ids } = req.query; + const history = triggerHistory(); + const before = beforeId + ? { time: Number(beforeTime), id: String(beforeId) } + : undefined; + const data = ids + ? await history.visibleTriggers( + Number(req.params.id), + ids as string[], + ) + : await history.recent( + Number(req.params.id), + Number(offset || 0), + Number(limit), + before, + ); + if (req.query.withQueueWait === 'true') { + const now = Date.now(); + return res.send({ + code: 200, + data: data.map((row) => + row.state === 'queued' && row.queued_at != null + ? { + ...row, + queue_wait_ms: Math.max( + 0, + (row.dequeued_at ?? now) - row.queued_at, + ), + } + : row, + ), + }); + } + return res.send({ code: 200, data }); + } catch (err) { + next(err); + } + }, + ); route.get( '/: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(), { - 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'), - otherwise: Joi.object().unknown(true), - }), + 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'), + 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); diff --git a/back/api/dashboard.ts b/back/api/dashboard.ts index 9a0f50ea..e26b0900 100644 --- a/back/api/dashboard.ts +++ b/back/api/dashboard.ts @@ -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,8 +135,11 @@ export default (app: Router) => { todaySuccess: totalSuccess, todayFail: totalFail, todayStopped: totalRuns - totalSuccess - totalFail, - successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0', - avgTime: averageElapsed(totalTime,totalRuns,row?.untimed_count), + successRate: + totalRuns > 0 + ? ((totalSuccess / totalRuns) * 100).toFixed(1) + : '0', + avgTime: averageElapsed(totalTime, totalRuns, row?.untimed_count), }, }); } catch (e) { @@ -114,55 +148,115 @@ export default (app: Router) => { }, ); - route.get('/schedule-anomalies', celebrate({ query: Joi.object({ - source: Joi.string().valid('panel', 'system').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) => { - try { - const { source, kind, page, at, revision, live } = req.query; - const until = Number(at); - const serverNow = Date.now(); - 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()) - 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 audit = source === 'panel' ? auditSchedule : systemScheduleAudit; - const summary = await audit(CrontabStatModel.sequelize!, dayjs(until).startOf('day').valueOf(), until, details); - if (live && (!summary || summary.since > summary.through)) - return res.send({ code: 200, data: { status: 'unavailable' } }); - if (!summary) return res.status(409).send({ code: 409 }); - const result = details.result(); - const ids = [...new Set(result.rows.filter(row => !row.name).map(row => row.task))]; - const tasks = ids.length ? await CrontabModel.findAll({ where: { id: ids }, attributes: ['id','name','command'], raw: true }) : []; - const names = new Map(tasks.map(task => [task.id, task.name || task.command])); - const rows = await Promise.all(result.rows.map(async ({ logPath, ...row }) => { - const path = logPath && resolveFileAccess(config.logPath, [logPath]); - const hasLog = path ? await stat(path).then(file => file.isFile(), () => false) : false; - return { ...row, name: row.name || names.get(row.task), hasLog }; - })); - // Log checks can yield after the audit transaction. Do not publish that - // snapshot if history cleanup has since removed part of its plan window. - if (live) { - const [retention] = await CrontabStatModel.sequelize!.query<{ cutoff: number }>( - 'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT }, + route.get( + '/schedule-anomalies', + celebrate({ + query: Joi.object({ + source: Joi.string().valid('panel', 'system').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) => { + try { + const { source, kind, page, at, revision, live } = req.query; + const until = Number(at); + const serverNow = Date.now(); + 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() + ) + 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, ); - if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0)) + const audit = source === 'panel' ? auditSchedule : systemScheduleAudit; + const summary = await audit( + CrontabStatModel.sequelize!, + dayjs(until).startOf('day').valueOf(), + until, + details, + ); + if (live && (!summary || summary.since > summary.through)) return res.send({ code: 200, data: { status: 'unavailable' } }); + if (!summary) return res.status(409).send({ code: 409 }); + const result = details.result(); + const ids = [ + ...new Set( + result.rows.filter((row) => !row.name).map((row) => row.task), + ), + ]; + const tasks = ids.length + ? await CrontabModel.findAll({ + where: { id: ids }, + attributes: ['id', 'name', 'command'], + raw: true, + }) + : []; + const names = new Map( + tasks.map((task) => [task.id, task.name || task.command]), + ); + const rows = await Promise.all( + result.rows.map(async ({ logPath, ...row }) => { + const path = + logPath && resolveFileAccess(config.logPath, [logPath]); + const hasLog = path + ? await stat(path).then( + (file) => file.isFile(), + () => false, + ) + : false; + return { ...row, name: row.name || names.get(row.task), hasLog }; + }), + ); + // Log checks can yield after the audit transaction. Do not publish that + // snapshot if history cleanup has since removed part of its plan window. + if (live) { + const [retention] = await CrontabStatModel.sequelize!.query<{ + cutoff: number; + }>('SELECT cutoff FROM CronHistoryRetention WHERE id=1', { + type: QueryTypes.SELECT, + }); + if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0)) + return res.send({ code: 200, data: { status: 'unavailable' } }); + } + if (live && Date.now() >= expiresAt) + return res.send({ code: 200, data: { status: 'expired' } }); + return res.send({ + code: 200, + data: { + ...result, + rows, + serverNow, + expiresAt, + summary: + source === 'panel' + ? { audit: summary } + : { systemAudit: summary }, + zone: Intl.DateTimeFormat().resolvedOptions().timeZone, + }, + }); + } catch (error) { + next(error); } - if (live && Date.now() >= expiresAt) - return res.send({ code: 200, data: { status: 'expired' } }); - return res.send({ code: 200, data: { ...result, rows, serverNow, expiresAt, summary: source === 'panel' ? { audit: summary } : { systemAudit: summary }, zone: Intl.DateTimeFormat().resolvedOptions().timeZone } }); - } catch (error) { next(error); } - }); + }, + ); for (const isSuccess of [false, true]) { 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({ - attributes: ['id', 'name', 'command'], - where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } }, - raw: true, - }) : []; + const crons = + rows.length > 0 + ? await CrontabModel.findAll({ + attributes: ['id', 'name', 'command'], + where: { + id: { [Op.in]: rows.map((row) => Number(row.ref_id)) }, + }, + raw: true, + }) + : []; const cronMap = new Map(crons.map((cron) => [cron.id, cron])); 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,9 +322,10 @@ export default (app: Router) => { const days = requestedDays === undefined ? 7 - : typeof requestedDays === 'string' && /^[1-9]\d{0,2}$/.test(requestedDays) - ? Number(requestedDays) - : NaN; + : typeof requestedDays === 'string' && + /^[1-9]\d{0,2}$/.test(requestedDays) + ? Number(requestedDays) + : NaN; if (!Number.isInteger(days) || days > 365) { return res.status(400).send({ code: 400, message: t('无效的天数') }); } @@ -286,12 +397,14 @@ export default (app: Router) => { raw: true, }); const nameMap: Record = {}; - 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, name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id), - avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count), + avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count), maxTime: Number(r.max_time), })); @@ -329,16 +442,20 @@ export default (app: Router) => { raw: true, }); const nameMap: Record = {}; - 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, name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id), runCount: Number(r.run_count), - avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count), + avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count), successRate: 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, @@ -368,9 +487,9 @@ export default (app: Router) => { const crons = cronIds.length > 0 ? await CrontabModel.findAll({ - where: { id: cronIds }, - raw: true, - }) + where: { id: cronIds }, + raw: true, + }) : []; const cronMap = new Map(crons.map((c: any) => [c.id, c])); @@ -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 = {}; - stats.forEach((s: any) => { statMap[s.ref_id] = s; }); + stats.forEach((s: any) => { + statMap[s.ref_id] = s; + }); - const labelMap: Record = {}; + 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,8 +606,9 @@ export default (app: Router) => { label, count: v.count, todayRuns: v.runs, - successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0', - avgTime: averageElapsed(v.totalTime,v.runs,v.untimed), + 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); diff --git a/back/api/env.ts b/back/api/env.ts index 469088df..8a4a2c9e 100644 --- a/back/api/env.ts +++ b/back/api/env.ts @@ -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' && - /^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) && - typeof x.value === 'string' && x.value.length > 0, + 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, ) ) { 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) { diff --git a/back/api/log.ts b/back/api/log.ts index 425d5a99..98d73cfd 100644 --- a/back/api/log.ts +++ b/back/api/log.ts @@ -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) => { - return res.send({ - code: 410, - message: t('接口已下线,请使用 /logs/detail 接口'), - }); - }, - ); + route.get('/:file', (req: Request, res: Response) => { + return res.send({ + code: 410, + message: t('接口已下线,请使用 /logs/detail 接口'), + }); + }); route.delete( '/', diff --git a/back/api/script.ts b/back/api/script.ts index 908ca3a0..51119be1 100644 --- a/back/api/script.ts +++ b/back/api/script.ts @@ -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, diff --git a/back/api/subscription.ts b/back/api/subscription.ts index 6683d88f..28ab2722 100644 --- a/back/api/subscription.ts +++ b/back/api/subscription.ts @@ -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) => { diff --git a/back/api/system.ts b/back/api/system.ts index 4e872461..c31ef3c4 100644 --- a/back/api/system.ts +++ b/back/api/system.ts @@ -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); } diff --git a/back/app.ts b/back/app.ts index 4bb33e50..bd84d90f 100644 --- a/back/app.ts +++ b/back/app.ts @@ -49,13 +49,14 @@ 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; // Fork gRPC worker first and wait for it to be ready const grpcWorker = this.forkWorker('grpc'); - + // Wait for gRPC worker to signal it's ready before starting HTTP worker this.waitForWorkerReady(grpcWorker, readyTimeout) .then(() => { @@ -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})`, + ); } } @@ -125,11 +137,15 @@ class Application { } }; worker.on('message', messageHandler); - + // 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,23 +155,32 @@ 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()) { - this.httpWorker.send('reregister-crons'); - } - }); + 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 (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 (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); + } + }); this.workerMetadataMap.set(worker.id, { id: worker.id, pid: worker.process.pid!, @@ -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); } } diff --git a/back/bootstrap/systemCron.ts b/back/bootstrap/systemCron.ts index 66c73b76..68804e04 100644 --- a/back/bootstrap/systemCron.ts +++ b/back/bootstrap/systemCron.ts @@ -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:%' + `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) => { - 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()); +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()); diff --git a/back/config/grpcCerts.ts b/back/config/grpcCerts.ts index b8c20abb..fb5adbc2 100644 --- a/back/config/grpcCerts.ts +++ b/back/config/grpcCerts.ts @@ -165,13 +165,14 @@ async function loadExistingCerts(): Promise { return null; } - const [caCert, serverCert, serverKey, clientCert, clientKey] = await Promise.all([ - fs.readFile(caCertPath, 'utf-8'), - fs.readFile(serverCertPath, 'utf-8'), - fs.readFile(serverKeyPath, 'utf-8'), - fs.readFile(clientCertPath, 'utf-8'), - fs.readFile(clientKeyPath, 'utf-8'), - ]); + const [caCert, serverCert, serverKey, clientCert, clientKey] = + await Promise.all([ + fs.readFile(caCertPath, 'utf-8'), + fs.readFile(serverCertPath, 'utf-8'), + fs.readFile(serverKeyPath, 'utf-8'), + fs.readFile(clientCertPath, 'utf-8'), + fs.readFile(clientKeyPath, 'utf-8'), + ]); Logger.info('[boot] Loaded existing gRPC mTLS certificates from disk'); return { caCert, serverCert, serverKey, clientCert, clientKey }; diff --git a/back/config/util.ts b/back/config/util.ts index 97f14733..761af643 100644 --- a/back/config/util.ts +++ b/back/config/util.ts @@ -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 { }); } -export async function killTask(pid: number, waitForExit = false, verifyOwner?: () => void, - withStopRequest?: (signalTree: () => Error | void, targets: string[]) => Promise) { +export async function killTask( + pid: number, + waitForExit = false, + verifyOwner?: () => void, + withStopRequest?: ( + signalTree: () => Error | void, + targets: string[], + ) => Promise, +) { 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); diff --git a/back/cron/compatibility/legacyClient.ts b/back/cron/compatibility/legacyClient.ts new file mode 100644 index 00000000..ccf72cb5 --- /dev/null +++ b/back/cron/compatibility/legacyClient.ts @@ -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; +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 { + 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 }, + ); + }); + } +} diff --git a/back/shared/cronCommand.ts b/back/cron/execution/cronCommand.ts similarity index 100% rename from back/shared/cronCommand.ts rename to back/cron/execution/cronCommand.ts diff --git a/back/cron/execution/cronCommandProcess.ts b/back/cron/execution/cronCommandProcess.ts new file mode 100644 index 00000000..94c926ef --- /dev/null +++ b/back/cron/execution/cronCommandProcess.ts @@ -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 { + return new Promise((resolve, reject) => + child.stdin.end('run\n', (error?: Error) => + error ? reject(error) : resolve(), + ), + ); +} diff --git a/back/cron/execution/cronExecution.ts b/back/cron/execution/cronExecution.ts new file mode 100644 index 00000000..43e22771 --- /dev/null +++ b/back/cron/execution/cronExecution.ts @@ -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['where']): Promise; + makeCommand(tab: Crontab, realTime?: boolean): string; + runSingle( + cronId: number, + expectedToken?: string, + triggerId?: string, + submitted?: Crontab, + ): Promise; + stopInstance(cronId: number, instanceId: number): Promise; + stop(ids: number[], requestId?: string): Promise; +} + +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>(); + + 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 => { + 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>, + batches: Awaited> = [], + ) { + 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) => { + 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 { + 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, + ); + } +} diff --git a/back/cron/execution/cronLimit.ts b/back/cron/execution/cronLimit.ts new file mode 100644 index 00000000..9f12b67a --- /dev/null +++ b/back/cron/execution/cronLimit.ts @@ -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[]>(); + private repeatCronNotifyMap = new Map(); + 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({ + 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) { + 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( + cron: TCron, + fn: ICronFn, + options?: Partial, + isCurrent: () => boolean = () => true, + onPending?: () => void, + waitingSignal?: EventEmitter, + triggerId?: string, + db?: Sequelize, + ): Promise { + 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((resolve, reject) => { + this.cronLimit + .add(run, { + ...options, + waitingSignal, + onRemoved: () => { + this.scheduledOccupants.forget(triggerId); + resolve(); + }, + }) + .then(resolve, reject); + }); + } + + private trackAdmission( + pool: QueueOccupants, + limit: number, + fn: () => Promise, + 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( + fn: () => Promise, + options?: Partial, + occupant: { id?: string; name: string } = { name: '—' }, + db?: Sequelize, + ): Promise { + return this.manualCronoLimit.add( + this.trackAdmission( + this.manualOccupants, + this.manualCronoLimit.concurrency, + fn, + occupant, + db, + ), + options, + ); + } +} + +export default new CronLimit(); diff --git a/back/shared/cronOperand.ts b/back/cron/execution/cronOperand.ts similarity index 60% rename from back/shared/cronOperand.ts rename to back/cron/execution/cronOperand.ts index 06ae1104..03a0a658 100644 --- a/back/shared/cronOperand.ts +++ b/back/cron/execution/cronOperand.ts @@ -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]; } diff --git a/back/shared/cronProcess.ts b/back/cron/execution/cronProcess.ts similarity index 63% rename from back/shared/cronProcess.ts rename to back/cron/execution/cronProcess.ts index bc959f1c..b68940b1 100644 --- a/back/shared/cronProcess.ts +++ b/back/cron/execution/cronProcess.ts @@ -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 => { - 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 []; - throw error; - } - }); - const remainingGrace = Math.min(1000, Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now())); +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 []; + throw error; + } + }); + 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)); } } diff --git a/back/shared/cronWaitQueue.ts b/back/cron/execution/cronWaitQueue.ts similarity index 72% rename from back/shared/cronWaitQueue.ts rename to back/cron/execution/cronWaitQueue.ts index 9fc7a0ae..e73fa873 100644 --- a/back/shared/cronWaitQueue.ts +++ b/back/cron/execution/cronWaitQueue.ts @@ -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 = {}) { 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) { - 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); } } diff --git a/back/shared/runCron.ts b/back/cron/execution/runCron.ts similarity index 73% rename from back/shared/runCron.ts rename to back/cron/execution/runCron.ts index c995c51a..839abbe7 100644 --- a/back/shared/runCron.ts +++ b/back/cron/execution/runCron.ts @@ -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 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 | 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); - }); - } : 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, + ); + }); + } + : 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, () => { - taskLimit.removeQueuedCron(cron.id, execute); - expiry.emit('expired'); - }); - return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize); + 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, + ); } 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 - ? history.skipQueued(trigger.id, outcomeReason, finishedAt) - : history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt), - { priority: 1 }); + await historyWrites.add( + () => + state === 'skipped' && !claimed + ? history.skipQueued(trigger.id, outcomeReason, finishedAt) + : history.complete( + trigger.id, + state, + outcomeReason || null, + exitCode, + finishedAt, + ), + { priority: 1 }, + ); } } } diff --git a/back/cron/execution/triggerLifecycle.ts b/back/cron/execution/triggerLifecycle.ts new file mode 100644 index 00000000..71446ef6 --- /dev/null +++ b/back/cron/execution/triggerLifecycle.ts @@ -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>; + +// 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; + recoverScriptSample(id: string, transaction: Transaction): Promise; + replayPublishedExits(transaction: Transaction): Promise; +} + +// 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, + ) { + 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, + ) { + 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); + }); + } +} diff --git a/back/cron/history.ts b/back/cron/history.ts new file mode 100644 index 00000000..93a1d456 --- /dev/null +++ b/back/cron/history.ts @@ -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>, + finishedAt?: number, + report?: VerifiedSupervisorExit | 'legacy', + recoveredCopies?: Awaited>[], + ) { + 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 { + 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, + ) { + 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, + ) { + 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); +} diff --git a/back/shared/executionIdentity.ts b/back/cron/identity.ts similarity index 52% rename from back/shared/executionIdentity.ts rename to back/cron/identity.ts index 72753ef5..04c1ab77 100644 --- a/back/shared/executionIdentity.ts +++ b/back/cron/identity.ts @@ -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'); +} diff --git a/back/cron/queries/cronLog.ts b/back/cron/queries/cronLog.ts new file mode 100644 index 00000000..aa43358c --- /dev/null +++ b/back/cron/queries/cronLog.ts @@ -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, + ) {} + + public async log( + id: number, + options: CronLogOptions = {}, + ): Promise { + let doc: Pick & { + 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 []; + } + } +} diff --git a/back/shared/cronPreview.ts b/back/cron/queries/cronPreview.ts similarity index 95% rename from back/shared/cronPreview.ts rename to back/cron/queries/cronPreview.ts index 034a1b2d..88223e5b 100644 --- a/back/shared/cronPreview.ts +++ b/back/cron/queries/cronPreview.ts @@ -1,4 +1,4 @@ -import { upcomingSlots } from './cronScheduler'; +import { upcomingSlots } from '../scheduling/cronScheduler'; type Definition = { schedule?: string; diff --git a/back/cron/queries/cronViews.ts b/back/cron/queries/cronViews.ts new file mode 100644 index 00000000..8a778729 --- /dev/null +++ b/back/cron/queries/cronViews.ts @@ -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', + ], +]; diff --git a/back/shared/queueDiagnostics.ts b/back/cron/queries/queueDiagnostics.ts similarity index 100% rename from back/shared/queueDiagnostics.ts rename to back/cron/queries/queueDiagnostics.ts diff --git a/back/shared/scheduleAnomalies.ts b/back/cron/queries/scheduleAnomalies.ts similarity index 79% rename from back/shared/scheduleAnomalies.ts rename to back/cron/queries/scheduleAnomalies.ts index 3400becb..0fd8e081 100644 --- a/back/shared/scheduleAnomalies.ts +++ b/back/cron/queries/scheduleAnomalies.ts @@ -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, + }; } } diff --git a/back/cron/queries/triggerQueries.ts b/back/cron/queries/triggerQueries.ts new file mode 100644 index 00000000..8db866f5 --- /dev/null +++ b/back/cron/queries/triggerQueries.ts @@ -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( + `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( + `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), + }; + } +} diff --git a/back/shared/cronRecovery.ts b/back/cron/scheduling/cronRecovery.ts similarity index 100% rename from back/shared/cronRecovery.ts rename to back/cron/scheduling/cronRecovery.ts diff --git a/back/shared/cronSchedule.ts b/back/cron/scheduling/cronSchedule.ts similarity index 99% rename from back/shared/cronSchedule.ts rename to back/cron/scheduling/cronSchedule.ts index a34174f1..91258a3e 100644 --- a/back/shared/cronSchedule.ts +++ b/back/cron/scheduling/cronSchedule.ts @@ -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 = { '@yearly': '0 0 0 1 1 *', diff --git a/back/shared/cronScheduler.ts b/back/cron/scheduling/cronScheduler.ts similarity index 78% rename from back/shared/cronScheduler.ts rename to back/cron/scheduling/cronScheduler.ts index b33d3b30..812a4bf0 100644 --- a/back/shared/cronScheduler.ts +++ b/back/cron/scheduling/cronScheduler.ts @@ -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, tasks: ScheduledTask[], index: number, date: Date) { +function acceptsSlot( + parsed: ReturnType, + 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,15 +144,17 @@ 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; } } diff --git a/back/cron/scheduling/cronScheduling.ts b/back/cron/scheduling/cronScheduling.ts new file mode 100644 index 00000000..264d6755 --- /dev/null +++ b/back/cron/scheduling/cronScheduling.ts @@ -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, + }; +} diff --git a/back/shared/scheduleAudit.ts b/back/cron/scheduling/scheduleAudit.ts similarity index 87% rename from back/shared/scheduleAudit.ts rename to back/cron/scheduling/scheduleAudit.ts index 9ad05593..e642357e 100644 --- a/back/shared/scheduleAudit.ts +++ b/back/cron/scheduling/scheduleAudit.ts @@ -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( - `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() : null; + const received = + details?.kind === 'missing' && certain ? new Set() : 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, + }); } } } diff --git a/back/shared/schedulerMutationLock.ts b/back/cron/scheduling/schedulerMutationLock.ts similarity index 96% rename from back/shared/schedulerMutationLock.ts rename to back/cron/scheduling/schedulerMutationLock.ts index a31c7fa3..d6437d91 100644 --- a/back/shared/schedulerMutationLock.ts +++ b/back/cron/scheduling/schedulerMutationLock.ts @@ -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). diff --git a/back/shared/schedulerReadiness.ts b/back/cron/scheduling/schedulerReadiness.ts similarity index 92% rename from back/shared/schedulerReadiness.ts rename to back/cron/scheduling/schedulerReadiness.ts index f2100695..2048f0d2 100644 --- a/back/shared/schedulerReadiness.ts +++ b/back/cron/scheduling/schedulerReadiness.ts @@ -66,9 +66,12 @@ export class SchedulerReadiness { }), ]); if (!available) { - throw Object.assign(new Error('Scheduler is recovering; try again later'), { - status: 503, - }); + throw Object.assign( + new Error('Scheduler is recovering; try again later'), + { + status: 503, + }, + ); } } finally { clearTimeout(timer); diff --git a/back/cron/scheduling/systemCron.ts b/back/cron/scheduling/systemCron.ts new file mode 100644 index 00000000..1e18eabf --- /dev/null +++ b/back/cron/scheduling/systemCron.ts @@ -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 }, + ); + } + } +} diff --git a/back/shared/systemScheduleAudit.ts b/back/cron/scheduling/systemScheduleAudit.ts similarity index 88% rename from back/shared/systemScheduleAudit.ts rename to back/cron/scheduling/systemScheduleAudit.ts index 3e179e3a..d2e3bfa9 100644 --- a/back/shared/systemScheduleAudit.ts +++ b/back/cron/scheduling/systemScheduleAudit.ts @@ -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( - `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() : null; + const matched = + details && details.kind !== 'missing' + ? new Map() + : null; const groups = new Map(); const dispatchedTasks = new Set(); const legacyThrough = new Map(); @@ -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, diff --git a/back/cron/schema.ts b/back/cron/schema.ts new file mode 100644 index 00000000..00cdee8e --- /dev/null +++ b/back/cron/schema.ts @@ -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 }, + ); +} diff --git a/back/shared/cronStatistics.ts b/back/cron/settlement/cronStatistics.ts similarity index 59% rename from back/shared/cronStatistics.ts rename to back/cron/settlement/cronStatistics.ts index 258cbcd0..cdba7b00 100644 --- a/back/shared/cronStatistics.ts +++ b/back/cron/settlement/cronStatistics.ts @@ -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 { 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, + }, + }, ); } diff --git a/back/cron/settlement/exitReceipt.cjs b/back/cron/settlement/exitReceipt.cjs new file mode 100644 index 00000000..2a82f98b --- /dev/null +++ b/back/cron/settlement/exitReceipt.cjs @@ -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, +}; diff --git a/back/shared/legacyDailyStatistics.ts b/back/cron/settlement/legacyDailyStatistics.ts similarity index 78% rename from back/shared/legacyDailyStatistics.ts rename to back/cron/settlement/legacyDailyStatistics.ts index 67cacfc7..f10b9fd2 100644 --- a/back/shared/legacyDailyStatistics.ts +++ b/back/cron/settlement/legacyDailyStatistics.ts @@ -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_idr.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(`WITH exits AS ( + const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD'); + const days = await database.query( + `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 }, + }, + ); } } diff --git a/back/cron/settlement/triggerSettlement.ts b/back/cron/settlement/triggerSettlement.ts new file mode 100644 index 00000000..db3f2894 --- /dev/null +++ b/back/cron/settlement/triggerSettlement.ts @@ -0,0 +1,1228 @@ +import { + isLegacyCapture, + isMetadataReceipt, + publishedExits, + publishedScriptStarts, + readExit, + receiptPath, + retireLegacyFile, + retiringExits, + validExit, +} from './exitReceipt.cjs'; +import { QueryTypes, Sequelize, Transaction } from 'sequelize'; +import dayjs from 'dayjs'; +import { addDailyExit, recordCronResult } from './cronStatistics'; +import { promises as fs } from 'fs'; +import { basename, join } from 'path'; +import type { + Trigger, + TriggerSource, + TriggerState, + VerifiedSupervisorExit, +} from '../types'; +import type { + TriggerLifecycle, + TriggerLifecycleEvidence, +} from '../execution/triggerLifecycle'; + +// The lifecycle owns transition guards; settlement must use its caller's transaction. +export type TriggerSettlementLifecycle = Pick< + TriggerLifecycle, + 'finish' | 'shouldStop' +>; + +type ExitObservation = Omit; + +type LegacyExitBooking = { + trigger_id: string; + cron_id: number; + source: TriggerSource; + started_at: number; + finished_at: number; + outcome: string; + stopped: number; + stat_id: number | null; + disputed: number; + bound: number; +}; + +function observationKey(id: string, exit: ExitObservation) { + return { id, outcome: exit.signal ?? String(exit.code), time: exit.time }; +} + +function isBoundPublication(file: string) { + return ( + /^\.(pending|published)\./.test(basename(file)) && !isLegacyCapture(file) + ); +} + +// Receipt verification, disputes and statistics are one transactional unit. +// Durable evidence is retired only after the committed outcome is checked again. +export class TriggerSettlement implements TriggerLifecycleEvidence { + constructor( + private database: Sequelize, + private lifecycle: TriggerSettlementLifecycle, + ) {} + + // 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', + ) { + const sample = await this.readScriptSample(id); + await this.database.transaction(async (transaction) => { + await this.saveScriptSample(id, sample, transaction); + await this.completeCommandExit( + id, + state, + reason, + code, + transaction, + undefined, + finishedAt, + report, + ); + }); + if (sample) await fs.unlink(sample.marker).catch(() => {}); + } + + async completeCommandExit( + id: string, + state: TriggerState, + reason: string | null, + code: number | null, + transaction: Transaction, + receipt?: Awaited>, + finishedAt?: number, + report?: VerifiedSupervisorExit | 'legacy', + recoveredCopies?: Awaited>[], + ) { + const file = receiptPath(id); + let pending = file ? await this.pendingExit(id, transaction) : undefined; + const [saved] = file + ? await this.database.query< + LegacyExitBooking & { + conflicted: number; + unmatched_outcome: string | null; + unmatched_time: number | null; + } + >( + `SELECT b.*,u.outcome AS unmatched_outcome,u.finished_at AS unmatched_time,EXISTS(SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id) AS conflicted + FROM (SELECT 1) LEFT JOIN CronLegacyExitBookings b ON b.trigger_id=$id LEFT JOIN CronUnmatchedBoundExits u ON u.trigger_id=$id`, + { bind: { id }, transaction, type: QueryTypes.SELECT }, + ) + : []; + const booking = saved?.trigger_id ? saved : undefined; + // Every version-1 publication has the same evidentiary weight, regardless of its path. + const recovered = + recoveredCopies ?? + (file + ? await Promise.all( + (await retiringExits()) + .filter((copy) => copy.id === id) + .map((copy) => readExit(id, copy.file)), + ) + : []); + const published = + receipt === undefined && file ? await readExit(id) : receipt; + const files = [published, ...recovered]; + const candidates = [ + ...files, + ...files.map((copy) => copy?.namedExit), + report === 'legacy' ? undefined : report, + ].filter((value): value is VerifiedSupervisorExit => value?.version === 1); + const bound = + file && candidates[0] ? { ...candidates[0], file } : undefined; + const tuples = candidates.map((value) => observationKey(id, value)); + if (booking?.bound) + tuples.push({ id, outcome: booking.outcome, time: booking.finished_at }); + if (saved?.unmatched_time != null && saved.unmatched_outcome != null) { + tuples.push({ + id, + outcome: saved.unmatched_outcome, + time: saved.unmatched_time, + }); + } + const first = tuples[0]; + if ( + saved?.conflicted || + tuples.some( + (tuple) => tuple.time !== first.time || tuple.outcome !== first.outcome, + ) + ) { + await this.disputeBoundExit(id, tuples, transaction); + if (saved.unmatched_time != null) + await this.database.query( + 'DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + this.retireDuplicatePublications(id, recovered, transaction); + if (!saved?.conflicted) { + if (booking) { + await this.withdrawBooking(booking, transaction); + await this.database.query( + 'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + } + if (await this.invalidateBookedTrigger(id, transaction)) + await this.deferExit(id, transaction); + } else if (pending?.state === 'running') + await this.deferExit(id, transaction); + return; + } + for (const copy of recovered) { + if (copy?.version === 1) + this.retireReceiptAfterCommit( + id, + copy.file, + transaction, + 'bound-copy', + copy, + ); + } + if (bound && !pending && saved.unmatched_time == null) { + // After history pruning the booking can disappear with its daily row. + // Before releasing a verified replay, retain just its tuple so a later + // conflicting file can still be recognized without recreating that day. + await this.database.query( + `INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at) + SELECT $id,$outcome,$time WHERE NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=$id)`, + { bind: observationKey(id, bound), transaction }, + ); + } + const start = + booking?.started_at ?? (pending?.owner ? pending.started_at : null); + const observation = + start != null && + finishedAt !== undefined && + finishedAt >= start && + validExit(code, reason, finishedAt) && + state === (code === 0 ? 'finished' : 'failed') + ? { code, signal: reason, time: finishedAt } + : undefined; + if ( + booking && + !booking.bound && + (bound || + (observation && + (booking.outcome !== observationKey(id, observation).outcome || + booking.finished_at !== observation.time))) + ) { + const retained = await this.reviseLegacyBooking( + booking, + bound, + transaction, + ); + if (!retained || !bound) { + if (retained) await this.deferExit(id, transaction, observation); + else if (file) + this.retireReceiptAfterCommit( + id, + file, + transaction, + 'exit', + published, + ); + return; + } + pending = await this.pendingExit(id, transaction); + } + if (file && !pending) { + if (bound && !booking) { + const [pruned] = await this.database.query< + Pick< + LegacyExitBooking, + 'trigger_id' | 'cron_id' | 'source' | 'started_at' + > + >( + 'SELECT trigger_id,cron_id,source,started_at FROM CronPrunedUnknownRuns WHERE trigger_id=$id', + { bind: { id }, transaction, type: QueryTypes.SELECT }, + ); + if (pruned) { + await this.bookPrunedExit(pruned, false, bound, transaction); + await this.database.query( + 'DELETE FROM CronPrunedUnknownRuns WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + } + } + await this.settleInstance(id, transaction); + this.retireReceiptAfterCommit(id, file, transaction, 'exit', published); + return; + } + if ( + pending?.finished_at != null && + ['finished', 'failed', 'stopped'].includes(pending.state) + ) { + // An earlier panel may have committed the trigger before claiming its statistic. + await this.completeInTransaction( + id, + pending.state, + pending.reason, + pending.exit_code, + transaction, + undefined, + pending.finished_at, + ); + if (file) + this.retireReceiptAfterCommit(id, file, transaction, 'exit', published); + return; + } + if (pending?.stop_exit_verified && pending.stop_exit_at != null) { + // The outcome was verified before the last worker finished checking the process tree. + await this.completeInTransaction( + id, + 'stopped', + 'cancelled', + pending.exit_code, + transaction, + undefined, + pending.stop_exit_at, + ); + this.retireReceiptAfterCommit(id, file!, transaction, 'exit'); + return; + } + // A truncated publication is different from no publication. In particular + // a killed supervisor cannot attest to the script's own exit status. + const unreadable = recovered.some( + (copy) => + copy === null || + (copy && copy.version !== 1 && isBoundPublication(copy.file)), + ); + const exit = bound ?? published ?? (unreadable ? null : published); + if (exit && exit.version !== 1 && !booking?.bound) { + if (observation) + await this.saveExitObservation(id, observation, transaction); + if ( + pending?.started_at == null || + exit.time < pending.started_at || + !(await this.hasExitObservation(id, exit, transaction)) + ) { + await this.deferExit(id, transaction); + return; + } + } + if (exit && pending?.started_at != null && !booking?.bound) { + // Track the exact contribution until its history and retained statistic expire. + await this.database.query( + `INSERT OR IGNORE INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound) + SELECT id,cron_id,source,started_at,$time,$outcome,$day,$bound FROM CronTriggers WHERE id=$id`, + { + bind: { + ...observationKey(id, exit), + bound: Number(exit.version === 1), + day: dayjs(exit.time).format('YYYY-MM-DD'), + }, + transaction, + }, + ); + await this.database.query( + 'DELETE FROM CronExitObservations WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + if (bound && saved?.unmatched_time != null) + await this.database.query( + 'DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + } + // A signal on the bound supervisor before its first write says nothing about + // the command it was waiting for. A verified stop has its own durable claim. + const supervisorKilled = + pending?.command_identity && + !pending.stop_requested && + code === null && + state === 'stopped' && + reason?.startsWith('SIG'); + if ( + pending && + pending.owner && + pending.started_at !== null && + (exit === null || + (!exit && + (pending.exit_pending || supervisorKilled || report === 'legacy'))) + ) { + await this.deferExit(id, transaction, observation); + return; + } + if (exit) { + await this.completeInTransaction( + id, + exit.signal || exit.code !== 0 ? 'failed' : 'finished', + exit.signal, + exit.code, + transaction, + undefined, + exit.time, + true, + ); + this.retireReceiptAfterCommit(id, exit.file, transaction, 'exit'); + } else if (state === 'skipped') { + await this.lifecycle.finish(id, state, reason, code, transaction); + await this.settleInstance(id, transaction); + } else { + await this.completeInTransaction( + id, + state, + reason, + code, + transaction, + undefined, + finishedAt, + ); + } + } + + private async withdrawBooking( + booking: LegacyExitBooking, + transaction: Transaction, + ) { + const { trigger_id: id, stat_id: stat } = booking; + const elapsed = Math.max(0, booking.finished_at - booking.started_at); + if (stat !== null) { + // Only the row that received this exact contribution can be debited. A deleted day stays deleted. + await this.database.query( + `UPDATE CrontabStats SET run_count=run_count-1, success_count=success_count-$success, + fail_count=fail_count-$failure,total_time=total_time-$elapsed,updatedAt=CURRENT_TIMESTAMP, + max_time=MAX(COALESCE(fixed_max_time,0),COALESCE((SELECT MAX(MAX(0,finished_at-started_at)) + FROM CronLegacyExitBookings WHERE stat_id=$stat AND trigger_id<>$id),0)) WHERE id=$stat`, + { + bind: { + stat, + id, + elapsed, + success: Number(!booking.stopped && booking.outcome === '0'), + failure: Number(!booking.stopped && booking.outcome !== '0'), + }, + transaction, + }, + ); + await this.database.query( + 'DELETE FROM CrontabStats WHERE id=$stat AND run_count=0', + { bind: { stat }, transaction }, + ); + } + } + + private async invalidateBookedTrigger(id: string, transaction: Transaction) { + const [trigger] = await this.database.query<{ + instance_id: number | null; + state: TriggerState; + cron_id: number; + }>( + 'SELECT instance_id,state,cron_id FROM CronTriggers WHERE id=$id AND started_at IS NOT NULL', + { bind: { id }, type: QueryTypes.SELECT, transaction }, + ); + if (!trigger) return false; + const ref = trigger.cron_id; + await this.database.query( + `UPDATE CronTriggers SET counted=0,exit_pending=1,stop_exit_verified=NULL,stop_exit_at=NULL, + exit_code=NULL,reason=NULL,state=CASE WHEN state='running' THEN state ELSE 'unknown' END WHERE id=$id`, + { bind: { id }, transaction }, + ); + if (trigger.instance_id !== null && trigger.state !== 'running') { + await this.database.query( + 'UPDATE RunningInstances SET status=4,exit_code=NULL,updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$ref', + { bind: { instance: trigger.instance_id, ref }, transaction }, + ); + await this.database.query( + 'UPDATE Crontabs SET last_running_time=NULL WHERE id=$ref AND last_instance_id=$instance', + { bind: { ref, instance: trigger.instance_id }, transaction }, + ); + } + return true; + } + + private async disputeBoundExit( + id: string, + tuples: { outcome: string; time: number }[], + transaction: Transaction, + ) { + if (!tuples.length) return; + await this.database.query( + `INSERT OR IGNORE INTO CronBoundExitConflicts(trigger_id,outcome,finished_at) + SELECT $id,json_extract(value,'$.outcome'),json_extract(value,'$.time') FROM json_each($tuples)`, + { bind: { id, tuples: JSON.stringify(tuples) }, transaction }, + ); + } + + private async bookPrunedExit( + run: Pick< + LegacyExitBooking, + 'trigger_id' | 'cron_id' | 'source' | 'started_at' + >, + stopped: boolean, + exit: ExitObservation, + transaction: Transaction, + ) { + const day = dayjs(exit.time).format('YYYY-MM-DD'); + const state = stopped ? 'stopped' : exit.code === 0 ? 'finished' : 'failed'; + await addDailyExit( + this.database, + run.cron_id, + day, + state, + Math.max(0, exit.time - run.started_at), + true, + transaction, + ); + await this.database.query( + `INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,stopped,bound,stat_id) + VALUES($id,$ref,$source,$start,$time,$outcome,$day,$stopped,1, + (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))) + ON CONFLICT(trigger_id) DO UPDATE SET bound=1,disputed=0,outcome=excluded.outcome,finished_at=excluded.finished_at, + day=excluded.day,stat_id=excluded.stat_id`, + { + bind: { + ...observationKey(run.trigger_id, exit), + ref: run.cron_id, + source: run.source, + start: run.started_at, + day, + stopped: Number(stopped), + }, + transaction, + }, + ); + } + + private async reviseLegacyBooking( + booking: LegacyExitBooking, + bound: ExitObservation | undefined, + transaction: Transaction, + ) { + const id = booking.trigger_id; + await this.withdrawBooking(booking, transaction); + const retained = await this.invalidateBookedTrigger(id, transaction); + if (!retained) { + if (!bound) { + await this.database.query( + 'UPDATE CronLegacyExitBookings SET disputed=1,stat_id=NULL WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + } else { + await this.bookPrunedExit( + booking, + Boolean(booking.stopped), + bound, + transaction, + ); + } + return false; + } + await this.database.query( + 'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id', + { bind: { id }, transaction }, + ); + if (!bound) + await this.database.query( + `INSERT OR IGNORE INTO CronExitObservations(trigger_id,outcome,finished_at) + VALUES($id,$outcome,$time)`, + { + bind: { id, outcome: booking.outcome, time: booking.finished_at }, + transaction, + }, + ); + return true; + } + + private retireDuplicatePublications( + id: string, + copies: Awaited>[], + transaction: Transaction, + ) { + // Independent scans must agree about which file to keep even if they see + // different subsets. Only newer per-writer publications can be discarded. + const witnesses = new Map(); + const redundant: { + file: string; + key: string; + outcome: string; + time: number; + }[] = []; + // Prefer a JSON copy readable by older panels. Compare full paths within + // each format so concurrent collectors always choose the same survivor. + const rank = (file: string) => (isMetadataReceipt(file) ? '1' : '0') + file; + for (const copy of copies) { + if ( + copy?.version !== 1 || + copy.namedExit || + !basename(copy.file).startsWith('.pending.') + ) + continue; + const { outcome, time } = observationKey(id, copy); + const key = JSON.stringify([outcome, time]); + const previous = witnesses.get(key); + if (previous && previous !== copy.file) { + redundant.push({ + file: rank(previous) < rank(copy.file) ? copy.file : previous, + key, + outcome, + time, + }); + } + if (!previous || rank(copy.file) < rank(previous)) + witnesses.set(key, copy.file); + } + if (!redundant.length) return; + transaction.afterCommit(async () => { + // Sequelize also invokes this hook after a failed COMMIT. Verify the + // specific tuple in a separate snapshot, including on an existing dispute. + try { + const rows = await this.database.query<{ + outcome: string; + finished_at: number; + }>( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id', + { bind: { id }, transaction: null, type: QueryTypes.SELECT }, + ); + const committed = new Set( + rows.map((row) => JSON.stringify([row.outcome, row.finished_at])), + ); + for (const copy of redundant) { + if (!committed.has(copy.key)) continue; + const keeper = await readExit(id, witnesses.get(copy.key)!); + if ( + keeper?.version === 1 && + keeper.time === copy.time && + observationKey(id, keeper).outcome === copy.outcome + ) { + await retireLegacyFile(id, copy.file, copy).catch(() => {}); + } + } + } catch { + /* Retry on the next recovery pass. */ + } + }); + } + + private retireReceiptAfterCommit( + id: string, + file: string, + transaction: Transaction, + kind: 'exit' | 'start' | 'bound-copy', + observed?: Awaited>, + ) { + // Sequelize 6 runs afterCommit even when COMMIT itself failed. Check a + // separate committed snapshot before deleting the only durable outcome. + transaction.afterCommit(async () => { + try { + const pendingCondition = + kind === 'start' ? 'script_started_at IS NULL' : 'counted=0'; + const [saved] = await this.database.query<{ + pending: number; + outcome: string | null; + finished_at: number | null; + bound: number; + conflicted: number; + unmatched: number; + }>( + `SELECT EXISTS(SELECT 1 FROM CronTriggers WHERE id=$id AND ${pendingCondition}) AS pending, + EXISTS(SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id) AS conflicted, + (b.trigger_id IS NULL AND u.trigger_id IS NOT NULL) AS unmatched, + COALESCE(b.outcome,u.outcome) AS outcome,COALESCE(b.finished_at,u.finished_at) AS finished_at, + COALESCE(b.bound,u.trigger_id IS NOT NULL) AS bound FROM (SELECT 1) + LEFT JOIN CronLegacyExitBookings b ON b.trigger_id=$id LEFT JOIN CronUnmatchedBoundExits u ON u.trigger_id=$id`, + { bind: { id }, transaction: null, type: QueryTypes.SELECT }, + ); + if (saved.pending || (kind !== 'start' && saved.conflicted)) return; + if ( + saved.outcome !== null && + saved.finished_at !== null && + kind !== 'start' + ) { + if (saved.unmatched) { + // A legacy public name may be unreadable until claimed. Verify the + // moved bytes directly against the durable unmatched observation. + await retireLegacyFile(id, file, { + outcome: saved.outcome, + time: saved.finished_at, + }); + return; + } + // After a failed correction the old booking is still visible. + if (kind === 'bound-copy' && !saved.bound) return; + const current = await readExit(id, file); + if ( + current && + ((saved.bound && current.version !== 1) || + (current.time === saved.finished_at && + observationKey(id, current).outcome === saved.outcome && + (saved.bound || current.version !== 1))) + ) { + await retireLegacyFile( + id, + file, + saved.bound + ? { outcome: saved.outcome, time: saved.finished_at } + : undefined, + ); + } + return; + } + if (kind === 'start') await fs.rm(file, { force: true }); + else if (observed?.version !== 1) await retireLegacyFile(id, file); + } catch { + /* Keep the receipt for the next recovery pass. */ + } + }); + } + + private async replayRetiringExits(transaction?: Transaction) { + const byId = new Map< + string, + NonNullable>>[] + >(); + const unreadable = new Set(); + for (const { id, file } of await retiringExits()) { + const exit = await readExit(id, file); + if (exit === undefined) continue; + if (exit === null || (exit.version !== 1 && isBoundPublication(file))) { + unreadable.add(id); + continue; + } + if (exit.version !== 1) { + // Inspect the atomically moved bytes even when a stale temporary file is being replaced. + await retireLegacyFile(id, file).catch(() => {}); + continue; + } + const copies = byId.get(id) ?? []; + copies.push(exit); + byId.set(id, copies); + } + if (unreadable.size) { + // Retention runs this scan before deletion. Keep unresolved history for + // later repair without ending a live process solely on damaged bytes. + await this.database.query( + `UPDATE CronTriggers SET exit_pending=1 WHERE counted=0 AND state='unknown' + AND exit_pending IS NOT 1 AND owner IS NOT NULL AND started_at IS NOT NULL + AND id IN (SELECT value FROM json_each($ids))`, + { transaction, bind: { ids: JSON.stringify([...unreadable]) } }, + ); + } + for (const [id, copies] of byId) { + const settle = async (tx: Transaction) => { + await this.recoverScriptSample(id, tx); + await this.completeCommandExit( + id, + 'unknown', + null, + null, + tx, + undefined, + undefined, + undefined, + copies, + ); + }; + if (transaction) await settle(transaction); + else await this.database.transaction(settle); + } + return byId; + } + + private async pendingExit(id: string, transaction: Transaction) { + const [row] = await this.database.query< + Pick< + Trigger, + 'state' | 'reason' | 'exit_code' | 'started_at' | 'finished_at' + > & { + owner: string | null; + command_identity: string | null; + stop_requested: number | null; + stop_exit_verified: number | null; + stop_exit_at: number | null; + exit_pending: number | null; + } + >( + `SELECT state,reason,exit_code,started_at,finished_at,owner,command_identity,stop_requested,stop_exit_verified,stop_exit_at,exit_pending + FROM CronTriggers WHERE id=$id AND counted=0`, + { bind: { id }, transaction, type: QueryTypes.SELECT }, + ); + return row; + } + + private async hasExitObservation( + id: string, + exit: ExitObservation, + transaction?: Transaction, + ) { + const [match] = await this.database.query( + `SELECT 1 FROM CronExitObservations WHERE trigger_id=$id GROUP BY trigger_id + HAVING COUNT(*)=1 AND MAX(outcome)=$outcome AND MAX(finished_at)=$time`, + { bind: observationKey(id, exit), type: QueryTypes.SELECT, transaction }, + ); + return Boolean(match); + } + + private async saveExitObservation( + id: string, + observation: ExitObservation, + transaction: Transaction, + ) { + await this.database.query( + `INSERT INTO CronExitObservations(trigger_id,outcome,finished_at) + SELECT $id,$outcome,$time WHERE NOT EXISTS + (SELECT 1 FROM CronExitObservations WHERE trigger_id=$id LIMIT 1 OFFSET 1) + ON CONFLICT(trigger_id,outcome,finished_at) DO NOTHING`, + { bind: observationKey(id, observation), transaction }, + ); + } + + private async deferExit( + id: string, + transaction: Transaction, + observation?: ExitObservation, + ) { + if (observation) + await this.saveExitObservation(id, observation, transaction); + await this.database.query( + 'UPDATE CronTriggers SET exit_pending=1 WHERE id=$id AND exit_pending IS NOT 1', + { bind: { id }, transaction }, + ); + // A signalled stop remains running until all of its descendants are gone. + await this.database.query( + `UPDATE CronTriggers SET state='unknown',reason=NULL,exit_code=NULL, + finished_at=COALESCE(finished_at,$now) 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 AND s.signalled=1)`, + { bind: { id, now: Date.now() }, transaction }, + ); + await this.settleInstance(id, transaction); + } + + async retryPendingExits() { + const rows = await this.database.query<{ id: string }>( + `SELECT id FROM CronTriggers WHERE exit_pending=1 AND + NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=CronTriggers.id)`, + { type: QueryTypes.SELECT }, + ); + for (const { id } of rows) { + const exit = await readExit(id); + if ( + exit && + (exit.version === 1 || (await this.hasExitObservation(id, exit))) + ) { + // Carry a verified bound receipt across a concurrent file replacement. + // Unbound evidence must still match inside the writer transaction. + await this.complete( + id, + 'unknown', + null, + null, + undefined, + exit.version === 1 ? exit : undefined, + ); + } + } + // A canonical-only file can reappear after startup already marked its owner + // unknown. Probe IDs found on disk so missing receipts cost no per-run work. + const recovered = await this.replayRetiringExits(); + const files = (await publishedExits()).filter((id) => !recovered.has(id)); + if (files.length) { + const candidates = await this.database.query<{ id: string }>( + `SELECT value AS id FROM json_each($files) WHERE + EXISTS (SELECT 1 FROM CronTriggers WHERE id=value AND state='unknown' AND reason='restart' + AND counted=0 AND owner IS NOT NULL AND started_at IS NOT NULL) OR + EXISTS (SELECT 1 FROM CronPrunedUnknownRuns WHERE trigger_id=value) OR + EXISTS (SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=value) OR + EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=value) OR + EXISTS (SELECT 1 FROM CronUnmatchedBoundExits WHERE trigger_id=value)`, + { bind: { files: JSON.stringify(files) }, type: QueryTypes.SELECT }, + ); + for (const { id } of candidates) { + const exit = await readExit(id); + if (exit?.version === 1) + await this.complete(id, 'unknown', null, null, undefined, exit); + } + } + await this.collectPublishedScriptStarts(); + } + + private async collectPublishedScriptStarts() { + const files = await publishedScriptStarts(); + if (!files.length) return; + // Only probe existing executions. Keep live markers in place so another + // instrumented command in the same execution cannot replace the first sample. + const rows = await this.database.query<{ + id: string; + counted: number; + script_started_at: number | null; + }>( + `SELECT id,counted,script_started_at FROM CronTriggers WHERE id IN (SELECT value FROM json_each($ids)) + AND started_at IS NOT NULL AND (script_started_at IS NULL OR counted=1)`, + { + bind: { ids: JSON.stringify(files.map(({ id }) => id)) }, + type: QueryTypes.SELECT, + }, + ); + for (const row of rows) { + const sample = await this.readScriptSample(row.id); + if (!sample) continue; + await this.database.transaction(async (transaction) => { + if (row.script_started_at === null) + await this.saveScriptSample(row.id, sample, transaction); + if (row.counted) + this.retireReceiptAfterCommit( + row.id, + sample.marker, + transaction, + 'start', + ); + }); + } + } + + async replayPublishedExits(transaction: Transaction) { + const recovered = await this.replayRetiringExits(transaction); + // Entry instrumentation can outlive its committed transaction even if the + // exit file was already deleted. An unregistered entry may still be live. + const exits = new Set(await publishedExits()); + for (const { id, file } of await publishedScriptStarts()) { + const [row] = await this.database.query<{ + counted: number; + script_started_at: number | null; + }>('SELECT counted,script_started_at FROM CronTriggers WHERE id=$id', { + bind: { id }, + transaction, + type: QueryTypes.SELECT, + }); + // After pruning the trigger, a matching supervisor exit still identifies + // this panel's retired run. A start file alone cannot establish that. + if (row ? row.counted && row.script_started_at !== null : exits.has(id)) { + this.retireReceiptAfterCommit(id, file, transaction, 'start'); + } + } + for (const id of exits) { + if (recovered.has(id)) continue; + const pending = await this.pendingExit(id, transaction); + if (!pending) { + await this.completeCommandExit( + id, + 'unknown', + 'restart', + null, + transaction, + undefined, + undefined, + undefined, + [], + ); + } else if (pending.owner && pending.started_at !== null) { + const exit = await readExit(id); + if (exit === undefined) continue; + await this.recoverScriptSample(id, transaction); + await this.completeCommandExit( + id, + 'unknown', + 'restart', + null, + transaction, + exit, + undefined, + undefined, + [], + ); + } + } + } + + async completeInTransaction( + id: string, + state: TriggerState, + reason: string | null, + code: number | null, + transaction: Transaction, + elapsedMs?: number, + finishedAt?: number, + verifiedExit = false, + ) { + if (await this.lifecycle.shouldStop(id, transaction)) { + state = 'stopped'; + reason = 'cancelled'; + // The command can exit before its TERM-resistant descendants. Keep the + // receipt running until the stop operation has verified the whole tree. + const waiting = await this.database.query( + `UPDATE CronTriggers SET + exit_code=CASE WHEN stop_exit_at IS NULL OR ($verified AND stop_exit_verified IS NOT 1) THEN $code ELSE exit_code END, + stop_exit_at=CASE WHEN stop_exit_at IS NULL OR ($verified AND stop_exit_verified IS NOT 1) THEN $now ELSE stop_exit_at END, + stop_exit_verified=CASE WHEN $verified THEN 1 ELSE stop_exit_verified END + WHERE id=$id AND state='running' AND stop_requested=1 AND instance_id IN + (SELECT instance_id FROM CronStopRequests WHERE targets IS NOT NULL AND signalled=1)`, + { + transaction, + bind: { + id, + code, + now: finishedAt ?? Date.now(), + verified: Number(verifiedExit), + }, + type: QueryTypes.BULKUPDATE, + }, + ); + if (waiting) return; + } else if (state === 'stopped' && reason?.startsWith('SIG')) { + state = 'failed'; + } + const changed = await this.lifecycle.finish( + id, + state, + reason, + code, + transaction, + finishedAt, + ); + const [row] = await this.database.query< + Trigger & { instance_id: number | null } + >( + `SELECT cron_id, instance_id, log_path, started_at, finished_at, exit_code FROM CronTriggers WHERE id=$id + AND state IN ('finished','failed','stopped') AND started_at IS NOT NULL AND counted=0`, + { transaction, bind: { id }, type: QueryTypes.SELECT }, + ); + await this.settleInstance(id, transaction); + if (!row) return; + const duration = + elapsedMs ?? Math.max(0, row.finished_at! - row.started_at!); + if (changed && row.instance_id !== null) { + await this.database.query( + `UPDATE Crontabs SET last_running_time=$duration + WHERE id=$cronId AND last_execution_time=$start AND (last_instance_id=$instance OR + (last_instance_id IS NULL AND $instance=(SELECT id FROM RunningInstances WHERE cron_id=$cronId + ORDER BY started_at DESC,id DESC LIMIT 1)))`, + { + transaction, + bind: { + cronId: row.cron_id, + start: Math.floor(row.started_at! / 1000), + instance: row.instance_id, + duration: Math.floor(duration / 1000), + }, + }, + ); + } + await recordCronResult( + this.database, + row.cron_id, + row.exit_code ?? 1, + duration, + row.finished_at!, + id, + transaction, + ); + } + + async hasBoundConflict(id: string, transaction: Transaction) { + const [conflict] = await this.database.query( + 'SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id', + { bind: { id }, transaction, type: QueryTypes.SELECT }, + ); + return Boolean(conflict); + } + + // 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.database.transaction(async (transaction) => { + if (await this.hasBoundConflict(id, transaction)) return; + const [row] = await this.database.query<{ + owner: string | null; + state: TriggerState; + }>( + 'SELECT owner,state FROM CronTriggers WHERE id=$id AND cron_id=$cronId', + { transaction, type: QueryTypes.SELECT, bind: { id, cronId } }, + ); + if (!row) { + if (finishedAt && finishedAt <= now) { + const [pruned] = await this.database.query( + 'SELECT 1 FROM CronHistoryRetention WHERE id=1 AND cutoff>$end', + { transaction, type: QueryTypes.SELECT, bind: { end: finishedAt } }, + ); + if (pruned) return; + } + throw new Error('Unknown trigger'); + } + if ( + row.owner === null && + (row.state === 'running' || row.state === 'unknown') + ) { + await this.completeInTransaction( + id, + code === 0 ? 'finished' : 'failed', + null, + code, + transaction, + elapsedMs, + finishedAt, + ); + } else { + await recordCronResult( + this.database, + cronId, + code, + elapsedMs, + now, + id, + transaction, + ); + } + }); + } + + async readScriptSample(id: string) { + if (!process.env.QL_DIR || !/^[a-z0-9-]{1,120}$/.test(id)) return; + const marker = join(process.env.QL_DIR, '.tmp', 'cron-start-' + id); + try { + const value = await fs.readFile(marker, 'utf8'); + if (/^\d{13}$/.test(value)) return { marker, time: Number(value) }; + } catch { + /* Entries without instrumentation have no sample. */ + } + } + + async recoverScriptSample(id: string, transaction: Transaction) { + const sample = await this.readScriptSample(id); + if (!sample) return; + await this.saveScriptSample(id, sample, transaction); + this.retireReceiptAfterCommit(id, sample.marker, transaction, 'start'); + } + + async saveScriptSample( + id: string, + sample: { time: number } | undefined, + transaction: Transaction, + ) { + if (sample) + await this.database.query( + `UPDATE CronTriggers SET script_started_at=$time + WHERE id=$id AND script_started_at IS NULL AND started_at <= $time AND $time <= $now + AND (finished_at IS NULL OR state='unknown' OR $time <= finished_at)`, + { transaction, bind: { time: sample.time, now: Date.now(), id } }, + ); + } + + async settleInstance(id: string, transaction: Transaction) { + const [row] = await this.database.query( + `SELECT cron_id,instance_id,log_path,state,finished_at,exit_code FROM CronTriggers + WHERE id=$id AND instance_id IS NOT NULL AND finished_at IS NOT NULL`, + { transaction, bind: { id }, type: QueryTypes.SELECT }, + ); + if (!row) return; + if (row.state === 'skipped') { + // The launch gate closed before user code ran. + await this.database.query( + 'DELETE FROM RunningInstances WHERE id=$instance AND status=0', + { transaction, bind: { instance: row.instance_id } }, + ); + await this.database.query( + 'UPDATE CronTriggers SET instance_id=NULL WHERE id=$id', + { transaction, bind: { id } }, + ); + } else { + const status = + row.state === 'finished' + ? 1 + : row.state === 'stopped' + ? 2 + : row.state === 'unknown' + ? 4 + : 3; + const updated = await this.database.query( + `UPDATE RunningInstances SET status=$status,finished_at=$end,exit_code=$code, + updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$cronId AND status=0`, + { + transaction, + type: QueryTypes.BULKUPDATE, + bind: { + instance: row.instance_id, + cronId: row.cron_id, + status, + end: Math.floor(row.finished_at! / 1000), + code: row.exit_code, + }, + }, + ); + if (!updated) { + // A late exit corrects only the historical instance. Its replacement + // already owns the task row, even when it uses the same PID and log. + if (status !== 4) + await this.database.query( + `UPDATE RunningInstances + SET status=$status,finished_at=$end,exit_code=$code,updatedAt=CURRENT_TIMESTAMP + WHERE id=$instance AND cron_id=$cronId AND status=4`, + { + transaction, + bind: { + instance: row.instance_id, + cronId: row.cron_id, + status, + end: Math.floor(row.finished_at! / 1000), + code: row.exit_code, + }, + }, + ); + return; + } + } + // A newer manual reservation owns its own token. Never clear it while an older run exits. + const [active] = await this.database.query<{ + pid: number; + log_path: string; + started_at: number; + }>( + 'SELECT pid,log_path,started_at FROM RunningInstances WHERE cron_id=$cronId AND status=0 ORDER BY id DESC LIMIT 1', + { transaction, bind: { cronId: row.cron_id }, type: QueryTypes.SELECT }, + ); + if (active) { + await this.database.query( + `UPDATE Crontabs SET status=0,pid=$pid,log_path=$log + WHERE id=$cronId AND status IS NOT 3`, + { + transaction, + bind: { cronId: row.cron_id, pid: active.pid, log: active.log_path }, + }, + ); + } else { + await this.database.query( + `UPDATE Crontabs SET status=1,pid=NULL,queued_token=NULL + WHERE id=$cronId AND status=0 AND log_path IS $log`, + { transaction, bind: { cronId: row.cron_id, log: row.log_path } }, + ); + } + } + + async exitBeforeStop(id: string) { + const recovered = await Promise.all( + (await retiringExits()) + .filter((copy) => copy.id === id) + .map((copy) => readExit(id, copy.file)), + ); + const canonical = await readExit(id); + const verified = recovered.some((copy) => copy?.version === 1); + const unreadable = + canonical === null || + recovered.some( + (copy) => + copy === null || + (copy && copy.version !== 1 && isBoundPublication(copy.file)), + ); + return { + canonical, + recovered, + published: Boolean(canonical || verified), + unreadable, + }; + } +} diff --git a/back/cron/types.ts b/back/cron/types.ts new file mode 100644 index 00000000..1bc7ae7c --- /dev/null +++ b/back/cron/types.ts @@ -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; +}; diff --git a/back/data/cronStats.ts b/back/data/cronStats.ts index 59b12452..522e8be1 100644 --- a/back/data/cronStats.ts +++ b/back/data/cronStats.ts @@ -26,7 +26,9 @@ export class CrontabStat { } } -export interface CrontabStatInstance extends Model, CrontabStat {} +export interface CrontabStatInstance + extends Model, + CrontabStat {} export const CrontabStatModel = sequelize.define( 'CrontabStat', diff --git a/back/data/index.ts b/back/data/index.ts index 86945718..d3c3092a 100644 --- a/back/data/index.ts +++ b/back/data/index.ts @@ -29,8 +29,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => { let ready = initialized.get(connection); if (!ready) { ready = new Promise((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; }); diff --git a/back/data/notificationSettings.ts b/back/data/notificationSettings.ts new file mode 100644 index 00000000..bea771d3 --- /dev/null +++ b/back/data/notificationSettings.ts @@ -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 { + 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; +} diff --git a/back/data/runningInstance.ts b/back/data/runningInstance.ts index 59da4bfc..cf772b52 100644 --- a/back/data/runningInstance.ts +++ b/back/data/runningInstance.ts @@ -79,5 +79,10 @@ export const RunningInstanceModel = sequelize.define( allowNull: true, }, }, - { indexes: [{ fields: ['cron_id', 'pid', 'started_at'] }, { fields: ['cron_id', 'id'] }] }, + { + indexes: [ + { fields: ['cron_id', 'pid', 'started_at'] }, + { fields: ['cron_id', 'id'] }, + ], + }, ); diff --git a/back/shared/schemaMigrations.ts b/back/data/schemaMigrations.ts similarity index 79% rename from back/shared/schemaMigrations.ts rename to back/data/schemaMigrations.ts index 9d10b274..31e6706a 100644 --- a/back/shared/schemaMigrations.ts +++ b/back/data/schemaMigrations.ts @@ -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 { } 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 diff --git a/back/loaders/db.ts b/back/loaders/db.ts index 44a9c076..c7356c44 100644 --- a/back/loaders/db.ts +++ b/back/loaders/db.ts @@ -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 { diff --git a/back/loaders/express.ts b/back/loaders/express.ts index 9a9e7e62..f8264234 100644 --- a/back/loaders/express.ts +++ b/back/loaders/express.ts @@ -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) || ([ diff --git a/back/loaders/initData.ts b/back/loaders/initData.ts index 8a862118..1fc57a7e 100644 --- a/back/loaders/initData.ts +++ b/back/loaders/initData.ts @@ -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 任务 @@ -213,7 +214,7 @@ export default async () => { if (!langEnvExist) { await writeFile(config.langEnvFile, `export QL_LANG='${lang}'\n`); } - } catch { } + } catch {} // Replace legacy task environment files before recovered tasks can run. await envService.set_envs(); diff --git a/back/middlewares/protectedPathCase.ts b/back/middlewares/protectedPathCase.ts index 21d2b62e..9743c8e0 100644 --- a/back/middlewares/protectedPathCase.ts +++ b/back/middlewares/protectedPathCase.ts @@ -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, diff --git a/back/protos/api.ts b/back/protos/api.ts index 11e759bc..08cfc19b 100644 --- a/back/protos/api.ts +++ b/back/protos/api.ts @@ -5,7 +5,7 @@ // source: back/protos/api.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.api"; +export const protobufPackage = 'com.ql.api'; export enum NotificationMode { gotify = 0, @@ -51,76 +51,76 @@ export enum NotificationMode { export function notificationModeFromJSON(object: any): NotificationMode { switch (object) { case 0: - case "gotify": + case 'gotify': return NotificationMode.gotify; case 1: - case "goCqHttpBot": + case 'goCqHttpBot': return NotificationMode.goCqHttpBot; case 2: - case "serverChan": + case 'serverChan': return NotificationMode.serverChan; case 3: - case "pushDeer": + case 'pushDeer': return NotificationMode.pushDeer; case 4: - case "bark": + case 'bark': return NotificationMode.bark; case 5: - case "chat": + case 'chat': return NotificationMode.chat; case 6: - case "telegramBot": + case 'telegramBot': return NotificationMode.telegramBot; case 7: - case "dingtalkBot": + case 'dingtalkBot': return NotificationMode.dingtalkBot; case 8: - case "weWorkBot": + case 'weWorkBot': return NotificationMode.weWorkBot; case 9: - case "weWorkApp": + case 'weWorkApp': return NotificationMode.weWorkApp; case 10: - case "aibotk": + case 'aibotk': return NotificationMode.aibotk; case 11: - case "iGot": + case 'iGot': return NotificationMode.iGot; case 12: - case "pushPlus": + case 'pushPlus': return NotificationMode.pushPlus; case 13: - case "wePlusBot": + case 'wePlusBot': return NotificationMode.wePlusBot; case 14: - case "email": + case 'email': return NotificationMode.email; case 15: - case "pushMe": + case 'pushMe': return NotificationMode.pushMe; case 16: - case "feishu": + case 'feishu': return NotificationMode.feishu; case 17: - case "webhook": + case 'webhook': return NotificationMode.webhook; case 18: - case "chronocat": + case 'chronocat': return NotificationMode.chronocat; case 19: - case "ntfy": + case 'ntfy': return NotificationMode.ntfy; case 20: - case "wxPusherBot": + case 'wxPusherBot': return NotificationMode.wxPusherBot; case 21: - case "wxPusherSpt": + case 'wxPusherSpt': return NotificationMode.wxPusherSpt; case 22: - case "wpush": + case 'wpush': return NotificationMode.wpush; case -1: - case "UNRECOGNIZED": + case 'UNRECOGNIZED': default: return NotificationMode.UNRECOGNIZED; } @@ -129,54 +129,54 @@ export function notificationModeFromJSON(object: any): NotificationMode { export function notificationModeToJSON(object: NotificationMode): string { switch (object) { case NotificationMode.gotify: - return "gotify"; + return 'gotify'; case NotificationMode.goCqHttpBot: - return "goCqHttpBot"; + return 'goCqHttpBot'; case NotificationMode.serverChan: - return "serverChan"; + return 'serverChan'; case NotificationMode.pushDeer: - return "pushDeer"; + return 'pushDeer'; case NotificationMode.bark: - return "bark"; + return 'bark'; case NotificationMode.chat: - return "chat"; + return 'chat'; case NotificationMode.telegramBot: - return "telegramBot"; + return 'telegramBot'; case NotificationMode.dingtalkBot: - return "dingtalkBot"; + return 'dingtalkBot'; case NotificationMode.weWorkBot: - return "weWorkBot"; + return 'weWorkBot'; case NotificationMode.weWorkApp: - return "weWorkApp"; + return 'weWorkApp'; case NotificationMode.aibotk: - return "aibotk"; + return 'aibotk'; case NotificationMode.iGot: - return "iGot"; + return 'iGot'; case NotificationMode.pushPlus: - return "pushPlus"; + return 'pushPlus'; case NotificationMode.wePlusBot: - return "wePlusBot"; + return 'wePlusBot'; case NotificationMode.email: - return "email"; + return 'email'; case NotificationMode.pushMe: - return "pushMe"; + return 'pushMe'; case NotificationMode.feishu: - return "feishu"; + return 'feishu'; case NotificationMode.webhook: - return "webhook"; + return 'webhook'; case NotificationMode.chronocat: - return "chronocat"; + return 'chronocat'; case NotificationMode.ntfy: - return "ntfy"; + return 'ntfy'; case NotificationMode.wxPusherBot: - return "wxPusherBot"; + return 'wxPusherBot'; case NotificationMode.wxPusherSpt: - return "wxPusherSpt"; + return 'wxPusherSpt'; case NotificationMode.wpush: - return "wpush"; + return 'wpush'; case NotificationMode.UNRECOGNIZED: default: - return "UNRECOGNIZED"; + return 'UNRECOGNIZED'; } } @@ -438,7 +438,10 @@ function createBaseEnvItem(): EnvItem { } export const EnvItem: MessageFns = { - encode(message: EnvItem, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: EnvItem, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== undefined) { writer.uint32(8).int32(message.id); } @@ -461,7 +464,8 @@ export const EnvItem: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): EnvItem { - 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 = createBaseEnvItem(); while (reader.pos < end) { @@ -529,9 +533,15 @@ export const EnvItem: MessageFns = { id: isSet(object.id) ? globalThis.Number(object.id) : undefined, name: isSet(object.name) ? globalThis.String(object.name) : undefined, value: isSet(object.value) ? globalThis.String(object.value) : undefined, - remarks: isSet(object.remarks) ? globalThis.String(object.remarks) : undefined, - status: isSet(object.status) ? globalThis.Number(object.status) : undefined, - position: isSet(object.position) ? globalThis.Number(object.position) : undefined, + remarks: isSet(object.remarks) + ? globalThis.String(object.remarks) + : undefined, + status: isSet(object.status) + ? globalThis.Number(object.status) + : undefined, + position: isSet(object.position) + ? globalThis.Number(object.position) + : undefined, }; }, @@ -574,19 +584,23 @@ export const EnvItem: MessageFns = { }; function createBaseGetEnvsRequest(): GetEnvsRequest { - return { searchValue: "" }; + return { searchValue: '' }; } export const GetEnvsRequest: MessageFns = { - encode(message: GetEnvsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.searchValue !== "") { + encode( + message: GetEnvsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.searchValue !== '') { writer.uint32(10).string(message.searchValue); } return writer; }, decode(input: BinaryReader | Uint8Array, length?: number): GetEnvsRequest { - 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 = createBaseGetEnvsRequest(); while (reader.pos < end) { @@ -610,23 +624,31 @@ export const GetEnvsRequest: MessageFns = { }, fromJSON(object: any): GetEnvsRequest { - return { searchValue: isSet(object.searchValue) ? globalThis.String(object.searchValue) : "" }; + return { + searchValue: isSet(object.searchValue) + ? globalThis.String(object.searchValue) + : '', + }; }, toJSON(message: GetEnvsRequest): unknown { const obj: any = {}; - if (message.searchValue !== "") { + if (message.searchValue !== '') { obj.searchValue = message.searchValue; } return obj; }, - create, I>>(base?: I): GetEnvsRequest { + create, I>>( + base?: I, + ): GetEnvsRequest { return GetEnvsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): GetEnvsRequest { + fromPartial, I>>( + object: I, + ): GetEnvsRequest { const message = createBaseGetEnvsRequest(); - message.searchValue = object.searchValue ?? ""; + message.searchValue = object.searchValue ?? ''; return message; }, }; @@ -636,7 +658,10 @@ function createBaseCreateEnvRequest(): CreateEnvRequest { } export const CreateEnvRequest: MessageFns = { - encode(message: CreateEnvRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: CreateEnvRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { for (const v of message.envs) { EnvItem.encode(v!, writer.uint32(10).fork()).join(); } @@ -644,7 +669,8 @@ export const CreateEnvRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): CreateEnvRequest { - 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 = createBaseCreateEnvRequest(); while (reader.pos < end) { @@ -668,7 +694,11 @@ export const CreateEnvRequest: MessageFns = { }, fromJSON(object: any): CreateEnvRequest { - return { envs: globalThis.Array.isArray(object?.envs) ? object.envs.map((e: any) => EnvItem.fromJSON(e)) : [] }; + return { + envs: globalThis.Array.isArray(object?.envs) + ? object.envs.map((e: any) => EnvItem.fromJSON(e)) + : [], + }; }, toJSON(message: CreateEnvRequest): unknown { @@ -679,10 +709,14 @@ export const CreateEnvRequest: MessageFns = { return obj; }, - create, I>>(base?: I): CreateEnvRequest { + create, I>>( + base?: I, + ): CreateEnvRequest { return CreateEnvRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CreateEnvRequest { + fromPartial, I>>( + object: I, + ): CreateEnvRequest { const message = createBaseCreateEnvRequest(); message.envs = object.envs?.map((e) => EnvItem.fromPartial(e)) || []; return message; @@ -694,7 +728,10 @@ function createBaseUpdateEnvRequest(): UpdateEnvRequest { } export const UpdateEnvRequest: MessageFns = { - encode(message: UpdateEnvRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: UpdateEnvRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.env !== undefined) { EnvItem.encode(message.env, writer.uint32(10).fork()).join(); } @@ -702,7 +739,8 @@ export const UpdateEnvRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): UpdateEnvRequest { - 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 = createBaseUpdateEnvRequest(); while (reader.pos < end) { @@ -726,7 +764,9 @@ export const UpdateEnvRequest: MessageFns = { }, fromJSON(object: any): UpdateEnvRequest { - return { env: isSet(object.env) ? EnvItem.fromJSON(object.env) : undefined }; + return { + env: isSet(object.env) ? EnvItem.fromJSON(object.env) : undefined, + }; }, toJSON(message: UpdateEnvRequest): unknown { @@ -737,12 +777,19 @@ export const UpdateEnvRequest: MessageFns = { return obj; }, - create, I>>(base?: I): UpdateEnvRequest { + create, I>>( + base?: I, + ): UpdateEnvRequest { return UpdateEnvRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): UpdateEnvRequest { + fromPartial, I>>( + object: I, + ): UpdateEnvRequest { const message = createBaseUpdateEnvRequest(); - message.env = (object.env !== undefined && object.env !== null) ? EnvItem.fromPartial(object.env) : undefined; + message.env = + object.env !== undefined && object.env !== null + ? EnvItem.fromPartial(object.env) + : undefined; return message; }, }; @@ -752,7 +799,10 @@ function createBaseDeleteEnvsRequest(): DeleteEnvsRequest { } export const DeleteEnvsRequest: MessageFns = { - encode(message: DeleteEnvsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: DeleteEnvsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -762,7 +812,8 @@ export const DeleteEnvsRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): DeleteEnvsRequest { - 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 = createBaseDeleteEnvsRequest(); while (reader.pos < end) { @@ -796,7 +847,11 @@ export const DeleteEnvsRequest: MessageFns = { }, fromJSON(object: any): DeleteEnvsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: DeleteEnvsRequest): unknown { @@ -807,10 +862,14 @@ export const DeleteEnvsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): DeleteEnvsRequest { + create, I>>( + base?: I, + ): DeleteEnvsRequest { return DeleteEnvsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): DeleteEnvsRequest { + fromPartial, I>>( + object: I, + ): DeleteEnvsRequest { const message = createBaseDeleteEnvsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -822,7 +881,10 @@ function createBaseMoveEnvRequest(): MoveEnvRequest { } export const MoveEnvRequest: MessageFns = { - encode(message: MoveEnvRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: MoveEnvRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== 0) { writer.uint32(8).int32(message.id); } @@ -836,7 +898,8 @@ export const MoveEnvRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): MoveEnvRequest { - 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 = createBaseMoveEnvRequest(); while (reader.pos < end) { @@ -878,7 +941,9 @@ export const MoveEnvRequest: MessageFns = { fromJSON(object: any): MoveEnvRequest { return { id: isSet(object.id) ? globalThis.Number(object.id) : 0, - fromIndex: isSet(object.fromIndex) ? globalThis.Number(object.fromIndex) : 0, + fromIndex: isSet(object.fromIndex) + ? globalThis.Number(object.fromIndex) + : 0, toIndex: isSet(object.toIndex) ? globalThis.Number(object.toIndex) : 0, }; }, @@ -897,10 +962,14 @@ export const MoveEnvRequest: MessageFns = { return obj; }, - create, I>>(base?: I): MoveEnvRequest { + create, I>>( + base?: I, + ): MoveEnvRequest { return MoveEnvRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): MoveEnvRequest { + fromPartial, I>>( + object: I, + ): MoveEnvRequest { const message = createBaseMoveEnvRequest(); message.id = object.id ?? 0; message.fromIndex = object.fromIndex ?? 0; @@ -914,7 +983,10 @@ function createBaseDisableEnvsRequest(): DisableEnvsRequest { } export const DisableEnvsRequest: MessageFns = { - encode(message: DisableEnvsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: DisableEnvsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -923,8 +995,12 @@ export const DisableEnvsRequest: MessageFns = { return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): DisableEnvsRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): DisableEnvsRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseDisableEnvsRequest(); while (reader.pos < end) { @@ -958,7 +1034,11 @@ export const DisableEnvsRequest: MessageFns = { }, fromJSON(object: any): DisableEnvsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: DisableEnvsRequest): unknown { @@ -969,10 +1049,14 @@ export const DisableEnvsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): DisableEnvsRequest { + create, I>>( + base?: I, + ): DisableEnvsRequest { return DisableEnvsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): DisableEnvsRequest { + fromPartial, I>>( + object: I, + ): DisableEnvsRequest { const message = createBaseDisableEnvsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -984,7 +1068,10 @@ function createBaseEnableEnvsRequest(): EnableEnvsRequest { } export const EnableEnvsRequest: MessageFns = { - encode(message: EnableEnvsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: EnableEnvsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -994,7 +1081,8 @@ export const EnableEnvsRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): EnableEnvsRequest { - 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 = createBaseEnableEnvsRequest(); while (reader.pos < end) { @@ -1028,7 +1116,11 @@ export const EnableEnvsRequest: MessageFns = { }, fromJSON(object: any): EnableEnvsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: EnableEnvsRequest): unknown { @@ -1039,10 +1131,14 @@ export const EnableEnvsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): EnableEnvsRequest { + create, I>>( + base?: I, + ): EnableEnvsRequest { return EnableEnvsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): EnableEnvsRequest { + fromPartial, I>>( + object: I, + ): EnableEnvsRequest { const message = createBaseEnableEnvsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -1050,24 +1146,31 @@ export const EnableEnvsRequest: MessageFns = { }; function createBaseUpdateEnvNamesRequest(): UpdateEnvNamesRequest { - return { ids: [], name: "" }; + return { ids: [], name: '' }; } export const UpdateEnvNamesRequest: MessageFns = { - encode(message: UpdateEnvNamesRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: UpdateEnvNamesRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); } writer.join(); - if (message.name !== "") { + if (message.name !== '') { writer.uint32(18).string(message.name); } return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): UpdateEnvNamesRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): UpdateEnvNamesRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseUpdateEnvNamesRequest(); while (reader.pos < end) { @@ -1110,8 +1213,10 @@ export const UpdateEnvNamesRequest: MessageFns = { fromJSON(object: any): UpdateEnvNamesRequest { return { - ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [], - name: isSet(object.name) ? globalThis.String(object.name) : "", + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + name: isSet(object.name) ? globalThis.String(object.name) : '', }; }, @@ -1120,19 +1225,23 @@ export const UpdateEnvNamesRequest: MessageFns = { if (message.ids?.length) { obj.ids = message.ids.map((e) => Math.round(e)); } - if (message.name !== "") { + if (message.name !== '') { obj.name = message.name; } return obj; }, - create, I>>(base?: I): UpdateEnvNamesRequest { + create, I>>( + base?: I, + ): UpdateEnvNamesRequest { return UpdateEnvNamesRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): UpdateEnvNamesRequest { + fromPartial, I>>( + object: I, + ): UpdateEnvNamesRequest { const message = createBaseUpdateEnvNamesRequest(); message.ids = object.ids?.map((e) => e) || []; - message.name = object.name ?? ""; + message.name = object.name ?? ''; return message; }, }; @@ -1142,7 +1251,10 @@ function createBaseGetEnvByIdRequest(): GetEnvByIdRequest { } export const GetEnvByIdRequest: MessageFns = { - encode(message: GetEnvByIdRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: GetEnvByIdRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== 0) { writer.uint32(8).int32(message.id); } @@ -1150,7 +1262,8 @@ export const GetEnvByIdRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): GetEnvByIdRequest { - 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 = createBaseGetEnvByIdRequest(); while (reader.pos < end) { @@ -1185,10 +1298,14 @@ export const GetEnvByIdRequest: MessageFns = { return obj; }, - create, I>>(base?: I): GetEnvByIdRequest { + create, I>>( + base?: I, + ): GetEnvByIdRequest { return GetEnvByIdRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): GetEnvByIdRequest { + fromPartial, I>>( + object: I, + ): GetEnvByIdRequest { const message = createBaseGetEnvByIdRequest(); message.id = object.id ?? 0; return message; @@ -1200,7 +1317,10 @@ function createBaseEnvsResponse(): EnvsResponse { } export const EnvsResponse: MessageFns = { - encode(message: EnvsResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: EnvsResponse, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -1214,7 +1334,8 @@ export const EnvsResponse: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): EnvsResponse { - 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 = createBaseEnvsResponse(); while (reader.pos < end) { @@ -1256,8 +1377,12 @@ export const EnvsResponse: MessageFns = { fromJSON(object: any): EnvsResponse { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, - data: globalThis.Array.isArray(object?.data) ? object.data.map((e: any) => EnvItem.fromJSON(e)) : [], - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + data: globalThis.Array.isArray(object?.data) + ? object.data.map((e: any) => EnvItem.fromJSON(e)) + : [], + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -1275,10 +1400,14 @@ export const EnvsResponse: MessageFns = { return obj; }, - create, I>>(base?: I): EnvsResponse { + create, I>>( + base?: I, + ): EnvsResponse { return EnvsResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): EnvsResponse { + fromPartial, I>>( + object: I, + ): EnvsResponse { const message = createBaseEnvsResponse(); message.code = object.code ?? 0; message.data = object.data?.map((e) => EnvItem.fromPartial(e)) || []; @@ -1292,7 +1421,10 @@ function createBaseEnvResponse(): EnvResponse { } export const EnvResponse: MessageFns = { - encode(message: EnvResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: EnvResponse, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -1306,7 +1438,8 @@ export const EnvResponse: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): EnvResponse { - 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 = createBaseEnvResponse(); while (reader.pos < end) { @@ -1349,7 +1482,9 @@ export const EnvResponse: MessageFns = { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, data: isSet(object.data) ? EnvItem.fromJSON(object.data) : undefined, - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -1370,10 +1505,15 @@ export const EnvResponse: MessageFns = { create, I>>(base?: I): EnvResponse { return EnvResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): EnvResponse { + fromPartial, I>>( + object: I, + ): EnvResponse { const message = createBaseEnvResponse(); message.code = object.code ?? 0; - message.data = (object.data !== undefined && object.data !== null) ? EnvItem.fromPartial(object.data) : undefined; + message.data = + object.data !== undefined && object.data !== null + ? EnvItem.fromPartial(object.data) + : undefined; message.message = object.message ?? undefined; return message; }, @@ -1384,7 +1524,10 @@ function createBaseResponse(): Response { } export const Response: MessageFns = { - encode(message: Response, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: Response, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -1395,7 +1538,8 @@ export const Response: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): Response { - 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 = createBaseResponse(); while (reader.pos < end) { @@ -1429,7 +1573,9 @@ export const Response: MessageFns = { fromJSON(object: any): Response { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -1456,19 +1602,23 @@ export const Response: MessageFns = { }; function createBaseExtraScheduleItem(): ExtraScheduleItem { - return { schedule: "" }; + return { schedule: '' }; } export const ExtraScheduleItem: MessageFns = { - encode(message: ExtraScheduleItem, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.schedule !== "") { + encode( + message: ExtraScheduleItem, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.schedule !== '') { writer.uint32(10).string(message.schedule); } return writer; }, decode(input: BinaryReader | Uint8Array, length?: number): ExtraScheduleItem { - 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 = createBaseExtraScheduleItem(); while (reader.pos < end) { @@ -1492,23 +1642,31 @@ export const ExtraScheduleItem: MessageFns = { }, fromJSON(object: any): ExtraScheduleItem { - return { schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "" }; + return { + schedule: isSet(object.schedule) + ? globalThis.String(object.schedule) + : '', + }; }, toJSON(message: ExtraScheduleItem): unknown { const obj: any = {}; - if (message.schedule !== "") { + if (message.schedule !== '') { obj.schedule = message.schedule; } return obj; }, - create, I>>(base?: I): ExtraScheduleItem { + create, I>>( + base?: I, + ): ExtraScheduleItem { return ExtraScheduleItem.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): ExtraScheduleItem { + fromPartial, I>>( + object: I, + ): ExtraScheduleItem { const message = createBaseExtraScheduleItem(); - message.schedule = object.schedule ?? ""; + message.schedule = object.schedule ?? ''; return message; }, }; @@ -1533,7 +1691,10 @@ function createBaseCronItem(): CronItem { } export const CronItem: MessageFns = { - encode(message: CronItem, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: CronItem, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== undefined) { writer.uint32(8).int32(message.id); } @@ -1580,7 +1741,8 @@ export const CronItem: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): CronItem { - 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 = createBaseCronItem(); while (reader.pos < end) { @@ -1639,7 +1801,9 @@ export const CronItem: MessageFns = { break; } - message.extra_schedules.push(ExtraScheduleItem.decode(reader, reader.uint32())); + message.extra_schedules.push( + ExtraScheduleItem.decode(reader, reader.uint32()), + ); continue; } case 8: { @@ -1710,20 +1874,38 @@ export const CronItem: MessageFns = { fromJSON(object: any): CronItem { return { id: isSet(object.id) ? globalThis.Number(object.id) : undefined, - command: isSet(object.command) ? globalThis.String(object.command) : undefined, - schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : undefined, + command: isSet(object.command) + ? globalThis.String(object.command) + : undefined, + schedule: isSet(object.schedule) + ? globalThis.String(object.schedule) + : undefined, name: isSet(object.name) ? globalThis.String(object.name) : undefined, - labels: globalThis.Array.isArray(object?.labels) ? object.labels.map((e: any) => globalThis.String(e)) : [], - sub_id: isSet(object.sub_id) ? globalThis.Number(object.sub_id) : undefined, + labels: globalThis.Array.isArray(object?.labels) + ? object.labels.map((e: any) => globalThis.String(e)) + : [], + sub_id: isSet(object.sub_id) + ? globalThis.Number(object.sub_id) + : undefined, extra_schedules: globalThis.Array.isArray(object?.extra_schedules) ? object.extra_schedules.map((e: any) => ExtraScheduleItem.fromJSON(e)) : [], - task_before: isSet(object.task_before) ? globalThis.String(object.task_before) : undefined, - task_after: isSet(object.task_after) ? globalThis.String(object.task_after) : undefined, - status: isSet(object.status) ? globalThis.Number(object.status) : undefined, - log_path: isSet(object.log_path) ? globalThis.String(object.log_path) : undefined, + task_before: isSet(object.task_before) + ? globalThis.String(object.task_before) + : undefined, + task_after: isSet(object.task_after) + ? globalThis.String(object.task_after) + : undefined, + status: isSet(object.status) + ? globalThis.Number(object.status) + : undefined, + log_path: isSet(object.log_path) + ? globalThis.String(object.log_path) + : undefined, pid: isSet(object.pid) ? globalThis.Number(object.pid) : undefined, - last_running_time: isSet(object.last_running_time) ? globalThis.Number(object.last_running_time) : undefined, + last_running_time: isSet(object.last_running_time) + ? globalThis.Number(object.last_running_time) + : undefined, last_execution_time: isSet(object.last_execution_time) ? globalThis.Number(object.last_execution_time) : undefined, @@ -1751,7 +1933,9 @@ export const CronItem: MessageFns = { obj.sub_id = Math.round(message.sub_id); } if (message.extra_schedules?.length) { - obj.extra_schedules = message.extra_schedules.map((e) => ExtraScheduleItem.toJSON(e)); + obj.extra_schedules = message.extra_schedules.map((e) => + ExtraScheduleItem.toJSON(e), + ); } if (message.task_before !== undefined) { obj.task_before = message.task_before; @@ -1788,7 +1972,9 @@ export const CronItem: MessageFns = { message.name = object.name ?? undefined; message.labels = object.labels?.map((e) => e) || []; message.sub_id = object.sub_id ?? undefined; - message.extra_schedules = object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || []; + message.extra_schedules = + object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || + []; message.task_before = object.task_before ?? undefined; message.task_after = object.task_after ?? undefined; message.status = object.status ?? undefined; @@ -1802,8 +1988,8 @@ export const CronItem: MessageFns = { function createBaseCreateCronRequest(): CreateCronRequest { return { - command: "", - schedule: "", + command: '', + schedule: '', name: undefined, labels: [], sub_id: undefined, @@ -1814,11 +2000,14 @@ function createBaseCreateCronRequest(): CreateCronRequest { } export const CreateCronRequest: MessageFns = { - encode(message: CreateCronRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.command !== "") { + encode( + message: CreateCronRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.command !== '') { writer.uint32(10).string(message.command); } - if (message.schedule !== "") { + if (message.schedule !== '') { writer.uint32(18).string(message.schedule); } if (message.name !== undefined) { @@ -1843,7 +2032,8 @@ export const CreateCronRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): CreateCronRequest { - 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 = createBaseCreateCronRequest(); while (reader.pos < end) { @@ -1894,7 +2084,9 @@ export const CreateCronRequest: MessageFns = { break; } - message.extra_schedules.push(ExtraScheduleItem.decode(reader, reader.uint32())); + message.extra_schedules.push( + ExtraScheduleItem.decode(reader, reader.uint32()), + ); continue; } case 7: { @@ -1924,25 +2116,35 @@ export const CreateCronRequest: MessageFns = { fromJSON(object: any): CreateCronRequest { return { - command: isSet(object.command) ? globalThis.String(object.command) : "", - schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : "", + command: isSet(object.command) ? globalThis.String(object.command) : '', + schedule: isSet(object.schedule) + ? globalThis.String(object.schedule) + : '', name: isSet(object.name) ? globalThis.String(object.name) : undefined, - labels: globalThis.Array.isArray(object?.labels) ? object.labels.map((e: any) => globalThis.String(e)) : [], - sub_id: isSet(object.sub_id) ? globalThis.Number(object.sub_id) : undefined, + labels: globalThis.Array.isArray(object?.labels) + ? object.labels.map((e: any) => globalThis.String(e)) + : [], + sub_id: isSet(object.sub_id) + ? globalThis.Number(object.sub_id) + : undefined, extra_schedules: globalThis.Array.isArray(object?.extra_schedules) ? object.extra_schedules.map((e: any) => ExtraScheduleItem.fromJSON(e)) : [], - task_before: isSet(object.task_before) ? globalThis.String(object.task_before) : undefined, - task_after: isSet(object.task_after) ? globalThis.String(object.task_after) : undefined, + task_before: isSet(object.task_before) + ? globalThis.String(object.task_before) + : undefined, + task_after: isSet(object.task_after) + ? globalThis.String(object.task_after) + : undefined, }; }, toJSON(message: CreateCronRequest): unknown { const obj: any = {}; - if (message.command !== "") { + if (message.command !== '') { obj.command = message.command; } - if (message.schedule !== "") { + if (message.schedule !== '') { obj.schedule = message.schedule; } if (message.name !== undefined) { @@ -1955,7 +2157,9 @@ export const CreateCronRequest: MessageFns = { obj.sub_id = Math.round(message.sub_id); } if (message.extra_schedules?.length) { - obj.extra_schedules = message.extra_schedules.map((e) => ExtraScheduleItem.toJSON(e)); + obj.extra_schedules = message.extra_schedules.map((e) => + ExtraScheduleItem.toJSON(e), + ); } if (message.task_before !== undefined) { obj.task_before = message.task_before; @@ -1966,17 +2170,23 @@ export const CreateCronRequest: MessageFns = { return obj; }, - create, I>>(base?: I): CreateCronRequest { + create, I>>( + base?: I, + ): CreateCronRequest { return CreateCronRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CreateCronRequest { + fromPartial, I>>( + object: I, + ): CreateCronRequest { const message = createBaseCreateCronRequest(); - message.command = object.command ?? ""; - message.schedule = object.schedule ?? ""; + message.command = object.command ?? ''; + message.schedule = object.schedule ?? ''; message.name = object.name ?? undefined; message.labels = object.labels?.map((e) => e) || []; message.sub_id = object.sub_id ?? undefined; - message.extra_schedules = object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || []; + message.extra_schedules = + object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || + []; message.task_before = object.task_before ?? undefined; message.task_after = object.task_after ?? undefined; return message; @@ -1998,7 +2208,10 @@ function createBaseUpdateCronRequest(): UpdateCronRequest { } export const UpdateCronRequest: MessageFns = { - encode(message: UpdateCronRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: UpdateCronRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== 0) { writer.uint32(8).int32(message.id); } @@ -2030,7 +2243,8 @@ export const UpdateCronRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): UpdateCronRequest { - 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 = createBaseUpdateCronRequest(); while (reader.pos < end) { @@ -2089,7 +2303,9 @@ export const UpdateCronRequest: MessageFns = { break; } - message.extra_schedules.push(ExtraScheduleItem.decode(reader, reader.uint32())); + message.extra_schedules.push( + ExtraScheduleItem.decode(reader, reader.uint32()), + ); continue; } case 8: { @@ -2120,16 +2336,28 @@ export const UpdateCronRequest: MessageFns = { fromJSON(object: any): UpdateCronRequest { return { id: isSet(object.id) ? globalThis.Number(object.id) : 0, - command: isSet(object.command) ? globalThis.String(object.command) : undefined, - schedule: isSet(object.schedule) ? globalThis.String(object.schedule) : undefined, + command: isSet(object.command) + ? globalThis.String(object.command) + : undefined, + schedule: isSet(object.schedule) + ? globalThis.String(object.schedule) + : undefined, name: isSet(object.name) ? globalThis.String(object.name) : undefined, - labels: globalThis.Array.isArray(object?.labels) ? object.labels.map((e: any) => globalThis.String(e)) : [], - sub_id: isSet(object.sub_id) ? globalThis.Number(object.sub_id) : undefined, + labels: globalThis.Array.isArray(object?.labels) + ? object.labels.map((e: any) => globalThis.String(e)) + : [], + sub_id: isSet(object.sub_id) + ? globalThis.Number(object.sub_id) + : undefined, extra_schedules: globalThis.Array.isArray(object?.extra_schedules) ? object.extra_schedules.map((e: any) => ExtraScheduleItem.fromJSON(e)) : [], - task_before: isSet(object.task_before) ? globalThis.String(object.task_before) : undefined, - task_after: isSet(object.task_after) ? globalThis.String(object.task_after) : undefined, + task_before: isSet(object.task_before) + ? globalThis.String(object.task_before) + : undefined, + task_after: isSet(object.task_after) + ? globalThis.String(object.task_after) + : undefined, }; }, @@ -2154,7 +2382,9 @@ export const UpdateCronRequest: MessageFns = { obj.sub_id = Math.round(message.sub_id); } if (message.extra_schedules?.length) { - obj.extra_schedules = message.extra_schedules.map((e) => ExtraScheduleItem.toJSON(e)); + obj.extra_schedules = message.extra_schedules.map((e) => + ExtraScheduleItem.toJSON(e), + ); } if (message.task_before !== undefined) { obj.task_before = message.task_before; @@ -2165,10 +2395,14 @@ export const UpdateCronRequest: MessageFns = { return obj; }, - create, I>>(base?: I): UpdateCronRequest { + create, I>>( + base?: I, + ): UpdateCronRequest { return UpdateCronRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): UpdateCronRequest { + fromPartial, I>>( + object: I, + ): UpdateCronRequest { const message = createBaseUpdateCronRequest(); message.id = object.id ?? 0; message.command = object.command ?? undefined; @@ -2176,7 +2410,9 @@ export const UpdateCronRequest: MessageFns = { message.name = object.name ?? undefined; message.labels = object.labels?.map((e) => e) || []; message.sub_id = object.sub_id ?? undefined; - message.extra_schedules = object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || []; + message.extra_schedules = + object.extra_schedules?.map((e) => ExtraScheduleItem.fromPartial(e)) || + []; message.task_before = object.task_before ?? undefined; message.task_after = object.task_after ?? undefined; return message; @@ -2188,7 +2424,10 @@ function createBaseDeleteCronsRequest(): DeleteCronsRequest { } export const DeleteCronsRequest: MessageFns = { - encode(message: DeleteCronsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: DeleteCronsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -2197,8 +2436,12 @@ export const DeleteCronsRequest: MessageFns = { return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): DeleteCronsRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): DeleteCronsRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseDeleteCronsRequest(); while (reader.pos < end) { @@ -2232,7 +2475,11 @@ export const DeleteCronsRequest: MessageFns = { }, fromJSON(object: any): DeleteCronsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: DeleteCronsRequest): unknown { @@ -2243,10 +2490,14 @@ export const DeleteCronsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): DeleteCronsRequest { + create, I>>( + base?: I, + ): DeleteCronsRequest { return DeleteCronsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): DeleteCronsRequest { + fromPartial, I>>( + object: I, + ): DeleteCronsRequest { const message = createBaseDeleteCronsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -2258,7 +2509,10 @@ function createBaseGetCronsRequest(): GetCronsRequest { } export const GetCronsRequest: MessageFns = { - encode(message: GetCronsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: GetCronsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.searchValue !== undefined) { writer.uint32(10).string(message.searchValue); } @@ -2266,7 +2520,8 @@ export const GetCronsRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): GetCronsRequest { - 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 = createBaseGetCronsRequest(); while (reader.pos < end) { @@ -2290,7 +2545,11 @@ export const GetCronsRequest: MessageFns = { }, fromJSON(object: any): GetCronsRequest { - return { searchValue: isSet(object.searchValue) ? globalThis.String(object.searchValue) : undefined }; + return { + searchValue: isSet(object.searchValue) + ? globalThis.String(object.searchValue) + : undefined, + }; }, toJSON(message: GetCronsRequest): unknown { @@ -2301,10 +2560,14 @@ export const GetCronsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): GetCronsRequest { + create, I>>( + base?: I, + ): GetCronsRequest { return GetCronsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): GetCronsRequest { + fromPartial, I>>( + object: I, + ): GetCronsRequest { const message = createBaseGetCronsRequest(); message.searchValue = object.searchValue ?? undefined; return message; @@ -2316,15 +2579,22 @@ function createBaseGetCronByIdRequest(): GetCronByIdRequest { } export const GetCronByIdRequest: MessageFns = { - encode(message: GetCronByIdRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: GetCronByIdRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.id !== 0) { writer.uint32(8).int32(message.id); } return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): GetCronByIdRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): GetCronByIdRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseGetCronByIdRequest(); while (reader.pos < end) { @@ -2359,10 +2629,14 @@ export const GetCronByIdRequest: MessageFns = { return obj; }, - create, I>>(base?: I): GetCronByIdRequest { + create, I>>( + base?: I, + ): GetCronByIdRequest { return GetCronByIdRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): GetCronByIdRequest { + fromPartial, I>>( + object: I, + ): GetCronByIdRequest { const message = createBaseGetCronByIdRequest(); message.id = object.id ?? 0; return message; @@ -2374,7 +2648,10 @@ function createBaseEnableCronsRequest(): EnableCronsRequest { } export const EnableCronsRequest: MessageFns = { - encode(message: EnableCronsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: EnableCronsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -2383,8 +2660,12 @@ export const EnableCronsRequest: MessageFns = { return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): EnableCronsRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): EnableCronsRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseEnableCronsRequest(); while (reader.pos < end) { @@ -2418,7 +2699,11 @@ export const EnableCronsRequest: MessageFns = { }, fromJSON(object: any): EnableCronsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: EnableCronsRequest): unknown { @@ -2429,10 +2714,14 @@ export const EnableCronsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): EnableCronsRequest { + create, I>>( + base?: I, + ): EnableCronsRequest { return EnableCronsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): EnableCronsRequest { + fromPartial, I>>( + object: I, + ): EnableCronsRequest { const message = createBaseEnableCronsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -2444,7 +2733,10 @@ function createBaseDisableCronsRequest(): DisableCronsRequest { } export const DisableCronsRequest: MessageFns = { - encode(message: DisableCronsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: DisableCronsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -2453,8 +2745,12 @@ export const DisableCronsRequest: MessageFns = { return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): DisableCronsRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): DisableCronsRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseDisableCronsRequest(); while (reader.pos < end) { @@ -2488,7 +2784,11 @@ export const DisableCronsRequest: MessageFns = { }, fromJSON(object: any): DisableCronsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: DisableCronsRequest): unknown { @@ -2499,10 +2799,14 @@ export const DisableCronsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): DisableCronsRequest { + create, I>>( + base?: I, + ): DisableCronsRequest { return DisableCronsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): DisableCronsRequest { + fromPartial, I>>( + object: I, + ): DisableCronsRequest { const message = createBaseDisableCronsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -2514,7 +2818,10 @@ function createBaseRunCronsRequest(): RunCronsRequest { } export const RunCronsRequest: MessageFns = { - encode(message: RunCronsRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: RunCronsRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { writer.uint32(10).fork(); for (const v of message.ids) { writer.int32(v); @@ -2524,7 +2831,8 @@ export const RunCronsRequest: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): RunCronsRequest { - 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 = createBaseRunCronsRequest(); while (reader.pos < end) { @@ -2558,7 +2866,11 @@ export const RunCronsRequest: MessageFns = { }, fromJSON(object: any): RunCronsRequest { - return { ids: globalThis.Array.isArray(object?.ids) ? object.ids.map((e: any) => globalThis.Number(e)) : [] }; + return { + ids: globalThis.Array.isArray(object?.ids) + ? object.ids.map((e: any) => globalThis.Number(e)) + : [], + }; }, toJSON(message: RunCronsRequest): unknown { @@ -2569,10 +2881,14 @@ export const RunCronsRequest: MessageFns = { return obj; }, - create, I>>(base?: I): RunCronsRequest { + create, I>>( + base?: I, + ): RunCronsRequest { return RunCronsRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): RunCronsRequest { + fromPartial, I>>( + object: I, + ): RunCronsRequest { const message = createBaseRunCronsRequest(); message.ids = object.ids?.map((e) => e) || []; return message; @@ -2584,7 +2900,10 @@ function createBaseCronsResponse(): CronsResponse { } export const CronsResponse: MessageFns = { - encode(message: CronsResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: CronsResponse, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -2598,7 +2917,8 @@ export const CronsResponse: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): CronsResponse { - 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 = createBaseCronsResponse(); while (reader.pos < end) { @@ -2640,8 +2960,12 @@ export const CronsResponse: MessageFns = { fromJSON(object: any): CronsResponse { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, - data: globalThis.Array.isArray(object?.data) ? object.data.map((e: any) => CronItem.fromJSON(e)) : [], - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + data: globalThis.Array.isArray(object?.data) + ? object.data.map((e: any) => CronItem.fromJSON(e)) + : [], + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -2659,10 +2983,14 @@ export const CronsResponse: MessageFns = { return obj; }, - create, I>>(base?: I): CronsResponse { + create, I>>( + base?: I, + ): CronsResponse { return CronsResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CronsResponse { + fromPartial, I>>( + object: I, + ): CronsResponse { const message = createBaseCronsResponse(); message.code = object.code ?? 0; message.data = object.data?.map((e) => CronItem.fromPartial(e)) || []; @@ -2676,7 +3004,10 @@ function createBaseCronResponse(): CronResponse { } export const CronResponse: MessageFns = { - encode(message: CronResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: CronResponse, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -2690,7 +3021,8 @@ export const CronResponse: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): CronResponse { - 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 = createBaseCronResponse(); while (reader.pos < end) { @@ -2733,7 +3065,9 @@ export const CronResponse: MessageFns = { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, data: isSet(object.data) ? CronItem.fromJSON(object.data) : undefined, - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -2751,32 +3085,43 @@ export const CronResponse: MessageFns = { return obj; }, - create, I>>(base?: I): CronResponse { + create, I>>( + base?: I, + ): CronResponse { return CronResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CronResponse { + fromPartial, I>>( + object: I, + ): CronResponse { const message = createBaseCronResponse(); message.code = object.code ?? 0; - message.data = (object.data !== undefined && object.data !== null) ? CronItem.fromPartial(object.data) : undefined; + message.data = + object.data !== undefined && object.data !== null + ? CronItem.fromPartial(object.data) + : undefined; message.message = object.message ?? undefined; return message; }, }; function createBaseCronDetailRequest(): CronDetailRequest { - return { log_path: "" }; + return { log_path: '' }; } export const CronDetailRequest: MessageFns = { - encode(message: CronDetailRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.log_path !== "") { + encode( + message: CronDetailRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.log_path !== '') { writer.uint32(10).string(message.log_path); } return writer; }, decode(input: BinaryReader | Uint8Array, length?: number): CronDetailRequest { - 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 = createBaseCronDetailRequest(); while (reader.pos < end) { @@ -2800,23 +3145,31 @@ export const CronDetailRequest: MessageFns = { }, fromJSON(object: any): CronDetailRequest { - return { log_path: isSet(object.log_path) ? globalThis.String(object.log_path) : "" }; + return { + log_path: isSet(object.log_path) + ? globalThis.String(object.log_path) + : '', + }; }, toJSON(message: CronDetailRequest): unknown { const obj: any = {}; - if (message.log_path !== "") { + if (message.log_path !== '') { obj.log_path = message.log_path; } return obj; }, - create, I>>(base?: I): CronDetailRequest { + create, I>>( + base?: I, + ): CronDetailRequest { return CronDetailRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CronDetailRequest { + fromPartial, I>>( + object: I, + ): CronDetailRequest { const message = createBaseCronDetailRequest(); - message.log_path = object.log_path ?? ""; + message.log_path = object.log_path ?? ''; return message; }, }; @@ -2826,7 +3179,10 @@ function createBaseCronDetailResponse(): CronDetailResponse { } export const CronDetailResponse: MessageFns = { - encode(message: CronDetailResponse, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: CronDetailResponse, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.code !== 0) { writer.uint32(8).int32(message.code); } @@ -2839,8 +3195,12 @@ export const CronDetailResponse: MessageFns = { return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): CronDetailResponse { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): CronDetailResponse { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseCronDetailResponse(); while (reader.pos < end) { @@ -2883,7 +3243,9 @@ export const CronDetailResponse: MessageFns = { return { code: isSet(object.code) ? globalThis.Number(object.code) : 0, data: isSet(object.data) ? CronItem.fromJSON(object.data) : undefined, - message: isSet(object.message) ? globalThis.String(object.message) : undefined, + message: isSet(object.message) + ? globalThis.String(object.message) + : undefined, }; }, @@ -2901,13 +3263,20 @@ export const CronDetailResponse: MessageFns = { return obj; }, - create, I>>(base?: I): CronDetailResponse { + create, I>>( + base?: I, + ): CronDetailResponse { return CronDetailResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): CronDetailResponse { + fromPartial, I>>( + object: I, + ): CronDetailResponse { const message = createBaseCronDetailResponse(); message.code = object.code ?? 0; - message.data = (object.data !== undefined && object.data !== null) ? CronItem.fromPartial(object.data) : undefined; + message.data = + object.data !== undefined && object.data !== null + ? CronItem.fromPartial(object.data) + : undefined; message.message = object.message ?? undefined; return message; }, @@ -2992,7 +3361,10 @@ function createBaseNotificationInfo(): NotificationInfo { } export const NotificationInfo: MessageFns = { - encode(message: NotificationInfo, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { + encode( + message: NotificationInfo, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { if (message.type !== 0) { writer.uint32(8).int32(message.type); } @@ -3216,7 +3588,8 @@ export const NotificationInfo: MessageFns = { }, decode(input: BinaryReader | Uint8Array, length?: number): NotificationInfo { - 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 = createBaseNotificationInfo(); while (reader.pos < end) { @@ -3818,25 +4191,63 @@ export const NotificationInfo: MessageFns = { fromJSON(object: any): NotificationInfo { return { type: isSet(object.type) ? notificationModeFromJSON(object.type) : 0, - gotifyUrl: isSet(object.gotifyUrl) ? globalThis.String(object.gotifyUrl) : undefined, - gotifyToken: isSet(object.gotifyToken) ? globalThis.String(object.gotifyToken) : undefined, - gotifyPriority: isSet(object.gotifyPriority) ? globalThis.Number(object.gotifyPriority) : undefined, - goCqHttpBotUrl: isSet(object.goCqHttpBotUrl) ? globalThis.String(object.goCqHttpBotUrl) : undefined, - goCqHttpBotToken: isSet(object.goCqHttpBotToken) ? globalThis.String(object.goCqHttpBotToken) : undefined, - goCqHttpBotQq: isSet(object.goCqHttpBotQq) ? globalThis.String(object.goCqHttpBotQq) : undefined, - serverChanKey: isSet(object.serverChanKey) ? globalThis.String(object.serverChanKey) : undefined, - pushDeerKey: isSet(object.pushDeerKey) ? globalThis.String(object.pushDeerKey) : undefined, - pushDeerUrl: isSet(object.pushDeerUrl) ? globalThis.String(object.pushDeerUrl) : undefined, - synologyChatUrl: isSet(object.synologyChatUrl) ? globalThis.String(object.synologyChatUrl) : undefined, - barkPush: isSet(object.barkPush) ? globalThis.String(object.barkPush) : undefined, - barkIcon: isSet(object.barkIcon) ? globalThis.String(object.barkIcon) : undefined, - barkSound: isSet(object.barkSound) ? globalThis.String(object.barkSound) : undefined, - barkGroup: isSet(object.barkGroup) ? globalThis.String(object.barkGroup) : undefined, - barkLevel: isSet(object.barkLevel) ? globalThis.String(object.barkLevel) : undefined, - barkUrl: isSet(object.barkUrl) ? globalThis.String(object.barkUrl) : undefined, - barkArchive: isSet(object.barkArchive) ? globalThis.String(object.barkArchive) : undefined, - telegramBotToken: isSet(object.telegramBotToken) ? globalThis.String(object.telegramBotToken) : undefined, - telegramBotUserId: isSet(object.telegramBotUserId) ? globalThis.String(object.telegramBotUserId) : undefined, + gotifyUrl: isSet(object.gotifyUrl) + ? globalThis.String(object.gotifyUrl) + : undefined, + gotifyToken: isSet(object.gotifyToken) + ? globalThis.String(object.gotifyToken) + : undefined, + gotifyPriority: isSet(object.gotifyPriority) + ? globalThis.Number(object.gotifyPriority) + : undefined, + goCqHttpBotUrl: isSet(object.goCqHttpBotUrl) + ? globalThis.String(object.goCqHttpBotUrl) + : undefined, + goCqHttpBotToken: isSet(object.goCqHttpBotToken) + ? globalThis.String(object.goCqHttpBotToken) + : undefined, + goCqHttpBotQq: isSet(object.goCqHttpBotQq) + ? globalThis.String(object.goCqHttpBotQq) + : undefined, + serverChanKey: isSet(object.serverChanKey) + ? globalThis.String(object.serverChanKey) + : undefined, + pushDeerKey: isSet(object.pushDeerKey) + ? globalThis.String(object.pushDeerKey) + : undefined, + pushDeerUrl: isSet(object.pushDeerUrl) + ? globalThis.String(object.pushDeerUrl) + : undefined, + synologyChatUrl: isSet(object.synologyChatUrl) + ? globalThis.String(object.synologyChatUrl) + : undefined, + barkPush: isSet(object.barkPush) + ? globalThis.String(object.barkPush) + : undefined, + barkIcon: isSet(object.barkIcon) + ? globalThis.String(object.barkIcon) + : undefined, + barkSound: isSet(object.barkSound) + ? globalThis.String(object.barkSound) + : undefined, + barkGroup: isSet(object.barkGroup) + ? globalThis.String(object.barkGroup) + : undefined, + barkLevel: isSet(object.barkLevel) + ? globalThis.String(object.barkLevel) + : undefined, + barkUrl: isSet(object.barkUrl) + ? globalThis.String(object.barkUrl) + : undefined, + barkArchive: isSet(object.barkArchive) + ? globalThis.String(object.barkArchive) + : undefined, + telegramBotToken: isSet(object.telegramBotToken) + ? globalThis.String(object.telegramBotToken) + : undefined, + telegramBotUserId: isSet(object.telegramBotUserId) + ? globalThis.String(object.telegramBotUserId) + : undefined, telegramBotProxyHost: isSet(object.telegramBotProxyHost) ? globalThis.String(object.telegramBotProxyHost) : undefined, @@ -3846,62 +4257,156 @@ export const NotificationInfo: MessageFns = { telegramBotProxyAuth: isSet(object.telegramBotProxyAuth) ? globalThis.String(object.telegramBotProxyAuth) : undefined, - telegramBotApiHost: isSet(object.telegramBotApiHost) ? globalThis.String(object.telegramBotApiHost) : undefined, - dingtalkBotToken: isSet(object.dingtalkBotToken) ? globalThis.String(object.dingtalkBotToken) : undefined, - dingtalkBotSecret: isSet(object.dingtalkBotSecret) ? globalThis.String(object.dingtalkBotSecret) : undefined, - weWorkBotKey: isSet(object.weWorkBotKey) ? globalThis.String(object.weWorkBotKey) : undefined, - weWorkOrigin: isSet(object.weWorkOrigin) ? globalThis.String(object.weWorkOrigin) : undefined, - weWorkAppKey: isSet(object.weWorkAppKey) ? globalThis.String(object.weWorkAppKey) : undefined, - aibotkKey: isSet(object.aibotkKey) ? globalThis.String(object.aibotkKey) : undefined, - aibotkType: isSet(object.aibotkType) ? globalThis.String(object.aibotkType) : undefined, - aibotkName: isSet(object.aibotkName) ? globalThis.String(object.aibotkName) : undefined, - iGotPushKey: isSet(object.iGotPushKey) ? globalThis.String(object.iGotPushKey) : undefined, - pushPlusToken: isSet(object.pushPlusToken) ? globalThis.String(object.pushPlusToken) : undefined, - pushPlusUser: isSet(object.pushPlusUser) ? globalThis.String(object.pushPlusUser) : undefined, - pushPlusTemplate: isSet(object.pushPlusTemplate) ? globalThis.String(object.pushPlusTemplate) : undefined, - pushplusChannel: isSet(object.pushplusChannel) ? globalThis.String(object.pushplusChannel) : undefined, - pushplusWebhook: isSet(object.pushplusWebhook) ? globalThis.String(object.pushplusWebhook) : undefined, + telegramBotApiHost: isSet(object.telegramBotApiHost) + ? globalThis.String(object.telegramBotApiHost) + : undefined, + dingtalkBotToken: isSet(object.dingtalkBotToken) + ? globalThis.String(object.dingtalkBotToken) + : undefined, + dingtalkBotSecret: isSet(object.dingtalkBotSecret) + ? globalThis.String(object.dingtalkBotSecret) + : undefined, + weWorkBotKey: isSet(object.weWorkBotKey) + ? globalThis.String(object.weWorkBotKey) + : undefined, + weWorkOrigin: isSet(object.weWorkOrigin) + ? globalThis.String(object.weWorkOrigin) + : undefined, + weWorkAppKey: isSet(object.weWorkAppKey) + ? globalThis.String(object.weWorkAppKey) + : undefined, + aibotkKey: isSet(object.aibotkKey) + ? globalThis.String(object.aibotkKey) + : undefined, + aibotkType: isSet(object.aibotkType) + ? globalThis.String(object.aibotkType) + : undefined, + aibotkName: isSet(object.aibotkName) + ? globalThis.String(object.aibotkName) + : undefined, + iGotPushKey: isSet(object.iGotPushKey) + ? globalThis.String(object.iGotPushKey) + : undefined, + pushPlusToken: isSet(object.pushPlusToken) + ? globalThis.String(object.pushPlusToken) + : undefined, + pushPlusUser: isSet(object.pushPlusUser) + ? globalThis.String(object.pushPlusUser) + : undefined, + pushPlusTemplate: isSet(object.pushPlusTemplate) + ? globalThis.String(object.pushPlusTemplate) + : undefined, + pushplusChannel: isSet(object.pushplusChannel) + ? globalThis.String(object.pushplusChannel) + : undefined, + pushplusWebhook: isSet(object.pushplusWebhook) + ? globalThis.String(object.pushplusWebhook) + : undefined, pushplusCallbackUrl: isSet(object.pushplusCallbackUrl) ? globalThis.String(object.pushplusCallbackUrl) : undefined, - pushplusTo: isSet(object.pushplusTo) ? globalThis.String(object.pushplusTo) : undefined, - wePlusBotToken: isSet(object.wePlusBotToken) ? globalThis.String(object.wePlusBotToken) : undefined, - wePlusBotReceiver: isSet(object.wePlusBotReceiver) ? globalThis.String(object.wePlusBotReceiver) : undefined, - wePlusBotVersion: isSet(object.wePlusBotVersion) ? globalThis.String(object.wePlusBotVersion) : undefined, - emailService: isSet(object.emailService) ? globalThis.String(object.emailService) : undefined, - emailUser: isSet(object.emailUser) ? globalThis.String(object.emailUser) : undefined, - emailPass: isSet(object.emailPass) ? globalThis.String(object.emailPass) : undefined, - emailTo: isSet(object.emailTo) ? globalThis.String(object.emailTo) : undefined, - pushMeKey: isSet(object.pushMeKey) ? globalThis.String(object.pushMeKey) : undefined, - pushMeUrl: isSet(object.pushMeUrl) ? globalThis.String(object.pushMeUrl) : undefined, - chronocatURL: isSet(object.chronocatURL) ? globalThis.String(object.chronocatURL) : undefined, - chronocatQQ: isSet(object.chronocatQQ) ? globalThis.String(object.chronocatQQ) : undefined, - chronocatToken: isSet(object.chronocatToken) ? globalThis.String(object.chronocatToken) : undefined, - webhookHeaders: isSet(object.webhookHeaders) ? globalThis.String(object.webhookHeaders) : undefined, - webhookBody: isSet(object.webhookBody) ? globalThis.String(object.webhookBody) : undefined, - webhookUrl: isSet(object.webhookUrl) ? globalThis.String(object.webhookUrl) : undefined, - webhookMethod: isSet(object.webhookMethod) ? globalThis.String(object.webhookMethod) : undefined, - webhookContentType: isSet(object.webhookContentType) ? globalThis.String(object.webhookContentType) : undefined, - larkKey: isSet(object.larkKey) ? globalThis.String(object.larkKey) : undefined, - larkSecret: isSet(object.larkSecret) ? globalThis.String(object.larkSecret) : undefined, - ntfyUrl: isSet(object.ntfyUrl) ? globalThis.String(object.ntfyUrl) : undefined, - ntfyTopic: isSet(object.ntfyTopic) ? globalThis.String(object.ntfyTopic) : undefined, - ntfyPriority: isSet(object.ntfyPriority) ? globalThis.String(object.ntfyPriority) : undefined, - ntfyToken: isSet(object.ntfyToken) ? globalThis.String(object.ntfyToken) : undefined, - ntfyUsername: isSet(object.ntfyUsername) ? globalThis.String(object.ntfyUsername) : undefined, - ntfyPassword: isSet(object.ntfyPassword) ? globalThis.String(object.ntfyPassword) : undefined, - ntfyActions: isSet(object.ntfyActions) ? globalThis.String(object.ntfyActions) : undefined, + pushplusTo: isSet(object.pushplusTo) + ? globalThis.String(object.pushplusTo) + : undefined, + wePlusBotToken: isSet(object.wePlusBotToken) + ? globalThis.String(object.wePlusBotToken) + : undefined, + wePlusBotReceiver: isSet(object.wePlusBotReceiver) + ? globalThis.String(object.wePlusBotReceiver) + : undefined, + wePlusBotVersion: isSet(object.wePlusBotVersion) + ? globalThis.String(object.wePlusBotVersion) + : undefined, + emailService: isSet(object.emailService) + ? globalThis.String(object.emailService) + : undefined, + emailUser: isSet(object.emailUser) + ? globalThis.String(object.emailUser) + : undefined, + emailPass: isSet(object.emailPass) + ? globalThis.String(object.emailPass) + : undefined, + emailTo: isSet(object.emailTo) + ? globalThis.String(object.emailTo) + : undefined, + pushMeKey: isSet(object.pushMeKey) + ? globalThis.String(object.pushMeKey) + : undefined, + pushMeUrl: isSet(object.pushMeUrl) + ? globalThis.String(object.pushMeUrl) + : undefined, + chronocatURL: isSet(object.chronocatURL) + ? globalThis.String(object.chronocatURL) + : undefined, + chronocatQQ: isSet(object.chronocatQQ) + ? globalThis.String(object.chronocatQQ) + : undefined, + chronocatToken: isSet(object.chronocatToken) + ? globalThis.String(object.chronocatToken) + : undefined, + webhookHeaders: isSet(object.webhookHeaders) + ? globalThis.String(object.webhookHeaders) + : undefined, + webhookBody: isSet(object.webhookBody) + ? globalThis.String(object.webhookBody) + : undefined, + webhookUrl: isSet(object.webhookUrl) + ? globalThis.String(object.webhookUrl) + : undefined, + webhookMethod: isSet(object.webhookMethod) + ? globalThis.String(object.webhookMethod) + : undefined, + webhookContentType: isSet(object.webhookContentType) + ? globalThis.String(object.webhookContentType) + : undefined, + larkKey: isSet(object.larkKey) + ? globalThis.String(object.larkKey) + : undefined, + larkSecret: isSet(object.larkSecret) + ? globalThis.String(object.larkSecret) + : undefined, + ntfyUrl: isSet(object.ntfyUrl) + ? globalThis.String(object.ntfyUrl) + : undefined, + ntfyTopic: isSet(object.ntfyTopic) + ? globalThis.String(object.ntfyTopic) + : undefined, + ntfyPriority: isSet(object.ntfyPriority) + ? globalThis.String(object.ntfyPriority) + : undefined, + ntfyToken: isSet(object.ntfyToken) + ? globalThis.String(object.ntfyToken) + : undefined, + ntfyUsername: isSet(object.ntfyUsername) + ? globalThis.String(object.ntfyUsername) + : undefined, + ntfyPassword: isSet(object.ntfyPassword) + ? globalThis.String(object.ntfyPassword) + : undefined, + ntfyActions: isSet(object.ntfyActions) + ? globalThis.String(object.ntfyActions) + : undefined, wxPusherBotAppToken: isSet(object.wxPusherBotAppToken) ? globalThis.String(object.wxPusherBotAppToken) : undefined, wxPusherBotTopicIds: isSet(object.wxPusherBotTopicIds) ? globalThis.String(object.wxPusherBotTopicIds) : undefined, - wxPusherBotUids: isSet(object.wxPusherBotUids) ? globalThis.String(object.wxPusherBotUids) : undefined, - wxPusherSptList: isSet(object.wxPusherSptList) ? globalThis.String(object.wxPusherSptList) : undefined, - wpushApiKey: isSet(object.wpushApiKey) ? globalThis.String(object.wpushApiKey) : undefined, - wpushChannel: isSet(object.wpushChannel) ? globalThis.String(object.wpushChannel) : undefined, - wpushTopicCode: isSet(object.wpushTopicCode) ? globalThis.String(object.wpushTopicCode) : undefined, + wxPusherBotUids: isSet(object.wxPusherBotUids) + ? globalThis.String(object.wxPusherBotUids) + : undefined, + wxPusherSptList: isSet(object.wxPusherSptList) + ? globalThis.String(object.wxPusherSptList) + : undefined, + wpushApiKey: isSet(object.wpushApiKey) + ? globalThis.String(object.wpushApiKey) + : undefined, + wpushChannel: isSet(object.wpushChannel) + ? globalThis.String(object.wpushChannel) + : undefined, + wpushTopicCode: isSet(object.wpushTopicCode) + ? globalThis.String(object.wpushTopicCode) + : undefined, }; }, @@ -4129,10 +4634,14 @@ export const NotificationInfo: MessageFns = { return obj; }, - create, I>>(base?: I): NotificationInfo { + create, I>>( + base?: I, + ): NotificationInfo { return NotificationInfo.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): NotificationInfo { + fromPartial, I>>( + object: I, + ): NotificationInfo { const message = createBaseNotificationInfo(); message.type = object.type ?? 0; message.gotifyUrl = object.gotifyUrl ?? undefined; @@ -4212,25 +4721,35 @@ export const NotificationInfo: MessageFns = { }; function createBaseSystemNotifyRequest(): SystemNotifyRequest { - return { title: "", content: "", notificationInfo: undefined }; + return { title: '', content: '', notificationInfo: undefined }; } export const SystemNotifyRequest: MessageFns = { - encode(message: SystemNotifyRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.title !== "") { + encode( + message: SystemNotifyRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.title !== '') { writer.uint32(10).string(message.title); } - if (message.content !== "") { + if (message.content !== '') { writer.uint32(18).string(message.content); } if (message.notificationInfo !== undefined) { - NotificationInfo.encode(message.notificationInfo, writer.uint32(26).fork()).join(); + NotificationInfo.encode( + message.notificationInfo, + writer.uint32(26).fork(), + ).join(); } return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): SystemNotifyRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): SystemNotifyRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseSystemNotifyRequest(); while (reader.pos < end) { @@ -4257,7 +4776,10 @@ export const SystemNotifyRequest: MessageFns = { break; } - message.notificationInfo = NotificationInfo.decode(reader, reader.uint32()); + message.notificationInfo = NotificationInfo.decode( + reader, + reader.uint32(), + ); continue; } } @@ -4271,18 +4793,20 @@ export const SystemNotifyRequest: MessageFns = { fromJSON(object: any): SystemNotifyRequest { return { - title: isSet(object.title) ? globalThis.String(object.title) : "", - content: isSet(object.content) ? globalThis.String(object.content) : "", - notificationInfo: isSet(object.notificationInfo) ? NotificationInfo.fromJSON(object.notificationInfo) : undefined, + title: isSet(object.title) ? globalThis.String(object.title) : '', + content: isSet(object.content) ? globalThis.String(object.content) : '', + notificationInfo: isSet(object.notificationInfo) + ? NotificationInfo.fromJSON(object.notificationInfo) + : undefined, }; }, toJSON(message: SystemNotifyRequest): unknown { const obj: any = {}; - if (message.title !== "") { + if (message.title !== '') { obj.title = message.title; } - if (message.content !== "") { + if (message.content !== '') { obj.content = message.content; } if (message.notificationInfo !== undefined) { @@ -4291,49 +4815,68 @@ export const SystemNotifyRequest: MessageFns = { return obj; }, - create, I>>(base?: I): SystemNotifyRequest { + create, I>>( + base?: I, + ): SystemNotifyRequest { return SystemNotifyRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): SystemNotifyRequest { + fromPartial, I>>( + object: I, + ): SystemNotifyRequest { const message = createBaseSystemNotifyRequest(); - message.title = object.title ?? ""; - message.content = object.content ?? ""; - message.notificationInfo = (object.notificationInfo !== undefined && object.notificationInfo !== null) - ? NotificationInfo.fromPartial(object.notificationInfo) - : undefined; + message.title = object.title ?? ''; + message.content = object.content ?? ''; + message.notificationInfo = + object.notificationInfo !== undefined && object.notificationInfo !== null + ? NotificationInfo.fromPartial(object.notificationInfo) + : undefined; return message; }, }; function createBaseRecordNotifyLogRequest(): RecordNotifyLogRequest { - return { title: "", content: "", success: false, notifyType: "", scriptName: "", taskId: "" }; + return { + title: '', + content: '', + success: false, + notifyType: '', + scriptName: '', + taskId: '', + }; } export const RecordNotifyLogRequest: MessageFns = { - encode(message: RecordNotifyLogRequest, writer: BinaryWriter = new BinaryWriter()): BinaryWriter { - if (message.title !== "") { + encode( + message: RecordNotifyLogRequest, + writer: BinaryWriter = new BinaryWriter(), + ): BinaryWriter { + if (message.title !== '') { writer.uint32(10).string(message.title); } - if (message.content !== "") { + if (message.content !== '') { writer.uint32(18).string(message.content); } if (message.success !== false) { writer.uint32(24).bool(message.success); } - if (message.notifyType !== "") { + if (message.notifyType !== '') { writer.uint32(34).string(message.notifyType); } - if (message.scriptName !== "") { + if (message.scriptName !== '') { writer.uint32(42).string(message.scriptName); } - if (message.taskId !== "") { + if (message.taskId !== '') { writer.uint32(50).string(message.taskId); } return writer; }, - decode(input: BinaryReader | Uint8Array, length?: number): RecordNotifyLogRequest { - const reader = input instanceof BinaryReader ? input : new BinaryReader(input); + decode( + input: BinaryReader | Uint8Array, + length?: number, + ): RecordNotifyLogRequest { + const reader = + input instanceof BinaryReader ? input : new BinaryReader(input); let end = length === undefined ? reader.len : reader.pos + length; const message = createBaseRecordNotifyLogRequest(); while (reader.pos < end) { @@ -4398,49 +4941,59 @@ export const RecordNotifyLogRequest: MessageFns = { fromJSON(object: any): RecordNotifyLogRequest { return { - title: isSet(object.title) ? globalThis.String(object.title) : "", - content: isSet(object.content) ? globalThis.String(object.content) : "", - success: isSet(object.success) ? globalThis.Boolean(object.success) : false, - notifyType: isSet(object.notifyType) ? globalThis.String(object.notifyType) : "", - scriptName: isSet(object.scriptName) ? globalThis.String(object.scriptName) : "", - taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : "", + title: isSet(object.title) ? globalThis.String(object.title) : '', + content: isSet(object.content) ? globalThis.String(object.content) : '', + success: isSet(object.success) + ? globalThis.Boolean(object.success) + : false, + notifyType: isSet(object.notifyType) + ? globalThis.String(object.notifyType) + : '', + scriptName: isSet(object.scriptName) + ? globalThis.String(object.scriptName) + : '', + taskId: isSet(object.taskId) ? globalThis.String(object.taskId) : '', }; }, toJSON(message: RecordNotifyLogRequest): unknown { const obj: any = {}; - if (message.title !== "") { + if (message.title !== '') { obj.title = message.title; } - if (message.content !== "") { + if (message.content !== '') { obj.content = message.content; } if (message.success !== false) { obj.success = message.success; } - if (message.notifyType !== "") { + if (message.notifyType !== '') { obj.notifyType = message.notifyType; } - if (message.scriptName !== "") { + if (message.scriptName !== '') { obj.scriptName = message.scriptName; } - if (message.taskId !== "") { + if (message.taskId !== '') { obj.taskId = message.taskId; } return obj; }, - create, I>>(base?: I): RecordNotifyLogRequest { + create, I>>( + base?: I, + ): RecordNotifyLogRequest { return RecordNotifyLogRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): RecordNotifyLogRequest { + fromPartial, I>>( + object: I, + ): RecordNotifyLogRequest { const message = createBaseRecordNotifyLogRequest(); - message.title = object.title ?? ""; - message.content = object.content ?? ""; + message.title = object.title ?? ''; + message.content = object.content ?? ''; message.success = object.success ?? false; - message.notifyType = object.notifyType ?? ""; - message.scriptName = object.scriptName ?? ""; - message.taskId = object.taskId ?? ""; + message.notifyType = object.notifyType ?? ''; + message.scriptName = object.scriptName ?? ''; + message.taskId = object.taskId ?? ''; return message; }, }; @@ -4448,183 +5001,223 @@ export const RecordNotifyLogRequest: MessageFns = { export type ApiService = typeof ApiService; export const ApiService = { getEnvs: { - path: "/com.ql.api.Api/GetEnvs", + path: '/com.ql.api.Api/GetEnvs', requestStream: false, responseStream: false, - requestSerialize: (value: GetEnvsRequest) => Buffer.from(GetEnvsRequest.encode(value).finish()), + requestSerialize: (value: GetEnvsRequest) => + Buffer.from(GetEnvsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => GetEnvsRequest.decode(value), - responseSerialize: (value: EnvsResponse) => Buffer.from(EnvsResponse.encode(value).finish()), + responseSerialize: (value: EnvsResponse) => + Buffer.from(EnvsResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => EnvsResponse.decode(value), }, createEnv: { - path: "/com.ql.api.Api/CreateEnv", + path: '/com.ql.api.Api/CreateEnv', requestStream: false, responseStream: false, - requestSerialize: (value: CreateEnvRequest) => Buffer.from(CreateEnvRequest.encode(value).finish()), + requestSerialize: (value: CreateEnvRequest) => + Buffer.from(CreateEnvRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => CreateEnvRequest.decode(value), - responseSerialize: (value: EnvsResponse) => Buffer.from(EnvsResponse.encode(value).finish()), + responseSerialize: (value: EnvsResponse) => + Buffer.from(EnvsResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => EnvsResponse.decode(value), }, updateEnv: { - path: "/com.ql.api.Api/UpdateEnv", + path: '/com.ql.api.Api/UpdateEnv', requestStream: false, responseStream: false, - requestSerialize: (value: UpdateEnvRequest) => Buffer.from(UpdateEnvRequest.encode(value).finish()), + requestSerialize: (value: UpdateEnvRequest) => + Buffer.from(UpdateEnvRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => UpdateEnvRequest.decode(value), - responseSerialize: (value: EnvResponse) => Buffer.from(EnvResponse.encode(value).finish()), + responseSerialize: (value: EnvResponse) => + Buffer.from(EnvResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => EnvResponse.decode(value), }, deleteEnvs: { - path: "/com.ql.api.Api/DeleteEnvs", + path: '/com.ql.api.Api/DeleteEnvs', requestStream: false, responseStream: false, - requestSerialize: (value: DeleteEnvsRequest) => Buffer.from(DeleteEnvsRequest.encode(value).finish()), + requestSerialize: (value: DeleteEnvsRequest) => + Buffer.from(DeleteEnvsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => DeleteEnvsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, moveEnv: { - path: "/com.ql.api.Api/MoveEnv", + path: '/com.ql.api.Api/MoveEnv', requestStream: false, responseStream: false, - requestSerialize: (value: MoveEnvRequest) => Buffer.from(MoveEnvRequest.encode(value).finish()), + requestSerialize: (value: MoveEnvRequest) => + Buffer.from(MoveEnvRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => MoveEnvRequest.decode(value), - responseSerialize: (value: EnvResponse) => Buffer.from(EnvResponse.encode(value).finish()), + responseSerialize: (value: EnvResponse) => + Buffer.from(EnvResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => EnvResponse.decode(value), }, disableEnvs: { - path: "/com.ql.api.Api/DisableEnvs", + path: '/com.ql.api.Api/DisableEnvs', requestStream: false, responseStream: false, - requestSerialize: (value: DisableEnvsRequest) => Buffer.from(DisableEnvsRequest.encode(value).finish()), + requestSerialize: (value: DisableEnvsRequest) => + Buffer.from(DisableEnvsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => DisableEnvsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, enableEnvs: { - path: "/com.ql.api.Api/EnableEnvs", + path: '/com.ql.api.Api/EnableEnvs', requestStream: false, responseStream: false, - requestSerialize: (value: EnableEnvsRequest) => Buffer.from(EnableEnvsRequest.encode(value).finish()), + requestSerialize: (value: EnableEnvsRequest) => + Buffer.from(EnableEnvsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => EnableEnvsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, updateEnvNames: { - path: "/com.ql.api.Api/UpdateEnvNames", + path: '/com.ql.api.Api/UpdateEnvNames', requestStream: false, responseStream: false, - requestSerialize: (value: UpdateEnvNamesRequest) => Buffer.from(UpdateEnvNamesRequest.encode(value).finish()), + requestSerialize: (value: UpdateEnvNamesRequest) => + Buffer.from(UpdateEnvNamesRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => UpdateEnvNamesRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, getEnvById: { - path: "/com.ql.api.Api/GetEnvById", + path: '/com.ql.api.Api/GetEnvById', requestStream: false, responseStream: false, - requestSerialize: (value: GetEnvByIdRequest) => Buffer.from(GetEnvByIdRequest.encode(value).finish()), + requestSerialize: (value: GetEnvByIdRequest) => + Buffer.from(GetEnvByIdRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => GetEnvByIdRequest.decode(value), - responseSerialize: (value: EnvResponse) => Buffer.from(EnvResponse.encode(value).finish()), + responseSerialize: (value: EnvResponse) => + Buffer.from(EnvResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => EnvResponse.decode(value), }, systemNotify: { - path: "/com.ql.api.Api/SystemNotify", + path: '/com.ql.api.Api/SystemNotify', requestStream: false, responseStream: false, - requestSerialize: (value: SystemNotifyRequest) => Buffer.from(SystemNotifyRequest.encode(value).finish()), + requestSerialize: (value: SystemNotifyRequest) => + Buffer.from(SystemNotifyRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => SystemNotifyRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, recordNotifyLog: { - path: "/com.ql.api.Api/RecordNotifyLog", + path: '/com.ql.api.Api/RecordNotifyLog', requestStream: false, responseStream: false, - requestSerialize: (value: RecordNotifyLogRequest) => Buffer.from(RecordNotifyLogRequest.encode(value).finish()), + requestSerialize: (value: RecordNotifyLogRequest) => + Buffer.from(RecordNotifyLogRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => RecordNotifyLogRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, getCronDetail: { - path: "/com.ql.api.Api/GetCronDetail", + path: '/com.ql.api.Api/GetCronDetail', requestStream: false, responseStream: false, - requestSerialize: (value: CronDetailRequest) => Buffer.from(CronDetailRequest.encode(value).finish()), + requestSerialize: (value: CronDetailRequest) => + Buffer.from(CronDetailRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => CronDetailRequest.decode(value), - responseSerialize: (value: CronDetailResponse) => Buffer.from(CronDetailResponse.encode(value).finish()), + responseSerialize: (value: CronDetailResponse) => + Buffer.from(CronDetailResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => CronDetailResponse.decode(value), }, createCron: { - path: "/com.ql.api.Api/CreateCron", + path: '/com.ql.api.Api/CreateCron', requestStream: false, responseStream: false, - requestSerialize: (value: CreateCronRequest) => Buffer.from(CreateCronRequest.encode(value).finish()), + requestSerialize: (value: CreateCronRequest) => + Buffer.from(CreateCronRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => CreateCronRequest.decode(value), - responseSerialize: (value: CronResponse) => Buffer.from(CronResponse.encode(value).finish()), + responseSerialize: (value: CronResponse) => + Buffer.from(CronResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => CronResponse.decode(value), }, updateCron: { - path: "/com.ql.api.Api/UpdateCron", + path: '/com.ql.api.Api/UpdateCron', requestStream: false, responseStream: false, - requestSerialize: (value: UpdateCronRequest) => Buffer.from(UpdateCronRequest.encode(value).finish()), + requestSerialize: (value: UpdateCronRequest) => + Buffer.from(UpdateCronRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => UpdateCronRequest.decode(value), - responseSerialize: (value: CronResponse) => Buffer.from(CronResponse.encode(value).finish()), + responseSerialize: (value: CronResponse) => + Buffer.from(CronResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => CronResponse.decode(value), }, deleteCrons: { - path: "/com.ql.api.Api/DeleteCrons", + path: '/com.ql.api.Api/DeleteCrons', requestStream: false, responseStream: false, - requestSerialize: (value: DeleteCronsRequest) => Buffer.from(DeleteCronsRequest.encode(value).finish()), + requestSerialize: (value: DeleteCronsRequest) => + Buffer.from(DeleteCronsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => DeleteCronsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, getCrons: { - path: "/com.ql.api.Api/GetCrons", + path: '/com.ql.api.Api/GetCrons', requestStream: false, responseStream: false, - requestSerialize: (value: GetCronsRequest) => Buffer.from(GetCronsRequest.encode(value).finish()), + requestSerialize: (value: GetCronsRequest) => + Buffer.from(GetCronsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => GetCronsRequest.decode(value), - responseSerialize: (value: CronsResponse) => Buffer.from(CronsResponse.encode(value).finish()), + responseSerialize: (value: CronsResponse) => + Buffer.from(CronsResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => CronsResponse.decode(value), }, getCronById: { - path: "/com.ql.api.Api/GetCronById", + path: '/com.ql.api.Api/GetCronById', requestStream: false, responseStream: false, - requestSerialize: (value: GetCronByIdRequest) => Buffer.from(GetCronByIdRequest.encode(value).finish()), + requestSerialize: (value: GetCronByIdRequest) => + Buffer.from(GetCronByIdRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => GetCronByIdRequest.decode(value), - responseSerialize: (value: CronResponse) => Buffer.from(CronResponse.encode(value).finish()), + responseSerialize: (value: CronResponse) => + Buffer.from(CronResponse.encode(value).finish()), responseDeserialize: (value: Buffer) => CronResponse.decode(value), }, enableCrons: { - path: "/com.ql.api.Api/EnableCrons", + path: '/com.ql.api.Api/EnableCrons', requestStream: false, responseStream: false, - requestSerialize: (value: EnableCronsRequest) => Buffer.from(EnableCronsRequest.encode(value).finish()), + requestSerialize: (value: EnableCronsRequest) => + Buffer.from(EnableCronsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => EnableCronsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, disableCrons: { - path: "/com.ql.api.Api/DisableCrons", + path: '/com.ql.api.Api/DisableCrons', requestStream: false, responseStream: false, - requestSerialize: (value: DisableCronsRequest) => Buffer.from(DisableCronsRequest.encode(value).finish()), + requestSerialize: (value: DisableCronsRequest) => + Buffer.from(DisableCronsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => DisableCronsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, runCrons: { - path: "/com.ql.api.Api/RunCrons", + path: '/com.ql.api.Api/RunCrons', requestStream: false, responseStream: false, - requestSerialize: (value: RunCronsRequest) => Buffer.from(RunCronsRequest.encode(value).finish()), + requestSerialize: (value: RunCronsRequest) => + Buffer.from(RunCronsRequest.encode(value).finish()), requestDeserialize: (value: Buffer) => RunCronsRequest.decode(value), - responseSerialize: (value: Response) => Buffer.from(Response.encode(value).finish()), + responseSerialize: (value: Response) => + Buffer.from(Response.encode(value).finish()), responseDeserialize: (value: Buffer) => Response.decode(value), }, } as const; @@ -4820,18 +5413,27 @@ export interface ApiClient extends Client { ): ClientUnaryCall; getCronDetail( request: CronDetailRequest, - callback: (error: ServiceError | null, response: CronDetailResponse) => void, + callback: ( + error: ServiceError | null, + response: CronDetailResponse, + ) => void, ): ClientUnaryCall; getCronDetail( request: CronDetailRequest, metadata: Metadata, - callback: (error: ServiceError | null, response: CronDetailResponse) => void, + callback: ( + error: ServiceError | null, + response: CronDetailResponse, + ) => void, ): ClientUnaryCall; getCronDetail( request: CronDetailRequest, metadata: Metadata, options: Partial, - callback: (error: ServiceError | null, response: CronDetailResponse) => void, + callback: ( + error: ServiceError | null, + response: CronDetailResponse, + ) => void, ): ClientUnaryCall; createCron( request: CreateCronRequest, @@ -4955,31 +5557,52 @@ export interface ApiClient extends Client { ): ClientUnaryCall; } -export const ApiClient = makeGenericClientConstructor(ApiService, "com.ql.api.Api") as unknown as { - new (address: string, credentials: ChannelCredentials, options?: Partial): ApiClient; +export const ApiClient = makeGenericClientConstructor( + ApiService, + 'com.ql.api.Api', +) as unknown as { + new ( + address: string, + credentials: ChannelCredentials, + options?: Partial, + ): ApiClient; service: typeof ApiService; serviceName: string; }; -type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined; +type Builtin = + | Date + | Function + | Uint8Array + | string + | number + | boolean + | undefined; -export type DeepPartial = T extends Builtin ? T - : T extends globalThis.Array ? globalThis.Array> - : T extends ReadonlyArray ? ReadonlyArray> - : T extends {} ? { [K in keyof T]?: DeepPartial } +export type DeepPartial = T extends Builtin + ? T + : T extends globalThis.Array + ? globalThis.Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends {} + ? { [K in keyof T]?: DeepPartial } : Partial; type KeysOfUnion = T extends T ? keyof T : never; -export type Exact = P extends Builtin ? P - : P & { [K in keyof P]: Exact } & { [K in Exclude>]: never }; +export type Exact = P extends Builtin + ? P + : P & { [K in keyof P]: Exact } & { + [K in Exclude>]: 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; } diff --git a/back/protos/cron.ts b/back/protos/cron.ts index 947bcb73..a9b7f7d6 100644 --- a/back/protos/cron.ts +++ b/back/protos/cron.ts @@ -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 = { - 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 = { }, 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 = { create, I>>(base?: I): ISchedule { return ISchedule.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): ISchedule { + fromPartial, 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 = { - 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 = { }, 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 = { 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 = { 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 = { }, fromPartial, 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 = { - 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 = { }, 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 = { 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 = { return obj; }, - create, I>>(base?: I): AddCronRequest { + create, I>>( + base?: I, + ): AddCronRequest { return AddCronRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): AddCronRequest { + fromPartial, 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 = { - 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 = { return obj; }, - create, I>>(base?: I): AddCronResponse { + create, I>>( + base?: I, + ): AddCronResponse { return AddCronResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(_: I): AddCronResponse { + fromPartial, I>>( + _: I, + ): AddCronResponse { const message = createBaseAddCronResponse(); return message; }, @@ -439,7 +486,10 @@ function createBaseDeleteCronRequest(): DeleteCronRequest { } export const DeleteCronRequest: MessageFns = { - 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 = { }, 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 = { }, 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 = { return obj; }, - create, I>>(base?: I): DeleteCronRequest { + create, I>>( + base?: I, + ): DeleteCronRequest { return DeleteCronRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): DeleteCronRequest { + fromPartial, 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 = { - 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 = { return obj; }, - create, I>>(base?: I): DeleteCronResponse { + create, I>>( + base?: I, + ): DeleteCronResponse { return DeleteCronResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(_: I): DeleteCronResponse { + fromPartial, I>>( + _: I, + ): DeleteCronResponse { const message = createBaseDeleteCronResponse(); return message; }, @@ -540,15 +610,22 @@ function createBaseSetConcurrencyRequest(): SetConcurrencyRequest { } export const SetConcurrencyRequest: MessageFns = { - 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 = { }, 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 = { return obj; }, - create, I>>(base?: I): SetConcurrencyRequest { + create, I>>( + base?: I, + ): SetConcurrencyRequest { return SetConcurrencyRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): SetConcurrencyRequest { + fromPartial, I>>( + object: I, + ): SetConcurrencyRequest { const message = createBaseSetConcurrencyRequest(); message.concurrency = object.concurrency ?? 0; return message; @@ -596,30 +681,36 @@ export const SetConcurrencyRequest: MessageFns = { 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, - 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): CronClient; +export const CronClient = makeGenericClientConstructor( + CronService, + 'com.ql.cron.Cron', +) as unknown as { + new ( + address: string, + credentials: ChannelCredentials, + options?: Partial, + ): 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 extends Builtin ? T - : T extends globalThis.Array ? globalThis.Array> - : T extends ReadonlyArray ? ReadonlyArray> - : T extends {} ? { [K in keyof T]?: DeepPartial } +export type DeepPartial = T extends Builtin + ? T + : T extends globalThis.Array + ? globalThis.Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends {} + ? { [K in keyof T]?: DeepPartial } : Partial; type KeysOfUnion = T extends T ? keyof T : never; -export type Exact = P extends Builtin ? P - : P & { [K in keyof P]: Exact } & { [K in Exclude>]: never }; +export type Exact = P extends Builtin + ? P + : P & { [K in keyof P]: Exact } & { + [K in Exclude>]: 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; } diff --git a/back/protos/health.ts b/back/protos/health.ts index adaf9761..de34dc23 100644 --- a/back/protos/health.ts +++ b/back/protos/health.ts @@ -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 = { - 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 = { }, 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>>(base?: I): HealthCheckRequest { + create, I>>( + base?: I, + ): HealthCheckRequest { return HealthCheckRequest.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): HealthCheckRequest { + fromPartial, 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 = { - 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 = { }, 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 = { return obj; }, - create, I>>(base?: I): HealthCheckResponse { + create, I>>( + base?: I, + ): HealthCheckResponse { return HealthCheckResponse.fromPartial(base ?? ({} as any)); }, - fromPartial, I>>(object: I): HealthCheckResponse { + fromPartial, I>>( + object: I, + ): HealthCheckResponse { const message = createBaseHealthCheckResponse(); message.status = object.status ?? 0; return message; @@ -195,21 +227,25 @@ export const HealthCheckResponse: MessageFns = { 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, - callback: (error: ServiceError | null, response: HealthCheckResponse) => void, + callback: ( + error: ServiceError | null, + response: HealthCheckResponse, + ) => void, ): ClientUnaryCall; - watch(request: HealthCheckRequest, options?: Partial): ClientReadableStream; + watch( + request: HealthCheckRequest, + options?: Partial, + ): ClientReadableStream; watch( request: HealthCheckRequest, metadata?: Metadata, @@ -243,23 +291,44 @@ export interface HealthClient extends Client { ): ClientReadableStream; } -export const HealthClient = makeGenericClientConstructor(HealthService, "com.ql.health.Health") as unknown as { - new (address: string, credentials: ChannelCredentials, options?: Partial): HealthClient; +export const HealthClient = makeGenericClientConstructor( + HealthService, + 'com.ql.health.Health', +) as unknown as { + new ( + address: string, + credentials: ChannelCredentials, + options?: Partial, + ): 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 extends Builtin ? T - : T extends globalThis.Array ? globalThis.Array> - : T extends ReadonlyArray ? ReadonlyArray> - : T extends {} ? { [K in keyof T]?: DeepPartial } +export type DeepPartial = T extends Builtin + ? T + : T extends globalThis.Array + ? globalThis.Array> + : T extends ReadonlyArray + ? ReadonlyArray> + : T extends {} + ? { [K in keyof T]?: DeepPartial } : Partial; type KeysOfUnion = T extends T ? keyof T : never; -export type Exact = P extends Builtin ? P - : P & { [K in keyof P]: Exact } & { [K in Exclude>]: never }; +export type Exact = P extends Builtin + ? P + : P & { [K in keyof P]: Exact } & { + [K in Exclude>]: never; + }; function isSet(value: any): boolean { return value !== null && value !== undefined; diff --git a/back/schedule/addCron.ts b/back/schedule/addCron.ts index 74689a9a..3a95a0a3 100644 --- a/back/schedule/addCron.ts +++ b/back/schedule/addCron.ts @@ -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)[] = []; 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, - { - name: `${item.id}: ${item.name || ''}`, - logger: Logger, - start: false, - }, - ), + createCronJob(schedule, fire, { + name: `${item.id}: ${item.name || ''}`, + logger: Logger, + start: false, + }), ); } } @@ -134,13 +153,17 @@ 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()); - callback(error); - }); + savePlan() + .then(activate) + .catch((error) => { + for (const jobs of prepared.values()) + jobs.forEach((job) => job.cancel()); + callback(error); + }); } else activate(); }; diff --git a/back/schedule/client.ts b/back/schedule/client.ts index a796ca1e..ece03466 100644 --- a/back/schedule/client.ts +++ b/back/schedule/client.ts @@ -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((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 { 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 { + async delCron( + request: DeleteCronRequest['ids'], + ): Promise { await this.waitForReady(2000); return new Promise((resolve, reject) => { - 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) { - this.readiness.invalidate(); - Object.assign(err, { status: 503 }); + 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 + ) { + this.readiness.invalidate(); + Object.assign(err, { status: 503 }); + } + return reject(err); } - return reject(err); - } - resolve(res); - }); + resolve(res); + }, + ); }); } } diff --git a/back/schedule/data.ts b/back/schedule/data.ts index 94969b81..44f4910c 100644 --- a/back/schedule/data.ts +++ b/back/schedule/data.ts @@ -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(); diff --git a/back/schedule/registeredPlans.ts b/back/schedule/registeredPlans.ts index a1bda2ae..9907a920 100644 --- a/back/schedule/registeredPlans.ts +++ b/back/schedule/registeredPlans.ts @@ -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. diff --git a/back/schedule/setConcurrency.ts b/back/schedule/setConcurrency.ts index 20fb1876..25e9dc22 100644 --- a/back/schedule/setConcurrency.ts +++ b/back/schedule/setConcurrency.ts @@ -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, diff --git a/back/services/cron.ts b/back/services/cron.ts index 13fb305d..aa619e72 100644 --- a/back/services/cron.ts +++ b/back/services/cron.ts @@ -1,99 +1,82 @@ -import { confirmSystemPlan, stageSystemPlan, suspendSystemPlan, SystemRule } from '../shared/systemScheduleAudit'; -import { cronOperand } from '../shared/cronOperand'; +import { CronExecution } from '../cron/execution/cronExecution'; +import { + isNodeCron, + schedulerMode, + shouldUseCronClient, + isOnceSchedule, + isBootSchedule, + isSpecialSchedule, + makeCommand, + nodeCron, +} from '../cron/scheduling/cronScheduling'; +import { SystemCronAdapter } from '../cron/scheduling/systemCron'; +import { cronOperand } from '../cron/execution/cronOperand'; import { PendingCronInstall } from '../shared/errors'; -import { shellQuote } from '../shared/shellQuote'; -import { finishStoppedTree, hasLiveCronProcess, pidNamespaceOwner, systemOwner, verifyCronProcess } from '../shared/cronProcess'; -import { TriggerHistory, TriggerState } from '../shared/triggerHistory'; -import { randomUUID } from 'crypto'; -import { getInvalidCronSchedules, isValidCronSchedule } from '../shared/cronSchedule'; +import { TriggerHistory } from '../cron/history'; +import { + getInvalidCronSchedules, + isValidCronSchedule, +} from '../cron/scheduling/cronSchedule'; import { withSchedulerMutation, schedulerRegistrationError, -} from '../shared/schedulerMutationLock'; +} from '../cron/scheduling/schedulerMutationLock'; import { Service, Inject } from 'typedi'; import winston from 'winston'; import config from '../config'; import { resolveLogPath } from '../shared/logPath'; import { Crontab, CrontabModel, CrontabStatus } from '../data/cron'; -import { - RunningInstanceModel, - InstanceStatus, -} from '../data/runningInstance'; -import { exec, execSync, execFileSync } from 'child_process'; +import { exec } from 'child_process'; import fs from 'fs/promises'; import { getFileContentByName, - fileExist, - killTask, getUniqPath, safeJSONParse, isDemoEnv, } from '../config/util'; -import { Op, where, col as colFn, literal, FindOptions, fn, Order, QueryTypes, Transaction } from 'sequelize'; +import { + Op, + where, + col as colFn, + literal, + FindOptions, + fn, + Order, +} from 'sequelize'; import path from 'path'; -import { TASK_PREFIX, QL_PREFIX } from '../config/const'; import cronClient from '../schedule/client'; -import taskLimit from '../shared/pLimit'; import dayjs from 'dayjs'; import pickBy from 'lodash/pickBy'; import { writeFileWithLock } from '../shared/utils'; import { t } from '../shared/i18n'; -import { ScheduleType } from '../interface/schedule'; -import { logStreamManager } from '../shared/logStreamManager'; -import { spawnCronCommand, releaseCronCommand } from '../shared/cronCommandProcess'; -import { observeChildProcess, asError } from '../shared/childProcess'; +import { asError } from '../shared/childProcess'; import { isEmpty } from 'lodash'; -import { LogReadOptions, readLogChunk } from '../shared/logReader'; -import { resolveFileAccess } from '../shared/fileAccess'; +import { + CronLogReader, + CronLogOptions, + CronLogResult, +} from '../cron/queries/cronLog'; +import { visibleStatus, visibleAttributes } from '../cron/queries/cronViews'; -type BatchStopSnapshot = { - docs: Array>; - instances: Array<{ id?: number; cron_id: number; pid?: number }>; - cancelled: string[]; - missingPids?: number[]; - missingTargets?: string[]; - identityConflict: boolean; -}; - -// Queue membership belongs to the trigger. Expose it for list/detail reads -// without writing it into the manual-run reservation used by the scheduler. -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`); -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`; -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'], -]; - -function shellValue(value: string) { - return /^[a-zA-Z0-9_./-]+$/.test(value) ? value : shellQuote(value); -} - -function statusFilter(values: CrontabStatus[], exclude: boolean, forDisplay: boolean) { +function statusFilter( + values: CrontabStatus[], + exclude: boolean, + forDisplay: boolean, +) { const column = forDisplay ? visibleStatus : colFn('status'); const disabled = values.includes(CrontabStatus.disabled); if (exclude) { - return { [Op.and]: [ - { [Op.or]: [where(column, { [Op.notIn]: values }), where(column, { [Op.is]: null })] }, - ...(disabled ? [{ isDisabled: { [Op.ne]: 1 } }] : []), - ] }; + return { + [Op.and]: [ + { + [Op.or]: [ + where(column, { [Op.notIn]: values }), + where(column, { [Op.is]: null }), + ], + }, + ...(disabled ? [{ isDisabled: { [Op.ne]: 1 } }] : []), + ], + }; } const matches = where(column, { [Op.in]: values }); return disabled @@ -103,57 +86,40 @@ function statusFilter(values: CrontabStatus[], exclude: boolean, forDisplay: boo @Service() export default class CronService { - constructor(@Inject('logger') private logger: winston.Logger) { } + constructor(@Inject('logger') private logger: winston.Logger) {} + + // One coordinator per service preserves in-flight stop deduplication. Late-bound + // callbacks keep existing service overrides and execution entry points intact. + private readonly execution: CronExecution = new CronExecution(this.logger, { + getDb: (query) => this.getDb(query), + makeCommand: (tab, realTime) => this.makeCommand(tab, realTime), + runSingle: (...args) => this.runSingle(...args), + stopInstance: (cronId, instanceId) => this.stopInstance(cronId, instanceId), + stop: (ids, requestId) => this.stop(ids, requestId), + }); private 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] !== '*') - ); + return isNodeCron(cron); } private get schedulerMode(): 'system' | 'node' { - 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'; - } + return schedulerMode(); } private shouldUseCronClient(cron: Crontab): boolean { - if (this.schedulerMode === 'node') { - return !this.isSpecialSchedule(cron.schedule); - } - return this.isNodeCron(cron) && !this.isSpecialSchedule(cron.schedule); + return shouldUseCronClient(cron, this.schedulerMode); } private isOnceSchedule(schedule?: string) { - return schedule?.startsWith(ScheduleType.ONCE); + return isOnceSchedule(schedule); } private isBootSchedule(schedule?: string) { - return schedule?.startsWith(ScheduleType.BOOT); + return isBootSchedule(schedule); } private isSpecialSchedule(schedule?: string) { - return this.isOnceSchedule(schedule) || this.isBootSchedule(schedule); + return isSpecialSchedule(schedule); } private async getLogName(cron: Crontab) { @@ -161,7 +127,7 @@ export default class CronService { if (log_name === '/dev/null') { return log_name; } - const candidate = log_name || await getUniqPath(command, `${id}`); + const candidate = log_name || (await getUniqPath(command, `${id}`)); const logDirPath = resolveLogPath(config.logPath, candidate); await fs.mkdir(logDirPath, { recursive: true }); // Shell joins the returned value to dir_log. Normalize old absolute names once. @@ -182,19 +148,7 @@ export default class CronService { if (this.shouldUseCronClient(doc)) { try { - await cronClient.addCron([ - { - name: doc.name || '', - id: String(doc.id), - schedule: doc.schedule!, - command: this.makeCommand(doc), - 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, - }, - ]); + await cronClient.addCron([nodeCron(doc, this.makeCommand(doc))]); } catch (error: any) { // gRPC 注册失败时回滚 DB 记录,避免产生"僵尸任务" // (DB 和 crontab.list 有记录但调度器永远不会执行) @@ -204,7 +158,9 @@ export default class CronService { error?.message || error, ); throw schedulerRegistrationError( - `${t('调度器注册失败,任务创建已回滚')}: ${(error as any)?.details || error?.message}`, + `${t('调度器注册失败,任务创建已回滚')}: ${ + (error as any)?.details || error?.message + }`, error, ); } @@ -232,7 +188,10 @@ export default class CronService { const doc = await this.getDb({ id: payload.id }); const tab = new Crontab({ ...doc, ...payload }); tab.saved = false; - tab.recovery_from = Math.max(Date.now(), Number(doc.recovery_from || 0) + 1); + tab.recovery_from = Math.max( + Date.now(), + Number(doc.recovery_from || 0) + 1, + ); tab.log_name = await this.getLogName(tab); if (isDemoEnv()) { tab.saved = doc.saved; @@ -246,34 +205,42 @@ export default class CronService { return updated; } - const register = (row: Crontab) => cronClient.addCron([{ - name: row.name || '', id: String(row.id), schedule: row.schedule!, - command: this.makeCommand(row), extra_schedules: row.extra_schedules || [], - max_queue_wait: row.max_queue_wait, skip_if_pending: Boolean(row.skip_if_pending), - catchup_seconds: row.catchup_seconds, recovery_from: row.recovery_from, - }]); + const register = (row: Crontab) => + cronClient.addCron([nodeCron(row, this.makeCommand(row))]); const restoreTimer = async () => { if (!this.shouldUseCronClient(doc)) return; - try { await register(doc); } - catch (error) { + try { + await register(doc); + } catch (error) { cronClient.readiness.invalidate(); - await CrontabModel.update({ saved: false }, { where: { id: doc.id } }); - throw Object.assign(new Error(t('原调度未能恢复,正在重试'), { cause: error }), { status: 503 }); + await CrontabModel.update( + { saved: false }, + { where: { id: doc.id } }, + ); + throw Object.assign( + new Error(t('原调度未能恢复,正在重试'), { cause: error }), + { status: 503 }, + ); } }; // addCron stages and atomically replaces a Node timer. Never tear down the // old timer for a Node-to-Node edit that the database may still reject. - const handOff = this.shouldUseCronClient(doc) && !this.shouldUseCronClient(tab); + const handOff = + this.shouldUseCronClient(doc) && !this.shouldUseCronClient(tab); if (handOff) await cronClient.delCron([String(doc.id)]); let newDoc: Crontab; - try { newDoc = await this.updateDb(tab); } - catch (error) { + try { + newDoc = await this.updateDb(tab); + } catch (error) { if (handOff) await restoreTimer(); throw error; } const useNode = this.shouldUseCronClient(newDoc); - const movingFromSystem = useNode && !this.shouldUseCronClient(doc) && !this.isSpecialSchedule(doc.schedule); + const movingFromSystem = + useNode && + !this.shouldUseCronClient(doc) && + !this.isSpecialSchedule(doc.schedule); // Remove the previous system entry before the new Node timer can fire. if (movingFromSystem) await this.setCrontab(); if (useNode) { @@ -284,7 +251,10 @@ export default class CronService { await this.updateDb(doc); await restoreTimer(); if (movingFromSystem) { - await CrontabModel.update({ saved: false }, { where: { id: doc.id } }); + await CrontabModel.update( + { saved: false }, + { where: { id: doc.id } }, + ); await this.setCrontab(undefined, [doc.id!]); } this.logger.error( @@ -292,13 +262,16 @@ export default class CronService { error?.message || error, ); throw schedulerRegistrationError( - `${t('调度器注册失败,任务更新已回滚')}: ${(error as any)?.details || error?.message}`, + `${t('调度器注册失败,任务更新已回滚')}: ${ + (error as any)?.details || error?.message + }`, error, ); } } - if (movingFromSystem) await CrontabModel.update({ saved: true }, { where: { id: doc.id } }); + if (movingFromSystem) + await CrontabModel.update({ saved: true }, { where: { id: doc.id } }); else await this.setCrontab(undefined, [doc.id!]); newDoc.saved = true; return newDoc; @@ -309,9 +282,25 @@ export default class CronService { // A concurrent dispatch owns the runtime fields, including during rollback. await CrontabModel.update(payload, { where: { id: payload.id }, - fields: ['name', 'command', 'schedule', 'timestamp', 'saved', 'labels', 'sub_id', - 'extra_schedules', 'task_before', 'task_after', 'log_name', 'work_dir', - 'allow_multiple_instances', 'skip_if_pending', 'max_queue_wait', 'catchup_seconds', 'recovery_from'], + fields: [ + 'name', + 'command', + 'schedule', + 'timestamp', + 'saved', + 'labels', + 'sub_id', + 'extra_schedules', + 'task_before', + 'task_after', + 'log_name', + 'work_dir', + 'allow_multiple_instances', + 'skip_if_pending', + 'max_queue_wait', + 'catchup_seconds', + 'recovery_from', + ], }); return await this.getDb({ id: payload.id }); } @@ -353,18 +342,42 @@ export default class CronService { } for (const id of ids) { - if (!await CrontabModel.findByPk(id, { attributes: ['id'] })) continue; - if (trigger_id && [CrontabStatus.running, CrontabStatus.idle].includes(status)) { - await new TriggerHistory(CrontabModel.sequelize!).reportInstance(trigger_id, id, - status === CrontabStatus.running, pid, log_path, last_execution_time, - last_running_time, exit_code, trigger_stopped, finished_at); + if (!(await CrontabModel.findByPk(id, { attributes: ['id'] }))) continue; + if ( + trigger_id && + [CrontabStatus.running, CrontabStatus.idle].includes(status) + ) { + await new TriggerHistory(CrontabModel.sequelize!).reportInstance( + trigger_id, + id, + status === CrontabStatus.running, + pid, + log_path, + last_execution_time, + last_running_time, + exit_code, + trigger_stopped, + finished_at, + ); continue; } if (status === CrontabStatus.running || status === CrontabStatus.idle) { - if (Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(last_execution_time) && last_execution_time > 0) { - await new TriggerHistory(CrontabModel.sequelize!).reportLegacy(id, status === CrontabStatus.running, - pid, log_path, last_execution_time, last_running_time ?? 0, exit_code); + if ( + Number.isSafeInteger(pid) && + pid > 0 && + Number.isSafeInteger(last_execution_time) && + last_execution_time > 0 + ) { + await new TriggerHistory(CrontabModel.sequelize!).reportLegacy( + id, + status === CrontabStatus.running, + pid, + log_path, + last_execution_time, + last_running_time ?? 0, + exit_code, + ); } continue; } @@ -376,17 +389,38 @@ export default class CronService { } } - public async remove(targets: (number | { id: number; script: string; command?: string; sub_id?: number | null; revision?: number })[]) { + public async remove( + targets: ( + | number + | { + id: number; + script: string; + command?: string; + sub_id?: number | null; + revision?: number; + } + )[], + ) { return withSchedulerMutation(async () => { - const ids = targets.map(target => typeof target === 'number' ? target : target.id); + const ids = targets.map((target) => + typeof target === 'number' ? target : target.id, + ); for (const target of targets) { if (typeof target === 'number') continue; const current = await CrontabModel.findByPk(target.id); - if (!current || cronOperand(current.command, true) !== target.script || - (target.command !== undefined && current.command !== target.command) || - (target.revision !== undefined && current.recovery_from !== target.revision) || - (target.sub_id !== undefined && (current.sub_id ?? null) !== target.sub_id)) { - throw Object.assign(new Error(t('任务已修改,请刷新后重试')), { status: 409 }); + if ( + !current || + cronOperand(current.command, true) !== target.script || + (target.command !== undefined && + current.command !== target.command) || + (target.revision !== undefined && + current.recovery_from !== target.revision) || + (target.sub_id !== undefined && + (current.sub_id ?? null) !== target.sub_id) + ) { + throw Object.assign(new Error(t('任务已修改,请刷新后重试')), { + status: 409, + }); } } await cronClient.delCron(ids.map(String)); @@ -438,8 +472,17 @@ export default class CronService { let q: any = {}; let operate2: any = null; let operate: any = null; - if (property === 'status' && (operation === 'In' || operation === 'Nin')) { - query[primaryOperate].push(statusFilter(Array.isArray(value) ? value : [value], operation === 'Nin', forDisplay)); + if ( + property === 'status' && + (operation === 'In' || operation === 'Nin') + ) { + query[primaryOperate].push( + statusFilter( + Array.isArray(value) ? value : [value], + operation === 'Nin', + forDisplay, + ), + ); continue; } switch (operation) { @@ -456,7 +499,11 @@ export default class CronService { break; case 'Nin': q[Op.or] = [ - { [property]: { [Op.notIn]: Array.isArray(value) ? value : [value] } }, + { + [property]: { + [Op.notIn]: Array.isArray(value) ? value : [value], + }, + }, { [property]: { [Op.is]: null } }, ]; break; @@ -573,14 +620,17 @@ export default class CronService { } } - public async crontabs(params?: { - searchValue: string; - page: string; - size: string; - sorter: string; - filters: string; - queryString: string; - }, forDisplay = false): Promise<{ data: Crontab[]; total: number }> { + public async crontabs( + params?: { + searchValue: string; + page: string; + size: string; + sorter: string; + filters: string; + queryString: string; + }, + forDisplay = false, + ): Promise<{ data: Crontab[]; total: number }> { const searchText = params?.searchValue; const page = Number(params?.page || '0'); const size = Number(params?.size || '0'); @@ -609,7 +659,12 @@ export default class CronService { } let condition: FindOptions = { where: query, - order: (forDisplay ? order.map(([field, dir]) => [field === 'status' ? visibleStatus : field, dir]) : order) as Order, + order: (forDisplay + ? order.map(([field, dir]) => [ + field === 'status' ? visibleStatus : field, + dir, + ]) + : order) as Order, ...(forDisplay ? { attributes: visibleAttributes } : {}), }; if (page && size) { @@ -630,7 +685,10 @@ export default class CronService { projection: boolean | FindOptions['attributes'] = false, ): Promise { const attributes = projection === true ? visibleAttributes : projection; - const doc: any = await CrontabModel.findOne({ where: { ...query }, ...(attributes && { attributes }) }); + const doc: any = await CrontabModel.findOne({ + where: { ...query }, + ...(attributes && { attributes }), + }); if (!doc) { throw new Error(`Cron ${JSON.stringify(query)} not found`); } @@ -638,321 +696,23 @@ export default class CronService { } public async run(ids: number[], source: 'manual' | 'boot' = 'manual') { - const token = randomUUID(); - const database = CrontabModel.sequelize!; - const history = new TriggerHistory(database); - const queued = await database.transaction(async (transaction) => { - const rows = await CrontabModel.findAll({ where: { id: ids }, transaction }); - const accepted: Crontab[] = []; - 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); - } else { - accepted.push(row.get({ plain: true })); - } - } - await CrontabModel.update({ status: CrontabStatus.queued, queued_token: token }, { - where: { id: accepted.map(row => row.id!) }, transaction, - }); - return accepted; - }); - for (const row of queued) { - const id = row.id!; - void this.runSingle(id, token, token + '-' + id, row).catch((err) => this.logger.error(String(err))); - } + return this.execution.run(ids, source); } - private readonly stoppingBatches = new Map>(); - 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; + return this.execution.stop(ids, requestId); } - 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 => { - 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.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 }); + public async resumePendingStops( + history: TriggerHistory, + requests: Awaited>, + batches: Awaited> = [], + ) { + return this.execution.resumePendingStops(history, requests, batches); } - // Older databases can have a PID or a command receipt without an instance. - // Give verified targets an instance before releasing the same 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(); - 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>, - batches: Awaited> = []) { - for (const row of requests) { - try { - const result = await this.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.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>(); - 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) => { - 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; + return this.execution.stopInstance(cronId, instanceId); } private async runSingle( @@ -961,204 +721,35 @@ export default class CronService { triggerId?: string, submitted?: Crontab, ): Promise { - 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.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.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); + return this.execution.runSingle( + cronId, + expectedToken, + triggerId, + submitted, + ); } public async disabled(ids: number[]) { return withSchedulerMutation(async () => { await cronClient.delCron(ids.map(String)); - await CrontabModel.update({ isDisabled: 1, saved: false }, { where: { id: ids } }); + await CrontabModel.update( + { isDisabled: 1, saved: false }, + { where: { id: ids } }, + ); await this.setCrontab(undefined, ids); }); } public async enabled(ids: number[]) { return withSchedulerMutation(async () => { - await CrontabModel.update({ isDisabled: 0, recovery_from: Date.now() }, { where: { id: ids } }); + await CrontabModel.update( + { isDisabled: 0, recovery_from: Date.now() }, + { where: { id: ids } }, + ); const docs = await CrontabModel.findAll({ where: { id: ids } }); const crons = docs .filter((x) => this.shouldUseCronClient(x)) - .map((doc) => ({ - name: doc.name || '', - id: String(doc.id), - schedule: doc.schedule!, - command: this.makeCommand(doc), - 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, - })); + .map((doc) => nodeCron(doc, this.makeCommand(doc))); if (isDemoEnv()) { return; @@ -1174,7 +765,9 @@ export default class CronService { error?.message || error, ); throw schedulerRegistrationError( - `${t('调度器注册失败,任务启用已回滚')}: ${(error as any)?.details || error?.message}`, + `${t('调度器注册失败,任务启用已回滚')}: ${ + (error as any)?.details || error?.message + }`, error, ); } @@ -1185,199 +778,43 @@ export default class CronService { public async log( id: number, - options: LogReadOptions & { previousPath?: string; triggerId?: string; instanceId?: number } = {}, - ): Promise<{ - content: string; - status: string; - logPath?: string; - triggerId?: string; - cursor?: string; - reset?: boolean; - offset: number; - nextOffset: number; - total: number; - truncated: boolean; - }> { - let doc: Pick & { 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 TriggerHistory(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.getDb({ 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, - }; - } + options: CronLogOptions = {}, + ): Promise { + return new CronLogReader((cronId, attributes) => + this.getDb({ id: cronId }, attributes), + ).log(id, options); } public async logs(id: number) { - const doc = await this.getDb({ 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 []; - } + return new CronLogReader((cronId, attributes) => + this.getDb({ id: cronId }, attributes), + ).logs(id); } private 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; + return makeCommand(tab, realTime); } - private async setCrontab(data?: { data: Crontab[]; total: number }, appliedIds: number[] = []) { + private async setCrontab( + data?: { data: Crontab[]; total: number }, + appliedIds: number[] = [], + ) { const tabs = data ?? (await this.crontabs()); - const rules: SystemRule[] = []; - var crontab_string = ''; - tabs.data.forEach((tab) => { - if ( - tab.isDisabled === 1 || - this.isNodeCron(tab) || - this.isSpecialSchedule(tab.schedule) - ) { - crontab_string += '# '; - crontab_string += tab.schedule; - crontab_string += ' '; - crontab_string += this.makeCommand(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(this.makeCommand(tab))}`; - crontab_string += '\n'; - } - }); - - try { - const system = this.schedulerMode === '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 (this.schedulerMode === 'system') { - const ids = tabs.data - .filter((row) => !this.isNodeCron(row) && !this.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 }); - } + await new SystemCronAdapter(this.logger).publish( + tabs.data, + () => this.schedulerMode, + (tab) => this.makeCommand(tab), + ); // Only these registrations were acknowledged by this mutation. An unrelated // file install cannot confirm a pending Node registration. if (appliedIds.length) await this.markSchedulesSaved(appliedIds); } private async markSchedulesSaved(ids: number[]) { - await CrontabModel.update({ saved: true }, { where: { id: ids, saved: false } }); + await CrontabModel.update( + { saved: true }, + { where: { id: ids, saved: false } }, + ); } public importCrontab() { @@ -1397,11 +834,7 @@ export default class CronService { const command = line.replace(regex, '').trim(); const schedule = line.replace(command, '').trim(); - if ( - command && - schedule && - isValidCronSchedule(schedule) - ) { + if (command && schedule && isValidCronSchedule(schedule)) { const name = namePrefix + '_' + index; const _crontab = await CrontabModel.findOne({ @@ -1437,22 +870,8 @@ export default class CronService { return false; }); const regularCrons = tabs.data - .filter( - (x) => - x.isDisabled !== 1 && - this.shouldUseCronClient(x), - ) - .map((doc) => ({ - name: doc.name || '', - id: String(doc.id), - schedule: doc.schedule!, - command: this.makeCommand(doc), - 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, - })); + .filter((x) => x.isDisabled !== 1 && this.shouldUseCronClient(x)) + .map((doc) => nodeCron(doc, this.makeCommand(doc))); if (isDemoEnv()) { await writeFileWithLock(config.crontabFile, ''); @@ -1482,7 +901,10 @@ export default class CronService { (x) => !x.isDisabled && this.isBootSchedule(x.schedule), ); if (bootTasks.length > 0) { - await this.run(bootTasks.map((task) => task.id!), 'boot'); + await this.run( + bootTasks.map((task) => task.id!), + 'boot', + ); } } } diff --git a/back/services/env.ts b/back/services/env.ts index 49708e56..51a3589a 100644 --- a/back/services/env.ts +++ b/back/services/env.ts @@ -21,7 +21,7 @@ import { @Service() export default class EnvService { - constructor(@Inject('logger') private logger: winston.Logger) { } + constructor(@Inject('logger') private logger: winston.Logger) {} public async create(payloads: Env[]): Promise { payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name)); @@ -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('&')), diff --git a/back/services/grpc.ts b/back/services/grpc.ts index 9aa37055..01fc6a49 100644 --- a/back/services/grpc.ts +++ b/back/services/grpc.ts @@ -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, + ); } } diff --git a/back/services/http.ts b/back/services/http.ts index 44ee30ee..5ff268f5 100644 --- a/back/services/http.ts +++ b/back/services/http.ts @@ -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 { + private async tryListen( + expressApp: express.Application, + port: number, + host: string, + ): Promise { 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({ - port, - host, - exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true', - }, () => { - resolve(server); - }); + const server = expressApp.listen( + { + port, + host, + exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true', + }, + () => { + resolve(server); + }, + ); server.on('error', (err: Error) => { server.close(); diff --git a/back/services/log.ts b/back/services/log.ts index 2434cdd7..73b7f966 100644 --- a/back/services/log.ts +++ b/back/services/log.ts @@ -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'], + ); } } diff --git a/back/services/notify.ts b/back/services/notify.ts index 2e9426b9..987c2a6d 100644 --- a/back/services/notify.ts +++ b/back/services/notify.ts @@ -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; diff --git a/back/services/retention.ts b/back/services/retention.ts index bf141c22..5f222653 100644 --- a/back/services/retention.ts +++ b/back/services/retention.ts @@ -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,34 +77,38 @@ 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([ - policy.runningInstanceRetentionDays > 0 - ? RunningInstanceModel.count({ - where: runningInstanceWhere(cutoffs.history), - }) - : 0, - policy.cronStatRetentionDays > 0 - ? CrontabStatModel.count({ - where: { date: { [Op.lt]: cutoffs.firstDay } }, - }) - : 0, - Promise.all( - dependenceCacheTypes.map(async (type) => ({ - type, - bytes: await getDirectorySize( - path.join(config.dependenceCachePath, type), - ), - })), - ), - policy.runningInstanceRetentionDays > 0 - ? new TriggerHistory(sequelize).countExpired(cutoffs.history) - : 0, - ]); + const [runningInstances, cronStats, dependenceCaches, triggers] = + await Promise.all([ + policy.runningInstanceRetentionDays > 0 + ? RunningInstanceModel.count({ + where: runningInstanceWhere(cutoffs.history), + }) + : 0, + policy.cronStatRetentionDays > 0 + ? CrontabStatModel.count({ + where: { date: { [Op.lt]: cutoffs.firstDay } }, + }) + : 0, + Promise.all( + dependenceCacheTypes.map(async (type) => ({ + type, + bytes: await getDirectorySize( + path.join(config.dependenceCachePath, type), + ), + })), + ), + policy.runningInstanceRetentionDays > 0 + ? new TriggerHistory(sequelize).countExpired(cutoffs.history) + : 0, + ]); return { policy, @@ -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 - ? await history.deleteExpired(cutoffs.history, transaction) - : 0; - if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) { + const triggers = + preview.policy.runningInstanceRetentionDays > 0 + ? await history.deleteExpired(cutoffs.history, transaction) + : 0; + 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 }; }); diff --git a/back/services/schedule.ts b/back/services/schedule.ts index a303fbe5..698c2323 100644 --- a/back/services/schedule.ts +++ b/back/services/schedule.ts @@ -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, diff --git a/back/services/script.ts b/back/services/script.ts index 5caa6116..338e5076 100644 --- a/back/services/script.ts +++ b/back/services/script.ts @@ -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 { diff --git a/back/services/sock.ts b/back/services/sock.ts index b09a43bb..60e78929 100644 --- a/back/services/sock.ts +++ b/back/services/sock.ts @@ -7,7 +7,7 @@ import { SockMessage } from '../data/sock'; export default class SockService { private clients: Connection[] = []; - constructor(@Inject('logger') private logger: winston.Logger) { } + constructor(@Inject('logger') private logger: winston.Logger) {} public getClients() { return this.clients; diff --git a/back/services/subscription.ts b/back/services/subscription.ts index 225b5b24..b2474eeb 100644 --- a/back/services/subscription.ts +++ b/back/services/subscription.ts @@ -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,10 +373,11 @@ 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) => - retained === storagePath || - retained.startsWith(`${storagePath}${path.sep}`) || - storagePath.startsWith(`${retained}${path.sep}`), + const shared = retainedPaths.some( + (retained) => + retained === storagePath || + retained.startsWith(`${storagePath}${path.sep}`) || + storagePath.startsWith(`${retained}${path.sep}`), ); if (!shared) await rmPath(storagePath); } diff --git a/back/services/system.ts b/back/services/system.ts index 35a71210..04e3b27b 100644 --- a/back/services/system.ts +++ b/back/services/system.ts @@ -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'; diff --git a/back/shared/containerResources.ts b/back/shared/containerResources.ts index 4564a303..771c5d30 100644 --- a/back/shared/containerResources.ts +++ b/back/shared/containerResources.ts @@ -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), + }; } diff --git a/back/shared/cronCommandProcess.ts b/back/shared/cronCommandProcess.ts deleted file mode 100644 index 0e837ad0..00000000 --- a/back/shared/cronCommandProcess.ts +++ /dev/null @@ -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 { - return new Promise((resolve, reject) => - child.stdin.end('run\n', (error?: Error) => error ? reject(error) : resolve())); -} diff --git a/back/shared/directoryPage.ts b/back/shared/directoryPage.ts index c4283ebf..354a8107 100644 --- a/back/shared/directoryPage.ts +++ b/back/shared/directoryPage.ts @@ -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]) => { - try { - 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; - } - })); + const matches = await Promise.all( + versions.map(async ([parent, expected]) => { + try { + 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) => - Number(b.isDirectory()) - Number(a.isDirectory()) || - compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1)); - const selected = sorted.filter(e => { + 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) => { 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 }; } diff --git a/back/shared/directoryPageRoute.ts b/back/shared/directoryPageRoute.ts index 838f8c98..e93ca312 100644 --- a/back/shared/directoryPageRoute.ts +++ b/back/shared/directoryPageRoute.ts @@ -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); + } }, ]; } diff --git a/back/shared/fileAccess.ts b/back/shared/fileAccess.ts index 43678482..5c67e80b 100644 --- a/back/shared/fileAccess.ts +++ b/back/shared/fileAccess.ts @@ -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); diff --git a/back/shared/i18n.ts b/back/shared/i18n.ts index dcb0c065..a0de9978 100644 --- a/back/shared/i18n.ts +++ b/back/shared/i18n.ts @@ -1,8 +1,9 @@ const messages: Record> = { 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> = { '执行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', diff --git a/back/shared/logReader.ts b/back/shared/logReader.ts index 4a4f33e4..664a29fb 100644 --- a/back/shared/logReader.ts +++ b/back/shared/logReader.ts @@ -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 - ? Math.max(total - limit, 0) - : Math.min(requestedOffset, total); - const resume = options.cursor && !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 [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 { diff --git a/back/shared/managedExit.cjs b/back/shared/managedExit.cjs index 99a39492..f2f817dd 100644 --- a/back/shared/managedExit.cjs +++ b/back/shared/managedExit.cjs @@ -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 => { - 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()); + 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()); } diff --git a/back/shared/pLimit.ts b/back/shared/pLimit.ts index f750fc0b..1e5f4204 100644 --- a/back/shared/pLimit.ts +++ b/back/shared/pLimit.ts @@ -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([]); - private queuedCrons = new Map[]>(); - private repeatCronNotifyMap = new Map(); 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({ - 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) { - 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( - cron: TCron, - fn: ICronFn, - options?: Partial, - isCurrent: () => boolean = () => true, - onPending?: () => void, - waitingSignal?: EventEmitter, - triggerId?: string, - db?: Sequelize, - ): Promise { - 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((resolve, reject) => { - this.cronLimit.add(run, { ...options, waitingSignal, onRemoved: () => { this.scheduledOccupants.forget(triggerId); resolve(); } }).then(resolve, reject); - }); - } - - private trackAdmission(pool: QueueOccupants, limit: number, fn: () => Promise, 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( - fn: () => Promise, - options?: Partial, - occupant: { id?: string; name: string } = { name: '—' }, - db?: Sequelize, - ): Promise { - return this.manualCronoLimit.add(this.trackAdmission(this.manualOccupants, this.manualCronoLimit.concurrency, fn, occupant, db), options); - } - public async runWithSubscriptionLimit( schedule: TCron, fn: IScheduleFn, diff --git a/back/shared/runtimeBuild.ts b/back/shared/runtimeBuild.ts index 9e20be9c..0d51880e 100644 --- a/back/shared/runtimeBuild.ts +++ b/back/shared/runtimeBuild.ts @@ -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(), diff --git a/back/shared/startupTiming.ts b/back/shared/startupTiming.ts index 8f6bd323..1cf04edf 100644 --- a/back/shared/startupTiming.ts +++ b/back/shared/startupTiming.ts @@ -1,13 +1,20 @@ import Logger from '../loaders/logger'; import { performance } from 'perf_hooks'; -export async function startupStage(name: string, operation: () => Promise): Promise { +export async function startupStage( + name: string, + operation: () => Promise, +): Promise { 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})`, + ); } } diff --git a/back/shared/taskEnvName.ts b/back/shared/taskEnvName.ts index 10e9ecef..e389227e 100644 --- a/back/shared/taskEnvName.ts +++ b/back/shared/taskEnvName.ts @@ -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, diff --git a/back/shared/triggerHistory.ts b/back/shared/triggerHistory.ts deleted file mode 100644 index c8a39c12..00000000 --- a/back/shared/triggerHistory.ts +++ /dev/null @@ -1,1563 +0,0 @@ -import { isLegacyCapture, isMetadataReceipt, publishedExits, publishedScriptStarts, readExit, receiptPath, retireLegacyFile, retiringExits, validExit } from './managedExit.cjs'; -import { executionIdPattern } from './executionIdentity'; -import type { Crontab } from '../data/cron'; -import { hasLiveCronProcess, isProcessDescendant, legacyProcessOwner, pidNamespaceOwner, systemOwner } from './cronProcess'; -export { systemOwner } from './cronProcess'; -import { QueryTypes, Sequelize, Transaction } from 'sequelize'; -import dayjs from 'dayjs'; -import { addDailyExit, recordCronResult } from './cronStatistics'; -import { promises as fs } from 'fs'; -import { basename, join } from 'path'; -import { createHash } from 'crypto'; -import { systemScheduleAudit } from './systemScheduleAudit'; -import { auditSchedule } from './scheduleAudit'; - -export type TriggerSource = 'node' | 'manual' | 'boot' | 'system' | 'recovery' | 'legacy' | 'client'; -export type TriggerState = - | 'queued' - | 'running' - | 'finished' - | 'failed' - | 'skipped' - | 'stopped' - | 'unknown'; -type VerifiedSupervisorExit = { code: number | null; signal: string | null; time: number; version: 1 }; -type ExitObservation = Omit; -type LegacyExitBooking = { - trigger_id: string; cron_id: number; source: TriggerSource; started_at: number; finished_at: number; outcome: string; - stopped: number; stat_id: number | null; disputed: number; bound: number; -}; - -function observationKey(id: string, exit: ExitObservation) { - return { id, outcome: exit.signal ?? String(exit.code), time: exit.time }; -} - -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; -}; - -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`; - -export function slotId( - task: string, - ruleIndex: number, - rule: string, - time: number, -) { - return createHash('sha256') - .update(JSON.stringify([task, ruleIndex, rule, time])) - .digest('hex'); -} - -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 }); -} - -function isBoundPublication(file: string) { - return /^\.(pending|published)\./.test(basename(file)) && !isLegacyCapture(file); -} - -export class TriggerHistory { - constructor(private database: Sequelize) {} - - // 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) { - 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; - } - - // 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.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() } }, - ); - } - - // 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') { - const sample = await this.readScriptSample(id); - await this.database.transaction(async (transaction) => { - await this.saveScriptSample(id, sample, transaction); - await this.completeCommandExit(id, state, reason, code, transaction, undefined, finishedAt, report); - }); - if (sample) await fs.unlink(sample.marker).catch(() => {}); - } - - private async completeCommandExit(id: string, state: TriggerState, reason: string | null, - code: number | null, transaction: Transaction, receipt?: Awaited>, finishedAt?: number, - report?: VerifiedSupervisorExit | 'legacy', recoveredCopies?: Awaited>[]) { - const file = receiptPath(id); - let pending = file ? await this.pendingExit(id, transaction) : undefined; - const [saved] = file ? await this.database.query( - `SELECT b.*,u.outcome AS unmatched_outcome,u.finished_at AS unmatched_time,EXISTS(SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id) AS conflicted - FROM (SELECT 1) LEFT JOIN CronLegacyExitBookings b ON b.trigger_id=$id LEFT JOIN CronUnmatchedBoundExits u ON u.trigger_id=$id`, - { bind: { id }, transaction, type: QueryTypes.SELECT }) : []; - const booking = saved?.trigger_id ? saved : undefined; - // Every version-1 publication has the same evidentiary weight, regardless of its path. - const recovered = recoveredCopies ?? (file ? await Promise.all((await retiringExits()) - .filter(copy => copy.id === id).map(copy => readExit(id, copy.file))) : []); - const published = receipt === undefined && file ? await readExit(id) : receipt; - const files = [published, ...recovered]; - const candidates = [...files, ...files.map(copy => copy?.namedExit), report === 'legacy' ? undefined : report] - .filter((value): value is VerifiedSupervisorExit => value?.version === 1); - const bound = file && candidates[0] ? { ...candidates[0], file } : undefined; - const tuples = candidates.map(value => observationKey(id, value)); - if (booking?.bound) tuples.push({ id, outcome: booking.outcome, time: booking.finished_at }); - if (saved?.unmatched_time != null && saved.unmatched_outcome != null) { - tuples.push({ id, outcome: saved.unmatched_outcome, time: saved.unmatched_time }); - } - const first = tuples[0]; - if (saved?.conflicted || tuples.some(tuple => tuple.time !== first.time || tuple.outcome !== first.outcome)) { - await this.disputeBoundExit(id, tuples, transaction); - if (saved.unmatched_time != null) await this.database.query('DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', { bind: { id }, transaction }); - this.retireDuplicatePublications(id, recovered, transaction); - if (!saved?.conflicted) { - if (booking) { - await this.withdrawBooking(booking, transaction); - await this.database.query('DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id', { bind: { id }, transaction }); - } - if (await this.invalidateBookedTrigger(id, transaction)) await this.deferExit(id, transaction); - } else if (pending?.state === 'running') await this.deferExit(id, transaction); - return; - } - for (const copy of recovered) { - if (copy?.version === 1) this.retireReceiptAfterCommit(id, copy.file, transaction, 'bound-copy', copy); - } - if (bound && !pending && saved.unmatched_time == null) { - // After history pruning the booking can disappear with its daily row. - // Before releasing a verified replay, retain just its tuple so a later - // conflicting file can still be recognized without recreating that day. - await this.database.query(`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at) - SELECT $id,$outcome,$time WHERE NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=$id)`, - { bind: observationKey(id, bound), transaction }); - } - const start = booking?.started_at ?? (pending?.owner ? pending.started_at : null); - const observation = start != null && finishedAt !== undefined && finishedAt >= start && - validExit(code, reason, finishedAt) && state === (code === 0 ? 'finished' : 'failed') - ? { code, signal: reason, time: finishedAt } : undefined; - if (booking && !booking.bound && (bound || (observation && (booking.outcome !== observationKey(id, observation).outcome || - booking.finished_at !== observation.time)))) { - const retained = await this.reviseLegacyBooking(booking, bound, transaction); - if (!retained || !bound) { - if (retained) await this.deferExit(id, transaction, observation); - else if (file) this.retireReceiptAfterCommit(id, file, transaction, 'exit', published); - return; - } - pending = await this.pendingExit(id, transaction); - } - if (file && !pending) { - if (bound && !booking) { - const [pruned] = await this.database.query>( - 'SELECT trigger_id,cron_id,source,started_at FROM CronPrunedUnknownRuns WHERE trigger_id=$id', - { bind: { id }, transaction, type: QueryTypes.SELECT }); - if (pruned) { - await this.bookPrunedExit(pruned, false, bound, transaction); - await this.database.query('DELETE FROM CronPrunedUnknownRuns WHERE trigger_id=$id', { bind: { id }, transaction }); - } - } - await this.settleInstance(id, transaction); - this.retireReceiptAfterCommit(id, file, transaction, 'exit', published); - return; - } - if (pending?.finished_at != null && ['finished', 'failed', 'stopped'].includes(pending.state)) { - // An earlier panel may have committed the trigger before claiming its statistic. - await this.completeInTransaction(id, pending.state, pending.reason, pending.exit_code, transaction, undefined, pending.finished_at); - if (file) this.retireReceiptAfterCommit(id, file, transaction, 'exit', published); - return; - } - if (pending?.stop_exit_verified && pending.stop_exit_at != null) { - // The outcome was verified before the last worker finished checking the process tree. - await this.completeInTransaction(id, 'stopped', 'cancelled', pending.exit_code, transaction, undefined, pending.stop_exit_at); - this.retireReceiptAfterCommit(id, file!, transaction, 'exit'); - return; - } - // A truncated publication is different from no publication. In particular - // a killed supervisor cannot attest to the script's own exit status. - const unreadable = recovered.some(copy => copy === null || (copy && copy.version !== 1 && isBoundPublication(copy.file))); - const exit = bound ?? published ?? (unreadable ? null : published); - if (exit && exit.version !== 1 && !booking?.bound) { - if (observation) await this.saveExitObservation(id, observation, transaction); - if (pending?.started_at == null || exit.time < pending.started_at || - !await this.hasExitObservation(id, exit, transaction)) { - await this.deferExit(id, transaction); - return; - } - } - if (exit && pending?.started_at != null && !booking?.bound) { - // Track the exact contribution until its history and retained statistic expire. - await this.database.query(`INSERT OR IGNORE INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound) - SELECT id,cron_id,source,started_at,$time,$outcome,$day,$bound FROM CronTriggers WHERE id=$id`, - { bind: { ...observationKey(id, exit), bound: Number(exit.version === 1), day: dayjs(exit.time).format('YYYY-MM-DD') }, transaction }); - await this.database.query('DELETE FROM CronExitObservations WHERE trigger_id=$id', { bind: { id }, transaction }); - if (bound && saved?.unmatched_time != null) await this.database.query('DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', { bind: { id }, transaction }); - } - // A signal on the bound supervisor before its first write says nothing about - // the command it was waiting for. A verified stop has its own durable claim. - const supervisorKilled = pending?.command_identity && !pending.stop_requested && - code === null && state === 'stopped' && reason?.startsWith('SIG'); - if (pending && pending.owner && pending.started_at !== null && - (exit === null || (!exit && (pending.exit_pending || supervisorKilled || report === 'legacy')))) { - await this.deferExit(id, transaction, observation); - return; - } - if (exit) { - await this.completeInTransaction(id, exit.signal || exit.code !== 0 ? 'failed' : 'finished', - exit.signal, exit.code, transaction, undefined, exit.time, true); - this.retireReceiptAfterCommit(id, exit.file, transaction, 'exit'); - } else if (state === 'skipped') { - await this.finish(id, state, reason, code, transaction); - await this.settleInstance(id, transaction); - } else { - await this.completeInTransaction(id, state, reason, code, transaction, undefined, finishedAt); - } - } - - private async withdrawBooking(booking: LegacyExitBooking, transaction: Transaction) { - const { trigger_id: id, stat_id: stat } = booking; - const elapsed = Math.max(0, booking.finished_at - booking.started_at); - if (stat !== null) { - // Only the row that received this exact contribution can be debited. A deleted day stays deleted. - await this.database.query(`UPDATE CrontabStats SET run_count=run_count-1, success_count=success_count-$success, - fail_count=fail_count-$failure,total_time=total_time-$elapsed,updatedAt=CURRENT_TIMESTAMP, - max_time=MAX(COALESCE(fixed_max_time,0),COALESCE((SELECT MAX(MAX(0,finished_at-started_at)) - FROM CronLegacyExitBookings WHERE stat_id=$stat AND trigger_id<>$id),0)) WHERE id=$stat`, - { bind: { stat, id, elapsed, success: Number(!booking.stopped && booking.outcome === '0'), - failure: Number(!booking.stopped && booking.outcome !== '0') }, transaction }); - await this.database.query('DELETE FROM CrontabStats WHERE id=$stat AND run_count=0', { bind: { stat }, transaction }); - } - } - - private async invalidateBookedTrigger(id: string, transaction: Transaction) { - const [trigger] = await this.database.query<{ instance_id: number | null; state: TriggerState; cron_id: number }>( - 'SELECT instance_id,state,cron_id FROM CronTriggers WHERE id=$id AND started_at IS NOT NULL', { bind: { id }, type: QueryTypes.SELECT, transaction }); - if (!trigger) return false; - const ref = trigger.cron_id; - await this.database.query(`UPDATE CronTriggers SET counted=0,exit_pending=1,stop_exit_verified=NULL,stop_exit_at=NULL, - exit_code=NULL,reason=NULL,state=CASE WHEN state='running' THEN state ELSE 'unknown' END WHERE id=$id`, { bind: { id }, transaction }); - if (trigger.instance_id !== null && trigger.state !== 'running') { - await this.database.query('UPDATE RunningInstances SET status=4,exit_code=NULL,updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$ref', - { bind: { instance: trigger.instance_id, ref }, transaction }); - await this.database.query('UPDATE Crontabs SET last_running_time=NULL WHERE id=$ref AND last_instance_id=$instance', - { bind: { ref, instance: trigger.instance_id }, transaction }); - } - return true; - } - - private async disputeBoundExit(id: string, tuples: { outcome: string; time: number }[], transaction: Transaction) { - if (!tuples.length) return; - await this.database.query(`INSERT OR IGNORE INTO CronBoundExitConflicts(trigger_id,outcome,finished_at) - SELECT $id,json_extract(value,'$.outcome'),json_extract(value,'$.time') FROM json_each($tuples)`, - { bind: { id, tuples: JSON.stringify(tuples) }, transaction }); - } - - private async bookPrunedExit(run: Pick, - stopped: boolean, exit: ExitObservation, transaction: Transaction) { - const day = dayjs(exit.time).format('YYYY-MM-DD'); - const state = stopped ? 'stopped' : exit.code === 0 ? 'finished' : 'failed'; - await addDailyExit(this.database, run.cron_id, day, state, Math.max(0, exit.time - run.started_at), true, transaction); - await this.database.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,stopped,bound,stat_id) - VALUES($id,$ref,$source,$start,$time,$outcome,$day,$stopped,1, - (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))) - ON CONFLICT(trigger_id) DO UPDATE SET bound=1,disputed=0,outcome=excluded.outcome,finished_at=excluded.finished_at, - day=excluded.day,stat_id=excluded.stat_id`, - { bind: { ...observationKey(run.trigger_id, exit), ref: run.cron_id, source: run.source, start: run.started_at, - day, stopped: Number(stopped) }, transaction }); - } - - private async reviseLegacyBooking(booking: LegacyExitBooking, bound: ExitObservation | undefined, transaction: Transaction) { - const id = booking.trigger_id; - await this.withdrawBooking(booking, transaction); - const retained = await this.invalidateBookedTrigger(id, transaction); - if (!retained) { - if (!bound) { - await this.database.query('UPDATE CronLegacyExitBookings SET disputed=1,stat_id=NULL WHERE trigger_id=$id', - { bind: { id }, transaction }); - } else { - await this.bookPrunedExit(booking, Boolean(booking.stopped), bound, transaction); - } - return false; - } - await this.database.query('DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id', { bind: { id }, transaction }); - if (!bound) await this.database.query(`INSERT OR IGNORE INTO CronExitObservations(trigger_id,outcome,finished_at) - VALUES($id,$outcome,$time)`, { bind: { id, outcome: booking.outcome, time: booking.finished_at }, transaction }); - return true; - } - - private retireDuplicatePublications(id: string, copies: Awaited>[], transaction: Transaction) { - // Independent scans must agree about which file to keep even if they see - // different subsets. Only newer per-writer publications can be discarded. - const witnesses = new Map(); - const redundant: { file: string; key: string; outcome: string; time: number }[] = []; - // Prefer a JSON copy readable by older panels. Compare full paths within - // each format so concurrent collectors always choose the same survivor. - const rank = (file: string) => (isMetadataReceipt(file) ? '1' : '0') + file; - for (const copy of copies) { - if (copy?.version !== 1 || copy.namedExit || !basename(copy.file).startsWith('.pending.')) continue; - const { outcome, time } = observationKey(id, copy); - const key = JSON.stringify([outcome, time]); - const previous = witnesses.get(key); - if (previous && previous !== copy.file) { - redundant.push({ file: rank(previous) < rank(copy.file) ? copy.file : previous, key, outcome, time }); - } - if (!previous || rank(copy.file) < rank(previous)) witnesses.set(key, copy.file); - } - if (!redundant.length) return; - transaction.afterCommit(async () => { - // Sequelize also invokes this hook after a failed COMMIT. Verify the - // specific tuple in a separate snapshot, including on an existing dispute. - try { - const rows = await this.database.query<{outcome: string; finished_at: number}>( - 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id', - { bind: { id }, transaction: null, type: QueryTypes.SELECT }); - const committed = new Set(rows.map(row => JSON.stringify([row.outcome, row.finished_at]))); - for (const copy of redundant) { - if (!committed.has(copy.key)) continue; - const keeper = await readExit(id, witnesses.get(copy.key)!); - if (keeper?.version === 1 && keeper.time === copy.time && observationKey(id, keeper).outcome === copy.outcome) { - await retireLegacyFile(id, copy.file, copy).catch(() => {}); - } - } - } catch { /* Retry on the next recovery pass. */ } - }); - } - - private retireReceiptAfterCommit(id: string, file: string, transaction: Transaction, kind: 'exit' | 'start' | 'bound-copy', observed?: Awaited>) { - // Sequelize 6 runs afterCommit even when COMMIT itself failed. Check a - // separate committed snapshot before deleting the only durable outcome. - transaction.afterCommit(async () => { - try { - const pendingCondition = kind === 'start' ? 'script_started_at IS NULL' : 'counted=0'; - const [saved] = await this.database.query<{ pending: number; outcome: string | null; finished_at: number | null; bound: number; conflicted: number; unmatched: number }>( - `SELECT EXISTS(SELECT 1 FROM CronTriggers WHERE id=$id AND ${pendingCondition}) AS pending, - EXISTS(SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id) AS conflicted, - (b.trigger_id IS NULL AND u.trigger_id IS NOT NULL) AS unmatched, - COALESCE(b.outcome,u.outcome) AS outcome,COALESCE(b.finished_at,u.finished_at) AS finished_at, - COALESCE(b.bound,u.trigger_id IS NOT NULL) AS bound FROM (SELECT 1) - LEFT JOIN CronLegacyExitBookings b ON b.trigger_id=$id LEFT JOIN CronUnmatchedBoundExits u ON u.trigger_id=$id`, - { bind: { id }, transaction: null, type: QueryTypes.SELECT }); - if (saved.pending || (kind !== 'start' && saved.conflicted)) return; - if (saved.outcome !== null && saved.finished_at !== null && kind !== 'start') { - if (saved.unmatched) { - // A legacy public name may be unreadable until claimed. Verify the - // moved bytes directly against the durable unmatched observation. - await retireLegacyFile(id, file, { outcome: saved.outcome, time: saved.finished_at }); - return; - } - // After a failed correction the old booking is still visible. - if (kind === 'bound-copy' && !saved.bound) return; - const current = await readExit(id, file); - if (current && ((saved.bound && current.version !== 1) || (current.time === saved.finished_at && - observationKey(id, current).outcome === saved.outcome && (saved.bound || current.version !== 1)))) { - await retireLegacyFile(id, file, saved.bound ? { outcome: saved.outcome, time: saved.finished_at } : undefined); - } - return; - } - if (kind === 'start') await fs.rm(file, { force: true }); - else if (observed?.version !== 1) await retireLegacyFile(id, file); - } catch { /* Keep the receipt for the next recovery pass. */ } - }); - } - - private async replayRetiringExits(transaction?: Transaction) { - const byId = new Map>>[]>(); - const unreadable = new Set(); - for (const { id, file } of await retiringExits()) { - const exit = await readExit(id, file); - if (exit === undefined) continue; - if (exit === null || (exit.version !== 1 && isBoundPublication(file))) { - unreadable.add(id); - continue; - } - if (exit.version !== 1) { - // Inspect the atomically moved bytes even when a stale temporary file is being replaced. - await retireLegacyFile(id, file).catch(() => {}); - continue; - } - const copies = byId.get(id) ?? []; - copies.push(exit); - byId.set(id, copies); - } - if (unreadable.size) { - // Retention runs this scan before deletion. Keep unresolved history for - // later repair without ending a live process solely on damaged bytes. - await this.database.query(`UPDATE CronTriggers SET exit_pending=1 WHERE counted=0 AND state='unknown' - AND exit_pending IS NOT 1 AND owner IS NOT NULL AND started_at IS NOT NULL - AND id IN (SELECT value FROM json_each($ids))`, { transaction, bind: { ids: JSON.stringify([...unreadable]) } }); - } - for (const [id, copies] of byId) { - const settle = async (tx: Transaction) => { - await this.recoverScriptSample(id, tx); - await this.completeCommandExit(id, 'unknown', null, null, tx, undefined, undefined, undefined, copies); - }; - if (transaction) await settle(transaction); - else await this.database.transaction(settle); - } - return byId; - } - - private async pendingExit(id: string, transaction: Transaction) { - const [row] = await this.database.query & { - owner: string | null; command_identity: string | null; stop_requested: number | null; stop_exit_verified: number | null; stop_exit_at: number | null; exit_pending: number | null; - }>( - `SELECT state,reason,exit_code,started_at,finished_at,owner,command_identity,stop_requested,stop_exit_verified,stop_exit_at,exit_pending - FROM CronTriggers WHERE id=$id AND counted=0`, - { bind: { id }, transaction, type: QueryTypes.SELECT }); - return row; - } - - private async hasExitObservation(id: string, exit: ExitObservation, transaction?: Transaction) { - const [match] = await this.database.query( - `SELECT 1 FROM CronExitObservations WHERE trigger_id=$id GROUP BY trigger_id - HAVING COUNT(*)=1 AND MAX(outcome)=$outcome AND MAX(finished_at)=$time`, - { bind: observationKey(id, exit), type: QueryTypes.SELECT, transaction }); - return Boolean(match); - } - - private async saveExitObservation(id: string, observation: ExitObservation, transaction: Transaction) { - await this.database.query(`INSERT INTO CronExitObservations(trigger_id,outcome,finished_at) - SELECT $id,$outcome,$time WHERE NOT EXISTS - (SELECT 1 FROM CronExitObservations WHERE trigger_id=$id LIMIT 1 OFFSET 1) - ON CONFLICT(trigger_id,outcome,finished_at) DO NOTHING`, { bind: observationKey(id, observation), transaction }); - } - - private async deferExit(id: string, transaction: Transaction, observation?: ExitObservation) { - if (observation) await this.saveExitObservation(id, observation, transaction); - await this.database.query('UPDATE CronTriggers SET exit_pending=1 WHERE id=$id AND exit_pending IS NOT 1', - { bind: { id }, transaction }); - // A signalled stop remains running until all of its descendants are gone. - await this.database.query(`UPDATE CronTriggers SET state='unknown',reason=NULL,exit_code=NULL, - finished_at=COALESCE(finished_at,$now) 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 AND s.signalled=1)`, - { bind: { id, now: Date.now() }, transaction }); - await this.settleInstance(id, transaction); - } - - async retryPendingExits() { - const rows = await this.database.query<{ id: string }>( - `SELECT id FROM CronTriggers WHERE exit_pending=1 AND - NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=CronTriggers.id)`, { type: QueryTypes.SELECT }); - for (const { id } of rows) { - const exit = await readExit(id); - if (exit && (exit.version === 1 || await this.hasExitObservation(id, exit))) { - // Carry a verified bound receipt across a concurrent file replacement. - // Unbound evidence must still match inside the writer transaction. - await this.complete(id, 'unknown', null, null, undefined, exit.version === 1 ? exit : undefined); - } - } - // A canonical-only file can reappear after startup already marked its owner - // unknown. Probe IDs found on disk so missing receipts cost no per-run work. - const recovered = await this.replayRetiringExits(); - const files = (await publishedExits()).filter(id => !recovered.has(id)); - if (files.length) { - const candidates = await this.database.query<{ id: string }>( - `SELECT value AS id FROM json_each($files) WHERE - EXISTS (SELECT 1 FROM CronTriggers WHERE id=value AND state='unknown' AND reason='restart' - AND counted=0 AND owner IS NOT NULL AND started_at IS NOT NULL) OR - EXISTS (SELECT 1 FROM CronPrunedUnknownRuns WHERE trigger_id=value) OR - EXISTS (SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=value) OR - EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=value) OR - EXISTS (SELECT 1 FROM CronUnmatchedBoundExits WHERE trigger_id=value)`, - { bind: { files: JSON.stringify(files) }, type: QueryTypes.SELECT }); - for (const { id } of candidates) { - const exit = await readExit(id); - if (exit?.version === 1) await this.complete(id, 'unknown', null, null, undefined, exit); - } - } - await this.collectPublishedScriptStarts(); - } - - private async collectPublishedScriptStarts() { - const files = await publishedScriptStarts(); - if (!files.length) return; - // Only probe existing executions. Keep live markers in place so another - // instrumented command in the same execution cannot replace the first sample. - const rows = await this.database.query<{ id: string; counted: number; script_started_at: number | null }>( - `SELECT id,counted,script_started_at FROM CronTriggers WHERE id IN (SELECT value FROM json_each($ids)) - AND started_at IS NOT NULL AND (script_started_at IS NULL OR counted=1)`, - { bind: { ids: JSON.stringify(files.map(({ id }) => id)) }, type: QueryTypes.SELECT }); - for (const row of rows) { - const sample = await this.readScriptSample(row.id); - if (!sample) continue; - await this.database.transaction(async transaction => { - if (row.script_started_at === null) await this.saveScriptSample(row.id, sample, transaction); - if (row.counted) this.retireReceiptAfterCommit(row.id, sample.marker, transaction, 'start'); - }); - } - } - - async replayPublishedExits(transaction: Transaction) { - const recovered = await this.replayRetiringExits(transaction); - // Entry instrumentation can outlive its committed transaction even if the - // exit file was already deleted. An unregistered entry may still be live. - const exits = new Set(await publishedExits()); - for (const { id, file } of await publishedScriptStarts()) { - const [row] = await this.database.query<{ counted: number; script_started_at: number | null }>( - 'SELECT counted,script_started_at FROM CronTriggers WHERE id=$id', - { bind: { id }, transaction, type: QueryTypes.SELECT }); - // After pruning the trigger, a matching supervisor exit still identifies - // this panel's retired run. A start file alone cannot establish that. - if (row ? row.counted && row.script_started_at !== null : exits.has(id)) { - this.retireReceiptAfterCommit(id, file, transaction, 'start'); - } - } - for (const id of exits) { - if (recovered.has(id)) continue; - const pending = await this.pendingExit(id, transaction); - if (!pending) { - await this.completeCommandExit(id, 'unknown', 'restart', null, transaction, undefined, undefined, undefined, []); - } else if (pending.owner && pending.started_at !== null) { - const exit = await readExit(id); - if (exit === undefined) continue; - await this.recoverScriptSample(id, transaction); - await this.completeCommandExit(id, 'unknown', 'restart', null, transaction, exit, undefined, undefined, []); - } - } - } - - // Original registration order breaks ties even when upgrade adoption runs later. - private 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) } }); - } - - private async completeInTransaction(id: string, state: TriggerState, reason: string | null, - code: number | null, transaction: Transaction, elapsedMs?: number, finishedAt?: number, verifiedExit = false) { - if (await this.shouldStop(id, transaction)) { - state = 'stopped'; - reason = 'cancelled'; - // The command can exit before its TERM-resistant descendants. Keep the - // receipt running until the stop operation has verified the whole tree. - const waiting = await this.database.query(`UPDATE CronTriggers SET - exit_code=CASE WHEN stop_exit_at IS NULL OR ($verified AND stop_exit_verified IS NOT 1) THEN $code ELSE exit_code END, - stop_exit_at=CASE WHEN stop_exit_at IS NULL OR ($verified AND stop_exit_verified IS NOT 1) THEN $now ELSE stop_exit_at END, - stop_exit_verified=CASE WHEN $verified THEN 1 ELSE stop_exit_verified END - WHERE id=$id AND state='running' AND stop_requested=1 AND instance_id IN - (SELECT instance_id FROM CronStopRequests WHERE targets IS NOT NULL AND signalled=1)`, - { transaction, bind: { id, code, now: finishedAt ?? Date.now(), verified: Number(verifiedExit) }, type: QueryTypes.BULKUPDATE }); - if (waiting) return; - } else if (state === 'stopped' && reason?.startsWith('SIG')) { - state = 'failed'; - } - const changed = await this.finish(id, state, reason, code, transaction, finishedAt); - const [row] = await this.database.query( - `SELECT cron_id, instance_id, log_path, started_at, finished_at, exit_code FROM CronTriggers WHERE id=$id - AND state IN ('finished','failed','stopped') AND started_at IS NOT NULL AND counted=0`, - { transaction, bind: { id }, type: QueryTypes.SELECT }, - ); - await this.settleInstance(id, transaction); - if (!row) return; - const duration = elapsedMs ?? Math.max(0, row.finished_at! - row.started_at!); - if (changed && row.instance_id !== null) { - await this.database.query(`UPDATE Crontabs SET last_running_time=$duration - WHERE id=$cronId AND last_execution_time=$start AND (last_instance_id=$instance OR - (last_instance_id IS NULL AND $instance=(SELECT id FROM RunningInstances WHERE cron_id=$cronId - ORDER BY started_at DESC,id DESC LIMIT 1)))`, - { transaction, bind: { cronId: row.cron_id, - start: Math.floor(row.started_at! / 1000), instance: row.instance_id, duration: Math.floor(duration / 1000) } }); - } - await recordCronResult(this.database, row.cron_id, row.exit_code ?? 1, duration, row.finished_at!, id, transaction); - } - - private async hasBoundConflict(id: string, transaction: Transaction) { - const [conflict] = await this.database.query('SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id', - { bind: { id }, transaction, type: QueryTypes.SELECT }); - return Boolean(conflict); - } - - // 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.database.transaction(async transaction => { - if (await this.hasBoundConflict(id, transaction)) return; - const [row] = await this.database.query<{ owner: string | null; state: TriggerState }>( - 'SELECT owner,state FROM CronTriggers WHERE id=$id AND cron_id=$cronId', - { transaction, type: QueryTypes.SELECT, bind: { id, cronId } }); - if (!row) { - if (finishedAt && finishedAt <= now) { - const [pruned] = await this.database.query('SELECT 1 FROM CronHistoryRetention WHERE id=1 AND cutoff>$end', - { transaction, type: QueryTypes.SELECT, bind: { end: finishedAt } }); - if (pruned) return; - } - throw new Error('Unknown trigger'); - } - if (row.owner === null && (row.state === 'running' || row.state === 'unknown')) { - await this.completeInTransaction(id, code === 0 ? 'finished' : 'failed', null, code, transaction, elapsedMs, finishedAt); - } else { - await recordCronResult(this.database, cronId, code, elapsedMs, now, id, transaction); - } - }); - } - - private async readScriptSample(id: string) { - if (!process.env.QL_DIR || !/^[a-z0-9-]{1,120}$/.test(id)) return; - const marker = join(process.env.QL_DIR, '.tmp', 'cron-start-' + id); - try { - const value = await fs.readFile(marker, 'utf8'); - if (/^\d{13}$/.test(value)) return { marker, time: Number(value) }; - } catch { /* Entries without instrumentation have no sample. */ } - } - - private async recoverScriptSample(id: string, transaction: Transaction) { - const sample = await this.readScriptSample(id); - if (!sample) return; - await this.saveScriptSample(id, sample, transaction); - this.retireReceiptAfterCommit(id, sample.marker, transaction, 'start'); - } - - private async saveScriptSample(id: string, sample: { time: number } | undefined, transaction: Transaction) { - if (sample) await this.database.query(`UPDATE CronTriggers SET script_started_at=$time - WHERE id=$id AND script_started_at IS NULL AND started_at <= $time AND $time <= $now - AND (finished_at IS NULL OR state='unknown' OR $time <= finished_at)`, - { transaction, bind: { time: sample.time, now: Date.now(), id } }); - } - - 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 shellReport( - id: string, - cronId: number, - system: boolean, - running: boolean, - log: string, - seconds: number, - exitCode?: number, - stopped = false, - transaction?: Transaction, - elapsedMs?: number, - finishedAt?: number, - ): Promise { - if (!transaction) return this.database.transaction(tx => - this.shellReport(id, cronId, system, running, log, seconds, exitCode, stopped, tx, elapsedMs, finishedAt)); - if (await this.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.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.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.claimSummary(cronId, instance!, seconds, transaction, old?.status === 0 || (running && !unknown)); - for (const other of others) { - if (other.started_at < seconds) await this.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.settleInstance(id, transaction); - } - if (!running) { - const state = code == null ? 'unknown' : code === 0 ? 'finished' : 'failed'; - await this.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.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.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.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.saveScriptSample(id, sample, transaction); - }); - } - - private async settleInstance(id: string, transaction: Transaction) { - const [row] = await this.database.query( - `SELECT cron_id,instance_id,log_path,state,finished_at,exit_code FROM CronTriggers - WHERE id=$id AND instance_id IS NOT NULL AND finished_at IS NOT NULL`, - { transaction, bind: { id }, type: QueryTypes.SELECT }); - if (!row) return; - if (row.state === 'skipped') { - // The launch gate closed before user code ran. - await this.database.query('DELETE FROM RunningInstances WHERE id=$instance AND status=0', - { transaction, bind: { instance: row.instance_id } }); - await this.database.query('UPDATE CronTriggers SET instance_id=NULL WHERE id=$id', { transaction, bind: { id } }); - } else { - const status = row.state === 'finished' ? 1 : row.state === 'stopped' ? 2 : row.state === 'unknown' ? 4 : 3; - const updated = await this.database.query(`UPDATE RunningInstances SET status=$status,finished_at=$end,exit_code=$code, - updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$cronId AND status=0`, - { transaction, type: QueryTypes.BULKUPDATE, bind: { instance: row.instance_id, cronId: row.cron_id, - status, end: Math.floor(row.finished_at! / 1000), code: row.exit_code } }); - if (!updated) { - // A late exit corrects only the historical instance. Its replacement - // already owns the task row, even when it uses the same PID and log. - if (status !== 4) await this.database.query(`UPDATE RunningInstances - SET status=$status,finished_at=$end,exit_code=$code,updatedAt=CURRENT_TIMESTAMP - WHERE id=$instance AND cron_id=$cronId AND status=4`, - { transaction, bind: { instance: row.instance_id, cronId: row.cron_id, status, - end: Math.floor(row.finished_at! / 1000), code: row.exit_code } }); - return; - } - } - // A newer manual reservation owns its own token. Never clear it while an older run exits. - const [active] = await this.database.query<{ pid: number; log_path: string; started_at: number }>( - 'SELECT pid,log_path,started_at FROM RunningInstances WHERE cron_id=$cronId AND status=0 ORDER BY id DESC LIMIT 1', - { transaction, bind: { cronId: row.cron_id }, type: QueryTypes.SELECT }); - if (active) { - await this.database.query(`UPDATE Crontabs SET status=0,pid=$pid,log_path=$log - WHERE id=$cronId AND status IS NOT 3`, { transaction, bind: { cronId: row.cron_id, - pid: active.pid, log: active.log_path } }); - } else { - await this.database.query(`UPDATE Crontabs SET status=1,pid=NULL,queued_token=NULL - WHERE id=$cronId AND status=0 AND log_path IS $log`, - { transaction, bind: { cronId: row.cron_id, log: row.log_path } }); - } - } - - 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) { - 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.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.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 }; - } - - private async exitBeforeStop(id: string) { - const recovered = await Promise.all((await retiringExits()).filter(copy => copy.id === id) - .map(copy => readExit(id, copy.file))); - const canonical = await readExit(id); - const verified = recovered.some(copy => copy?.version === 1); - const unreadable = canonical === null || recovered.some(copy => copy === null || - (copy && copy.version !== 1 && isBoundPublication(copy.file))); - return { canonical, recovered, published: Boolean(canonical || verified), unreadable }; - } - - 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) { - 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.exitBeforeStop(row.id); - if (exit.published || exit.unreadable || row.exit_pending || row.stop_exit_at !== null || !row.owner || legacyCrond || row.reason === 'restart') { - await this.recoverScriptSample(row.id, transaction); - await this.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.recoverScriptSample(row.id, tx); - await this.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.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); - }); - } - - 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 }); - }); - } - - 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 }, - ); - } - - async visibleTriggers(cronId: number, ids: string[]) { - return this.database.query( - `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( - `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) }; - } -} - -export function triggerHistory(): TriggerHistory { - return new TriggerHistory(require('../data').sequelize); -} diff --git a/back/shared/utils.ts b/back/shared/utils.ts index 6760f4f9..4a084438 100644 --- a/back/shared/utils.ts +++ b/back/shared/utils.ts @@ -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 diff --git a/back/types/express.d.ts b/back/types/express.d.ts index 4a8fd216..3899d0bd 100644 --- a/back/types/express.d.ts +++ b/back/types/express.d.ts @@ -8,4 +8,4 @@ declare global { platform: 'desktop' | 'mobile'; } } -} \ No newline at end of file +} diff --git a/back/validation/schedule.ts b/back/validation/schedule.ts index ec593aea..ea983663 100644 --- a/back/validation/schedule.ts +++ b/back/validation/schedule.ts @@ -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', }), diff --git a/cli/README.en.md b/cli/README.en.md index 6cb12b32..e704daad 100644 --- a/cli/README.en.md +++ b/cli/README.en.md @@ -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 --timeout 300 --json +ql task logs 12 --trigger-id --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 diff --git a/cli/README.md b/cli/README.md index 1762e82d..d0c261fb 100644 --- a/cli/README.md +++ b/cli/README.md @@ -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 --timeout 300 --json +ql task logs 12 --trigger-id --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、构建与验证 diff --git a/cli/scripts/verify-package.cjs b/cli/scripts/verify-package.cjs index 839a9b57..87ab3a85 100644 --- a/cli/scripts/verify-package.cjs +++ b/cli/scripts/verify-package.cjs @@ -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( diff --git a/cli/skills/qinglong-cli/references/openapi.md b/cli/skills/qinglong-cli/references/openapi.md index 8ff3d4bc..c5f62e42 100644 --- a/cli/skills/qinglong-cli/references/openapi.md +++ b/cli/skills/qinglong-cli/references/openapi.md @@ -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=` 查询,日志通过 `GET /open/crons/:id/log?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=` and its log via `crons/:id/log?triggerId=`. History retention still applies; run requests are not idempotent. + +`ql task run --wait --timeout 300 --json` 等待本轮;`ql task wait --trigger-id --timeout 300 --json` 仅等待已有轮次;`ql task logs --trigger-id --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 ''` / `--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 ` | PUT | `crons/run` | --query via api request | +| `ql task run ` | PUT | `crons/run` | --wait --timeout 300 | | `ql task stop ` | 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 ` | PUT | `crons/disable` | --query | | `ql task enable ` | PUT | `crons/enable` | --query | -| `ql task logs ` | GET | `crons/:id/log` | --query via api request | +| `ql task logs ` | GET | `crons/:id/log` | --trigger-id --tail | | `ql task update ` | PUT | `crons` | --data, --query | | `ql task delete ` | DELETE | `crons` | --query | | `ql task pin ` | PUT | `crons/pin` | --query | diff --git a/cli/skills/qinglong-cli/references/panel.md b/cli/skills/qinglong-cli/references/panel.md index cda70cdf..b3890ef5 100644 --- a/cli/skills/qinglong-cli/references/panel.md +++ b/cli/skills/qinglong-cli/references/panel.md @@ -36,7 +36,9 @@ Remote URLs require HTTPS; loopback HTTP is allowed. Use the panel root URL with Use ` task run --json` or ` task stop --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 --wait --timeout 300 --json` to submit once and wait for that run, or `task wait --trigger-id --timeout 300 --json` to resume waiting without executing again. Read its log with `task logs --trigger-id --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 diff --git a/cli/src/entrypoints/ql.ts b/cli/src/entrypoints/ql.ts index 9eb24043..cfd08f2c 100644 --- a/cli/src/entrypoints/ql.ts +++ b/cli/src/entrypoints/ql.ts @@ -33,6 +33,7 @@ const remoteTaskActions = new Set([ 'list', 'get', 'run', + 'wait', 'stop', 'logs', ]); diff --git a/cli/src/entrypoints/task.ts b/cli/src/entrypoints/task.ts index b8a0e6aa..bfadb1b8 100644 --- a/cli/src/entrypoints/task.ts +++ b/cli/src/entrypoints/task.ts @@ -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; + }); diff --git a/cli/src/internal/execution/taskRunner.ts b/cli/src/internal/execution/taskRunner.ts index 464f3d47..40d8b013 100644 --- a/cli/src/internal/execution/taskRunner.ts +++ b/cli/src/internal/execution/taskRunner.ts @@ -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({ - ids: [taskId], - status: final ? '1' : '0', - pid: String(process.pid), - log_path: logPath, - last_execution_time: started, - last_running_time: duration, - }, final ? code : undefined); + 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, + ); } catch { output( Buffer.from( @@ -401,11 +417,17 @@ export async function executeTask( } } } - 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 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') + : ''; 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( diff --git a/cli/src/internal/maintenance/check.ts b/cli/src/internal/maintenance/check.ts index 189608cd..a0f7c9f0 100644 --- a/cli/src/internal/maintenance/check.ts +++ b/cli/src/internal/maintenance/check.ts @@ -88,22 +88,28 @@ export async function inspectPanel( probe(port, `${basePath}/`, (body) => /\s*<\/div>/.test(body), ), - probe(port, `${basePath}/api/health?t=${Math.floor(Date.now() / 1000)}`, (body) => { - try { - const response: unknown = JSON.parse(body); - return ( - !!response && - typeof response === 'object' && - 'code' in response && - response.code === 200 && - 'data' in response && !!response.data && - typeof response.data === 'object' && - 'status' in response.data && response.data.status === 'ok' - ); - } catch { - return false; - } - }), + probe( + port, + `${basePath}/api/health?t=${Math.floor(Date.now() / 1000)}`, + (body) => { + try { + const response: unknown = JSON.parse(body); + return ( + !!response && + typeof response === 'object' && + 'code' in response && + response.code === 200 && + 'data' in response && + !!response.data && + typeof response.data === 'object' && + 'status' in response.data && + response.data.status === 'ok' + ); + } catch { + return false; + } + }, + ), ]); return { panel, backend }; } diff --git a/cli/src/internal/maintenance/panelUpgrade.cjs b/cli/src/internal/maintenance/panelUpgrade.cjs index b3d76116..9d4d8ae9 100644 --- a/cli/src/internal/maintenance/panelUpgrade.cjs +++ b/cli/src/internal/maintenance/panelUpgrade.cjs @@ -182,8 +182,12 @@ async function getStatus(tmp) { // 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) { + if ( + active.has(state.status) && + state.id === previous.id && + state.pid === previous.pid && + state.startedAt === previous.startedAt + ) { state.status = 'failed'; state.error = '升级任务意外中断,请重试'; } diff --git a/cli/src/internal/maintenance/platformBundle.cjs b/cli/src/internal/maintenance/platformBundle.cjs index be31be85..58a496a6 100644 --- a/cli/src/internal/maintenance/platformBundle.cjs +++ b/cli/src/internal/maintenance/platformBundle.cjs @@ -212,14 +212,18 @@ async function smokeDependencies(source, signal) { `; // Match the server's normal runtime. Node 20.18's built-in HTTP parser needs // WebAssembly, which --jitless disables; only archive workers need that flag. - await execute(process.execPath, [...serverRuntimeArgs(process), '-e', probe], { - cwd: source, - env: { ...process.env, NODE_PATH: '', NODE_OPTIONS: '' }, - // ARM1176 devices need the same startup allowance as the backend probe. - // Keep this bounded and cancellable without forcing an unnecessary repair. - timeout: nodeRuntimeArgs().length ? 300000 : 30000, - signal, - }); + await execute( + process.execPath, + [...serverRuntimeArgs(process), '-e', probe], + { + cwd: source, + env: { ...process.env, NODE_PATH: '', NODE_OPTIONS: '' }, + // ARM1176 devices need the same startup allowance as the backend probe. + // Keep this bounded and cancellable without forcing an unnecessary repair. + timeout: nodeRuntimeArgs().length ? 300000 : 30000, + signal, + }, + ); } async function extractArchive(archive, destination) { diff --git a/cli/src/internal/maintenance/upgradePrestart.cjs b/cli/src/internal/maintenance/upgradePrestart.cjs index d37fc6bb..e22e97b9 100644 --- a/cli/src/internal/maintenance/upgradePrestart.cjs +++ b/cli/src/internal/maintenance/upgradePrestart.cjs @@ -51,7 +51,8 @@ function childGroupSignaler(child) { return (signal) => { if (finished) return; try { - if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal); + if (process.platform !== 'win32' && child.pid) + process.kill(-child.pid, signal); else child.kill(signal); if (signal === 'SIGKILL') finished = true; } catch (error) { @@ -141,7 +142,11 @@ async function prestartBackend( // one backend process. Keep normal V8 mode for Node 20's HTTP/WASM support. const child = spawn( process.execPath, - [...serverRuntimeArgs(), `--max-old-space-size=${limits.heapMb}`, entry], + [ + ...serverRuntimeArgs(), + `--max-old-space-size=${limits.heapMb}`, + entry, + ], { cwd: workspace, env, @@ -154,7 +159,11 @@ async function prestartBackend( } catch {} const signalGroup = childGroupSignaler(child); const kill = (signalName) => { - try { signalGroup(signalName); } catch (error) { failure ||= error; } + try { + signalGroup(signalName); + } catch (error) { + failure ||= error; + } }; const stop = (error) => { failure ||= error; @@ -346,7 +355,9 @@ async function runRepair(program, args, options) { }); const signalGroup = childGroupSignaler(child); const kill = (sig) => { - try { signalGroup(sig); } catch {} + try { + signalGroup(sig); + } catch {} }; const stop = (error) => { failure ||= error; diff --git a/cli/src/internal/runtime/api.ts b/cli/src/internal/runtime/api.ts index ef9b9055..9c6f47d7 100644 --- a/cli/src/internal/runtime/api.ts +++ b/cli/src/internal/runtime/api.ts @@ -78,9 +78,11 @@ export class LocalApi { const port = this.context.env.QlPort || '5700'; if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) fail(translate(this.context.env, '本机面板端口无效。'), 2); - const retryReceipt = isRecord(body) && !!(body.execution_id || body.trigger_id) && + const retryReceipt = + isRecord(body) && + !!(body.execution_id || body.trigger_id) && ((method === 'PUT' && endpoint === 'crons/status') || - (method === 'POST' && endpoint === 'dashboard/record')); + (method === 'POST' && endpoint === 'dashboard/record')); const payload = body === undefined ? undefined : JSON.stringify(body); let result: unknown; for (let attempt = 0; attempt < 2; attempt++) { @@ -92,7 +94,9 @@ export class LocalApi { method, headers: { Authorization: `Bearer ${token}`, - ...(finishedAt !== undefined && { 'X-QL-Finished-At': String(finishedAt) }), + ...(finishedAt !== undefined && { + 'X-QL-Finished-At': String(finishedAt), + }), ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), @@ -103,12 +107,24 @@ export class LocalApi { }, ); if (!response.ok) { - if (attempt === 0 && method === 'PUT' && endpoint === 'crons/status' && response.status === 400) { + 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])) { + 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 { @@ -126,7 +142,13 @@ export class LocalApi { break; } catch (error) { if (error instanceof ReceiptValidationError) throw error; - if (attempt === 0 && retryReceipt && request.signal.aborted && !operationSignal()?.aborted) continue; + if ( + attempt === 0 && + retryReceipt && + request.signal.aborted && + !operationSignal()?.aborted + ) + continue; fail( translate( this.context.env, diff --git a/cli/src/internal/runtime/commandLog.ts b/cli/src/internal/runtime/commandLog.ts index 5f09c68e..ce0b6a8e 100644 --- a/cli/src/internal/runtime/commandLog.ts +++ b/cli/src/internal/runtime/commandLog.ts @@ -32,7 +32,9 @@ export async function loggedOperation( .join('-'); const receipt = new LifecycleReceipt(context, started); const triggerId = receipt.triggerId; - const logPath = context.env.real_log_path || `${action}/${stamp}${triggerId ? '-' + triggerId : ''}.log`; + 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 }); @@ -48,14 +50,19 @@ export async function loggedOperation( const report = async (final: boolean, code: number) => { if (!Number.isSafeInteger(id) || id <= 0) return; try { - 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 ? code : undefined); + 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 ? code : undefined, + ); } catch { output( Buffer.from( diff --git a/cli/src/internal/runtime/lifecycle.ts b/cli/src/internal/runtime/lifecycle.ts index 423405eb..c59d1319 100644 --- a/cli/src/internal/runtime/lifecycle.ts +++ b/cli/src/internal/runtime/lifecycle.ts @@ -22,14 +22,18 @@ export class LifecycleReceipt { this.triggerId = parent; this.identity = { trigger_id: parent }; } else { - const prefix = context.env.QL_EXECUTION_ORIGIN === 'scheduled_system' - ? `legacy-system:${started}:` : 'client-'; + const prefix = + context.env.QL_EXECUTION_ORIGIN === 'scheduled_system' + ? `legacy-system:${started}:` + : 'client-'; this.identity = { execution_id: prefix + randomUUID() }; } } get executionId() { - return this.identity && 'execution_id' in this.identity ? this.identity.execution_id : undefined; + return this.identity && 'execution_id' in this.identity + ? this.identity.execution_id + : undefined; } async status(body: Record, exitCode?: number) { @@ -38,15 +42,27 @@ export class LifecycleReceipt { 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); + 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') { + } else if ( + !starting && + !this.identity && + this.extended && + error.field === 'exit_code' + ) { this.extended = false; } else { throw error; @@ -58,6 +74,11 @@ export class LifecycleReceipt { 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); + await this.api.call( + 'dashboard/record', + 'POST', + { ref_id: refId, code, elapsed, ...this.identity }, + this.finishedAt, + ); } } diff --git a/cli/src/internal/runtime/process.ts b/cli/src/internal/runtime/process.ts index bb62b2de..2b851811 100644 --- a/cli/src/internal/runtime/process.ts +++ b/cli/src/internal/runtime/process.ts @@ -124,7 +124,8 @@ export async function runProcess( terminate(cancellationSignal(options.signal)); }; const startTimeout = () => { - if (!options.timeoutMs || options.timeoutMs <= 0 || timedOut || aborted) return; + if (!options.timeoutMs || options.timeoutMs <= 0 || timedOut || aborted) + return; clearTimeout(timeout); timeout = setTimeout(() => { timedOut = true; @@ -184,20 +185,21 @@ export async function runProcess( else capture(chunk); }); if (options.captureFd === 3) child.stdio[3]!.on('data', capture); - if (options.timeoutControl) child.stdio[3]!.on('data', (chunk: Buffer) => { - for (const phase of chunk.toString()) { - if (phase === 'T') startTimeout(); - if (phase === 'A') { - cleanupStarted = true; - clearTimeout(timeout); - // Allow the Shell's cleanup to finish after a cooperative timeout. - if (timedOut && !aborted) { - clearTimeout(escalation); - escalation = undefined; + if (options.timeoutControl) + child.stdio[3]!.on('data', (chunk: Buffer) => { + for (const phase of chunk.toString()) { + if (phase === 'T') startTimeout(); + if (phase === 'A') { + cleanupStarted = true; + clearTimeout(timeout); + // Allow the Shell's cleanup to finish after a cooperative timeout. + if (timedOut && !aborted) { + clearTimeout(escalation); + escalation = undefined; + } } } - } - }); + }); child.stderr!.on('data', (chunk: Buffer) => emit(chunk, options.stderrOutput ?? options.output), ); diff --git a/cli/src/internal/subscription/subscriptionRunner.ts b/cli/src/internal/subscription/subscriptionRunner.ts index 57487e4a..5ffe915c 100644 --- a/cli/src/internal/subscription/subscriptionRunner.ts +++ b/cli/src/internal/subscription/subscriptionRunner.ts @@ -199,8 +199,15 @@ async function reconcile( await api.call( 'crons', 'DELETE', - 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 }) })), + 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( @@ -239,7 +246,11 @@ async function reconcile( // 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) { +async function checkNamespace( + root: string, + name: string, + env: NodeJS.ProcessEnv, +) { let current = root; for (const part of name.split('/')) { current = path.join(current, part); @@ -260,8 +271,12 @@ 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))); + 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 || diff --git a/cli/src/internal/subscription/worker.ts b/cli/src/internal/subscription/worker.ts index 5d08aeac..024f63b5 100644 --- a/cli/src/internal/subscription/worker.ts +++ b/cli/src/internal/subscription/worker.ts @@ -1,7 +1,10 @@ #!/usr/bin/env node import { translate } from '../../shared/i18n/index'; import { standaloneHelp } from '../help/standalone'; -import { withCommandCancellation, interruptedCode } from '../runtime/cancellation'; +import { + withCommandCancellation, + interruptedCode, +} from '../runtime/cancellation'; import { localContext } from '../runtime/context'; import { syncRaw, diff --git a/cli/src/remote/api/download.ts b/cli/src/remote/api/download.ts index 4956efdf..0b980989 100644 --- a/cli/src/remote/api/download.ts +++ b/cli/src/remote/api/download.ts @@ -14,7 +14,10 @@ export async function saveResponse( try { if (!response.body) throw new Error('Missing response body'); const stream = handle.createWriteStream(); - await pipeline(Readable.fromWeb(response.body as ReadableStream), stream); + await pipeline( + Readable.fromWeb(response.body as ReadableStream), + stream, + ); return { code: 200, data: { path, bytes: stream.bytesWritten } }; } catch (error) { await unlink(path).catch(() => undefined); diff --git a/cli/src/remote/api/openOperations.ts b/cli/src/remote/api/openOperations.ts index 20b6e855..3b473bab 100644 --- a/cli/src/remote/api/openOperations.ts +++ b/cli/src/remote/api/openOperations.ts @@ -115,7 +115,12 @@ 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 daily-results', + method: 'GET', + path: 'crons/:id/daily-results', + params: ['id'], + }, { name: 'task triggers', method: 'GET', @@ -291,7 +296,12 @@ export const openOperations: readonly OpenOperation[] = [ { 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 entries-check', + method: 'POST', + path: 'scripts/entries/check', + body: 'json', + }, { name: 'script history-list', method: 'GET', path: 'scripts/history' }, { name: 'script history-detail', @@ -337,7 +347,12 @@ 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 entries-check', + method: 'POST', + path: 'logs/entries/check', + body: 'json', + }, { name: 'log delete', method: 'DELETE', path: 'logs', body: 'json' }, { name: 'log download', diff --git a/cli/src/remote/auth/store.ts b/cli/src/remote/auth/store.ts index da5568b1..6c85a372 100644 --- a/cli/src/remote/auth/store.ts +++ b/cli/src/remote/auth/store.ts @@ -21,10 +21,7 @@ export function readConfig(): StoredConfig { const pathStat = fs.lstatSync(file); if (!pathStat.isFile()) fail( - translate( - process.env, - 'CLI 配置必须是普通文件,且不能是符号链接。', - ), + translate(process.env, 'CLI 配置必须是普通文件,且不能是符号链接。'), ); // Not every platform or filesystem implements POSIX mode bits or O_NOFOLLOW. const noFollow = fs.constants.O_NOFOLLOW ?? 0; @@ -36,10 +33,7 @@ export function readConfig(): StoredConfig { pathStat.ino !== stat.ino ) { fail( - translate( - process.env, - 'CLI 配置必须是普通文件,且不能是符号链接。', - ), + translate(process.env, 'CLI 配置必须是普通文件,且不能是符号链接。'), ); } const config: unknown = JSON.parse(fs.readFileSync(fd, 'utf8')); diff --git a/cli/src/remote/commands/dispatch.ts b/cli/src/remote/commands/dispatch.ts index e9f6cbda..7a1390b8 100644 --- a/cli/src/remote/commands/dispatch.ts +++ b/cli/src/remote/commands/dispatch.ts @@ -35,8 +35,27 @@ export async function dispatchRemote( }); const id = Number(positionals[0]); if (name === 'task logs') - return task({ kind: 'logs', id, tail: Number(values.tail) }); - return task({ kind: name.slice(5) as 'get' | 'run' | 'stop', id }); + return task({ + kind: 'logs', + id, + tail: Number(values.tail), + triggerId: values['trigger-id'] as string | undefined, + }); + if (name === 'task run') + return task({ + kind: 'run', + id, + wait: values.wait === true, + timeout: values.timeout === undefined ? 300 : Number(values.timeout), + }); + if (name === 'task wait') + return task({ + kind: 'wait', + id, + triggerId: values['trigger-id'] as string, + timeout: Number(values.timeout), + }); + return task({ kind: name.slice(5) as 'get' | 'stop', id }); } if (name.startsWith('subscription ')) { const { subscription } = await import('./subscription'); diff --git a/cli/src/remote/commands/open.ts b/cli/src/remote/commands/open.ts index 5ba7b30b..2944ca73 100644 --- a/cli/src/remote/commands/open.ts +++ b/cli/src/remote/commands/open.ts @@ -1,10 +1,7 @@ import { readFile, stat, lstat } from 'node:fs/promises'; import { openAsBlob } from 'node:fs'; import { basename } from 'node:path'; -import { - openOperations, - type OpenOperation, -} from '../api/openOperations'; +import { openOperations, type OpenOperation } from '../api/openOperations'; import { request, isRecord } from '../api/client'; import { session } from './auth'; import { panelUrl } from '../auth/url'; @@ -12,7 +9,6 @@ import { integer, type Invocation } from '../../shared/cli/arguments'; import { fail } from '../../shared/errors'; import type { ApiResponse } from '../../shared/types'; - function usage(zh: string, en: string): never { return fail(process.env.QL_LANG === 'en' ? en : zh, 2); } diff --git a/cli/src/remote/commands/registry.ts b/cli/src/remote/commands/registry.ts index a72aa053..0538c312 100644 --- a/cli/src/remote/commands/registry.ts +++ b/cli/src/remote/commands/registry.ts @@ -2,7 +2,20 @@ import { openCommands } from './openCommands'; import { openOperations } from '../api/openOperations'; import type { CommandSpec, CommandRegistry } from '../../shared/cli/registry'; import { integer } from '../../shared/cli/arguments'; +import { validTriggerId } from '../trigger'; +import { fail } from '../../shared/errors'; +import { translate } from '../../shared/i18n/index'; const positiveId = ''; +const waitTimeout = { + type: 'string' as const, + description: 'Maximum wait in seconds (default 300; does not stop the task)', + default: '300', + integer: { min: 1, max: 86400 }, +}; +const triggerOption = { + type: 'string' as const, + description: 'Exact trigger ID returned by task run', +}; export const commands: readonly CommandSpec[] = [ ...openCommands, { @@ -62,7 +75,7 @@ export const commands: readonly CommandSpec[] = [ }, }, }, - ...['get', 'run', 'stop'].map( + ...['get', 'stop'].map( (action): CommandSpec => ({ name: `task ${action}`, summary: `${action} a remote task by ID`, @@ -71,6 +84,31 @@ export const commands: readonly CommandSpec[] = [ maximum: 1, }), ), + { + name: 'task run', + summary: 'run a remote task by ID', + arguments: positiveId, + minimum: 1, + maximum: 1, + options: { + wait: { + type: 'boolean', + description: 'Wait for this run to finish successfully', + }, + timeout: { ...waitTimeout, default: undefined }, + }, + }, + { + name: 'task wait', + summary: 'Wait for an existing trigger without running the task again', + arguments: positiveId, + minimum: 1, + maximum: 1, + options: { + 'trigger-id': { ...triggerOption, required: true }, + timeout: waitTimeout, + }, + }, { name: 'task logs', summary: 'Read the latest task log', @@ -78,6 +116,7 @@ export const commands: readonly CommandSpec[] = [ minimum: 1, maximum: 1, options: { + 'trigger-id': triggerOption, tail: { type: 'string', short: 'n', @@ -126,6 +165,19 @@ export const registry: CommandRegistry = { options: {}, surface: 'public', validate(command) { + if ( + command.name === 'task run' && + command.values.timeout !== undefined && + !command.values.wait + ) { + fail(translate(process.env, '--timeout 需要与 --wait 一起使用。'), 2); + } + if ( + command.values['trigger-id'] !== undefined && + !validTriggerId(command.values['trigger-id']) + ) { + fail(translate(process.env, '触发 ID 无效。'), 2); + } if ( !openCommands.some((op) => op.name === command.name) && /^(task|subscription) /.test(command.name) && diff --git a/cli/src/remote/commands/subscription.ts b/cli/src/remote/commands/subscription.ts index 5ece907e..b9f943fe 100644 --- a/cli/src/remote/commands/subscription.ts +++ b/cli/src/remote/commands/subscription.ts @@ -5,7 +5,6 @@ import { session } from './auth'; import { fail } from '../../shared/errors'; import type { ApiResponse, LogResponse } from '../../shared/types'; - // Subscription API records can contain private repository credentials and hooks. // The management view deliberately exposes only the fields needed for selection. const visibleFields = [ diff --git a/cli/src/remote/commands/task.ts b/cli/src/remote/commands/task.ts index f3b18f30..d8dedc66 100644 --- a/cli/src/remote/commands/task.ts +++ b/cli/src/remote/commands/task.ts @@ -4,10 +4,11 @@ import { fail } from '../../shared/errors'; import type { ApiResponse, LogResponse } from '../../shared/types'; import type { Command, Task } from '../types'; import { session } from './auth'; +import { runReceipt, waitForTrigger } from './taskRun'; type TaskCommand = Extract< Command, - { kind: 'list' | 'get' | 'logs' | 'run' | 'stop' } + { kind: 'list' | 'get' | 'logs' | 'run' | 'stop' | 'wait' } >; function isTask(value: unknown): value is Task { @@ -23,6 +24,15 @@ export async function task( command: TaskCommand, ): Promise | LogResponse> { const config = await session(); + if (command.kind === 'wait') { + return waitForTrigger( + config, + command.id, + command.triggerId, + command.timeout, + 'wait', + ); + } if (command.kind === 'list') { const query = new URLSearchParams({ page: String(command.page), @@ -50,7 +60,18 @@ export async function task( return { code: 200, data: result.data }; } if (command.kind === 'logs') { - const result = await request(config, `crons/${command.id}/log`); + const query = command.triggerId + ? `?${new URLSearchParams({ triggerId: command.triggerId })}` + : ''; + const result = await request(config, `crons/${command.id}/log${query}`); + if (command.triggerId && result.triggerId !== command.triggerId) { + fail( + translate( + process.env, + '面板未确认日志所属的触发 ID,已拒绝返回可能属于其他轮次的日志。', + ), + ); + } if ( typeof result.data !== 'string' || (result.logStatus !== undefined && typeof result.logStatus !== 'string') @@ -63,14 +84,39 @@ export async function task( data: lines.slice(-command.tail).join('\n'), logStatus: result.logStatus as string | undefined, truncated: result.truncated === true || lines.length > command.tail, + ...(command.triggerId ? { triggerId: command.triggerId } : {}), }; } - await request(config, `crons/${command.kind}`, { + const result = await request(config, `crons/${command.kind}`, { method: 'PUT', body: [command.id], }); + const receipt = + command.kind === 'run' ? runReceipt(result, command.id) : undefined; + if (command.kind === 'run' && command.wait) { + if (!receipt) { + fail( + translate( + process.env, + '运行请求已提交,但面板未返回 triggerId,无法等待本轮执行。请检查任务状态,不要直接重试运行。', + ), + ); + } + return waitForTrigger( + config, + command.id, + receipt.triggerId, + command.timeout ?? 300, + 'run', + ); + } return { code: 200, - data: { taskId: command.id, action: command.kind, accepted: true }, + data: { + taskId: command.id, + action: command.kind, + accepted: true, + ...receipt, + }, }; } diff --git a/cli/src/remote/commands/taskRun.ts b/cli/src/remote/commands/taskRun.ts new file mode 100644 index 00000000..68062cf9 --- /dev/null +++ b/cli/src/remote/commands/taskRun.ts @@ -0,0 +1,151 @@ +import { performance } from 'node:perf_hooks'; +import { setTimeout as delay } from 'node:timers/promises'; +import { isRecord, request } from '../api/client'; +import type { StoredConfig } from '../types'; +import { validTriggerId } from '../trigger'; +import { CliError, fail } from '../../shared/errors'; +import { CliResultError } from '../../shared/resultError'; +import { translate } from '../../shared/i18n/index'; + +const states = [ + 'queued', + 'running', + 'finished', + 'failed', + 'skipped', + 'stopped', + 'unknown', +]; + +export function runReceipt(result: Record, taskId: number) { + // Older panels return only {code:200}; keep the immediate-run contract. + if (result.data === undefined || result.data === null) return undefined; + const entries = Array.isArray(result.data) + ? result.data.filter((row) => isRecord(row) && row.taskId === taskId) + : []; + const row = entries[0]; + if ( + entries.length !== 1 || + !isRecord(row) || + !validTriggerId(row.triggerId) || + typeof row.state !== 'string' || + !['queued', 'skipped'].includes(row.state) || + !(row.reason === null || typeof row.reason === 'string') + ) { + fail( + translate( + process.env, + '运行响应未包含有效的本轮触发记录,请检查任务状态,不要直接重试运行。', + ), + ); + } + return { + triggerId: row.triggerId, + state: row.state, + reason: row.reason, + }; +} + +export async function waitForTrigger( + config: StoredConfig, + taskId: number, + triggerId: string, + timeout: number, + action: 'run' | 'wait', +) { + const data = { + taskId, + action, + triggerId, + ...(action === 'run' ? { accepted: true } : {}), + }; + const deadline = performance.now() + timeout * 1000; + const timedOut = () => + new CliResultError( + translate( + process.env, + '等待触发 %s 超时;任务未被停止或重新运行,可用 task wait 继续等待。', + triggerId, + ), + { ...data, waitStatus: 'timeout' }, + ); + const query = new URLSearchParams({ ids: triggerId }); + while (true) { + const remaining = deadline - performance.now(); + if (remaining <= 0) throw timedOut(); + let result: Record; + try { + result = await request(config, `crons/${taskId}/triggers?${query}`, { + timeoutMs: Math.max(1, Math.ceil(Math.min(30000, remaining))), + }); + } catch (error) { + if (performance.now() >= deadline) throw timedOut(); + if (error instanceof CliError) { + throw new CliResultError( + translate( + process.env, + '等待触发 %s 中断:%s 不会重试运行,可用 task wait 继续等待。', + triggerId, + error.message, + ), + { ...data, waitStatus: 'interrupted' }, + error.exitCode, + ); + } + throw error; + } + if (performance.now() >= deadline) throw timedOut(); + const rows = result.data; + if (Array.isArray(rows) && rows.length === 0) { + throw new CliResultError( + translate( + process.env, + '触发 %s 不存在、已清理或不属于该任务,无法确认执行结果。', + triggerId, + ), + { ...data, waitStatus: 'notFound' }, + ); + } + const row = Array.isArray(rows) && rows.length === 1 ? rows[0] : undefined; + if ( + !isRecord(row) || + row.id !== triggerId || + row.cron_id !== taskId || + typeof row.state !== 'string' || + !states.includes(row.state) || + !(row.reason === null || typeof row.reason === 'string') || + !(row.exit_code === null || Number.isInteger(row.exit_code)) + ) { + throw new CliResultError( + translate( + process.env, + '触发 %s 的查询响应无效或与请求不匹配,无法确认执行结果。', + triggerId, + ), + { ...data, waitStatus: 'invalidResponse' }, + ); + } + if (row.state !== 'queued' && row.state !== 'running') { + const outcome = { + ...data, + state: row.state, + reason: row.reason, + exitCode: row.exit_code, + }; + if (row.state === 'finished' && row.exit_code === 0) { + return { code: 200 as const, data: outcome }; + } + throw new CliResultError( + translate( + process.env, + '触发 %s 未成功完成(状态 %s,退出码 %s)。', + triggerId, + row.state, + row.exit_code ?? '-', + ), + outcome, + ); + } + await delay(Math.max(1, Math.min(1000, deadline - performance.now()))); + } +} diff --git a/cli/src/remote/trigger.ts b/cli/src/remote/trigger.ts new file mode 100644 index 00000000..d1eb5922 --- /dev/null +++ b/cli/src/remote/trigger.ts @@ -0,0 +1,3 @@ +export function validTriggerId(value: unknown): value is string { + return typeof value === 'string' && /^[a-zA-Z0-9_:.-]{1,256}$/.test(value); +} diff --git a/cli/src/remote/types.ts b/cli/src/remote/types.ts index 2d8fa040..7aa5685e 100644 --- a/cli/src/remote/types.ts +++ b/cli/src/remote/types.ts @@ -32,5 +32,7 @@ export type Command = | { kind: 'logout' } | { kind: 'list'; search?: string; page: number; size: number } | { kind: 'get'; id: number } - | { kind: 'logs'; id: number; tail: number } - | { kind: 'run' | 'stop'; id: number }; + | { kind: 'logs'; id: number; tail: number; triggerId?: string } + | { kind: 'run'; id: number; wait?: boolean; timeout?: number } + | { kind: 'wait'; id: number; triggerId: string; timeout: number } + | { kind: 'stop'; id: number }; diff --git a/cli/src/shared/cli/invoke.ts b/cli/src/shared/cli/invoke.ts index 5524db5a..474c4c39 100644 --- a/cli/src/shared/cli/invoke.ts +++ b/cli/src/shared/cli/invoke.ts @@ -1,6 +1,7 @@ import { parse } from './arguments'; import { translate } from '../i18n/index'; import { CliError } from '../errors'; +import { CliResultError } from '../resultError'; import type { Invocation } from './arguments'; import type { CommandRegistry } from './registry'; @@ -42,7 +43,15 @@ export async function invoke( ? error.message : translate(process.env, 'CLI 操作失败,请检查本机配置和权限。'); process.stderr.write( - (json ? JSON.stringify({ code, message }) : message) + '\n', + (json + ? JSON.stringify({ + code, + message, + ...(!cancelled && error instanceof CliResultError + ? { data: error.data } + : {}), + }) + : message) + '\n', ); return code; } diff --git a/cli/src/shared/cli/options.ts b/cli/src/shared/cli/options.ts index 2e4d3772..02a6169e 100644 --- a/cli/src/shared/cli/options.ts +++ b/cli/src/shared/cli/options.ts @@ -25,7 +25,9 @@ export function addFlags( const seen = new Set(); for (const [name, definition] of Object.entries(schema)) { const option = new Option( - `${definition.short ? `-${definition.short}, ` : ''}--${name}${definition.type === 'string' ? ' ' : ''}`, + `${definition.short ? `-${definition.short}, ` : ''}--${name}${ + definition.type === 'string' ? ' ' : '' + }`, definition.description, ); // --no-startup is a positive application flag, not Commander negation. @@ -47,7 +49,7 @@ export function flagValues( const raw = command.opts(); const result: Record = {}; for (const name of Object.keys(schema)) { - const option = command.options.find(item => item.long === `--${name}`)!; + const option = command.options.find((item) => item.long === `--${name}`)!; if (raw[option.attributeName()] !== undefined) result[name] = raw[option.attributeName()]; } @@ -70,10 +72,13 @@ export function assertOptionValues( } let expectsValue = false; if (token.startsWith('--')) { - if (!token.includes('=')) expectsValue = schema[token.slice(2)]?.type === 'string'; + if (!token.includes('=')) + expectsValue = schema[token.slice(2)]?.type === 'string'; } else { for (let offset = 1; offset < token.length; offset++) { - const definition = Object.values(schema).find(option => option.short === token[offset]); + const definition = Object.values(schema).find( + (option) => option.short === token[offset], + ); if (!definition) break; if (definition.type === 'string') { expectsValue = offset === token.length - 1; @@ -84,7 +89,11 @@ export function assertOptionValues( if (expectsValue) { const next = args[++index]; if (next === undefined || (next.length > 1 && next.startsWith('-'))) - throw new CommanderError(2, 'commander.optionMissingArgument', 'Missing option value'); + throw new CommanderError( + 2, + 'commander.optionMissingArgument', + 'Missing option value', + ); } } } @@ -93,13 +102,16 @@ export function parseFlags( args: string[], schema: Record, options: { passThrough?: boolean; rejectDuplicates?: boolean } = {}, -): { values: Record; positionals: string[] } { +): { + values: Record; + positionals: string[]; +} { const command = quietCommand('ql').allowExcessArguments(true); if (options.passThrough) command.passThroughOptions(); addFlags(command, schema, options.rejectDuplicates ?? true); assertOptionValues(args, schema, options.passThrough); - command.parse(args, { from:'user' }); - return { values:flagValues(command, schema), positionals:command.args }; + command.parse(args, { from: 'user' }); + return { values: flagValues(command, schema), positionals: command.args }; } export function isArgumentError(error: unknown): boolean { diff --git a/cli/src/shared/cli/router.ts b/cli/src/shared/cli/router.ts index 757871ec..5974d6bc 100644 --- a/cli/src/shared/cli/router.ts +++ b/cli/src/shared/cli/router.ts @@ -10,14 +10,25 @@ export async function routeCommands( fallback: () => Promise, ): Promise { let result: number | undefined; - const root = quietCommand(name).enablePositionalOptions() - .passThroughOptions().allowUnknownOption().argument('[arguments...]'); - root.action(async () => { result = await fallback(); }); + const root = quietCommand(name) + .enablePositionalOptions() + .passThroughOptions() + .allowUnknownOption() + .argument('[arguments...]'); + root.action(async () => { + result = await fallback(); + }); for (const [command, handler] of Object.entries(handlers)) { - root.addCommand(quietCommand(command).allowUnknownOption() - .allowExcessArguments(true).passThroughOptions() - .action(async () => { result = await handler(args.slice(1)); })); + root.addCommand( + quietCommand(command) + .allowUnknownOption() + .allowExcessArguments(true) + .passThroughOptions() + .action(async () => { + result = await handler(args.slice(1)); + }), + ); } - await root.parseAsync(args, { from:'user' }); - return result ?? await fallback(); + await root.parseAsync(args, { from: 'user' }); + return result ?? (await fallback()); } diff --git a/cli/src/shared/i18n/en.ts b/cli/src/shared/i18n/en.ts index dc6e5a46..7de3426a 100644 --- a/cli/src/shared/i18n/en.ts +++ b/cli/src/shared/i18n/en.ts @@ -31,6 +31,24 @@ export const english: Record = { 'Local API rejected request. Check panel logs and permissions.', '任务列表响应无效。': 'Invalid task list response.', '任务响应无效。': 'Invalid task response.', + '触发 ID 无效。': 'Invalid trigger ID.', + '--timeout 需要与 --wait 一起使用。': '--timeout requires --wait.', + '运行响应未包含有效的本轮触发记录,请检查任务状态,不要直接重试运行。': + 'The run response has no valid receipt for this task. Check task status; do not blindly retry the run.', + '运行请求已提交,但面板未返回 triggerId,无法等待本轮执行。请检查任务状态,不要直接重试运行。': + 'The run request was submitted, but the panel returned no triggerId. Cannot wait for this run. Check task status; do not blindly retry the run.', + '面板未确认日志所属的触发 ID,已拒绝返回可能属于其他轮次的日志。': + 'The panel did not confirm the log trigger ID. Refusing to return logs that may belong to another run.', + '等待触发 %s 超时;任务未被停止或重新运行,可用 task wait 继续等待。': + 'Timed out waiting for trigger %s. The task was not stopped or rerun; use task wait to resume waiting.', + '等待触发 %s 中断:%s 不会重试运行,可用 task wait 继续等待。': + 'Waiting for trigger %s was interrupted: %s The run will not be retried; use task wait to resume waiting.', + '触发 %s 不存在、已清理或不属于该任务,无法确认执行结果。': + 'Trigger %s does not exist, was pruned, or belongs to another task. Cannot confirm the execution result.', + '触发 %s 的查询响应无效或与请求不匹配,无法确认执行结果。': + 'The query response for trigger %s is invalid or does not match the request. Cannot confirm the execution result.', + '触发 %s 未成功完成(状态 %s,退出码 %s)。': + 'Trigger %s did not finish successfully (state %s, exit code %s).', '日志响应无效。': 'Invalid log response.', '订阅响应无效。': 'Invalid subscription response.', '订阅列表响应无效。': 'Invalid subscription list response.', diff --git a/cli/src/shared/i18n/help.ts b/cli/src/shared/i18n/help.ts index 1daa7027..34e869bc 100644 --- a/cli/src/shared/i18n/help.ts +++ b/cli/src/shared/i18n/help.ts @@ -1,6 +1,8 @@ const chinese: Record = { - 'Query object as JSON, @file or - for stdin': '查询参数 JSON;支持 @文件或 - 从 stdin 读取', - 'Request body as JSON, @file or - for stdin': '请求体 JSON;支持 @文件或 - 从 stdin 读取', + 'Query object as JSON, @file or - for stdin': + '查询参数 JSON;支持 @文件或 - 从 stdin 读取', + 'Request body as JSON, @file or - for stdin': + '请求体 JSON;支持 @文件或 - 从 stdin 读取', 'Request timeout in seconds': '请求超时秒数(默认 30,最多 3600)', 'Local file to upload': '要上传的本机文件', 'Save response to a new local file': '响应保存到新文件(不覆盖已有文件)', @@ -8,9 +10,11 @@ const chinese: Record = { 'Command executed by the remote panel': '由远程面板执行的命令', 'Cron schedule': '定时规则', 'Comma-separated application permissions': '应用权限,用逗号分隔', - 'Explicitly include application credentials in output': '显式输出应用密钥(默认隐藏)', + 'Explicitly include application credentials in output': + '显式输出应用密钥(默认隐藏)', 'Call a registered OpenAPI route': '调用已登记的 OpenAPI 路由', - 'List supported OpenAPI routes and commands': '列出支持的 OpenAPI 路由和对应命令', + 'List supported OpenAPI routes and commands': + '列出支持的 OpenAPI 路由和对应命令', 'Subscription type': '订阅类型:public-repo/private-repo/file', 'Subscription url': '订阅地址', 'Subscription alias': '订阅别名', @@ -32,6 +36,12 @@ const chinese: Record = { 'Page number': '页码', 'Page size': '每页数量', 'Read the latest task log': '读取最新任务日志', + 'Maximum wait in seconds (default 300; does not stop the task)': + '最长等待秒数(默认 300;不会停止任务)', + 'Exact trigger ID returned by task run': 'task run 返回的本轮触发 ID', + 'Wait for this run to finish successfully': '等待本轮执行成功完成', + 'Wait for an existing trigger without running the task again': + '等待已有触发结果,不会重新运行任务', 'Last N lines': '最后 N 行', 'List panel subscriptions': '列出面板订阅', 'Search subscriptions': '搜索订阅', diff --git a/cli/src/shared/resultError.ts b/cli/src/shared/resultError.ts new file mode 100644 index 00000000..ca9170c7 --- /dev/null +++ b/cli/src/shared/resultError.ts @@ -0,0 +1,12 @@ +import { CliError, type ExitCode } from './errors'; + +// Opt-in structured context for commands that have already identified an operation. +export class CliResultError extends CliError { + constructor( + message: string, + readonly data: Record, + exitCode: ExitCode = 1, + ) { + super(message, exitCode); + } +} diff --git a/cli/src/shared/types.ts b/cli/src/shared/types.ts index 752f8d68..46f0ad10 100644 --- a/cli/src/shared/types.ts +++ b/cli/src/shared/types.ts @@ -4,6 +4,7 @@ export interface ApiResponse { } export interface LogResponse extends ApiResponse { + triggerId?: string; logStatus?: string; truncated: boolean; } diff --git a/cli/test/integration/differential.test.cjs b/cli/test/integration/differential.test.cjs index 76a0e348..ff90ed33 100644 --- a/cli/test/integration/differential.test.cjs +++ b/cli/test/integration/differential.test.cjs @@ -4,7 +4,10 @@ const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); const { execFileSync, spawnSync } = require('node:child_process'); -const { createContext, sourceEnvironment } = require('../../dist/internal/runtime/context'); +const { + createContext, + sourceEnvironment, +} = require('../../dist/internal/runtime/context'); const { executeTask } = require('../../dist/internal/execution/taskRunner'); test('Shell and CLI agree on isolated script state and account modes', async (t) => { @@ -31,7 +34,14 @@ test('Shell and CLI agree on isolated script state and account modes', async (t) path.join(root, 'static/build'), ]) await fs.mkdir(directory, { recursive: true }); - for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh']) + for (const name of [ + 'task.sh', + 'task-timeout.sh', + 'otask.sh', + 'share.sh', + 'api.sh', + 'env.sh', + ]) await fs.copyFile( path.resolve(__dirname, '../../../shell', name), path.join(context.paths.dir_shell, name), @@ -406,9 +416,12 @@ test('configuration shell options survive the environment bridge for pipeline an assert.ok(env.SHELLOPTS.split(':').includes('pipefail')); assert.ok(!env.SHELLOPTS.split(':').includes('allexport')); // Bash 3.x cannot import BASHOPTS itself; exercise the actual CLI bridge. - const execution = await require('../../dist/internal/runtime/process').runProcess( - 'bash', ['--noprofile', '--norc', '-c', probe], { env, capture: true }, - ); + const execution = + await require('../../dist/internal/runtime/process').runProcess( + 'bash', + ['--noprofile', '--norc', '-c', probe], + { env, capture: true }, + ); assert.equal(execution.code, 0); const modern = execution.stdout; assert.equal(modern, legacy); diff --git a/cli/test/integration/entrypointPaths.test.cjs b/cli/test/integration/entrypointPaths.test.cjs index 95cad7b6..28ef769c 100644 --- a/cli/test/integration/entrypointPaths.test.cjs +++ b/cli/test/integration/entrypointPaths.test.cjs @@ -9,19 +9,38 @@ const { installCliEntrypoints } = require('../../dist/local/entrypoints'); test('generated entries treat quotes, newlines and code-like paths as data', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-entry-paths-')); t.after(() => fs.rm(root, { recursive: true, force: true })); - const cliRoot = path.join(root, "CLI '中文\n\");throw new Error('injected');//"); + const cliRoot = path.join( + root, + "CLI '中文\n\");throw new Error('injected');//", + ); const bin = path.join(root, 'bin'); await fs.mkdir(path.join(cliRoot, 'dist'), { recursive: true }); - await fs.writeFile(path.join(cliRoot, 'dist/ql.js'), 'exports.qlMain=async()=>{console.log(JSON.stringify(process.argv.slice(2)));return 7;};'); - await fs.writeFile(path.join(cliRoot, 'dist/task.js'), 'exports.taskMain=async()=>{throw new Error("secret-value");};'); + await fs.writeFile( + path.join(cliRoot, 'dist/ql.js'), + 'exports.qlMain=async()=>{console.log(JSON.stringify(process.argv.slice(2)));return 7;};', + ); + await fs.writeFile( + path.join(cliRoot, 'dist/task.js'), + 'exports.taskMain=async()=>{throw new Error("secret-value");};', + ); await installCliEntrypoints(bin, cliRoot); - const ql = spawnSync(process.execPath, [path.join(bin, 'ql'), '--literal', 'value'], { encoding: 'utf8' }); + const ql = spawnSync( + process.execPath, + [path.join(bin, 'ql'), '--literal', 'value'], + { encoding: 'utf8' }, + ); assert.equal(ql.status, 7, ql.stderr); assert.deepEqual(JSON.parse(ql.stdout), ['--literal', 'value']); for (const language of ['en', 'zh']) { - const result = spawnSync(process.execPath, [path.join(bin, 'task')], { encoding: 'utf8', env: { QL_LANG: language } }); + const result = spawnSync(process.execPath, [path.join(bin, 'task')], { + encoding: 'utf8', + env: { QL_LANG: language }, + }); assert.equal(result.status, 1); - assert.equal(result.stderr, language === 'en' ? 'CLI invocation failed.\n' : 'CLI 调用失败。\n'); + assert.equal( + result.stderr, + language === 'en' ? 'CLI invocation failed.\n' : 'CLI 调用失败。\n', + ); assert.doesNotMatch(result.stderr, /secret-value/); } }); diff --git a/cli/test/integration/executablePaths.test.cjs b/cli/test/integration/executablePaths.test.cjs index 8cbf8013..899e72e7 100644 --- a/cli/test/integration/executablePaths.test.cjs +++ b/cli/test/integration/executablePaths.test.cjs @@ -5,23 +5,59 @@ const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); -test('legacy Shell and TS resolve executable paths after selecting the working directory', t => { - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ql-executable-'))); +test('legacy Shell and TS resolve executable paths after selecting the working directory', (t) => { + const root = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), 'ql-executable-')), + ); t.after(() => fs.rmSync(root, { recursive: true, force: true })); - for (const dir of ['shell/preload', 'shell/lang', 'data/config', 'data/scripts/bin', 'data/scripts/custom', 'data/log', 'static/build', 'bin']) + for (const dir of [ + 'shell/preload', + 'shell/lang', + 'data/config', + 'data/scripts/bin', + 'data/scripts/custom', + 'data/log', + 'static/build', + 'bin', + ]) fs.mkdirSync(path.join(root, dir), { recursive: true }); - for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh']) - fs.copyFileSync(path.resolve(__dirname, '../../../shell', name), path.join(root, 'shell', name)); + for (const name of [ + 'task.sh', + 'task-timeout.sh', + 'otask.sh', + 'share.sh', + 'api.sh', + 'env.sh', + ]) + fs.copyFileSync( + path.resolve(__dirname, '../../../shell', name), + path.join(root, 'shell', name), + ); for (const name of ['zh.sh', 'en.sh']) - fs.copyFileSync(path.resolve(__dirname, '../../../shell/lang', name), path.join(root, 'shell/lang', name)); + fs.copyFileSync( + path.resolve(__dirname, '../../../shell/lang', name), + path.join(root, 'shell/lang', name), + ); fs.symlinkSync(process.execPath, path.join(root, 'bin/node')); - fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); - fs.writeFileSync(path.join(root, 'static/build/token.js'), 'process.stdout.write("fixture")'); - fs.writeFileSync(path.join(root, 'data/config/config.sh'), - 'no_tee=true\nmy_task() { printf "%s\\n" "$PWD" "$@" > "$TRACE"; }\n'); + fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { + mode: 0o755, + }); + fs.writeFileSync( + path.join(root, 'static/build/token.js'), + 'process.stdout.write("fixture")', + ); + fs.writeFileSync( + path.join(root, 'data/config/config.sh'), + 'no_tee=true\nmy_task() { printf "%s\\n" "$PWD" "$@" > "$TRACE"; }\n', + ); fs.writeFileSync(path.join(root, 'data/config/crontab.list'), ''); const script = '#!/bin/sh\nprintf "%s\\n" "$PWD" "$@" > "$TRACE"\n'; - for (const file of ['data/scripts/bin/tool', 'data/scripts/bin/tool.exe', 'data/scripts/custom/tool', 'bin/path-tool']) + for (const file of [ + 'data/scripts/bin/tool', + 'data/scripts/bin/tool.exe', + 'data/scripts/custom/tool', + 'bin/path-tool', + ]) fs.writeFileSync(path.join(root, file), script, { mode: 0o755 }); const cases = [ ['bin/tool', '', 'bin'], @@ -36,56 +72,116 @@ test('legacy Shell and TS resolve executable paths after selecting the working d for (const [program, workDir, directory] of cases) { for (const [label, command, prefix] of [ ['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]], - ['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]], + [ + 'ts', + process.execPath, + [path.resolve(__dirname, '../../dist/runner.js'), '--root', root], + ], ]) { const trace = path.join(root, `${label}.trace`); fs.rmSync(trace, { force: true }); - const result = spawnSync(command, [...prefix, program, 'first', 'two words'], { - env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, QL_DIR: root, work_dir: workDir, TRACE: trace }, - encoding: 'utf8', timeout: 15000, - }); + const result = spawnSync( + command, + [...prefix, program, 'first', 'two words'], + { + env: { + PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, + QL_DIR: root, + work_dir: workDir, + TRACE: trace, + }, + encoding: 'utf8', + timeout: 15000, + }, + ); assert.equal(result.status, 0, `${label}/${program}: ${result.stderr}`); - assert.equal(fs.readFileSync(trace, 'utf8'), - `${path.join(root, 'data/scripts', directory)}\nfirst\ntwo words\n`, `${label}/${program}`); + assert.equal( + fs.readFileSync(trace, 'utf8'), + `${path.join(root, 'data/scripts', directory)}\nfirst\ntwo words\n`, + `${label}/${program}`, + ); } } // A builtin has no executable file. Function arguments must remain literal. - for (const args of [[':', 'unused'], ['my_task', '$(touch INJECTED)', '; exit 9']]) { - const result = spawnSync(process.execPath, - [path.resolve(__dirname, '../../dist/runner.js'), '--root', root, '--json', ...args], { - env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, TRACE: path.join(root, 'literal.trace') }, - encoding: 'utf8', timeout: 15000, - }); + for (const args of [ + [':', 'unused'], + ['my_task', '$(touch INJECTED)', '; exit 9'], + ]) { + const result = spawnSync( + process.execPath, + [ + path.resolve(__dirname, '../../dist/runner.js'), + '--root', + root, + '--json', + ...args, + ], + { + env: { + PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, + TRACE: path.join(root, 'literal.trace'), + }, + encoding: 'utf8', + timeout: 15000, + }, + ); assert.equal(result.status, 0, result.stderr); } - assert.equal(fs.readFileSync(path.join(root, 'literal.trace'), 'utf8'), - `${path.join(root, 'data/scripts')}\n$(touch INJECTED)\n; exit 9\n`); + assert.equal( + fs.readFileSync(path.join(root, 'literal.trace'), 'utf8'), + `${path.join(root, 'data/scripts')}\n$(touch INJECTED)\n; exit 9\n`, + ); assert.equal(fs.existsSync(path.join(root, 'data/scripts/INJECTED')), false); - fs.writeFileSync(path.join(root, 'data/config/config.sh'), - 'no_tee=true\nSTATE=before\nmy_task() { export STATE=after; return 7; }\n'); - fs.writeFileSync(path.join(root, 'data/config/task_after.sh'), - 'printf "%s:%s" "$STATE" "$_task_exit_code" > "$TRACE.after"\n'); + fs.writeFileSync( + path.join(root, 'data/config/config.sh'), + 'no_tee=true\nSTATE=before\nmy_task() { export STATE=after; return 7; }\n', + ); + fs.writeFileSync( + path.join(root, 'data/config/task_after.sh'), + 'printf "%s:%s" "$STATE" "$_task_exit_code" > "$TRACE.after"\n', + ); for (const dir of ['', 'custom']) - fs.writeFileSync(path.join(root, 'data/scripts', dir, 'show.sh'), - 'printf "%s" "$PWD" > "$TRACE"\n'); + fs.writeFileSync( + path.join(root, 'data/scripts', dir, 'show.sh'), + 'printf "%s" "$PWD" > "$TRACE"\n', + ); for (const scenario of ['function-state', 'hook-directory']) { - fs.writeFileSync(path.join(root, 'data/config/task_before.sh'), - scenario === 'hook-directory' ? 'work_dir=custom\n' : ''); - const args = scenario === 'function-state' ? ['my_task'] : ['show.sh', 'now']; + fs.writeFileSync( + path.join(root, 'data/config/task_before.sh'), + scenario === 'hook-directory' ? 'work_dir=custom\n' : '', + ); + const args = + scenario === 'function-state' ? ['my_task'] : ['show.sh', 'now']; for (const [label, command, prefix] of [ ['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]], - ['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]], + [ + 'ts', + process.execPath, + [path.resolve(__dirname, '../../dist/runner.js'), '--root', root], + ], ]) { const trace = path.join(root, `${scenario}-${label}`); const result = spawnSync(command, [...prefix, ...args], { - env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, QL_DIR: root, TRACE: trace }, - encoding: 'utf8', timeout: 15000, + env: { + PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, + QL_DIR: root, + TRACE: trace, + }, + encoding: 'utf8', + timeout: 15000, }); - assert.equal(result.status, scenario === 'function-state' && label === 'ts' ? 7 : 0, result.stderr); + assert.equal( + result.status, + scenario === 'function-state' && label === 'ts' ? 7 : 0, + result.stderr, + ); if (scenario === 'function-state') assert.equal(fs.readFileSync(`${trace}.after`, 'utf8'), 'after:7'); else - assert.equal(fs.readFileSync(trace, 'utf8'), path.join(root, 'data/scripts/custom')); + assert.equal( + fs.readFileSync(trace, 'utf8'), + path.join(root, 'data/scripts/custom'), + ); } } }); diff --git a/cli/test/integration/loadingBoundary.test.cjs b/cli/test/integration/loadingBoundary.test.cjs index 96c3cd1f..00bf570e 100644 --- a/cli/test/integration/loadingBoundary.test.cjs +++ b/cli/test/integration/loadingBoundary.test.cjs @@ -59,15 +59,21 @@ require(entry).main(JSON.parse(process.argv[2])).then(code => { if (args.includes('--help')) assert.ok( !result.modules.some((module) => - /^remote[/\\](commands[/\\](auth|open|task|subscription)\.js|api[/\\](client|download)\.js|auth[/\\])/.test(module), + /^remote[/\\](commands[/\\](auth|open|task|subscription)\.js|api[/\\](client|download)\.js|auth[/\\])/.test( + module, + ), ), 'Help eagerly loaded command implementation', ); if (args[0] === 'task' && !args.includes('--help')) - assert.ok(result.modules.includes(path.join('remote', 'commands', 'task.js'))); + assert.ok( + result.modules.includes(path.join('remote', 'commands', 'task.js')), + ); if (args[0] === 'subscription') assert.ok( - result.modules.includes(path.join('remote', 'commands', 'subscription.js')), + result.modules.includes( + path.join('remote', 'commands', 'subscription.js'), + ), ); } }); diff --git a/cli/test/integration/operatorRouting.test.cjs b/cli/test/integration/operatorRouting.test.cjs index c9e41364..f2f61dde 100644 --- a/cli/test/integration/operatorRouting.test.cjs +++ b/cli/test/integration/operatorRouting.test.cjs @@ -10,24 +10,41 @@ function invoke(args) { require('./cli/dist/internal/commands/dispatch').dispatch = async command => ({code:200,data:command}); require('./cli/dist/ql').qlMain(JSON.parse(process.argv[1])).then(code=>{process.exitCode=code});`; return spawnSync(process.execPath, ['-e', script, JSON.stringify(args)], { - cwd: path.resolve(__dirname, '../../..'), encoding: 'utf8', - env: { PATH: process.env.PATH, QL_LANG: 'en' }, timeout: 5000, + cwd: path.resolve(__dirname, '../../..'), + encoding: 'utf8', + env: { PATH: process.env.PATH, QL_LANG: 'en' }, + timeout: 5000, }); } test('direct maintenance commands and local aliases accept modern and legacy options identically', () => { for (const [args, name, values, positionals] of [ - [['update', '--mirror', 'gitee', '--download-only', '--root', '/isolated'], 'update', {mirror:'gitee', 'download-only':true, root:'/isolated'}, []], - [['update', 'false', '--root', '/isolated'], 'update', {'download-only':true, root:'/isolated'}, []], - [['update', 'true'], 'update', {mirror:'github'}, []], - [['reload', 'system', '--root', '/isolated'], 'reload', {target:'system', root:'/isolated'}, []], - [['reload', '--target', 'data'], 'reload', {target:'data'}, []], + [ + ['update', '--mirror', 'gitee', '--download-only', '--root', '/isolated'], + 'update', + { mirror: 'gitee', 'download-only': true, root: '/isolated' }, + [], + ], + [ + ['update', 'false', '--root', '/isolated'], + 'update', + { 'download-only': true, root: '/isolated' }, + [], + ], + [['update', 'true'], 'update', { mirror: 'github' }, []], + [ + ['reload', 'system', '--root', '/isolated'], + 'reload', + { target: 'system', root: '/isolated' }, + [], + ], + [['reload', '--target', 'data'], 'reload', { target: 'data' }, []], [['check'], 'check', {}, []], [['rmlog', '7'], 'rmlog', {}, ['7']], - [['start', '--no-startup'], 'start', {'no-startup':true}, []], + [['start', '--no-startup'], 'start', { 'no-startup': true }, []], [['repair-config'], 'repair-config', {}, []], [['resetpwd', '--', '-literal-value'], 'resetpwd', {}, ['-literal-value']], - [['update', '--root', 'false'], 'update', {root:'false'}, []], + [['update', '--root', 'false'], 'update', { root: 'false' }, []], ]) { const direct = invoke(['--json', ...args]); const alias = invoke(['--json', 'local', ...args]); @@ -37,15 +54,20 @@ test('direct maintenance commands and local aliases accept modern and legacy opt const command = JSON.parse(direct.stdout).data; assert.equal(command.name, `local ${name}`); assert.deepEqual(command.positionals, positionals); - for (const [key, value] of Object.entries(values)) assert.equal(command.values[key], value); + for (const [key, value] of Object.entries(values)) + assert.equal(command.values[key], value); } }); test('invalid maintenance options fail before dispatch; help recommends direct commands', () => { for (const args of [ - ['update', 'invalid'], ['reload', 'invalid'], ['update', 'false', 'extra'], - ['reload', 'system', '--target', 'data'], ['update', '--unknown'], - ['update', '--', 'false'], ['rmlog', '-1'], + ['update', 'invalid'], + ['reload', 'invalid'], + ['update', 'false', 'extra'], + ['reload', 'system', '--target', 'data'], + ['update', '--unknown'], + ['update', '--', 'false'], + ['rmlog', '-1'], ]) { const result = invoke(['--json', ...args]); assert.equal(result.status, 2, result.stderr); @@ -62,11 +84,13 @@ test('invalid maintenance options fail before dispatch; help recommends direct c } }); -test('direct and aliased maintenance preserve logs, lifecycle and single configuration evaluation', async t => { +test('direct and aliased maintenance preserve logs, lifecycle and single configuration evaluation', async (t) => { const fs = require('node:fs/promises'); const os = require('node:os'); const http = require('node:http'); - const exec = require('node:util').promisify(require('node:child_process').execFile); + const exec = require('node:util').promisify( + require('node:child_process').execFile, + ); for (const prefix of [[], ['local']]) { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-direct-extra-')); t.after(() => fs.rm(root, { recursive: true, force: true })); @@ -77,24 +101,61 @@ test('direct and aliased maintenance preserve logs, lifecycle and single configu reports.push({ url: req.url, data: JSON.parse(body) }); res.end(JSON.stringify({ code: 200 })); }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); try { await fs.mkdir(path.join(root, 'data/config'), { recursive: true }); - await fs.writeFile(path.join(root, 'data/config/config.sh'), 'no_tee=true\nprintf x >> "$QL_DIR/loads"\n'); - await fs.writeFile(path.join(root, 'data/config/token.json'), JSON.stringify({value:'fixture', expiration:Date.now()/1000+3600})); - await fs.writeFile(path.join(root, 'data/config/extra.sh'), 'printf "logged-extra\\n"\n'); - const result = await exec(process.execPath, [path.resolve(__dirname, '../../dist/ql.js'), ...prefix, 'extra', '--root', root, '--json'], { - env: {PATH:process.env.PATH, QlPort:String(server.address().port), ID:'9'}, timeout:10000, - }); + await fs.writeFile( + path.join(root, 'data/config/config.sh'), + 'no_tee=true\nprintf x >> "$QL_DIR/loads"\n', + ); + await fs.writeFile( + path.join(root, 'data/config/token.json'), + JSON.stringify({ + value: 'fixture', + expiration: Date.now() / 1000 + 3600, + }), + ); + await fs.writeFile( + path.join(root, 'data/config/extra.sh'), + 'printf "logged-extra\\n"\n', + ); + const result = await exec( + process.execPath, + [ + path.resolve(__dirname, '../../dist/ql.js'), + ...prefix, + 'extra', + '--root', + root, + '--json', + ], + { + env: { + PATH: process.env.PATH, + QlPort: String(server.address().port), + ID: '9', + }, + timeout: 10000, + }, + ); assert.equal(await fs.readFile(path.join(root, 'loads'), 'utf8'), 'x'); assert.equal(result.stderr, ''); const response = JSON.parse(result.stdout); assert.match(response.logPath, /^extra\//); - assert.match(await fs.readFile(path.join(root, 'data/log', response.logPath), 'utf8'), /logged-extra/); - assert.deepEqual(reports.map(report => report.data.status), ['0', '1']); - assert.ok(reports.every(report => report.url === '/open/crons/status')); + assert.match( + await fs.readFile( + path.join(root, 'data/log', response.logPath), + 'utf8', + ), + /logged-extra/, + ); + assert.deepEqual( + reports.map((report) => report.data.status), + ['0', '1'], + ); + assert.ok(reports.every((report) => report.url === '/open/crons/status')); } finally { - await new Promise(resolve => server.close(resolve)); + await new Promise((resolve) => server.close(resolve)); } } }); diff --git a/cli/test/integration/stdin.test.cjs b/cli/test/integration/stdin.test.cjs index aac8b5a7..f40f7096 100644 --- a/cli/test/integration/stdin.test.cjs +++ b/cli/test/integration/stdin.test.cjs @@ -5,23 +5,54 @@ const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); -test('legacy Shell and TS preserve task stdin in each execution mode', t => { +test('legacy Shell and TS preserve task stdin in each execution mode', (t) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-stdin-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); - for (const dir of ['shell/preload', 'shell/lang', 'data/config', 'data/scripts', 'data/log', 'static/build', 'bin']) + for (const dir of [ + 'shell/preload', + 'shell/lang', + 'data/config', + 'data/scripts', + 'data/log', + 'static/build', + 'bin', + ]) fs.mkdirSync(path.join(root, dir), { recursive: true }); - for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh']) - fs.copyFileSync(path.resolve(__dirname, '../../../shell', name), path.join(root, 'shell', name)); + for (const name of [ + 'task.sh', + 'task-timeout.sh', + 'otask.sh', + 'share.sh', + 'api.sh', + 'env.sh', + ]) + fs.copyFileSync( + path.resolve(__dirname, '../../../shell', name), + path.join(root, 'shell', name), + ); for (const name of ['zh.sh', 'en.sh']) - fs.copyFileSync(path.resolve(__dirname, '../../../shell/lang', name), path.join(root, 'shell/lang', name)); + fs.copyFileSync( + path.resolve(__dirname, '../../../shell/lang', name), + path.join(root, 'shell/lang', name), + ); fs.symlinkSync(process.execPath, path.join(root, 'bin/node')); - fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); - fs.writeFileSync(path.join(root, 'static/build/token.js'), 'process.stdout.write("fixture")'); + fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { + mode: 0o755, + }); + fs.writeFileSync( + path.join(root, 'static/build/token.js'), + 'process.stdout.write("fixture")', + ); fs.writeFileSync(path.join(root, 'data/config/config.sh'), 'no_tee=true\n'); fs.writeFileSync(path.join(root, 'data/config/crontab.list'), ''); - fs.writeFileSync(path.join(root, 'shell/preload/env.sh'), 'export ACCOUNTS=one\n'); - fs.writeFileSync(path.join(root, 'data/scripts/read.sh'), - 'IFS= read -r value\nprintf "value=%s\\n" "$value" > "$TRACE"\n'); + fs.writeFileSync( + path.join(root, 'shell/preload/env.sh'), + 'export ACCOUNTS=one\n', + ); + fs.writeFileSync( + path.join(root, 'data/scripts/read.sh'), + 'IFS= read -r value\nprintf "value=%s\\n" "$value" > "$TRACE"\n', + ); const env = { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, QL_DIR: root, @@ -29,18 +60,32 @@ test('legacy Shell and TS preserve task stdin in each execution mode', t => { no_delay: 'true', }; for (const mode of ['normal', 'now', 'desi', 'conc']) { - const args = ['read.sh', ...(mode === 'normal' ? [] : [mode]), - ...(['desi', 'conc'].includes(mode) ? ['ACCOUNTS', '1'] : [])]; + const args = [ + 'read.sh', + ...(mode === 'normal' ? [] : [mode]), + ...(['desi', 'conc'].includes(mode) ? ['ACCOUNTS', '1'] : []), + ]; for (const [label, command, prefix] of [ ['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]], - ['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]], + [ + 'ts', + process.execPath, + [path.resolve(__dirname, '../../dist/runner.js'), '--root', root], + ], ]) { const trace = path.join(root, `${mode}-${label}`); const result = spawnSync(command, [...prefix, ...args], { - env: { ...env, TRACE: trace }, input: 'hello\n', encoding: 'utf8', timeout: 15000, + env: { ...env, TRACE: trace }, + input: 'hello\n', + encoding: 'utf8', + timeout: 15000, }); assert.equal(result.status, 0, `${mode}/${label}: ${result.stderr}`); - assert.equal(fs.readFileSync(trace, 'utf8'), 'value=hello\n', `${mode}/${label}`); + assert.equal( + fs.readFileSync(trace, 'utf8'), + 'value=hello\n', + `${mode}/${label}`, + ); } } }); diff --git a/cli/test/internal/armv6-startup.test.cjs b/cli/test/internal/armv6-startup.test.cjs index 09e88bee..747a4075 100644 --- a/cli/test/internal/armv6-startup.test.cjs +++ b/cli/test/internal/armv6-startup.test.cjs @@ -54,7 +54,10 @@ for (const [arch, arm, node] of [ ); const context = createContext( { root }, - { PATH: process.platform === 'linux' ? '' : '/usr/bin:/bin', QL_LANG: 'en' }, + { + PATH: process.platform === 'linux' ? '' : '/usr/bin:/bin', + QL_LANG: 'en', + }, ); const entry = path.join(context.paths.dir_static, 'build/app.js'); let pid; diff --git a/cli/test/internal/bootstrap.test.cjs b/cli/test/internal/bootstrap.test.cjs index 7dad5a8d..428da383 100644 --- a/cli/test/internal/bootstrap.test.cjs +++ b/cli/test/internal/bootstrap.test.cjs @@ -240,7 +240,9 @@ for (const language of ['zh', 'en', 'unsupported']) { return true; }, ); - const { runtimeEnvironment } = require('../../dist/internal/maintenance/bootstrap'); + const { + runtimeEnvironment, + } = require('../../dist/internal/maintenance/bootstrap'); assert.throws( () => runtimeEnvironment(ctx, 'bad'), (error) => { diff --git a/cli/test/internal/botDiagnostics.test.cjs b/cli/test/internal/botDiagnostics.test.cjs index f34ece02..aa152a32 100644 --- a/cli/test/internal/botDiagnostics.test.cjs +++ b/cli/test/internal/botDiagnostics.test.cjs @@ -6,14 +6,26 @@ const vm = require('node:vm'); test('bot integration failure does not print environment-derived error details', async () => { const messages = []; - const childProcess = { env: { QL_PANEL_INTEGRATION: '1', QL_CLIENT_SECRET: 'sensitive-marker' }, exitCode: 0 }; - const source = fs.readFileSync(path.join(__dirname, '../linux/bot-install.cjs'), 'utf8'); + const childProcess = { + env: { QL_PANEL_INTEGRATION: '1', QL_CLIENT_SECRET: 'sensitive-marker' }, + exitCode: 0, + }; + const source = fs.readFileSync( + path.join(__dirname, '../linux/bot-install.cjs'), + 'utf8', + ); vm.runInNewContext(source, { process: childProcess, console: { error: (message) => messages.push(message) }, require: (name) => { - if (name === 'node:fs/promises') return { mkdtemp: async () => '/fixture' }; - if (name === '../../dist/internal/runtime/context') return { createContext: () => { throw new Error(childProcess.env.QL_CLIENT_SECRET); } }; + if (name === 'node:fs/promises') + return { mkdtemp: async () => '/fixture' }; + if (name === '../../dist/internal/runtime/context') + return { + createContext: () => { + throw new Error(childProcess.env.QL_CLIENT_SECRET); + }, + }; if (name === '../../dist/internal/maintenance/bot') return {}; return require(name); }, diff --git a/cli/test/internal/containerRuntime.test.cjs b/cli/test/internal/containerRuntime.test.cjs index 3099b03a..5361e850 100644 --- a/cli/test/internal/containerRuntime.test.cjs +++ b/cli/test/internal/containerRuntime.test.cjs @@ -5,7 +5,9 @@ const path = require('node:path'); const os = require('node:os'); const { setTimeout: delay } = require('node:timers/promises'); const { createContext } = require('../../dist/internal/runtime/context'); -const { runContainer } = require('../../dist/internal/runtime/containerRuntime'); +const { + runContainer, +} = require('../../dist/internal/runtime/containerRuntime'); async function fixture(t, mode = 'node') { const root = await fs.mkdtemp( @@ -180,7 +182,9 @@ test( { timeout: 20000 }, async (t) => { const f = await fixture(t); - const { launchStartupHook } = require('../../dist/internal/maintenance/bootstrap'); + const { + launchStartupHook, + } = require('../../dist/internal/maintenance/bootstrap'); const pidFile = path.join(f.root, 'extra-pid'); f.context.env.QL_TEST_EXTRA_PID = pidFile; await fs.writeFile( diff --git a/cli/test/internal/environmentTransport.test.cjs b/cli/test/internal/environmentTransport.test.cjs index 2cfac4b3..6c595d9f 100644 --- a/cli/test/internal/environmentTransport.test.cjs +++ b/cli/test/internal/environmentTransport.test.cjs @@ -5,24 +5,35 @@ const { runProcess } = require('../../dist/internal/runtime/process'); test('environment transport preserves multiline values, empty values and exported functions', async () => { const value = '中文\nsecond=line\r\n"quoted"\\literal'; - const env = await sourceEnvironment({ PATH: process.env.PATH, VALUE: value }, [], [], { - command: 'export EMPTY=""; exported_fn() { printf "%s" "$VALUE"; }; export -f exported_fn; set -o pipefail; shopt -s nullglob; printf "user output"', - output: () => {}, - }); + const env = await sourceEnvironment( + { PATH: process.env.PATH, VALUE: value }, + [], + [], + { + command: + 'export EMPTY=""; exported_fn() { printf "%s" "$VALUE"; }; export -f exported_fn; set -o pipefail; shopt -s nullglob; printf "user output"', + output: () => {}, + }, + ); assert.equal(env.VALUE, value); assert.equal(env.EMPTY, ''); assert.ok(env.QL_CLI_SHELLOPTS.split(':').includes('pipefail')); assert.ok(!env.QL_CLI_SHELLOPTS.split(':').includes('allexport')); assert.ok(env.QL_CLI_BASHOPTS.split(':').includes('nullglob')); - assert.ok(!Object.keys(env).some(key => key.startsWith('__ql_'))); - const child = await runProcess('bash', ['--noprofile', '--norc', '-c', 'exported_fn'], { env, capture: true }); + assert.ok(!Object.keys(env).some((key) => key.startsWith('__ql_'))); + const child = await runProcess( + 'bash', + ['--noprofile', '--norc', '-c', 'exported_fn'], + { env, capture: true }, + ); assert.equal(child.code, 0); assert.equal(child.stdout, value); }); test('environment transport does not execute a Node runtime from user configuration', async () => { const env = await sourceEnvironment({ PATH: process.env.PATH }, [], [], { - command: 'export NODE_OPTIONS="--this-option-does-not-exist"; export PATH="/nonexistent"', + command: + 'export NODE_OPTIONS="--this-option-does-not-exist"; export PATH="/nonexistent"', }); assert.equal(env.NODE_OPTIONS, '--this-option-does-not-exist'); assert.equal(env.PATH, '/nonexistent'); diff --git a/cli/test/internal/hostServices.test.cjs b/cli/test/internal/hostServices.test.cjs index cb8c9ef9..de4c45b0 100644 --- a/cli/test/internal/hostServices.test.cjs +++ b/cli/test/internal/hostServices.test.cjs @@ -3,7 +3,9 @@ const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); -const { registerHostServices } = require('../../dist/internal/runtime/hostServices'); +const { + registerHostServices, +} = require('../../dist/internal/runtime/hostServices'); const { createContext } = require('../../dist/internal/runtime/context'); for (const manager of ['openrc', 'systemd', 'missing']) { diff --git a/cli/test/internal/lifecycle.test.cjs b/cli/test/internal/lifecycle.test.cjs index 455d2ea2..c75faf37 100644 --- a/cli/test/internal/lifecycle.test.cjs +++ b/cli/test/internal/lifecycle.test.cjs @@ -25,26 +25,42 @@ test('command log preserves scheduler path and rejects escaping the log director ); }); -test('managed CLI tasks and maintenance commands report against the parent receipt', 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-managed-cli-')); t.after(() => fs.rm(root, { recursive: true, force: 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', - }); + 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 }; }); - const result = await executeTask(context, { argv: ['fixture.sh'], mode: 'now' }); + 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']); + 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) { @@ -55,23 +71,43 @@ test('managed CLI tasks and maintenance commands report against the parent recei 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))); + 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 => { +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' }); + 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); + 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 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); @@ -82,25 +118,41 @@ test('distinct managed triggers in the same clock tick have separate maintenance assert.doesNotMatch(b.content, /marker-alpha/); }); -test('same-tick standalone tasks and commands share a receipt only within one invocation', async t => { +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 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}; + 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']); + 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'], + ); }); diff --git a/cli/test/internal/local.test.cjs b/cli/test/internal/local.test.cjs index ca812f96..38a05791 100644 --- a/cli/test/internal/local.test.cjs +++ b/cli/test/internal/local.test.cjs @@ -4,7 +4,10 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const http = require('node:http'); -const { createContext, sourceEnvironment } = require('../../dist/internal/runtime/context'); +const { + createContext, + sourceEnvironment, +} = require('../../dist/internal/runtime/context'); const { runProcess } = require('../../dist/internal/runtime/process'); const { pruneLogs } = require('../../dist/internal/maintenance/maintenance'); const { parse } = require('../helpers/commands.cjs'); @@ -276,7 +279,9 @@ test('concurrent accounts finish independently but merge logs in selection order }); test('concurrent log spool waits for peers and cleans up on invocation failure', async (t) => { - const { orderedConcurrent } = require('../../dist/internal/execution/concurrent'); + const { + orderedConcurrent, + } = require('../../dist/internal/execution/concurrent'); const root = sandbox(t); const chunks = []; let peerFinished = false; @@ -485,10 +490,7 @@ test('shell tasks inherit before-hook state without leaking script state into af path.join(context.paths.dir_log, result.logPath), 'utf8', ); - assert.match( - log, - /before:private\narg:space value\nafter:private:unset:7/, - ); + assert.match(log, /before:private\narg:space value\nafter:private:unset:7/); }); test('task resolves modules from pnpm global root and restores the previous path for after hooks', async (t) => { @@ -538,7 +540,9 @@ test('task resolves modules from pnpm global root and restores the previous path }); test('missing optional pnpm still provides user dependency resolution', async (t) => { - const { taskDependencyEnvironment } = require('../../dist/internal/execution/dependencies'); + const { + taskDependencyEnvironment, + } = require('../../dist/internal/execution/dependencies'); const context = createContext( { root: sandbox(t) }, { diff --git a/cli/test/internal/localApi.test.cjs b/cli/test/internal/localApi.test.cjs index 3c1d80ae..88b6c6ab 100644 --- a/cli/test/internal/localApi.test.cjs +++ b/cli/test/internal/localApi.test.cjs @@ -184,8 +184,12 @@ test( 'cancelled local API requests do not replay mutations and final lifecycle still reports', { timeout: 5000 }, async (t) => { - const { cancellableOperation } = require('../../dist/internal/runtime/cancellation'); - const { loggedOperation } = require('../../dist/internal/runtime/commandLog'); + const { + cancellableOperation, + } = require('../../dist/internal/runtime/cancellation'); + const { + loggedOperation, + } = require('../../dist/internal/runtime/commandLog'); for (const partialBody of [false, true]) { const controller = new AbortController(); const calls = []; @@ -288,22 +292,36 @@ for (const language of ['zh', 'en', 'unsupported']) { }); } -test('a lifecycle timeout retries the identical payload once and other writes are not retried', async t => { +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}) => { + 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})); + 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], + [ + '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)); @@ -311,98 +329,151 @@ test('a lifecycle timeout retries the identical payload once and other writes ar } }); -test('the live status schema selects every receipt on old, intermediate and upgraded panels', async t => { +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 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')); + 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]}}})); + res.writeHead(400).end( + JSON.stringify({ + validation: { body: { source: 'body', keys: [forbidden] } }, + }), + ); return; } - written.push([req.url,body]); + 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'); + 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'), ''); + await fs.mkdir(path.join(context.root, 'static/build/cron'), { + recursive: true, + }); + await fs.writeFile( + path.join(context.root, 'static/build/cron/identity.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]) { + 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]) { + 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]); + 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.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); + 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 => { +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; + 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]}} })); + 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'})); + 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); + 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); + 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 => { +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})); + 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); + 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); } }); diff --git a/cli/test/internal/networkRepository.test.cjs b/cli/test/internal/networkRepository.test.cjs index f448f8fb..3296b5c1 100644 --- a/cli/test/internal/networkRepository.test.cjs +++ b/cli/test/internal/networkRepository.test.cjs @@ -9,7 +9,9 @@ const net = require('node:net'); const { randomUUID } = require('node:crypto'); const { execFileSync, spawn } = require('node:child_process'); const { createContext } = require('../../dist/internal/runtime/context'); -const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner'); +const { + syncRepository, +} = require('../../dist/internal/subscription/subscriptionRunner'); const git = process.platform === 'darwin' ? '/usr/bin/git' : 'git'; for (const tls of [false, true]) diff --git a/cli/test/internal/operatorDiagnostics.test.cjs b/cli/test/internal/operatorDiagnostics.test.cjs index 9cc15240..db4e20a8 100644 --- a/cli/test/internal/operatorDiagnostics.test.cjs +++ b/cli/test/internal/operatorDiagnostics.test.cjs @@ -5,7 +5,10 @@ const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); const { createContext } = require('../../dist/internal/runtime/context'); -const { replaceAndReload, reloadPanel } = require('../../dist/internal/maintenance/upgrade'); +const { + replaceAndReload, + reloadPanel, +} = require('../../dist/internal/maintenance/upgrade'); const { installCronEntrypoint } = require('../../dist/local/cronEntrypoint'); for (const language of ['zh', 'en', 'unsupported']) { diff --git a/cli/test/internal/pathDiagnostics.test.cjs b/cli/test/internal/pathDiagnostics.test.cjs index 7e962b3c..462d2482 100644 --- a/cli/test/internal/pathDiagnostics.test.cjs +++ b/cli/test/internal/pathDiagnostics.test.cjs @@ -7,7 +7,10 @@ const { within } = require('../../dist/internal/runtime/files'); const { createContext } = require('../../dist/internal/runtime/context'); const { loggedOperation } = require('../../dist/internal/runtime/commandLog'); const { executeTask } = require('../../dist/internal/execution/taskRunner'); -const { syncRaw, repositoryName } = require('../../dist/internal/subscription/subscriptionRunner'); +const { + syncRaw, + repositoryName, +} = require('../../dist/internal/subscription/subscriptionRunner'); const { LocalApi } = require('../../dist/internal/runtime/api'); const subprocess = require('../../dist/internal/runtime/process'); diff --git a/cli/test/internal/processDiagnostics.test.cjs b/cli/test/internal/processDiagnostics.test.cjs index 433d3913..4007c516 100644 --- a/cli/test/internal/processDiagnostics.test.cjs +++ b/cli/test/internal/processDiagnostics.test.cjs @@ -1,6 +1,9 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const { runProcess, checkedProcess } = require('../../dist/internal/runtime/process'); +const { + runProcess, + checkedProcess, +} = require('../../dist/internal/runtime/process'); for (const language of ['zh', 'en', 'unsupported']) { test(`subprocess failures localize and reap failed writers: ${language}`, async () => { diff --git a/cli/test/internal/scriptInventory.test.cjs b/cli/test/internal/scriptInventory.test.cjs index 525fb15b..220b9202 100644 --- a/cli/test/internal/scriptInventory.test.cjs +++ b/cli/test/internal/scriptInventory.test.cjs @@ -5,7 +5,9 @@ const path = require('node:path'); const os = require('node:os'); const { execFileSync } = require('node:child_process'); const { createContext } = require('../../dist/internal/runtime/context'); -const { listTaskScripts } = require('../../dist/internal/execution/scriptInventory'); +const { + listTaskScripts, +} = require('../../dist/internal/execution/scriptInventory'); test('no-argument runner lists legacy JS candidates without evaluating scripts or config', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-inventory-')); diff --git a/cli/test/internal/subscriptionFilter.test.cjs b/cli/test/internal/subscriptionFilter.test.cjs index 63b4c443..a93027ca 100644 --- a/cli/test/internal/subscriptionFilter.test.cjs +++ b/cli/test/internal/subscriptionFilter.test.cjs @@ -4,7 +4,9 @@ const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const { execFileSync } = require('node:child_process'); -const { matchSubscriptionPaths } = require('../../dist/internal/subscription/subscriptionFilter'); +const { + matchSubscriptionPaths, +} = require('../../dist/internal/subscription/subscriptionFilter'); test('subscription filters preserve legacy POSIX classes, escaping, anchors and option-like patterns', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-filter-')); diff --git a/cli/test/internal/subscriptionRunner.test.cjs b/cli/test/internal/subscriptionRunner.test.cjs index 31a5a626..0d8cb5ae 100644 --- a/cli/test/internal/subscriptionRunner.test.cjs +++ b/cli/test/internal/subscriptionRunner.test.cjs @@ -164,7 +164,14 @@ 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, [{ id: 1, script: 'owner_repository/old.js', command: rows[0].command, sub_id: 7 }]); + 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 * * *', @@ -180,7 +187,9 @@ test('subscription reconciliation scopes removals to canonical paths and the cur }); test('raw download failure preserves the last script and does not reconcile tasks', async (t) => { - const { syncRaw } = require('../../dist/internal/subscription/subscriptionRunner'); + const { + syncRaw, + } = require('../../dist/internal/subscription/subscriptionRunner'); const http = require('node:http'); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-raw-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); @@ -215,7 +224,9 @@ test('raw download failure preserves the last script and does not reconcile task test('directory replacement stages on the destination filesystem before switching old files', async (t) => { const fsp = require('node:fs/promises'); - const { replaceDirectory } = require('../../dist/internal/subscription/subscriptionRunner'); + const { + replaceDirectory, + } = require('../../dist/internal/subscription/subscriptionRunner'); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-cross-device-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const staged = path.join(root, 'staged'), @@ -251,7 +262,9 @@ test('directory replacement stages on the destination filesystem before switchin test('cross-filesystem preparation failure leaves the old subscription directory untouched', async (t) => { const fsp = require('node:fs/promises'); - const { replaceDirectory } = require('../../dist/internal/subscription/subscriptionRunner'); + const { + replaceDirectory, + } = require('../../dist/internal/subscription/subscriptionRunner'); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-copy-failure-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const staged = path.join(root, 'staged'), @@ -433,7 +446,7 @@ 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 => { +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 }); @@ -444,9 +457,13 @@ test('a slash in a branch cannot publish through a linked namespace parent', asy 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/); + 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); } diff --git a/cli/test/internal/taskDelay.test.cjs b/cli/test/internal/taskDelay.test.cjs index 9aa9b3e2..4e33d444 100644 --- a/cli/test/internal/taskDelay.test.cjs +++ b/cli/test/internal/taskDelay.test.cjs @@ -4,7 +4,9 @@ const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); const { spawnSync } = require('node:child_process'); -const { matchesDelayExtension } = require('../../dist/internal/execution/taskDelay'); +const { + matchesDelayExtension, +} = require('../../dist/internal/execution/taskDelay'); const { createContext } = require('../../dist/internal/runtime/context'); const { executeTask } = require('../../dist/internal/execution/taskRunner'); diff --git a/cli/test/internal/taskLifecycle.test.cjs b/cli/test/internal/taskLifecycle.test.cjs index 3c8e8d1d..9f397c26 100644 --- a/cli/test/internal/taskLifecycle.test.cjs +++ b/cli/test/internal/taskLifecycle.test.cjs @@ -10,69 +10,200 @@ function fixture(t) { t.after(() => fs.rmSync(root, { recursive: true, force: true })); for (const dir of ['data/config', 'data/scripts', 'bin']) fs.mkdirSync(path.join(root, dir), { recursive: true }); - fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { + mode: 0o755, + }); const trace = path.join(root, 'trace'); return { - root, trace, - write(file, contents) { fs.writeFileSync(path.join(root, file), contents); }, - args: [path.resolve(__dirname, '../../dist/runner.js'), '--root', root, '--json'], + root, + trace, + write(file, contents) { + fs.writeFileSync(path.join(root, file), contents); + }, + args: [ + path.resolve(__dirname, '../../dist/runner.js'), + '--root', + root, + '--json', + ], env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, TRACE: trace }, - events() { return fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8').trim().split('\n') : []; }, + events() { + return fs.existsSync(trace) + ? fs.readFileSync(trace, 'utf8').trim().split('\n') + : []; + }, }; } -test('shared Shell lifecycle scopes timeouts to the task and runs cleanup exactly once', async t => { +test('shared Shell lifecycle scopes timeouts to the task and runs cleanup exactly once', async (t) => { const cases = [ { name: 'success', task: 'return 0', code: 0 }, { name: 'failure', task: 'return 7', code: 7 }, - { name: 'function timeout preserves state', task: 'STATE=changed; sleep 10', code: 124, timeout: true, state: 'changed' }, - { name: 'external timeout', args: ['sleep', '10'], code: 124, timeout: true }, - { name: 'Shell script timeout preserves parent hook state', task: 'STATE=changed; sleep 10', shell: true, code: 124, timeout: true }, - { name: 'slow before is outside task timeout', before: 'sleep 0.2', task: 'return 0', code: 0 }, - { name: 'slow after is outside task timeout', after: 'sleep 0.2', task: 'return 0', code: 0 }, - { name: 'background child cannot hold pipes after timeout cleanup', task: '(trap "" INT; sleep 30) & sleep 30', after: 'sleep 0.3', code: 124, timeout: true }, - { name: 'script may redirect fd 3', shell: true, task: 'exec 3> "$TRACE.fd"; return 0', after: 'sleep 0.3', code: 0 }, - { name: 'before may close fd 3 and redirect fd 9', before: 'exec 3>&- 9> "$TRACE.lock"', task: 'return 0', after: 'sleep 0.3', code: 0 }, - { name: 'timeout cleanup survives script fd 3 redirection', shell: true, task: 'exec 3> "$TRACE.fd"; STATE=changed; sleep 30', after: 'sleep 0.3', code: 124, timeout: true }, - { name: 'Shell exit preserves user trap and runs after once', shell: true, task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', code: 9, userExit: true }, - { name: 'explicit exit preserves user trap and skips after', task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', code: 9, noAfter: true, userExit: true }, - { name: 'user EXIT trap survives timeout with parent cleanup', task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; sleep 10', code: 124, timeout: true, userExit: true }, - { name: 'forced termination falls back to cleanup', task: 'trap "" INT; sleep 30', code: 124, timeout: true }, + { + name: 'function timeout preserves state', + task: 'STATE=changed; sleep 10', + code: 124, + timeout: true, + state: 'changed', + }, + { + name: 'external timeout', + args: ['sleep', '10'], + code: 124, + timeout: true, + }, + { + name: 'Shell script timeout preserves parent hook state', + task: 'STATE=changed; sleep 10', + shell: true, + code: 124, + timeout: true, + }, + { + name: 'slow before is outside task timeout', + before: 'sleep 0.2', + task: 'return 0', + code: 0, + }, + { + name: 'slow after is outside task timeout', + after: 'sleep 0.2', + task: 'return 0', + code: 0, + }, + { + name: 'background child cannot hold pipes after timeout cleanup', + task: '(trap "" INT; sleep 30) & sleep 30', + after: 'sleep 0.3', + code: 124, + timeout: true, + }, + { + name: 'script may redirect fd 3', + shell: true, + task: 'exec 3> "$TRACE.fd"; return 0', + after: 'sleep 0.3', + code: 0, + }, + { + name: 'before may close fd 3 and redirect fd 9', + before: 'exec 3>&- 9> "$TRACE.lock"', + task: 'return 0', + after: 'sleep 0.3', + code: 0, + }, + { + name: 'timeout cleanup survives script fd 3 redirection', + shell: true, + task: 'exec 3> "$TRACE.fd"; STATE=changed; sleep 30', + after: 'sleep 0.3', + code: 124, + timeout: true, + }, + { + name: 'Shell exit preserves user trap and runs after once', + shell: true, + task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', + code: 9, + userExit: true, + }, + { + name: 'explicit exit preserves user trap and skips after', + task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', + code: 9, + noAfter: true, + userExit: true, + }, + { + name: 'user EXIT trap survives timeout with parent cleanup', + task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; sleep 10', + code: 124, + timeout: true, + userExit: true, + }, + { + name: 'forced termination falls back to cleanup', + task: 'trap "" INT; sleep 30', + code: 124, + timeout: true, + }, ]; - for (const scenario of cases) await t.test(scenario.name, t => { - const f = fixture(t); - f.write('data/config/config.sh', `no_tee=true\nSTATE=original\nmy_task() { ${scenario.task || ':'}; }\n`); - f.write('data/config/task_before.sh', `printf 'before\\n' >> "$TRACE"\n${scenario.before || ':'}\n`); - f.write('data/config/task_after.sh', `${scenario.after || ':'}\nprintf 'after:%s:%s\\n' "$STATE" "$_task_exit_code" >> "$TRACE"\n`); - if (scenario.shell) f.write('data/scripts/task.sh', scenario.task + '\n'); - const result = spawnSync(process.execPath, [...f.args, '-m', '0.1s', ...(scenario.args || [scenario.shell ? 'task.sh' : 'my_task'])], { - env: f.env, encoding: 'utf8', timeout: 15000, + for (const scenario of cases) + await t.test(scenario.name, (t) => { + const f = fixture(t); + f.write( + 'data/config/config.sh', + `no_tee=true\nSTATE=original\nmy_task() { ${scenario.task || ':'}; }\n`, + ); + f.write( + 'data/config/task_before.sh', + `printf 'before\\n' >> "$TRACE"\n${scenario.before || ':'}\n`, + ); + f.write( + 'data/config/task_after.sh', + `${ + scenario.after || ':' + }\nprintf 'after:%s:%s\\n' "$STATE" "$_task_exit_code" >> "$TRACE"\n`, + ); + if (scenario.shell) f.write('data/scripts/task.sh', scenario.task + '\n'); + const result = spawnSync( + process.execPath, + [ + ...f.args, + '-m', + '0.1s', + ...(scenario.args || [scenario.shell ? 'task.sh' : 'my_task']), + ], + { + env: f.env, + encoding: 'utf8', + timeout: 15000, + }, + ); + assert.equal(result.status, scenario.code, result.stderr); + const data = JSON.parse(result.stdout).data; + assert.equal(data.exitCode, scenario.code); + assert.equal(data.timedOut, !!scenario.timeout); + assert.deepEqual(f.events(), [ + 'before', + ...(scenario.userExit ? ['exit'] : []), + ...(scenario.noAfter + ? [] + : [`after:${scenario.state || 'original'}:${scenario.code}`]), + ]); }); - assert.equal(result.status, scenario.code, result.stderr); - const data = JSON.parse(result.stdout).data; - assert.equal(data.exitCode, scenario.code); - assert.equal(data.timedOut, !!scenario.timeout); - assert.deepEqual(f.events(), [ - 'before', ...(scenario.userExit ? ['exit'] : []), - ...(scenario.noAfter ? [] : [`after:${scenario.state || 'original'}:${scenario.code}`]), - ]); - }); }); -test('user cancellation remains cancellation, without timeout cleanup replay', async t => { +test('user cancellation remains cancellation, without timeout cleanup replay', async (t) => { const f = fixture(t); - f.write('data/config/config.sh', 'my_task() { printf "READY\\n"; sleep 30; }\n'); + f.write( + 'data/config/config.sh', + 'my_task() { printf "READY\\n"; sleep 30; }\n', + ); f.write('data/config/task_after.sh', 'printf "after\\n" >> "$TRACE"\n'); - const child = spawn(process.execPath, [...f.args, '-m', '20s', 'my_task'], { env: f.env }); - let out = '', err = '', sent = false; + const child = spawn(process.execPath, [...f.args, '-m', '20s', 'my_task'], { + env: f.env, + }); + let out = '', + err = '', + sent = false; const timer = setTimeout(() => child.kill('SIGKILL'), 15000); - t.after(() => { clearTimeout(timer); child.kill('SIGKILL'); }); - child.stdout.on('data', chunk => out += chunk); - child.stderr.on('data', chunk => { + t.after(() => { + clearTimeout(timer); + child.kill('SIGKILL'); + }); + child.stdout.on('data', (chunk) => (out += chunk)); + child.stderr.on('data', (chunk) => { err += chunk; - if (!sent && err.includes('READY')) { sent = true; child.kill('SIGTERM'); } + if (!sent && err.includes('READY')) { + sent = true; + child.kill('SIGTERM'); + } + }); + const code = await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('close', resolve); }); - const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); }); assert.equal(sent, true, err); assert.equal(code, 143, err); assert.equal(JSON.parse(out).data.timedOut, false); diff --git a/cli/test/linux/bot-install.cjs b/cli/test/linux/bot-install.cjs index 661d071a..f8de5ba7 100644 --- a/cli/test/linux/bot-install.cjs +++ b/cli/test/linux/bot-install.cjs @@ -106,6 +106,8 @@ assert.equal(process.env.QL_PANEL_INTEGRATION, '1'); await fs.rm(foreignRoot, { recursive: true, force: true }); } })().catch(() => { - console.error('Bot installation integration test failed; raw subprocess errors are omitted to protect environment credentials.'); + console.error( + 'Bot installation integration test failed; raw subprocess errors are omitted to protect environment credentials.', + ); process.exitCode = 1; }); diff --git a/cli/test/linux/container-bot.test.cjs b/cli/test/linux/container-bot.test.cjs index f893e56c..fa4d418a 100644 --- a/cli/test/linux/container-bot.test.cjs +++ b/cli/test/linux/container-bot.test.cjs @@ -5,8 +5,12 @@ const path = require('node:path'); const os = require('node:os'); const { setTimeout: delay } = require('node:timers/promises'); const { createContext } = require('../../dist/internal/runtime/context'); -const { runContainer } = require('../../dist/internal/runtime/containerRuntime'); -const { launchStartupHook } = require('../../dist/internal/maintenance/bootstrap'); +const { + runContainer, +} = require('../../dist/internal/runtime/containerRuntime'); +const { + launchStartupHook, +} = require('../../dist/internal/maintenance/bootstrap'); const { launchBot } = require('../../dist/internal/maintenance/bot'); const live = (pid) => { diff --git a/cli/test/linux/host-boot.cjs b/cli/test/linux/host-boot.cjs index f1b18ab8..5b3113b1 100644 --- a/cli/test/linux/host-boot.cjs +++ b/cli/test/linux/host-boot.cjs @@ -36,7 +36,12 @@ const { LocalApi } = require('../../dist/internal/runtime/api'); { stdio: 'pipe' }, ); const nginxPid = Number( - (await fs.readFile(systemd ? '/run/nginx.pid' : '/run/nginx/nginx.pid', 'utf8')).trim(), + ( + await fs.readFile( + systemd ? '/run/nginx.pid' : '/run/nginx/nginx.pid', + 'utf8', + ) + ).trim(), ); assert.ok(Number.isSafeInteger(nginxPid) && nginxPid > 1); process.kill(nginxPid, 0); diff --git a/cli/test/linux/image-selection.cjs b/cli/test/linux/image-selection.cjs index 3da22648..54ee74a2 100644 --- a/cli/test/linux/image-selection.cjs +++ b/cli/test/linux/image-selection.cjs @@ -1,7 +1,9 @@ const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const { spawnSync } = require('node:child_process'); -const { createContext } = require('/opt/qinglong-cli/dist/internal/runtime/context'); +const { + createContext, +} = require('/opt/qinglong-cli/dist/internal/runtime/context'); const { LocalApi } = require('/opt/qinglong-cli/dist/internal/runtime/api'); assert.equal(process.env.QL_PANEL_INTEGRATION, '1'); (async () => { diff --git a/cli/test/linux/interrupted-reload.cjs b/cli/test/linux/interrupted-reload.cjs index b7617adb..5b822353 100644 --- a/cli/test/linux/interrupted-reload.cjs +++ b/cli/test/linux/interrupted-reload.cjs @@ -2,7 +2,10 @@ process.channel.ref(); // Child fixture: real service startup pauses at a deterministic cancellation boundary. const { createContext } = require('../../dist/internal/runtime/context'); const { replaceAndReload } = require('../../dist/internal/maintenance/upgrade'); -const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator'); +const { + startPanel, + stopPanel, +} = require('../../dist/internal/maintenance/operator'); const { withCommandCancellation, cancellableOperation, diff --git a/cli/test/linux/mounted-data.test.cjs b/cli/test/linux/mounted-data.test.cjs index 5b8ec7f3..b4cfcad0 100644 --- a/cli/test/linux/mounted-data.test.cjs +++ b/cli/test/linux/mounted-data.test.cjs @@ -4,7 +4,10 @@ const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const { createContext } = require('../../dist/internal/runtime/context'); -const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator'); +const { + startPanel, + stopPanel, +} = require('../../dist/internal/maintenance/operator'); const { reloadPanel } = require('../../dist/internal/maintenance/upgrade'); test( diff --git a/cli/test/linux/openapi.cjs b/cli/test/linux/openapi.cjs index ea4bdb6b..769abe0d 100644 --- a/cli/test/linux/openapi.cjs +++ b/cli/test/linux/openapi.cjs @@ -9,53 +9,202 @@ const fs = require('node:fs/promises'); assert.equal(process.env.QL_PANEL_INTEGRATION, '1'); const url = 'http://127.0.0.1:5700'; const api = async (route, method = 'GET', body) => { - const response = await fetch(url + '/api/' + route, { method, - headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); - const result = await response.json(); assert.equal(result.code, 200); return result.data; + const response = await fetch(url + '/api/' + route, { + method, + headers: { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const result = await response.json(); + assert.equal(result.code, 200); + return result.data; + }; + const info = await api('system'); + assert.equal(info.isInitialized, false, 'Refuse initialized panels'); + const credentials = { + username: 'fixture-' + randomUUID(), + password: randomUUID(), }; - const info = await api('system'); assert.equal(info.isInitialized, false, 'Refuse initialized panels'); - const credentials = { username: 'fixture-' + randomUUID(), password: randomUUID() }; await api('user/init', 'PUT', credentials); const owner = (await api('user/login', 'POST', credentials)).token; const config = '/tmp/ql-openapi-auth.json'; const entry = path.resolve(__dirname, '../../dist/npm/ql.js'); const cli = (args, ownerMode = false, extra = {}) => { const result = spawnSync(process.execPath, [entry, ...args, '--json'], { - encoding: 'utf8', timeout: 30000, - env: { ...process.env, QL_CLI_CONFIG: config, QL_URL: ownerMode ? url : '', QL_ACCESS_TOKEN: ownerMode ? owner : '', ...extra }, + encoding: 'utf8', + timeout: 30000, + env: { + ...process.env, + QL_CLI_CONFIG: config, + QL_URL: ownerMode ? url : '', + QL_ACCESS_TOKEN: ownerMode ? owner : '', + ...extra, + }, }); // Report only the command name, never request bodies or application credentials. - assert.equal(result.status, 0, args.slice(0, 2).join(' ') + ': ' + result.stderr); + assert.equal( + result.status, + 0, + args.slice(0, 2).join(' ') + ': ' + result.stderr, + ); return JSON.parse(result.stdout).data; }; - const app = cli(['app', 'create', '--name', 'cli-fixture', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard', '--show-secrets'], true); + const app = cli( + [ + 'app', + 'create', + '--name', + 'cli-fixture', + '--scopes', + 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard', + '--show-secrets', + ], + true, + ); assert.ok(app.client_id && app.client_secret); - cli(['login', '--url', url], false, { QL_CLIENT_ID: app.client_id, QL_CLIENT_SECRET: app.client_secret }); + cli(['login', '--url', url], false, { + QL_CLIENT_ID: app.client_id, + QL_CLIENT_SECRET: app.client_secret, + }); cli(['auth', 'status', '--scope', 'crons']); - cli(['app', 'update', String(app.id), '--name', 'cli-updated', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard'], true); - assert.ok(cli(['app', 'list'], true).every(item => !('client_secret' in item) && !('tokens' in item))); - const task = cli(['task', 'create', '--name', 'cli-task', '--command', 'echo OPENAPI_FIXTURE', '--schedule', '0 0 * * *']); - cli(['task', 'update', String(task.id), '--name', 'cli-task-updated', '--command', 'echo OPENAPI_UPDATED', '--schedule', '0 1 * * *']); - cli(['task', 'disable', String(task.id)]); cli(['task', 'enable', String(task.id)]); + cli( + [ + 'app', + 'update', + String(app.id), + '--name', + 'cli-updated', + '--scopes', + 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard', + ], + true, + ); + assert.ok( + cli(['app', 'list'], true).every( + (item) => !('client_secret' in item) && !('tokens' in item), + ), + ); + const task = cli([ + 'task', + 'create', + '--name', + 'cli-task', + '--command', + 'echo OPENAPI_FIXTURE', + '--schedule', + '0 0 * * *', + ]); + cli([ + 'task', + 'update', + String(task.id), + '--name', + 'cli-task-updated', + '--command', + 'echo OPENAPI_UPDATED', + '--schedule', + '0 1 * * *', + ]); + cli(['task', 'disable', String(task.id)]); + cli(['task', 'enable', String(task.id)]); assert.equal(cli(['task', 'get', String(task.id)]).name, 'cli-task-updated'); - const sub = cli(['subscription', 'create', '--type', 'file', '--url', url + '/fixture.js', '--alias', 'cli-sub', '--schedule-type', 'crontab', '--schedule', '0 0 * * *']); - cli(['subscription', 'update', String(sub.id), '--data', JSON.stringify({ type: 'file', url: url + '/fixture.js', alias: 'cli-sub', name: 'cli-sub-updated', schedule_type: 'crontab', schedule: '0 1 * * *' })]); - cli(['subscription', 'disable', String(sub.id)]); cli(['subscription', 'enable', String(sub.id)]); - assert.equal(cli(['subscription', 'get', String(sub.id)]).name, 'cli-sub-updated'); - const env = cli(['env', 'create', '--data', '[{"name":"CLI_FIXTURE","value":"one"}]'])[0]; - cli(['env', 'update', String(env.id), '--data', '{"name":"CLI_FIXTURE","value":"two"}']); + const sub = cli([ + 'subscription', + 'create', + '--type', + 'file', + '--url', + url + '/fixture.js', + '--alias', + 'cli-sub', + '--schedule-type', + 'crontab', + '--schedule', + '0 0 * * *', + ]); + cli([ + 'subscription', + 'update', + String(sub.id), + '--data', + JSON.stringify({ + type: 'file', + url: url + '/fixture.js', + alias: 'cli-sub', + name: 'cli-sub-updated', + schedule_type: 'crontab', + schedule: '0 1 * * *', + }), + ]); + cli(['subscription', 'disable', String(sub.id)]); + cli(['subscription', 'enable', String(sub.id)]); + assert.equal( + cli(['subscription', 'get', String(sub.id)]).name, + 'cli-sub-updated', + ); + const env = cli([ + 'env', + 'create', + '--data', + '[{"name":"CLI_FIXTURE","value":"one"}]', + ])[0]; + cli([ + 'env', + 'update', + String(env.id), + '--data', + '{"name":"CLI_FIXTURE","value":"two"}', + ]); assert.equal(cli(['env', 'get', String(env.id)]).value, 'two'); cli(['env', 'delete', String(env.id)]); - cli(['script', 'create', '--data', '{"filename":"cli-openapi.js","content":"console.log(1)","path":""}']); - assert.equal(cli(['script', 'get', '--query', '{"file":"cli-openapi.js"}']), 'console.log(1)'); - cli(['config', 'save', '--data', '{"name":"cli-openapi.sh","content":"# fixture"}']); - assert.equal(cli(['config', 'get', '--query', '{"path":"cli-openapi.sh"}']), '# fixture'); - cli(['log', 'list']); cli(['dependency', 'list']); - cli(['task', 'delete', String(task.id)]); cli(['subscription', 'delete', String(sub.id)]); - const reset = cli(['app', 'reset-secret', String(app.id), '--show-secrets'], true); + cli([ + 'script', + 'create', + '--data', + '{"filename":"cli-openapi.js","content":"console.log(1)","path":""}', + ]); + assert.equal( + cli(['script', 'get', '--query', '{"file":"cli-openapi.js"}']), + 'console.log(1)', + ); + cli([ + 'config', + 'save', + '--data', + '{"name":"cli-openapi.sh","content":"# fixture"}', + ]); + assert.equal( + cli(['config', 'get', '--query', '{"path":"cli-openapi.sh"}']), + '# fixture', + ); + cli(['log', 'list']); + cli(['dependency', 'list']); + cli(['task', 'delete', String(task.id)]); + cli(['subscription', 'delete', String(sub.id)]); + const reset = cli( + ['app', 'reset-secret', String(app.id), '--show-secrets'], + true, + ); assert.ok(reset.client_secret !== app.client_secret); - cli(['login', '--url', url], false, { QL_CLIENT_ID: app.client_id, QL_CLIENT_SECRET: reset.client_secret }); - cli(['auth', 'status']); cli(['app', 'delete', String(app.id)], true); + cli(['login', '--url', url], false, { + QL_CLIENT_ID: app.client_id, + QL_CLIENT_SECRET: reset.client_secret, + }); + cli(['auth', 'status']); + cli(['app', 'delete', String(app.id)], true); await fs.rm(config, { force: true }); - console.log(JSON.stringify({ panelVersion: info.version, taskCrud: true, subscriptionCrud: true, appCrudAndSecretRotation: true, envCrud: true, scriptCreateRead: true, configSaveRead: true, logAndDependencyRead: true })); -})().catch(error => { console.error(error.message); process.exitCode = 1; }); + console.log( + JSON.stringify({ + panelVersion: info.version, + taskCrud: true, + subscriptionCrud: true, + appCrudAndSecretRotation: true, + envCrud: true, + scriptCreateRead: true, + configSaveRead: true, + logAndDependencyRead: true, + }), + ); +})().catch((error) => { + console.error(error.message); + process.exitCode = 1; +}); diff --git a/cli/test/linux/panel-account.cjs b/cli/test/linux/panel-account.cjs index 92acd7c5..fd5b91eb 100644 --- a/cli/test/linux/panel-account.cjs +++ b/cli/test/linux/panel-account.cjs @@ -38,7 +38,11 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance( assert.equal((await login()).code, 200, 'New credentials were not saved'); 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(incorrect)).code, + 400, + 'Expected a rejected password before throttling', + ); } assert.equal( (await login()).code, @@ -49,7 +53,12 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance( 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); + await api( + 'system/auth/reset', + 'PUT', + { twoFactorActivated: true }, + session.data.token, + ); assert.equal( (await login()).code, 420, diff --git a/cli/test/linux/panel-operator.cjs b/cli/test/linux/panel-operator.cjs index bd25c95f..a22a5a30 100644 --- a/cli/test/linux/panel-operator.cjs +++ b/cli/test/linux/panel-operator.cjs @@ -38,7 +38,10 @@ exports.verifyOperator = async function verifyOperator(api) { 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'); + 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')); diff --git a/cli/test/linux/panel-upgrade.cjs b/cli/test/linux/panel-upgrade.cjs index 74af3ba9..bc8a6a2f 100644 --- a/cli/test/linux/panel-upgrade.cjs +++ b/cli/test/linux/panel-upgrade.cjs @@ -2,7 +2,9 @@ const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const { randomUUID } = require('node:crypto'); const { createContext } = require('../../dist/internal/runtime/context'); -const { installPanelDependencies } = require('../../dist/internal/maintenance/operator'); +const { + installPanelDependencies, +} = require('../../dist/internal/maintenance/operator'); const { reloadPanel } = require('../../dist/internal/maintenance/upgrade'); assert.equal(process.env.QL_PANEL_INTEGRATION, '1'); (async () => { diff --git a/cli/test/linux/panel.cjs b/cli/test/linux/panel.cjs index 74bf6a23..eb7d56d3 100644 --- a/cli/test/linux/panel.cjs +++ b/cli/test/linux/panel.cjs @@ -43,10 +43,21 @@ let restoreEntrypoints; const switched = process.env.QL_PANEL_ENTRYPOINTS === '1'; if (switched && process.env.QL_PANEL_PACKAGED === '1') { assert.equal(process.env.QL_CLI_ROOT, '/opt/qinglong-cli'); - for (const [name, module] of [['task', 'task'], ['ql', 'ql']]) { - const target = require('node:path').join(require('node:os').homedir(), 'bin', name); + for (const [name, module] of [ + ['task', 'task'], + ['ql', 'ql'], + ]) { + const target = require('node:path').join( + require('node:os').homedir(), + 'bin', + name, + ); assert.equal((await fs.lstat(target)).isSymbolicLink(), false); - assert.ok((await fs.readFile(target, 'utf8')).includes(Buffer.from(`/opt/qinglong-cli/dist/${module}.js`).toString('base64'))); + assert.ok( + (await fs.readFile(target, 'utf8')).includes( + Buffer.from(`/opt/qinglong-cli/dist/${module}.js`).toString('base64'), + ), + ); } } else if (switched) restoreEntrypoints = @@ -214,7 +225,9 @@ let restoreEntrypoints; })() .catch(() => { // Assertions can embed environment values or subprocess output in their message. - console.error('Disposable panel integration failed; inspect the failing scenario locally.'); + console.error( + 'Disposable panel integration failed; inspect the failing scenario locally.', + ); process.exitCode = 1; }) .finally(async () => { diff --git a/cli/test/linux/published-archive.test.cjs b/cli/test/linux/published-archive.test.cjs index 56309479..73f3843f 100644 --- a/cli/test/linux/published-archive.test.cjs +++ b/cli/test/linux/published-archive.test.cjs @@ -7,7 +7,9 @@ const { createHash } = require('node:crypto'); const { createContext } = require('../../dist/internal/runtime/context'); const operator = require('../../dist/internal/maintenance/operator'); const { stageUpgrade } = require('../../dist/internal/maintenance/upgrade'); -const { cancellableOperation } = require('../../dist/internal/runtime/cancellation'); +const { + cancellableOperation, +} = require('../../dist/internal/runtime/cancellation'); test( 'published master archives pass actual HTTPS download and staging validation', @@ -43,7 +45,9 @@ test( context.paths.dir_tmp, ); installations.push(directory); - await fs.mkdir(path.join(directory, 'node_modules'), { recursive: true }); + await fs.mkdir(path.join(directory, 'node_modules'), { + recursive: true, + }); }, ); const controller = new AbortController(); diff --git a/cli/test/linux/ssh-repository.test.cjs b/cli/test/linux/ssh-repository.test.cjs index ee1e0965..66159a83 100644 --- a/cli/test/linux/ssh-repository.test.cjs +++ b/cli/test/linux/ssh-repository.test.cjs @@ -7,7 +7,9 @@ const net = require('node:net'); const { execFileSync, spawn } = require('node:child_process'); const { setTimeout: delay } = require('node:timers/promises'); const { createContext } = require('../../dist/internal/runtime/context'); -const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner'); +const { + syncRepository, +} = require('../../dist/internal/subscription/subscriptionRunner'); test( 'real SSH subscriptions require the configured identity and pinned host key', diff --git a/cli/test/linux/upgrade.test.cjs b/cli/test/linux/upgrade.test.cjs index 4e9ad42c..19c4fffb 100644 --- a/cli/test/linux/upgrade.test.cjs +++ b/cli/test/linux/upgrade.test.cjs @@ -5,7 +5,10 @@ const os = require('node:os'); const path = require('node:path'); const { fork } = require('node:child_process'); const { createContext } = require('../../dist/internal/runtime/context'); -const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator'); +const { + startPanel, + stopPanel, +} = require('../../dist/internal/maintenance/operator'); const { runProcess } = require('../../dist/internal/runtime/process'); test( diff --git a/cli/test/remote/cli.test.cjs b/cli/test/remote/cli.test.cjs index b3c1d38e..bf8e4ab6 100644 --- a/cli/test/remote/cli.test.cjs +++ b/cli/test/remote/cli.test.cjs @@ -82,10 +82,15 @@ async function fixture(t) { data: { data: [{ id: 12, name: 'example' }], total: 1 }, }); else if ( - ['/panel/open/envs', '/panel/open/configs/files', '/panel/open/scripts', - '/panel/open/subscriptions', '/panel/open/dependencies', - '/panel/open/logs', '/panel/open/dashboard/overview'] - .includes(url.pathname) + [ + '/panel/open/envs', + '/panel/open/configs/files', + '/panel/open/scripts', + '/panel/open/subscriptions', + '/panel/open/dependencies', + '/panel/open/logs', + '/panel/open/dashboard/overview', + ].includes(url.pathname) ) json({ code: 200, data: [] }); else if ( @@ -172,7 +177,13 @@ test('compiled entry: login aliases, private storage, status, refresh and local ['logs:read', '/panel/open/logs'], ['dashboard:read', '/panel/open/dashboard/overview'], ]) { - const checked = await f.invoke(['auth', 'status', '--scope', scope, '--json']); + const checked = await f.invoke([ + 'auth', + 'status', + '--scope', + scope, + '--json', + ]); assert.equal(checked.code, 0, checked.err); assert.equal(JSON.parse(checked.out).data.scopeChecked, scope); assert.equal(f.requests.at(-1).url.pathname, pathname); @@ -338,7 +349,10 @@ test('config content and symlinks are checked independently of permission bits', fs.symlinkSync(target, f.file); const linked = await f.invoke(['task', 'list', '--json'], { QL_LANG: 'en' }); failure(linked, 1); - assert.match(JSON.parse(linked.err).message, /regular file, not a symbolic link/); + assert.match( + JSON.parse(linked.err).message, + /regular file, not a symbolic link/, + ); await f.login(); assert.equal(fs.lstatSync(f.file).isSymbolicLink(), false); assert.equal(JSON.parse(fs.readFileSync(target)).clientId, 123); diff --git a/cli/test/remote/logTruncation.test.cjs b/cli/test/remote/logTruncation.test.cjs index 4c3897a1..be2c0a30 100644 --- a/cli/test/remote/logTruncation.test.cjs +++ b/cli/test/remote/logTruncation.test.cjs @@ -4,26 +4,47 @@ const { task } = require('../../dist/remote/commands/task'); const { subscription } = require('../../dist/remote/commands/subscription'); test('task and subscription logs preserve server truncation as well as local tail limits', async (t) => { - const previous = { url: process.env.QL_URL, token: process.env.QL_ACCESS_TOKEN }; + const previous = { + url: process.env.QL_URL, + token: process.env.QL_ACCESS_TOKEN, + }; process.env.QL_URL = 'http://127.0.0.1'; process.env.QL_ACCESS_TOKEN = 'fixture'; t.after(() => { - for (const [key, value] of [['QL_URL', previous.url], ['QL_ACCESS_TOKEN', previous.token]]) { + for (const [key, value] of [ + ['QL_URL', previous.url], + ['QL_ACCESS_TOKEN', previous.token], + ]) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } }); let response; - t.mock.method(global, 'fetch', async () => new Response(JSON.stringify(response), { - headers: { 'content-type': 'application/json' }, - })); + t.mock.method( + global, + 'fetch', + async () => + new Response(JSON.stringify(response), { + headers: { 'content-type': 'application/json' }, + }), + ); const run = async (tail) => [ await task({ kind: 'logs', id: 1, tail }), - await subscription({ name: 'subscription logs', positionals: ['1'], values: { tail: String(tail) } }), + await subscription({ + name: 'subscription logs', + positionals: ['1'], + values: { tail: String(tail) }, + }), ]; // A byte-limited backend response can contain fewer lines than --tail. - response = { code: 200, data: 'partial long line\nlast line\n', offset: 262144, total: 524288, truncated: true }; + response = { + code: 200, + data: 'partial long line\nlast line\n', + offset: 262144, + total: 524288, + truncated: true, + }; for (const result of await run(200)) { assert.equal(result.data, 'partial long line\nlast line'); assert.equal(result.truncated, true); diff --git a/cli/test/remote/openapi.test.cjs b/cli/test/remote/openapi.test.cjs index fc9fee11..38e1b051 100644 --- a/cli/test/remote/openapi.test.cjs +++ b/cli/test/remote/openapi.test.cjs @@ -15,41 +15,99 @@ async function fixture(t) { const server = http.createServer(async (req, res) => { const chunks = []; for await (const chunk of req) chunks.push(chunk); - const record = { method: req.method, url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString() }; + const record = { + method: req.method, + url: req.url, + headers: req.headers, + body: Buffer.concat(chunks).toString(), + }; requests.push(record); if (reply) return reply(req, res); if (/\/(download|data\/export|command-run)$/.test(req.url)) { - res.writeHead(200, { 'content-type': 'application/json', 'content-disposition': 'attachment; filename="fixture.json"' }); + res.writeHead(200, { + 'content-type': 'application/json', + 'content-disposition': 'attachment; filename="fixture.json"', + }); res.end('{"fixture":true}'); } else if (req.url === '/panel/open/system/log') { - res.writeHead(200, { 'content-type': 'text/plain' }); res.end('log content'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end('log content'); } else { res.setHeader('content-type', 'application/json'); - res.end(JSON.stringify({ code: 200, data: { id: 7, name: 'fixture', client_secret: 'SECRET-MARKER', tokens: [{ value: 'TOKEN-MARKER' }] } })); + res.end( + JSON.stringify({ + code: 200, + data: { + id: 7, + name: 'fixture', + client_secret: 'SECRET-MARKER', + tokens: [{ value: 'TOKEN-MARKER' }], + }, + }), + ); } }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await fs.rm(root, { recursive: true, force: true }); }); - const url = `http://127.0.0.1:${server.address().port}/panel`; - const run = (args, stdin = '', extra = {}) => new Promise((resolve, reject) => { - const child = spawn(process.execPath, [entry, ...args, '--json'], { - env: { PATH: process.env.PATH, QL_URL: url, QL_ACCESS_TOKEN: 'fixture-token', QL_LANG: 'en', ...extra }, - stdio: ['pipe', 'pipe', 'pipe'], - }); - let out = '', err = ''; - const timer = setTimeout(() => { child.kill(); reject(new Error('CLI timeout')); }, 12000); - child.stdout.on('data', data => { out += data; }); child.stderr.on('data', data => { err += data; }); - child.on('error', reject); child.on('close', code => { clearTimeout(timer); resolve({ code, out, err }); }); - child.stdin.end(stdin); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + await fs.rm(root, { recursive: true, force: true }); }); - return { root, requests, run, reply: value => { reply = value; } }; + const url = `http://127.0.0.1:${server.address().port}/panel`; + const run = (args, stdin = '', extra = {}) => + new Promise((resolve, reject) => { + const child = spawn(process.execPath, [entry, ...args, '--json'], { + env: { + PATH: process.env.PATH, + QL_URL: url, + QL_ACCESS_TOKEN: 'fixture-token', + QL_LANG: 'en', + ...extra, + }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + let out = '', + err = ''; + const timer = setTimeout(() => { + child.kill(); + reject(new Error('CLI timeout')); + }, 12000); + child.stdout.on('data', (data) => { + out += data; + }); + child.stderr.on('data', (data) => { + err += data; + }); + child.on('error', reject); + child.on('close', (code) => { + clearTimeout(timer); + resolve({ code, out, err }); + }); + child.stdin.end(stdin); + }); + return { + root, + requests, + run, + reply: (value) => { + reply = value; + }, + }; +} +function success(result) { + assert.equal(result.code, 0, result.err); + return JSON.parse(result.out); } -function success(result) { assert.equal(result.code, 0, result.err); return JSON.parse(result.out); } -test('dashboard record sends execution statistics and rejects a missing body before HTTP', async t => { +test('dashboard record sends execution statistics and rejects a missing body before HTTP', async (t) => { const f = await fixture(t); const payload = { ref_id: 7, code: 0, elapsed: 1.5 }; - success(await f.run(['dashboard', 'record', '--data', '-'], JSON.stringify(payload))); + success( + await f.run( + ['dashboard', 'record', '--data', '-'], + JSON.stringify(payload), + ), + ); assert.equal(f.requests.length, 1); assert.equal(f.requests[0].method, 'POST'); assert.equal(f.requests[0].url, '/panel/open/dashboard/record'); @@ -58,7 +116,7 @@ test('dashboard record sends execution statistics and rejects a missing body bef assert.equal(f.requests.length, 1); }); -test('schedule anomaly commands preserve sources, pagination and expired responses', async t => { +test('schedule anomaly commands preserve sources, pagination and expired responses', async (t) => { const f = await fixture(t); const response = { code: 200, data: { status: 'expired' } }; f.reply((_req, res) => { @@ -67,19 +125,38 @@ test('schedule anomaly commands preserve sources, pagination and expired respons }); for (const source of ['panel', 'system']) { for (const kind of ['missing', 'skipped', 'unconfirmed']) { - const query = { source, kind, at: 1795046400000, page: 3, revision: 'a'.repeat(64), live: true }; + const query = { + source, + kind, + at: 1795046400000, + page: 3, + revision: 'a'.repeat(64), + live: true, + }; for (const command of [ ['dashboard', 'schedule-anomalies'], ['api', 'request', 'GET', '/open/dashboard/schedule-anomalies'], ]) { const before = f.requests.length; - assert.deepEqual(success(await f.run([...command, '--query', JSON.stringify(query)])), response); - assert.equal(f.requests.length, before + 1, 'expired responses must not be retried'); - const req = f.requests.at(-1), url = new URL(req.url, 'http://localhost'); + assert.deepEqual( + success(await f.run([...command, '--query', JSON.stringify(query)])), + response, + ); + assert.equal( + f.requests.length, + before + 1, + 'expired responses must not be retried', + ); + const req = f.requests.at(-1), + url = new URL(req.url, 'http://localhost'); assert.equal(req.method, 'GET'); assert.equal(url.pathname, '/panel/open/dashboard/schedule-anomalies'); - assert.deepEqual(Object.fromEntries(url.searchParams), - Object.fromEntries(Object.entries(query).map(([key, value]) => [key, String(value)]))); + assert.deepEqual( + Object.fromEntries(url.searchParams), + Object.fromEntries( + Object.entries(query).map(([key, value]) => [key, String(value)]), + ), + ); assert.equal(req.body, ''); assert.equal(req.headers.authorization, 'Bearer fixture-token'); } @@ -87,7 +164,7 @@ test('schedule anomaly commands preserve sources, pagination and expired respons } }); -test('script history commands send exact query parameters and restore payloads', async t => { +test('script history commands send exact query parameters and restore payloads', async (t) => { const f = await fixture(t); const identity = { filename: '中文 script.js', path: 'nested folder' }; const version = { ...identity, id: '32ec8b22-2c48-4bcf-85d4-b394198417ba' }; @@ -96,25 +173,38 @@ test('script history commands send exact query parameters and restore payloads', ['history-detail', 'scripts/history/detail', version], ]) { success(await f.run(['script', command, '--query', JSON.stringify(query)])); - const req = f.requests.at(-1), url = new URL(req.url, 'http://localhost'); + const req = f.requests.at(-1), + url = new URL(req.url, 'http://localhost'); assert.equal(req.method, 'GET'); assert.equal(url.pathname, '/panel/open/' + endpoint); - for (const [key, value] of Object.entries(query)) assert.equal(url.searchParams.get(key), value); + for (const [key, value] of Object.entries(query)) + assert.equal(url.searchParams.get(key), value); assert.equal(req.body, ''); } const payload = { ...version, expectedHash: 'a'.repeat(64) }; - success(await f.run(['script', 'history-restore', '--data', '-'], JSON.stringify(payload))); + success( + await f.run( + ['script', 'history-restore', '--data', '-'], + JSON.stringify(payload), + ), + ); assert.equal(f.requests.at(-1).method, 'PUT'); assert.equal(f.requests.at(-1).url, '/panel/open/scripts/history/restore'); assert.deepEqual(JSON.parse(f.requests.at(-1).body), payload); const count = f.requests.length; assert.equal((await f.run(['script', 'history-restore'])).code, 2); - assert.equal(f.requests.length, count, 'missing restore payload must not issue a request'); + assert.equal( + f.requests.length, + count, + 'missing restore payload must not issue a request', + ); }); -test('dependency refresh commands send the dependency type and address background jobs', async t => { +test('dependency refresh commands send the dependency type and address background jobs', async (t) => { const f = await fixture(t); - success(await f.run(['dependency', 'refresh', '--data', '{"type":"python3"}'])); + success( + await f.run(['dependency', 'refresh', '--data', '{"type":"python3"}']), + ); assert.equal(f.requests[0].method, 'POST'); assert.equal(f.requests[0].url, '/panel/open/dependencies/refresh'); assert.deepEqual(JSON.parse(f.requests[0].body), { type: 'python3' }); @@ -125,164 +215,378 @@ test('dependency refresh commands send the dependency type and address backgroun success(await f.run(['dependency', 'refresh-active'])); assert.equal(f.requests[2].method, 'GET'); assert.equal(f.requests[2].url, '/panel/open/dependencies/refresh/active'); - success(await f.run(['api', 'request', 'GET', `/open/dependencies/refresh/${id}`])); + success( + await f.run(['api', 'request', 'GET', `/open/dependencies/refresh/${id}`]), + ); assert.equal(f.requests[3].url, `/panel/open/dependencies/refresh/${id}`); assert.equal((await f.run(['dependency', 'refresh-status', '7'])).code, 2); - assert.equal((await f.run(['api', 'request', 'GET', '/open/dependencies/refresh/7'])).code, 2); + assert.equal( + (await f.run(['api', 'request', 'GET', '/open/dependencies/refresh/7'])) + .code, + 2, + ); assert.equal((await f.run(['dependency', 'refresh'])).code, 2); - assert.equal(f.requests.length, 4, 'invalid arguments must not issue a request'); + assert.equal( + f.requests.length, + 4, + 'invalid arguments must not issue a request', + ); }); test('OpenAPI catalogue covers every active registered backend route; retired 410 routes are explicit', async () => { const root = path.resolve(__dirname, '../../../back/api'); const expected = []; - const retired = new Set(['GET configs/:file', 'GET scripts/:file', 'GET logs/:file']); + const retired = new Set([ + 'GET configs/:file', + 'GET scripts/:file', + 'GET logs/:file', + ]); const index = await fs.readFile(path.join(root, 'index.ts'), 'utf8'); for (const filename of await fs.readdir(root)) { if (!filename.endsWith('.ts') || filename === 'index.ts') continue; const source = await fs.readFile(path.join(root, filename), 'utf8'); - assert.ok(index.includes(`'./${filename.slice(0, -3)}'`), `Unregistered API module ${filename}`); + assert.ok( + index.includes(`'./${filename.slice(0, -3)}'`), + `Unregistered API module ${filename}`, + ); const mount = /app\.use\(['"]([^'"]+)['"]/.exec(source); assert.ok(mount, filename); - for (const m of source.matchAll(/route\.(get|post|put|delete|patch)\(\s*['"]([^'"]+)['"]/g)) { - const endpoint = [mount[1], m[2]].join('/').split('/').filter(Boolean).join('/'); + for (const m of source.matchAll( + /route\.(get|post|put|delete|patch)\(\s*['"]([^'"]+)['"]/g, + )) { + const endpoint = [mount[1], m[2]] + .join('/') + .split('/') + .filter(Boolean) + .join('/'); const key = `${m[1].toUpperCase()} ${endpoint}`; if (!retired.has(key)) expected.push(key); else assert.match(source.slice(m.index, m.index + 200), /code: 410/); } } - const actual = openOperations.map(op => `${op.method} ${op.path}`); + const actual = openOperations.map((op) => `${op.method} ${op.path}`); assert.equal(new Set(actual).size, actual.length); - assert.equal(new Set(openOperations.map(op => op.name)).size, openOperations.length); + assert.equal( + new Set(openOperations.map((op) => op.name)).size, + openOperations.length, + ); assert.deepEqual(actual.sort(), expected.sort()); }); -test('task, subscription and app CRUD produce exact 2.x requests and protect app credentials', async t => { +test('task, subscription and app CRUD produce exact 2.x requests and protect app credentials', async (t) => { const f = await fixture(t); - success(await f.run(['task', 'create', '--name', 'demo', '--command', 'task demo.js', '--schedule', '0 0 * * *'])); - assert.deepEqual(JSON.parse(f.requests.at(-1).body), { name: 'demo', command: 'task demo.js', schedule: '0 0 * * *' }); - assert.equal(f.requests.at(-1).method, 'POST'); assert.equal(f.requests.at(-1).url, '/panel/open/crons'); - success(await f.run(['task', 'update', '7', '--data', '-', '--name', 'updated'], '{"command":"task demo.js","schedule":"0 1 * * *"}')); - assert.deepEqual(JSON.parse(f.requests.at(-1).body), { id: 7, name: 'updated', command: 'task demo.js', schedule: '0 1 * * *' }); - success(await f.run(['task', 'delete', '7', '8'])); assert.deepEqual(JSON.parse(f.requests.at(-1).body), [7, 8]); + success( + await f.run([ + 'task', + 'create', + '--name', + 'demo', + '--command', + 'task demo.js', + '--schedule', + '0 0 * * *', + ]), + ); + assert.deepEqual(JSON.parse(f.requests.at(-1).body), { + name: 'demo', + command: 'task demo.js', + schedule: '0 0 * * *', + }); + assert.equal(f.requests.at(-1).method, 'POST'); + assert.equal(f.requests.at(-1).url, '/panel/open/crons'); + success( + await f.run( + ['task', 'update', '7', '--data', '-', '--name', 'updated'], + '{"command":"task demo.js","schedule":"0 1 * * *"}', + ), + ); + assert.deepEqual(JSON.parse(f.requests.at(-1).body), { + id: 7, + name: 'updated', + command: 'task demo.js', + schedule: '0 1 * * *', + }); + success(await f.run(['task', 'delete', '7', '8'])); + assert.deepEqual(JSON.parse(f.requests.at(-1).body), [7, 8]); assert.equal(f.requests.at(-1).method, 'DELETE'); - success(await f.run(['subscription', 'create', '--type', 'public-repo', '--url', 'https://example.com/repo.git', '--alias', 'demo', '--schedule-type', 'crontab', '--schedule', '0 0 * * *'])); + success( + await f.run([ + 'subscription', + 'create', + '--type', + 'public-repo', + '--url', + 'https://example.com/repo.git', + '--alias', + 'demo', + '--schedule-type', + 'crontab', + '--schedule', + '0 0 * * *', + ]), + ); assert.equal(f.requests.at(-1).url, '/panel/open/subscriptions'); assert.equal(JSON.parse(f.requests.at(-1).body).schedule_type, 'crontab'); - const app = success(await f.run(['app', 'create', '--name', 'worker', '--scopes', 'crons,subscriptions'])); - assert.deepEqual(JSON.parse(f.requests.at(-1).body), { name: 'worker', scopes: ['crons', 'subscriptions'] }); - assert.equal(app.data.client_secret, undefined); assert.equal(app.data.tokens, undefined); - assert.equal(success(await f.run(['app', 'reset-secret', '7', '--show-secrets'])).data.client_secret, 'SECRET-MARKER'); + const app = success( + await f.run([ + 'app', + 'create', + '--name', + 'worker', + '--scopes', + 'crons,subscriptions', + ]), + ); + assert.deepEqual(JSON.parse(f.requests.at(-1).body), { + name: 'worker', + scopes: ['crons', 'subscriptions'], + }); + assert.equal(app.data.client_secret, undefined); + assert.equal(app.data.tokens, undefined); + assert.equal( + success(await f.run(['app', 'reset-secret', '7', '--show-secrets'])).data + .client_secret, + 'SECRET-MARKER', + ); assert.equal(f.requests.at(-1).url, '/panel/open/apps/7/reset-secret'); - for (const req of f.requests) assert.equal(req.headers.authorization, 'Bearer fixture-token'); + for (const req of f.requests) + assert.equal(req.headers.authorization, 'Bearer fixture-token'); }); -test('all added named operations reach their registered method/path, including upload/download and anonymous routes', async t => { +test('all added named operations reach their registered method/path, including upload/download and anonymous routes', async (t) => { const f = await fixture(t); - const file = path.join(f.root, 'fixture.json'); await fs.writeFile(file, '{}'); - for (const op of openOperations.filter(op => !op.existing)) { + const file = path.join(f.root, 'fixture.json'); + await fs.writeFile(file, '{}'); + for (const op of openOperations.filter((op) => !op.existing)) { const args = op.name.split(' '); - const parameter = name => op.uuidParams?.includes(name) ? '32ec8b22-2c48-4bcf-85d4-b394198417ba' : '7'; + const parameter = (name) => + op.uuidParams?.includes(name) + ? '32ec8b22-2c48-4bcf-85d4-b394198417ba' + : '7'; for (const name of op.params ?? []) args.push(parameter(name)); if (op.body === 'ids') args.push('7', '8'); else if (op.body) { - const data = op.name.startsWith('task ') ? { command: 'echo fixture', schedule: '0 0 * * *' } - : op.name.startsWith('subscription ') ? { type: 'file', url: 'https://example.com/job.js', alias: 'job', schedule_type: 'crontab' } : {}; + const data = op.name.startsWith('task ') + ? { command: 'echo fixture', schedule: '0 0 * * *' } + : op.name.startsWith('subscription ') + ? { + type: 'file', + url: 'https://example.com/job.js', + alias: 'job', + schedule_type: 'crontab', + } + : {}; args.push('--data', JSON.stringify(data)); } if (op.upload) args.push('--file', file); - if (op.download) args.push('--output', path.join(f.root, op.name.replace(' ', '-') + '.out')); + if (op.download) + args.push( + '--output', + path.join(f.root, op.name.replace(' ', '-') + '.out'), + ); success(await f.run(args)); const last = f.requests.at(-1); assert.equal(last.method, op.method, op.name); - assert.equal(last.url, '/panel/open/' + op.path.replace(/:([A-Za-z]+)/g, (_match, name) => parameter(name)), op.name); - assert.equal(last.headers.authorization, op.anonymous ? undefined : 'Bearer fixture-token', op.name); - if (op.upload) assert.ok(last.body.includes(`name="${op.upload}"; filename="fixture.json"`), op.name); + assert.equal( + last.url, + '/panel/open/' + + op.path.replace(/:([A-Za-z]+)/g, (_match, name) => parameter(name)), + op.name, + ); + assert.equal( + last.headers.authorization, + op.anonymous ? undefined : 'Bearer fixture-token', + op.name, + ); + if (op.upload) + assert.ok( + last.body.includes(`name="${op.upload}"; filename="fixture.json"`), + op.name, + ); } }); -test('raw route access retains query/body capabilities and rejects unsupported paths before authentication', async t => { +test('raw route access retains query/body capabilities and rejects unsupported paths before authentication', async (t) => { const f = await fixture(t); - success(await f.run(['api', 'request', 'GET', '/open/crons', '--query', '{"searchValue":"a & b","page":2}'])); - assert.equal(f.requests.at(-1).url, '/panel/open/crons?searchValue=a+%26+b&page=2'); - const bodyFile = path.join(f.root, 'env.json'); await fs.writeFile(bodyFile, '[{"name":"A","value":"B"}]'); + success( + await f.run([ + 'api', + 'request', + 'GET', + '/open/crons', + '--query', + '{"searchValue":"a & b","page":2}', + ]), + ); + assert.equal( + f.requests.at(-1).url, + '/panel/open/crons?searchValue=a+%26+b&page=2', + ); + const bodyFile = path.join(f.root, 'env.json'); + await fs.writeFile(bodyFile, '[{"name":"A","value":"B"}]'); success(await f.run(['env', 'create', '--data', '@' + bodyFile])); assert.equal(f.requests.at(-1).body, '[{"name":"A","value":"B"}]'); const count = f.requests.length; for (const args of [ - ['api', 'request', 'GET', 'https://example.com'], ['api', 'request', 'DELETE', 'auth/token'], - ['api', 'request', 'GET', '../api/user'], ['api', 'request', 'GET', 'crons/0'], ['api', 'request', 'GET', 'crons/9007199254740993'], - ['task', 'create', '--data', '{'], ['task', 'create', '--command', 'echo fixture'], - ['task', 'update', '7', '--data', '{"id":8}'], ['task', 'delete', '-1'], + ['api', 'request', 'GET', 'https://example.com'], + ['api', 'request', 'DELETE', 'auth/token'], + ['api', 'request', 'GET', '../api/user'], + ['api', 'request', 'GET', 'crons/0'], + ['api', 'request', 'GET', 'crons/9007199254740993'], + ['task', 'create', '--data', '{'], + ['task', 'create', '--command', 'echo fixture'], + ['task', 'update', '7', '--data', '{"id":8}'], + ['task', 'delete', '-1'], ['env', 'list', '--query', '{"secret":{"value":1}}'], ['app', 'create', '--data', '{"name":"A"}', '--name', 'B'], ['log', 'download', '--data', '{}', '--output', bodyFile], - ]) { const result = await f.run(args); assert.equal(result.code, 2, JSON.stringify(args) + result.err); assert.equal(result.out, ''); } + ]) { + const result = await f.run(args); + assert.equal(result.code, 2, JSON.stringify(args) + result.err); + assert.equal(result.out, ''); + } assert.equal(f.requests.length, count); const output = path.join(f.root, 'download.json'); - success(await f.run(['log', 'download', '--data', '{"filename":"fixture.json"}', '--output', output])); + success( + await f.run([ + 'log', + 'download', + '--data', + '{"filename":"fixture.json"}', + '--output', + output, + ]), + ); assert.equal(await fs.readFile(output, 'utf8'), '{"fixture":true}'); assert.equal((await fs.stat(output)).mode & 0o777, 0o600); }); -test('POST/DELETE uncertainty and permission failures never retry or print server secrets', async t => { +test('POST/DELETE uncertainty and permission failures never retry or print server secrets', async (t) => { const f = await fixture(t); - f.reply((_req, res) => { res.writeHead(503); res.end('SERVER-SECRET'); }); - for (const args of [['task', 'create', '--command', 'echo fixture', '--schedule', '0 0 * * *'], ['task', 'delete', '7']]) { - const count = f.requests.length; const result = await f.run(args); - assert.equal(result.code, 1); assert.match(result.err, /unknown|retry/i); - assert.doesNotMatch(result.err, /SERVER-SECRET/); assert.equal(f.requests.length, count + 1); + f.reply((_req, res) => { + res.writeHead(503); + res.end('SERVER-SECRET'); + }); + for (const args of [ + ['task', 'create', '--command', 'echo fixture', '--schedule', '0 0 * * *'], + ['task', 'delete', '7'], + ]) { + const count = f.requests.length; + const result = await f.run(args); + assert.equal(result.code, 1); + assert.match(result.err, /unknown|retry/i); + assert.doesNotMatch(result.err, /SERVER-SECRET/); + assert.equal(f.requests.length, count + 1); } - f.reply((_req, res) => { res.writeHead(403); res.end('SERVER-SECRET'); }); - const result = await f.run(['app', 'list']); assert.equal(result.code, 3); assert.match(result.err, /apps/); + f.reply((_req, res) => { + res.writeHead(403); + res.end('SERVER-SECRET'); + }); + const result = await f.run(['app', 'list']); + assert.equal(result.code, 3); + assert.match(result.err, /apps/); assert.doesNotMatch(result.err, /SERVER-SECRET/); }); -test('failed downloads leave no partial files and timed-out mutations are not replayed', async t => { +test('failed downloads leave no partial files and timed-out mutations are not replayed', async (t) => { const f = await fixture(t); const output = path.join(f.root, 'partial.log'); f.reply((_req, res) => { - res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.write('partial'); + res.writeHead(200, { 'content-type': 'application/octet-stream' }); + res.write('partial'); setTimeout(() => res.destroy(), 50); }); - const failed = await f.run(['log', 'download', '--data', '{"filename":"fixture.log"}', '--output', output]); - assert.equal(failed.code, 1); assert.equal(failed.out, ''); + const failed = await f.run([ + 'log', + 'download', + '--data', + '{"filename":"fixture.log"}', + '--output', + output, + ]); + assert.equal(failed.code, 1); + assert.equal(failed.out, ''); await assert.rejects(fs.stat(output), { code: 'ENOENT' }); f.reply(() => {}); const count = f.requests.length; - const timeout = await f.run(['app', 'create', '--name', 'fixture', '--scopes', 'crons', '--timeout', '1']); - assert.equal(timeout.code, 1); assert.match(timeout.err, /unknown/); + const timeout = await f.run([ + 'app', + 'create', + '--name', + 'fixture', + '--scopes', + 'crons', + '--timeout', + '1', + ]); + assert.equal(timeout.code, 1); + assert.match(timeout.err, /unknown/); assert.equal(f.requests.length, count + 1); }); -test('owner two-factor challenge remains actionable without exposing server messages', async t => { +test('owner two-factor challenge remains actionable without exposing server messages', async (t) => { const f = await fixture(t); - f.reply((_req, res) => { res.setHeader('content-type', 'application/json'); res.end('{"code":420,"message":"SERVER-SECRET"}'); }); - const result = await f.run(['user', 'login', '--data', '{"username":"fixture","password":"fixture"}']); - assert.equal(result.code, 3); assert.match(result.err, /two-factor-login/); assert.doesNotMatch(result.err, /SERVER-SECRET/); - assert.equal(f.requests.length, 1); assert.equal(f.requests[0].headers.authorization, undefined); + f.reply((_req, res) => { + res.setHeader('content-type', 'application/json'); + res.end('{"code":420,"message":"SERVER-SECRET"}'); + }); + const result = await f.run([ + 'user', + 'login', + '--data', + '{"username":"fixture","password":"fixture"}', + ]); + assert.equal(result.code, 3); + assert.match(result.err, /two-factor-login/); + assert.doesNotMatch(result.err, /SERVER-SECRET/); + assert.equal(f.requests.length, 1); + assert.equal(f.requests[0].headers.authorization, undefined); }); -test('node mirror configuration accepts the real empty response for named and raw API commands', async t => { +test('node mirror configuration accepts the real empty response for named and raw API commands', async (t) => { const f = await fixture(t); - f.reply((_req, res) => { res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(); }); + f.reply((_req, res) => { + res.writeHead(200, { 'content-type': 'application/octet-stream' }); + res.end(); + }); for (const args of [ ['system', 'config-node-mirror'], ['api', 'request', 'PUT', '/open/system/config/node-mirror'], ]) { - const reply = success(await f.run([...args, '--data', '{"nodeMirror":"https://registry.npmmirror.com"}'])); + const reply = success( + await f.run([ + ...args, + '--data', + '{"nodeMirror":"https://registry.npmmirror.com"}', + ]), + ); assert.equal(reply.code, 200); assert.equal(f.requests.at(-1).method, 'PUT'); - assert.equal(f.requests.at(-1).url, '/panel/open/system/config/node-mirror'); + assert.equal( + f.requests.at(-1).url, + '/panel/open/system/config/node-mirror', + ); } - assert.equal(f.requests.length, 2, 'configuration writes must not be retried'); + assert.equal( + f.requests.length, + 2, + 'configuration writes must not be retried', + ); }); -test('empty node mirror responses still reject authentication and server failures without retries', async t => { +test('empty node mirror responses still reject authentication and server failures without retries', async (t) => { const f = await fixture(t); for (const status of [401, 403, 500]) { - f.reply((_req, res) => { res.writeHead(status, { 'content-type': 'application/octet-stream' }); res.end(); }); - const result = await f.run(['system', 'config-node-mirror', '--data', '{}']); + f.reply((_req, res) => { + res.writeHead(status, { 'content-type': 'application/octet-stream' }); + res.end(); + }); + const result = await f.run([ + 'system', + 'config-node-mirror', + '--data', + '{}', + ]); assert.notEqual(result.code, 0); assert.equal(result.out, ''); } diff --git a/cli/test/remote/platformSmoke.test.cjs b/cli/test/remote/platformSmoke.test.cjs index 6b44ed25..4d707877 100644 --- a/cli/test/remote/platformSmoke.test.cjs +++ b/cli/test/remote/platformSmoke.test.cjs @@ -17,13 +17,15 @@ test('saved login works on the host filesystem', async (t) => { if (url.pathname === '/panel/open/auth/token') { assert.equal(url.searchParams.get('client_id'), 'smoke-id'); assert.equal(url.searchParams.get('client_secret'), 'smoke-secret'); - res.end(JSON.stringify({ - code: 200, - data: { - token: 'smoke-token', - expiration: Math.floor(Date.now() / 1000) + 3600, - }, - })); + res.end( + JSON.stringify({ + code: 200, + data: { + token: 'smoke-token', + expiration: Math.floor(Date.now() / 1000) + 3600, + }, + }), + ); return; } assert.equal(req.headers.authorization, 'Bearer smoke-token'); @@ -48,18 +50,19 @@ test('saved login works on the host filesystem', async (t) => { QL_URL: '', QL_ACCESS_TOKEN: '', }; - const invoke = (args) => new Promise((resolve, reject) => { - const child = spawn(process.execPath, [entry, ...args], { - env, - stdio: ['ignore', 'pipe', 'pipe'], + const invoke = (args) => + new Promise((resolve, reject) => { + const child = spawn(process.execPath, [entry, ...args], { + env, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let out = ''; + let err = ''; + child.stdout.on('data', (data) => (out += data)); + child.stderr.on('data', (data) => (err += data)); + child.once('error', reject); + child.once('close', (code) => resolve({ code, out, err })); }); - let out = ''; - let err = ''; - child.stdout.on('data', (data) => (out += data)); - child.stderr.on('data', (data) => (err += data)); - child.once('error', reject); - child.once('close', (code) => resolve({ code, out, err })); - }); const url = `http://127.0.0.1:${server.address().port}/panel`; const login = await invoke(['login', '--url', url, '--json']); assert.equal(login.code, 0, login.err); diff --git a/cli/test/remote/rawCredentials.test.cjs b/cli/test/remote/rawCredentials.test.cjs index 786704c7..62ae0ca3 100644 --- a/cli/test/remote/rawCredentials.test.cjs +++ b/cli/test/remote/rawCredentials.test.cjs @@ -6,7 +6,9 @@ const os = require('node:os'); const http = require('node:http'); const { randomUUID } = require('node:crypto'); const { createContext } = require('../../dist/internal/runtime/context'); -const { syncRaw } = require('../../dist/internal/subscription/subscriptionRunner'); +const { + syncRaw, +} = require('../../dist/internal/subscription/subscriptionRunner'); const { runProcess } = require('../../dist/internal/runtime/process'); test('raw subscriptions retain legacy netrc authentication and preserve files on denied access', async (t) => { diff --git a/cli/test/remote/requestBodyCoverage.test.cjs b/cli/test/remote/requestBodyCoverage.test.cjs index fd3260c5..74c057ea 100644 --- a/cli/test/remote/requestBodyCoverage.test.cjs +++ b/cli/test/remote/requestBodyCoverage.test.cjs @@ -8,22 +8,42 @@ const { openOperations } = require('../../dist/remote/api/openOperations'); test('body-consuming backend routes expose a CLI request body or upload', () => { const root = path.resolve(__dirname, '../../../back/api'); let checked = 0; - for (const filename of fs.readdirSync(root).filter(name => name.endsWith('.ts'))) { + for (const filename of fs + .readdirSync(root) + .filter((name) => name.endsWith('.ts'))) { const text = fs.readFileSync(path.join(root, filename), 'utf8'); const mount = text.match(/app\.use\(['"]([^'"]+)/)?.[1]; if (!mount) continue; - const source = ts.createSourceFile(filename, text, ts.ScriptTarget.Latest, true); - const visit = node => { - if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) - && node.expression.expression.getText(source) === 'route' - && ['post', 'put', 'delete'].includes(node.expression.name.text) - && node.arguments[0] && ts.isStringLiteral(node.arguments[0]) - && /\breq\.body\b/.test(node.getText(source))) { - const endpoint = [mount, node.arguments[0].text].join('/').split('/').filter(Boolean).join('/'); + const source = ts.createSourceFile( + filename, + text, + ts.ScriptTarget.Latest, + true, + ); + const visit = (node) => { + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) && + node.expression.expression.getText(source) === 'route' && + ['post', 'put', 'delete'].includes(node.expression.name.text) && + node.arguments[0] && + ts.isStringLiteral(node.arguments[0]) && + /\breq\.body\b/.test(node.getText(source)) + ) { + const endpoint = [mount, node.arguments[0].text] + .join('/') + .split('/') + .filter(Boolean) + .join('/'); const method = node.expression.name.text.toUpperCase(); - const operation = openOperations.find(item => item.method === method && item.path === endpoint); + const operation = openOperations.find( + (item) => item.method === method && item.path === endpoint, + ); assert.ok(operation, `${method} ${endpoint} is missing`); - assert.ok(operation.body || operation.upload, `${operation.name} cannot provide req.body`); + assert.ok( + operation.body || operation.upload, + `${operation.name} cannot provide req.body`, + ); checked++; } ts.forEachChild(node, visit); diff --git a/cli/test/remote/scope.test.cjs b/cli/test/remote/scope.test.cjs index 1650b5a1..06e866b9 100644 --- a/cli/test/remote/scope.test.cjs +++ b/cli/test/remote/scope.test.cjs @@ -11,18 +11,47 @@ test('public task entries retain no-argument script discovery and help stays rea const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-public-inventory-')); t.after(() => fs.rm(root, { recursive: true, force: true })); await fs.mkdir(path.join(root, 'data/scripts'), { recursive: true }); - await fs.writeFile(path.join(root, 'data/scripts/job.js'), 'throw Error("do not execute"); const $ = new Env("Job");'); - for (const [entry, args] of [['task', []], ['ql', ['task']]]) { - const run = (...extra) => spawnSync(process.execPath, [path.resolve(__dirname, `../../dist/${entry}.js`), ...args, ...extra, '--json'], { env: { PATH: process.env.PATH, QL_DIR: root }, encoding: 'utf8' }); + await fs.writeFile( + path.join(root, 'data/scripts/job.js'), + 'throw Error("do not execute"); const $ = new Env("Job");', + ); + for (const [entry, args] of [ + ['task', []], + ['ql', ['task']], + ]) { + const run = (...extra) => + spawnSync( + process.execPath, + [ + path.resolve(__dirname, `../../dist/${entry}.js`), + ...args, + ...extra, + '--json', + ], + { env: { PATH: process.env.PATH, QL_DIR: root }, encoding: 'utf8' }, + ); const listing = run(); assert.equal(listing.status, 0, listing.stderr); - assert.deepEqual(JSON.parse(listing.stdout).data.scripts, [{ file: 'job.js', name: 'Job' }]); + assert.deepEqual(JSON.parse(listing.stdout).data.scripts, [ + { file: 'job.js', name: 'Job' }, + ]); assert.equal(JSON.parse(run('--help').stdout).data.scripts, undefined); } }); test('removed development publication is rejected before doing any work', () => { - const result = spawnSync(process.execPath, [path.resolve(__dirname, '../../dist/ql.js'), 'dev', 'release', '--root', '/absent', '--json'], { encoding: 'utf8' }); + const result = spawnSync( + process.execPath, + [ + path.resolve(__dirname, '../../dist/ql.js'), + 'dev', + 'release', + '--root', + '/absent', + '--json', + ], + { encoding: 'utf8' }, + ); assert.equal(result.status, 2); assert.equal(result.stdout, ''); assert.equal(JSON.parse(result.stderr).code, 2); @@ -39,13 +68,18 @@ test('health probes use the base path and reject failed or malformed scheduler h } else if (req.url === '/ql/') res.end('
'); else res.end('{"code":200,"data":{"version":"2.21.0"}}'); }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - t.after(() => new Promise(resolve => server.close(resolve))); - const context = { env: { QlPort: String(server.address().port), QlBaseUrl: '/ql/' } }; + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const context = { + env: { QlPort: String(server.address().port), QlBaseUrl: '/ql/' }, + }; assert.equal((await inspectPanel(context)).backend.healthy, false); health = { status: 200, body: { code: 200, data: {} } }; assert.equal((await inspectPanel(context)).backend.healthy, false); health = { status: 200, body: { code: 200, data: { status: 'ok' } } }; assert.equal((await inspectPanel(context)).backend.healthy, true); - assert.equal(seen.some(route => route.includes('/api/system')), false); + assert.equal( + seen.some((route) => route.includes('/api/system')), + false, + ); }); diff --git a/cli/test/remote/subscription.test.cjs b/cli/test/remote/subscription.test.cjs index 200cdc83..95e8a0ed 100644 --- a/cli/test/remote/subscription.test.cjs +++ b/cli/test/remote/subscription.test.cjs @@ -18,10 +18,9 @@ test('public CLI excludes local maintenance while the admin entry retains compat parse(['--help'], 'local').help, /subscription list|auth login/, ); - assert.throws( - () => parse(['auth', 'status', '--scope', 'all']), - { exitCode: 2 }, - ); + assert.throws(() => parse(['auth', 'status', '--scope', 'all']), { + exitCode: 2, + }); }); test('subscription management uses panel API, projects credentials out and never invokes local repo/raw', async (t) => { diff --git a/cli/test/remote/taskRun.test.cjs b/cli/test/remote/taskRun.test.cjs new file mode 100644 index 00000000..b84a8ccc --- /dev/null +++ b/cli/test/remote/taskRun.test.cjs @@ -0,0 +1,320 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); +const entry = path.resolve(__dirname, '../../dist/npm/ql.js'); +const triggerId = '6ecf88e9-b7dc-42c9-b2a6-47a0d707aceb-12'; + +async function fixture(t) { + const requests = []; + const state = { + run: [{ taskId: 12, triggerId, state: 'queued', reason: null }], + rows: [ + { + id: triggerId, + cron_id: 12, + state: 'finished', + reason: null, + exit_code: 0, + }, + ], + log: { + code: 200, + triggerId, + data: 'this run\nlast line\n', + logStatus: 'completed', + }, + polls: 0, + }; + const server = http.createServer(async (req, res) => { + let body = ''; + for await (const chunk of req) body += chunk; + const url = new URL(req.url, 'http://localhost'); + requests.push({ + path: url.pathname, + query: url.searchParams, + method: req.method, + body, + }); + assert.equal(req.headers.authorization, 'Bearer fixture'); + res.setHeader('content-type', 'application/json'); + if (url.pathname === '/panel/open/crons/run') { + assert.equal(req.method, 'PUT'); + assert.equal(body, '[12]'); + return res.end(JSON.stringify({ code: 200, data: state.run })); + } + if (url.pathname === '/panel/open/crons/12/triggers') { + assert.equal(url.searchParams.get('ids'), triggerId); + state.polls++; + if (state.hang) return; + if (state.denied) { + res.statusCode = 403; + return res.end('{}'); + } + if (state.disconnect) return req.socket.destroy(); + const data = + state.polls <= (state.pending || 0) + ? [ + { + id: triggerId, + cron_id: 12, + state: 'running', + reason: null, + exit_code: null, + }, + ] + : state.rows; + return res.end(JSON.stringify({ code: 200, data })); + } + if (url.pathname === '/panel/open/crons/12/log') + return res.end(JSON.stringify(state.log)); + res.statusCode = 404; + res.end('{}'); + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + t.after(() => { + server.closeAllConnections(); + server.close(); + }); + const invoke = (args, language = 'en') => + new Promise((resolve, reject) => { + const child = spawn(process.execPath, [entry, ...args, '--json'], { + env: { + PATH: process.env.PATH, + QL_URL: `http://127.0.0.1:${server.address().port}/panel`, + QL_ACCESS_TOKEN: 'fixture', + QL_LANG: language, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let out = '', + err = ''; + child.stdout.on('data', (chunk) => (out += chunk)); + child.stderr.on('data', (chunk) => (err += chunk)); + child.on('error', reject); + child.on('close', (code) => resolve({ code, out, err })); + }); + return { state, requests, invoke }; +} + +function failure(result, code = 1) { + assert.equal(result.code, code, result.err); + assert.equal(result.out, ''); + const error = JSON.parse(result.err); + assert.equal(error.code, code); + return error; +} + +test('immediate run exposes its receipt and remains compatible with older panels', async (t) => { + const f = await fixture(t); + let result = await f.invoke(['task', 'run', '12']); + assert.equal(result.code, 0, result.err); + assert.deepEqual(JSON.parse(result.out).data, { + taskId: 12, + action: 'run', + accepted: true, + triggerId, + state: 'queued', + reason: null, + }); + assert.equal(f.state.polls, 0); + for (const data of [undefined, null]) { + f.state.run = data; + result = await f.invoke(['task', 'run', '12']); + assert.deepEqual(JSON.parse(result.out).data, { + taskId: 12, + action: 'run', + accepted: true, + }); + const error = failure(await f.invoke(['task', 'run', '12', '--wait'])); + assert.match( + error.message, + /submitted.*no triggerId.*do not blindly retry/, + ); + } + assert.equal(f.state.polls, 0); + assert.equal(f.requests.length, 5); // Exactly one mutation per invocation, never replayed. +}); + +test('wait polls only the returned trigger and logs read exactly that run', async (t) => { + const f = await fixture(t); + f.state.pending = 1; + const result = await f.invoke([ + 'task', + 'run', + '12', + '--wait', + '--timeout', + '5', + ]); + assert.equal(result.code, 0, result.err); + assert.deepEqual(JSON.parse(result.out).data, { + taskId: 12, + action: 'run', + accepted: true, + triggerId, + state: 'finished', + reason: null, + exitCode: 0, + }); + assert.equal(f.state.polls, 2); + assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1); + const log = await f.invoke([ + 'task', + 'logs', + '12', + '--trigger-id', + triggerId, + '--tail', + '1', + ]); + assert.equal(log.code, 0, log.err); + assert.deepEqual(JSON.parse(log.out), { + code: 200, + data: 'last line', + triggerId, + logStatus: 'completed', + truncated: true, + }); + assert.equal(f.requests.at(-1).query.get('triggerId'), triggerId); +}); + +test('each non-success terminal state returns structured outcome and never reruns', async (t) => { + const f = await fixture(t); + for (const [state, reason, exit_code] of [ + ['failed', 'exit', 17], + ['skipped', 'overlap', null], + ['stopped', 'manual', null], + ['unknown', 'restart', null], + ['finished', 'exit_pending', null], + ]) { + f.state.rows = [{ id: triggerId, cron_id: 12, state, reason, exit_code }]; + const error = failure( + await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId]), + ); + assert.deepEqual(error.data, { + taskId: 12, + action: 'wait', + triggerId, + state, + reason, + exitCode: exit_code, + }); + } + assert.ok(f.requests.every((r) => r.method === 'GET')); +}); + +test('timeouts bound polling and in-flight reads, retain the trigger and never stop it', async (t) => { + for (const hang of [false, true]) { + const f = await fixture(t); + f.state.pending = Infinity; + f.state.hang = hang; + const start = Date.now(); + const error = failure( + await f.invoke(['task', 'run', '12', '--wait', '--timeout', '1']), + ); + assert.equal(error.data.triggerId, triggerId); + assert.equal(error.data.waitStatus, 'timeout'); + assert.ok(Date.now() - start < 5000); + assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1); + f.state.pending = 0; + f.state.hang = false; + const resumed = await f.invoke([ + 'task', + 'wait', + '12', + '--trigger-id', + triggerId, + ]); + assert.equal(resumed.code, 0, resumed.err); + assert.equal(JSON.parse(resumed.out).data.action, 'wait'); + assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1); + } +}); + +test('missing, mismatched or malformed receipts never fall back to the latest run', async (t) => { + const f = await fixture(t); + for (const rows of [ + [], + [{ id: 'sibling', cron_id: 12 }], + [{ id: triggerId, cron_id: 13 }], + [{ ...f.state.rows[0], state: 'invalid' }], + [{ ...f.state.rows[0], state: ['finished'] }], + [{ ...f.state.rows[0], exit_code: '0' }], + { data: [] }, + [f.state.rows[0], f.state.rows[0]], + ]) { + f.state.rows = rows; + const error = failure( + await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId]), + ); + assert.equal(error.data.triggerId, triggerId); + assert.ok(['invalidResponse', 'notFound'].includes(error.data.waitStatus)); + } + for (const data of [ + [], + {}, + [{ taskId: 13, triggerId }], + [{ taskId: 12, triggerId: 'bad id', state: 'queued', reason: null }], + ]) { + f.state.run = data; + failure(await f.invoke(['task', 'run', '12', '--wait'])); + } +}); + +test('legacy or mismatched log responses are rejected only when selecting a trigger', async (t) => { + const f = await fixture(t); + for (const id of [undefined, 'another-trigger']) { + f.state.log.triggerId = id; + const result = await f.invoke([ + 'task', + 'logs', + '12', + '--trigger-id', + triggerId, + ]); + assert.match(failure(result).message, /did not confirm the log trigger ID/); + const latest = await f.invoke(['task', 'logs', '12']); + assert.equal(latest.code, 0, latest.err); + assert.equal(JSON.parse(latest.out).triggerId, undefined); + assert.equal(f.requests.at(-1).query.has('triggerId'), false); + } +}); + +test('auth and network failures retain the trigger without replaying mutations', async (t) => { + for (const mode of ['denied', 'disconnect']) { + const f = await fixture(t); + f.state[mode] = true; + const error = failure( + await f.invoke(['task', 'run', '12', '--wait']), + mode === 'denied' ? 3 : 1, + ); + assert.equal(error.data.triggerId, triggerId); + assert.equal(error.data.waitStatus, 'interrupted'); + assert.equal(f.requests.length, 2); + assert.doesNotMatch(JSON.stringify(error), /Bearer fixture/); + } +}); + +test('new option validation happens before any network access and errors are bilingual', async (t) => { + const f = await fixture(t); + for (const args of [ + ['task', 'run', '12', '--timeout', '10'], + ['task', 'run', '12', '--wait', '--timeout', '0'], + ['task', 'run', '12', '--wait', '--timeout', '86401'], + ['task', 'wait', '12'], + ['task', 'wait', '12', '--trigger-id', 'bad id'], + ['task', 'logs', '12', '--trigger-id', 'a'.repeat(257)], + ]) + failure(await f.invoke(args), 2); + assert.equal(f.requests.length, 0); + f.state.rows = []; + const error = failure( + await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId], 'zh'), + ); + assert.match(error.message, /不存在、已清理或不属于该任务/); +}); diff --git a/cli/test/shared/commander.test.cjs b/cli/test/shared/commander.test.cjs index 341fd84d..f763189e 100644 --- a/cli/test/shared/commander.test.cjs +++ b/cli/test/shared/commander.test.cjs @@ -6,38 +6,87 @@ const fs = require('node:fs'); const path = require('node:path'); test('Commander adapter preserves literal values, option polarity, duplicate errors and IDs', () => { - assert.equal(parse(['task','list','--search','00123']).values.search, '00123'); - assert.equal(parse(['local','start','--no-startup'], 'local').values['no-startup'], true); - assert.equal(parse(['local','start'], 'local').values['no-startup'], undefined); - assert.equal(parse(['auth','login','--url=--json']).values.url, '--json'); - assert.deepEqual(parse(['local','resetpwd','--','-literal'], 'local').positionals, ['-literal']); + assert.equal( + parse(['task', 'list', '--search', '00123']).values.search, + '00123', + ); + assert.equal( + parse(['local', 'start', '--no-startup'], 'local').values['no-startup'], + true, + ); + assert.equal( + parse(['local', 'start'], 'local').values['no-startup'], + undefined, + ); + assert.equal(parse(['auth', 'login', '--url=--json']).values.url, '--json'); + assert.deepEqual( + parse(['local', 'resetpwd', '--', '-literal'], 'local').positionals, + ['-literal'], + ); for (const args of [ - ['task','list','--search','--json'], ['auth','login','--url','--json'], - ['task','list','-p','2','--page','3'], ['task','list','--json','--json'], - ['--json','task','list','--json'], ['task','list','unexpected'], - ['task','run','0'], ['task','run','script.js'], ['task','list','--size','201'], - ['task','list','--json=false'], - ]) assert.throws(() => parse(args), { exitCode:2 }, JSON.stringify(args)); - assert.ok(parse(['auth','login','--help']).help); + ['task', 'list', '--search', '--json'], + ['auth', 'login', '--url', '--json'], + ['task', 'list', '-p', '2', '--page', '3'], + ['task', 'list', '--json', '--json'], + ['--json', 'task', 'list', '--json'], + ['task', 'list', 'unexpected'], + ['task', 'run', '0'], + ['task', 'run', 'script.js'], + ['task', 'list', '--size', '201'], + ['task', 'list', '--json=false'], + ]) + assert.throws(() => parse(args), { exitCode: 2 }, JSON.stringify(args)); + assert.ok(parse(['auth', 'login', '--help']).help); assert.ok(parse(['--help']).help); }); test('Commander task parsing stops at the script and preserves the execution separator', () => { - const args = ['--root','/isolated','--json','script.sh','now','--','--json','--root','-literal']; + const args = [ + '--root', + '/isolated', + '--json', + 'script.sh', + 'now', + '--', + '--json', + '--root', + '-literal', + ]; const parsed = parseExecution(args); assert.equal(parsed.values.root, '/isolated'); assert.equal(parsed.values.json, true); - assert.deepEqual(parsed.execution.scriptArgs, ['--json','--root','-literal']); - assert.deepEqual(parseExecution(['script.sh','--json']).execution.argv, ['script.sh','--json']); - assert.deepEqual(parseExecution(['--','-script','--','-x']).execution.scriptArgs, ['-x']); - assert.throws(() => parseExecution(['--root','--json','script.sh']), { exitCode:2 }); + assert.deepEqual(parsed.execution.scriptArgs, [ + '--json', + '--root', + '-literal', + ]); + assert.deepEqual(parseExecution(['script.sh', '--json']).execution.argv, [ + 'script.sh', + '--json', + ]); + assert.deepEqual( + parseExecution(['--', '-script', '--', '-x']).execution.scriptArgs, + ['-x'], + ); + assert.throws(() => parseExecution(['--root', '--json', 'script.sh']), { + exitCode: 2, + }); }); test('Commander is bundled once with its license and has no external runtime resolution', () => { const manifest = require('../../package.json'); assert.equal(manifest.devDependencies.commander, '15.0.0'); assert.equal(Object.keys(manifest.dependencies || {}).length, 0); - const bundled = fs.readFileSync(path.join(__dirname,'../../dist/shared/cli/commander.js'), 'utf8'); + const bundled = fs.readFileSync( + path.join(__dirname, '../../dist/shared/cli/commander.js'), + 'utf8', + ); assert.doesNotMatch(bundled, /require\(["']commander["']\)/); - assert.match(fs.readFileSync(path.join(__dirname,'../../dist/licenses/commander-LICENSE'), 'utf8'), /MIT/); + assert.match( + fs.readFileSync( + path.join(__dirname, '../../dist/licenses/commander-LICENSE'), + 'utf8', + ), + /MIT/, + ); }); diff --git a/cli/test/shared/i18n.test.cjs b/cli/test/shared/i18n.test.cjs index fa180fef..54ee01c1 100644 --- a/cli/test/shared/i18n.test.cjs +++ b/cli/test/shared/i18n.test.cjs @@ -82,11 +82,7 @@ test('maintenance log banners honor Chinese fallback and English selection', asy }); test('standalone entry help supports both languages without panel or repository setup', () => { - for (const entry of [ - 'runner', - 'compat', - 'subscription-worker', - ]) { + for (const entry of ['runner', 'compat', 'subscription-worker']) { for (const language of ['en', 'zh']) { const result = spawnSync( process.execPath, @@ -113,7 +109,9 @@ test('standalone entry help supports both languages without panel or repository test('task, maintenance and subscription failure warnings honor locale without failing completed work', async (t) => { const { LocalApi } = require('../../dist/internal/runtime/api'); const { executeTask } = require('../../dist/internal/execution/taskRunner'); - const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner'); + const { + syncRepository, + } = require('../../dist/internal/subscription/subscriptionRunner'); const { withOperationOutput } = require('../../dist/internal/runtime/output'); const { execFileSync } = require('node:child_process'); const git = process.platform === 'darwin' ? '/usr/bin/git' : 'git'; diff --git a/deploy/kubernetes/base/qinglong.yaml b/deploy/kubernetes/base/qinglong.yaml index 62213799..e2231c04 100644 --- a/deploy/kubernetes/base/qinglong.yaml +++ b/deploy/kubernetes/base/qinglong.yaml @@ -46,7 +46,7 @@ spec: imagePullPolicy: IfNotPresent env: - name: QlBaseUrl - value: "/" + value: '/' - name: TZ value: Asia/Shanghai ports: diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 2461a966..4946baaa 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -1,10 +1,10 @@ services: web: - image: whyour/qinglong:latest # 基于 Debian 的版本:whyour/qinglong:debian + image: whyour/qinglong:latest # 基于 Debian 的版本:whyour/qinglong:debian volumes: - ./data:/ql/data ports: - - "5700:5700" + - '5700:5700' environment: QlBaseUrl: '/' # 部署路径非必须,以斜杠开头和结尾,比如 /test/ restart: unless-stopped diff --git a/docs/development/execution-modules.md b/docs/development/execution-modules.md new file mode 100644 index 00000000..49649cca --- /dev/null +++ b/docs/development/execution-modules.md @@ -0,0 +1,106 @@ +# 执行链路的模块边界 + +业务实现统一位于 `back/cron`,按调度、执行、结算和查询分组,保持现有 API、CLI 和服务方法的调用约定。 + +```text +back/cron/ +├── scheduling/ # 路由、规则发布、表达式、计划审计和调度就绪 +├── execution/ # 入队、启动、停止、进程身份与等待队列 +├── settlement/ # 回执核实、冲突处理和统计入账 +├── queries/ # 历史、日志、展示投影及调度诊断 +├── compatibility/ # 旧客户端、Shell 上报和升级实例接管 +├── history.ts # TriggerHistory 组合入口及保留策略 +├── schema.ts # 触发历史表、索引和已有结构升级 +├── identity.ts # 执行标识和回执时间 +└── types.ts # 共用类型 +``` + +内部代码和测试直接导入 `back/cron` 下的所属模块,不增加统一的 `index.ts` 聚合入口。原 `back/shared` 下的 19 个历史转发,以及本轮新拆模块在中间目录的转发均已移除;后端内部模块的旧导入路径不再提供兼容。`back/services/cron.ts` 保留服务入口;API、数据模型和调度进程入口仍位于各自的层级目录。 + +`back/shared/managedExit.cjs` 保留为 supervisor 独立启动的回执进程入口,不再作为库导入。回执格式、持久化、目录锁和安全回收位于 `back/cron/settlement/exitReceipt.cjs`;该模块只依赖 Node 内置模块,不加载服务、数据库或历史协调器。执行模块同时维护源码和编译产物中的 supervisor、回执脚本路径。目录迁移不改变文件格式、事务、状态判断或重试策略。 + +移除内部文件路径不改变现有 API、CLI 或 HTTP/gRPC 上报协议。直接导入旧后端模块的自定义代码需要改用 `back/cron`;已编译代码对应 `static/build/cron`。独立回执进程根据 `cron/history.js` 判断是否加载编译产物。源码目录迁移后需一并清除旧 `.js` 和 `.js.map`,TypeScript 构建不会主动删除这些残留文件;正常升级会停服、替换整个 `static` 目录并在失败时回滚。 + +| 模块 | 当前职责 | +| --- | --- | +| `back/cron/queries/triggerQueries.ts` | 按任务和触发 ID 查询历史、游标分页、延迟指标及调度审计聚合 | +| `back/cron/queries/cronViews.ts` | 任务展示状态、当前日志所属触发的 SQL 投影 | +| `back/cron/queries/cronLog.ts` | 按任务、触发或实例读取日志;文件切换、增量读取和日志列表 | +| `back/cron/types.ts` | 触发来源、状态和历史记录类型 | +| `back/cron/identity.ts` | 执行标识转换、计划槽位 ID 和回执时间解析 | +| `back/cron/scheduling/cronScheduling.ts` | Node/system 路由、特殊任务识别、三种执行入口共用的命令格式、Node 注册参数 | +| `back/cron/scheduling/systemCron.ts` | 生成系统规则文件,暂存计划、安装和确认,以及发布失败后的就绪状态与保存标记处理 | +| `back/cron/execution/cronExecution.ts` | 手动与开机执行提交、进程启动、终态回报、批量及单实例停止、待完成停止恢复 | +| `back/cron/execution/triggerLifecycle.ts` | 持久化入队、认领、实例绑定、停止请求、终态状态迁移和工作进程中断恢复 | +| `back/cron/execution/cronLimit.ts` | 每个进程内共享的定时与手动队列、并发配置、重复执行预算及等待取消 | +| `back/cron/queries/queueDiagnostics.ts` | 队列占用采样、等待原因和排队诊断查询 | +| `back/cron/settlement/triggerSettlement.ts` | 退出回执核实、冲突记录与撤销、实例结算、统计入账和提交后的证据清理 | +| `back/cron/settlement/exitReceipt.cjs` | 独立于服务与数据库的回执校验、持久化、扫描和安全回收 | +| `back/cron/settlement/cronStatistics.ts` | 统计认领与每日聚合写入,沿用结算方传入的事务和保留条件 | +| `back/cron/compatibility/legacyClient.ts` | 无触发 ID 的旧上报、带 ID 的 Shell 上报、实例关联和升级对账 | + +`TriggerHistory.visibleTriggers/recent/metrics` 和 `CronService.log/logs` 保留现有方法签名,转发给读取模块。触发类型和 `slotId` 仍由 `back/cron/history.ts` 重导出。新查询调用可直接使用 `new TriggerQueries(database)`,无需依赖执行生命周期类。日志读取模块接收已有的任务查询函数,沿用任务不存在时的行为。 + +查询模块只解释已经保存的证据。`unknown/restart`、待核实退出和冲突回执继续隐藏尚未确认的退出码与结束时间。日志的 `completed` 表示日志读取状态,不能用来判断脚本执行成功;执行结果仍来自触发记录。指定 `triggerId` 后,即使记录被清理,也不会回退到其他执行的日志。 + +任务状态和当前日志归属仍通过同一条 SQL 读取。审计仍使用原有数据库快照;历史排序、分页、指标口径和日志游标均沿用现有实现。 + +## 依赖方向 + +服务层组合 `cron` 能力,执行模块通过显式的 host 接口接收服务回调,不导入服务实现。通用 `shared` 库不反向导入 `cron` 或 `services`。`shared/managedExit.cjs` 是独立进程入口这一例外:它组合回执存储与历史结算,但不会被后端模块导入,也不提供转发导出。 + +`CronLimit` 保持每个进程一个实例,HTTP 手动执行、定时执行及并发设置使用同一个所属进程内的队列。`shared/pLimit.ts` 仅管理订阅、系统、脚本和依赖安装等通用队列,不再加载任务队列、数据库配置或通知服务。重复执行告警继续通过原 gRPC 客户端发送,排队去重、取消与占用采样不变。 + +数据库迁移由 `back/data/schemaMigrations.ts` 组合,直接调用 `cron/schema.ts` 的建表与升级逻辑,无需加载执行协调器。`history.ts` 继续导出同一个安装函数,迁移 ID、SQL 顺序与外层事务不变。通用文件存在检查与文件锁位于 `shared/utils.ts`,`config/util.ts` 保留原导出并复用实现,消除两者相互加载。 + +通知服务通过 `back/data/notificationSettings.ts` 读取已保存的通知配置,不再反向依赖用户服务;原查询条件、缺失配置错误、空配置回退及显式配置覆盖规则不变。类型引用不计为运行时依赖。回归检查 TypeScript 编译后实际产生的本地导入及字面量 `require()`,覆盖循环依赖、模块边界和独立回执进程加载。 + +## 调度适配 + +`CronService` 保留路由和命令构造的转发入口。创建、更新、启用和启动恢复使用同一个 `nodeCron` 构造注册参数,继续携带补跑时间窗、等待上限、跳过积压和定义版本。`QL_SCHEDULER` 的覆盖行为、crond 探测,以及扩展表达式和特殊任务的路由规则保持原样。 + +`SystemCronAdapter.publish` 在调用方已有的调度变更锁内工作。系统模式依次暂存计划、写 `crontab.list`、执行 `crontab` 安装、确认计划;Node 模式暂停系统审计覆盖并更新兼容文件,不安装系统 crontab。失败仍返回 503 并使调度器失去就绪状态;系统模式下原先受影响的任务会被标记为未保存,gRPC 进程继续发送安装失败通知。服务仅在发布成功后确认本次操作实际注册的任务。 + +Node 定时器的批量校验、停止态预构造、注册顺序和补跑仍由现有 `back/schedule/addCron.ts`、`registeredPlans.ts` 承接,并进入 `runCron`。系统 crond 保留 `system-cron.sh` 和 `back/bootstrap/systemCron.ts` 的启动及回执协议。手动和开机任务继续通过 `CronService.run/runSingle` 的原事务与队列;适配层不增加启动、重试或结算逻辑。 + +Node/system 切换时移除旧规则、登记新规则以及失败回滚的次序仍由 `CronService` 协调。命令中的 `QL_CRON_REVISION`、`real_time`、`ID`、前后置脚本、工作目录和日志路径保持原格式,系统规则仍携带派发时间和规则文本。 + +## 执行生命周期 + +`CronService.run/stop/stopInstance/resumePendingStops` 与原 `runSingle` 入口转发给同一个 `CronExecution` 实例。单实例停止和批量停止的进行中请求缓存随该实例保留,单次请求不会创建新的去重缓存。原有任务查询、命令构造和调用入口通过 `CronExecutionHost` 接口连接,避免模块反向导入服务类。 + +`TriggerHistory` 的生命周期方法保留原参数和默认值,转发给 `TriggerLifecycle`。Node 调度、手动执行和系统 crond 继续使用同一套入队去重、启动认领、停止标记和终态写入条件。只有尚未启动且因重启跳过的记录允许恢复入队;已进入 `unknown` 或已有终态的触发不会被重复执行。 + +事务边界保持原样:手动提交在同一事务内保存触发记录与队列令牌,提交成功后才派发进程;停止批次在立即事务内捕获实例快照与取消队列;配置版本检查和启动认领在同一事务内完成。调用方传入的事务直接传递到状态写入,不另行提交。 + +停止目标树仍在发送信号前持久化。重复停止使用原实例和原批次快照,后续产生的执行不会被纳入旧请求。退出证据结算失败时,事务内的状态写入回滚,事务外已保存的目标树继续保留供重试。 + +`TriggerLifecycleEvidence` 明确连接四项现有证据处理:停止前核查退出、结算命令退出、恢复脚本入口时间、重放已发布回执。需要写入的回调接收当前事务,保持状态、实例和统计一致提交。进程身份失效时仍提交 `unknown/restart` 给证据处理,不推测成功;工作进程中断时先重放证据,再处理尚在排队或运行的记录。 + +## 退出证据与结算 + +`TriggerSettlement` 聚合回执核实、冲突处理、实例结算和统计入账,并实现 `TriggerLifecycleEvidence`。它通过 `TriggerSettlementLifecycle` 接口使用原有 `finish` 和 `shouldStop` 条件,不反向导入 `TriggerHistory`。文件格式核验与安全回收复用 `exitReceipt.cjs`,统计认领和每日聚合继续复用 `cronStatistics.ts`。 + +`TriggerHistory.complete/retryPendingExits/replayPublishedExits/recordShellResult` 保留原签名。生命周期与旧 Shell 适配传入的事务继续用于同一组状态和结算写入。旧客户端上报、实例关联和升级对账由兼容适配层承接;保留策略清理仍在 `TriggerHistory`,`countExpired` 与 `deleteExpired` 继续共用保留条件。 + +所有已验证的版本 1 回执具有相同证据权重,不因文件路径不同而优先采信。退出码、信号或结束时间冲突时,保留冲突记录,并只撤销该执行实际记入的统计贡献;同日其他执行、固定最大耗时和已删除的统计日不受重复回放影响。旧格式回执仍需独立观察相互印证;损坏或缺失的证据不能把未知结果推断为成功,也不会触发自动重跑。 + +状态、实例、冲突记录、统计认领及每日计数保持在同一事务中。停止目标树尚未核实结束时,退出结果继续暂存,不能提前完成实例结算。回执清理仍注册在原事务的 `afterCommit` 中,并再次读取独立的已提交快照;即使 Sequelize 在 COMMIT 失败后调用该钩子,也不能删掉唯一的持久化结果。重复回执和重启回放沿用原有去重条件。 + +## 旧客户端兼容 + +`LegacyClientAdapter` 负责 `shellReport`、`reportLegacy`、`reportInstance`、`recordShellResult` 和 `reconcileInstances`,`TriggerHistory` 保留这五个公开入口及原参数、默认值和返回值。适配层通过 `LegacyClientLifecycle` 和 `LegacyClientSettlement` 接收已有模块的能力,不反向导入历史门面。 + +无触发 ID 的回执继续按任务、PID、启动秒和日志路径生成同一个标识;已绑定到 supervisor 的旧 Shell 上报仍归属于原受管命令。带 ID 的上报保持原有来源识别、历史保留条件及开始与结束乱序处理。已结束的旧执行不能抢占新实例,未知结果不能因重试开始上报或成功的 wrapper 退出而变为成功。 + +`shellReport` 沿用调用方事务,其余原有事务入口继续在适配层开启同样的事务。实例关联、任务摘要、状态更新和统计认领共享该事务;失败时一起回滚,重试不会重复计数。升级对账继续接管未关联的旧实例,保留已入账的历史结果和待完成停止请求,不启动任何执行。 + +验证包括只读 SQLite 下的历史与诊断查询、未知和冲突结果的投影、同时间戳分页,以及现有恢复、结算、日志和运行回执回归。CLI 的等待和指定触发日志继续复用同一组接口。 + +调度回归覆盖扩展与旧版表达式的路由、队列策略、发布各阶段失败、保存标记、变更锁、失败回滚、恢复替换、命令协议、手动执行和运行回执。路由测试通过真实服务转发到适配模块执行,避免从服务源码截取实现片段。 + +生命周期回归包含直接调用新模块的事务回滚、重启去重和结算失败注入,以及现有并发停止、持久化停止重试、PID 身份、启动门控、短进程退出、日志存活、退出证据恢复与历史清理测试。 + +结算模块回归直接组合 `TriggerLifecycle` 与 `TriggerSettlement`,覆盖调用方回滚、实际 COMMIT 失败后的证据保留、重建模块后的重复回放、退出码与时间冲突的精确撤销,以及损坏回执从未知到可靠结果的修复。现有回归继续验证旧客户端、跨日修正、历史清理、磁盘故障和多进程恢复。 + +兼容适配层回归直接组合适配层、生命周期和结算模块,覆盖调用方回滚、统计写入失败回滚、重复和乱序回执、PID 复用后的新实例保护、先退出后启动、未知结果的可靠结算,以及升级对账不重复入账和不清除待停止实例。 diff --git a/docs/development/node-cron-migration.md b/docs/development/node-cron-migration.md index 7261e95e..12948ba5 100644 --- a/docs/development/node-cron-migration.md +++ b/docs/development/node-cron-migration.md @@ -1,6 +1,6 @@ # Node cron 调度器迁移 -Node 调度路径使用固定版本 `node-cron@4.6.0`,普通任务(含额外规则)、订阅和系统 cron 共用 `back/shared/cronScheduler.ts`。启动/一次性任务、间隔任务、脚本并发限制和进程执行链路保持原有实现。系统模式只将语义一致的普通五字段规则交给 crond。 +Node 调度路径使用固定版本 `node-cron@4.6.0`,普通任务(含额外规则)、订阅和系统 cron 共用 `back/cron/scheduling/cronScheduler.ts`。启动/一次性任务、间隔任务、脚本并发限制和进程执行链路保持原有实现。系统模式只将语义一致的普通五字段规则交给 crond。 移除 `node-schedule`、其类型包以及兼容别名 `cron-parser-v4`。保留 `cron-parser@5` 做旧表达式的校验与标准化;计时器和日历推进由 node-cron 管理。 diff --git a/docs/development/scheduler-reliability-v1.md b/docs/development/scheduler-reliability-v1.md index 34c8a85b..4fa8b317 100644 --- a/docs/development/scheduler-reliability-v1.md +++ b/docs/development/scheduler-reliability-v1.md @@ -459,9 +459,9 @@ Linux 验收使用 16 MiB、4096 个 inode 的专用 tmpfs,另一个容器保 旧实现在有可用空间时,会把已经移入私有目录的回执再移动一次。实测中,第一个回收进程已核对退出码,随后它核对过的目录被改名,原名重新指向含新回执的目录。两个回收进程放行后,新文件被删除了。[修复前的进程与文件记录](../../output/playwright/ext4-reuse/before-fix.json) -上一轮实现直接在已有私有目录中复核回执。对新分配的目录也从移动前一直持有目录描述符到删除结束,用该描述符定位子文件。回收器通过同一个目录 inode 上的共享锁并发读取;向目录放入文件的回收器需要排他锁并检查槽位为空。锁忙时保留原文件供重试,进程退出后内核释放锁。实现使用系统 flock,缺少该命令时通过监督进程使用的 Python 运行时调用 fcntl.flock。公开路径仍先移动再复核,磁盘回执格式兼容已有版本。[实现](../../back/shared/managedExit.cjs) · [并发进程回归](../../test/helpers/receipt-claim-reuse-worker.cjs) +上一轮实现直接在已有私有目录中复核回执。对新分配的目录也从移动前一直持有目录描述符到删除结束,用该描述符定位子文件。回收器通过同一个目录 inode 上的共享锁并发读取;向目录放入文件的回收器需要排他锁并检查槽位为空。锁忙时保留原文件供重试,进程退出后内核释放锁。实现使用系统 flock,缺少该命令时通过监督进程使用的 Python 运行时调用 fcntl.flock。公开路径仍先移动再复核,磁盘回执格式兼容已有版本。[实现](../../back/cron/settlement/exitReceipt.cjs) · [并发进程回归](../../test/helpers/receipt-claim-reuse-worker.cjs) -复查还发现,触发和入账记录均已清理后,如果两份相互冲突的回执分开到达,先到的文件可能在第二份到达前被回收。现在 SQLite 为失去原入账关联的有效回执保留执行 ID、结果和结束毫秒。回收前重新读取已提交的记录;提交失败时保留文件。相同回报匹配同一条记录,有差异时在同一事务内转存为冲突证据。这一笔内部观测没有日统计贡献,也不会重建触发记录。首次迟到的执行 ID 按需占用一行,没有时间到期自动删除;否则无法保证任意迟到的第二份回报仍可比对。[退出结算](../../back/shared/triggerHistory.ts) · [提交失败及两种到达顺序的回归](../../test/back/cron-first-version.test.cjs) +复查还发现,触发和入账记录均已清理后,如果两份相互冲突的回执分开到达,先到的文件可能在第二份到达前被回收。现在 SQLite 为失去原入账关联的有效回执保留执行 ID、结果和结束毫秒。回收前重新读取已提交的记录;提交失败时保留文件。相同回报匹配同一条记录,有差异时在同一事务内转存为冲突证据。这一笔内部观测没有日统计贡献,也不会重建触发记录。首次迟到的执行 ID 按需占用一行,没有时间到期自动删除;否则无法保证任意迟到的第二份回报仍可比对。[退出结算](../../back/cron/settlement/triggerSettlement.ts) · [提交失败及两种到达顺序的回归](../../test/back/cron-first-version.test.cjs) 验收使用 Docker 面板和专用虚拟机上的真实 ext4。原生 unlink 成功后、目录变更尚未刷盘时,强杀虚拟机;重新挂载后先确认仍有 0 个可用块,并从原路径读回相同回执。释放空间后,两个独立进程在生产结算代码中均已复核旧文件且即将删除,此时控制程序在同一文件系统上改名旧目录,重建同名目录并写入与同一执行 ID 绑定的新回执。放行后,旧 inode 上的回执消失,新目录和新文件的 inode 与旧值不同,新回执的 SHA-256 保持不变。另用已清理的执行 ID 验证先收到单份新结果、清理并重启服务、再重复送达旧回报的顺序。[逐轮文件、进程及日账](../../output/playwright/ext4-reuse/verification.json) @@ -475,7 +475,7 @@ Linux 验收使用 16 MiB、4096 个 inode 的专用 tmpfs,另一个容器保 旧回收器的共享锁固定了目录 inode。两个回收进程都读到旧文件后,独立写入进程在同一目录用 `rename` 替换了 `receipt` 并同步目录。目录 inode 仍是 19,新回执的 inode 是 20;两个回收器均返回成功,新回执却已消失。[修复前原始记录](../../output/playwright/ext4-slot/before-fix.json) -回收器现在将源目录项原子移到本次尝试专用的随机名字,通常位于数据库目录。核对移走的实际内容后,才从这个新名字删除与已确认结果相符的副本。与原观测不一致的文件留给恢复扫描处理。已读到的旧格式元组在移动时带上摘要,以便中途退出后仍能识别文件是否被换过。摘要只用于核对旧格式内容,无法证明脚本退出。回执目录独立挂载时,在同一文件系统的 `.reclaim` 目录完成移动。在专用 ext4 卷上实测跨设备移动失败,内核返回 `EXDEV`;随后从备用目录读回退出码 42,并在结果匹配后正常回收。[实现](../../back/shared/managedExit.cjs) · [跨设备原始记录](../../output/playwright/ext4-slot/exdev.json) · [双进程 ext4 探针](../../test/helpers/receipt-allocation-reuse-ext4.cjs) +回收器现在将源目录项原子移到本次尝试专用的随机名字,通常位于数据库目录。核对移走的实际内容后,才从这个新名字删除与已确认结果相符的副本。与原观测不一致的文件留给恢复扫描处理。已读到的旧格式元组在移动时带上摘要,以便中途退出后仍能识别文件是否被换过。摘要只用于核对旧格式内容,无法证明脚本退出。回执目录独立挂载时,在同一文件系统的 `.reclaim` 目录完成移动。在专用 ext4 卷上实测跨设备移动失败,内核返回 `EXDEV`;随后从备用目录读回退出码 42,并在结果匹配后正常回收。[实现](../../back/cron/settlement/exitReceipt.cjs) · [跨设备原始记录](../../output/playwright/ext4-slot/exdev.json) · [双进程 ext4 探针](../../test/helpers/receipt-allocation-reuse-ext4.cjs) 最终构建在 Docker 内执行 11 个真实脚本,使用独立 QEMU 客体和 ext4 数据盘,挂载选项为 `data=ordered,commit=600`。控制程序按上海时区推进容器时钟,两个实际运行中的脚本跨过午夜。故障轮次使用三个已经清理的实例。独立写入程序给每个实例各放入一份校验通过、与真实退出冲突的回执,仅把旧结果送达两次,并行执行历史清理。文件替换和断电时机通过屏障控制,移动、删除、目录同步、SQLite 提交、强杀客体和重新挂载均实际执行。 diff --git a/nodemon.json b/nodemon.json index 81a20e98..aaf7fecd 100644 --- a/nodemon.json +++ b/nodemon.json @@ -1,8 +1,5 @@ { - "watch": [ - "back", - ".env" - ], + "watch": ["back", ".env"], "ext": "js,cjs,ts,json", "env": { "NODE_ENV": "development", diff --git a/package.json b/package.json index 599b36e7..21d49568 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,8 @@ "build:info": "node scripts/write-build-info.cjs", "panel": "npm run build:back && node static/build/app.js", "gen:proto": "protoc --experimental_allow_proto3_optional --plugin=./node_modules/.bin/protoc-gen-ts_proto ./back/protos/*.proto --ts_proto_out=./ --ts_proto_opt=outputServices=grpc-js,env=node,esModuleInterop=true,snakeToCamel=false", - "prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'", + "prettier": "node scripts/format.cjs", + "prettier:check": "node scripts/format.cjs --check", "prepack": "node scripts/prepare-npm-package.cjs", "postpack": "node scripts/prepare-npm-package.cjs --clean", "postinstall": "node -e \"const fs = require('fs'); if (fs.existsSync('shell/install-package.cjs')) require('./shell/install-package.cjs').installPackage(); else fs.accessSync('pnpm-lock.yaml')\" && (max setup 2>/dev/null || true)", @@ -78,11 +79,8 @@ "pre-commit": "lint-staged" }, "lint-staged": { - "*.{js,jsx,less,md,json}": [ + "*.{js,jsx,cjs,mjs,ts,tsx,css,less,md,json,jsonc,yml,yaml}": [ "prettier --write" - ], - "*.ts?(x)": [ - "prettier --parser=typescript --write" ] }, "bin": { diff --git a/sample/ql_sample.js b/sample/ql_sample.js index 7f5b6863..5b18e0c3 100644 --- a/sample/ql_sample.js +++ b/sample/ql_sample.js @@ -19,11 +19,13 @@ QLAPI.getCrons({ searchValue: 'test' }).then((x) => { }); // 通过ID查询定时任务 (Get cron by ID) -QLAPI.getCronById({ id: 1 }).then((x) => { - console.log('getCronById', x); -}).catch((err) => { - console.log('getCronById error', err); -}); +QLAPI.getCronById({ id: 1 }) + .then((x) => { + console.log('getCronById', x); + }) + .catch((err) => { + console.log('getCronById error', err); + }); // 启用定时任务 (Enable cron tasks) QLAPI.enableCrons({ ids: [1, 2] }).then((x) => { diff --git a/scripts/format.cjs b/scripts/format.cjs new file mode 100644 index 00000000..c1ff05b8 --- /dev/null +++ b/scripts/format.cjs @@ -0,0 +1,47 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); +const prettier = require('prettier'); + +process.chdir(path.resolve(__dirname, '..')); +const check = process.argv.includes('--check'); +// Include new source files, but never build output or ignored local tooling. +const files = new Set( + execFileSync( + 'git', + ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], + { + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + }, + ) + .split('\0') + .filter(Boolean), +); +let checked = 0; +let changed = 0; +for (const file of [...files].sort()) { + if (!fs.existsSync(file) || !fs.lstatSync(file).isFile()) continue; + const info = prettier.getFileInfo.sync(file, { + ignorePath: '.prettierignore', + }); + if (info.ignored) continue; + const options = { + ...prettier.resolveConfig.sync(file, { editorconfig: true }), + filepath: file, + }; + if (!info.inferredParser && !options.parser) continue; + checked++; + const original = fs.readFileSync(file, 'utf8'); + const formatted = prettier.format(original, options); + if (original === formatted) continue; + changed++; + console.log(file); + if (!check) fs.writeFileSync(file, formatted); +} +console.log( + `${checked} files checked; ${changed} ${ + check ? 'need formatting' : 'formatted' + }.`, +); +if (check && changed) process.exitCode = 1; diff --git a/scripts/prepare-npm-package.cjs b/scripts/prepare-npm-package.cjs index 1d4875a2..6469d4a1 100644 --- a/scripts/prepare-npm-package.cjs +++ b/scripts/prepare-npm-package.cjs @@ -8,12 +8,20 @@ const copy = path.join(root, 'shell/upgrade-lock.yaml'); if (process.argv.includes('--clean')) { fs.rmSync(copy, { force: true }); } else { - if (execFileSync('git', ['-C', root, 'status', '--porcelain', '--untracked-files=all'], { encoding: 'utf8' }).trim()) + if ( + execFileSync( + 'git', + ['-C', root, 'status', '--porcelain', '--untracked-files=all'], + { encoding: 'utf8' }, + ).trim() + ) throw new Error('Pack only from a clean source checkout'); // The native npm pack/publish hooks must enforce the same checks as CI: // current commit, clean build, lockfile and every output file's checksum. // Capture stdout so npm pack --json remains machine-readable. - execFileSync(process.execPath, [path.join(root, 'docker/verify-build.cjs')], { cwd: root }); + execFileSync(process.execPath, [path.join(root, 'docker/verify-build.cjs')], { + cwd: root, + }); const bytes = fs.readFileSync(path.join(root, 'pnpm-lock.yaml')); fs.rmSync(copy, { force: true }); fs.writeFileSync(copy, bytes, { flag: 'wx', mode: 0o644 }); diff --git a/scripts/verify-panel-package.cjs b/scripts/verify-panel-package.cjs index c6ab7102..3e8e084d 100644 --- a/scripts/verify-panel-package.cjs +++ b/scripts/verify-panel-package.cjs @@ -16,63 +16,128 @@ const execute = promisify(execFile); const repository = path.resolve(__dirname, '..'); const hash = (bytes) => createHash('sha256').update(bytes).digest('hex'); const read = async (file) => JSON.parse(await fs.readFile(file, 'utf8')); -const run = (program, args, options = {}) => execute(program, args, { - encoding: 'utf8', maxBuffer: 8 * 1024 * 1024, timeout: 120000, - ...options, -}); +const run = (program, args, options = {}) => + execute(program, args, { + encoding: 'utf8', + maxBuffer: 8 * 1024 * 1024, + timeout: 120000, + ...options, + }); const requiredFiles = [ ...Object.values(require('../package.json').pnpm?.patchedDependencies || {}), - '.env.example', 'back/protos/api.proto', 'ecosystem.config.js', 'version.yaml', - 'shell/upgrade.cjs', 'shell/install-bundle.cjs', 'shell/install-package.cjs', - 'shell/upgrade-lock.yaml', 'shell/node-runtime-probe.cjs', 'shell/start.sh', 'shell/start-simplify.sh', - 'shell/cron-command.py', 'static/build/shared/managedExit.cjs', - 'shell/task.sh', 'shell/subscription-files.py', 'shell/preload/client.js', 'shell/preload/client.py', - 'shell/preload/sitecustomize.js', 'shell/preload/sitecustomize.py', - 'shell/preload/esm-loader.mjs', 'shell/preload/notificationAudit.js', - 'sample/config.sample.sh', 'sample/auth.sample.json', - 'static/build-info.json', 'static/build/app.js', 'static/build/token.js', + '.env.example', + 'back/protos/api.proto', + 'ecosystem.config.js', + 'version.yaml', + 'shell/upgrade.cjs', + 'shell/install-bundle.cjs', + 'shell/install-package.cjs', + 'shell/upgrade-lock.yaml', + 'shell/node-runtime-probe.cjs', + 'shell/start.sh', + 'shell/start-simplify.sh', + 'shell/cron-command.py', + 'static/build/shared/managedExit.cjs', + 'static/build/cron/settlement/exitReceipt.cjs', + 'shell/task.sh', + 'shell/subscription-files.py', + 'shell/preload/client.js', + 'shell/preload/client.py', + 'shell/preload/sitecustomize.js', + 'shell/preload/sitecustomize.py', + 'shell/preload/esm-loader.mjs', + 'shell/preload/notificationAudit.js', + 'sample/config.sample.sh', + 'sample/auth.sample.json', + 'static/build-info.json', + 'static/build/app.js', + 'static/build/token.js', 'static/build/bootstrap/upgradeProbe.js', 'static/dist/index.html', - ...['upgradeArtifacts', 'platformBundle', 'upgradePrestart', 'panelUpgrade', 'nodeRuntime'] - .map((name) => `cli/src/internal/maintenance/${name}.cjs`), + ...[ + 'upgradeArtifacts', + 'platformBundle', + 'upgradePrestart', + 'panelUpgrade', + 'nodeRuntime', + ].map((name) => `cli/src/internal/maintenance/${name}.cjs`), ]; function checkPackedFiles(files) { const names = new Set(files.map((file) => file.path)); - for (const name of requiredFiles) assert.ok(names.has(name), `Missing npm runtime: ${name}`); + for (const name of requiredFiles) + assert.ok(names.has(name), `Missing npm runtime: ${name}`); for (const name of names) { - assert.ok(requiredFiles.includes(name) || /^(?:package\.json$|LICENSE$|README[^/]*\.md$|\.env\.example$|ecosystem\.config\.js$|version\.yaml$|back\/protos\/api\.proto$|cli\/(?:README[^/]*\.md$|src\/internal\/maintenance\/[^/]+\.cjs$)|sample\/|shell\/|static\/)/.test(name), `Unexpected npm file: ${name}`); - assert.ok(!/^shell\/(?:pub\.sh$|preload\/(?:env\.|notify\.|__ql_notify__\.|lang_env\.sh|.*-notify\.json))/.test(name), `Generated or release-only runtime file: ${name}`); - assert.ok(!/(?:^|\/)__pycache__\/|\.pyc$|(?:^|\/)\.DS_Store$/.test(name), name); + assert.ok( + requiredFiles.includes(name) || + /^(?:package\.json$|LICENSE$|README[^/]*\.md$|\.env\.example$|ecosystem\.config\.js$|version\.yaml$|back\/protos\/api\.proto$|cli\/(?:README[^/]*\.md$|src\/internal\/maintenance\/[^/]+\.cjs$)|sample\/|shell\/|static\/)/.test( + name, + ), + `Unexpected npm file: ${name}`, + ); + assert.ok( + !/^shell\/(?:pub\.sh$|preload\/(?:env\.|notify\.|__ql_notify__\.|lang_env\.sh|.*-notify\.json))/.test( + name, + ), + `Generated or release-only runtime file: ${name}`, + ); + assert.ok( + !/(?:^|\/)__pycache__\/|\.pyc$|(?:^|\/)\.DS_Store$/.test(name), + name, + ); assert.notEqual(name, 'sample/tool.ts'); } } async function packPanel(output) { const git = (...args) => run('git', args, { cwd: repository }); - assert.equal((await git('status', '--porcelain', '--untracked-files=all')).stdout.trim(), '', 'Pack only from a clean source checkout'); - await run(process.execPath, [path.join(repository, 'docker/verify-build.cjs')], { cwd: repository }); + assert.equal( + (await git('status', '--porcelain', '--untracked-files=all')).stdout.trim(), + '', + 'Pack only from a clean source checkout', + ); + await run( + process.execPath, + [path.join(repository, 'docker/verify-build.cjs')], + { cwd: repository }, + ); await fs.mkdir(output, { recursive: true }); const cache = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-pack-cache-')); try { - const result = await run('npm', ['pack', '--json', '--cache', cache, '--pack-destination', output], { cwd: repository }); + const result = await run( + 'npm', + ['pack', '--json', '--cache', cache, '--pack-destination', output], + { cwd: repository }, + ); const [manifest] = JSON.parse(result.stdout); checkPackedFiles(manifest.files); assert.equal(manifest.name, '@whyour/qinglong'); const build = await read(path.join(repository, 'static/build-info.json')); const names = new Set(manifest.files.map((file) => file.path)); - for (const name of Object.keys(build.files)) assert.ok(names.has(`static/${name}`), `npm filtered a verified build artifact: ${name}`); + for (const name of Object.keys(build.files)) + assert.ok( + names.has(`static/${name}`), + `npm filtered a verified build artifact: ${name}`, + ); const receipt = { - filename: manifest.filename, sha256: hash(await fs.readFile(path.join(output, manifest.filename))), - sourceCommit: build.sourceCommit, size: manifest.size, fileCount: manifest.files.length, + filename: manifest.filename, + sha256: hash(await fs.readFile(path.join(output, manifest.filename))), + sourceCommit: build.sourceCommit, + size: manifest.size, + fileCount: manifest.files.length, }; - await fs.writeFile(path.join(output, 'package-receipt.json'), JSON.stringify(receipt, null, 2)); + await fs.writeFile( + path.join(output, 'package-receipt.json'), + JSON.stringify(receipt, null, 2), + ); console.log(JSON.stringify(receipt)); return receipt; } finally { await fs.rm(cache, { recursive: true, force: true }); // Also recover an interrupted npm pack whose postpack hook did not execute. - await fs.rm(path.join(repository, 'shell/upgrade-lock.yaml'), { force: true }); + await fs.rm(path.join(repository, 'shell/upgrade-lock.yaml'), { + force: true, + }); } } @@ -86,8 +151,13 @@ async function unusedPort() { // Consume the unmodified output of Dockerfile.upgrade-bundle / buildBundle. async function platformFixture(root, directory, expectedCommit) { - assert.ok(directory, 'Set QL_PANEL_TEST_BUNDLE_DIR to the official platform bundle output'); - const names = (await fs.readdir(directory)).filter((name) => name.endsWith('.tar.gz')); + assert.ok( + directory, + 'Set QL_PANEL_TEST_BUNDLE_DIR to the official platform bundle output', + ); + const names = (await fs.readdir(directory)).filter((name) => + name.endsWith('.tar.gz'), + ); assert.equal(names.length, 1, 'Expected one official platform package'); const archive = path.resolve(directory, names[0]); const record = await read(archive + '.json'); @@ -107,55 +177,123 @@ async function platformFixture(root, directory, expectedCommit) { async function legacyArchive(temp, env) { const directory = path.join(temp, 'legacy'); await fs.mkdir(directory); - const result = await run('npm', ['pack', '@whyour/qinglong@2.23.0', '--ignore-scripts', '--json', '--registry=https://registry.npmjs.org', '--pack-destination', directory, '--cache', path.join(temp, 'cache')], { cwd: temp, env, timeout: 300000 }); + const result = await run( + 'npm', + [ + 'pack', + '@whyour/qinglong@2.23.0', + '--ignore-scripts', + '--json', + '--registry=https://registry.npmjs.org', + '--pack-destination', + directory, + '--cache', + path.join(temp, 'cache'), + ], + { cwd: temp, env, timeout: 300000 }, + ); const [record] = JSON.parse(result.stdout); assert.equal(record.name, '@whyour/qinglong'); assert.equal(record.version, '2.23.0'); assert.equal(record.filename, 'whyour-qinglong-2.23.0.tgz'); const archive = path.join(directory, record.filename); - const integrity = 'sha512-' + createHash('sha512').update(await fs.readFile(archive)).digest('base64'); - assert.equal(integrity, 'sha512-x6B9s1/SRKkHe7jRQtb3LzMluJ3O3PAAssrr/5jaFMMl7DZvABSEiqkkZMu0r1BNtiCF72uj8OqXN9pCnF2WVw==', 'Published legacy package integrity changed'); + const integrity = + 'sha512-' + + createHash('sha512') + .update(await fs.readFile(archive)) + .digest('base64'); + assert.equal( + integrity, + 'sha512-x6B9s1/SRKkHe7jRQtb3LzMluJ3O3PAAssrr/5jaFMMl7DZvABSEiqkkZMu0r1BNtiCF72uj8OqXN9pCnF2WVw==', + 'Published legacy package integrity changed', + ); return { archive, integrity, version: record.version }; } async function verifyPanel(input, output) { assert.equal(process.platform, 'linux', 'Service tests require Linux'); - assert.equal(process.env.QL_PANEL_PACKAGE_TEST_ISOLATED, '1', 'Run only inside a disposable Linux container: QL_PANEL_PACKAGE_TEST_ISOLATED=1'); + assert.equal( + process.env.QL_PANEL_PACKAGE_TEST_ISOLATED, + '1', + 'Run only inside a disposable Linux container: QL_PANEL_PACKAGE_TEST_ISOLATED=1', + ); const stat = await fs.stat(input); if (stat.isDirectory()) { - const names = (await fs.readdir(input)).filter((name) => name.endsWith('.tgz')); + const names = (await fs.readdir(input)).filter((name) => + name.endsWith('.tgz'), + ); assert.equal(names.length, 1, 'Expected one exact npm archive'); input = path.join(input, names[0]); } - const expected = await read(path.join(path.dirname(input), 'package-receipt.json')); + const expected = await read( + path.join(path.dirname(input), 'package-receipt.json'), + ); assert.equal(path.basename(input), expected.filename); - assert.equal(hash(await fs.readFile(input)), expected.sha256, 'npm archive differs from its build receipt'); + assert.equal( + hash(await fs.readFile(input)), + expected.sha256, + 'npm archive differs from its build receipt', + ); assert.equal((await fs.stat(input)).size, expected.size); assert.match(expected.sourceCommit, /^[a-f0-9]{40}$/); - if (process.env.GITHUB_SHA) assert.equal(expected.sourceCommit, process.env.GITHUB_SHA); + if (process.env.GITHUB_SHA) + assert.equal(expected.sourceCommit, process.env.GITHUB_SHA); const nodeSha = hash(await fs.readFile(process.execPath)); const pm2 = process.env.QL_PANEL_TEST_PM2; - assert.ok(pm2 && path.isAbsolute(pm2), 'Set QL_PANEL_TEST_PM2 to an isolated PM2 executable'); - const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-install-'))); - const home = path.join(temp, 'home'), prefix = path.join(temp, 'prefix'), data = path.join(temp, 'data'); + assert.ok( + pm2 && path.isAbsolute(pm2), + 'Set QL_PANEL_TEST_PM2 to an isolated PM2 executable', + ); + const temp = await fs.realpath( + await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-install-')), + ); + const home = path.join(temp, 'home'), + prefix = path.join(temp, 'prefix'), + data = path.join(temp, 'data'); await fs.mkdir(home); await fs.mkdir(data); const port = await unusedPort(); let grpcPort = await unusedPort(); while (grpcPort === port) grpcPort = await unusedPort(); - const env = { ...process.env, HOME: home, PM2_HOME: path.join(temp, '.pm2'), - QL_DATA_DIR: data, QL_BRANCH: 'develop', NODE_ENV: 'production', QL_CONTAINER: 'false', - BACK_PORT: String(port), GRPC_PORT: String(grpcPort), QlPort: String(port), QlGrpcPort: String(grpcPort), - BIND_HOST: '127.0.0.1', BIND_HOST_GRPC: '127.0.0.1', - NODE_PATH: '', NODE_OPTIONS: '', - PATH: [path.join(prefix, 'bin'), path.dirname(pm2), process.env.PATH].join(path.delimiter), + const env = { + ...process.env, + HOME: home, + PM2_HOME: path.join(temp, '.pm2'), + QL_DATA_DIR: data, + QL_BRANCH: 'develop', + NODE_ENV: 'production', + QL_CONTAINER: 'false', + BACK_PORT: String(port), + GRPC_PORT: String(grpcPort), + QlPort: String(port), + QlGrpcPort: String(grpcPort), + BIND_HOST: '127.0.0.1', + BIND_HOST_GRPC: '127.0.0.1', + NODE_PATH: '', + NODE_OPTIONS: '', + PATH: [path.join(prefix, 'bin'), path.dirname(pm2), process.env.PATH].join( + path.delimiter, + ), }; - for (const key of ['QL_CLI_ROOT', 'QL_DIR', 'QL_UPGRADE_FILE', 'QL_UPGRADE_REPAIR_DEPS', 'QL_UPGRADE_LAUNCHER_PID', 'QL_UPGRADE_INDEX_URL']) delete env[key]; + for (const key of [ + 'QL_CLI_ROOT', + 'QL_DIR', + 'QL_UPGRADE_FILE', + 'QL_UPGRADE_REPAIR_DEPS', + 'QL_UPGRADE_LAUNCHER_PID', + 'QL_UPGRADE_INDEX_URL', + ]) + delete env[key]; let root, fixtureServer, token; const api = async (route, method = 'GET', body, anonymous = false) => { const response = await fetch(`http://127.0.0.1:${port}/api/${route}`, { - method, headers: { 'Content-Type': 'application/json', ...(!anonymous && token ? { Authorization: `Bearer ${token}` } : {}) }, - body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(5000), + method, + headers: { + 'Content-Type': 'application/json', + ...(!anonymous && token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(5000), }); const result = await response.json(); assert.equal(result.code, 200, `${method} ${route}: ${result.message}`); @@ -164,7 +302,10 @@ async function verifyPanel(input, output) { const healthy = async () => { const deadline = Date.now() + 120000; while (Date.now() < deadline) { - try { const value = await api('health', 'GET', undefined, true); if (value.status === 'ok') return value; } catch {} + try { + const value = await api('health', 'GET', undefined, true); + if (value.status === 'ok') return value; + } catch {} await delay(300); } throw new Error('Installed npm backend did not become healthy'); @@ -176,32 +317,80 @@ async function verifyPanel(input, output) { const value = await api('system/update-status'); assert.equal(value.id, id); if (value.status === status) return value; - if (value.status === 'failed' && status !== 'failed') throw new Error(value.error); + if (value.status === 'failed' && status !== 'failed') + throw new Error(value.error); } catch (error) { - if (!/fetch failed|ECONNRESET|ECONNREFUSED|aborted|timeout/i.test(error.message)) throw error; + if ( + !/fetch failed|ECONNRESET|ECONNREFUSED|aborted|timeout/i.test( + error.message, + ) + ) + throw error; } await delay(250); } throw new Error(`Installed npm update never reached ${status}`); }; try { - const install = (archive) => run('npm', ['install', '--global', '--prefix', prefix, '--force', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), archive], { cwd: temp, env, timeout: 600000 }); - const start = () => run(path.join(prefix, 'bin/qinglong'), ['reload'], { cwd: temp, env, timeout: 180000 }); - const stop = () => run(pm2, ['delete', 'ecosystem.config.js'], { cwd: root, env }); - console.log(`Installing actual npm archive with production lifecycle scripts on ${process.version}`); + const install = (archive) => + run( + 'npm', + [ + 'install', + '--global', + '--prefix', + prefix, + '--force', + '--omit=dev', + '--no-audit', + '--no-fund', + '--cache', + path.join(temp, 'cache'), + archive, + ], + { cwd: temp, env, timeout: 600000 }, + ); + const start = () => + run(path.join(prefix, 'bin/qinglong'), ['reload'], { + cwd: temp, + env, + timeout: 180000, + }); + const stop = () => + run(pm2, ['delete', 'ecosystem.config.js'], { cwd: root, env }); + console.log( + `Installing actual npm archive with production lifecycle scripts on ${process.version}`, + ); await install(input); - const globalRoot = (await run('npm', ['root', '--global', '--prefix', prefix], { cwd: temp, env })).stdout.trim(); + const globalRoot = ( + await run('npm', ['root', '--global', '--prefix', prefix], { + cwd: temp, + env, + }) + ).stdout.trim(); root = path.join(globalRoot, '@whyour/qinglong'); env.QL_DIR = root; const runtimeProbes = []; const checkRuntime = async () => { - const result = await run(process.execPath, [path.join(root, 'shell/node-runtime-probe.cjs')], { cwd: temp, env, timeout: 540000 }); + const result = await run( + process.execPath, + [path.join(root, 'shell/node-runtime-probe.cjs')], + { cwd: temp, env, timeout: 540000 }, + ); runtimeProbes.push(JSON.parse(result.stdout.trim())); }; await checkRuntime(); // Use a subprocess: cached candidate modules must not mask missing files // after old-package installation and the real npm overwrite below. - await run(process.execPath, ['-e', `const root=process.argv[1],p=require('node:path');const m=require(root+'/package.json');for(const target of Object.values(m.bin))require('node:fs').accessSync(p.join(root,target));for(const name of ['platformBundle','upgradePrestart','panelUpgrade'])require(root+'/cli/src/internal/maintenance/'+name+'.cjs');require(root+'/shell/upgrade.cjs').verifyUpgrade(root,p.join(root,'static')).catch(e=>{console.error(e);process.exitCode=1});`, root], { env, cwd: temp }); + await run( + process.execPath, + [ + '-e', + `const root=process.argv[1],p=require('node:path');const m=require(root+'/package.json');for(const target of Object.values(m.bin))require('node:fs').accessSync(p.join(root,target));for(const name of ['platformBundle','upgradePrestart','panelUpgrade'])require(root+'/cli/src/internal/maintenance/'+name+'.cjs');require(root+'/shell/upgrade.cjs').verifyUpgrade(root,p.join(root,'static')).catch(e=>{console.error(e);process.exitCode=1});`, + root, + ], + { env, cwd: temp }, + ); env.QL_DATA_DIR = path.join(temp, 'fresh/data'); await fs.mkdir(env.QL_DATA_DIR, { recursive: true }); console.log('Starting the freshly installed npm package'); @@ -209,40 +398,75 @@ async function verifyPanel(input, output) { const fresh = await healthy(); assert.equal(fresh.build.sourceCommit, expected.sourceCommit); assert.equal(fresh.services.grpc, true); - assert.match(await fetch(`http://127.0.0.1:${port}/`).then((r) => r.text()), / r.text()), + / { assert.equal((await api('user')).username, credentials.username); - assert.ok((await api('envs')).some((x) => x.name === 'NPM_PACKAGE_PRESERVE' && x.value === nonce)); + assert.ok( + (await api('envs')).some( + (x) => x.name === 'NPM_PACKAGE_PRESERVE' && x.value === nonce, + ), + ); assert.equal((await api(`crons/${cron.id}`)).command, cron.command); assert.equal(hash(await fs.readFile(userConfig)), userConfigSha); - assert.equal(await fs.readFile(script, 'utf8'), `console.log(${JSON.stringify(nonce)});\n`); + assert.equal( + await fs.readFile(script, 'utf8'), + `console.log(${JSON.stringify(nonce)});\n`, + ); }; await preservedData(); - console.log('Stopping legacy service and verifying npm automatically preserves its .env during overwrite'); + console.log( + 'Stopping legacy service and verifying npm automatically preserves its .env during overwrite', + ); await stop(); - await fs.appendFile(path.join(root, '.env'), `\n# retained custom npm environment ${nonce}\n`); + await fs.appendFile( + path.join(root, '.env'), + `\n# retained custom npm environment ${nonce}\n`, + ); const savedEnv = await fs.readFile(path.join(root, '.env')); await install(input); assert.deepEqual(await fs.readFile(path.join(root, '.env')), savedEnv); @@ -250,25 +474,62 @@ async function verifyPanel(input, output) { const configSha = hash(savedEnv); const local = createRequire(path.join(root, 'package.json')); const artifacts = local('./shell/upgrade.cjs'); - const build = await artifacts.verifyUpgrade(root, path.join(root, 'static')); + const build = await artifacts.verifyUpgrade( + root, + path.join(root, 'static'), + ); assert.equal(build.sourceCommit, expected.sourceCommit); - assert.notEqual(hash(await fs.readFile(path.join(root, 'static/build/app.js'))), legacyBackendSha); - assert.equal(hash(await fs.readFile(path.join(root, 'pnpm-lock.yaml'))), build.lockfileSha256); - const fixture = await platformFixture(root, process.env.QL_PANEL_TEST_BUNDLE_DIR, expected.sourceCommit); - let badChecksum = true, requests = 0; + assert.notEqual( + hash(await fs.readFile(path.join(root, 'static/build/app.js'))), + legacyBackendSha, + ); + assert.equal( + hash(await fs.readFile(path.join(root, 'pnpm-lock.yaml'))), + build.lockfileSha256, + ); + const fixture = await platformFixture( + root, + process.env.QL_PANEL_TEST_BUNDLE_DIR, + expected.sourceCommit, + ); + let badChecksum = true, + requests = 0; fixtureServer = http.createServer((request, response) => { requests++; if (request.url === '/latest.json') { response.setHeader('Content-Type', 'application/json'); - response.end(JSON.stringify({ format: 2, sourceCommit: fixture.sourceCommit, packages: { [fixture.target]: { size: fixture.size, sha256: badChecksum ? '0'.repeat(64) : fixture.sha256, url: `http://127.0.0.1:${fixtureServer.address().port}/bundle.tar.gz` } } })); + response.end( + JSON.stringify({ + format: 2, + sourceCommit: fixture.sourceCommit, + packages: { + [fixture.target]: { + size: fixture.size, + sha256: badChecksum ? '0'.repeat(64) : fixture.sha256, + url: `http://127.0.0.1:${ + fixtureServer.address().port + }/bundle.tar.gz`, + }, + }, + }), + ); } else if (request.url === '/bundle.tar.gz') { response.setHeader('Content-Length', fixture.size); sync.createReadStream(fixture.archive).pipe(response); - } else { response.statusCode = 404; response.end(); } + } else { + response.statusCode = 404; + response.end(); + } }); - await new Promise((resolve) => fixtureServer.listen(0, '127.0.0.1', resolve)); - env.QL_UPGRADE_INDEX_URL = `http://127.0.0.1:${fixtureServer.address().port}/latest.json`; - console.log('Starting the overwritten npm package against legacy user data'); + await new Promise((resolve) => + fixtureServer.listen(0, '127.0.0.1', resolve), + ); + env.QL_UPGRADE_INDEX_URL = `http://127.0.0.1:${ + fixtureServer.address().port + }/latest.json`; + console.log( + 'Starting the overwritten npm package against legacy user data', + ); await start(); const original = await healthy(); assert.equal(original.build.sourceCommit, build.sourceCommit); @@ -285,13 +546,22 @@ async function verifyPanel(input, output) { assert.equal((await healthy()).build.instanceId, original.build.instanceId); await preserved(); badChecksum = false; - console.log('Testing installed panel download, prestart and explicit application'); + console.log( + 'Testing installed panel download, prestart and explicit application', + ); const accepted = await api('system/update', 'PUT'); const ready = await job(accepted.id, 'ready'); assert.equal((await healthy()).build.instanceId, original.build.instanceId); - const pointer = await read(path.join(root, '.tmp/upgrade-ready-develop.json')); - const receipt = await read(path.join(root, '.tmp', pointer.directory, 'prestart.json')); - assert.ok(receipt.completedAt <= ready.updatedAt, 'Readiness was recorded before backend prestart'); + const pointer = await read( + path.join(root, '.tmp/upgrade-ready-develop.json'), + ); + const receipt = await read( + path.join(root, '.tmp', pointer.directory, 'prestart.json'), + ); + assert.ok( + receipt.completedAt <= ready.updatedAt, + 'Readiness was recorded before backend prestart', + ); const applying = await api('update/system', 'PUT'); await job(applying.id, 'completed'); const afterOnline = await healthy(); @@ -299,20 +569,53 @@ async function verifyPanel(input, output) { assert.notEqual(afterOnline.build.instanceId, original.build.instanceId); assert.equal(afterOnline.build.sourceCommit, fixture.sourceCommit); await fs.access(path.join(root, 'node_modules/.pnpm')); - assert.match(await fs.realpath(path.join(root, 'node_modules/sqlite3')), /[/\\]node_modules[/\\]\.pnpm[/\\]/); + assert.match( + await fs.realpath(path.join(root, 'node_modules/sqlite3')), + /[/\\]node_modules[/\\]\.pnpm[/\\]/, + ); await fs.access(path.join(root, 'scripts/build-upgrade-bundle.cjs')); await artifacts.verifyUpgrade(root, path.join(root, 'static')); - assert.match(await fetch(`http://127.0.0.1:${port}/`).then((r) => r.text()), / r.text()), + / ''); + const text = await fs + .readFile(path.join(env.PM2_HOME, 'logs', file), 'utf8') + .catch(() => ''); if (text) console.error(text.slice(-6000)); } } @@ -370,10 +703,18 @@ async function verifyPanel(input, output) { module.exports = { checkPackedFiles, packPanel, verifyPanel }; if (require.main === module) { const [action, input, output] = process.argv.slice(2); - const operation = action === 'pack' && input - ? packPanel(path.resolve(input)) - : action === 'verify' && input + const operation = + action === 'pack' && input + ? packPanel(path.resolve(input)) + : action === 'verify' && input ? verifyPanel(path.resolve(input), output && path.resolve(output)) - : Promise.reject(new Error('Usage: node scripts/verify-panel-package.cjs pack OUTPUT | verify ARCHIVE_OR_DIRECTORY [RESULT_DIRECTORY]')); - operation.catch((error) => { console.error(error); process.exitCode = 1; }); + : Promise.reject( + new Error( + 'Usage: node scripts/verify-panel-package.cjs pack OUTPUT | verify ARCHIVE_OR_DIRECTORY [RESULT_DIRECTORY]', + ), + ); + operation.catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/scripts/verify-runtime-dependencies.cjs b/scripts/verify-runtime-dependencies.cjs index 32353c14..bcf7bbad 100644 --- a/scripts/verify-runtime-dependencies.cjs +++ b/scripts/verify-runtime-dependencies.cjs @@ -5,7 +5,11 @@ const path = require('node:path'); const { createRequire } = require('node:module'); const yaml = require('js-yaml'); -assert.equal(process.versions.node, fs.readFileSync('.nvmrc', 'utf8').trim(), 'Node runtime differs from the production version'); +assert.equal( + process.versions.node, + fs.readFileSync('.nvmrc', 'utf8').trim(), + 'Node runtime differs from the production version', +); const panelRequire = createRequire(path.resolve('package.json')); const manifest = panelRequire('./package.json'); @@ -13,9 +17,17 @@ const lock = yaml.load(fs.readFileSync('pnpm-lock.yaml', 'utf8')); function verifyDirect(name) { const entry = lock.dependencies[name]; - assert.equal(entry?.specifier, manifest.dependencies[name], `${name}: manifest/lock mismatch`); + assert.equal( + entry?.specifier, + manifest.dependencies[name], + `${name}: manifest/lock mismatch`, + ); // pnpm appends peer resolution context, e.g. 6.37.8(@whyour/sqlite3@1.1.5). - assert.equal(panelRequire(`${name}/package.json`).version, entry.version.split('(')[0], `${name}: installed/lock mismatch`); + assert.equal( + panelRequire(`${name}/package.json`).version, + entry.version.split('(')[0], + `${name}: installed/lock mismatch`, + ); return entry.version; } @@ -23,13 +35,22 @@ for (const name of ['@grpc/grpc-js', 'compression', 'multer', 'sequelize']) { verifyDirect(name); } -for (const [parent, name] of [['express', 'proxy-addr'], ['sockjs', 'websocket-driver']]) { +for (const [parent, name] of [ + ['express', 'proxy-addr'], + ['sockjs', 'websocket-driver'], +]) { const version = verifyDirect(parent); const expected = lock.packages[`/${parent}@${version}`]?.dependencies?.[name]; assert.ok(expected, `${parent} > ${name}: missing lock entry`); const parentRequire = createRequire(panelRequire.resolve(parent)); - assert.equal(parentRequire(`${name}/package.json`).version, expected.split('(')[0], `${parent} > ${name}: installed/lock mismatch`); + assert.equal( + parentRequire(`${name}/package.json`).version, + expected.split('(')[0], + `${parent} > ${name}: installed/lock mismatch`, + ); } for (const name of ['sqlite3', 'nodemailer', 'undici']) panelRequire(name); -console.log('Production dependencies match the manifest and lockfile; runtime imports verified'); +console.log( + 'Production dependencies match the manifest and lockfile; runtime imports verified', +); diff --git a/shell/install-package.cjs b/shell/install-package.cjs index 895455ff..e8764d78 100644 --- a/shell/install-package.cjs +++ b/shell/install-package.cjs @@ -31,34 +31,57 @@ function restorePackageLock(root = path.resolve(__dirname, '..')) { function restoreEnvironment(root = path.resolve(__dirname, '..')) { // npm's Arborist keeps this exact retirement directory until lifecycle scripts // succeed, then deletes it. Never search other installations or sibling backups. - const suffix = createHash('sha1').update(root).digest('base64') - .replace(/[^a-zA-Z0-9]+/g, '').slice(0, 8); - const retired = path.join(path.dirname(root), `.${path.basename(root)}-${suffix}`); + const suffix = createHash('sha1') + .update(root) + .digest('base64') + .replace(/[^a-zA-Z0-9]+/g, '') + .slice(0, 8); + const retired = path.join( + path.dirname(root), + `.${path.basename(root)}-${suffix}`, + ); const destination = path.join(root, '.env'); const exists = (file) => { - try { return fs.lstatSync(file); } - catch (error) { if (error.code === 'ENOENT') return; throw error; } + try { + return fs.lstatSync(file); + } catch (error) { + if (error.code === 'ENOENT') return; + throw error; + } }; if (exists(destination)) return; const directory = exists(retired); if (!directory) return; - if (!directory.isDirectory()) throw new Error('Invalid npm retirement directory'); + if (!directory.isDirectory()) + throw new Error('Invalid npm retirement directory'); const metadata = path.join(retired, 'package.json'); - if (!exists(metadata)?.isFile()) throw new Error('Invalid retired npm package'); + if (!exists(metadata)?.isFile()) + throw new Error('Invalid retired npm package'); if (JSON.parse(fs.readFileSync(metadata, 'utf8')).name !== '@whyour/qinglong') throw new Error('Unexpected retired npm package'); const source = path.join(retired, '.env'); const stat = exists(source); if (!stat) return; - if (!stat.isFile()) throw new Error('Retired npm .env must be a regular file'); - const descriptor = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + if (!stat.isFile()) + throw new Error('Retired npm .env must be a regular file'); + const descriptor = fs.openSync( + source, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW, + ); const temporary = path.join(root, `.upgrade-env-${randomUUID()}`); try { - if (!fs.fstatSync(descriptor).isFile()) throw new Error('Invalid retired npm .env'); - fs.writeFileSync(temporary, fs.readFileSync(descriptor), { flag: 'wx', mode: 0o600 }); + if (!fs.fstatSync(descriptor).isFile()) + throw new Error('Invalid retired npm .env'); + fs.writeFileSync(temporary, fs.readFileSync(descriptor), { + flag: 'wx', + mode: 0o600, + }); // Linking publishes a complete file without replacing a concurrently created .env. - try { fs.linkSync(temporary, destination); } - catch (error) { if (error.code !== 'EEXIST') throw error; } + try { + fs.linkSync(temporary, destination); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + } } finally { fs.closeSync(descriptor); fs.rmSync(temporary, { force: true }); diff --git a/shell/preload/client.js b/shell/preload/client.js index b15a8822..01ddb9e1 100644 --- a/shell/preload/client.js +++ b/shell/preload/client.js @@ -86,7 +86,9 @@ class GrpcClient { grpcOptions, ); } catch (error) { - throw new Error('Failed to initialize gRPC client: ' + error.message, { cause: error }); + throw new Error('Failed to initialize gRPC client: ' + error.message, { + cause: error, + }); } finally { module.loadingPanelDependencies = false; } @@ -105,12 +107,17 @@ class GrpcClient { Date.now() + GrpcClient.#config.defaultTimeout, ); - this.#client[capitalizedMethod](params, metadata, { deadline }, (error, response) => { - if (error) { - return reject(error); - } - resolve(response); - }); + this.#client[capitalizedMethod]( + params, + metadata, + { deadline }, + (error, response) => { + if (error) { + return reject(error); + } + resolve(response); + }, + ); }); }; } diff --git a/shell/preload/esm-loader.mjs b/shell/preload/esm-loader.mjs index c59bf3b1..5f38b5a7 100644 --- a/shell/preload/esm-loader.mjs +++ b/shell/preload/esm-loader.mjs @@ -2,19 +2,43 @@ import { existsSync } from 'node:fs'; import { join } from 'node:path'; const builtinModules = [ - 'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', - 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'process', 'querystring', - 'readline', 'stream', 'string_decoder', 'timers', 'tls', 'tty', 'url', 'util', - 'v8', 'zlib', + 'assert', + 'buffer', + 'child_process', + 'cluster', + 'crypto', + 'dgram', + 'dns', + 'events', + 'fs', + 'http', + 'https', + 'net', + 'os', + 'path', + 'process', + 'querystring', + 'readline', + 'stream', + 'string_decoder', + 'timers', + 'tls', + 'tty', + 'url', + 'util', + 'v8', + 'zlib', ]; function isBareSpecifier(specifier) { - return !specifier.startsWith('.') && + return ( + !specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('file:') && !specifier.startsWith('node:') && !builtinModules.includes(specifier) && - !builtinModules.includes(specifier.split('/')[0]); + !builtinModules.includes(specifier.split('/')[0]) + ); } export function resolve(specifier, context, nextResolve) { diff --git a/shell/preload/script-start.cjs b/shell/preload/script-start.cjs index 8d98de49..f5eb5594 100644 --- a/shell/preload/script-start.cjs +++ b/shell/preload/script-start.cjs @@ -11,16 +11,32 @@ module.exports = function observeScriptStart(entry, marker) { session.connect(); const target = pathToFileURL(entry).href; session.post('Debugger.enable'); - session.post('Debugger.setBreakpointByUrl', { url: target, lineNumber: 0 }, (err, bp) => { - if (err || !bp) { session.disconnect(); return; } - session.on('Debugger.paused', ({ params }) => { - if (params.hitBreakpoints?.includes(bp.breakpointId)) { - try { writeFileSync(marker, String(Date.now()), { flag: 'wx', mode: 0o600 }); } catch {} + session.post( + 'Debugger.setBreakpointByUrl', + { url: target, lineNumber: 0 }, + (err, bp) => { + if (err || !bp) { session.disconnect(); - } else { - session.post('Debugger.resume'); + return; } - }); - }); - } catch { try { session.disconnect(); } catch {} } + session.on('Debugger.paused', ({ params }) => { + if (params.hitBreakpoints?.includes(bp.breakpointId)) { + try { + writeFileSync(marker, String(Date.now()), { + flag: 'wx', + mode: 0o600, + }); + } catch {} + session.disconnect(); + } else { + session.post('Debugger.resume'); + } + }); + }, + ); + } catch { + try { + session.disconnect(); + } catch {} + } }; diff --git a/shell/preload/sitecustomize.js b/shell/preload/sitecustomize.js index 3ce11c55..bee46d12 100644 --- a/shell/preload/sitecustomize.js +++ b/shell/preload/sitecustomize.js @@ -84,7 +84,11 @@ function run() { ].filter(Boolean); if (task_before) { - console.log(process.env.QL_LANG === 'en' ? 'Executing before command\n' : '执行前置命令\n'); + console.log( + process.env.QL_LANG === 'en' + ? 'Executing before command\n' + : '执行前置命令\n', + ); } const res = execSync(commands.join(' && '), { @@ -124,7 +128,11 @@ function run() { console.log(output); } if (task_before) { - console.log(process.env.QL_LANG === 'en' ? 'Before command finished\n' : '执行前置命令结束\n'); + console.log( + process.env.QL_LANG === 'en' + ? 'Before command finished\n' + : '执行前置命令结束\n', + ); } } catch (error) { if (!error.message.includes('spawnSync /bin/bash E2BIG')) { @@ -133,7 +141,11 @@ function run() { // environment variable is too large } if (task_before) { - console.log(process.env.QL_LANG === 'en' ? 'Before command finished\n' : '执行前置命令结束\n'); + console.log( + process.env.QL_LANG === 'en' + ? 'Before command finished\n' + : '执行前置命令结束\n', + ); } } @@ -175,5 +187,8 @@ try { } if (process.env.QL_SCRIPT_ENTRY && process.env.QL_SCRIPT_START_FILE) { - require('./script-start.cjs')(process.env.QL_SCRIPT_ENTRY, process.env.QL_SCRIPT_START_FILE); + require('./script-start.cjs')( + process.env.QL_SCRIPT_ENTRY, + process.env.QL_SCRIPT_START_FILE, + ); } diff --git a/shell/upgrade.cjs b/shell/upgrade.cjs index 3ede09ad..189ed9e7 100644 --- a/shell/upgrade.cjs +++ b/shell/upgrade.cjs @@ -3,6 +3,8 @@ const upgrade = require('../cli/src/internal/maintenance/upgradeArtifacts.cjs'); module.exports = upgrade; if (require.main === module) upgrade.main().catch((error) => { - console.error(upgrade.upgradeMessage('更新失败: %s', process.env, error.message)); + console.error( + upgrade.upgradeMessage('更新失败: %s', process.env, error.message), + ); process.exitCode = 1; }); diff --git a/src/app.ts b/src/app.ts index f18e4a19..99ee19bf 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,16 +4,18 @@ import intl from 'react-intl-universal'; export function rootContainer(container: any) { const locales = { - 'en': require('./locales/en-US.json'), - 'zh': require('./locales/zh-CN.json'), + en: require('./locales/en-US.json'), + zh: require('./locales/zh-CN.json'), }; let currentLocale: string; try { - currentLocale = intl.determineLocale({ - urlLocaleKey: 'lang', - cookieLocaleKey: 'lang', - localStorageLocaleKey: 'lang', - }).slice(0, 2); + currentLocale = intl + .determineLocale({ + urlLocaleKey: 'lang', + cookieLocaleKey: 'lang', + localStorageLocaleKey: 'lang', + }) + .slice(0, 2); } catch (e: unknown) { // Handle decodeURIComponent errors from malformed cookies console.warn('Failed to determine locale from cookies:', e); diff --git a/src/components/UpgradeNotice.tsx b/src/components/UpgradeNotice.tsx index facd3d2b..cfcaeac4 100644 --- a/src/components/UpgradeNotice.tsx +++ b/src/components/UpgradeNotice.tsx @@ -27,7 +27,8 @@ export default function UpgradeNotice({ : intl.get(upgradeStatusLabel(job)); const label = activeStatuses.includes(job.status) && - job.phase === 'downloading' && job.percent != null + job.phase === 'downloading' && + job.percent != null ? `${text} ${job.percent}%` : text; return ( diff --git a/src/components/fileBrowser/index.less b/src/components/fileBrowser/index.less index 7a90f77f..f4dccc9c 100644 --- a/src/components/fileBrowser/index.less +++ b/src/components/fileBrowser/index.less @@ -1,22 +1,103 @@ -.file-browser { height: 100%; display: flex; flex-direction: column; gap: 6px; min-height: 0; } -.file-browser-location { display: flex; align-items: center; gap: 8px; min-width: 0; padding-bottom: 4px; border-bottom: 1px solid rgba(127,127,127,.24); } -.file-browser-location > button { flex: none; min-height: 28px; } -.file-browser-path { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.9em; padding-inline-start: 8px; border-inline-start: 1px solid rgba(127,127,127,.3); } -.file-picker-label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; text-align: left; } -.file-browser-entries { min-height: 0; overflow: auto; flex: 1; } -.file-browser-pagination { display: flex; justify-content: center; align-items: center; min-height: 32px; } +.file-browser { + height: 100%; + display: flex; + flex-direction: column; + gap: 6px; + min-height: 0; +} +.file-browser-location { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + padding-bottom: 4px; + border-bottom: 1px solid rgba(127, 127, 127, 0.24); +} +.file-browser-location > button { + flex: none; + min-height: 28px; +} +.file-browser-path { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.9em; + padding-inline-start: 8px; + border-inline-start: 1px solid rgba(127, 127, 127, 0.3); +} +.file-picker-label { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + text-align: left; +} +.file-browser-entries { + min-height: 0; + overflow: auto; + flex: 1; +} +.file-browser-pagination { + display: flex; + justify-content: center; + align-items: center; + min-height: 32px; +} .file-browser-entries > button:not(.ant-btn) { - background: transparent; border: 0; color: inherit; cursor: pointer; display: flex; - align-items: flex-start; gap: 6px; padding: 4px; text-align: left; width: 100%; line-height: 1.5; + background: transparent; + border: 0; + color: inherit; + cursor: pointer; + display: flex; + align-items: flex-start; + gap: 6px; + padding: 4px; + text-align: left; + width: 100%; + line-height: 1.5; +} +.file-browser-entries > button > .anticon { + flex: none; + margin-top: 0.25em; +} +.file-browser-label { + display: block; + min-width: 0; +} +.file-browser-name { + display: flex; + white-space: nowrap; } -.file-browser-entries > button > .anticon { flex: none; margin-top: .25em; } -.file-browser-label { display: block; min-width: 0; } -.file-browser-name { display: flex; white-space: nowrap; } .file-browser-name > span:first-child, -.file-browser-parent { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.file-browser-name > span:last-child { display: flex; justify-content: flex-end; flex: none; max-width: 100%; overflow: hidden; } -.file-browser-name > span:first-child:not(:empty) + span { max-width: 70%; } -.file-browser-parent { font-size: .85em; } -.file-browser-entries > button:hover, .file-browser-entries > button[aria-pressed=true] { background: rgba(127,127,127,.14); } -.file-picker { width: min(320px, 74vw); height: 320px; display: flex; flex-direction: column; } -.file-picker-label { max-width: min(300px, 60vw); } +.file-browser-parent { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.file-browser-name > span:last-child { + display: flex; + justify-content: flex-end; + flex: none; + max-width: 100%; + overflow: hidden; +} +.file-browser-name > span:first-child:not(:empty) + span { + max-width: 70%; +} +.file-browser-parent { + font-size: 0.85em; +} +.file-browser-entries > button:hover, +.file-browser-entries > button[aria-pressed='true'] { + background: rgba(127, 127, 127, 0.14); +} +.file-picker { + width: min(320px, 74vw); + height: 320px; + display: flex; + flex-direction: column; +} +.file-picker-label { + max-width: min(300px, 60vw); +} diff --git a/src/components/fileBrowser/index.tsx b/src/components/fileBrowser/index.tsx index 5c8b0b71..63083ad9 100644 --- a/src/components/fileBrowser/index.tsx +++ b/src/components/fileBrowser/index.tsx @@ -1,33 +1,71 @@ import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Button, Empty, Input, Popover, Spin, Typography } from 'antd'; -import { FileOutlined, FolderOutlined, ArrowUpOutlined, ReloadOutlined } from '@ant-design/icons'; +import { + FileOutlined, + FolderOutlined, + ArrowUpOutlined, + ReloadOutlined, +} from '@ant-design/icons'; import intl from 'react-intl-universal'; import config from '@/utils/config'; import { request } from '@/utils/http'; import { readableLogName } from './name'; import './index.less'; -type Entry = { key: string; title: string; parent: string; type: 'file' | 'directory'; size?: number }; -type Listing = { rows: Entry[]; next: string; versions: Map; retryMinimum?: number; retryAfter?: string }; +type Entry = { + key: string; + title: string; + parent: string; + type: 'file' | 'directory'; + size?: number; +}; +type Listing = { + rows: Entry[]; + next: string; + versions: Map; + retryMinimum?: number; + retryAfter?: string; +}; type ReadingPosition = { scrollTop: number; offsets: Map }; const emptyListing: Listing = { rows: [], next: '', versions: new Map() }; type Props = { - source: 'logs' | 'scripts'; value?: string; initialDirectory?: string; revision?: number; folders?: boolean; - onSelect: (entry: Entry) => void; onDoubleClick?: (entry: Entry) => void; + source: 'logs' | 'scripts'; + value?: string; + initialDirectory?: string; + revision?: number; + folders?: boolean; + onSelect: (entry: Entry) => void; + onDoubleClick?: (entry: Entry) => void; }; // Match readDirectoryPage's depth-first search and directory-first listing order. -function pastCursor(cursor: string, boundary: string, source: Props['source'], search: string) { +function pastCursor( + cursor: string, + boundary: string, + source: Props['source'], + search: string, +) { if (search) { // A directory's children precede its next sibling. NUL cannot occur in a filename. return cursor.replace(/\//g, '\0') > boundary.replace(/\//g, '\0'); } - if (source === 'logs' && cursor.startsWith('1') && boundary.startsWith('1')) return cursor < boundary; + if (source === 'logs' && cursor.startsWith('1') && boundary.startsWith('1')) + return cursor < boundary; return cursor > boundary; } -function Entries({ source, path, search, folders, value, open, onDoubleClick }: Props & { - path: string; search: string; open: (entry: Entry) => void; +function Entries({ + source, + path, + search, + folders, + value, + open, + onDoubleClick, +}: Props & { + path: string; + search: string; + open: (entry: Entry) => void; }) { const listing = useRef(emptyListing); const [visible, setListing] = useState(listing.current); @@ -42,12 +80,15 @@ function Entries({ source, path, search, folders, value, open, onDoubleClick }: if (!element || position.current) return; const top = element.getBoundingClientRect().top; const offsets = new Map(); - for (const row of Array.from(element.querySelectorAll('button[title]'))) { + for (const row of Array.from( + element.querySelectorAll('button[title]'), + )) { const rect = row.getBoundingClientRect(); if (rect.top >= top + element.clientHeight) break; if (rect.bottom > top) offsets.set(row.title, rect.top - top); } - if (offsets.size) position.current = { scrollTop: element.scrollTop, offsets }; + if (offsets.size) + position.current = { scrollTop: element.scrollTop, offsets }; } useLayoutEffect(() => { const element = viewport.current; @@ -56,7 +97,9 @@ function Entries({ source, path, search, folders, value, open, onDoubleClick }: position.current = undefined; const top = element.getBoundingClientRect().top; for (const [key, offset] of saved.offsets) { - const row = element.querySelector(`button[title="${CSS.escape(key)}"]`); + const row = element.querySelector( + `button[title="${CSS.escape(key)}"]`, + ); if (row) { element.scrollTop += row.getBoundingClientRect().top - top - offset; return; @@ -74,35 +117,54 @@ function Entries({ source, path, search, folders, value, open, onDoubleClick }: try { const url = config.apiPrefix + source + '/entries'; const options = { signal: controller.signal, retryInPlace: true }; - const minimum = previous.retryMinimum ?? (previous.rows.length + 1); + const minimum = previous.retryMinimum ?? previous.rows.length + 1; const boundary = previous.retryAfter ?? after; // Rebuild the visible prefix if an external change crossed the cursor. // Bound automatic restarts so a busy directory still offers a manual retry. for (let attempt = 0; attempt < 3; attempt++) { const append = attempt === 0 && Boolean(after); const batch = append ? [...previous.rows] : []; - const seen = new Map(append ? previous.versions : emptyListing.versions); + const seen = new Map( + append ? previous.versions : emptyListing.versions, + ); let current = true; let cursor = append ? after : ''; do { - const result = await request.get<{code: number; data: Entry[]; next: string | null; versions?: [string, string | null][]}>(url, { - ...options, params: { path, after: cursor, search, folders }, + const result = await request.get<{ + code: number; + data: Entry[]; + next: string | null; + versions?: [string, string | null][]; + }>(url, { + ...options, + params: { path, after: cursor, search, folders }, }); if (controller.signal.aborted) return; - if (result.code !== 200 || !Array.isArray(result.data)) throw new Error(); + if (result.code !== 200 || !Array.isArray(result.data)) + throw new Error(); for (const [dir, version] of result.versions || []) { if (seen.has(dir) && seen.get(dir) !== version) current = false; seen.set(dir, version); } batch.push(...result.data); cursor = result.next || ''; - } while (current && cursor && (batch.length < minimum || - (!append && boundary && !pastCursor(cursor, boundary, source, search)))); + } while ( + current && + cursor && + (batch.length < minimum || + (!append && + boundary && + !pastCursor(cursor, boundary, source, search))) + ); // Recheck even a terminal page: the response itself may have been delayed. const stamps = [...seen]; for (let i = 0; current && i < stamps.length; i += 128) { - const check = await request.post<{code: number; current: boolean}>(url + '/check', stamps.slice(i, i + 128), options); + const check = await request.post<{ code: number; current: boolean }>( + url + '/check', + stamps.slice(i, i + 128), + options, + ); if (controller.signal.aborted) return; if (check.code !== 200) throw new Error(); current = check.current; @@ -115,82 +177,208 @@ function Entries({ source, path, search, folders, value, open, onDoubleClick }: // The old rows and cursor are stale, but a manual retry must reach the // same depth even if this read exhausts its retries or loses the network. rememberPosition(); - listing.current = { ...emptyListing, retryMinimum: minimum, retryAfter: boundary }; + listing.current = { + ...emptyListing, + retryMinimum: minimum, + retryAfter: boundary, + }; setListing(listing.current); } setFailed(true); } catch { if (!controller.signal.aborted) setFailed(true); } finally { - if (!controller.signal.aborted) { pending.current = undefined; setLoading(false); } + if (!controller.signal.aborted) { + pending.current = undefined; + setLoading(false); + } } } useEffect(() => { void read(listing.current); - return () => { pending.current?.abort(); pending.current = undefined; }; + return () => { + pending.current?.abort(); + pending.current = undefined; + }; }, []); - return
- {rows.map(item => { - const name = source === 'logs' ? readableLogName(item.title) : item.title; - // Prefer a complete suffix such as "_register.js" or "___init__". - const tail = name.match(/[_ .-].{4,14}$/su)?.[0] ?? Array.from(name).slice(-10).join(''); - return ; - })} - {loading || failed || next ?
- {loading ? : } -
: !rows.length && } -
; + return ( +
+ {rows.map((item) => { + const name = + source === 'logs' ? readableLogName(item.title) : item.title; + // Prefer a complete suffix such as "_register.js" or "___init__". + const tail = + name.match(/[_ .-].{4,14}$/su)?.[0] ?? + Array.from(name).slice(-10).join(''); + return ( + + ); + })} + {loading || failed || next ? ( +
+ {loading ? ( + + ) : ( + + )} +
+ ) : ( + !rows.length && + )} +
+ ); } export function FileBrowser(props: Props) { const [path, setPath] = useState(props.initialDirectory || ''); const [input, setInput] = useState(''); const [search, setSearch] = useState(''); - useEffect(() => { setPath(props.initialDirectory || ''); }, [props.initialDirectory]); + useEffect(() => { + setPath(props.initialDirectory || ''); + }, [props.initialDirectory]); useEffect(() => { const timer = setTimeout(() => setSearch(input.trim()), 220); return () => clearTimeout(timer); }, [input]); const open = (entry: Entry) => { - if (entry.type === 'directory') { setPath(entry.key); setInput(''); setSearch(''); } + if (entry.type === 'directory') { + setPath(entry.key); + setInput(''); + setSearch(''); + } props.onSelect(entry); }; - return
- setInput(e.target.value)} - placeholder={intl.get(props.source === 'logs' ? '搜索日志名称' : '搜索脚本名称')} /> - {!input.trim() && path &&
- - {path} -
} - {input.trim() === search - ? - : } -
; + return ( +
+ setInput(e.target.value)} + placeholder={intl.get( + props.source === 'logs' ? '搜索日志名称' : '搜索脚本名称', + )} + /> + {!input.trim() && path && ( +
+ + + {path} + +
+ )} + {input.trim() === search ? ( + + ) : ( + + )} +
+ ); } -export function FilePicker({ onChange, ...props }: Omit & { onSelect?: Props['onSelect']; onChange?: (key: string) => void }) { +export function FilePicker({ + onChange, + ...props +}: Omit & { + onSelect?: Props['onSelect']; + onChange?: (key: string) => void; +}) { const [visible, setVisible] = useState(false); - return - {visible && { - if (props.folders || entry.type === 'file') { - onChange?.(entry.key); props.onSelect?.(entry); - if (!props.folders) setVisible(false); + return ( + + {visible && ( + { + if (props.folders || entry.type === 'file') { + onChange?.(entry.key); + props.onSelect?.(entry); + if (!props.folders) setVisible(false); + } + }} + /> + )} + {props.folders && ( + + )} + } - }} />} - {props.folders && } - }> - - ; + > + + + ); } diff --git a/src/components/fileBrowser/name.ts b/src/components/fileBrowser/name.ts index d8b66edf..d9d5b9e9 100644 --- a/src/components/fileBrowser/name.ts +++ b/src/components/fileBrowser/name.ts @@ -1,6 +1,9 @@ // Keep the on-disk identity for API operations; shorten only generated names. export function readableLogName(name: string) { - const match = /^(\d{4}-\d\d-\d\d)-(\d\d)-(\d\d)-(\d\d)-(\d{3})(?:-([a-z0-9-]{8,120}))?\.log$/.exec(name); + const match = + /^(\d{4}-\d\d-\d\d)-(\d\d)-(\d\d)-(\d\d)-(\d{3})(?:-([a-z0-9-]{8,120}))?\.log$/.exec( + name, + ); if (!match) return name; const [, date, h, m, s, ms, id] = match; return `${date} ${h}:${m}:${s}.${ms}${id ? ' · ' + id.slice(-6) : ''}`; diff --git a/src/pages/crontab/dailyResults.tsx b/src/pages/crontab/dailyResults.tsx index 3c651313..0d129fac 100644 --- a/src/pages/crontab/dailyResults.tsx +++ b/src/pages/crontab/dailyResults.tsx @@ -24,7 +24,10 @@ export default function DailyResults({ id }: { id: number }) { let timer: ReturnType; async function load() { try { - const { code, data } = await request.get(`${config.apiPrefix}crons/${id}/daily-results`, { signal, retryInPlace: true }); + const { code, data } = await request.get( + `${config.apiPrefix}crons/${id}/daily-results`, + { signal, retryInPlace: true }, + ); if (code !== 200) throw new Error(); if (signal.aborted) return; setRows(data); @@ -37,26 +40,80 @@ export default function DailyResults({ id }: { id: number }) { } } void load(); - return () => { controller.abort(); clearTimeout(timer); }; + return () => { + controller.abort(); + clearTimeout(timer); + }; }, [id, attempt]); - return
- {intl.get('近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。')} - {failed &&
{intl.get(rows.length ? '刷新失败,仍显示上次的数据' : '加载失败')} - -
} - size="small" rowKey="day" dataSource={rows} pagination={false} - loading={loading} scroll={{ x: 520 }} columns={[ - { title: intl.get('日期'), dataIndex: 'day' }, - { title: intl.get('按执行明细统计'), children: [ - { title: intl.get('成功'), dataIndex: 'exitSuccess', align: 'right' }, - { title: intl.get('失败'), dataIndex: 'exitFail', align: 'right' }, - ] }, - { title: intl.get('每日汇总'), children: [ - { title: intl.get('成功'), dataIndex: 'bookedSuccess', align: 'right' }, - { title: intl.get('失败'), dataIndex: 'bookedFail', align: 'right' }, - { title: intl.get('其中升级时补记'), dataIndex: 'supplement', align: 'right' }, - ] }, - ]} /> -
; + return ( +
+ + {intl.get( + '近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。', + )} + + {failed && ( +
+ {intl.get(rows.length ? '刷新失败,仍显示上次的数据' : '加载失败')} + +
+ )} + + size="small" + rowKey="day" + dataSource={rows} + pagination={false} + loading={loading} + scroll={{ x: 520 }} + columns={[ + { title: intl.get('日期'), dataIndex: 'day' }, + { + title: intl.get('按执行明细统计'), + children: [ + { + title: intl.get('成功'), + dataIndex: 'exitSuccess', + align: 'right', + }, + { + title: intl.get('失败'), + dataIndex: 'exitFail', + align: 'right', + }, + ], + }, + { + title: intl.get('每日汇总'), + children: [ + { + title: intl.get('成功'), + dataIndex: 'bookedSuccess', + align: 'right', + }, + { + title: intl.get('失败'), + dataIndex: 'bookedFail', + align: 'right', + }, + { + title: intl.get('其中升级时补记'), + dataIndex: 'supplement', + align: 'right', + }, + ], + }, + ]} + /> +
+ ); } diff --git a/src/pages/crontab/detail.tsx b/src/pages/crontab/detail.tsx index 0762cd5f..fd1ee984 100644 --- a/src/pages/crontab/detail.tsx +++ b/src/pages/crontab/detail.tsx @@ -41,7 +41,9 @@ const { Text } = Typography; function instanceTitle(item: { id: number; log_path?: string | null }) { const filename = item.log_path?.split('/').pop(); - return filename ? readableLogName(filename) : intl.get('执行实例 #{id}', { id: String(item.id) }); + return filename + ? readableLogName(filename) + : intl.get('执行实例 #{id}', { id: String(item.id) }); } const tabList = [ @@ -67,7 +69,9 @@ const CronDetailModal = ({ }) => { const [activeTabKey, setActiveTabKey] = useState('runningHistory'); const [value, setValue] = useState(''); - const [scriptState, setScriptState] = useState<'loading' | 'ready' | 'failed'>('loading'); + const [scriptState, setScriptState] = useState< + 'loading' | 'ready' | 'failed' + >('loading'); const editorRef = useRef(null); const [scriptInfo, setScriptInfo] = useState({}); const [validTabs, setValidTabs] = useState(tabList); @@ -94,12 +98,13 @@ const CronDetailModal = ({ setRefreshFailed(false); } } catch { - if (!signal.aborted && version === refreshVersion.current) setRefreshFailed(true); + if (!signal.aborted && version === refreshVersion.current) + setRefreshFailed(true); } }; const refreshAfterChange = () => { needRefreshRef.current = true; - setHistoryRevision(n => n + 1); + setHistoryRevision((n) => n + 1); return refreshDetails(); }; @@ -122,111 +127,138 @@ const CronDetailModal = ({ const contentList: any = { daily: , - triggers: activeTabKey === 'triggers' && viewInstanceLog(row, row.id)} />, - script: scriptState === 'failed' ? ( - {intl.get('加载失败')} - ) : scriptState === 'loading' ? intl.get('加载中...') : scriptInfo.filename && ( - { - editorRef.current = editor; - }} + triggers: activeTabKey === 'triggers' && ( + viewInstanceLog(row, row.id)} /> ), + script: + scriptState === 'failed' ? ( + + {intl.get('加载失败')}{' '} + + + ) : scriptState === 'loading' ? ( + intl.get('加载中...') + ) : ( + scriptInfo.filename && ( + { + editorRef.current = editor; + }} + /> + ) + ), runningHistory: activeTabKey === 'runningHistory' && ( - {(item) => ( - item.log_path && viewInstanceLog(item)} - style={{ cursor: item.log_path ? 'pointer' : 'default' }} - actions={[ - item.log_path && ( - - - } + {refreshFailed && ( + + {intl.get('任务状态刷新失败')} + + + )} {(!currentCron.isDisabled || currentCron.status !== CrontabStatus.idle) && ( - <> - {currentCron.status === CrontabStatus.idle && ( - } color="default"> - {intl.get('空闲中')} - - )} - {currentCron.status === CrontabStatus.running && ( - } - color="processing" - > - {intl.get('运行中')} - - )} - {currentCron.status === CrontabStatus.queued && ( - } color="default"> - {intl.get('队列中')} - - )} - - )} + <> + {currentCron.status === CrontabStatus.idle && ( + } color="default"> + {intl.get('空闲中')} + + )} + {currentCron.status === CrontabStatus.running && ( + } + color="processing" + > + {intl.get('运行中')} + + )} + {currentCron.status === CrontabStatus.queued && ( + } color="default"> + {intl.get('队列中')} + + )} + + )} {currentCron.isDisabled === 1 && currentCron.status === CrontabStatus.idle && ( } color="error"> @@ -626,8 +698,8 @@ const CronDetailModal = ({
{currentCron.last_execution_time ? dayjs(currentCron.last_execution_time * 1000).format( - 'YYYY-MM-DD HH:mm:ss', - ) + 'YYYY-MM-DD HH:mm:ss', + ) : '-'}
@@ -636,7 +708,8 @@ const CronDetailModal = ({ {intl.get('最后运行时长')}
- {currentCron.last_execution_time && currentCron.last_running_time != null + {currentCron.last_execution_time && + currentCron.last_running_time != null ? diffTime(currentCron.last_running_time) : '-'}
@@ -659,7 +732,8 @@ const CronDetailModal = ({ onTabChange(key); }} tabBarExtraContent={ - activeTabKey === 'script' && scriptState === 'ready' && ( + activeTabKey === 'script' && + scriptState === 'ready' && ( <> - } + {listFailed && ( +
+ {intl.get('任务列表刷新失败')} + +
+ )} { getCrons(); }} key={logCron.id} - cron={value.find(row => row.id === logCron.id) ?? logCron} + cron={value.find((row) => row.id === logCron.id) ?? logCron} /> )} {isModalVisible && ( diff --git a/src/pages/crontab/instanceHistory.tsx b/src/pages/crontab/instanceHistory.tsx index 02d2ac82..726efefe 100644 --- a/src/pages/crontab/instanceHistory.tsx +++ b/src/pages/crontab/instanceHistory.tsx @@ -11,10 +11,22 @@ import { pageSize } from './triggerUpdates'; const paginationRow = { id: 'pagination' }; -export default function InstanceHistory({ id, revision, children }: { - id: number; revision: number; children: (row: any) => React.ReactElement; +export default function InstanceHistory({ + id, + revision, + children, +}: { + id: number; + revision: number; + children: (row: any) => React.ReactElement; }) { - const state = useRef({ rows: [] as any[], next: null as number | null, expanded: false, head: 0, hasNew: false }); + const state = useRef({ + rows: [] as any[], + next: null as number | null, + expanded: false, + head: 0, + hasNew: false, + }); const visibleIds = useRef(new Set()); const [view, setView] = useState(state.current); const [busy, setBusy] = useState(true); @@ -25,8 +37,10 @@ export default function InstanceHistory({ id, revision, children }: { const list = useRef(null); const listHeight = useScrollHeight(viewport); const showPagination = Boolean(failed || view.next || view.expanded); - const items = useMemo(() => showPagination ? [...view.rows, paginationRow] : view.rows, - [view.rows, showPagination]); + const items = useMemo( + () => (showPagination ? [...view.rows, paginationRow] : view.rows), + [view.rows, showPagination], + ); async function load(action: 'older' | 'refresh' | 'latest') { if (action === 'older' && !state.current.next) return; if (pending.current && (action === 'refresh' || paging.current)) return; @@ -42,8 +56,14 @@ export default function InstanceHistory({ id, revision, children }: { } const previous = state.current; const read = async (params: any) => { - const result = await request.get<{code: number; data: any[]; next?: number | null}>(`${config.apiPrefix}crons/${id}/instances`, { - params: { paged: true, ...params }, signal: controller.signal, retryInPlace: true, + const result = await request.get<{ + code: number; + data: any[]; + next?: number | null; + }>(`${config.apiPrefix}crons/${id}/instances`, { + params: { paged: true, ...params }, + signal: controller.signal, + retryInPlace: true, }); if (result.code !== 200 || !Array.isArray(result.data)) throw new Error(); return result; @@ -53,56 +73,125 @@ export default function InstanceHistory({ id, revision, children }: { if (action === 'refresh' && previous.expanded) { const latest = await read({ limit: 1 }); if (controller.signal.aborted) return; - const active = previous.rows.filter(row => row.status === 0 || row.status === 4 || visibleIds.current.has(row.id)); + const active = previous.rows.filter( + (row) => + row.status === 0 || + row.status === 4 || + visibleIds.current.has(row.id), + ); const updates = new Map(); for (let i = 0; i < active.length; i += pageSize) { - const ids = active.slice(i, i + pageSize).map(row => row.id); + const ids = active.slice(i, i + pageSize).map((row) => row.id); const page = await read({ ids: ids.join(',') }); if (controller.signal.aborted) return; - ids.forEach(id => updates.set(id, undefined)); + ids.forEach((id) => updates.set(id, undefined)); page.data.forEach((r: any) => updates.set(r.id, r)); } - result = { ...previous, hasNew: latest.data[0]?.id > previous.head, - rows: previous.rows.map(r => updates.has(r.id) ? updates.get(r.id) : r).filter(Boolean) }; + result = { + ...previous, + hasNew: latest.data[0]?.id > previous.head, + rows: previous.rows + .map((r) => (updates.has(r.id) ? updates.get(r.id) : r)) + .filter(Boolean), + }; } else { const more = action === 'older'; - const page = await read({ limit: pageSize, ...(more && { before: previous.next }) }); - result = { rows: more ? [...previous.rows, ...page.data] : page.data, next: page.next ?? null, expanded: more, - head: more ? previous.head : (page.data[0]?.id ?? 0), hasNew: more && previous.hasNew }; + const page = await read({ + limit: pageSize, + ...(more && { before: previous.next }), + }); + result = { + rows: more ? [...previous.rows, ...page.data] : page.data, + next: page.next ?? null, + expanded: more, + head: more ? previous.head : page.data[0]?.id ?? 0, + hasNew: more && previous.hasNew, + }; } if (!controller.signal.aborted) { - state.current = result; setView(result); + state.current = result; + setView(result); if (action === 'latest') list.current?.scrollTo(0); - setFailed(old => action === 'refresh' && old !== 'refresh' ? old : ''); + setFailed((old) => + action === 'refresh' && old !== 'refresh' ? old : '', + ); } } catch { - if (!controller.signal.aborted) setFailed(old => action === 'refresh' && old ? old : action); + if (!controller.signal.aborted) + setFailed((old) => (action === 'refresh' && old ? old : action)); } finally { - if (!controller.signal.aborted) { pending.current = undefined; paging.current = false; setBusy(false); } + if (!controller.signal.aborted) { + pending.current = undefined; + paging.current = false; + setBusy(false); + } } } useEffect(() => { void load('refresh'); const timer = setInterval(() => void load('refresh'), 10000); - return () => { clearInterval(timer); pending.current?.abort(); pending.current = undefined; paging.current = false; }; + return () => { + clearInterval(timer); + pending.current?.abort(); + pending.current = undefined; + paging.current = false; + }; }, [id, revision]); - const pagination =
- - {failed && } - {!!view.next && failed !== 'older' && } - {view.expanded && failed !== 'latest' && } - -
; - return
- - {listHeight > 0 && { - visibleIds.current = new Set(rows.filter(row => row !== paginationRow).map(row => row.id)); - }}> - {row => row === paginationRow ? pagination : children(row)} - } - -
; + const pagination = ( +
+ + {failed && ( + + )} + {!!view.next && failed !== 'older' && ( + + )} + {view.expanded && failed !== 'latest' && ( + + )} + +
+ ); + return ( +
+ + {listHeight > 0 && ( + { + visibleIds.current = new Set( + rows + .filter((row) => row !== paginationRow) + .map((row) => row.id), + ); + }} + > + {(row) => (row === paginationRow ? pagination : children(row))} + + )} + +
+ ); } diff --git a/src/pages/crontab/logModal.tsx b/src/pages/crontab/logModal.tsx index b7f28d45..85d39588 100644 --- a/src/pages/crontab/logModal.tsx +++ b/src/pages/crontab/logModal.tsx @@ -1,5 +1,5 @@ -import intl from "react-intl-universal"; -import React, { useEffect, useRef, useState } from "react"; +import intl from 'react-intl-universal'; +import React, { useEffect, useRef, useState } from 'react'; import { Modal, message, @@ -8,16 +8,16 @@ import { Statistic, Button, Typography, -} from "antd"; -import { request } from "@/utils/http"; -import config from "@/utils/config"; +} from 'antd'; +import { request } from '@/utils/http'; +import config from '@/utils/config'; import { Loading3QuartersOutlined, CheckCircleOutlined, -} from "@ant-design/icons"; -import { PageLoading } from "@ant-design/pro-layout"; -import { CrontabStatus } from "./type"; -import Ansi from "ansi-to-react"; +} from '@ant-design/icons'; +import { PageLoading } from '@ant-design/pro-layout'; +import { CrontabStatus } from './type'; +import Ansi from 'ansi-to-react'; const { Countdown } = Statistic; const LOG_CHUNK_BYTES = 256 * 1024; @@ -34,7 +34,7 @@ const CronLogModal = ({ data?: string; logUrl?: string; }) => { - const [value, setValue] = useState(intl.get("启动中...")); + const [value, setValue] = useState(intl.get('启动中...')); const [loading, setLoading] = useState(true); const [executing, setExecuting] = useState(true); const [readFailed, setReadFailed] = useState(false); @@ -61,72 +61,103 @@ const CronLogModal = ({ setLoading(true); } const baseUrl = logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`; - const triggerParam = !logUrl && pinnedTrigger.current - ? "&triggerId=" + encodeURIComponent(pinnedTrigger.current) : ""; - const separator = baseUrl.includes("?") ? "&" : "?"; + const triggerParam = + !logUrl && pinnedTrigger.current + ? '&triggerId=' + encodeURIComponent(pinnedTrigger.current) + : ''; + const separator = baseUrl.includes('?') ? '&' : '?'; const offset = isFirst ? undefined : logOffsetRef.current; const pagination = `${separator}limit=${LOG_CHUNK_BYTES}${ - isFirst ? "&tail=true" : offset !== undefined ? `&offset=${offset}` : "" + isFirst ? '&tail=true' : offset !== undefined ? `&offset=${offset}` : '' }`; - const pathParam = offset !== undefined && lastPath.current - ? "&previousPath=" + encodeURIComponent(lastPath.current) : ""; - const cursorParam = offset !== undefined && lastCursor.current ? "&cursor=" + lastCursor.current : ""; + const pathParam = + offset !== undefined && lastPath.current + ? '&previousPath=' + encodeURIComponent(lastPath.current) + : ''; + const cursorParam = + offset !== undefined && lastCursor.current + ? '&cursor=' + lastCursor.current + : ''; request - .get(`${baseUrl}${pagination}${pathParam}${cursorParam}${triggerParam}&follow=true`, { signal, retryInPlace: true }) - .then(({ code, data, logStatus, logPath, triggerId, cursor, reset, nextOffset, total }) => { - if (signal.aborted) { - return; - } + .get( + `${baseUrl}${pagination}${pathParam}${cursorParam}${triggerParam}&follow=true`, + { signal, retryInPlace: true }, + ) + .then( + ({ + code, + data, + logStatus, + logPath, + triggerId, + cursor, + reset, + nextOffset, + total, + }) => { + if (signal.aborted) { + return; + } - if (code !== 200) throw new Error("Log read failed"); - setReadFailed(false); - const isRunning = logStatus === "running"; - // A completed process can still have multiple unread chunks. Drain - // them before stopping, without presenting it as a running task. - if (triggerId) pinnedTrigger.current = triggerId; - const changedFile = reset === true || lastPath.current !== logPath; - const hasUnread = - typeof nextOffset === "number" && - typeof total === "number" && - nextOffset > (changedFile ? 0 : offset ?? 0) && - nextOffset < total; - const hasNext = isRunning || hasUnread; - const chunk = (data as string) || ""; - lastPath.current = logPath; - lastCursor.current = cursor; - // A missing file can return a localized status message with zero bytes. - // Keep that message out of the buffer used for subsequent appends. - const noBytes = total === 0; - if (!isFirst && !changedFile && offset !== undefined && total > 0 && total < offset) { - logOffsetRef.current = undefined; - pollTimerRef.current = setTimeout(() => getCronLog(true), 0); - return; - } - let log = isFirst || changedFile || noBytes || offset === undefined ? chunk : valueRef.current + chunk; - if (!log && !hasNext) { - log = intl.get("暂无日志"); - } - if (log.length > MAX_LOG_VIEW_CHARS) { - log = log.slice(-MAX_LOG_VIEW_CHARS); - } - valueRef.current = noBytes ? "" : log; - setValue(log); - if (typeof nextOffset === "number") { - logOffsetRef.current = nextOffset; - } - drained.current = !hasNext; - setExecuting(isRunning); + if (code !== 200) throw new Error('Log read failed'); + setReadFailed(false); + const isRunning = logStatus === 'running'; + // A completed process can still have multiple unread chunks. Drain + // them before stopping, without presenting it as a running task. + if (triggerId) pinnedTrigger.current = triggerId; + const changedFile = reset === true || lastPath.current !== logPath; + const hasUnread = + typeof nextOffset === 'number' && + typeof total === 'number' && + nextOffset > (changedFile ? 0 : offset ?? 0) && + nextOffset < total; + const hasNext = isRunning || hasUnread; + const chunk = (data as string) || ''; + lastPath.current = logPath; + lastCursor.current = cursor; + // A missing file can return a localized status message with zero bytes. + // Keep that message out of the buffer used for subsequent appends. + const noBytes = total === 0; + if ( + !isFirst && + !changedFile && + offset !== undefined && + total > 0 && + total < offset + ) { + logOffsetRef.current = undefined; + pollTimerRef.current = setTimeout(() => getCronLog(true), 0); + return; + } + let log = + isFirst || changedFile || noBytes || offset === undefined + ? chunk + : valueRef.current + chunk; + if (!log && !hasNext) { + log = intl.get('暂无日志'); + } + if (log.length > MAX_LOG_VIEW_CHARS) { + log = log.slice(-MAX_LOG_VIEW_CHARS); + } + valueRef.current = noBytes ? '' : log; + setValue(log); + if (typeof nextOffset === 'number') { + logOffsetRef.current = nextOffset; + } + drained.current = !hasNext; + setExecuting(isRunning); - if (chunk || !hasNext) { - autoScroll(); - } - if (hasNext) { - pollTimerRef.current = setTimeout( - () => getCronLog(), - hasUnread ? 0 : 2000, - ); - } - }) + if (chunk || !hasNext) { + autoScroll(); + } + if (hasNext) { + pollTimerRef.current = setTimeout( + () => getCronLog(), + hasUnread ? 0 : 2000, + ); + } + }, + ) .catch(() => { if (!signal.aborted) setReadFailed(true); }) @@ -145,7 +176,7 @@ const CronLogModal = ({ clearTimeout(scrollTimer.current); scrollTimer.current = setTimeout(() => { - logEndRef.current?.scrollIntoView({ behavior: "smooth" }); + logEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, 600); }; @@ -172,12 +203,16 @@ const CronLogModal = ({ const titleElement = () => { return ( -
- {!readFailed && (executing || loading) && } +
+ {!readFailed && (executing || loading) && ( + + )} {!readFailed && !executing && !loading && } {cron && cron.name} - {pinnedTrigger.current && lastPath.current && ` · ${lastPath.current.split("/").pop()}`} + {pinnedTrigger.current && + lastPath.current && + ` · ${lastPath.current.split('/').pop()}`}
); @@ -198,8 +233,11 @@ const CronLogModal = ({ // start (and finish) after this viewer drained the previous file. useEffect(() => { if (logUrl || pinnedTrigger.current || !cron || !drained.current) return; - if ((cron.log_path && cron.log_path !== lastPath.current) || - cron.status === CrontabStatus.running || cron.status === CrontabStatus.queued) { + if ( + (cron.log_path && cron.log_path !== lastPath.current) || + cron.status === CrontabStatus.running || + cron.status === CrontabStatus.queued + ) { getCronLog(); } }, [cron]); @@ -226,18 +264,25 @@ const CronLogModal = ({ onCancel={() => cancel()} footer={[ , ]} >
- {readFailed &&
- {intl.get("加载失败")} - -
} + {readFailed && ( +
+ {intl.get('加载失败')} + +
+ )} {loading ? ( ) : ( @@ -245,13 +290,15 @@ const CronLogModal = ({ style={ isPhone ? { - fontFamily: "Source Code Pro", - zoom: 0.83, - } + fontFamily: 'Source Code Pro', + zoom: 0.83, + } : {} } > - {readFailed && logOffsetRef.current === undefined ? "" : value} + + {readFailed && logOffsetRef.current === undefined ? '' : value} + )}
diff --git a/src/pages/crontab/modal.tsx b/src/pages/crontab/modal.tsx index d3b738a0..7bb3428a 100644 --- a/src/pages/crontab/modal.tsx +++ b/src/pages/crontab/modal.tsx @@ -2,7 +2,17 @@ import EditableTagGroup from '@/components/tag'; import config from '@/utils/config'; import { request } from '@/utils/http'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; -import { Button, Checkbox, Form, Input, InputNumber, Modal, Select, Space, message } from 'antd'; +import { + Button, + Checkbox, + Form, + Input, + InputNumber, + Modal, + Select, + Space, + message, +} from 'antd'; import { useEffect, useState } from 'react'; import intl from 'react-intl-universal'; import { getScheduleType, scheduleTypeMap } from './const'; @@ -86,13 +96,30 @@ const CronModal = ({ let invalid = false; try { result = await request.get(`${config.apiPrefix}crons/preview`, { - params: { schedule: rule }, onError: (response) => { invalid = response?.status === 400; }, + params: { schedule: rule }, + onError: (response) => { + invalid = response?.status === 400; + }, }); - } catch { /* Transport errors have no validation result. */ } - if (!result?.data?.times) throw new Error(intl.get(invalid ? 'Cron表达式格式有误' : '无法获取调度预览,请重试')); + } catch { + /* Transport errors have no validation result. */ + } + if (!result?.data?.times) + throw new Error( + intl.get(invalid ? 'Cron表达式格式有误' : '无法获取调度预览,请重试'), + ); if (form.getFieldValue('schedule') === rule) { const { times, timezone } = result.data; - setPreview(times.map((time: number) => new Date(time).toLocaleString(undefined, { timeZone: timezone })).join(' · ') + ' (' + timezone + ')'); + setPreview( + times + .map((time: number) => + new Date(time).toLocaleString(undefined, { timeZone: timezone }), + ) + .join(' · ') + + ' (' + + timezone + + ')', + ); } }; @@ -108,15 +135,30 @@ const CronModal = ({ validateTrigger="onBlur" rules={[{ required: true }, { validator: previewRule }]} > - setPreview('')} placeholder={intl.get('秒(可选) 分 时 天 月 周')} /> + setPreview('')} + placeholder={intl.get('秒(可选) 分 时 天 月 周')} + /> - {intl.get('如果上一次定时执行仍在排队或运行,跳过本次')} + + {intl.get('如果上一次定时执行仍在排队或运行,跳过本次')} + - + - + diff --git a/src/pages/crontab/stopRequest.ts b/src/pages/crontab/stopRequest.ts index 7cf05ec3..62cfef0c 100644 --- a/src/pages/crontab/stopRequest.ts +++ b/src/pages/crontab/stopRequest.ts @@ -10,7 +10,11 @@ export function createStopRequest(ids: readonly (string | number)[]) { const headers = { 'Idempotency-Key': uuid() }; return async () => { try { - const result = await request.put(`${config.apiPrefix}crons/stop`, targets, { headers, retryInPlace: true }); + const result = await request.put( + `${config.apiPrefix}crons/stop`, + targets, + { headers, retryInPlace: true }, + ); if (result.code !== 200) throw new Error(result.message); return result; } catch (error) { diff --git a/src/pages/crontab/triggerList.tsx b/src/pages/crontab/triggerList.tsx index 9b32ce59..fb59188e 100644 --- a/src/pages/crontab/triggerList.tsx +++ b/src/pages/crontab/triggerList.tsx @@ -237,24 +237,28 @@ export default function TriggerList({ )}
- { - if (!expanded) statusRequest.current?.abort(); - if (!pinned) { - headRef.current = rows[0]; - pageRequest.current?.abort(); - // An open and close may be batched without ever committing a pinned page. - setAttempt((value) => value + 1); - setFailed(false); - setHasNew(false); - setRefreshFailed(false); - } - setOpenIds((previous) => { - const next = new Set(previous); - if (next.has(row.id)) next.delete(row.id); - else next.add(row.id); - return next; - }); - }} /> + { + if (!expanded) statusRequest.current?.abort(); + if (!pinned) { + headRef.current = rows[0]; + pageRequest.current?.abort(); + // An open and close may be batched without ever committing a pinned page. + setAttempt((value) => value + 1); + setFailed(false); + setHasNew(false); + setRefreshFailed(false); + } + setOpenIds((previous) => { + const next = new Set(previous); + if (next.has(row.id)) next.delete(row.id); + else next.add(row.id); + return next; + }); + }} + />
)} diff --git a/src/pages/crontab/triggerTiming.tsx b/src/pages/crontab/triggerTiming.tsx index c790eac4..c5c9a062 100644 --- a/src/pages/crontab/triggerTiming.tsx +++ b/src/pages/crontab/triggerTiming.tsx @@ -6,86 +6,212 @@ function elapsed(start?: number, end?: number) { if (start == null || end == null || end < start) return; const ms = end - start; if (ms < 1000) return ms + ' ms'; - return (ms / 1000) + ' s'; + return ms / 1000 + ' s'; } -export function QueueReason({ context, live = false }: { context: string; live?: boolean }) { - const admission: {queue: string; limit: number; occupied: number; holders: { id?: string; name: string }[]} = JSON.parse(context); - return
- {intl.get(admission.queue === 'manual' ? '手动执行队列' : '定时执行队列')} - {' · '}{intl.get(live ? '最近一次检查(运行 {used},上限 {limit})' : '入队时已达并发上限(运行 {used},上限 {limit})', { used: admission.occupied, limit: admission.limit })} -
    {admission.holders.map((holder, i) =>
  • - {holder.name}{holder.id && <> · {holder.id.slice(-8)}} -
  • )}
- {admission.occupied > admission.holders.length && intl.get('仅列出最早开始运行的 8 个实例')} -
; +export function QueueReason({ + context, + live = false, +}: { + context: string; + live?: boolean; +}) { + const admission: { + queue: string; + limit: number; + occupied: number; + holders: { id?: string; name: string }[]; + } = JSON.parse(context); + return ( +
+ + {intl.get( + admission.queue === 'manual' ? '手动执行队列' : '定时执行队列', + )} + + {' · '} + {intl.get( + live + ? '最近一次检查(运行 {used},上限 {limit})' + : '入队时已达并发上限(运行 {used},上限 {limit})', + { used: admission.occupied, limit: admission.limit }, + )} +
    + {admission.holders.map((holder, i) => ( +
  • + {holder.name} + {holder.id && ( + <> + {' '} + · {holder.id.slice(-8)} + + )} +
  • + ))} +
+ {admission.occupied > admission.holders.length && + intl.get('仅列出最早开始运行的 8 个实例')} +
+ ); } -export default function TriggerTiming({ row, open, onToggle }: { row: TriggerEntry; open: boolean; onToggle: () => void }) { +export default function TriggerTiming({ + row, + open, + onToggle, +}: { + row: TriggerEntry; + open: boolean; + onToggle: () => void; +}) { const queued = row.state === 'queued'; const skipped = row.state === 'skipped'; const unknown = row.state === 'unknown'; const terminal = !queued && row.state !== 'running'; - const start = row.scheduled_at ?? row.queued_at ?? row.started_at ?? row.observed_at; - const startLabel = row.scheduled_at != null ? '计划运行' : row.queued_at != null - ? '进入队列' : row.started_at != null ? '记录启动' : '记录时间'; + const start = + row.scheduled_at ?? row.queued_at ?? row.started_at ?? row.observed_at; + const startLabel = + row.scheduled_at != null + ? '计划运行' + : row.queued_at != null + ? '进入队列' + : row.started_at != null + ? '记录启动' + : '记录时间'; const endLabel = skipped ? '跳过时间' : unknown ? '状态记录时间' : '结束时间'; - const queueEnd = row.dequeued_at ?? row.started_at ?? (queued ? Date.now() : (skipped || row.state === 'stopped') ? row.finished_at : undefined); - const wait = queued && row.queue_wait_ms != null - ? elapsed(0, row.queue_wait_ms) : elapsed(row.queued_at, queueEnd); + const queueEnd = + row.dequeued_at ?? + row.started_at ?? + (queued + ? Date.now() + : skipped || row.state === 'stopped' + ? row.finished_at + : undefined); + const wait = + queued && row.queue_wait_ms != null + ? elapsed(0, row.queue_wait_ms) + : elapsed(row.queued_at, queueEnd); const launch = elapsed(row.scheduled_at, row.command_started_at); - const entryDelay = elapsed(row.scheduled_at ?? row.queued_at ?? row.started_at, row.script_started_at); - const entryLabel = row.scheduled_at != null ? '计划到脚本开始' : row.queued_at != null - ? '入队到脚本开始' : '启动记录到脚本开始'; + const entryDelay = elapsed( + row.scheduled_at ?? row.queued_at ?? row.started_at, + row.script_started_at, + ); + const entryLabel = + row.scheduled_at != null + ? '计划到脚本开始' + : row.queued_at != null + ? '入队到脚本开始' + : '启动记录到脚本开始'; const time = (value: number, precise: boolean) => { const date = dayjs(value); - const format = date.isSame(start, 'day') ? 'HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss'; + const format = date.isSame(start, 'day') + ? 'HH:mm:ss' + : 'YYYY-MM-DD HH:mm:ss'; return date.format(precise ? format + '.SSS' : format); }; const timestamps: [string, number | undefined][] = [ ['计划运行', row.scheduled_at], ['进入队列', row.queued_at], - [row.queued_at != null ? '排队结束' : '记录启动', row.dequeued_at ?? row.started_at], + [ + row.queued_at != null ? '排队结束' : '记录启动', + row.dequeued_at ?? row.started_at, + ], ['命令启动', row.command_started_at], ['脚本开始执行(采样)', row.script_started_at], [endLabel, row.finished_at], ]; - return <> -
- {intl.get(startLabel)} {dayjs(start).format('YYYY-MM-DD HH:mm:ss')} - {queued && wait != null && {intl.get('已排队')} {wait}} - {!skipped && !queued && launch != null && {intl.get('计划到命令启动')} {launch}} - {row.scheduled_at == null && row.command_started_at != null && ( - {intl.get('命令启动')} {time(row.command_started_at, false)} - )} - {!skipped && !queued && wait != null && {intl.get('排队等待')} {wait}} - {terminal && row.finished_at != null && !unknown && !skipped && ( - {intl.get(endLabel)} {time(row.finished_at, false)} - )} - {row.exit_code != null && row.exit_code !== 0 && {intl.get('退出码')} {row.exit_code}} -
-
- { - event.preventDefault(); - onToggle(); - }}>{intl.get('时间明细')} - {queued && row.dequeued_at != null ?

{intl.get('排队结束,正在准备命令')}

- : queued && row.queue_live_context ? - : row.queue_context && } - {queued && row.dequeued_at == null && !row.queue_context && !row.queue_live_context &&

{intl.get('正在排队,尚无同时运行的任务记录')}

} -
- {timestamps.map(([key, value]) =>
-
{intl.get(key)}
-
{value != null ? time(value, true) : intl.get( - key === '脚本开始执行(采样)' ? '未采集到开始时间' : '未记录', - )}
-
)} -
- {(entryDelay != null || (skipped && wait != null)) &&
- {skipped && wait != null && {intl.get('跳过前等待')} {wait}} - {entryDelay != null && {intl.get(entryLabel)} {entryDelay}} -
} -
- ; + return ( + <> +
+ + {intl.get(startLabel)}{' '} + {dayjs(start).format('YYYY-MM-DD HH:mm:ss')} + + {queued && wait != null && ( + + {intl.get('已排队')} {wait} + + )} + {!skipped && !queued && launch != null && ( + + {intl.get('计划到命令启动')} {launch} + + )} + {row.scheduled_at == null && row.command_started_at != null && ( + + {intl.get('命令启动')} {time(row.command_started_at, false)} + + )} + {!skipped && !queued && wait != null && ( + + {intl.get('排队等待')} {wait} + + )} + {terminal && row.finished_at != null && !unknown && !skipped && ( + + {intl.get(endLabel)} {time(row.finished_at, false)} + + )} + {row.exit_code != null && row.exit_code !== 0 && ( + + {intl.get('退出码')} {row.exit_code} + + )} +
+
+ { + event.preventDefault(); + onToggle(); + }} + > + {intl.get('时间明细')} + + {queued && row.dequeued_at != null ? ( +

{intl.get('排队结束,正在准备命令')}

+ ) : queued && row.queue_live_context ? ( + + ) : ( + row.queue_context && + )} + {queued && + row.dequeued_at == null && + !row.queue_context && + !row.queue_live_context && ( +

{intl.get('正在排队,尚无同时运行的任务记录')}

+ )} +
+ {timestamps.map(([key, value]) => ( +
+
{intl.get(key)}
+
+ {value != null + ? time(value, true) + : intl.get( + key === '脚本开始执行(采样)' + ? '未采集到开始时间' + : '未记录', + )} +
+
+ ))} +
+ {(entryDelay != null || (skipped && wait != null)) && ( +
+ {skipped && wait != null && ( + + {intl.get('跳过前等待')} {wait} + + )} + {entryDelay != null && ( + + {intl.get(entryLabel)} {entryDelay} + + )} +
+ )} +
+ + ); } diff --git a/src/pages/crontab/triggerUpdates.ts b/src/pages/crontab/triggerUpdates.ts index 70515471..572af4c4 100644 --- a/src/pages/crontab/triggerUpdates.ts +++ b/src/pages/crontab/triggerUpdates.ts @@ -49,8 +49,11 @@ export function createTriggerPoll( try { const [latest] = await read(new URLSearchParams({ limit: '1' })); if (!active()) return; - onHead(!!latest && (latest.observed_at > head.observed_at || - (latest.observed_at === head.observed_at && latest.id > head.id))); + onHead( + !!latest && + (latest.observed_at > head.observed_at || + (latest.observed_at === head.observed_at && latest.id > head.id)), + ); headFailed = false; } catch { headFailed = true; @@ -95,16 +98,28 @@ export function createTriggerPoll( } } - return function poll(rows: TriggerEntry[], action: 'poll' | 'retry' | ReadonlySet = 'poll') { + return function poll( + rows: TriggerEntry[], + action: 'poll' | 'retry' | ReadonlySet = 'poll', + ) { if (!active()) return; const previousOpen = openIds; if (typeof action !== 'string') openIds = action; - watched = new Set(rows.filter(row => - openIds.has(row.id) || row.state === 'running' || row.state === 'queued' || - row.reason === 'exit_pending' || row.reason === 'exit_conflict' || - row.legacy_exit_booking === 1 || - (row.reason === 'restart' && (row.state === 'skipped' || row.state === 'unknown')), - ).map(row => row.id)); + watched = new Set( + rows + .filter( + (row) => + openIds.has(row.id) || + row.state === 'running' || + row.state === 'queued' || + row.reason === 'exit_pending' || + row.reason === 'exit_conflict' || + row.legacy_exit_booking === 1 || + (row.reason === 'restart' && + (row.state === 'skipped' || row.state === 'unknown')), + ) + .map((row) => row.id), + ); const previousFailures = failed.size; for (const id of failed) if (!watched.has(id)) failed.delete(id); @@ -120,7 +135,8 @@ export function createTriggerPoll( } if (!inFlight.has(id)) waiting.add(id); } - if (action === 'poll' || (action === 'retry' && headFailed)) void checkHead(); + if (action === 'poll' || (action === 'retry' && headFailed)) + void checkHead(); while (active() && waiting.size && workers < 2) void refreshBatches(); }; } diff --git a/src/pages/dashboard/index.less b/src/pages/dashboard/index.less index 2bb7c248..b82550cc 100644 --- a/src/pages/dashboard/index.less +++ b/src/pages/dashboard/index.less @@ -68,28 +68,57 @@ grid-auto-rows: 1fr; gap: 12px; margin: 0 !important; - > .ant-col { min-width: 0; max-width: none; padding: 0 !important; } - .ant-card { height: 100%; } - .ant-statistic-content { font-variant-numeric: tabular-nums; overflow-wrap: anywhere; line-height: 1.3; } - small { display: block; margin-top: 3px; } + > .ant-col { + min-width: 0; + max-width: none; + padding: 0 !important; + } + .ant-card { + height: 100%; + } + .ant-statistic-content { + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; + line-height: 1.3; + } + small { + display: block; + margin-top: 3px; + } } -.dashboard-wrapper { container-type: inline-size; } +.dashboard-wrapper { + container-type: inline-size; +} @container (min-width: 640px) { - .dashboard-totals.ant-row { grid-template-columns: repeat(4, minmax(0, 1fr)); } + .dashboard-totals.ant-row { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } } @container (min-width: 1280px) { - .dashboard-totals.ant-row { grid-template-columns: repeat(8, minmax(0, 1fr)); } + .dashboard-totals.ant-row { + grid-template-columns: repeat(8, minmax(0, 1fr)); + } } -.queue-entry { padding: 8px 0; border-bottom: 1px solid var(--ant-border-color-split); } -.queue-reason ul { padding-inline-start: 22px; margin: 4px 0; } +.queue-entry { + padding: 8px 0; + border-bottom: 1px solid var(--ant-border-color-split); +} +.queue-reason ul { + padding-inline-start: 22px; + margin: 4px 0; +} -.schedule-group-title { margin-top: 16px; } +.schedule-group-title { + margin-top: 16px; +} .timing-samples { margin: 0; - dd { margin: 0; } + dd { + margin: 0; + } } .schedule-overview > .ant-card-head .ant-card-head-title { @@ -118,10 +147,19 @@ overscroll-behavior: contain; overflow-wrap: anywhere; - h4 { margin: 12px 0 6px; } - p { margin: 8px 0 0; } - > :first-child { margin-top: 0; } - .timing-samples { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 16px; } + h4 { + margin: 12px 0 6px; + } + p { + margin: 8px 0 0; + } + > :first-child { + margin-top: 0; + } + .timing-samples { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px 16px; + } } .anomaly-count { @@ -131,5 +169,8 @@ color: var(--ant-primary-color, @primary-color); font: inherit; cursor: pointer; - &:hover, &:focus-visible { text-decoration: underline; } + &:hover, + &:focus-visible { + text-decoration: underline; + } } diff --git a/src/pages/dashboard/index.tsx b/src/pages/dashboard/index.tsx index 06b8bc31..c3318223 100644 --- a/src/pages/dashboard/index.tsx +++ b/src/pages/dashboard/index.tsx @@ -1,5 +1,24 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; -import { message, Button, Card, Col, Popover, Row, Statistic, Table, Tabs, Tag, Spin, Empty } from 'antd'; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from 'react'; +import { + message, + Button, + Card, + Col, + Popover, + Row, + Statistic, + Table, + Tabs, + Tag, + Spin, + Empty, +} from 'antd'; import { CheckCircleOutlined, CloseCircleOutlined, @@ -19,7 +38,10 @@ import config from '@/utils/config'; import CronLogModal from '../crontab/logModal'; import { QueueReason } from '../crontab/triggerTiming'; import TimingStatistic from './timingStatistic'; -import ScheduleAnomalies, { AnomalyMetric, AnomalySelection } from './scheduleAnomalies'; +import ScheduleAnomalies, { + AnomalyMetric, + AnomalySelection, +} from './scheduleAnomalies'; import TaskResultModal from './taskResultModal'; import './index.less'; @@ -30,17 +52,60 @@ export interface Overview { total: number; enabled: number; disabled: number; - triggers?: { audit?: { - since: number; through: number; zone: string; partial?: boolean; expected: number; observed: number; missing: number; - onTime: number; dispatched: number; commandSamples: number; skipped: number; queued: number; unconfirmed: number; - waitSamples?: number; - triggerDeviationP95: number | null; waitP95: number | null; commandStartP95: number | null; - scriptStartP95: number | null; scriptSamples: number; - } | null; systemAudit?: { - since: number; through: number; actualUnconfirmed?: number; confirmedAt: number | null; pending: boolean; partial: boolean; expected: number; observed: number; - dispatched: number; skipped: number; missing: number; unmatched: number; duplicates: number; actualStarts: number; actualSkips?: number; uncertain: number; awaiting: number; switchSlots: number; - recent: { time: number; task: number; name?: string; status: string; id?: string; triggerCount?: number; startCount?: number; skipCount?: number; unknownExitCount?: number }[]; - } | null }; + triggers?: { + audit?: { + since: number; + through: number; + zone: string; + partial?: boolean; + expected: number; + observed: number; + missing: number; + onTime: number; + dispatched: number; + commandSamples: number; + skipped: number; + queued: number; + unconfirmed: number; + waitSamples?: number; + triggerDeviationP95: number | null; + waitP95: number | null; + commandStartP95: number | null; + scriptStartP95: number | null; + scriptSamples: number; + } | null; + systemAudit?: { + since: number; + through: number; + actualUnconfirmed?: number; + confirmedAt: number | null; + pending: boolean; + partial: boolean; + expected: number; + observed: number; + dispatched: number; + skipped: number; + missing: number; + unmatched: number; + duplicates: number; + actualStarts: number; + actualSkips?: number; + uncertain: number; + awaiting: number; + switchSlots: number; + recent: { + time: number; + task: number; + name?: string; + status: string; + id?: string; + triggerCount?: number; + startCount?: number; + skipCount?: number; + unknownExitCount?: number; + }[]; + } | null; + }; todayRuns: number; todaySuccess: number; todayFail: number; @@ -69,8 +134,21 @@ interface Runtime { runningCount: number; queuedCount: number; queuedTasks: number; - oldestQueued?: { id: string; name: string; queued_at: number; queue_context?: string; queue_live_context?: string }[]; - running: Array<{ instanceId: number; id: number; name: string; pid: number; elapsed: number; logPath: string }>; + oldestQueued?: { + id: string; + name: string; + queued_at: number; + queue_context?: string; + queue_live_context?: string; + }[]; + running: Array<{ + instanceId: number; + id: number; + name: string; + pid: number; + elapsed: number; + logPath: string; + }>; idleTasks: Array<{ id: number; name: string; lastRun: string }>; } @@ -106,14 +184,34 @@ const formatSeconds = (s: number) => { const REFRESH_INTERVAL = 30000; -function ScheduleRate({ title, count, total }: { title: string; count?: number; total: number }) { +function ScheduleRate({ + title, + count, + total, +}: { + title: string; + count?: number; + total: number; +}) { const measured = count != null && total > 0; - const percent = measured ? (100 * count / total).toFixed(1) : null; + const percent = measured ? ((100 * count) / total).toFixed(1) : null; return ( 99.9%' : measured ? `${percent}%` : '—'} - suffix={measured ? ({count}/{total}) : undefined} + value={ + measured && percent === '100.0' && count < total + ? '>99.9%' + : measured + ? `${percent}%` + : '—' + } + suffix={ + measured ? ( + + ({count}/{total}) + + ) : undefined + } /> ); } @@ -121,8 +219,16 @@ function ScheduleRate({ title, count, total }: { title: string; count?: number; function formatCount(raw: number | string) { const count = Number(raw); const locale = document.documentElement.lang || navigator.language; - return {count.toLocaleString(locale, - count >= 100000 ? { notation: 'compact', maximumFractionDigits: 1 } : {})}; + return ( + + {count.toLocaleString( + locale, + count >= 100000 + ? { notation: 'compact', maximumFractionDigits: 1 } + : {}, + )} + + ); } const Dashboard = () => { @@ -148,22 +254,43 @@ const Dashboard = () => { anomalySession.current = undefined; setAnomaly(undefined); }, []); - const updateAnomalySummary = useCallback((selection: AnomalySelection, summary: NonNullable) => { - if (anomalySession.current !== selection) return; - setOverview(previous => anomalySession.current === selection && previous - ? { ...previous, triggers: { ...previous.triggers, ...summary } } : previous); - }, []); - const invalidateAnomaly = useCallback((selection: AnomalySelection, reason: 'expired' | 'unavailable') => { - if (anomalySession.current !== selection) return; - const version = anomalyVersion.current; - closeAnomaly(); - setOverview(previous => anomalyVersion.current === version && previous - ? { ...previous, triggers: undefined } : previous); - setLogCron(previous => previous?.anomalySession === selection.session ? null : previous); - message.info(intl.get(reason === 'expired' - ? '日期已变化,已关闭旧明细并刷新今日调度。' - : '这次明细已不可用,已关闭并刷新调度统计。')); - }, [closeAnomaly]); + const updateAnomalySummary = useCallback( + ( + selection: AnomalySelection, + summary: NonNullable, + ) => { + if (anomalySession.current !== selection) return; + setOverview((previous) => + anomalySession.current === selection && previous + ? { ...previous, triggers: { ...previous.triggers, ...summary } } + : previous, + ); + }, + [], + ); + const invalidateAnomaly = useCallback( + (selection: AnomalySelection, reason: 'expired' | 'unavailable') => { + if (anomalySession.current !== selection) return; + const version = anomalyVersion.current; + closeAnomaly(); + setOverview((previous) => + anomalyVersion.current === version && previous + ? { ...previous, triggers: undefined } + : previous, + ); + setLogCron((previous) => + previous?.anomalySession === selection.session ? null : previous, + ); + message.info( + intl.get( + reason === 'expired' + ? '日期已变化,已关闭旧明细并刷新今日调度。' + : '这次明细已不可用,已关闭并刷新调度统计。', + ), + ); + }, + [closeAnomaly], + ); const [helpOpen, setHelpOpen] = useState(false); const helpButton = useRef(null); const helpPopover = useRef<{ forcePopupAlign(): void }>(null); @@ -179,7 +306,11 @@ const Dashboard = () => { const alignArrow = () => { const trigger = button.getBoundingClientRect(); const box = popup.getBoundingClientRect(); - if (box.width) arrow.style.left = `${(trigger.left + trigger.width / 2 - box.left) * popup.offsetWidth / box.width}px`; + if (box.width) + arrow.style.left = `${ + ((trigger.left + trigger.width / 2 - box.left) * popup.offsetWidth) / + box.width + }px`; }; const viewport = window.visualViewport; const positionHelp = () => { @@ -189,12 +320,16 @@ const Dashboard = () => { const space = Math.max(trigger.top - top, top + height - trigger.bottom); const chromeHeight = popup.offsetHeight - helpContent.offsetHeight; // Leave room for the pointer, padding and viewport edge on the side that fits. - helpContent.style.maxHeight = `${Math.max(0, Math.min(height * 0.65, space - chromeHeight - 8))}px`; + helpContent.style.maxHeight = `${Math.max( + 0, + Math.min(height * 0.65, space - chromeHeight - 8), + )}px`; helpPopover.current?.forcePopupAlign(); alignArrow(); }; const onScroll = (event: Event) => { - if (!(event.target instanceof Node && popup.contains(event.target))) positionHelp(); + if (!(event.target instanceof Node && popup.contains(event.target))) + positionHelp(); }; positionHelp(); const resize = new ResizeObserver(positionHelp); @@ -205,7 +340,10 @@ const Dashboard = () => { }); visibility.observe(button); const observer = new MutationObserver(alignArrow); - observer.observe(popup, { attributes: true, attributeFilter: ['style', 'class'] }); + observer.observe(popup, { + attributes: true, + attributeFilter: ['style', 'class'], + }); popup.addEventListener('animationend', alignArrow); window.addEventListener('resize', positionHelp); window.addEventListener('scroll', onScroll, true); @@ -236,16 +374,21 @@ const Dashboard = () => { try { const requestedAt = performance.now(); const response = await request.get<{ code: number; data: T }>( - `${config.apiPrefix}dashboard/${section}`, { signal, retryInPlace: true }, + `${config.apiPrefix}dashboard/${section}`, + { signal, retryInPlace: true }, ); if (signal.aborted) return; if (response.code === 200) { let data = response.data; if (section === 'overview' && data) { const clock = data as Overview; - if (typeof clock.expiresAt === 'number' && typeof clock.serverNow === 'number') { + if ( + typeof clock.expiresAt === 'number' && + typeof clock.serverNow === 'number' + ) { const deadline = requestedAt + clock.expiresAt - clock.serverNow; - if (Number.isFinite(deadline)) data = { ...data, anomalyDeadline: deadline }; + if (Number.isFinite(deadline)) + data = { ...data, anomalyDeadline: deadline }; } } apply(data); @@ -306,119 +449,327 @@ const Dashboard = () => { showTotal: (total: number) => intl.get('总条数', { total }), }; - if (loading) return ; + if (loading) + return ; - const anomalyMetric = (source: AnomalySelection['source'], kind: AnomalySelection['kind'], count: number | undefined, through: number) => - { - const selection = { kind, source, count: count!, at: through + 5000, session: ++anomalyVersion.current, - deadline: overview?.anomalyDeadline }; - anomalySession.current = selection; - setAnomaly(selection); - }} />; + const anomalyMetric = ( + source: AnomalySelection['source'], + kind: AnomalySelection['kind'], + count: number | undefined, + through: number, + ) => ( + { + const selection = { + kind, + source, + count: count!, + at: through + 5000, + session: ++anomalyVersion.current, + deadline: overview?.anomalyDeadline, + }; + anomalySession.current = selection; + setAnomaly(selection); + }} + /> + ); const sources = []; if (audit) { const timings = [ - { title: intl.get('触发时间偏差 P95'), ms: audit.triggerDeviationP95, samples: audit.observed }, - { title: intl.get('排队等待 P95'), ms: audit.waitP95, samples: audit.waitSamples }, - { title: intl.get('计划到命令启动 P95'), ms: audit.commandStartP95, samples: audit.commandSamples }, - { title: intl.get('计划到脚本开始 P95'), ms: audit.scriptStartP95, samples: audit.scriptSamples }, + { + title: intl.get('触发时间偏差 P95'), + ms: audit.triggerDeviationP95, + samples: audit.observed, + }, + { + title: intl.get('排队等待 P95'), + ms: audit.waitP95, + samples: audit.waitSamples, + }, + { + title: intl.get('计划到命令启动 P95'), + ms: audit.commandStartP95, + samples: audit.commandSamples, + }, + { + title: intl.get('计划到脚本开始 P95'), + ms: audit.scriptStartP95, + samples: audit.scriptSamples, + }, ]; sources.push({ key: 'panel', label: intl.get('内置调度'), - help: <> - {audit.partial &&

{intl.get('规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。')}

} -

{intl.get('从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。', { - time: new Date(audit.since).toLocaleTimeString(undefined, {timeZone: audit.zone, hour12: false}), - })}

-

{intl.get('样本与计算方式')}

-
- {timings.map(({ title, samples }) =>
-
{title}
-
{samples == null ? '—' : intl.get('{count} 个样本', { count: samples })}
-
)} -
-

{intl.get('P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。')}

- , - children: <> -
- - {anomalyMetric('panel', 'missing', audit.missing, audit.through)} - - - - {anomalyMetric('panel', 'skipped', audit.skipped, audit.through)} - - {anomalyMetric('panel', 'unconfirmed', audit.unconfirmed, audit.through)} -
-
- {intl.get('查看启动耗时')} + help: ( + <> + {audit.partial && ( +

+ {intl.get( + '规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。', + )} +

+ )} +

+ {intl.get( + '从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。', + { + time: new Date(audit.since).toLocaleTimeString(undefined, { + timeZone: audit.zone, + hour12: false, + }), + }, + )} +

+

{intl.get('样本与计算方式')}

+
+ {timings.map(({ title, samples }) => ( +
+
{title}
+
+ {samples == null + ? '—' + : intl.get('{count} 个样本', { count: samples })} +
+
+ ))} +
+

+ {intl.get( + 'P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。', + )} +

+ + ), + children: ( + <>
- {timings.map(({ title, ms }) => )} + + {anomalyMetric('panel', 'missing', audit.missing, audit.through)} + + + + {anomalyMetric('panel', 'skipped', audit.skipped, audit.through)} + + {anomalyMetric( + 'panel', + 'unconfirmed', + audit.unconfirmed, + audit.through, + )}
-
- , +
+ {intl.get('查看启动耗时')} +
+ {timings.map(({ title, ms }) => ( + + ))} +
+
+ + ), }); } if (systemAudit) { sources.push({ key: 'system', label: intl.get('系统调度(crond)'), - help: <> -

{intl.get('同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。')}

-

{intl.get('上次成功安装规则')} {systemAudit.confirmedAt ? new Date(systemAudit.confirmedAt).toLocaleString() : '—'} - {' · '}{intl.get('按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。')}

- {(systemAudit.uncertain>0 || systemAudit.awaiting>0 || systemAudit.switchSlots>0) && -

{intl.get('等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。', {waiting:systemAudit.awaiting,uncertain:systemAudit.uncertain,switches:systemAudit.switchSlots})}

} - {(systemAudit.partial || systemAudit.pending) &&

{intl.get('部分时段的计划还无法确定,只统计能确认的计划。')}

} - , - children: <> -

{intl.get('按计划统计')}

-
- - - {anomalyMetric('system', 'missing', systemAudit.missing, systemAudit.through)} -
-

{intl.get('按触发记录统计(共 {count} 条)', { - count: systemAudit.observed + systemAudit.duplicates + systemAudit.unmatched, - })}

-
- - {anomalyMetric('system', 'skipped', systemAudit.actualSkips, systemAudit.through)} - {anomalyMetric('system', 'unconfirmed', systemAudit.actualUnconfirmed, systemAudit.through)} - - -
-
{intl.get('查看最近 25 次计划触发')} -
r.task + '/' + r.time} columns={[ - {title:intl.get('计划时间'),render:(_,r) => new Date(r.time).toLocaleTimeString()}, - {title:intl.get('任务'),render:(_,r) => r.name || '#' + r.task}, - {title:intl.get('匹配的触发记录'),dataIndex:'triggerCount',render:count => count ?? '—'}, - {title:intl.get('执行情况'),render:(_, row) => { - const { triggerCount = 0, startCount = 0, skipCount = 0, unknownExitCount = 0 } = row; - const unconfirmed = triggerCount - startCount - skipCount; - const status = triggerCount > 1 ? [ - startCount > 0 && intl.get('启动 {count} 次', {count: startCount}), - skipCount > 0 && intl.get('跳过 {count} 次', {count: skipCount}), - unconfirmed > 0 && intl.get('启动未确认 {count} 次', {count: unconfirmed}), - ].filter(Boolean).join(' · ') : intl.get(({ - started:'命令已启动', skipped:'已跳过', unconfirmed:'启动未确认', missing:'未收到触发记录', - switch:'生效规则不确定', uncertain:'触发分钟不确定', awaiting:'等待触发记录', - } as Record)[row.status]); - if (!unknownExitCount) return status; - return <>{status} · {triggerCount === 1 ? intl.get('结果未知') : - intl.get('其中 {count} 次执行结果未知', { count: unknownExitCount })}; - }}, - {title:intl.get('执行 ID(示例)'),render:(_,r) => r.id ? {r.id.slice(-8)} : '—'}, - ]} /> - - , + help: ( + <> +

+ {intl.get( + '同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。', + )} +

+

+ {intl.get('上次成功安装规则')}{' '} + {systemAudit.confirmedAt + ? new Date(systemAudit.confirmedAt).toLocaleString() + : '—'} + {' · '} + {intl.get( + '按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。', + )} +

+ {(systemAudit.uncertain > 0 || + systemAudit.awaiting > 0 || + systemAudit.switchSlots > 0) && ( +

+ {intl.get( + '等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。', + { + waiting: systemAudit.awaiting, + uncertain: systemAudit.uncertain, + switches: systemAudit.switchSlots, + }, + )} +

+ )} + {(systemAudit.partial || systemAudit.pending) && ( +

{intl.get('部分时段的计划还无法确定,只统计能确认的计划。')}

+ )} + + ), + children: ( + <> +

{intl.get('按计划统计')}

+
+ + + {anomalyMetric( + 'system', + 'missing', + systemAudit.missing, + systemAudit.through, + )} +
+

+ {intl.get('按触发记录统计(共 {count} 条)', { + count: + systemAudit.observed + + systemAudit.duplicates + + systemAudit.unmatched, + })} +

+
+ + {anomalyMetric( + 'system', + 'skipped', + systemAudit.actualSkips, + systemAudit.through, + )} + {anomalyMetric( + 'system', + 'unconfirmed', + systemAudit.actualUnconfirmed, + systemAudit.through, + )} + + +
+
+ {intl.get('查看最近 25 次计划触发')} +
r.task + '/' + r.time} + columns={[ + { + title: intl.get('计划时间'), + render: (_, r) => new Date(r.time).toLocaleTimeString(), + }, + { + title: intl.get('任务'), + render: (_, r) => r.name || '#' + r.task, + }, + { + title: intl.get('匹配的触发记录'), + dataIndex: 'triggerCount', + render: (count) => count ?? '—', + }, + { + title: intl.get('执行情况'), + render: (_, row) => { + const { + triggerCount = 0, + startCount = 0, + skipCount = 0, + unknownExitCount = 0, + } = row; + const unconfirmed = triggerCount - startCount - skipCount; + const status = + triggerCount > 1 + ? [ + startCount > 0 && + intl.get('启动 {count} 次', { + count: startCount, + }), + skipCount > 0 && + intl.get('跳过 {count} 次', { count: skipCount }), + unconfirmed > 0 && + intl.get('启动未确认 {count} 次', { + count: unconfirmed, + }), + ] + .filter(Boolean) + .join(' · ') + : intl.get( + ( + { + started: '命令已启动', + skipped: '已跳过', + unconfirmed: '启动未确认', + missing: '未收到触发记录', + switch: '生效规则不确定', + uncertain: '触发分钟不确定', + awaiting: '等待触发记录', + } as Record + )[row.status], + ); + if (!unknownExitCount) return status; + return ( + <> + {status} ·{' '} + {triggerCount === 1 + ? intl.get('结果未知') + : intl.get('其中 {count} 次执行结果未知', { + count: unknownExitCount, + })} + + ); + }, + }, + { + title: intl.get('执行 ID(示例)'), + render: (_, r) => + r.id ? {r.id.slice(-8)} : '—', + }, + ]} + /> + + + ), }); } - const activeSource = sources.find(source => source.key === selectedSource) - ?? sources.find(source => source.key === (audit?.expected || audit?.partial ? 'panel' : 'system')) - ?? sources[0]; + const activeSource = + sources.find((source) => source.key === selectedSource) ?? + sources.find( + (source) => + source.key === (audit?.expected || audit?.partial ? 'panel' : 'system'), + ) ?? + sources[0]; return ( { > - } /> - - - } /> - - - } /> - {!!overview?.todayStopped && {intl.get('已停止')} {overview.todayStopped}} + + } + /> - + + } + /> + - + } + /> + {!!overview?.todayStopped && ( + + {intl.get('已停止')} {overview.todayStopped} + + )} + + + + + + + + + setResult('success')} onKeyDown={(event) => { @@ -452,10 +838,22 @@ const Dashboard = () => { setResult('success'); } }} - >} /> + > + } + /> + - setResult('failure')} onKeyDown={(event) => { @@ -464,50 +862,118 @@ const Dashboard = () => { setResult('failure'); } }} - >} /> + > + } + /> + - } /> + + } + /> + - } /> + + } + /> + - {overviewFailed && overview &&

{intl.get('刷新失败,仍显示上次的数据')}

} - - {intl.get('今日定时调度')} - {activeSource && {activeSource.help}} - > - - {trend.length > 0 ? : } + {trend.length > 0 ? ( + + ) : ( + + )} @@ -522,9 +988,25 @@ const Dashboard = () => { size="small" columns={[ { title: '#', dataIndex: 'rank', width: 40 }, - { title: intl.get('定时任务'), dataIndex: 'name', ellipsis: true }, - { title: intl.get('平均耗时'), dataIndex: 'avgTime', width: 100, render: (v: number) => v ? `${(v / 1000).toFixed(1)}s` : '-' }, - { title: intl.get('最长单次'), dataIndex: 'maxTime', width: 100, render: (v: number) => v ? `${(v / 1000).toFixed(1)}s` : '-' }, + { + title: intl.get('定时任务'), + dataIndex: 'name', + ellipsis: true, + }, + { + title: intl.get('平均耗时'), + dataIndex: 'avgTime', + width: 100, + render: (v: number) => + v ? `${(v / 1000).toFixed(1)}s` : '-', + }, + { + title: intl.get('最长单次'), + dataIndex: 'maxTime', + width: 100, + render: (v: number) => + v ? `${(v / 1000).toFixed(1)}s` : '-', + }, ]} /> @@ -538,10 +1020,25 @@ const Dashboard = () => { size="small" columns={[ { title: '#', dataIndex: 'rank', width: 40 }, - { title: intl.get('定时任务'), dataIndex: 'name', ellipsis: true }, + { + title: intl.get('定时任务'), + dataIndex: 'name', + ellipsis: true, + }, { title: intl.get('次数'), dataIndex: 'runCount', width: 60 }, - { title: intl.get('平均耗时'), dataIndex: 'avgTime', width: 100, render: (v: number) => v ? `${(v / 1000).toFixed(1)}s` : '-' }, - { title: intl.get('成功率'), dataIndex: 'successRate', width: 80, render: (v: string) => `${v}%` }, + { + title: intl.get('平均耗时'), + dataIndex: 'avgTime', + width: 100, + render: (v: number) => + v ? `${(v / 1000).toFixed(1)}s` : '-', + }, + { + title: intl.get('成功率'), + dataIndex: 'successRate', + width: 80, + render: (v: string) => `${v}%`, + }, ]} /> @@ -558,11 +1055,31 @@ const Dashboard = () => { pagination={false} size="small" columns={[ - { title: intl.get('标签'), dataIndex: 'label', width: 150, render: (v: string) => {v} }, + { + title: intl.get('标签'), + dataIndex: 'label', + width: 150, + render: (v: string) => {v}, + }, { title: intl.get('任务数'), dataIndex: 'count', width: 80 }, - { title: intl.get('今日执行'), dataIndex: 'todayRuns', width: 100 }, - { title: intl.get('成功率'), dataIndex: 'successRate', width: 100, render: (v: string) => `${v}%` }, - { title: intl.get('平均耗时'), dataIndex: 'avgTime', width: 120, render: (v: number) => v ? `${(v / 1000).toFixed(1)}s` : '-' }, + { + title: intl.get('今日执行'), + dataIndex: 'todayRuns', + width: 100, + }, + { + title: intl.get('成功率'), + dataIndex: 'successRate', + width: 100, + render: (v: string) => `${v}%`, + }, + { + title: intl.get('平均耗时'), + dataIndex: 'avgTime', + width: 120, + render: (v: number) => + v ? `${(v / 1000).toFixed(1)}s` : '-', + }, ]} /> @@ -577,32 +1094,106 @@ const Dashboard = () => { size="small" extra={ <> - {intl.get('运行中')} {runtime?.runningCount || 0} - {intl.get('排队中 {runs} 次,涉及 {tasks} 个任务', { runs: runtime?.queuedCount || 0, tasks: runtime?.queuedTasks || 0 })} + + {intl.get('运行中')} {runtime?.runningCount || 0} + + + {intl.get('排队中 {runs} 次,涉及 {tasks} 个任务', { + runs: runtime?.queuedCount || 0, + tasks: runtime?.queuedTasks || 0, + })} + } > - {!!runtime?.oldestQueued?.length &&
{intl.get('查看排队原因')} - {runtime.oldestQueued.map(row =>
- {row.name}{' · '}{intl.get('已排队')} {formatSeconds(Math.max(0, Math.floor((Date.now()-row.queued_at)/1000)))} - {row.queue_live_context ? : row.queue_context ? :

{intl.get('正在排队,尚无同时运行的任务记录')}

} -
)} - {runtime.queuedCount > runtime.oldestQueued.length && intl.get('仅显示等待最久的 25 个实例')} -
} + {!!runtime?.oldestQueued?.length && ( +
+ {intl.get('查看排队原因')} + {runtime.oldestQueued.map((row) => ( +
+ {row.name} + {' · '} + {intl.get('已排队')}{' '} + {formatSeconds( + Math.max( + 0, + Math.floor((Date.now() - row.queued_at) / 1000), + ), + )} + {row.queue_live_context ? ( + + ) : row.queue_context ? ( + + ) : ( +

{intl.get('正在排队,尚无同时运行的任务记录')}

+ )} +
+ ))} + {runtime.queuedCount > runtime.oldestQueued.length && + intl.get('仅显示等待最久的 25 个实例')} +
+ )}
5 ? runtimePagination : false} + pagination={ + runtime && runtime.running.length > 5 + ? runtimePagination + : false + } size="small" - locale={{ emptyText: }} + locale={{ + emptyText: , + }} columns={[ - { title: intl.get('定时任务'), dataIndex: 'name', ellipsis: true, render: (name: string, record) => { - const sameTaskCount = (runtime?.running || []).filter(r => r.id === record.id).length; - return sameTaskCount > 1 ? {name} ×{sameTaskCount} : name; - } }, + { + title: intl.get('定时任务'), + dataIndex: 'name', + ellipsis: true, + render: (name: string, record) => { + const sameTaskCount = (runtime?.running || []).filter( + (r) => r.id === record.id, + ).length; + return sameTaskCount > 1 ? ( + + {name}{' '} + + ×{sameTaskCount} + + + ) : ( + name + ); + }, + }, { title: 'PID', dataIndex: 'pid', width: 80 }, - { title: intl.get('已运行'), dataIndex: 'elapsed', width: 100, render: (v: number) => v ? formatSeconds(v) : '-' }, - { title: intl.get('日志'), dataIndex: 'id', width: 60, render: (id, record) => { setLogCron({ id, instanceId: record.instanceId, name: record.name }); }}>{intl.get('查看')} }, + { + title: intl.get('已运行'), + dataIndex: 'elapsed', + width: 100, + render: (v: number) => (v ? formatSeconds(v) : '-'), + }, + { + title: intl.get('日志'), + dataIndex: 'id', + width: 60, + render: (id, record) => ( + { + setLogCron({ + id, + instanceId: record.instanceId, + name: record.name, + }); + }} + > + {intl.get('查看')} + + ), + }, ]} /> {runtime?.idleTasks && runtime.idleTasks.length > 0 && ( @@ -618,7 +1209,13 @@ const Dashboard = () => { showHeader={false} columns={[ { dataIndex: 'name', ellipsis: true }, - { dataIndex: 'lastRun', width: 110, render: (v: string) => {v} }, + { + dataIndex: 'lastRun', + width: 110, + render: (v: string) => ( + {v} + ), + }, ]} /> @@ -647,13 +1244,29 @@ const Dashboard = () => { /> - - + +
- {intl.get('负载 1m')}: {system.loadAvg?.[0] ?? '-'} | CPU: {system.cpus} {intl.get('核心')} | {system.platform} -
{intl.get('可用内存上限')} {(system.memTotal / 1024 ** 3).toFixed(2)} GiB - {(system.hostCpus !== system.cpus || system.hostMemory !== system.memTotal) && - <> · {intl.get('宿主机资源')} {system.hostCpus} CPU / {(system.hostMemory / 1024 ** 3).toFixed(2)} GiB} + {intl.get('负载 1m')}: {system.loadAvg?.[0] ?? '-'} | CPU:{' '} + {system.cpus} {intl.get('核心')} | {system.platform} +
+ {intl.get('可用内存上限')}{' '} + {(system.memTotal / 1024 ** 3).toFixed(2)} GiB + {(system.hostCpus !== system.cpus || + system.hostMemory !== system.memTotal) && ( + <> + {' '} + · {intl.get('宿主机资源')} {system.hostCpus} CPU /{' '} + {(system.hostMemory / 1024 ** 3).toFixed(2)} GiB + + )}
@@ -661,18 +1274,40 @@ const Dashboard = () => { - {result && setResult(null)} />} - {anomaly && { - if (anomalySession.current === anomaly) - setLogCron({ id, trigger, name, anomalySession: anomaly.session }); - }} />} + {result && ( + setResult(null)} + /> + )} + {anomaly && ( + { + if (anomalySession.current === anomaly) + setLogCron({ + id, + trigger, + name, + anomalySession: anomaly.session, + }); + }} + /> + )} {logCron && ( ; + rows: Row[]; + page: number; + total: number; + pageSize: number; + revision: string; + changed: boolean; + zone: string; } -interface Result { summary: NonNullable; rows: Row[]; page: number; total: number; pageSize: number; revision: string; changed: boolean; zone: string } -export function AnomalyMetric({ kind, count, open }: { - kind: AnomalySelection['kind']; count?: number; open: () => void; +export function AnomalyMetric({ + kind, + count, + open, +}: { + kind: AnomalySelection['kind']; + count?: number; + open: () => void; }) { - return
-
{intl.get(titles[kind])}
-
- {count != null && count > 0 ? : count ?? '—'} + return ( +
+
{intl.get(titles[kind])}
+
+ {count != null && count > 0 ? ( + + ) : ( + count ?? '—' + )} +
-
; + ); } const reasons: Record = { - pending: '上一次定时触发仍在排队或运行', overlap: '上一次执行仍在运行', changed: '任务已变更或取消', - queue_timeout: '超过排队时限', capacity: '该任务的待执行次数已达上限', restart: '服务重启', - spawn: '启动或执行失败', cancelled: '已取消', + pending: '上一次定时触发仍在排队或运行', + overlap: '上一次执行仍在运行', + changed: '任务已变更或取消', + queue_timeout: '超过排队时限', + capacity: '该任务的待执行次数已达上限', + restart: '服务重启', + spawn: '启动或执行失败', + cancelled: '已取消', }; function explanation(kind: AnomalySelection['kind'], row: Row) { - if (kind === 'missing') return intl.get(row.source === 'system' - ? '规则已生效,计划过了一分钟仍无匹配的系统触发记录。' : '规则已生效,统计时未找到本轮计划的触发记录。'); - const reason = row.reason && (reasons[row.reason] ? intl.get(reasons[row.reason]) : row.reason); - if (kind === 'skipped') return reason || intl.get('已记录跳过,未提供具体原因。'); - return [intl.get('已收到触发,缺少可核实命令已启动的记录。'), reason].filter(Boolean).join(' '); + if (kind === 'missing') + return intl.get( + row.source === 'system' + ? '规则已生效,计划过了一分钟仍无匹配的系统触发记录。' + : '规则已生效,统计时未找到本轮计划的触发记录。', + ); + const reason = + row.reason && + (reasons[row.reason] ? intl.get(reasons[row.reason]) : row.reason); + if (kind === 'skipped') + return reason || intl.get('已记录跳过,未提供具体原因。'); + return [intl.get('已收到触发,缺少可核实命令已启动的记录。'), reason] + .filter(Boolean) + .join(' '); } -export default function ScheduleAnomalies({ selection, close, openLog, onUpdate, onInvalidate }: { - onUpdate: (selection: AnomalySelection, summary: NonNullable) => void; - onInvalidate: (selection: AnomalySelection, reason: 'expired' | 'unavailable') => void; - selection: AnomalySelection; close: () => void; openLog: (id: number, trigger: string, name?: string) => void; +export default function ScheduleAnomalies({ + selection, + close, + openLog, + onUpdate, + onInvalidate, +}: { + onUpdate: ( + selection: AnomalySelection, + summary: NonNullable, + ) => void; + onInvalidate: ( + selection: AnomalySelection, + reason: 'expired' | 'unavailable', + ) => void; + selection: AnomalySelection; + close: () => void; + openLog: (id: number, trigger: string, name?: string) => void; }) { - const [query, setQuery] = useState<{ page: number; revision?: string }>({ page: 1 }); - const [response, setResponse] = useState<{ query: typeof query; result: Result }>(); + const [query, setQuery] = useState<{ page: number; revision?: string }>({ + page: 1, + }); + const [response, setResponse] = useState<{ + query: typeof query; + result: Result; + }>(); const data = response?.query === query ? response.result : undefined; const [failed, setFailed] = useState(false); const [loading, setLoading] = useState(true); @@ -82,17 +156,28 @@ export default function ScheduleAnomalies({ selection, close, openLog, onUpdate, async function refresh() { try { const requestedAt = performance.now(); - const { code, data } = await request.get(config.apiPrefix + 'dashboard/schedule-anomalies', { - params: { kind: selection.kind, source: selection.source, at: selection.at, live: true, ...cursor }, - signal: ctrl.signal, retryInPlace: true, - }); + const { code, data } = await request.get( + config.apiPrefix + 'dashboard/schedule-anomalies', + { + params: { + kind: selection.kind, + source: selection.source, + at: selection.at, + live: true, + ...cursor, + }, + signal: ctrl.signal, + retryInPlace: true, + }, + ); if (ctrl.signal.aborted) return; if (code !== 200) throw new Error(); if (data.status === 'expired' || data.status === 'unavailable') { invalidate(data.status); return; } - const remaining = data.expiresAt - data.serverNow - (performance.now() - requestedAt); + const remaining = + data.expiresAt - data.serverNow - (performance.now() - requestedAt); if (Number.isFinite(remaining)) { if (remaining <= 0) { invalidate('expired'); @@ -113,28 +198,145 @@ export default function ScheduleAnomalies({ selection, close, openLog, onUpdate, } } void refresh(); - return () => { ctrl.abort(); clearTimeout(timer); clearTimeout(deadline); }; + return () => { + ctrl.abort(); + clearTimeout(timer); + clearTimeout(deadline); + }; }, [selection, query, onUpdate, onInvalidate]); - const format = (ms: number) => new Date(ms).toLocaleString(undefined, { timeZone: data?.zone, hour12: false }); - return {intl.get(titles[selection.kind])} · {intl.get(selection.source === 'panel' ? '内置调度' : '系统调度(crond)')}} onCancel={close} footer={null}> -

{intl.get('截至 {time} 的计划,明细随回报更新。', { time: format(selection.at - 5000) })}

- {failed ? {intl.get('加载失败')} } /> : <> - {data && (data.changed || data.total !== selection.count) && } - size="small" loading={loading} dataSource={data?.rows ?? []} scroll={{ x: 660 }} - rowKey={row => row.trigger ?? [row.task, row.time, row.ruleIndex, row.rule].join('/')} - pagination={data && { current: data.page, pageSize: data.pageSize, total: data.total, showSizeChanger: false, - showTotal: total => intl.get('总条数', { total }), onChange: page => setQuery({ page, revision: data.revision }) }} - columns={[ - { title: intl.get('任务'), render: (_, r) => <>{r.name || '#' + r.task}
{r.rule} }, - { title: intl.get('计划时间'), render: (_, r) => r.time != null ? format(r.time) : <> - {intl.get('计划时间无法确定')}
{r.observed != null && intl.get('收到于 {time}', {time: format(r.observed)})} }, - { title: intl.get('调度来源'), render: (_, r) => intl.get(r.source === 'system' ? '系统调度(crond)' : r.source === 'recovery' ? '重启补跑' : '内置调度') }, - { title: intl.get('判断原因'), render: (_, r) => explanation(selection.kind, r) }, - { title: intl.get('日志'), render: (_, r) => r.hasLog && r.trigger ? : '—' }, - ]} /> - } -
; + const format = (ms: number) => + new Date(ms).toLocaleString(undefined, { + timeZone: data?.zone, + hour12: false, + }); + return ( + + {intl.get(titles[selection.kind])} ·{' '} + {intl.get( + selection.source === 'panel' ? '内置调度' : '系统调度(crond)', + )} + + } + onCancel={close} + footer={null} + > +

+ {intl.get('截至 {time} 的计划,明细随回报更新。', { + time: format(selection.at - 5000), + })} +

+ {failed ? ( + + {intl.get('加载失败')}{' '} + + + } + /> + ) : ( + <> + {data && (data.changed || data.total !== selection.count) && ( + + )} + + size="small" + loading={loading} + dataSource={data?.rows ?? []} + scroll={{ x: 660 }} + rowKey={(row) => + row.trigger ?? + [row.task, row.time, row.ruleIndex, row.rule].join('/') + } + pagination={ + data && { + current: data.page, + pageSize: data.pageSize, + total: data.total, + showSizeChanger: false, + showTotal: (total) => intl.get('总条数', { total }), + onChange: (page) => setQuery({ page, revision: data.revision }), + } + } + columns={[ + { + title: intl.get('任务'), + render: (_, r) => ( + <> + {r.name || '#' + r.task} +
+ {r.rule} + + ), + }, + { + title: intl.get('计划时间'), + render: (_, r) => + r.time != null ? ( + format(r.time) + ) : ( + <> + {intl.get('计划时间无法确定')} +
+ + {r.observed != null && + intl.get('收到于 {time}', { + time: format(r.observed), + })} + + + ), + }, + { + title: intl.get('调度来源'), + render: (_, r) => + intl.get( + r.source === 'system' + ? '系统调度(crond)' + : r.source === 'recovery' + ? '重启补跑' + : '内置调度', + ), + }, + { + title: intl.get('判断原因'), + render: (_, r) => explanation(selection.kind, r), + }, + { + title: intl.get('日志'), + render: (_, r) => + r.hasLog && r.trigger ? ( + + ) : ( + '—' + ), + }, + ]} + /> + + )} +
+ ); } diff --git a/src/pages/dashboard/taskResultModal.tsx b/src/pages/dashboard/taskResultModal.tsx index 0f57b239..94219068 100644 --- a/src/pages/dashboard/taskResultModal.tsx +++ b/src/pages/dashboard/taskResultModal.tsx @@ -119,7 +119,11 @@ export default function TaskResultModal({ )} {logCron && ( - setLogCron(null)} /> + setLogCron(null)} + /> )} ); diff --git a/src/pages/dashboard/timingStatistic.tsx b/src/pages/dashboard/timingStatistic.tsx index 3b158dbf..e040b2a7 100644 --- a/src/pages/dashboard/timingStatistic.tsx +++ b/src/pages/dashboard/timingStatistic.tsx @@ -12,11 +12,22 @@ export function formatTiming(ms: number | null) { }); } -export default function TimingStatistic({ title, ms }: { +export default function TimingStatistic({ + title, + ms, +}: { title: string; ms: number | null; }) { - return ( - {formatTiming(ms)} - )} />; + return ( + ( + + {formatTiming(ms)} + + )} + /> + ); } diff --git a/src/pages/dependence/logModal.tsx b/src/pages/dependence/logModal.tsx index 66aad46e..63dc5356 100644 --- a/src/pages/dependence/logModal.tsx +++ b/src/pages/dependence/logModal.tsx @@ -98,10 +98,7 @@ const DependenceLogModal = ({ const handleMessage = (payload: any) => { const { message, references, status } = payload; - if ( - !references?.length || - !references.includes(dependence.id) - ) return; + if (!references?.length || !references.includes(dependence.id)) return; if (typeof status === 'number') { setExecuting(status === Status.安装中 || status === Status.删除中); diff --git a/src/pages/dependence/type.ts b/src/pages/dependence/type.ts index 238ca17a..19a8c09a 100644 --- a/src/pages/dependence/type.ts +++ b/src/pages/dependence/type.ts @@ -18,4 +18,4 @@ export enum Status { '删除失败', '队列中', '已取消', -} \ No newline at end of file +} diff --git a/src/pages/diff/index.tsx b/src/pages/diff/index.tsx index 540a759a..be094648 100644 --- a/src/pages/diff/index.tsx +++ b/src/pages/diff/index.tsx @@ -39,7 +39,9 @@ const Diff = () => { const getSample = () => { request - .get(`${config.apiPrefix}configs/detail?path=${encodeURIComponent(origin)}`) + .get( + `${config.apiPrefix}configs/detail?path=${encodeURIComponent(origin)}`, + ) .then(({ code, data }) => { if (code === 200) { setOriginValue(data); diff --git a/src/pages/env/editNameModal.tsx b/src/pages/env/editNameModal.tsx index 9a0fa260..6ef8294e 100644 --- a/src/pages/env/editNameModal.tsx +++ b/src/pages/env/editNameModal.tsx @@ -1,4 +1,4 @@ -import intl from 'react-intl-universal' +import intl from 'react-intl-universal'; import React, { useEffect, useState } from 'react'; import { Modal, message, Input, Form } from 'antd'; import { request } from '@/utils/http'; @@ -55,7 +55,9 @@ const EditNameModal = ({
diff --git a/src/pages/env/index.tsx b/src/pages/env/index.tsx index 52fd152c..2d9ea1e4 100644 --- a/src/pages/env/index.tsx +++ b/src/pages/env/index.tsx @@ -300,7 +300,13 @@ const Env = () => { }), content: ( <> - {intl.get('确认操作对象', { operation: record.status === Status.已禁用 ? intl.get('启用') : intl.get('禁用'), object: 'Env' })}{' '} + {intl.get('确认操作对象', { + operation: + record.status === Status.已禁用 + ? intl.get('启用') + : intl.get('禁用'), + object: 'Env', + })}{' '} { }), content: ( <> - {intl.get('确认操作对象', { operation: record.isPinned === 1 ? intl.get('取消置顶') : intl.get('置顶'), object: 'Env' })}{' '} + {intl.get('确认操作对象', { + operation: + record.isPinned === 1 ? intl.get('取消置顶') : intl.get('置顶'), + object: 'Env', + })}{' '} { const operateEnvs = (operationStatus: number) => { if ( operationStatus === 0 && - value.some((env) => selectedRowIds.includes(env.id) && env.securityBlocked) + value.some( + (env) => selectedRowIds.includes(env.id) && env.securityBlocked, + ) ) { message.error(intl.get('请先修改环境变量名称')); return; @@ -566,7 +578,10 @@ const Env = () => { }), content: ( <> - {intl.get('确认批量操作', { operation: intl.get(OperationName[operationStatus]), object: intl.get('环境变量') })} + {intl.get('确认批量操作', { + operation: intl.get(OperationName[operationStatus]), + object: intl.get('环境变量'), + })} ), onOk() { @@ -762,10 +777,7 @@ const Env = () => { /> )} {isLabelModalVisible && ( - + )} ); diff --git a/src/pages/log/index.tsx b/src/pages/log/index.tsx index 90b5ce7a..fc0ed303 100644 --- a/src/pages/log/index.tsx +++ b/src/pages/log/index.tsx @@ -8,13 +8,7 @@ import { PageContainer } from '@ant-design/pro-layout'; import Editor from '@monaco-editor/react'; import CodeMirror from '@uiw/react-codemirror'; import { useOutletContext } from '@umijs/max'; -import { - Button, - message, - Modal, - Tooltip, - Typography, -} from 'antd'; +import { Button, message, Modal, Tooltip, Typography } from 'antd'; import { saveAs } from 'file-saver'; import prettyBytes from 'pretty-bytes'; import { useEffect, useRef, useState } from 'react'; @@ -41,14 +35,25 @@ const Log = () => { detailRequest.current = controller; setReadFailed(false); request - .get( - `${config.apiPrefix}logs/detail`, { signal: controller.signal, retryInPlace: true, params: { file: node.title, path: node.parent || '', tail: true, limit: 1024 * 1024 } }, - ) + .get(`${config.apiPrefix}logs/detail`, { + signal: controller.signal, + retryInPlace: true, + params: { + file: node.title, + path: node.parent || '', + tail: true, + limit: 1024 * 1024, + }, + }) .then(({ code, data }) => { - if (controller.signal.aborted || selectedKey.current !== node.key) return; + if (controller.signal.aborted || selectedKey.current !== node.key) + return; if (code === 200) setValue(data); else setReadFailed(true); - }).catch(() => { if (!controller.signal.aborted) setReadFailed(true); }); + }) + .catch(() => { + if (!controller.signal.aborted) setReadFailed(true); + }); }; const downloadLog = () => { @@ -113,7 +118,7 @@ const Log = () => { .then(({ code }) => { if (code === 200) { message.success(intl.get('删除成功')); - setRevision(n => n + 1); + setRevision((n) => n + 1); initState(); } }); @@ -134,8 +139,16 @@ const Log = () => { className="ql-container-wrapper log-wrapper" title={ <> - {currentNode?.type === 'file' ? {readableLogName(currentNode.title)} : select} - {currentNode?.type === 'file' && readFailed && } + {currentNode?.type === 'file' ? ( + {readableLogName(currentNode.title)} + ) : ( + select + )} + {currentNode?.type === 'file' && readFailed && ( + + )} {currentNode?.type === 'file' && ( { extra={ isPhone ? [ - onSelect(node.key, node)} />, + onSelect(node.key, node)} + />, ] : [ @@ -184,7 +202,12 @@ const Log = () => { /*// @ts-ignore*/
- onSelect(node.key, node)} /> + onSelect(node.key, node)} + />
{
{intl.get('上次登录状态:')} - {retries > 0 ? intl.get('登录失败次数', { count: retries }) : intl.get('成功')} + {retries > 0 + ? intl.get('登录失败次数', { count: retries }) + : intl.get('成功')}
), diff --git a/src/pages/script/components/UnsupportedFilePreview/index.module.less b/src/pages/script/components/UnsupportedFilePreview/index.module.less index 688e4857..17e46f9f 100644 --- a/src/pages/script/components/UnsupportedFilePreview/index.module.less +++ b/src/pages/script/components/UnsupportedFilePreview/index.module.less @@ -64,4 +64,4 @@ .warningIcon { font-size: 14px; color: #faad14; -} \ No newline at end of file +} diff --git a/src/pages/script/components/UnsupportedFilePreview/index.tsx b/src/pages/script/components/UnsupportedFilePreview/index.tsx index 4cac37ff..95c74f6b 100644 --- a/src/pages/script/components/UnsupportedFilePreview/index.tsx +++ b/src/pages/script/components/UnsupportedFilePreview/index.tsx @@ -17,12 +17,10 @@ const UnsupportedFilePreview: React.FC = ({
-
- {intl.get('当前文件不支持预览')} -
+
{intl.get('当前文件不支持预览')}
- - + - @@ -529,7 +541,10 @@ const Other = ({ autoSize={{ minRows: 3, maxRows: 8 }} placeholder={intl.get('请输入完整的SSH私钥内容')} onChange={(e) => { - setSystemConfig({ ...systemConfig, globalSshKey: e.target.value }); + setSystemConfig({ + ...systemConfig, + globalSshKey: e.target.value, + }); }} /> diff --git a/src/pages/setting/security.tsx b/src/pages/setting/security.tsx index 29b92f00..93806933 100644 --- a/src/pages/setting/security.tsx +++ b/src/pages/setting/security.tsx @@ -97,9 +97,7 @@ const SecuritySettings = ({ user, userChange }: any) => { const onChange = (e) => { if (e.file && e.file.response) { - setAvatar( - `${config.apiPrefix}static/${e.file.response.data}`, - ); + setAvatar(`${config.apiPrefix}static/${e.file.response.data}`); userChange(); } }; diff --git a/src/pages/subscription/index.tsx b/src/pages/subscription/index.tsx index 7edf40c6..7ca0463a 100644 --- a/src/pages/subscription/index.tsx +++ b/src/pages/subscription/index.tsx @@ -121,7 +121,10 @@ const Subscription = () => { render: (text: string, record: any) => { if (record.schedule_type === 'interval') { const { type, value } = record.interval_schedule; - return intl.get('间隔定时规则', { value, unit: intl.get((IntervalSchedule as any)[type]) }); + return intl.get('间隔定时规则', { + value, + unit: intl.get((IntervalSchedule as any)[type]), + }); } return record.schedule; }, @@ -375,7 +378,11 @@ const Subscription = () => { }), content: ( <> - {intl.get('确认操作对象', { operation: record.is_disabled === 1 ? intl.get('启用') : intl.get('禁用'), object: intl.get('定时订阅') })}{' '} + {intl.get('确认操作对象', { + operation: + record.is_disabled === 1 ? intl.get('启用') : intl.get('禁用'), + object: intl.get('定时订阅'), + })}{' '} {record.name} {' '} diff --git a/src/pages/subscription/modal.tsx b/src/pages/subscription/modal.tsx index cf4d8745..2b6bd5b3 100644 --- a/src/pages/subscription/modal.tsx +++ b/src/pages/subscription/modal.tsx @@ -153,7 +153,11 @@ const SubscriptionModal = ({ style={{ width: 'calc(100% - 100px)' }} onChange={numberChange} /> - @@ -213,10 +217,18 @@ const SubscriptionModal = ({ let justClosed = false; for (const ch of text) { if (inDouble) { - if (ch === '"') { inDouble = false; justClosed = true; continue; } + if (ch === '"') { + inDouble = false; + justClosed = true; + continue; + } current += ch; } else if (inSingle) { - if (ch === "'") { inSingle = false; justClosed = true; continue; } + if (ch === "'") { + inSingle = false; + justClosed = true; + continue; + } current += ch; } else if (ch === '"') { inDouble = true; @@ -225,7 +237,11 @@ const SubscriptionModal = ({ inSingle = true; justClosed = false; } else if (ch === ' ' || ch === '\t') { - if (current || justClosed) { args.push(current); current = ''; justClosed = false; } + if (current || justClosed) { + args.push(current); + current = ''; + justClosed = false; + } } else { current += ch; justClosed = false; @@ -250,8 +266,8 @@ const SubscriptionModal = ({ type === 'raw' ? 'file' : url.startsWith('http') - ? 'public-repo' - : 'private-repo'; + ? 'public-repo' + : 'private-repo'; form.setFieldsValue({ type: _type, @@ -412,7 +428,9 @@ const SubscriptionModal = ({ ) { return Promise.resolve(); } else { - return Promise.reject(intl.get('Subscription表达式格式有误')); + return Promise.reject( + intl.get('Subscription表达式格式有误'), + ); } } catch (e) { return Promise.reject(intl.get('Subscription表达式格式有误')); diff --git a/src/utils/init.ts b/src/utils/init.ts index d0170502..37c16699 100644 --- a/src/utils/init.ts +++ b/src/utils/init.ts @@ -10,7 +10,8 @@ export function init(version: string) { }, 'vs/nls': { availableLanguages: { - '*': intl.getInitOptions().currentLocale === 'en' ? 'i-default' : 'zh-cn', + '*': + intl.getInitOptions().currentLocale === 'en' ? 'i-default' : 'zh-cn', }, }, }); diff --git a/src/utils/monaco/index.ts b/src/utils/monaco/index.ts index 6ca2fb39..47d512de 100644 --- a/src/utils/monaco/index.ts +++ b/src/utils/monaco/index.ts @@ -1,11 +1,11 @@ import * as monaco from 'monaco-editor'; interface FileTypeConfig { - extensions?: string[]; // 文件扩展名 - filenames?: string[]; // 完整文件名 - patterns?: RegExp[]; // 文件名正则匹配 - startsWith?: string[]; // 文件名前缀匹配 - endsWith?: string[]; // 文件名后缀匹配 + extensions?: string[]; // 文件扩展名 + filenames?: string[]; // 完整文件名 + patterns?: RegExp[]; // 文件名正则匹配 + startsWith?: string[]; // 文件名前缀匹配 + endsWith?: string[]; // 文件名后缀匹配 } // 文件类型分类配置(只包含特殊文件类型) @@ -19,13 +19,13 @@ const fileTypeConfigs: Record = { // 前端特殊文件 frontend: { extensions: [ - '.json5', // JSON5 - '.vue', // Vue - '.svelte', // Svelte - '.astro', // Astro - '.wxss', // 微信小程序样式 - '.pcss', // PostCSS - '.acss', // 支付宝小程序样式 + '.json5', // JSON5 + '.vue', // Vue + '.svelte', // Svelte + '.astro', // Astro + '.wxss', // 微信小程序样式 + '.pcss', // PostCSS + '.acss', // 支付宝小程序样式 ], patterns: [ /\.env\.(local|development|production|test)$/, @@ -38,28 +38,28 @@ const fileTypeConfigs: Record = { // 小程序相关 miniprogram: { extensions: [ - '.wxml', // 微信小程序 - '.wxs', // 微信小程序 - '.axml', // 支付宝小程序 - '.sjs', // 支付宝小程序 - '.swan', // 百度小程序 - '.ttml', // 字节跳动小程序 - '.ttss', // 字节跳动小程序 - '.wxl', // 微信小程序语言包 - '.qml', // QQ小程序 - '.qss', // QQ小程序 - '.ksml', // 快手小程序 - '.kss', // 快手小程序 + '.wxml', // 微信小程序 + '.wxs', // 微信小程序 + '.axml', // 支付宝小程序 + '.sjs', // 支付宝小程序 + '.swan', // 百度小程序 + '.ttml', // 字节跳动小程序 + '.ttss', // 字节跳动小程序 + '.wxl', // 微信小程序语言包 + '.qml', // QQ小程序 + '.qss', // QQ小程序 + '.ksml', // 快手小程序 + '.kss', // 快手小程序 ], }, // 开发工具相关 devtools: { extensions: [ - '.prisma', // Prisma - '.mdx', // MDX - '.swagger', // Swagger - '.openapi', // OpenAPI + '.prisma', // Prisma + '.mdx', // MDX + '.swagger', // Swagger + '.openapi', // OpenAPI ], }, @@ -90,9 +90,7 @@ const fileTypeConfigs: Record = { '.gcloudignore', '.htaccess', ], - patterns: [ - /^\.env\./, - ], + patterns: [/^\.env\./], }, // CI/CD 配置 @@ -112,28 +110,33 @@ const fileTypeConfigs: Record = { */ export function canPreviewInMonaco(fileName: string): boolean { if (!fileName) return false; - + // 获取 Monaco 支持的语言 const supportedLanguages = monaco.languages.getLanguages(); const ext = fileName.slice(fileName.lastIndexOf('.')).toLowerCase(); const lowercaseFileName = fileName.toLowerCase(); // 检查 Monaco 原生支持 - if (supportedLanguages.some((lang) => - lang.extensions?.includes(ext) || - (lang.filenames?.includes(lowercaseFileName)) - )) { + if ( + supportedLanguages.some( + (lang) => + lang.extensions?.includes(ext) || + lang.filenames?.includes(lowercaseFileName), + ) + ) { return true; } // 检查额外支持的文件类型 - return Object.values(fileTypeConfigs).some(config => { + return Object.values(fileTypeConfigs).some((config) => { return ( - (config.extensions?.includes(ext)) || - (config.filenames?.includes(lowercaseFileName)) || - (config.patterns?.some(pattern => pattern.test(lowercaseFileName))) || - (config.startsWith?.some(prefix => lowercaseFileName.startsWith(prefix))) || - (config.endsWith?.some(suffix => lowercaseFileName.endsWith(suffix))) + config.extensions?.includes(ext) || + config.filenames?.includes(lowercaseFileName) || + config.patterns?.some((pattern) => pattern.test(lowercaseFileName)) || + config.startsWith?.some((prefix) => + lowercaseFileName.startsWith(prefix), + ) || + config.endsWith?.some((suffix) => lowercaseFileName.endsWith(suffix)) ); }); } @@ -145,17 +148,19 @@ export function canPreviewInMonaco(fileName: string): boolean { */ export function getFileCategory(fileName: string): string { if (!fileName) return 'unknown'; - + const lowercaseFileName = fileName.toLowerCase(); const ext = fileName.slice(fileName.lastIndexOf('.')).toLowerCase(); for (const [category, config] of Object.entries(fileTypeConfigs)) { if ( - (config.extensions?.includes(ext)) || - (config.filenames?.includes(lowercaseFileName)) || - (config.patterns?.some(pattern => pattern.test(lowercaseFileName))) || - (config.startsWith?.some(prefix => lowercaseFileName.startsWith(prefix))) || - (config.endsWith?.some(suffix => lowercaseFileName.endsWith(suffix))) + config.extensions?.includes(ext) || + config.filenames?.includes(lowercaseFileName) || + config.patterns?.some((pattern) => pattern.test(lowercaseFileName)) || + config.startsWith?.some((prefix) => + lowercaseFileName.startsWith(prefix), + ) || + config.endsWith?.some((suffix) => lowercaseFileName.endsWith(suffix)) ) { return category; } @@ -163,10 +168,13 @@ export function getFileCategory(fileName: string): string { // 检查 Monaco 原生支持 const supportedLanguages = monaco.languages.getLanguages(); - if (supportedLanguages.some((lang) => - lang.extensions?.includes(ext) || - (lang.filenames?.includes(lowercaseFileName)) - )) { + if ( + supportedLanguages.some( + (lang) => + lang.extensions?.includes(ext) || + lang.filenames?.includes(lowercaseFileName), + ) + ) { return 'monaco-native'; } diff --git a/test/back/advisory-input-security.test.cjs b/test/back/advisory-input-security.test.cjs index 16ae62ef..7e6e8589 100644 --- a/test/back/advisory-input-security.test.cjs +++ b/test/back/advisory-input-security.test.cjs @@ -50,7 +50,11 @@ test('environment API rejects execution controls and legacy rows stay out of tas const legacy = [ { id: 1, name: 'task_before', value: 'touch /tmp/untrusted' }, { id: 2, name: 'NODE_OPTIONS', value: '--require /tmp/untrusted.js' }, - { id: 3, name: 'PREV_NODE_OPTIONS', value: '--import=data:text/javascript,bad' }, + { + id: 3, + name: 'PREV_NODE_OPTIONS', + value: '--import=data:text/javascript,bad', + }, { id: 4, name: 'GIT_SSH_COMMAND', value: 'sh -c bad' }, { id: 5, name: 'PATH', value: '/tmp/untrusted' }, { id: 6, name: 'file_task_before', value: '/tmp/untrusted.sh' }, @@ -72,7 +76,11 @@ test('environment API rejects execution controls and legacy rows stay out of tas typedi: decorators, '../config': { envFile: 'sh', jsEnvFile: 'js', pyEnvFile: 'py' }, '../data/env': { - Env: class { constructor(value) { Object.assign(this, value); } }, + Env: class { + constructor(value) { + Object.assign(this, value); + } + }, EnvModel: { update: async (value, query) => { writes++; @@ -83,7 +91,9 @@ test('environment API rejects execution controls and legacy rows stay out of tas }, '../data': { sequelize: { literal: (value) => value } }, '../shared/utils': { - writeFileWithLock: async (file, value) => { output[file] = value; }, + writeFileWithLock: async (file, value) => { + output[file] = value; + }, }, }).default; const service = new Env({ @@ -91,15 +101,30 @@ test('environment API rejects execution controls and legacy rows stay out of tas warn: (...args) => warnings.push(args), }); service.envs = async () => legacy; - service.insert = async () => { writes++; return []; }; + service.insert = async () => { + writes++; + return []; + }; service.getDb = async () => ({ id: 1, name: 'SAFE_VALUE', value: 'kept' }); - service.updateDb = async () => { writes++; return {}; }; + service.updateDb = async () => { + writes++; + return {}; + }; for (const name of [ - 'task_before', 'PREV_NODE_OPTIONS', 'GIT_SSH_COMMAND', 'work_dir', - 'task_shell_params', 'which_program', 'script_params', 'LOG_DIR', + 'task_before', + 'PREV_NODE_OPTIONS', + 'GIT_SSH_COMMAND', + 'work_dir', + 'task_shell_params', + 'which_program', + 'script_params', + 'LOG_DIR', 'EXPORTED_VARIABLES', - 'begin_timestamp', 'is_macos', 'RandomDelayIgnoredMinutes', 'ID', + 'begin_timestamp', + 'is_macos', + 'RandomDelayIgnoredMinutes', + 'ID', 'BASH_XTRACEFD', ]) { await assert.rejects( @@ -252,11 +277,11 @@ function cronService(config, updates = []) { '../config/util': { fileExist: async (p) => fs.existsSync(p) }, '../config/const': {}, '../schedule/client': {}, - '../shared/pLimit': {}, - '../shared/utils': {}, + '../cron/execution/cronLimit': {}, + '../shared/utils': { fileExist: async (p) => fs.existsSync(p) }, '../shared/i18n': translate, '../shared/logStreamManager': {}, - '../shared/cronSchedule': {}, + '../cron/scheduling/cronSchedule': {}, }).default; return new Cron(logger); } @@ -364,7 +389,7 @@ function systemService(config, overrides = {}) { DependenceStatus: {}, }, '../data/system': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../shared/i18n': { ...translate, setLang() {} }, './notify': {}, diff --git a/test/back/api-fallback.test.cjs b/test/back/api-fallback.test.cjs index 68abd332..86fba3d8 100644 --- a/test/back/api-fallback.test.cjs +++ b/test/back/api-fallback.test.cjs @@ -12,7 +12,7 @@ test('unknown API requests return JSON 404 while env.js and SPA deep links work' fs.writeFileSync(path.join(dir, 'static/dist/index.html'), 'SPA'); const app = express(); load('back/loaders/express.ts', { - '../api': () => express.Router(), + '../api/index': () => express.Router(), './logger': { error() {} }, '../config': { rootPath: dir, diff --git a/test/back/armv6-worker-readiness.test.cjs b/test/back/armv6-worker-readiness.test.cjs index bec541fb..059cb436 100644 --- a/test/back/armv6-worker-readiness.test.cjs +++ b/test/back/armv6-worker-readiness.test.cjs @@ -37,9 +37,9 @@ for (const [arch, armVersion, mode, timeout] of [ ['x64', undefined, 'development', 120000], ['arm64', undefined, 'development', 120000], ]) { - test(`${arch} v${ - armVersion ?? '' - } ${mode ?? 'default'} waits for scheduler readiness before HTTP and job recovery`, async () => { + test(`${arch} v${armVersion ?? ''} ${ + mode ?? 'default' + } waits for scheduler readiness before HTTP and job recovery`, async () => { const cluster = new EventEmitter(); const module = { exports: {} }; const logger = { info() {}, warn() {}, error() {} }; diff --git a/test/back/build-provenance.test.cjs b/test/back/build-provenance.test.cjs index d9005615..67d88d89 100644 --- a/test/back/build-provenance.test.cjs +++ b/test/back/build-provenance.test.cjs @@ -46,12 +46,11 @@ test('release images receive the same-run artifact and verify it before use', () fs.readFileSync('.github/workflows/build-docker-image.yml', 'utf8'), ); assert.equal(workflow.jobs['build-static'].needs, 'validate'); - const upload = workflow.jobs['build-static'].steps.find(step => step.uses?.startsWith('actions/upload-artifact@')); + const upload = workflow.jobs['build-static'].steps.find((step) => + step.uses?.startsWith('actions/upload-artifact@'), + ); assert.equal(upload.with['include-hidden-files'], true); - for (const name of [ - 'build-alpine', - 'build-debian', - ]) { + for (const name of ['build-alpine', 'build-debian']) { const job = workflow.jobs[name]; assert.equal(job.needs, 'build-static'); const download = job.steps.find((step) => diff --git a/test/back/code-scanning-security.test.cjs b/test/back/code-scanning-security.test.cjs index 325398f2..7f4af71a 100644 --- a/test/back/code-scanning-security.test.cjs +++ b/test/back/code-scanning-security.test.cjs @@ -19,7 +19,11 @@ test('config saves share a rate limit across API mounts before writing files', a '../config/const': { SAMPLE_FILES: [] }, '../services/config': {}, '../shared/i18n': { t: (x) => x }, - '../shared/utils': { writeFileWithLock: async () => { writes++; } }, + '../shared/utils': { + writeFileWithLock: async () => { + writes++; + }, + }, typedi: { Container: { get: () => ({}) } }, }).default(router); app.use('/api', router); @@ -30,11 +34,14 @@ test('config saves share a rate limit across API mounts before writing files', a t.after(() => new Promise((resolve) => server.close(resolve))); const base = `http://127.0.0.1:${server.address().port}`; for (let i = 0; i < 601; i++) { - const response = await fetch(`${base}/${i % 2 ? 'api' : 'open'}/configs/save`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name: 'settings.json', content: '{}' }), - }); + const response = await fetch( + `${base}/${i % 2 ? 'api' : 'open'}/configs/save`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: 'settings.json', content: '{}' }), + }, + ); if (i < 600) { assert.equal(response.status, 200); assert.equal((await response.json()).code, 200); @@ -81,7 +88,9 @@ test('Python environment generation escapes backslashes and triple quotes togeth }); test('cron lookup treats regex and shell metacharacters as literal command text', () => { - const { findCronId } = load(path.resolve('back/shared/cronCommand.ts')); + const { findCronId } = load( + path.resolve('back/cron/execution/cronCommand.ts'), + ); const command = 'task file[1].js --value "$(touch ignored)"'; const crontab = `* * * * * real_time=false no_tee=true ID=17 ${command}\n` + diff --git a/test/back/cron-calendar-boundaries.test.cjs b/test/back/cron-calendar-boundaries.test.cjs index 89de9685..3766b811 100644 --- a/test/back/cron-calendar-boundaries.test.cjs +++ b/test/back/cron-calendar-boundaries.test.cjs @@ -1,8 +1,10 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { spawnSync } = require('node:child_process'); -const { createCronJob } = require('../../back/shared/cronScheduler'); -const { isValidCronSchedule } = require('../../back/shared/cronSchedule'); +const { createCronJob } = require('../../back/cron/scheduling/cronScheduler'); +const { + isValidCronSchedule, +} = require('../../back/cron/scheduling/cronSchedule'); const native = require('node-cron'); const fixture = require('../fixtures/cron-calendar-boundaries.json'); diff --git a/test/back/cron-dependencies.test.cjs b/test/back/cron-dependencies.test.cjs new file mode 100644 index 00000000..9c6477a4 --- /dev/null +++ b/test/back/cron-dependencies.test.cjs @@ -0,0 +1,47 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { + runtimeModuleGraph, + moduleCycles, +} = require('../helpers/runtime-module-graph.cjs'); +const graph = runtimeModuleGraph('back'); + +test('cron and shared libraries do not import service implementations or the orphan reporter', () => { + for (const [file, dependencies] of graph) { + if ( + !/^back\/(cron|shared)\//.test(file) || + file === 'back/shared/managedExit.cjs' + ) + continue; + for (const dependency of dependencies) { + assert.ok( + !dependency.startsWith('back/services/'), + file + ' -> ' + dependency, + ); + assert.notEqual(dependency, 'back/shared/managedExit.cjs', file); + if (file.startsWith('back/shared/')) + assert.ok( + !dependency.startsWith('back/cron/'), + file + ' -> ' + dependency, + ); + } + } +}); + +test('runtime imports involving cron, services and shared have no circular dependency', () => { + const cycles = moduleCycles(graph).filter((cycle) => + cycle.some((file) => /^back\/(cron|services|shared)\//.test(file)), + ); + assert.deepEqual(cycles, []); +}); + +test('receipt storage and schema installation do not load the execution coordinator', () => { + assert.deepEqual([...graph.get('back/cron/settlement/exitReceipt.cjs')], []); + assert.deepEqual([...graph.get('back/cron/schema.ts')], []); + assert.ok( + graph.get('back/data/schemaMigrations.ts').has('back/cron/schema.ts'), + ); + assert.ok( + !graph.get('back/data/schemaMigrations.ts').has('back/cron/history.ts'), + ); +}); diff --git a/test/back/cron-first-version.test.cjs b/test/back/cron-first-version.test.cjs index 8f9e901e..e6e9083e 100644 --- a/test/back/cron-first-version.test.cjs +++ b/test/back/cron-first-version.test.cjs @@ -11,17 +11,18 @@ const { installTriggerHistory, slotId, systemOwner, -} = require('../../back/shared/triggerHistory'); -const { upcomingSlots } = require('../../back/shared/cronScheduler'); -const { withNextRun } = require('../../back/shared/cronPreview'); -const { latestMissedSlot } = require('../../back/shared/cronRecovery'); +} = require('../../back/cron/history'); +const { upcomingSlots } = require('../../back/cron/scheduling/cronScheduler'); +const { withNextRun } = require('../../back/cron/queries/cronPreview'); +const { latestMissedSlot } = require('../../back/cron/scheduling/cronRecovery'); const { getTasks } = require('node-cron'); const logger = { info() {}, error() {}, warn() {} }; async function fixture(t, usePanelDatabase = false) { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-triggers-')); const db = usePanelDatabase - ? load('back/data/index.ts', { '../config/index': { dbPath: root } }).sequelize + ? load('back/data/index.ts', { '../config/index': { dbPath: root } }) + .sequelize : new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), @@ -36,12 +37,21 @@ async function fixture(t, usePanelDatabase = false) { load('back/data/runningInstance.ts', { '.': { sequelize: db } }); const stats = load('back/data/cronStats.ts', { '.': { sequelize: db } }); await db.sync(); - await db.transaction(async transaction => { + await db.transaction(async (transaction) => { await installTriggerHistory(db, transaction); - await db.query('CREATE TABLE SchemaMigrations(id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)', { transaction }); - await db.query('INSERT INTO SchemaMigrations VALUES ($id,CURRENT_TIMESTAMP)', { - bind: { id: require('../../back/shared/schemaMigrations').prunedExitMigrationId }, transaction, - }); + await db.query( + 'CREATE TABLE SchemaMigrations(id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)', + { transaction }, + ); + await db.query( + 'INSERT INTO SchemaMigrations VALUES ($id,CURRENT_TIMESTAMP)', + { + bind: { + id: require('../../back/data/schemaMigrations').prunedExitMigrationId, + }, + transaction, + }, + ); }); return { root, db, models, stats, history: new TriggerHistory(db) }; } @@ -75,13 +85,15 @@ test('failed system install is reported for create, update and disable; retry re '../data/cron': models, '../config': { crontabFile: '/test/crontab' }, '../config/util': { isDemoEnv: () => false }, - '../shared/schedulerMutationLock': { withSchedulerMutation: (fn) => fn() }, + '../cron/scheduling/schedulerMutationLock': { + withSchedulerMutation: (fn) => fn(), + }, '../shared/utils': { writeFileWithLock: async (_, value) => { file = value; }, }, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': client, '../data/runningInstance': {}, '../shared/logStreamManager': {}, @@ -102,7 +114,8 @@ test('failed system install is reported for create, update and disable; retry re name: 'backup', command: 'task backup.sh', schedule: '0 8 * * *', - }), (err) => { + }), + (err) => { pendingId = err.cronId; return err.status === 503 && Number.isInteger(pendingId); }, @@ -175,12 +188,8 @@ test('service previews use the registered calendar including midnight, extra rul const cases = require('../fixtures/cron-calendar-boundaries.json').cases; for (const tz of ['UTC', 'Asia/Shanghai']) { // node-cron caches local timezone formatters for the lifetime of its worker. - const script = ` - const {upcomingSlots} = require('./back/shared/cronScheduler'); - for (const {schedule,currentDate,next} of JSON.parse(process.argv[1])) { - require('node:assert/strict').deepEqual(upcomingSlots(schedule, Date.parse(currentDate), next[process.env.TZ].length), - next[process.env.TZ].map(Date.parse), schedule); - }`; + const script = + "\n const {upcomingSlots} = require('./back/cron/scheduling/cronScheduler');\n for (const {schedule,currentDate,next} of JSON.parse(process.argv[1])) {\n require('node:assert/strict').deepEqual(upcomingSlots(schedule, Date.parse(currentDate), next[process.env.TZ].length),\n next[process.env.TZ].map(Date.parse), schedule);\n }"; require('node:child_process').execFileSync( process.execPath, [ @@ -208,23 +217,41 @@ test('service previews use the registered calendar including midnight, extra rul assert.equal(getTasks().size, before); }); -test('anonymous statistics replay before, during and after identified exits cannot count or settle another run', async t => { +test('anonymous statistics replay before, during and after identified exits cannot count or settle another run', async (t) => { const { db, stats, history } = await fixture(t); const router = express.Router(); load('back/api/dashboard.ts', { - '../data/cronStats': stats, '../data/cron': {}, '../data/runningInstance': {}, '../shared/i18n': {}, + '../data/cronStats': stats, + '../data/cron': {}, + '../data/runningInstance': {}, + '../shared/i18n': {}, }).default(router); - const handle = router.stack[0].handle.stack.find(x => x.route?.path === '/record').route.stack[0].handle; + const handle = router.stack[0].handle.stack.find( + (x) => x.route?.path === '/record', + ).route.stack[0].handle; const post = async (id) => { let reply; - await handle({ get: () => undefined, body: { ref_id: 1, code: 0, elapsed: 2, ...(id && { trigger_id: id }) } }, - { send(value) { reply = value; } }); + await handle( + { + get: () => undefined, + body: { ref_id: 1, code: 0, elapsed: 2, ...(id && { trigger_id: id }) }, + }, + { + send(value) { + reply = value; + }, + }, + ); assert.equal(reply.code, 200); return reply; }; - const replay = () => Promise.all(Array.from({length: 6}, () => post())); + const replay = () => Promise.all(Array.from({ length: 6 }, () => post())); await replay(); - const totals = () => db.query('SELECT run_count,success_count,fail_count,total_time FROM CrontabStats', {type: QueryTypes.SELECT}); + const totals = () => + db.query( + 'SELECT run_count,success_count,fail_count,total_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(await totals(), []); await history.shellReport('system-old', 1, true, true, 'old.log', 100); await history.enqueue('next', 1, 'manual', null); @@ -232,12 +259,23 @@ test('anonymous statistics replay before, during and after identified exits cann // Lose the first HTTP response after the server handles it, then retry the same body. await post(); await Promise.all([replay(), post('system-old'), post('system-old')]); - assert.deepEqual(await totals(), [{ run_count: 1, success_count: 1, fail_count: 0, total_time: 2000 }]); - assert.deepEqual((await history.recent(1,0)).map(r => [r.id,r.state]), [['next','running'],['system-old','finished']]); - await Promise.all([replay(), history.complete('next','failed',null,17)]); + assert.deepEqual(await totals(), [ + { run_count: 1, success_count: 1, fail_count: 0, total_time: 2000 }, + ]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.id, r.state]), + [ + ['next', 'running'], + ['system-old', 'finished'], + ], + ); + await Promise.all([replay(), history.complete('next', 'failed', null, 17)]); await replay(); const [row] = await totals(); - assert.deepEqual([row.run_count,row.success_count,row.fail_count], [2,1,1]); + assert.deepEqual( + [row.run_count, row.success_count, row.fail_count], + [2, 1, 1], + ); }); test('a restart distinguishes queued work from uncertain side effects and reclaims only the latest eligible slot', async (t) => { @@ -260,28 +298,45 @@ test('a restart distinguishes queued work from uncertain side effects and reclai assert.equal(latestMissedSlot('@minutely', 120000, 179999), null); }); -test('a wake burst settles every rejected slot without opening receipt transactions or losing a duplicate', async t => { +test('a wake burst settles every rejected slot without opening receipt transactions or losing a duplicate', async (t) => { const { db, models, history, root } = await fixture(t, true); const marker = path.join(root, 'launches'); - await models.CrontabModel.create({ id: 1, status: 1, allow_multiple_instances: 1 }); - const limit = load('back/shared/pLimit.ts', { - '../data/system': { SystemModel: { sync: async () => {}, findOne: async () => null }, AuthDataType: {} }, - '../loaders/logger': logger, '../services/notify': class {}, - '../config': {}, '../config/grpcCerts': {}, '../protos/api': {}, + await models.CrontabModel.create({ + id: 1, + status: 1, + allow_multiple_instances: 1, + }); + const limit = load('back/cron/execution/cronLimit.ts', { + '../../data/system': { + SystemModel: { sync: async () => {}, findOne: async () => null }, + AuthDataType: {}, + }, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../config': {}, + '../../config/grpcCerts': {}, + '../../protos/api': {}, }).default; limit.cronLimit.pause(); limit._client = { systemNotify() {} }; t.after(() => limit.cronLimit.start()); - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': limit, '../data/cron': models, '../loaders/logger': logger, - './triggerHistory': { triggerHistory: () => history }, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': limit, + '../../data/cron': models, + '../../loaders/logger': logger, + '../history': { triggerHistory: () => history }, }); - const rows = () => db.query('SELECT * FROM CronTriggers', { type: QueryTypes.SELECT }); + const rows = () => + db.query('SELECT * FROM CronTriggers', { type: QueryTypes.SELECT }); const transaction = t.mock.method(db, 'transaction'); - const now = Date.now(), total = 120; - const fire = i => runCron('echo ran >> ' + marker, { id: '1' }, () => true, { - id: 'wake-' + i, time: now - (total - i) * 60000, source: 'node', - }); + const now = Date.now(), + total = 120; + const fire = (i) => + runCron('echo ran >> ' + marker, { id: '1' }, () => true, { + id: 'wake-' + i, + time: now - (total - i) * 60000, + source: 'node', + }); const burst = Array.from({ length: total }, (_, i) => fire(i)); const duplicates = Array.from({ length: total }, (_, i) => fire(i)); try { @@ -289,54 +344,71 @@ test('a wake burst settles every rejected slot without opening receipt transacti await Promise.all([...burst.slice(5), ...duplicates]); const before = await rows(); assert.equal(before.length, total); - assert.equal(before.filter(r => r.state === 'queued').length, 5); - assert.equal(before.filter(r => r.state === 'skipped' && r.reason === 'capacity' && - r.started_at === null && r.finished_at >= r.queued_at).length, total - 5); + assert.equal(before.filter((r) => r.state === 'queued').length, 5); + assert.equal( + before.filter( + (r) => + r.state === 'skipped' && + r.reason === 'capacity' && + r.started_at === null && + r.finished_at >= r.queued_at, + ).length, + total - 5, + ); assert.equal(transaction.mock.callCount(), 0); } finally { limit.cronLimit.start(); await Promise.all(burst); } const final = await rows(); - assert.equal(final.filter(r => r.state === 'finished' && r.exit_code === 0).length, 5); - assert.equal(final.filter(r => r.state === 'queued' || r.state === 'running').length, 0); - assert.equal((await fs.readFile(marker, 'utf8')).trim().split('\n').length, 5); + assert.equal( + final.filter((r) => r.state === 'finished' && r.exit_code === 0).length, + 5, + ); + assert.equal( + final.filter((r) => r.state === 'queued' || r.state === 'running').length, + 0, + ); + assert.equal( + (await fs.readFile(marker, 'utf8')).trim().split('\n').length, + 5, + ); await history.skipQueued('wake-0', 'capacity', now); - assert.equal((await rows()).find(r => r.id === 'wake-0').state, 'finished'); + assert.equal((await rows()).find((r) => r.id === 'wake-0').state, 'finished'); }); test('real scheduled admission records overlap, backlog and expiry, without launching rejected scripts', async (t) => { const { history, models } = await fixture(t); const notices = []; const spawned = []; - const limit = load('back/shared/pLimit.ts', { - '../data/system': { + const limit = load('back/cron/execution/cronLimit.ts', { + '../../data/system': { SystemModel: { sync: async () => {}, findOne: async () => null }, AuthDataType: {}, }, - '../loaders/logger': logger, - '../services/notify': class {}, - '../config': {}, - '../config/grpcCerts': {}, - '../protos/api': {}, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../config': {}, + '../../config/grpcCerts': {}, + '../../protos/api': {}, }).default; const queue = limit.cronLimit; queue.concurrency = 1; queue.pause(); limit._client = { systemNotify: (msg) => notices.push(msg) }; - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': limit, - '../data/cron': models, - '../data/runningInstance': {}, - '../loaders/logger': logger, - './triggerHistory': { triggerHistory: () => history }, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': limit, + '../../data/cron': models, + '../../data/runningInstance': {}, + '../../loaders/logger': logger, + '../history': { triggerHistory: () => history }, './cronCommandProcess': { spawnCronCommand: (cmd, triggerId) => { spawned.push(triggerId); return {}; }, }, - './childProcess': { + '../../shared/childProcess': { observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }), }, }); @@ -385,9 +457,16 @@ test('real scheduled admission records overlap, backlog and expiry, without laun ); await waiting; assert.equal(queue.size, 0); - const fresh = runCron('test', { ...rule, skip_if_pending: true, max_queue_wait: 2 }, () => true, { - time: 8000, id: 'ok', source: 'node', - }); + const fresh = runCron( + 'test', + { ...rule, skip_if_pending: true, max_queue_wait: 2 }, + () => true, + { + time: 8000, + id: 'ok', + source: 'node', + }, + ); await until(() => queue.size === 1); queue.start(); await fresh; @@ -436,25 +515,26 @@ test('restoring a protobuf snapshot launches one real process for the latest mis await history.enqueue(id, 1, 'node', at); await history.interrupt(process.env.SERVICE_TYPE || 'http'); const marker = path.join(root, 'observed'); - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': { runWithCronLimit: (_, fn) => fn(), removeQueuedCron() {} }, - './triggerHistory': { triggerHistory: () => history }, - '../data/cron': models, - '../data/runningInstance': {}, - '../loaders/logger': logger, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': { runWithCronLimit: (_, fn) => fn(), removeQueuedCron() {} }, + '../history': { triggerHistory: () => history }, + '../../data/cron': models, + '../../data/runningInstance': {}, + '../../loaders/logger': logger, }); const seen = []; const stacks = new Map(); const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/runCron': { + '../cron/execution/runCron': { runCron: (...args) => { seen.push(runCron(...args)); return seen.at(-1); }, }, '../loaders/logger': logger, - '../shared/cronScheduler': { + '../cron/scheduling/cronScheduler': { + ...require('../../back/cron/scheduling/cronScheduler'), createCronJob: () => ({ start() {}, cancel() {} }), }, }); @@ -571,43 +651,84 @@ test('retention preview and deletion agree, protecting recent, queued and runnin test('single-instance starts contend per task across connections and only the winner runs', async (t) => { const { db, history, root, models } = await fixture(t); - const peer = new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), logging: false }); + const peer = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + }); t.after(() => peer.close()); const manual = new TriggerHistory(peer); await models.CrontabModel.create({ id: 1, command: 'true', isDisabled: 0 }); - await Promise.all([history.enqueue('main', 1, 'node', 10), manual.enqueue('extra', 1, 'node', 10), - manual.enqueue('manual', 1, 'manual', null)]); + await Promise.all([ + history.enqueue('main', 1, 'node', 10), + manual.enqueue('extra', 1, 'node', 10), + manual.enqueue('manual', 1, 'manual', null), + ]); const ids = ['main', 'extra', 'manual']; - const claims = await Promise.all([history.start(ids[0]), manual.start(ids[1]), manual.start(ids[2])]); + const claims = await Promise.all([ + history.start(ids[0]), + manual.start(ids[1]), + manual.start(ids[2]), + ]); assert.equal(claims.filter(Boolean).length, 1); const winner = ids[claims.indexOf(true)]; - assert.equal(await history.startSystem('system-denied', 1, 'test-owner'), false); - assert.equal((await history.recent(1, 0)).find(r => r.id === 'system-denied').reason, 'overlap'); + assert.equal( + await history.startSystem('system-denied', 1, 'test-owner'), + false, + ); + assert.equal( + (await history.recent(1, 0)).find((r) => r.id === 'system-denied').reason, + 'overlap', + ); await history.complete(winner, 'finished', null, 0); assert.equal(await history.startSystem('system-next', 1, 'test-owner'), true); const loser = ids[claims.indexOf(false)]; assert.equal(await manual.start(loser), false); assert.equal(await manual.start(loser, Date.now(), true), true); - assert.equal((await db.query("SELECT id FROM CronTriggers WHERE state='running'", { type: QueryTypes.SELECT })).length, 2); + assert.equal( + ( + await db.query("SELECT id FROM CronTriggers WHERE state='running'", { + type: QueryTypes.SELECT, + }) + ).length, + 2, + ); }); test('parent settlement and independently lost, late or duplicate shell receipts count each failure once', async (t) => { const { db, history } = await fixture(t); - const { recordCronResult } = require('../../back/shared/cronStatistics'); - for (const [index, [status, stat]] of [[false,false],[false,true],[true,false],[true,true]].entries()) { + const { + recordCronResult, + } = require('../../back/cron/settlement/cronStatistics'); + for (const [index, [status, stat]] of [ + [false, false], + [false, true], + [true, false], + [true, true], + ].entries()) { const id = 'run-' + index; await history.enqueue(id, 1, 'node', 1000); await history.start(id); - const statusReport = () => history.shellReport(id, 1, false, false, 'script.log', 0, 17); + const statusReport = () => + history.shellReport(id, 1, false, false, 'script.log', 0, 17); const record = () => recordCronResult(db, 1, 17, 1000, Date.now(), id); if (status) await statusReport(); if (stat) await record(); await history.complete(id, 'failed', null, 17); - await Promise.all([statusReport(),record(),history.complete(id, 'failed', null, 17)]); + await Promise.all([ + statusReport(), + record(), + history.complete(id, 'failed', null, 17), + ]); } - assert.deepEqual((await history.recent(1, 0)).map(r => [r.state, r.exit_code]), - Array.from({ length: 4 }, () => ['failed', 17])); - const [row] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.state, r.exit_code]), + Array.from({ length: 4 }, () => ['failed', 17]), + ); + const [row] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(row, { run_count: 4, success_count: 0, fail_count: 4 }); }); @@ -615,18 +736,28 @@ test('online reconciliation preserves pending callbacks only for unchanged rules const stacks = new Map(); const queued = []; const { addCron } = load('back/schedule/addCron.ts', { - './data': { scheduleStacks: stacks }, '../loaders/logger': logger, - '../shared/cronScheduler': { createCronJob: (_, fire) => ({ fire, start() {}, cancel() {} }) }, - '../shared/runCron': { runCron: (_cmd, _item, isCurrent) => queued.push(isCurrent) }, + './data': { scheduleStacks: stacks }, + '../loaders/logger': logger, + '../cron/scheduling/cronScheduler': { + createCronJob: (_, fire) => ({ fire, start() {}, cancel() {} }), + }, + '../cron/execution/runCron': { + runCron: (_cmd, _item, isCurrent) => queued.push(isCurrent), + }, }); const item = { id: 'b', schedule: '* * * * * *', command: 'old' }; - const apply = (crons) => addCron({ request: { replace: true, crons } }, err => assert.ifError(err)); + const apply = (crons) => + addCron({ request: { replace: true, crons } }, (err) => + assert.ifError(err), + ); apply([item]); await stacks.get('b')[0].fire(new Date()); - apply([ { ...item, id: 'unrelated' }, { ...item } ]); + apply([{ ...item, id: 'unrelated' }, { ...item }]); apply([item]); const original = stacks.get('b'); - addCron({ request: { replace: false, crons: [{...item}] } }, err => assert.ifError(err)); + addCron({ request: { replace: false, crons: [{ ...item }] } }, (err) => + assert.ifError(err), + ); assert.equal(stacks.get('b'), original); assert.equal(queued[0](), true); apply([{ ...item, command: 'new' }]); @@ -639,97 +770,166 @@ test('online reconciliation preserves pending callbacks only for unchanged rules test('a live crond wrapper keeps its claim across HTTP restart, and a dead owner releases it for Node', async (t) => { const { db, history, models } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', isDisabled: 0 }); - assert.equal(await history.startSystem('system-live', 1, systemOwner(process.pid)), true); + assert.equal( + await history.startSystem('system-live', 1, systemOwner(process.pid)), + true, + ); await history.interrupt('http'); await history.enqueue('next', 1, 'node', Date.now()); assert.equal(await history.start('next'), false); // Simulate PID reuse on this boot. A liveness check for the PID alone would block this run. - await db.query("UPDATE CronTriggers SET owner=owner || '-old' WHERE id='system-live'"); + await db.query( + "UPDATE CronTriggers SET owner=owner || '-old' WHERE id='system-live'", + ); assert.equal(await history.start('next'), true); - const previous = (await history.recent(1, 0)).find(row => row.id === 'system-live'); - assert.deepEqual([previous.state, previous.reason, previous.exit_code], ['unknown', 'restart', null]); + const previous = (await history.recent(1, 0)).find( + (row) => row.id === 'system-live', + ); + assert.deepEqual( + [previous.state, previous.reason, previous.exit_code], + ['unknown', 'restart', null], + ); }); test('manual and system single-instance requests preserve a live legacy process without a receipt', async (t) => { const { models, history } = await fixture(t); const Service = load('back/services/cron.ts', { - '../data/cron': models, '../config': {}, '../shared/pLimit': {}, - '../schedule/client': {}, '../data/runningInstance': {}, '../config/util': {}, - '../shared/logStreamManager': {}, '../loaders/logger': logger, + '../data/cron': models, + '../config': {}, + '../cron/execution/cronLimit': {}, + '../schedule/client': {}, + '../data/runningInstance': {}, + '../config/util': {}, + '../shared/logStreamManager': {}, + '../loaders/logger': logger, }).default; - await models.CrontabModel.create({ id: 1, command: 'true', status: 0, pid: process.pid, - isDisabled: 0, allow_multiple_instances: 0 }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + pid: process.pid, + isDisabled: 0, + allow_multiple_instances: 0, + }); const svc = new Service(logger); let launched = false; - svc.runSingle = async () => { launched = true; }; + svc.runSingle = async () => { + launched = true; + }; await svc.run([1]); assert.equal(launched, false); - assert.equal(await history.startSystem('system-blocked', 1, 'test-owner'), false); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.state, r.reason]), - [['skipped','overlap'],['skipped','overlap']]); + assert.equal( + await history.startSystem('system-blocked', 1, 'test-owner'), + false, + ); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.state, r.reason]), + [ + ['skipped', 'overlap'], + ['skipped', 'overlap'], + ], + ); const row = await models.CrontabModel.findByPk(1); assert.deepEqual([row.status, row.pid], [0, process.pid]); }); test('trigger instances settle once on child close, ignore late starts and retain another live copy', async (t) => { const { db, history, models } = await fixture(t); - await models.CrontabModel.create({ id: 1, command: 'true', status: 1, allow_multiple_instances: 1 }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); for (const id of ['a', 'b']) { await history.enqueue(id, 1, 'node', Date.now()); assert.equal(await history.start(id, Date.now(), true), true); - await history.reportInstance(id, 1, true, process.pid, id+'.log', 100, 0); + await history.reportInstance(id, 1, true, process.pid, id + '.log', 100, 0); } - await history.complete('b','failed',null,17); - await history.reportInstance('b',1,true,process.pid,'b.log',100,0); - assert.equal((await models.CrontabModel.findByPk(1)).status,0); - assert.equal((await models.CrontabModel.findByPk(1)).log_path,'a.log'); - await history.complete('a','finished',null,0); - assert.equal((await models.CrontabModel.findByPk(1)).status,1); - const rows = await db.query('SELECT status,exit_code FROM RunningInstances ORDER BY id', { type: QueryTypes.SELECT }); - assert.deepEqual(rows,[{status:1,exit_code:0},{status:3,exit_code:17}]); + await history.complete('b', 'failed', null, 17); + await history.reportInstance('b', 1, true, process.pid, 'b.log', 100, 0); + assert.equal((await models.CrontabModel.findByPk(1)).status, 0); + assert.equal((await models.CrontabModel.findByPk(1)).log_path, 'a.log'); + await history.complete('a', 'finished', null, 0); + assert.equal((await models.CrontabModel.findByPk(1)).status, 1); + const rows = await db.query( + 'SELECT status,exit_code FROM RunningInstances ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(rows, [ + { status: 1, exit_code: 0 }, + { status: 3, exit_code: 17 }, + ]); }); test('queue cancellation wins against future dispatch, counts requests and leaves future slots eligible', async (t) => { const { history } = await fixture(t); - for (const id of ['first','second']) await history.enqueue(id,1,'node',Date.now()); - assert.deepEqual(await history.queueCounts(),{triggers:2,tasks:1}); - assert.deepEqual((await history.cancelQueued([1])).sort(),['first','second']); - assert.equal(await history.start('first'),false); - assert.deepEqual(await history.queueCounts(),{triggers:0,tasks:0}); - await history.enqueue('next',1,'node',Date.now()); - assert.equal(await history.start('next'),true); - assert.equal(await history.shouldStop('next'),false); + for (const id of ['first', 'second']) + await history.enqueue(id, 1, 'node', Date.now()); + assert.deepEqual(await history.queueCounts(), { triggers: 2, tasks: 1 }); + assert.deepEqual((await history.cancelQueued([1])).sort(), [ + 'first', + 'second', + ]); + assert.equal(await history.start('first'), false); + assert.deepEqual(await history.queueCounts(), { triggers: 0, tasks: 0 }); + await history.enqueue('next', 1, 'node', Date.now()); + assert.equal(await history.start('next'), true); + assert.equal(await history.shouldStop('next'), false); await history.cancelQueued([1]); - assert.equal(await history.shouldStop('next'),true); + assert.equal(await history.shouldStop('next'), true); }); test('script entry percentile covers only scheduled entries that reached the script', async (t) => { const { db, history } = await fixture(t); - for (const [id,source,planned,entry] of [['a','node',100,601],['b','node',200,7000], - ['c','manual',null,500],['d','node',400,null]]) { - await history.enqueue(id,42,source,planned,500); - await db.query('UPDATE CronTriggers SET script_started_at=$entry WHERE id=$id',{bind:{id,entry}}); + for (const [id, source, planned, entry] of [ + ['a', 'node', 100, 601], + ['b', 'node', 200, 7000], + ['c', 'manual', null, 500], + ['d', 'node', 400, null], + ]) { + await history.enqueue(id, 42, source, planned, 500); + await db.query( + 'UPDATE CronTriggers SET script_started_at=$entry WHERE id=$id', + { bind: { id, entry } }, + ); } - const {scriptSamples,scriptStartP95,scriptOnTime,planned} = await history.metrics(0); - assert.deepEqual([scriptSamples,scriptStartP95,scriptOnTime,planned],[2,6800,1,3]); + const { scriptSamples, scriptStartP95, scriptOnTime, planned } = + await history.metrics(0); + assert.deepEqual( + [scriptSamples, scriptStartP95, scriptOnTime, planned], + [2, 6800, 1, 3], + ); }); -test('trigger punctuality uses the time the scheduler saw each dated slot, including skipped slots', async t => { +test('trigger punctuality uses the time the scheduler saw each dated slot, including skipped slots', async (t) => { const { history } = await fixture(t); await history.enqueue('manual', 1, 'manual', null, 12000); const empty = await history.metrics(0); - assert.deepEqual([empty.planned, empty.triggerOnTime, empty.triggerDeviationP95], [0, 0, null]); + assert.deepEqual( + [empty.planned, empty.triggerOnTime, empty.triggerDeviationP95], + [0, 0, null], + ); await history.enqueue('timely', 1, 'node', 10000, 15000); await history.finish('timely', 'skipped', 'overlap', null); await history.enqueue('late', 1, 'recovery', 10000, 15001); await history.enqueue('early', 1, 'node', 20000, 14000); await history.enqueue('previous', 1, 'node', 1000, 1000); const metrics = await history.metrics(10000); - assert.deepEqual([metrics.observed, metrics.planned, metrics.triggerOnTime, metrics.triggerDeviationP95, - metrics.skipped, metrics.scriptSamples], [4, 3, 1, 6000, 1, 0]); + assert.deepEqual( + [ + metrics.observed, + metrics.planned, + metrics.triggerOnTime, + metrics.triggerDeviationP95, + metrics.skipped, + metrics.scriptSamples, + ], + [4, 3, 1, 6000, 1, 0], + ); }); -test('a scheduled sleep contributes its trigger time independently of its three-second execution', async t => { +test('a scheduled sleep contributes its trigger time independently of its three-second execution', async (t) => { const { root, history, models } = await fixture(t); const previous = process.env.QL_DATA_DIR; process.env.QL_DATA_DIR = root; @@ -739,45 +939,86 @@ test('a scheduled sleep contributes its trigger time independently of its three- }); const rule = { id: '1', command: 'sleep 3' }; await models.CrontabModel.create({ id: 1, status: 1, isDisabled: 0 }); - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': { runWithCronLimit: (_, run) => run(), removeQueuedCron() {} }, - './triggerHistory': { triggerHistory: () => history }, - '../data/cron': models, '../data/runningInstance': {}, '../loaders/logger': logger, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': { + runWithCronLimit: (_, run) => run(), + removeQueuedCron() {}, + }, + '../history': { triggerHistory: () => history }, + '../../data/cron': models, + '../../data/runningInstance': {}, + '../../loaders/logger': logger, }); const time = Date.now(); - await runCron(rule.command, rule, () => true, { id: 'timed-sleep', source: 'node', time }); + await runCron(rule.command, rule, () => true, { + id: 'timed-sleep', + source: 'node', + time, + }); const [row] = await history.recent(1, 0); assert.equal(row.exit_code, 0); assert.ok(row.finished_at - row.started_at >= 3000); - assert.ok(row.command_started_at >= row.started_at && row.command_started_at < row.finished_at); + assert.ok( + row.command_started_at >= row.started_at && + row.command_started_at < row.finished_at, + ); assert.ok(row.finished_at - row.command_started_at >= 2900); assert.equal(row.script_started_at, null); const metrics = await history.metrics(time); - assert.deepEqual([metrics.planned, metrics.triggerDeviationP95, metrics.scriptSamples], - [1, row.observed_at - time, 0]); + assert.deepEqual( + [metrics.planned, metrics.triggerDeviationP95, metrics.scriptSamples], + [1, row.observed_at - time, 0], + ); }); test('effective resource limits support nested v2, legacy v1 and absent quotas', () => { - const { containerResources } = require('../../back/shared/containerResources'); - function resources(files) { return containerResources(path => files[path] ?? '', 'linux'); } - const v2=resources({'/proc/self/cgroup':'0::/parent/child','/sys/fs/cgroup/parent/cpu.max':'150000 100000', - '/sys/fs/cgroup/parent/child/memory.max':'1073741824','/sys/fs/cgroup/parent/child/memory.current':'268435456'}); - assert.deepEqual([v2.cpus,v2.memTotal,v2.memFree],[Math.min(1.5,v2.hostCpus),1073741824,805306368]); - const v1=resources({'/proc/self/cgroup':'2:cpu,cpuacct:/\n3:memory:/', - '/sys/fs/cgroup/cpu,cpuacct/cpu.cfs_quota_us':'100000','/sys/fs/cgroup/cpu,cpuacct/cpu.cfs_period_us':'100000', - '/sys/fs/cgroup/memory/memory.limit_in_bytes':'400','/sys/fs/cgroup/memory/memory.usage_in_bytes':'80'}); - assert.deepEqual([v1.cpus,v1.memTotal,v1.memFree],[1,400,320]); - const host=resources({'/proc/self/cgroup':'0::/','/sys/fs/cgroup/memory.max':'max','/sys/fs/cgroup/cpu.max':'max 100000'}); - assert.deepEqual([host.cpus,host.memTotal],[host.hostCpus,host.hostMemory]); + const { + containerResources, + } = require('../../back/shared/containerResources'); + function resources(files) { + return containerResources((path) => files[path] ?? '', 'linux'); + } + const v2 = resources({ + '/proc/self/cgroup': '0::/parent/child', + '/sys/fs/cgroup/parent/cpu.max': '150000 100000', + '/sys/fs/cgroup/parent/child/memory.max': '1073741824', + '/sys/fs/cgroup/parent/child/memory.current': '268435456', + }); + assert.deepEqual( + [v2.cpus, v2.memTotal, v2.memFree], + [Math.min(1.5, v2.hostCpus), 1073741824, 805306368], + ); + const v1 = resources({ + '/proc/self/cgroup': '2:cpu,cpuacct:/\n3:memory:/', + '/sys/fs/cgroup/cpu,cpuacct/cpu.cfs_quota_us': '100000', + '/sys/fs/cgroup/cpu,cpuacct/cpu.cfs_period_us': '100000', + '/sys/fs/cgroup/memory/memory.limit_in_bytes': '400', + '/sys/fs/cgroup/memory/memory.usage_in_bytes': '80', + }); + assert.deepEqual([v1.cpus, v1.memTotal, v1.memFree], [1, 400, 320]); + const host = resources({ + '/proc/self/cgroup': '0::/', + '/sys/fs/cgroup/memory.max': 'max', + '/sys/fs/cgroup/cpu.max': 'max 100000', + }); + assert.deepEqual( + [host.cpus, host.memTotal], + [host.hostCpus, host.hostMemory], + ); }); test('queued scheduled work is actionable in list, detail, pagination and saved filters without changing the scheduler reservation', async (t) => { const { history, models } = await fixture(t); const Service = load('back/services/cron.ts', { - '../data/cron': models, '../config': {}, '../schedule/client': {}, + '../data/cron': models, + '../config': {}, + '../schedule/client': {}, '../config/util': { safeJSONParse: (value) => JSON.parse(value || '{}') }, - '../shared/pLimit': {}, '../shared/logStreamManager': {}, '../shared/utils': {}, - '../data/runningInstance': {}, '../shared/i18n': { t: key => key }, + '../cron/execution/cronLimit': {}, + '../shared/logStreamManager': {}, + '../shared/utils': {}, + '../data/runningInstance': {}, + '../shared/i18n': { t: (key) => key }, }).default; const service = new Service(logger); for (const command of ['task a.sh', 'task b.sh']) { @@ -786,85 +1027,146 @@ test('queued scheduled work is actionable in list, detail, pagination and saved await history.enqueue('waiting', 2, 'node', Date.now()); assert.equal((await service.getDb({ id: 2 })).status, 1); assert.equal((await service.getDb({ id: 2 }, true)).status, 3); - const list = params => service.crontabs({ page: '1', size: '1', ...params }, true); + const list = (params) => + service.crontabs({ page: '1', size: '1', ...params }, true); const queued = await list({ filters: JSON.stringify({ status: [3] }) }); - assert.deepEqual([queued.total, queued.data[0].id, queued.data[0].status], [1, 2, 3]); + assert.deepEqual( + [queued.total, queued.data[0].id, queued.data[0].status], + [1, 2, 3], + ); for (const operation of ['In', 'Nin']) { - const view = await list({ queryString: JSON.stringify({ filters: [{ property: 'status', value: [3], operation }] }) }); - assert.deepEqual([view.total, view.data[0].id], [1, operation === 'In' ? 2 : 1]); + const view = await list({ + queryString: JSON.stringify({ + filters: [{ property: 'status', value: [3], operation }], + }), + }); + assert.deepEqual( + [view.total, view.data[0].id], + [1, operation === 'In' ? 2 : 1], + ); } await history.enqueue('dispatch', 2, 'node', Date.now()); await history.start('dispatch'); assert.equal((await service.getDb({ id: 2 }, true)).status, 0); - assert.equal((await list({ filters: JSON.stringify({ status: [0] }) })).total, 1); + assert.equal( + (await list({ filters: JSON.stringify({ status: [0] }) })).total, + 1, + ); await history.finish('dispatch', 'finished', null, 0); assert.equal((await service.getDb({ id: 2 }, true)).status, 3); await history.cancelQueued([2]); assert.equal((await service.getDb({ id: 2 }, true)).status, 1); - assert.equal((await list({ filters: JSON.stringify({ status: [3] }) })).total, 0); + assert.equal( + (await list({ filters: JSON.stringify({ status: [3] }) })).total, + 0, + ); }); -test('managed child reports cannot finish a compound command or count its first segment', async t => { +test('managed child reports cannot finish a compound command or count its first segment', async (t) => { const { db, history, models } = await fixture(t); - await models.CrontabModel.create({ id: 1, command: 'task first.sh && exit 17', status: 1 }); - const { recordCronResult } = require('../../back/shared/cronStatistics'); - for (const [id, first, final] of [['tail-fails', 0, 17], ['tail-recovers', 7, 0]]) { + await models.CrontabModel.create({ + id: 1, + command: 'task first.sh && exit 17', + status: 1, + }); + const { + recordCronResult, + } = require('../../back/cron/settlement/cronStatistics'); + for (const [id, first, final] of [ + ['tail-fails', 0, 17], + ['tail-recovers', 7, 0], + ]) { await history.enqueue(id, 1, 'manual', null); await history.start(id); await history.bindCommand(id, process.pid); await history.reportInstance(id, 1, true, process.pid, id, 100, 0); await history.reportInstance(id, 1, false, process.pid, id, 100, 1, first); await recordCronResult(db, 1, first, 1000, Date.now(), id); - const [intermediate] = await db.query('SELECT state,counted FROM CronTriggers WHERE id=$id', - { bind: {id}, type: QueryTypes.SELECT }); + const [intermediate] = await db.query( + 'SELECT state,counted FROM CronTriggers WHERE id=$id', + { bind: { id }, type: QueryTypes.SELECT }, + ); assert.deepEqual(intermediate, { state: 'running', counted: 0 }); assert.equal((await models.CrontabModel.findByPk(1)).status, 0); - await history.enqueue(id+'-overlap', 1, 'manual', null); - assert.equal(await history.start(id+'-overlap'), false); + await history.enqueue(id + '-overlap', 1, 'manual', null); + assert.equal(await history.start(id + '-overlap'), false); const state = final ? 'failed' : 'finished'; await history.complete(id, state, null, final); await history.reportInstance(id, 1, false, process.pid, id, 100, 1, first); await history.complete(id, state, null, final); - const [result] = await db.query('SELECT state,exit_code FROM CronTriggers WHERE id=$id', - { bind: {id}, type: QueryTypes.SELECT }); - assert.deepEqual(result,{ state, exit_code: final }); + const [result] = await db.query( + 'SELECT state,exit_code FROM CronTriggers WHERE id=$id', + { bind: { id }, type: QueryTypes.SELECT }, + ); + assert.deepEqual(result, { state, exit_code: final }); } - const [totals] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + const [totals] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(totals, { run_count: 2, success_count: 1, fail_count: 1 }); }); -test('manual multi-instance submissions each claim their own slot, with separate cancellation and edit outcomes', async t => { +test('manual multi-instance submissions each claim their own slot, with separate cancellation and edit outcomes', async (t) => { const { root, db, models, history } = await fixture(t); const queue = []; const marker = path.join(root, 'ran'); - const logs = new (require('../../back/shared/logStreamManager').LogStreamManager)(root); + const logs = + new (require('../../back/shared/logStreamManager').LogStreamManager)(root); const Service = load('back/services/cron.ts', { - '../schedule/client': {}, '../loaders/logger': logger, - '../data/cron': models, '../config': {logPath: root}, - '../data/runningInstance': {RunningInstanceModel: db.models.RunningInstance, InstanceStatus: {running: 0, stopped: 2}}, - '../config/util': {getUniqPath: async () => 'test'}, - '../shared/logStreamManager': {logStreamManager: logs}, - '../shared/pLimit': {manualRunWithCronLimit: fn => { queue.push(fn); }}, - '../shared/i18n': {t: key => key}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../data/cron': models, + '../config': { logPath: root }, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0, stopped: 2 }, + }, + '../config/util': { getUniqPath: async () => 'test' }, + '../shared/logStreamManager': { logStreamManager: logs }, + '../cron/execution/cronLimit': { + manualRunWithCronLimit: (fn) => { + queue.push(fn); + }, + }, + '../shared/i18n': { t: (key) => key }, }).default; const svc = new Service(logger); const command = 'echo ran >> ' + marker; - svc.makeCommand = row => row.command; - await models.CrontabModel.create({ id: 1, command, status: 1, allow_multiple_instances: 1 }); - for (let i=0; i<3; i++) await svc.run([1]); + svc.makeCommand = (row) => row.command; + await models.CrontabModel.create({ + id: 1, + command, + status: 1, + allow_multiple_instances: 1, + }); + for (let i = 0; i < 3; i++) await svc.run([1]); for (const run of queue.splice(0)) await run(); - assert.deepEqual((await history.recent(1,0)).map(r=>r.state), ['finished','finished','finished']); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => r.state), + ['finished', 'finished', 'finished'], + ); await svc.run([1]); await svc.run([1]); await svc.stop([1]); for (const run of queue.splice(0)) await run(); await svc.run([1]); - await models.CrontabModel.update({command: 'exit 99'}, {where:{id:1}}); + await models.CrontabModel.update( + { command: 'exit 99' }, + { where: { id: 1 } }, + ); await queue.shift()(); - const rows = await history.recent(1,0); - assert.equal(rows.filter(r => r.state==='stopped' && r.reason==='cancelled').length, 2); - assert.equal(rows.filter(r => r.state==='skipped' && r.reason==='changed').length, 1); - assert.equal((await fs.readFile(marker,'utf8')).trim(), 'ran\nran\nran'); + const rows = await history.recent(1, 0); + assert.equal( + rows.filter((r) => r.state === 'stopped' && r.reason === 'cancelled') + .length, + 2, + ); + assert.equal( + rows.filter((r) => r.state === 'skipped' && r.reason === 'changed').length, + 1, + ); + assert.equal((await fs.readFile(marker, 'utf8')).trim(), 'ran\nran\nran'); const idle = await svc.getDb({ id: 1 }, true); assert.equal(idle.status, models.CrontabStatus.idle); assert.equal(idle.queued_token, null); @@ -878,41 +1180,72 @@ test('manual multi-instance submissions each claim their own slot, with separate assert.equal(pending.status, models.CrontabStatus.queued); assert.equal(pending.queued_token, replacement.queued_token); await queue.shift()(); - assert.equal((await fs.readFile(marker, 'utf8')).trim().split('\n').length, 4); + assert.equal( + (await fs.readFile(marker, 'utf8')).trim().split('\n').length, + 4, + ); }); -test('both stop routes reject a reused PID and still stop a valid sibling', async t => { +test('both stop routes reject a reused PID and still stop a valid sibling', async (t) => { const { db, models, history } = await fixture(t); - const {spawn} = require('node:child_process'); - const {once} = require('node:events'); - const other = spawn(process.execPath, ['-e','setInterval(()=>{},1000)']); - const sibling = spawn(process.execPath, ['-e','setInterval(()=>{},1000)']); - await Promise.all([once(other,'spawn'),once(sibling,'spawn')]); - t.after(()=>{ other.kill(); sibling.kill(); }); - await models.CrontabModel.create({ id: 1, command: 'task one', status: 1, allow_multiple_instances: 1 }); - for (const [id, pid] of [['stale',other.pid],['sibling',sibling.pid]]) { - await history.enqueue(id,1,'manual',null); - await history.start(id,Date.now(),true); - await history.reportInstance(id,1,true,pid,id,1,0); + const { spawn } = require('node:child_process'); + const { once } = require('node:events'); + const other = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)']); + const sibling = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)']); + await Promise.all([once(other, 'spawn'), once(sibling, 'spawn')]); + t.after(() => { + other.kill(); + sibling.kill(); + }); + await models.CrontabModel.create({ + id: 1, + command: 'task one', + status: 1, + allow_multiple_instances: 1, + }); + for (const [id, pid] of [ + ['stale', other.pid], + ['sibling', sibling.pid], + ]) { + await history.enqueue(id, 1, 'manual', null); + await history.start(id, Date.now(), true); + await history.reportInstance(id, 1, true, pid, id, 1, 0); } - await db.query("UPDATE CronTriggers SET process_identity=process_identity || '-previous' WHERE id='stale'"); - const [row] = await db.query("SELECT instance_id FROM CronTriggers WHERE id='stale'", {type:QueryTypes.SELECT}); + await db.query( + "UPDATE CronTriggers SET process_identity=process_identity || '-previous' WHERE id='stale'", + ); + const [row] = await db.query( + "SELECT instance_id FROM CronTriggers WHERE id='stale'", + { type: QueryTypes.SELECT }, + ); const Service = load('back/services/cron.ts', { - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../config': {}, '../data/cron': models, - '../data/runningInstance': {RunningInstanceModel: db.models.RunningInstance, InstanceStatus:{running:0,stopped:2}}, - '../config/util': {killTask: async (pid, wait, verify) => { verify(); process.kill(pid); }}, - '../shared/pLimit': {}, '../shared/i18n': {t: key=>key}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../config': {}, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0, stopped: 2 }, + }, + '../config/util': { + killTask: async (pid, wait, verify) => { + verify(); + process.kill(pid); + }, + }, + '../cron/execution/cronLimit': {}, + '../shared/i18n': { t: (key) => key }, }).default; const svc = new Service(logger); - assert.equal((await svc.stopInstance(1,row.instance_id)).code,409); - const died = once(sibling,'exit'); - await assert.rejects(svc.stop([1]), e=>e.status===409); + assert.equal((await svc.stopInstance(1, row.instance_id)).code, 409); + const died = once(sibling, 'exit'); + await assert.rejects(svc.stop([1]), (e) => e.status === 409); await died; - assert.doesNotThrow(()=>process.kill(other.pid,0)); + assert.doesNotThrow(() => process.kill(other.pid, 0)); }); -test('scheduled admission survives worker restart and resumes once the old command exits', async t => { +test('scheduled admission survives worker restart and resumes once the old command exits', async (t) => { const { once } = require('node:events'); const { spawn } = require('node:child_process'); const { root, models, history } = await fixture(t); @@ -921,39 +1254,71 @@ test('scheduled admission survives worker restart and resumes once the old comma await once(old, 'spawn'); const ended = once(old, 'exit'); const marker = path.join(root, 'launches'); - const rule = { id: '1', command: 'echo fired >> ' + marker, skip_if_pending: true }; - await models.CrontabModel.create({ id: 1, status: 1, isDisabled: 0, allow_multiple_instances: 1 }); + const rule = { + id: '1', + command: 'echo fired >> ' + marker, + skip_if_pending: true, + }; + await models.CrontabModel.create({ + id: 1, + status: 1, + isDisabled: 0, + allow_multiple_instances: 1, + }); await history.enqueue('prior', 1, 'node', Date.now()); await history.start('prior', Date.now(), true); await history.bindCommand('prior', old.pid); await history.interrupt(process.env.SERVICE_TYPE || 'http'); - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': { runWithCronLimit: (_, run) => run(), removeQueuedCron() {} }, - './triggerHistory': { triggerHistory: () => history }, - '../data/cron': models, '../data/runningInstance': {}, '../loaders/logger': logger, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': { + runWithCronLimit: (_, run) => run(), + removeQueuedCron() {}, + }, + '../history': { triggerHistory: () => history }, + '../../data/cron': models, + '../../data/runningInstance': {}, + '../../loaders/logger': logger, }); - const fire = (id, source) => runCron(rule.command, rule, () => true, { id, source, time: Date.now() }); + const fire = (id, source) => + runCron(rule.command, rule, () => true, { id, source, time: Date.now() }); await fire('during-restart', 'node'); const rows = await history.recent(1, 0); - assert.equal(rows.find(r => r.id === 'prior').state, 'running'); - assert.equal(rows.find(r => r.id === 'during-restart').reason, 'pending'); + assert.equal(rows.find((r) => r.id === 'prior').state, 'running'); + assert.equal(rows.find((r) => r.id === 'during-restart').reason, 'pending'); await assert.rejects(fs.access(marker), { code: 'ENOENT' }); old.kill(); await ended; await fire('resumed', 'recovery'); assert.equal(await fs.readFile(marker, 'utf8'), 'fired\n'); - assert.equal((await history.recent(1, 0)).find(r => r.id === 'resumed').state, 'finished'); + assert.equal( + (await history.recent(1, 0)).find((r) => r.id === 'resumed').state, + 'finished', + ); const now = Date.now(); - const admissions = await Promise.all(['node', 'recovery'].map(source => - history.enqueueUnlessPending(source, 1, source, now, now))); + const admissions = await Promise.all( + ['node', 'recovery'].map((source) => + history.enqueueUnlessPending(source, 1, source, now, now), + ), + ); assert.deepEqual(admissions.sort(), [false, true]); }); function barrier() { let enter, release; - const entered = new Promise(resolve => { enter = resolve; }); - const resume = new Promise(resolve => { release = resolve; }); - return { entered, release, wait() { enter(); return resume; } }; + const entered = new Promise((resolve) => { + enter = resolve; + }); + const resume = new Promise((resolve) => { + release = resolve; + }); + return { + entered, + release, + wait() { + enter(); + return resume; + }, + }; } async function editRaceFixture(t) { @@ -962,34 +1327,85 @@ async function editRaceFixture(t) { const client = { delCron: async () => {}, addCron: async () => {} }; let prepareLogs = async () => {}; const Service = load('back/services/cron.ts', { - '../data/cron': models, '../data/runningInstance': {}, '../loaders/logger': logger, - '../schedule/client': client, '../config': { logPath: root }, - '../config/util': { isDemoEnv: () => false, getUniqPath: async () => 'test' }, - '../shared/schedulerMutationLock': { withSchedulerMutation: fn => fn() }, - '../shared/pLimit': { manualRunWithCronLimit: fn => { queued.push(fn); } }, - '../shared/logStreamManager': { logStreamManager: new (require('../../back/shared/logStreamManager').LogStreamManager)(root) }, - 'fs/promises': { ...fs, mkdir: async (...args) => { await prepareLogs(); return fs.mkdir(...args); } }, + '../data/cron': models, + '../data/runningInstance': {}, + '../loaders/logger': logger, + '../schedule/client': client, + '../config': { logPath: root }, + '../config/util': { + isDemoEnv: () => false, + getUniqPath: async () => 'test', + }, + '../cron/scheduling/schedulerMutationLock': { + withSchedulerMutation: (fn) => fn(), + }, + '../cron/execution/cronLimit': { + manualRunWithCronLimit: (fn) => { + queued.push(fn); + }, + }, + '../shared/logStreamManager': { + logStreamManager: + new (require('../../back/shared/logStreamManager').LogStreamManager)( + root, + ), + }, + 'fs/promises': { + ...fs, + mkdir: async (...args) => { + await prepareLogs(); + return fs.mkdir(...args); + }, + }, }).default; const service = new Service(logger); service.getLogName = async () => 'test'; service.setCrontab = async () => {}; - service.makeCommand = task => task.command; + service.makeCommand = (task) => task.command; Object.defineProperty(service, 'schedulerMode', { value: 'node' }); - return { root, service, client, models, history, queued, setLogBarrier(fn) { prepareLogs = fn; } }; + return { + root, + service, + client, + models, + history, + queued, + setLogBarrier(fn) { + prepareLogs = fn; + }, + }; } for (const rollback of [false, true]) { - test(`configuration ${rollback ? 'rollback' : 'save'} preserves a concurrently finished run`, async t => { - const { service, models, history, client, queued } = await editRaceFixture(t); - const task = await service.create({ name: 'before', command: 'true', schedule: '* * * * *' }); + test(`configuration ${ + rollback ? 'rollback' : 'save' + } preserves a concurrently finished run`, async (t) => { + const { service, models, history, client, queued } = await editRaceFixture( + t, + ); + const task = await service.create({ + name: 'before', + command: 'true', + schedule: '* * * * *', + }); await service.run([task.id]); const gate = barrier(); - service.getLogName = async () => { await gate.wait(); return 'test'; }; - if (rollback) client.addCron = async () => { throw Error('scheduler unavailable'); }; + service.getLogName = async () => { + await gate.wait(); + return 'test'; + }; + if (rollback) + client.addCron = async () => { + throw Error('scheduler unavailable'); + }; const saved = service.update({ id: task.id, name: 'changed' }); const checked = rollback ? assert.rejects(saved) : saved; await gate.entered; - try { await queued.shift()(); } finally { gate.release(); } + try { + await queued.shift()(); + } finally { + gate.release(); + } await checked; const row = await service.getDb({ id: task.id }, true); assert.equal(row.name, rollback ? 'before' : 'changed'); @@ -1003,18 +1419,26 @@ for (const rollback of [false, true]) { } for (const multiple of [0, 1]) { - test(`an edit winning the manual claim suppresses the old command (multiple=${multiple})`, async t => { - const { root, service, history, queued, setLogBarrier } = await editRaceFixture(t); + test(`an edit winning the manual claim suppresses the old command (multiple=${multiple})`, async (t) => { + const { root, service, history, queued, setLogBarrier } = + await editRaceFixture(t); const marker = path.join(root, 'effects'); - const task = await service.create({ name: 'race', command: 'echo old >> ' + marker, - schedule: '@once', allow_multiple_instances: multiple }); + const task = await service.create({ + name: 'race', + command: 'echo old >> ' + marker, + schedule: '@once', + allow_multiple_instances: multiple, + }); await service.run([task.id]); const gate = barrier(); setLogBarrier(() => gate.wait()); const dispatch = queued.shift()(); await gate.entered; - try { await service.update({ id: task.id, command: 'echo new >> ' + marker }); } - finally { gate.release(); } + try { + await service.update({ id: task.id, command: 'echo new >> ' + marker }); + } finally { + gate.release(); + } await dispatch; const [discarded] = await history.recent(task.id, 0); assert.equal(discarded.state, 'skipped'); @@ -1027,19 +1451,25 @@ for (const multiple of [0, 1]) { }); } -test('worker crash before identity commit closes the launch pipe without executing user code', async t => { +test('worker crash before identity commit closes the launch pipe without executing user code', async (t) => { const { root, history, models } = await fixture(t); const { fork } = require('node:child_process'); const { once } = require('node:events'); const workerFile = path.join(root, 'worker.cjs'); const marker = path.join(root, 'old-started'); - await models.CrontabModel.create({ id: 1, status: 1, allow_multiple_instances: 1 }); - await fs.writeFile(workerFile, ` + await models.CrontabModel.create({ + id: 1, + status: 1, + allow_multiple_instances: 1, + }); + await fs.writeFile( + workerFile, + ` const { createRequire } = require('node:module'); const r = createRequire(process.cwd() + '/package.json'); const { Sequelize, Transaction } = r('sequelize'); const load = r('./test/helpers/load-security-module.cjs'); - const { TriggerHistory } = r('./back/shared/triggerHistory'); + const { TriggerHistory } = r('./back/cron/history'); const db = new Sequelize({ dialect: 'sqlite', storage: process.argv[2], logging: false, transactionType: Transaction.TYPES.IMMEDIATE }); const history = new TriggerHistory(db); @@ -1047,18 +1477,20 @@ test('worker crash before identity commit closes the launch pipe without executi process.send(pid); await new Promise(() => {}); }; - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': { runWithCronLimit: (_, fn) => fn(), removeQueuedCron() {} }, - './triggerHistory': { triggerHistory: () => history }, - '../data/cron': load('back/data/cron.ts', { '.': { sequelize: db } }), - '../data/runningInstance': {}, '../loaders/logger': { info() {}, error() {} }, + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': { runWithCronLimit: (_, fn) => fn(), removeQueuedCron() {} }, + "../history": { triggerHistory: () => history }, + "../../data/cron": load('back/data/cron.ts', { '.': { sequelize: db } }), + "../../data/runningInstance": {}, "../../loaders/logger": { info() {}, error() {} }, }); runCron('echo old > "$PROBE"', { id: '1', skip_if_pending: true }, () => true, { id: 'prior', time: Date.now(), source: 'node' }).catch(e => { throw e; }); - `); + `, + ); const worker = fork(workerFile, [path.join(root, 'panel.sqlite')], { execArgv: ['-r', require.resolve('ts-node/register/transpile-only')], - stdio: ['ignore', 'ignore', 'inherit', 'ipc'], env: { ...process.env, PROBE: marker }, + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + env: { ...process.env, PROBE: marker }, }); t.after(() => worker.kill()); const [pid] = await once(worker, 'message'); @@ -1067,20 +1499,39 @@ test('worker crash before identity commit closes the launch pipe without executi worker.kill('SIGKILL'); await exit; await history.interrupt(process.env.SERVICE_TYPE || 'http'); - assert.equal(await history.enqueueUnlessPending('next', 1, 'node', Date.now(), Date.now()), true); + assert.equal( + await history.enqueueUnlessPending( + 'next', + 1, + 'node', + Date.now(), + Date.now(), + ), + true, + ); // Wait for the shell to observe EOF, including on hosts that retain an orphan zombie. const deadline = Date.now() + 3000; for (;;) { - try { systemOwner(pid); } catch { break; } - assert.ok(Date.now() < deadline, 'unreleased shell must exit with its worker'); - await new Promise(resolve => setTimeout(resolve, 15)); + try { + systemOwner(pid); + } catch { + break; + } + assert.ok( + Date.now() < deadline, + 'unreleased shell must exit with its worker', + ); + await new Promise((resolve) => setTimeout(resolve, 15)); } await assert.rejects(fs.access(marker), { code: 'ENOENT' }); }); test('a managed shell sources BASH_ENV once and only after launch authorization', async (t) => { const { once } = require('node:events'); - const { spawnCronCommand, releaseCronCommand } = require('../../back/shared/cronCommandProcess'); + const { + spawnCronCommand, + releaseCronCommand, + } = require('../../back/cron/execution/cronCommandProcess'); const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-shell-gate-')); t.after(() => fs.rm(root, { recursive: true, force: true })); const marker = path.join(root, 'events'); @@ -1094,7 +1545,8 @@ test('a managed shell sources BASH_ENV once and only after launch authorization' process.env.BASH_ENV = profile; return spawnCronCommand(`echo command >> "${marker}"`, 'profile-test'); } finally { - if (data === undefined) delete process.env.QL_DATA_DIR; else process.env.QL_DATA_DIR = data; + if (data === undefined) delete process.env.QL_DATA_DIR; + else process.env.QL_DATA_DIR = data; if (previous === undefined) delete process.env.BASH_ENV; else process.env.BASH_ENV = previous; } @@ -1112,83 +1564,135 @@ test('a managed shell sources BASH_ENV once and only after launch authorization' assert.equal(await fs.readFile(marker, 'utf8'), 'profile\ncommand\n'); }); -test('a rejected same-backend edit never withdraws the timer; failed cross-backend restoration stays pending', async t => { +test('a rejected same-backend edit never withdraws the timer; failed cross-backend restoration stays pending', async (t) => { const { service, models, client } = await editRaceFixture(t); const timers = new Map(); - client.addCron = async rows => rows.forEach(row => timers.set(row.id, row)); - client.delCron = async ids => ids.forEach(id => timers.delete(id)); + client.addCron = async (rows) => + rows.forEach((row) => timers.set(row.id, row)); + client.delCron = async (ids) => ids.forEach((id) => timers.delete(id)); const rule = { command: 'true', schedule: '*/2 * * * * *' }; await service.create({ ...rule, name: 'conflict' }); - const job = await service.create({ ...rule, name: 'original', max_queue_wait: 3 }); + const job = await service.create({ + ...rule, + name: 'original', + max_queue_wait: 3, + }); const old = timers.get(String(job.id)); const save = service.updateDb.bind(service); let uninterrupted = false; - service.updateDb = async row => { + service.updateDb = async (row) => { uninterrupted = timers.get(String(job.id)) === old; return save(row); }; - await assert.rejects(service.update({ id: job.id, name: 'conflict' }), { name: 'SequelizeUniqueConstraintError' }); + await assert.rejects(service.update({ id: job.id, name: 'conflict' }), { + name: 'SequelizeUniqueConstraintError', + }); assert.equal(uninterrupted, true); assert.equal(timers.get(String(job.id)), old); let retry = 0; - client.readiness = { invalidate() { retry++; } }; - client.addCron = async () => { throw Error('unavailable'); }; - service.updateDb = async () => { throw Error('database is unavailable'); }; - await assert.rejects(service.update({ id: job.id, schedule: '@once' }), { status: 503 }); + client.readiness = { + invalidate() { + retry++; + }, + }; + client.addCron = async () => { + throw Error('unavailable'); + }; + service.updateDb = async () => { + throw Error('database is unavailable'); + }; + await assert.rejects(service.update({ id: job.id, schedule: '@once' }), { + status: 503, + }); assert.equal(retry, 1); const row = await models.CrontabModel.findByPk(job.id); assert.equal(row.name, 'original'); assert.equal(row.saved, false); }); -test('disabled edits publish their new command; a stale subscription batch deletes nothing', async t => { +test('disabled edits publish their new command; a stale subscription batch deletes nothing', async (t) => { const { service, models } = await editRaceFixture(t); - const original = { command: 'task node "repo/my file.sh"', schedule: '* * * * *' }; + const original = { + command: 'task node "repo/my file.sh"', + schedule: '* * * * *', + }; const a = await service.create({ ...original, name: 'keep' }); const b = await service.create({ ...original, name: 'other' }); await service.disabled([a.id]); const snapshots = []; - service.setCrontab = async () => snapshots.push((await models.CrontabModel.findByPk(a.id))?.command); - const old = { id: a.id, script: 'repo/my file.sh', revision: a.recovery_from }; - await service.update({ id: a.id, name: 'repurposed', command: original.command }); + service.setCrontab = async () => + snapshots.push((await models.CrontabModel.findByPk(a.id))?.command); + const old = { + id: a.id, + script: 'repo/my file.sh', + revision: a.recovery_from, + }; + await service.update({ + id: a.id, + name: 'repurposed', + command: original.command, + }); assert.deepEqual(snapshots, [original.command]); // Even an edit which keeps the operand invalidates the old snapshot. await assert.rejects(service.remove([b.id, old]), { status: 409 }); await service.update({ id: a.id, command: 'task other.sh' }); assert.equal(snapshots.at(-1), 'task other.sh'); - await assert.rejects(service.remove([b.id, { id: a.id, script: old.script }]), { status: 409 }); + await assert.rejects( + service.remove([b.id, { id: a.id, script: old.script }]), + { status: 409 }, + ); assert.equal(await models.CrontabModel.count(), 2); await service.remove([{ id: a.id, script: 'other.sh' }]); assert.equal(await models.CrontabModel.count(), 1); }); for (const reason of ['changed', 'queue_timeout']) { - test('the last launch gate rejects ' + reason + ' during command identity binding', async t => { - const { root, models, history } = await fixture(t); - await models.CrontabModel.create({ id: 1, status: 1, isDisabled: 0 }); - const rule = { id: '1', max_queue_wait: reason === 'queue_timeout' ? 1 : 0 }; - let current = true; - const bind = history.bindCommand.bind(history); - history.bindCommand = async (...args) => { - assert.equal(await bind(...args), true); - if (reason === 'changed') current = false; - else await new Promise(resolve => setTimeout(resolve, 1010)); - return true; - }; - const { runCron } = load('back/shared/runCron.ts', { - './pLimit': { runWithCronLimit: (_, run) => run(), removeQueuedCron() {} }, - './triggerHistory': { triggerHistory: () => history }, - '../data/cron': models, '../data/runningInstance': {}, '../loaders/logger': logger, - }); - const marker = path.join(root, 'must-not-run'); - await runCron('echo fired > ' + marker, rule, () => current, { id: reason, source: 'node', time: Date.now() }); - const [row] = await history.recent(1, 0); - assert.deepEqual([row.state, row.reason, row.started_at, row.exit_code], ['skipped', reason, null, null]); - await assert.rejects(fs.access(marker), { code: 'ENOENT' }); - }); + test( + 'the last launch gate rejects ' + + reason + + ' during command identity binding', + async (t) => { + const { root, models, history } = await fixture(t); + await models.CrontabModel.create({ id: 1, status: 1, isDisabled: 0 }); + const rule = { + id: '1', + max_queue_wait: reason === 'queue_timeout' ? 1 : 0, + }; + let current = true; + const bind = history.bindCommand.bind(history); + history.bindCommand = async (...args) => { + assert.equal(await bind(...args), true); + if (reason === 'changed') current = false; + else await new Promise((resolve) => setTimeout(resolve, 1010)); + return true; + }; + const { runCron } = load('back/cron/execution/runCron.ts', { + './cronLimit': { + runWithCronLimit: (_, run) => run(), + removeQueuedCron() {}, + }, + '../history': { triggerHistory: () => history }, + '../../data/cron': models, + '../../data/runningInstance': {}, + '../../loaders/logger': logger, + }); + const marker = path.join(root, 'must-not-run'); + await runCron('echo fired > ' + marker, rule, () => current, { + id: reason, + source: 'node', + time: Date.now(), + }); + const [row] = await history.recent(1, 0); + assert.deepEqual( + [row.state, row.reason, row.started_at, row.exit_code], + ['skipped', reason, null, null], + ); + await assert.rejects(fs.access(marker), { code: 'ENOENT' }); + }, + ); } -test('new and legacy log names keep a quoted subscription script executable and preserve its real exit code', async t => { +test('new and legacy log names keep a quoted subscription script executable and preserve its real exit code', async (t) => { const { spawnSync } = require('node:child_process'); const { getUniqPath } = require('../../back/config/util'); const { shellQuote } = require('../../back/shared/shellQuote'); @@ -1200,76 +1704,159 @@ test('new and legacy log names keep a quoted subscription script executable and await fs.mkdir(path.join(root, 'repo')); await fs.writeFile(path.join(root, file), 'echo executed; exit 7'); for (const log_name of [clean, "repo_what'$(touch injected)"]) { - const cmd = Object.getPrototypeOf(service).makeCommand.call(service, { command, id: 99, log_name }); - const result = spawnSync('/bin/bash', ['-c', 'task(){ bash "$1"; }; ' + cmd], { cwd: root, encoding: 'utf8' }); + const cmd = Object.getPrototypeOf(service).makeCommand.call(service, { + command, + id: 99, + log_name, + }); + const result = spawnSync( + '/bin/bash', + ['-c', 'task(){ bash "$1"; }; ' + cmd], + { cwd: root, encoding: 'utf8' }, + ); assert.equal(result.status, 7); assert.equal(result.stdout.trim(), 'executed'); - await assert.rejects(fs.access(path.join(root, 'injected')), { code: 'ENOENT' }); + await assert.rejects(fs.access(path.join(root, 'injected')), { + code: 'ENOENT', + }); } }); -test('trigger history continues from the last visible row even when newer rows arrive or the cursor is pruned', async t => { +test('trigger history continues from the last visible row even when newer rows arrive or the cursor is pruned', async (t) => { const { history, db } = await fixture(t); - for (let n = 0; n < 25; n++) await history.enqueue('slot-' + String(n).padStart(2, '0'), 1, 'manual', null, 100); + for (let n = 0; n < 25; n++) + await history.enqueue( + 'slot-' + String(n).padStart(2, '0'), + 1, + 'manual', + null, + 100, + ); assert.equal((await history.recent(1, 0, 26)).length, 25); await history.enqueue('older', 1, 'manual', null, 99); const first = await history.recent(1, 0, 26); assert.equal(first.length, 26); const last = first[24]; await history.enqueue('newer', 1, 'manual', null, 101); - await db.query('DELETE FROM CronTriggers WHERE id=$id', {bind: {id: last.id}}); - const older = await history.recent(1, 0, 26, { time: last.observed_at, id: last.id }); - assert.deepEqual(older.map(row => row.id), ['older']); + await db.query('DELETE FROM CronTriggers WHERE id=$id', { + bind: { id: last.id }, + }); + const older = await history.recent(1, 0, 26, { + time: last.observed_at, + id: last.id, + }); + assert.deepEqual( + older.map((row) => row.id), + ['older'], + ); assert.equal((await history.recent(1, 0)).length, 25); }); -test('expanded history refreshes visible runs by identity after newer records push them off the first page', async t => { +test('expanded history refreshes visible runs by identity after newer records push them off the first page', async (t) => { const { history } = await fixture(t); await history.enqueue('visible', 1, 'manual', null, 10); await history.start('visible', 11); await history.enqueue('other-task', 2, 'manual', null, 15); - for (let i = 0; i < 26; i++) await history.enqueue('new-' + i, 1, 'manual', null, 20 + i); - assert.ok(!(await history.recent(1, 0)).some(row => row.id === 'visible')); + for (let i = 0; i < 26; i++) + await history.enqueue('new-' + i, 1, 'manual', null, 20 + i); + assert.ok(!(await history.recent(1, 0)).some((row) => row.id === 'visible')); await history.finish('visible', 'finished', null, 0); - const rows = await history.visibleTriggers(1, ['visible', 'other-task', 'pruned']); - assert.deepEqual(rows.map(row => [row.id, row.state, row.exit_code]), [['visible', 'finished', 0]]); + const rows = await history.visibleTriggers(1, [ + 'visible', + 'other-task', + 'pruned', + ]); + assert.deepEqual( + rows.map((row) => [row.id, row.state, row.exit_code]), + [['visible', 'finished', 0]], + ); }); -test('live logs follow the active trigger while queued or awaiting its shell path', async t => { +test('live logs follow the active trigger while queued or awaiting its shell path', async (t) => { const { root, models, history } = await fixture(t); const Service = load('back/services/cron.ts', { - '../data/cron': models, '../data/runningInstance': {}, '../config': { logPath: root }, - '../config/util': { fileExist: async file => (await fs.stat(file)).isFile() }, - '../shared/i18n': { t: text => text }, '../shared/pLimit': {}, '../schedule/client': {}, - '../shared/logStreamManager': {}, '../loaders/logger': logger, + '../data/cron': models, + '../data/runningInstance': {}, + '../config': { logPath: root }, + '../config/util': { + fileExist: async (file) => (await fs.stat(file)).isFile(), + }, + '../shared/i18n': { t: (text) => text }, + '../cron/execution/cronLimit': {}, + '../schedule/client': {}, + '../shared/logStreamManager': {}, + '../loaders/logger': logger, }).default; const service = new Service(logger); await fs.writeFile(path.join(root, 'old.log'), 'finished first run'); - await models.CrontabModel.create({ id: 1, status: 1, log_path: 'old.log', command: 'task sample' }); + await models.CrontabModel.create({ + id: 1, + status: 1, + log_path: 'old.log', + command: 'task sample', + }); assert.equal((await service.log(1)).content, 'finished first run'); await history.enqueue('later', 1, 'node', Date.now()); const queued = await service.log(1); - assert.deepEqual([queued.status, queued.nextOffset, queued.logPath], ['running', 0, undefined]); + assert.deepEqual( + [queued.status, queued.nextOffset, queued.logPath], + ['running', 0, undefined], + ); await history.start('later', Date.now(), false); const starting = await service.log(1); - assert.deepEqual([starting.status, starting.nextOffset, starting.logPath], ['running', 0, undefined]); + assert.deepEqual( + [starting.status, starting.nextOffset, starting.logPath], + ['running', 0, undefined], + ); await fs.writeFile(path.join(root, 'new.log'), 'second run'); - await history.reportInstance('later', 1, true, process.pid, 'new.log', 100, 0); - const live = await service.log(1, { previousPath: 'old.log', offset: 10, follow: true }); - assert.deepEqual([live.logPath, live.content, live.offset], ['new.log', 'second run', 0]); + await history.reportInstance( + 'later', + 1, + true, + process.pid, + 'new.log', + 100, + 0, + ); + const live = await service.log(1, { + previousPath: 'old.log', + offset: 10, + follow: true, + }); + assert.deepEqual( + [live.logPath, live.content, live.offset], + ['new.log', 'second run', 0], + ); }); -test('a concurrent viewer keeps its receipt through sibling starts, interleaved finishes and retention', async t => { +test('a concurrent viewer keeps its receipt through sibling starts, interleaved finishes and retention', async (t) => { const { root, models, history, db } = await fixture(t); const Service = load('back/services/cron.ts', { - '../data/cron': models, '../data/runningInstance': {}, '../config': { logPath: root }, - '../config/util': { fileExist: async file => fs.stat(file).then(() => true, () => false) }, - '../shared/i18n': { t: text => text }, '../shared/pLimit': {}, '../schedule/client': {}, - '../shared/logStreamManager': {}, '../loaders/logger': logger, + '../data/cron': models, + '../data/runningInstance': {}, + '../config': { logPath: root }, + '../config/util': { + fileExist: async (file) => + fs.stat(file).then( + () => true, + () => false, + ), + }, + '../shared/i18n': { t: (text) => text }, + '../cron/execution/cronLimit': {}, + '../schedule/client': {}, + '../shared/logStreamManager': {}, + '../loaders/logger': logger, }).default; const service = new Service(logger); - await models.CrontabModel.create({ id: 1, status: 1, command: 'task sample', allow_multiple_instances: 1 }); - const poll = (triggerId, options) => service.log(1, { triggerId, follow: true, ...options }); + await models.CrontabModel.create({ + id: 1, + status: 1, + command: 'task sample', + allow_multiple_instances: 1, + }); + const poll = (triggerId, options) => + service.log(1, { triggerId, follow: true, ...options }); await history.enqueue('first', 1, 'node', 100); assert.equal((await poll()).triggerId, 'first'); for (const [i, id] of ['first', 'second', 'third'].entries()) { @@ -1284,57 +1871,105 @@ test('a concurrent viewer keeps its receipt through sibling starts, interleaved const earlier = await poll('second'); await fs.appendFile(path.join(root, 'second.log'), 'final\n'); await history.complete('second', 'finished', null, 0); - const final = await poll('second', { previousPath: earlier.logPath, offset: earlier.nextOffset, cursor: earlier.cursor }); - assert.deepEqual([final.triggerId, final.content, final.status], ['second', 'final\n', 'completed']); + const final = await poll('second', { + previousPath: earlier.logPath, + offset: earlier.nextOffset, + cursor: earlier.cursor, + }); + assert.deepEqual( + [final.triggerId, final.content, final.status], + ['second', 'final\n', 'completed'], + ); await history.complete('third', 'finished', null, 0); assert.equal((await poll()).triggerId, 'first'); assert.equal((await poll('second')).content, 'second\nfinal\n'); assert.equal((await service.log(2, { triggerId: 'first' })).total, 0); await db.query("DELETE FROM CronTriggers WHERE id='second'"); const removed = await poll('second'); - assert.deepEqual([removed.status, removed.total, removed.logPath], ['notFound', 0, undefined]); + assert.deepEqual( + [removed.status, removed.total, removed.logPath], + ['notFound', 0, undefined], + ); }); -test('concurrent manual runs with logging disabled drain both pipes and publish only the ignored path', async t => { +test('concurrent manual runs with logging disabled drain both pipes and publish only the ignored path', async (t) => { const { root, models, history } = await fixture(t); const queue = []; const Service = load('back/services/cron.ts', { - '../data/cron': models, '../data/runningInstance': {}, '../config': { logPath: root }, - '../config/util': {}, '../schedule/client': {}, '../loaders/logger': logger, - '../shared/pLimit': { manualRunWithCronLimit: fn => queue.push(fn) }, - '../shared/i18n': { t: text => text }, '../shared/logStreamManager': { logStreamManager: {} }, + '../data/cron': models, + '../data/runningInstance': {}, + '../config': { logPath: root }, + '../config/util': {}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../cron/execution/cronLimit': { + manualRunWithCronLimit: (fn) => queue.push(fn), + }, + '../shared/i18n': { t: (text) => text }, + '../shared/logStreamManager': { logStreamManager: {} }, }).default; const service = new Service(logger); - service.makeCommand = row => row.command; - await models.CrontabModel.create({ id: 1, command: 'echo stdout && echo stderr >&2', status: 1, - log_name: '/dev/null', allow_multiple_instances: 1 }); - await service.run([1]); await service.run([1]); - await Promise.all(queue.map(job => job())); + service.makeCommand = (row) => row.command; + await models.CrontabModel.create({ + id: 1, + command: 'echo stdout && echo stderr >&2', + status: 1, + log_name: '/dev/null', + allow_multiple_instances: 1, + }); + await service.run([1]); + await service.run([1]); + await Promise.all(queue.map((job) => job())); const receipts = await history.recent(1, 0); assert.equal(receipts.length, 2); for (const row of receipts) { - assert.deepEqual([row.state, row.exit_code, row.log_path], ['finished', 0, '/dev/null']); - assert.equal((await service.log(1, {triggerId: row.id})).status, 'ignored'); + assert.deepEqual( + [row.state, row.exit_code, row.log_path], + ['finished', 0, '/dev/null'], + ); + assert.equal( + (await service.log(1, { triggerId: row.id })).status, + 'ignored', + ); } }); -test('a single stop settles its own receipt, logs and daily counts even when SIGTERM exits zero', async t => { +test('a single stop settles its own receipt, logs and daily counts even when SIGTERM exits zero', async (t) => { const { root, db, models, history } = await fixture(t); - const { recordCronResult } = require('../../back/shared/cronStatistics'); + const { + recordCronResult, + } = require('../../back/cron/settlement/cronStatistics'); const instances = db.models.RunningInstance; const Service = load('back/services/cron.ts', { - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../config': { logPath: root }, '../data/cron': models, - '../data/runningInstance': { RunningInstanceModel: instances, InstanceStatus: { running: 0 } }, - '../config/util': { fileExist: async file => !!await fs.stat(file), killTask: async (pid, wait, verify, request) => { - verify(); - await request(() => { if (deny) throw Object.assign(Error('denied'), { code: 'EPERM' }); }); - } }, - '../shared/pLimit': {}, '../shared/i18n': { t: key => key }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../config': { logPath: root }, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: instances, + InstanceStatus: { running: 0 }, + }, + '../config/util': { + fileExist: async (file) => !!(await fs.stat(file)), + killTask: async (pid, wait, verify, request) => { + verify(); + await request(() => { + if (deny) throw Object.assign(Error('denied'), { code: 'EPERM' }); + }); + }, + }, + '../cron/execution/cronLimit': {}, + '../shared/i18n': { t: (key) => key }, }).default; let deny = true; const service = new Service(logger); - await models.CrontabModel.create({ id: 1, command: 'true', status: 1, allow_multiple_instances: 1 }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); const target = {}; for (const id of ['a', 'b', 'c']) { await history.enqueue(id, 1, 'manual', null); @@ -1355,30 +1990,70 @@ test('a single stop settles its own receipt, logs and daily counts even when SIG await history.complete('b', 'finished', null, 0); for (const id of ['a', 'b', 'c']) { const log = await service.log(1, { instanceId: target[id] }); - assert.deepEqual([log.content, log.status], ['instance-' + id, id === 'b' ? 'completed' : 'running']); + assert.deepEqual( + [log.content, log.status], + ['instance-' + id, id === 'b' ? 'completed' : 'running'], + ); } - assert.equal((await service.log(2, { instanceId: target.b })).status, 'notFound'); + assert.equal( + (await service.log(2, { instanceId: target.b })).status, + 'notFound', + ); await history.complete('c', 'failed', null, 17); await history.complete('a', 'finished', null, 0); await recordCronResult(db, 1, 17, 900, Date.now(), 'b'); await history.complete('b', 'failed', null, 17); - const receipts = await db.query('SELECT id,state,exit_code,counted FROM CronTriggers ORDER BY id', { type: QueryTypes.SELECT }); - assert.deepEqual(receipts.map(r => [r.id, r.state, r.exit_code, r.counted]), - [['a', 'finished', 0, 1], ['b', 'stopped', 0, 1], ['c', 'failed', 17, 1]]); - assert.deepEqual((await instances.findAll({ order: [['id', 'ASC']] })).map(row => [row.status, row.exit_code]), - [[1, 0], [2, 0], [3, 17]]); - assert.equal((await service.log(1, { instanceId: target.b })).content, 'instance-b'); - const [counts] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + const receipts = await db.query( + 'SELECT id,state,exit_code,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + receipts.map((r) => [r.id, r.state, r.exit_code, r.counted]), + [ + ['a', 'finished', 0, 1], + ['b', 'stopped', 0, 1], + ['c', 'failed', 17, 1], + ], + ); + assert.deepEqual( + (await instances.findAll({ order: [['id', 'ASC']] })).map((row) => [ + row.status, + row.exit_code, + ]), + [ + [1, 0], + [2, 0], + [3, 17], + ], + ); + assert.equal( + (await service.log(1, { instanceId: target.b })).content, + 'instance-b', + ); + const [counts] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(counts, { run_count: 3, success_count: 1, fail_count: 1 }); }); -test('a crond stop racing owner recovery is counted once and an unsolicited signal is a failure', async t => { +test('a crond stop racing owner recovery is counted once and an unsolicited signal is a failure', async (t) => { const { db, history, models } = await fixture(t); - await models.CrontabModel.create({ id: 1, command: 'true', status: 1, isDisabled: 0 }); - assert.equal(await history.startSystem('system-stop', 1, systemOwner(process.pid)), true); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + isDisabled: 0, + }); + assert.equal( + await history.startSystem('system-stop', 1, systemOwner(process.pid)), + true, + ); const instance = await db.models.RunningInstance.findOne(); await history.requestInstanceStop(instance.id, process.pid, () => {}); - await db.query("UPDATE CronTriggers SET owner=owner || '-old' WHERE id='system-stop'"); + await db.query( + "UPDATE CronTriggers SET owner=owner || '-old' WHERE id='system-stop'", + ); await history.queueCounts(); await history.stopVerifiedInstance(instance.id); await history.complete('system-stop', 'failed', null, 143); @@ -1387,57 +2062,112 @@ test('a crond stop racing owner recovery is counted once and an unsolicited sign await history.start('external'); await history.complete('external', 'stopped', 'SIGKILL', null); assert.equal((await history.recent(1, 0))[0].state, 'failed'); - const [counts] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + const [counts] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(counts, { run_count: 2, success_count: 0, fail_count: 1 }); }); -test('late dashboard callbacks cannot count a trigger cancelled before dispatch', async t => { +test('late dashboard callbacks cannot count a trigger cancelled before dispatch', async (t) => { const { db, history } = await fixture(t); - const { recordCronResult } = require('../../back/shared/cronStatistics'); + const { + recordCronResult, + } = require('../../back/cron/settlement/cronStatistics'); await history.enqueue('waiting', 1, 'manual', null); await history.cancelQueued([1]); await recordCronResult(db, 1, 0, 10, Date.now(), 'waiting'); - assert.equal((await db.query('SELECT * FROM CrontabStats', { type: QueryTypes.SELECT })).length, 0); + assert.equal( + (await db.query('SELECT * FROM CrontabStats', { type: QueryTypes.SELECT })) + .length, + 0, + ); }); -test('stop claims serialize with natural completion and duplicate requests from separate connections', async t => { +test('stop claims serialize with natural completion and duplicate requests from separate connections', async (t) => { const { history, models, db, root } = await fixture(t); - const peer = new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), - logging: false, transactionType: Transaction.TYPES.IMMEDIATE }); + const peer = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + transactionType: Transaction.TYPES.IMMEDIATE, + }); t.after(() => peer.close()); const remote = new TriggerHistory(peer); - await models.CrontabModel.create({ id: 1, command: 'true', status: 1, allow_multiple_instances: 1 }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); const ids = {}; for (const id of ['natural', 'cancel', 'other']) { await history.enqueue(id, 1, 'manual', null); await history.start(id, Date.now(), true); await history.bindCommand(id, process.pid, id + '.log'); - ids[id] = (await db.models.RunningInstance.findOne({ where: { log_path: id + '.log' } })).id; + ids[id] = ( + await db.models.RunningInstance.findOne({ + where: { log_path: id + '.log' }, + }) + ).id; } - const signalGone = () => { throw Object.assign(Error('gone'), {code: 'ESRCH'}); }; - await assert.rejects(remote.requestInstanceStop(ids.natural, process.pid, signalGone), {code: 'ESRCH'}); + const signalGone = () => { + throw Object.assign(Error('gone'), { code: 'ESRCH' }); + }; + await assert.rejects( + remote.requestInstanceStop(ids.natural, process.pid, signalGone), + { code: 'ESRCH' }, + ); await history.complete('natural', 'finished', null, 0); let signals = 0; - const signal = () => { signals++; }; - await assert.rejects(remote.requestInstanceStop(ids.natural, process.pid, signal), {code: 'ESRCH'}); - await Promise.all([remote, history].map(h => h.requestInstanceStop(ids.cancel, process.pid, signal))); + const signal = () => { + signals++; + }; + await assert.rejects( + remote.requestInstanceStop(ids.natural, process.pid, signal), + { code: 'ESRCH' }, + ); + await Promise.all( + [remote, history].map((h) => + h.requestInstanceStop(ids.cancel, process.pid, signal), + ), + ); assert.equal(signals, 1); assert.equal(await history.shouldStop('natural'), false); assert.equal(await history.shouldStop('other'), false); - await Promise.all([remote.complete('cancel', 'finished', null, 0), history.complete('cancel', 'finished', null, 0)]); + await Promise.all([ + remote.complete('cancel', 'finished', null, 0), + history.complete('cancel', 'finished', null, 0), + ]); await history.complete('other', 'failed', null, 17); - const rows = await db.query('SELECT state,exit_code,counted FROM CronTriggers ORDER BY id', {type: QueryTypes.SELECT}); - assert.deepEqual(rows.map(r => [r.state,r.exit_code,r.counted]), [['stopped',0,1],['finished',0,1],['failed',17,1]]); - const [counts] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', {type: QueryTypes.SELECT}); - assert.deepEqual(counts, {run_count: 3, success_count: 1, fail_count: 1}); + const rows = await db.query( + 'SELECT state,exit_code,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.map((r) => [r.state, r.exit_code, r.counted]), + [ + ['stopped', 0, 1], + ['finished', 0, 1], + ['failed', 17, 1], + ], + ); + const [counts] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(counts, { run_count: 3, success_count: 1, fail_count: 1 }); }); -test('crond waits for its supervisor to report the actual exit after the separate command exits', async t => { +test('crond waits for its supervisor to report the actual exit after the separate command exits', async (t) => { const { db, history, models } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); const supervisor = systemOwner(process.pid); const command = 'crond:9090:1:boot'; - assert.equal(await history.startSystem('system-race', 1, supervisor, command), true); + assert.equal( + await history.startSystem('system-race', 1, supervisor, command), + true, + ); const instance = await db.models.RunningInstance.findOne(); assert.equal(instance.pid, 9090); assert.equal(await history.instanceIdentity(instance.id), command); @@ -1448,38 +2178,66 @@ test('crond waits for its supervisor to report the actual exit after the separat assert.equal((await history.recent(1, 0))[0].state, 'finished'); }); -test('a legacy crontab entering a sourced wrapper runs its original arguments once and reports its actual exit', async t => { +test('a legacy crontab entering a sourced wrapper runs its original arguments once and reports its actual exit', async (t) => { const { root } = await fixture(t); const bin = path.join(root, 'bin'); await fs.mkdir(bin); // Stand in only for the Node receipt client; bash, argument passing and exit // propagation run through the production crond supervisor. - await fs.writeFile(path.join(bin, 'node'), '#!/bin/sh\nif [ "$1" = -p ]; then echo "test-uuid"; exit 0; fi\necho "$2" >> "$TRACE"\n', { mode: 0o755 }); + await fs.writeFile( + path.join(bin, 'node'), + '#!/bin/sh\nif [ "$1" = -p ]; then echo "test-uuid"; exit 0; fi\necho "$2" >> "$TRACE"\n', + { mode: 0o755 }, + ); const wrapper = path.join(root, "old ' task.sh"); - await fs.writeFile(wrapper, [ - 'if [[ -z ${QL_TRIGGER_ID:-} ]]; then . "$SUPERVISOR"; fi', - 'printf "%s\\n" "$@" >> "$TRACE"', - 'exit 17', - ].join('\n')); + await fs.writeFile( + wrapper, + [ + 'if [[ -z ${QL_TRIGGER_ID:-} ]]; then . "$SUPERVISOR"; fi', + 'printf "%s\\n" "$@" >> "$TRACE"', + 'exit 17', + ].join('\n'), + ); const trace = path.join(root, 'trace'); const args = ['a b', "quote' and $literal", '']; - const result = require('node:child_process').spawnSync('/bin/bash', [wrapper, ...args], { - env: { ...process.env, ID: '7', QL_DIR: root, QL_TRIGGER_ID: '', TRACE: trace, SUPERVISOR: path.resolve('shell/system-cron.sh'), - PATH: bin + ':' + process.env.PATH }, encoding: 'utf8', - }); + const result = require('node:child_process').spawnSync( + '/bin/bash', + [wrapper, ...args], + { + env: { + ...process.env, + ID: '7', + QL_DIR: root, + QL_TRIGGER_ID: '', + TRACE: trace, + SUPERVISOR: path.resolve('shell/system-cron.sh'), + PATH: bin + ':' + process.env.PATH, + }, + encoding: 'utf8', + }, + ); assert.equal(result.status, 17, result.stderr); - assert.equal(await fs.readFile(trace, 'utf8'), ['start', ...args, 'finish', ''].join('\n')); + assert.equal( + await fs.readFile(trace, 'utf8'), + ['start', ...args, 'finish', ''].join('\n'), + ); }); for (const legacy of [false, true]) { - test(`stop recovery keeps a real surviving descendant and its first exit receipt linked (legacy=${legacy})`, async t => { + test(`stop recovery keeps a real surviving descendant and its first exit receipt linked (legacy=${legacy})`, async (t) => { const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { db, models, history } = await fixture(t); const children = []; - t.after(() => { for (const c of children) if (c.exitCode === null && c.signalCode === null) c.kill('SIGKILL'); }); + t.after(() => { + for (const c of children) + if (c.exitCode === null && c.signalCode === null) c.kill('SIGKILL'); + }); for (let i = 0; i < 2; i++) { - const c = spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{}); console.log('ready');setInterval(()=>{},1000)"]); + const c = spawn(process.execPath, [ + '-e', + "process.on('SIGTERM',()=>{}); console.log('ready');setInterval(()=>{},1000)", + ]); children.push(c); await once(c.stdout, 'data'); } @@ -1490,12 +2248,39 @@ for (const legacy of [false, true]) { await history.start('stop-restart'); await history.bindCommand('stop-restart', target.pid, 'original.log'); const instance = await db.models.RunningInstance.findOne(); - if (legacy) await db.query("UPDATE CronTriggers SET owner=NULL,command_identity=NULL"); - const identities = [systemOwner(target.pid), systemOwner(peer.pid) + '-old']; - await history.requestInstanceStop(instance.id, target.pid, () => target.kill('SIGTERM'), identities); + if (legacy) + await db.query( + 'UPDATE CronTriggers SET owner=NULL,command_identity=NULL', + ); + const identities = [ + systemOwner(target.pid), + systemOwner(peer.pid) + '-old', + ]; + await history.requestInstanceStop( + instance.id, + target.pid, + () => target.kill('SIGTERM'), + identities, + ); if (legacy) { - await history.reportInstance('stop-restart', 1, false, target.pid, 'original.log', 0, 1, 143); - await require('../../back/shared/cronStatistics').recordCronResult(db, 1, 143, 1000, Date.now(), 'stop-restart'); + await history.reportInstance( + 'stop-restart', + 1, + false, + target.pid, + 'original.log', + 0, + 1, + 143, + ); + await require('../../back/cron/settlement/cronStatistics').recordCronResult( + db, + 1, + 143, + 1000, + Date.now(), + 'stop-restart', + ); } else { await history.complete('stop-restart', 'failed', null, 143); } @@ -1505,10 +2290,18 @@ for (const legacy of [false, true]) { assert.equal(await db.models.CrontabStat.count(), 0); assert.equal((await instance.reload()).status, 0); const service = new (load('back/services/cron.ts', { - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../config': {}, '../data/cron': models, '../shared/pLimit': {}, '../config/util': {}, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0, stopped: 2 } }, - '../shared/i18n': { t: key => key }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../config': {}, + '../data/cron': models, + '../cron/execution/cronLimit': {}, + '../config/util': {}, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0, stopped: 2 }, + }, + '../shared/i18n': { t: (key) => key }, }).default)(logger); const pending = await history.pendingStops(); await service.resumePendingStops(history, pending); @@ -1520,14 +2313,20 @@ for (const legacy of [false, true]) { assert.deepEqual(await history.pendingStops(), []); await instance.reload(); assert.deepEqual([instance.status, instance.exit_code], [2, 143]); - const [row] = await db.query('SELECT state,exit_code,counted FROM CronTriggers', { type: QueryTypes.SELECT }); + const [row] = await db.query( + 'SELECT state,exit_code,counted FROM CronTriggers', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(row, { state: 'stopped', exit_code: 143, counted: 1 }); - const [counts] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + const [counts] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(counts, { run_count: 1, success_count: 0, fail_count: 0 }); }); } -test('restart separates a stop before launch, a lost exit, and a legacy pending stop', async t => { +test('restart separates a stop before launch, a lost exit, and a legacy pending stop', async (t) => { const { db, history, models } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); for (const id of ['gate', 'lost', 'old']) { @@ -1536,25 +2335,55 @@ test('restart separates a stop before launch, a lost exit, and a legacy pending if (id !== 'gate') await history.bindCommand(id, process.pid, id + '.log'); } await history.cancelQueued([1]); - await db.query("UPDATE CronTriggers SET command_identity=NULL,process_identity=process_identity || '-gone' WHERE id='lost'"); + await db.query( + "UPDATE CronTriggers SET command_identity=NULL,process_identity=process_identity || '-gone' WHERE id='lost'", + ); await db.query("UPDATE CronTriggers SET stop_requested=1 WHERE id='old'"); await history.interrupt('http'); - const rows = await db.query('SELECT id,state,reason,counted FROM CronTriggers ORDER BY id', { type: QueryTypes.SELECT }); - assert.deepEqual(rows.map(r => [r.id,r.state,r.reason,r.counted]), [ - ['gate','stopped','cancelled',0], ['lost','unknown','restart',0], ['old','running','restart',0], - ]); - assert.equal((await db.models.RunningInstance.findOne({ where: { log_path: 'lost.log' } })).status, 4); - await db.models.RunningInstance.update({ status: 3 }, { where: { log_path: 'lost.log' } }); + const rows = await db.query( + 'SELECT id,state,reason,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.map((r) => [r.id, r.state, r.reason, r.counted]), + [ + ['gate', 'stopped', 'cancelled', 0], + ['lost', 'unknown', 'restart', 0], + ['old', 'running', 'restart', 0], + ], + ); + assert.equal( + ( + await db.models.RunningInstance.findOne({ + where: { log_path: 'lost.log' }, + }) + ).status, + 4, + ); + await db.models.RunningInstance.update( + { status: 3 }, + { where: { log_path: 'lost.log' } }, + ); await history.reconcileInstances(); - assert.equal((await db.models.RunningInstance.findOne({ where: { log_path: 'lost.log' } })).status, 4); + assert.equal( + ( + await db.models.RunningInstance.findOne({ + where: { log_path: 'lost.log' }, + }) + ).status, + 4, + ); assert.equal((await history.pendingStops())[0].pid, process.pid); }); -test('recovered stops persist the real script entry timestamp before consuming the marker', async t => { +test('recovered stops persist the real script entry timestamp before consuming the marker', async (t) => { const { db, root, history, models } = await fixture(t); const original = process.env.QL_DIR; process.env.QL_DIR = root; - t.after(() => { if (original === undefined) delete process.env.QL_DIR; else process.env.QL_DIR = original; }); + t.after(() => { + if (original === undefined) delete process.env.QL_DIR; + else process.env.QL_DIR = original; + }); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); await history.enqueue('timed-stop', 1, 'manual', null); await history.start('timed-stop'); @@ -1569,48 +2398,73 @@ test('recovered stops persist the real script entry timestamp before consuming t await history.interrupt('http'); await history.stopVerifiedInstance(instance.id); const [receipt] = await history.recent(1, 0); - assert.deepEqual([receipt.state, receipt.script_started_at], ['stopped', time]); + assert.deepEqual( + [receipt.state, receipt.script_started_at], + ['stopped', time], + ); await assert.rejects(fs.stat(marker), { code: 'ENOENT' }); }); -test('a BSD child disappearing during ps does not strand a signalled instance or count its stop twice', async t => { +test('a BSD child disappearing during ps does not strand a signalled instance or count its stop twice', async (t) => { const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { db, models, history } = await fixture(t); const service = retiredProcessFixtureService(db, models); - const root = spawn(process.execPath, ['-e', ` + const root = spawn(process.execPath, [ + '-e', + ` const child = require('node:child_process').spawn('cat', { stdio: ['inherit', 'ignore', 'ignore'] }); process.on('SIGTERM', () => child.kill('SIGTERM')); child.on('exit', () => process.exit(0)); console.log(child.pid); - `]); + `, + ]); t.after(() => root.stdin.end()); const childPid = Number((await once(root.stdout, 'data'))[0]); - await models.CrontabModel.create({ id: 1, status: 1, command: 'cat', allow_multiple_instances: 1 }); - for (const [id, pid] of [['target', root.pid], ['sibling', process.pid]]) { + await models.CrontabModel.create({ + id: 1, + status: 1, + command: 'cat', + allow_multiple_instances: 1, + }); + for (const [id, pid] of [ + ['target', root.pid], + ['sibling', process.pid], + ]) { await history.enqueue(id, 1, 'manual', null); await history.start(id, Date.now(), true); await history.bindCommand(id, pid); } - const instance = await db.models.RunningInstance.findOne({ where: { pid: root.pid } }); + const instance = await db.models.RunningInstance.findOne({ + where: { pid: root.pid }, + }); const targets = [systemOwner(root.pid), systemOwner(childPid)]; const exited = once(root, 'close'); - await history.requestInstanceStop(instance.id, root.pid, () => root.kill('SIGTERM'), targets); + await history.requestInstanceStop( + instance.id, + root.pid, + () => root.kill('SIGTERM'), + targets, + ); await exited; await history.complete('target', 'stopped', 'cancelled', null); const api = load('back/api/cron.ts', { typedi: { Container: { get: () => service } }, - '../services/cron': class {}, '../services/cronView': class {}, - '../schedule/client': {}, '../validation/schedule': { commonCronSchema: {} }, + '../services/cron': class {}, + '../services/cronView': class {}, + '../schedule/client': {}, + '../validation/schedule': { commonCronSchema: {} }, }); const app = express(); const router = express.Router(); api.default(router); const server = app.use('/api', router).listen(0, '127.0.0.1'); await once(server, 'listening'); - t.after(() => new Promise(resolve => server.close(resolve))); - const url = `http://127.0.0.1:${server.address().port}/api/crons/1/instances/${instance.id}/stop`; + t.after(() => new Promise((resolve) => server.close(resolve))); + const url = `http://127.0.0.1:${ + server.address().port + }/api/crons/1/instances/${instance.id}/stop`; // Recreate the window after kill(pid, 0) has succeeded. The real ps now sees no row. const platform = Object.getOwnPropertyDescriptor(process, 'platform'); @@ -1632,17 +2486,31 @@ test('a BSD child disappearing during ps does not strand a signalled instance or Object.defineProperty(process, 'platform', platform); } assert.equal(await history.pendingStop(instance.id), undefined); - const rows = await db.query('SELECT id,state,counted FROM CronTriggers ORDER BY id', { type: QueryTypes.SELECT }); - assert.deepEqual(rows, [{ id: 'sibling', state: 'running', counted: 0 }, { id: 'target', state: 'stopped', counted: 1 }]); + const rows = await db.query( + 'SELECT id,state,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(rows, [ + { id: 'sibling', state: 'running', counted: 0 }, + { id: 'target', state: 'stopped', counted: 1 }, + ]); }); -test('a restarted stop consumes only the remainder of the original TERM grace period', async t => { +test('a restarted stop consumes only the remainder of the original TERM grace period', async (t) => { const { spawn } = require('node:child_process'); const { once } = require('node:events'); - const { finishStoppedTree } = require('../../back/shared/cronProcess'); + const { + finishStoppedTree, + } = require('../../back/cron/execution/cronProcess'); const { db, history, models } = await fixture(t); - const child = spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{});console.log('ready');setInterval(()=>{},1000)"]); - t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }); + const child = spawn(process.execPath, [ + '-e', + "process.on('SIGTERM',()=>{});console.log('ready');setInterval(()=>{},1000)", + ]); + t.after(() => { + if (child.exitCode === null && child.signalCode === null) + child.kill('SIGKILL'); + }); await once(child.stdout, 'data'); const exited = once(child, 'exit'); await models.CrontabModel.create({ id: 1, status: 1, command: 'true' }); @@ -1652,11 +2520,19 @@ test('a restarted stop consumes only the remainder of the original TERM grace pe const row = await db.models.RunningInstance.findOne(); const targets = [systemOwner(child.pid)]; const began = Date.now(); - await history.requestInstanceStop(row.id, child.pid, () => child.kill('SIGTERM'), targets); + await history.requestInstanceStop( + row.id, + child.pid, + () => child.kill('SIGTERM'), + targets, + ); const first = await history.pendingStop(row.id); assert.ok(first.signalled_at >= began); for (let i = 0; i < 2; i++) await history.interrupt('http'); - assert.equal((await history.pendingStop(row.id)).signalled_at, first.signalled_at); + assert.equal( + (await history.pendingStop(row.id)).signalled_at, + first.signalled_at, + ); // Observe scheduled delays, independently of load on the test host. const delays = []; const timer = global.setTimeout; @@ -1664,97 +2540,177 @@ test('a restarted stop consumes only the remainder of the original TERM grace pe delays.push(ms); return timer(fn, ms, ...args); }); - try { await finishStoppedTree(targets, first.signalled_at - 1000); } - finally { spy.mock.restore(); } + try { + await finishStoppedTree(targets, first.signalled_at - 1000); + } finally { + spy.mock.restore(); + } assert.equal((await exited)[1], 'SIGKILL'); - assert.ok(delays.every(ms => ms <= 20), JSON.stringify(delays)); + assert.ok( + delays.every((ms) => ms <= 20), + JSON.stringify(delays), + ); await history.stopVerifiedInstance(row.id); await history.stopVerifiedInstance(row.id); assert.equal((await history.recent(1, 0))[0].state, 'stopped'); }); -test('a command without an instance survives two interrupted stop attempts and its old batch cannot select a new command', async t => { +test('a command without an instance survives two interrupted stop attempts and its old batch cannot select a new command', async (t) => { const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { db, models, history } = await fixture(t); - const child = spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{});console.log('ready');setInterval(()=>{},1000)"]); - t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }); + const child = spawn(process.execPath, [ + '-e', + "process.on('SIGTERM',()=>{});console.log('ready');setInterval(()=>{},1000)", + ]); + t.after(() => { + if (child.exitCode === null && child.signalCode === null) + child.kill('SIGKILL'); + }); await once(child.stdout, 'data'); const exited = once(child, 'exit'); const { killTask } = require('../../back/config/util'); const service = new (load('back/services/cron.ts', { - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../data/cron': models, '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0, stopped: 2 } }, - '../config': {}, '../shared/pLimit': {}, '../shared/i18n': { t: s => s }, - '../config/util': { killTask: async (pid, wait, verify, request) => { - await killTask(pid, wait, verify, async (signal, targets) => { - await request(signal, targets); - throw Error('worker interrupted after TERM'); - }); - } }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0, stopped: 2 }, + }, + '../config': {}, + '../cron/execution/cronLimit': {}, + '../shared/i18n': { t: (s) => s }, + '../config/util': { + killTask: async (pid, wait, verify, request) => { + await killTask(pid, wait, verify, async (signal, targets) => { + await request(signal, targets); + throw Error('worker interrupted after TERM'); + }); + }, + }, }).default)(logger); - await models.CrontabModel.create({ id: 1, status: 0, pid: child.pid, command: 'true', allow_multiple_instances: 1 }); + await models.CrontabModel.create({ + id: 1, + status: 0, + pid: child.pid, + command: 'true', + allow_multiple_instances: 1, + }); const birth = systemOwner(child.pid); await history.enqueue('legacy', 1, 'manual', null); await history.start('legacy'); - await db.query("UPDATE CronTriggers SET command_identity=$birth WHERE id='legacy'", { bind: { birth } }); + await db.query( + "UPDATE CronTriggers SET command_identity=$birth WHERE id='legacy'", + { bind: { birth } }, + ); const key = require('node:crypto').randomUUID(); await assert.rejects(service.stop([1], key), /interrupted after TERM/); const [pending] = await history.pendingStops(); - assert.equal((await history.pendingStop(pending.instance_id)).root_identity, birth); - for (let n=0;n<2;n++) await history.interrupt('http'); + assert.equal( + (await history.pendingStop(pending.instance_id)).root_identity, + birth, + ); + for (let n = 0; n < 2; n++) await history.interrupt('http'); await history.enqueue('next', 1, 'manual', null); await history.start('next', Date.now(), true); await history.bindCommand('next', process.pid, 'next.log'); - await service.resumePendingStops(history, await history.pendingStops(), await history.pendingStopBatches()); + await service.resumePendingStops( + history, + await history.pendingStops(), + await history.pendingStopBatches(), + ); assert.equal((await exited)[1], 'SIGKILL'); await service.stop([1], key); - const rows = await db.query('SELECT state,counted FROM CronTriggers ORDER BY id', { type: QueryTypes.SELECT }); - assert.deepEqual(rows, [{ state:'stopped', counted:1 }, { state:'running', counted:0 }]); - const [stat] = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); - assert.deepEqual(stat, { run_count:1, success_count:0, fail_count:0 }); + const rows = await db.query( + 'SELECT state,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(rows, [ + { state: 'stopped', counted: 1 }, + { state: 'running', counted: 0 }, + ]); + const [stat] = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(stat, { run_count: 1, success_count: 0, fail_count: 0 }); assert.deepEqual(await history.pendingStops(), []); assert.deepEqual(await history.pendingStopBatches(), []); }); -test('two connections atomically bind a fresh batch key to one normalized task set', async t => { +test('two connections atomically bind a fresh batch key to one normalized task set', async (t) => { const { db, models, history, root } = await fixture(t); - const peer = new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), logging: false }); + const peer = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + }); t.after(() => peer.close()); - const makeService = (database, cronModels) => new (load('back/services/cron.ts', { - '../data/cron': cronModels, - '../data/runningInstance': load('back/data/runningInstance.ts', { '.': { sequelize: database } }), - '../config': {}, '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../shared/pLimit': {}, '../config/util': {}, '../shared/i18n': { t: key => key }, - }).default)(logger); - const services = [makeService(db, models), makeService(peer, load('back/data/cron.ts', { '.': { sequelize: peer } }))]; + const makeService = (database, cronModels) => + new (load('back/services/cron.ts', { + '../data/cron': cronModels, + '../data/runningInstance': load('back/data/runningInstance.ts', { + '.': { sequelize: database }, + }), + '../config': {}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../cron/execution/cronLimit': {}, + '../config/util': {}, + '../shared/i18n': { t: (key) => key }, + }).default)(logger); + const services = [ + makeService(db, models), + makeService(peer, load('back/data/cron.ts', { '.': { sequelize: peer } })), + ]; for (const id of [1, 2, 3]) { await models.CrontabModel.create({ id, command: 'true', status: 3 }); await history.enqueue('queue-' + id, id, 'manual', null); } const payloads = [[2, 1, 1], [3], [1, 2], [3, 3]]; const key = require('node:crypto').randomUUID(); - const attempts = await Promise.allSettled(payloads.map((ids, i) => services[i % 2].stop(ids, key))); - const [binding] = await db.query('SELECT cron_ids,snapshot FROM CronStopBatches', { type: QueryTypes.SELECT }); + const attempts = await Promise.allSettled( + payloads.map((ids, i) => services[i % 2].stop(ids, key)), + ); + const [binding] = await db.query( + 'SELECT cron_ids,snapshot FROM CronStopBatches', + { type: QueryTypes.SELECT }, + ); const winner = JSON.parse(binding.cron_ids); assert.equal(binding.snapshot, null); for (const [i, attempt] of attempts.entries()) { - if (winner.includes(payloads[i][0])) assert.equal(attempt.status, 'fulfilled'); + if (winner.includes(payloads[i][0])) + assert.equal(attempt.status, 'fulfilled'); else assert.equal(attempt.reason.status, 409); } for (const id of [1, 2, 3]) { - assert.equal((await history.recent(id, 0))[0].state, winner.includes(id) ? 'stopped' : 'queued'); + assert.equal( + (await history.recent(id, 0))[0].state, + winner.includes(id) ? 'stopped' : 'queued', + ); } const next = 'after-binding'; await history.enqueue(next, winner[0], 'manual', null); - await Promise.all(services.map(service => service.stop(winner.slice().reverse(), key))); - assert.equal((await history.recent(winner[0], 0)).find(row => row.id === next).state, 'queued'); + await Promise.all( + services.map((service) => service.stop(winner.slice().reverse(), key)), + ); + assert.equal( + (await history.recent(winner[0], 0)).find((row) => row.id === next).state, + 'queued', + ); }); -test('a failed stop-marker write leaves the root untouched and two workers finish only the claimed tree', async t => { +test('a failed stop-marker write leaves the root untouched and two workers finish only the claimed tree', async (t) => { const { db, models, history, root } = await fixture(t); - const peer = new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), logging: false, - transactionType: Transaction.TYPES.IMMEDIATE }); + const peer = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + transactionType: Transaction.TYPES.IMMEDIATE, + }); t.after(() => peer.close()); const remote = new TriggerHistory(peer); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); @@ -1763,33 +2719,63 @@ test('a failed stop-marker write leaves the root untouched and two workers finis await history.bindCommand('claim', process.pid, 'claim.log'); const instance = await db.models.RunningInstance.findOne(); let signals = 0; - const claim = (worker, targets, callback) => worker.requestInstanceStop(instance.id, process.pid, callback, targets); - const signal = () => { signals++; }; + const claim = (worker, targets, callback) => + worker.requestInstanceStop(instance.id, process.pid, callback, targets); + const signal = () => { + signals++; + }; await db.query(`CREATE TRIGGER reject_marker BEFORE UPDATE OF signalled ON CronStopRequests BEGIN SELECT json_extract('invalid json','$'); END`); - await assert.rejects(claim(history, ['root', 'child'], signal), /malformed JSON/i); + await assert.rejects( + claim(history, ['root', 'child'], signal), + /malformed JSON/i, + ); assert.equal(signals, 0); assert.equal(await history.shouldStop('claim'), false); await db.query('DROP TRIGGER reject_marker'); const denied = Object.assign(Error('child denied'), { code: 'EPERM' }); - await assert.rejects(claim(remote, ['root'], () => { signals++; return denied; }), error => error === denied); + await assert.rejects( + claim(remote, ['root'], () => { + signals++; + return denied; + }), + (error) => error === denied, + ); const saved = await history.pendingStop(instance.id); assert.equal(saved.signalled, 1); assert.deepEqual(JSON.parse(saved.targets).sort(), ['child', 'root']); assert.deepEqual(await history.forgetStop(instance.id), saved); const duplicate = await claim(history, ['root', 'different-child'], signal); - assert.deepEqual(duplicate, { targets: JSON.parse(saved.targets), signalledAt: saved.signalled_at }); + assert.deepEqual(duplicate, { + targets: JSON.parse(saved.targets), + signalledAt: saved.signalled_at, + }); assert.equal(signals, 1); await history.complete('claim', 'finished', null, 0); - await Promise.all([remote, history].map(worker => worker.stopVerifiedInstance(instance.id))); - const counts = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); + await Promise.all( + [remote, history].map((worker) => worker.stopVerifiedInstance(instance.id)), + ); + const counts = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(counts, [{ run_count: 1, success_count: 0, fail_count: 0 }]); }); -test('startup reconciliation preserves a live legacy instance whose stop has not succeeded', async t => { +test('startup reconciliation preserves a live legacy instance whose stop has not succeeded', async (t) => { const { db, models, history } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 0, pid: process.pid }); - const instance = await db.models.RunningInstance.create({ cron_id: 1, pid: process.pid, status: 0, started_at: 1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + pid: process.pid, + }); + const instance = await db.models.RunningInstance.create({ + cron_id: 1, + pid: process.pid, + status: 0, + started_at: 1, + }); await history.queueInstanceStop(instance.id, 1, process.pid); for (let n = 0; n < 2; n++) await history.reconcileInstances(); assert.equal((await instance.reload()).status, 0); @@ -1798,16 +2784,35 @@ test('startup reconciliation preserves a live legacy instance whose stop has not assert.equal((await history.pendingStops())[0].instance_id, instance.id); }); -test('a frozen legacy identity conflict is returned on replay without repeating recovery', async t => { +test('a frozen legacy identity conflict is returned on replay without repeating recovery', async (t) => { const { models, history, db } = await fixture(t); - const conflict = () => { throw Object.assign(Error('birth differs'), { status: 409 }); }; + const conflict = () => { + throw Object.assign(Error('birth differs'), { status: 409 }); + }; const service = new (load('back/services/cron.ts', { - '../data/cron': models, '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../config': {}, '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../config/util': {}, '../shared/pLimit': {}, '../shared/i18n': { t: key => key }, - '../shared/cronProcess': { systemOwner, verifyCronProcess: conflict }, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../config': {}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../config/util': {}, + '../cron/execution/cronLimit': {}, + '../shared/i18n': { t: (key) => key }, + '../cron/execution/cronProcess': { + systemOwner, + verifyCronProcess: conflict, + }, }).default)(logger); - await models.CrontabModel.create({ id: 1, command: 'true', status: 0, pid: process.pid }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + pid: process.pid, + }); const key = require('node:crypto').randomUUID(); await assert.rejects(service.stop([1], key), { status: 409 }); assert.deepEqual(await history.pendingStopBatches(), []); @@ -1816,7 +2821,7 @@ test('a frozen legacy identity conflict is returned on replay without repeating assert.equal((await history.recent(1, 0))[0].state, 'queued'); }); -test('losing the prepared tree to another worker cannot deliver an unrecorded signal', async t => { +test('losing the prepared tree to another worker cannot deliver an unrecorded signal', async (t) => { const { db, models, history } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); await history.enqueue('released', 1, 'manual', null); @@ -1826,7 +2831,15 @@ test('losing the prepared tree to another worker cannot deliver an unrecorded si await db.query(`CREATE TRIGGER drop_preparation AFTER INSERT ON CronStopRequests BEGIN DELETE FROM CronStopRequests WHERE instance_id=NEW.instance_id; END`); let received = 0; - const submit = () => history.requestInstanceStop(instance.id, process.pid, () => { received++; }, ['original']); + const submit = () => + history.requestInstanceStop( + instance.id, + process.pid, + () => { + received++; + }, + ['original'], + ); await assert.rejects(submit(), { status: 503 }); assert.equal(received, 0); assert.equal(await history.shouldStop('released'), false); @@ -1838,38 +2851,87 @@ test('losing the prepared tree to another worker cannot deliver an unrecorded si function retiredProcessFixtureService(db, models) { return new (load('back/services/cron.ts', { - '../config': {}, '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../data/cron': models, '../shared/pLimit': {}, '../shared/i18n': { t: key => key }, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0, stopped: 2, unknown: 4 } }, - '../config/util': { killTask() { assert.fail('the replacement must never receive a signal'); } }, + '../config': {}, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../data/cron': models, + '../cron/execution/cronLimit': {}, + '../shared/i18n': { t: (key) => key }, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0, stopped: 2, unknown: 4 }, + }, + '../config/util': { + killTask() { + assert.fail('the replacement must never receive a signal'); + }, + }, }).default)(logger); } for (const legacy of [false, true]) { - test(`a cold batch retry settles its old instance while the same PID is live again (legacy=${legacy})`, async t => { + test(`a cold batch retry settles its old instance while the same PID is live again (legacy=${legacy})`, async (t) => { const { db, history, models } = await fixture(t); const service = retiredProcessFixtureService(db, models); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 1, allow_multiple_instances: 1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); const birth = systemOwner(process.pid); let old; if (legacy) { - old = await db.models.RunningInstance.create({ cron_id: 1, pid: process.pid, log_path: 'same.log', started_at: 1, status: 0 }); + old = await db.models.RunningInstance.create({ + cron_id: 1, + pid: process.pid, + log_path: 'same.log', + started_at: 1, + status: 0, + }); } else { // Simulate a persisted request from before namespace_owner existed. - await history.startSystem('old', 1, birth + '-old-supervisor', birth + '-old-command'); + await history.startSystem( + 'old', + 1, + birth + '-old-supervisor', + birth + '-old-command', + ); old = await db.models.RunningInstance.findOne(); } await history.queueInstanceStop(old.id, 1, process.pid); - await db.query('UPDATE CronStopRequests SET namespace_owner=$namespace,targets=$targets WHERE instance_id=$id', - { bind: { id: old.id, namespace: legacy ? 'crond:1:previous' : null, targets: JSON.stringify([birth + '-old-command']) } }); + await db.query( + 'UPDATE CronStopRequests SET namespace_owner=$namespace,targets=$targets WHERE instance_id=$id', + { + bind: { + id: old.id, + namespace: legacy ? 'crond:1:previous' : null, + targets: JSON.stringify([birth + '-old-command']), + }, + }, + ); const key = require('node:crypto').randomUUID(); - await db.query("INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($key,'[1]',$snapshot)", { - bind: { key, snapshot: JSON.stringify({ docs: [], instances: [{ id: old.id, cron_id: 1, pid: process.pid }], cancelled: [], missingPids: [] }) }, - }); + await db.query( + "INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($key,'[1]',$snapshot)", + { + bind: { + key, + snapshot: JSON.stringify({ + docs: [], + instances: [{ id: old.id, cron_id: 1, pid: process.pid }], + cancelled: [], + missingPids: [], + }), + }, + }, + ); await history.enqueue('replacement', 1, 'manual', null); await history.start('replacement', Date.now(), true); await history.bindCommand('replacement', process.pid); - const fresh = await db.models.RunningInstance.findOne({ order: [['id','DESC']] }); + const fresh = await db.models.RunningInstance.findOne({ + order: [['id', 'DESC']], + }); await db.query(`CREATE TRIGGER fail_retirement BEFORE UPDATE OF status ON RunningInstances WHEN OLD.id=${old.id} BEGIN SELECT json_extract('invalid json','$'); END`); await assert.rejects(service.stop([1], key), /malformed JSON/i); @@ -1885,21 +2947,43 @@ for (const legacy of [false, true]) { assert.deepEqual(await history.pendingStops(), []); assert.deepEqual(await history.pendingStopBatches(), []); if (!legacy) { - const [row] = await db.query("SELECT state,reason,counted,exit_code FROM CronTriggers WHERE id='old'", { type: QueryTypes.SELECT }); - assert.deepEqual(row, { state: 'unknown', reason: 'restart', counted: 0, exit_code: null }); + const [row] = await db.query( + "SELECT state,reason,counted,exit_code FROM CronTriggers WHERE id='old'", + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(row, { + state: 'unknown', + reason: 'restart', + counted: 0, + exit_code: null, + }); } await history.complete('replacement', 'finished', null, 0); - await Promise.all([service.stop([1],key), service.stop([1,1],key), history.complete('replacement','finished',null,0)]); - const stats = await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }); - assert.deepEqual(stats, [{run_count: 1, success_count: 1, fail_count: 0}]); + await Promise.all([ + service.stop([1], key), + service.stop([1, 1], key), + history.complete('replacement', 'finished', null, 0), + ]); + const stats = await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(stats, [ + { run_count: 1, success_count: 1, fail_count: 0 }, + ]); }); } -test('a lost command with a live crond supervisor keeps its real exit receipt', async t => { +test('a lost command with a live crond supervisor keeps its real exit receipt', async (t) => { const { db, models, history } = await fixture(t); const service = retiredProcessFixtureService(db, models); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); - await history.startSystem('exiting', 1, systemOwner(process.pid), systemOwner(process.pid) + '-retired'); + await history.startSystem( + 'exiting', + 1, + systemOwner(process.pid), + systemOwner(process.pid) + '-retired', + ); const old = await db.models.RunningInstance.findOne(); await history.queueInstanceStop(old.id, 1, process.pid); assert.equal((await service.stopInstance(1, old.id)).code, 409); @@ -1911,95 +2995,219 @@ test('a lost command with a live crond supervisor keeps its real exit receipt', }); for (const receipt of ['supervisor', 'shell status', 'shell statistics']) { - test(`late ${receipt} after unknown repairs only its instance and counts once across retries`, async t => { + test(`late ${receipt} after unknown repairs only its instance and counts once across retries`, async (t) => { const { db, history, models, root } = await fixture(t); - const peer = new Sequelize({ dialect: 'sqlite', storage: path.join(root, 'panel.sqlite'), - logging: false, transactionType: Transaction.TYPES.IMMEDIATE }); + const peer = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + transactionType: Transaction.TYPES.IMMEDIATE, + }); t.after(() => peer.close()); const remote = new TriggerHistory(peer); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 1, allow_multiple_instances: 1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); await history.enqueue('old', 1, 'manual', null); await history.start('old'); await history.bindCommand('old', process.pid, '/dev/null'); - if (receipt !== 'supervisor') await db.query("UPDATE CronTriggers SET owner=NULL WHERE id='old'"); + if (receipt !== 'supervisor') + await db.query("UPDATE CronTriggers SET owner=NULL WHERE id='old'"); const old = await db.models.RunningInstance.findOne(); const now = Date.now(); const end = now - 86400000; - await db.query("UPDATE CronTriggers SET state='unknown',reason='restart',started_at=$start,finished_at=$end WHERE id='old'", - { bind: { start: end - 2000, end } }); + await db.query( + "UPDATE CronTriggers SET state='unknown',reason='restart',started_at=$start,finished_at=$end WHERE id='old'", + { bind: { start: end - 2000, end } }, + ); await history.reconcileInstances(); assert.equal((await old.reload()).status, 4); await history.enqueue('new', 1, 'manual', null); await history.start('new'); await history.bindCommand('new', process.pid, '/dev/null'); - await task.update({ status: 0, pid: process.pid, log_path: '/dev/null', last_execution_time: Math.floor(now/1000), last_running_time: 73 }); + await task.update({ + status: 0, + pid: process.pid, + log_path: '/dev/null', + last_execution_time: Math.floor(now / 1000), + last_running_time: 73, + }); const liveTask = (await task.reload()).toJSON(); const service = retiredProcessFixtureService(db, models); const key = require('node:crypto').randomUUID(); - await db.query("INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($key,'[1]',$snapshot)", - { bind: { key, snapshot: JSON.stringify({ docs: [], instances: [{ id: old.id, cron_id: 1, pid: process.pid }], cancelled: [] }) } }); - const status = (code) => remote.reportInstance('old', 1, false, process.pid, '/dev/null', 1, 2, code); + await db.query( + "INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($key,'[1]',$snapshot)", + { + bind: { + key, + snapshot: JSON.stringify({ + docs: [], + instances: [{ id: old.id, cron_id: 1, pid: process.pid }], + cancelled: [], + }), + }, + }, + ); + const status = (code) => + remote.reportInstance( + 'old', + 1, + false, + process.pid, + '/dev/null', + 1, + 2, + code, + ); const stat = (code) => history.recordShellResult('old', 1, code, 2000, now); - const exit = () => receipt === 'supervisor' ? remote.complete('old','failed',null,17) - : receipt === 'shell status' ? status(17) : stat(17); + const exit = () => + receipt === 'supervisor' + ? remote.complete('old', 'failed', null, 17) + : receipt === 'shell status' + ? status(17) + : stat(17); if (receipt === 'supervisor') { await status(0); await stat(0); assert.equal((await old.reload()).status, 4); } - await db.query("CREATE TRIGGER refuse_stat BEFORE INSERT ON CrontabStats BEGIN SELECT json_extract('bad','$'); END"); + await db.query( + "CREATE TRIGGER refuse_stat BEFORE INSERT ON CrontabStats BEGIN SELECT json_extract('bad','$'); END", + ); await assert.rejects(exit(), /malformed JSON/i); assert.equal((await old.reload()).status, 4); - const read = () => db.query("SELECT state,exit_code,finished_at,counted FROM CronTriggers WHERE id='old'", { type: QueryTypes.SELECT }); - assert.deepEqual(await read(), [{ state: 'unknown', exit_code: null, finished_at: end, counted: 0 }]); + const read = () => + db.query( + "SELECT state,exit_code,finished_at,counted FROM CronTriggers WHERE id='old'", + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(await read(), [ + { state: 'unknown', exit_code: null, finished_at: end, counted: 0 }, + ]); await db.query('DROP TRIGGER refuse_stat'); - await Promise.all([exit(), exit(), service.stop([1],key), service.stop([1,1],key)]); - await Promise.all([remote.complete('old','finished',null,0), stat(0), status(0), service.stop([1],key)]); - assert.deepEqual(await read(), [{ state: 'failed', exit_code: 17, finished_at: end, counted: 1 }]); + await Promise.all([ + exit(), + exit(), + service.stop([1], key), + service.stop([1, 1], key), + ]); + await Promise.all([ + remote.complete('old', 'finished', null, 0), + stat(0), + status(0), + service.stop([1], key), + ]); + assert.deepEqual(await read(), [ + { state: 'failed', exit_code: 17, finished_at: end, counted: 1 }, + ]); await old.reload(); - assert.deepEqual([old.status,old.exit_code,old.finished_at], [3,17,Math.floor(end/1000)]); + assert.deepEqual( + [old.status, old.exit_code, old.finished_at], + [3, 17, Math.floor(end / 1000)], + ); assert.deepEqual((await task.reload()).toJSON(), liveTask); - assert.equal((await history.recent(1, 0)).find(x => x.id === 'new').state, 'running'); - const [totals] = await db.query('SELECT date,run_count,success_count,fail_count,total_time FROM CrontabStats', { type: QueryTypes.SELECT }); - assert.deepEqual(totals, { date: require('dayjs')(end).format('YYYY-MM-DD'), run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 }); - await history.complete('new','finished',null,0); + assert.equal( + (await history.recent(1, 0)).find((x) => x.id === 'new').state, + 'running', + ); + const [totals] = await db.query( + 'SELECT date,run_count,success_count,fail_count,total_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(totals, { + date: require('dayjs')(end).format('YYYY-MM-DD'), + run_count: 1, + success_count: 0, + fail_count: 1, + total_time: 2000, + }); + await history.complete('new', 'finished', null, 0); const after = (await task.reload()).toJSON(); await exit(); assert.deepEqual((await task.reload()).toJSON(), after); }); } -test('untagged legacy exits need a unique run when a newer instance shares the PID and log', async t => { +test('untagged legacy exits need a unique run when a newer instance shares the PID and log', async (t) => { const { db, models } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 0, pid: 1350, - log_path: '/dev/null', last_execution_time: 202, last_running_time: 55 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + pid: 1350, + log_path: '/dev/null', + last_execution_time: 202, + last_running_time: 55, + }); const before = (await task.reload()).toJSON(); const Instance = db.models.RunningInstance; - const old = await Instance.create({ cron_id: 1, pid: 1350, status: 4, log_path: '/dev/null', started_at: 101, finished_at: 150 }); - const fresh = await Instance.create({ cron_id: 1, pid: 1350, status: 0, log_path: '/dev/null', started_at: 202 }); + const old = await Instance.create({ + cron_id: 1, + pid: 1350, + status: 4, + log_path: '/dev/null', + started_at: 101, + finished_at: 150, + }); + const fresh = await Instance.create({ + cron_id: 1, + pid: 1350, + status: 0, + log_path: '/dev/null', + started_at: 202, + }); const service = new (load('back/services/cron.ts', { - '../config': {}, '../shared/logPath': { resolveLogPath() {} }, '../data/cron': models, - '../data/runningInstance': { RunningInstanceModel: Instance, InstanceStatus: { running: 0, finished: 1, stopped: 2, error: 3, unknown: 4 } }, - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../shared/pLimit': {}, '../config/util': {}, '../shared/i18n': { t: key => key }, + '../config': {}, + '../shared/logPath': { resolveLogPath() {} }, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: Instance, + InstanceStatus: { + running: 0, + finished: 1, + stopped: 2, + error: 3, + unknown: 4, + }, + }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../cron/execution/cronLimit': {}, + '../config/util': {}, + '../shared/i18n': { t: (key) => key }, }).default)(logger); - const send = (seconds, code) => service.status({ ids: [1], status: 1, pid: 1350, log_path: '/dev/null', - last_execution_time: seconds, last_running_time: 9, exit_code: code }); + const send = (seconds, code) => + service.status({ + ids: [1], + status: 1, + pid: 1350, + log_path: '/dev/null', + last_execution_time: seconds, + last_running_time: 9, + exit_code: code, + }); // A stale PID-only exit is still unsafe after the original row has expired. await old.destroy(); - await send(0,17); + await send(0, 17); assert.equal((await fresh.reload()).status, 0); await Instance.create(old.toJSON()); - await send(0,17); + await send(0, 17); assert.equal((await old.reload()).status, 4); - await send(101,17); - await send(101,0); - assert.deepEqual([(await old.reload()).status, old.exit_code, old.finished_at], [3,17,150]); + await send(101, 17); + await send(101, 0); + assert.deepEqual( + [(await old.reload()).status, old.exit_code, old.finished_at], + [3, 17, 150], + ); assert.equal((await fresh.reload()).status, 0); assert.deepEqual((await task.reload()).toJSON(), before); }); -test('a legacy exit without a code can be resolved by a later statistics receipt', async t => { +test('a legacy exit without a code can be resolved by a later statistics receipt', async (t) => { const { db, history, models } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', status: 0 }); const id = 'system-1-legacy'; @@ -2011,698 +3219,1638 @@ test('a legacy exit without a code can be resolved by a later statistics receipt await history.recordShellResult(id, 1, 0, 1000, Date.now()); const [row] = await history.recent(1, 0); const instance = await db.models.RunningInstance.findOne(); - assert.deepEqual([row.state, row.exit_code, row.finished_at, instance.status, instance.exit_code], - ['failed', 9, unknown.finished_at, 3, 9]); - assert.deepEqual(await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }), - [{ run_count: 1, success_count: 0, fail_count: 1 }]); + assert.deepEqual( + [ + row.state, + row.exit_code, + row.finished_at, + instance.status, + instance.exit_code, + ], + ['failed', 9, unknown.finished_at, 3, 9], + ); + assert.deepEqual( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [{ run_count: 1, success_count: 0, fail_count: 1 }], + ); }); -test('legacy status retries commit one receipt per physical run, including equal results and a lost response', async t => { +test('legacy status retries commit one receipt per physical run, including equal results and a lost response', async (t) => { const { db, models, history } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + }); const service = new (load('back/services/cron.ts', { - './cronProcess': { ...require('../../back/shared/cronProcess'), legacyProcessOwner: pid => 'test:' + pid }, - '../config': {}, '../shared/logPath': { resolveLogPath() {} }, '../data/cron': models, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running:0, finished:1, stopped:2, error:3, unknown:4 } }, - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../shared/pLimit': {}, '../config/util': {}, '../shared/i18n': { t: key => key }, + '../cron/execution/cronProcess': { + ...require('../../back/cron/execution/cronProcess'), + legacyProcessOwner: (pid) => 'test:' + pid, + }, + '../config': {}, + '../shared/logPath': { resolveLogPath() {} }, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { + running: 0, + finished: 1, + stopped: 2, + error: 3, + unknown: 4, + }, + }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../cron/execution/cronLimit': {}, + '../config/util': {}, + '../shared/i18n': { t: (key) => key }, }).default)(logger); - const send = (pid, status, code) => service.status({ ids:[1], status, pid, log_path:'/dev/null', - last_execution_time: 100, last_running_time: status ? 2 : 0, exit_code: code }); - await Promise.all([send(111,0),send(111,0)]); - await send(222,0); - await db.query("CREATE TRIGGER refuse_stat BEFORE INSERT ON CrontabStats BEGIN SELECT json_extract('bad','$'); END"); - await assert.rejects(send(222,1,7), /malformed JSON/); - assert.equal((await db.models.RunningInstance.findOne({where:{pid:222}})).status,0); - assert.deepEqual((await history.recent(1,0)).map(row => row.state), ['running','running']); + const send = (pid, status, code) => + service.status({ + ids: [1], + status, + pid, + log_path: '/dev/null', + last_execution_time: 100, + last_running_time: status ? 2 : 0, + exit_code: code, + }); + await Promise.all([send(111, 0), send(111, 0)]); + await send(222, 0); + await db.query( + "CREATE TRIGGER refuse_stat BEFORE INSERT ON CrontabStats BEGIN SELECT json_extract('bad','$'); END", + ); + await assert.rejects(send(222, 1, 7), /malformed JSON/); + assert.equal( + (await db.models.RunningInstance.findOne({ where: { pid: 222 } })).status, + 0, + ); + assert.deepEqual( + (await history.recent(1, 0)).map((row) => row.state), + ['running', 'running'], + ); await db.query('DROP TRIGGER refuse_stat'); - await Promise.all([send(222,1,7),send(222,1,7)]); - await send(222,0); - assert.equal((await task.reload()).pid,111); - await send(111,1); // An exit without a result cannot be counted as successful. - await Promise.all([send(111,1,7),send(111,1,7)]); - assert.equal(await db.models.RunningInstance.count(),2); - const rows = await history.recent(1,0); - assert.equal(rows.length,2); - assert.ok(rows.every(r => r.source === 'legacy' && r.state === 'failed' && r.exit_code === 7)); - assert.deepEqual(await db.query('SELECT run_count,fail_count,success_count,total_time,max_time FROM CrontabStats', {type:QueryTypes.SELECT}), - [{run_count:2,fail_count:2,success_count:0,total_time:4000,max_time:2000}]); + await Promise.all([send(222, 1, 7), send(222, 1, 7)]); + await send(222, 0); + assert.equal((await task.reload()).pid, 111); + await send(111, 1); // An exit without a result cannot be counted as successful. + await Promise.all([send(111, 1, 7), send(111, 1, 7)]); + assert.equal(await db.models.RunningInstance.count(), 2); + const rows = await history.recent(1, 0); + assert.equal(rows.length, 2); + assert.ok( + rows.every( + (r) => r.source === 'legacy' && r.state === 'failed' && r.exit_code === 7, + ), + ); + assert.deepEqual( + await db.query( + 'SELECT run_count,fail_count,success_count,total_time,max_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [ + { + run_count: 2, + fail_count: 2, + success_count: 0, + total_time: 4000, + max_time: 2000, + }, + ], + ); // A legacy wrapper belonging to a managed command is not another execution. - await history.enqueue('managed',1,'manual',null); + await history.enqueue('managed', 1, 'manual', null); await history.start('managed'); - await history.bindCommand('managed',process.pid); - const wrapperStart = Math.floor(Date.now()/1000); - const wrapper = (status, code) => service.status({ids:[1],status,pid:process.pid,log_path:'/dev/null', - last_execution_time:wrapperStart,last_running_time:2,exit_code:code}); + await history.bindCommand('managed', process.pid); + const wrapperStart = Math.floor(Date.now() / 1000); + const wrapper = (status, code) => + service.status({ + ids: [1], + status, + pid: process.pid, + log_path: '/dev/null', + last_execution_time: wrapperStart, + last_running_time: 2, + exit_code: code, + }); await wrapper(0); - await wrapper(1,9); - assert.equal(await db.models.RunningInstance.count(),3); - assert.equal((await history.recent(1,0)).find(r=>r.id==='managed').state,'running'); - await history.complete('managed','finished',null,0); + await wrapper(1, 9); + assert.equal(await db.models.RunningInstance.count(), 3); + assert.equal( + (await history.recent(1, 0)).find((r) => r.id === 'managed').state, + 'running', + ); + await history.complete('managed', 'finished', null, 0); await wrapper(0); - await wrapper(1,9); - assert.equal(await db.models.RunningInstance.count(),3); - const [totals] = await db.query('SELECT run_count,fail_count,success_count FROM CrontabStats',{type:QueryTypes.SELECT}); - assert.deepEqual(totals,{run_count:3,fail_count:2,success_count:1}); + await wrapper(1, 9); + assert.equal(await db.models.RunningInstance.count(), 3); + const [totals] = await db.query( + 'SELECT run_count,fail_count,success_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(totals, { run_count: 3, fail_count: 2, success_count: 1 }); }); -test('legacy start and exit delivered out of order cannot resurrect a run or overwrite its PID replacement', async t => { +test('legacy start and exit delivered out of order cannot resurrect a run or overwrite its PID replacement', async (t) => { const { db, models, history } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + }); const instances = db.models.RunningInstance; const service = new (load('back/services/cron.ts', { - './cronProcess': { ...require('../../back/shared/cronProcess'), legacyProcessOwner: pid => 'test:' + pid }, - '../config': {}, '../shared/logPath': { resolveLogPath() {} }, '../data/cron': models, - '../data/runningInstance': { RunningInstanceModel: instances, InstanceStatus: { running:0, finished:1, stopped:2, error:3, unknown:4 } }, - '../schedule/client': {}, '../loaders/logger': logger, '../shared/logStreamManager': {}, - '../shared/pLimit': {}, '../config/util': {}, '../shared/i18n': { t: key => key }, + '../cron/execution/cronProcess': { + ...require('../../back/cron/execution/cronProcess'), + legacyProcessOwner: (pid) => 'test:' + pid, + }, + '../config': {}, + '../shared/logPath': { resolveLogPath() {} }, + '../data/cron': models, + '../data/runningInstance': { + RunningInstanceModel: instances, + InstanceStatus: { + running: 0, + finished: 1, + stopped: 2, + error: 3, + unknown: 4, + }, + }, + '../schedule/client': {}, + '../loaders/logger': logger, + '../shared/logStreamManager': {}, + '../cron/execution/cronLimit': {}, + '../config/util': {}, + '../shared/i18n': { t: (key) => key }, }).default)(logger); - const now = Math.floor(Date.now()/1000); - const send = (seconds, status, code, trigger_id) => service.status({ ids:[1], status, pid: 31415, - log_path:'shared.log', last_execution_time:seconds, last_running_time:status ? 2 : 0, exit_code:code, trigger_id }); - const counts = async () => (await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', {type: QueryTypes.SELECT}))[0]; - await send(now,0); + const now = Math.floor(Date.now() / 1000); + const send = (seconds, status, code, trigger_id) => + service.status({ + ids: [1], + status, + pid: 31415, + log_path: 'shared.log', + last_execution_time: seconds, + last_running_time: status ? 2 : 0, + exit_code: code, + trigger_id, + }); + const counts = async () => + ( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ) + )[0]; + await send(now, 0); const current = (await task.reload()).toJSON(); - for (const [seconds,id] of [[now-20, undefined],[now-10,'system-cli-older']]) { - await send(seconds,1,17,id); - await Promise.all([send(seconds,0,undefined,id),send(seconds,0,undefined,id),send(seconds,1,0,id)]); - const row = await instances.findOne({where:{started_at:seconds}}); + for (const [seconds, id] of [ + [now - 20, undefined], + [now - 10, 'system-cli-older'], + ]) { + await send(seconds, 1, 17, id); + await Promise.all([ + send(seconds, 0, undefined, id), + send(seconds, 0, undefined, id), + send(seconds, 1, 0, id), + ]); + const row = await instances.findOne({ where: { started_at: seconds } }); assert.ok(row); - assert.deepEqual([row.status,row.exit_code], [3,17]); + assert.deepEqual([row.status, row.exit_code], [3, 17]); assert.deepEqual((await task.reload()).toJSON(), current); } - assert.equal(await instances.count({where:{status:0}}),1); - await Promise.all([send(now,1,0),send(now,0),send(now,1,0)]); - assert.deepEqual(await counts(), { run_count:3, success_count:1, fail_count:2 }); - assert.equal((await task.reload()).status,1); - // The newer start is proof that the old PID has exited even if its exit packet is delayed. - await send(now+1,0); - await send(now+2,0); - assert.deepEqual((await instances.findAll({where:{status:0}})).map(row => row.started_at),[now+2]); - assert.equal((await instances.findOne({where:{started_at:now+1}})).status,4); - await Promise.all([send(now+1,0),send(now+1,1,9)]); - assert.equal((await task.reload()).last_execution_time,now+2); - await send(now+2,1,0); - const finalCounts = { run_count:5, success_count:2, fail_count:3 }; - assert.deepEqual(await counts(),finalCounts); - const cutoff = (now+3)*1000; - await db.transaction(async tx => { - await instances.destroy({where:{},transaction:tx}); - await history.deleteExpired(cutoff,tx); + assert.equal(await instances.count({ where: { status: 0 } }), 1); + await Promise.all([send(now, 1, 0), send(now, 0), send(now, 1, 0)]); + assert.deepEqual(await counts(), { + run_count: 3, + success_count: 1, + fail_count: 2, }); - await Promise.all([send(now-20,0),send(now-20,1,17),send(now-10,0,undefined,'system-cli-older')]); - assert.equal(await instances.count(),0); - assert.equal((await history.recent(1,0)).length,0); - assert.deepEqual(await counts(),finalCounts); + assert.equal((await task.reload()).status, 1); + // The newer start is proof that the old PID has exited even if its exit packet is delayed. + await send(now + 1, 0); + await send(now + 2, 0); + assert.deepEqual( + (await instances.findAll({ where: { status: 0 } })).map( + (row) => row.started_at, + ), + [now + 2], + ); + assert.equal( + (await instances.findOne({ where: { started_at: now + 1 } })).status, + 4, + ); + await Promise.all([send(now + 1, 0), send(now + 1, 1, 9)]); + assert.equal((await task.reload()).last_execution_time, now + 2); + await send(now + 2, 1, 0); + const finalCounts = { run_count: 5, success_count: 2, fail_count: 3 }; + assert.deepEqual(await counts(), finalCounts); + const cutoff = (now + 3) * 1000; + await db.transaction(async (tx) => { + await instances.destroy({ where: {}, transaction: tx }); + await history.deleteExpired(cutoff, tx); + }); + await Promise.all([ + send(now - 20, 0), + send(now - 20, 1, 17), + send(now - 10, 0, undefined, 'system-cli-older'), + ]); + assert.equal(await instances.count(), 0); + assert.equal((await history.recent(1, 0)).length, 0); + assert.deepEqual(await counts(), finalCounts); }); -test('a legacy start with a dead or newer PID is historical even before the replacement reports', async t => { +test('a legacy start with a dead or newer PID is historical even before the replacement reports', async (t) => { const { history, db, models } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command:'true', status:1 }); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + }); for (const pid of [process.pid, 2147483000]) { - await history.reportLegacy(1,true,pid,'shared.log',100,0); - assert.equal((await db.models.RunningInstance.findOne({where:{pid}})).status,4); - assert.equal((await task.reload()).status,1); - await history.reportLegacy(1,false,pid,'shared.log',100,1,17); - await history.reportLegacy(1,true,pid,'shared.log',100,0); + await history.reportLegacy(1, true, pid, 'shared.log', 100, 0); + assert.equal( + (await db.models.RunningInstance.findOne({ where: { pid } })).status, + 4, + ); + assert.equal((await task.reload()).status, 1); + await history.reportLegacy(1, false, pid, 'shared.log', 100, 1, 17); + await history.reportLegacy(1, true, pid, 'shared.log', 100, 0); } - assert.deepEqual((await history.recent(1,0)).map(row=>[row.state,row.exit_code]),[['failed',17],['failed',17]]); - assert.deepEqual(await db.query('SELECT run_count,fail_count FROM CrontabStats',{type:QueryTypes.SELECT}), - [{run_count:2,fail_count:2}]); + assert.deepEqual( + (await history.recent(1, 0)).map((row) => [row.state, row.exit_code]), + [ + ['failed', 17], + ['failed', 17], + ], + ); + assert.deepEqual( + await db.query('SELECT run_count,fail_count FROM CrontabStats', { + type: QueryTypes.SELECT, + }), + [{ run_count: 2, fail_count: 2 }], + ); }); -test('two identified executions and one legacy execution can share a task, PID, second and log', async t => { +test('two identified executions and one legacy execution can share a task, PID, second and log', async (t) => { const { db, models, history } = await fixture(t); await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); - const pid = process.pid, log = 'same.log', seconds = Math.floor(Date.now() / 1000); - const ids = Array.from({ length: 2 }, () => 'client-' + require('node:crypto').randomUUID()); - const tagged = (id, running, code) => history.reportInstance(id, 1, running, pid, log, seconds, 0, code); - const legacy = (running, code) => history.reportLegacy(1, running, pid, log, seconds, 0, code); + const pid = process.pid, + log = 'same.log', + seconds = Math.floor(Date.now() / 1000); + const ids = Array.from( + { length: 2 }, + () => 'client-' + require('node:crypto').randomUUID(), + ); + const tagged = (id, running, code) => + history.reportInstance(id, 1, running, pid, log, seconds, 0, code); + const legacy = (running, code) => + history.reportLegacy(1, running, pid, log, seconds, 0, code); await tagged(ids[0], true); await legacy(true); await tagged(ids[1], false, 0); // exit beats the initial start - await Promise.all([tagged(ids[1], true), legacy(false, 17), tagged(ids[0], true)]); - await Promise.all([tagged(ids[0], false, 0), legacy(true), legacy(false, 17), - history.recordShellResult(ids[1], 1, 0, 0, Date.now())]); + await Promise.all([ + tagged(ids[1], true), + legacy(false, 17), + tagged(ids[0], true), + ]); + await Promise.all([ + tagged(ids[0], false, 0), + legacy(true), + legacy(false, 17), + history.recordShellResult(ids[1], 1, 0, 0, Date.now()), + ]); await history.recordShellResult(ids[0], 1, 0, 0, Date.now()); - const rows = await db.query('SELECT t.source,t.id,t.state,t.counted,i.exit_code,i.status FROM CronTriggers t JOIN RunningInstances i ON t.instance_id=i.id', { type: QueryTypes.SELECT }); + const rows = await db.query( + 'SELECT t.source,t.id,t.state,t.counted,i.exit_code,i.status FROM CronTriggers t JOIN RunningInstances i ON t.instance_id=i.id', + { type: QueryTypes.SELECT }, + ); assert.equal(rows.length, 3); - for (const id of ids) assert.deepEqual(rows.find(r => r.id === id), { - source: 'client', id, state: 'finished', counted: 1, exit_code: 0, status: 1 }); - assert.deepEqual(rows.filter(r => r.source === 'legacy').map(r => [r.state,r.counted,r.exit_code,r.status]), - [['failed',1,17,3]]); - assert.deepEqual(await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats', { type: QueryTypes.SELECT }), - [{ run_count: 3, success_count: 2, fail_count: 1 }]); + for (const id of ids) + assert.deepEqual( + rows.find((r) => r.id === id), + { + source: 'client', + id, + state: 'finished', + counted: 1, + exit_code: 0, + status: 1, + }, + ); + assert.deepEqual( + rows + .filter((r) => r.source === 'legacy') + .map((r) => [r.state, r.counted, r.exit_code, r.status]), + [['failed', 1, 17, 3]], + ); + assert.deepEqual( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [{ run_count: 3, success_count: 2, fail_count: 1 }], + ); }); -test('when a later run exits first its start remains the last run time while an earlier instance stays active', async t => { +test('when a later run exits first its start remains the last run time while an earlier instance stays active', async (t) => { const { history, models } = await fixture(t); - const task = await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); - const [early, late] = [1,2].map(() => 'client-' + require('node:crypto').randomUUID()); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + }); + const [early, late] = [1, 2].map( + () => 'client-' + require('node:crypto').randomUUID(), + ); const send = (id, running, pid, log, start) => - history.reportInstance(id, 1, running, pid, log, start, running ? 0 : id === late ? 7 : 15, running ? undefined : 0); + history.reportInstance( + id, + 1, + running, + pid, + log, + start, + running ? 0 : id === late ? 7 : 15, + running ? undefined : 0, + ); await send(early, true, 88801, 'early.log', 100); await send(late, true, 88802, 'late.log', 101); await send(late, false, 88802, 'late.log', 101); await task.reload(); - assert.deepEqual([task.pid, task.log_path, task.last_execution_time], [88801, 'early.log', 101]); + assert.deepEqual( + [task.pid, task.log_path, task.last_execution_time], + [88801, 'early.log', 101], + ); await send(early, false, 88801, 'early.log', 100); await task.reload(); - assert.deepEqual([task.status, task.last_execution_time, task.last_running_time], [1,101,7]); + assert.deepEqual( + [task.status, task.last_execution_time, task.last_running_time], + [1, 101, 7], + ); }); -test('same-second summaries stay with the last observed start through late exits, zero elapsed and retries', async t => { +test('same-second summaries stay with the last observed start through late exits, zero elapsed and retries', async (t) => { const { db, history, models } = await fixture(t); - const task = await models.CrontabModel.create({ id:1, command:'true', status:1, last_execution_time:5, last_running_time:90 }); - const second = Math.floor(Date.now()/1000); - const pid = process.pid, log = 'mixed.log'; + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + last_execution_time: 5, + last_running_time: 90, + }); + const second = Math.floor(Date.now() / 1000); + const pid = process.pid, + log = 'mixed.log'; const id = () => 'client-' + require('node:crypto').randomUUID(); - const newest = id(), exitFirst = id(); - const tagged = (key,running,elapsed,sec=second) => history.reportInstance(key,1,running,pid,log,sec,elapsed,running ? undefined : 0); - const old = (running,elapsed) => history.reportLegacy(1,running,pid,log,second,elapsed,running ? undefined : 17); + const newest = id(), + exitFirst = id(); + const tagged = (key, running, elapsed, sec = second) => + history.reportInstance( + key, + 1, + running, + pid, + log, + sec, + elapsed, + running ? undefined : 0, + ); + const old = (running, elapsed) => + history.reportLegacy( + 1, + running, + pid, + log, + second, + elapsed, + running ? undefined : 17, + ); const summary = async () => { await task.reload(); - return [task.last_execution_time,task.last_running_time,task.last_instance_id]; + return [ + task.last_execution_time, + task.last_running_time, + task.last_instance_id, + ]; }; - await old(true,0); - await tagged(newest,true,0); - const [record] = await db.query('SELECT instance_id FROM CronTriggers WHERE id=$id',{bind:{id:newest},type:QueryTypes.SELECT}); - const expected = [second,null,record.instance_id]; - assert.deepEqual(await summary(),expected); - await old(false,19); - await tagged(exitFirst,false,50); - await tagged(exitFirst,true,0); - assert.deepEqual(await summary(),expected); - await tagged(newest,false,0); - await history.recordShellResult(newest,1,0,75000,Date.now()); - await old(false,19); - assert.deepEqual(await summary(),[second,0,record.instance_id]); - const next=id(); - await tagged(next,false,27,second+1); - await tagged(next,true,0,second+1); - assert.deepEqual((await summary()).slice(0,2),[second+1,27]); - assert.deepEqual(await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats',{type:QueryTypes.SELECT}), - [{run_count:4,success_count:3,fail_count:1}]); + await old(true, 0); + await tagged(newest, true, 0); + const [record] = await db.query( + 'SELECT instance_id FROM CronTriggers WHERE id=$id', + { bind: { id: newest }, type: QueryTypes.SELECT }, + ); + const expected = [second, null, record.instance_id]; + assert.deepEqual(await summary(), expected); + await old(false, 19); + await tagged(exitFirst, false, 50); + await tagged(exitFirst, true, 0); + assert.deepEqual(await summary(), expected); + await tagged(newest, false, 0); + await history.recordShellResult(newest, 1, 0, 75000, Date.now()); + await old(false, 19); + assert.deepEqual(await summary(), [second, 0, record.instance_id]); + const next = id(); + await tagged(next, false, 27, second + 1); + await tagged(next, true, 0, second + 1); + assert.deepEqual((await summary()).slice(0, 2), [second + 1, 27]); + assert.deepEqual( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [{ run_count: 4, success_count: 3, fail_count: 1 }], + ); }); -test('panel upgrade adopts outstanding legacy instances and a delayed exit settles its original row', async t => { +test('panel upgrade adopts outstanding legacy instances and a delayed exit settles its original row', async (t) => { const { db, models, history } = await fixture(t); - const start = Math.floor(Date.now()/1000); - const task = await models.CrontabModel.create({id:1, command:'true',status:0,last_running_time:58,last_execution_time:start}); - const prior = await db.models.RunningInstance.create({cron_id:1,status:0,pid:process.pid,log_path:'old.log',started_at:start}); - const dead = await db.models.RunningInstance.create({cron_id:1,status:0,pid:2147483000,log_path:'gone.log',started_at:start-5}); - await history.reconcileInstances(); await history.reconcileInstances(); - assert.equal((await prior.reload()).status,0); - assert.equal((await dead.reload()).status,4); - await history.reportLegacy(1,false,dead.pid,dead.log_path,start-5,38,17); - await history.reportLegacy(1,false,process.pid,'old.log',start,6,0); - await history.reportLegacy(1,false,process.pid,'old.log',start,6,0); - assert.equal(await db.models.RunningInstance.count(),2); - assert.deepEqual((await history.recent(1,0)).map(r=>r.state),['finished','failed']); - assert.deepEqual([(await task.reload()).last_instance_id,task.last_running_time],[prior.id,6]); - assert.deepEqual(await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats',{type:QueryTypes.SELECT}), - [{run_count:2,success_count:1,fail_count:1}]); + const start = Math.floor(Date.now() / 1000); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + last_running_time: 58, + last_execution_time: start, + }); + const prior = await db.models.RunningInstance.create({ + cron_id: 1, + status: 0, + pid: process.pid, + log_path: 'old.log', + started_at: start, + }); + const dead = await db.models.RunningInstance.create({ + cron_id: 1, + status: 0, + pid: 2147483000, + log_path: 'gone.log', + started_at: start - 5, + }); + await history.reconcileInstances(); + await history.reconcileInstances(); + assert.equal((await prior.reload()).status, 0); + assert.equal((await dead.reload()).status, 4); + await history.reportLegacy( + 1, + false, + dead.pid, + dead.log_path, + start - 5, + 38, + 17, + ); + await history.reportLegacy(1, false, process.pid, 'old.log', start, 6, 0); + await history.reportLegacy(1, false, process.pid, 'old.log', start, 6, 0); + assert.equal(await db.models.RunningInstance.count(), 2); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => r.state), + ['finished', 'failed'], + ); + assert.deepEqual( + [(await task.reload()).last_instance_id, task.last_running_time], + [prior.id, 6], + ); + assert.deepEqual( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [{ run_count: 2, success_count: 1, fail_count: 1 }], + ); }); for (const newStartsFirst of [true, false]) { - test(`same-second upgrade reconciles settled, gone and live siblings when the new start arrives ${newStartsFirst ? 'before' : 'after'} adoption`, async t => { + test(`same-second upgrade reconciles settled, gone and live siblings when the new start arrives ${ + newStartsFirst ? 'before' : 'after' + } adoption`, async (t) => { const { history, db, models, stats } = await fixture(t); - const second = Math.floor(Date.now()/1000) - 1; - const task = await models.CrontabModel.create({id:1, command:'true',status:0,last_execution_time:second}); + const second = Math.floor(Date.now() / 1000) - 1; + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + last_execution_time: second, + }); const instances = db.models.RunningInstance; - const create = (pid, log_path, status=0, extra={}) => instances.create({ - cron_id:1, started_at:second, pid, log_path, status, ...extra }); + const create = (pid, log_path, status = 0, extra = {}) => + instances.create({ + cron_id: 1, + started_at: second, + pid, + log_path, + status, + ...extra, + }); const gone = await create(2147483000, 'shared.log'); const live = await create(process.pid, 'shared.log'); - const settled = await create(2147483001, 'shared.log',1,{finished_at:second+1,exit_code:0}); - await stats.CrontabStatModel.create({ref_id:1,date:require('dayjs')().format('YYYY-MM-DD'),run_count:1,success_count:1}); + const settled = await create(2147483001, 'shared.log', 1, { + finished_at: second + 1, + exit_code: 0, + }); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: require('dayjs')().format('YYYY-MM-DD'), + run_count: 1, + success_count: 1, + }); const key = 'client-' + require('node:crypto').randomUUID(); - const reportNew = running => history.reportInstance(key,1,running,88802,'new.log',second,running ? 0 : 2,running ? undefined : 0); - const reportOld = (row, elapsed, code) => history.reportLegacy(1,false,row.pid,row.log_path,second,elapsed,code); + const reportNew = (running) => + history.reportInstance( + key, + 1, + running, + 88802, + 'new.log', + second, + running ? 0 : 2, + running ? undefined : 0, + ); + const reportOld = (row, elapsed, code) => + history.reportLegacy( + 1, + false, + row.pid, + row.log_path, + second, + elapsed, + code, + ); if (newStartsFirst) await reportNew(true); await history.reconcileInstances(); - const snapshot = async () => db.query(`SELECT instance_id,state,counted,exit_code FROM CronTriggers - ORDER BY instance_id`,{type:QueryTypes.SELECT}); - assert.deepEqual((await snapshot()).slice(0,3).map(r=>[r.instance_id,r.state,r.counted]),[ - [gone.id,'unknown',0],[live.id,'running',0],[settled.id,'finished',1]]); + const snapshot = async () => + db.query( + `SELECT instance_id,state,counted,exit_code FROM CronTriggers + ORDER BY instance_id`, + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + (await snapshot()) + .slice(0, 3) + .map((r) => [r.instance_id, r.state, r.counted]), + [ + [gone.id, 'unknown', 0], + [live.id, 'running', 0], + [settled.id, 'finished', 1], + ], + ); await task.reload(); if (!newStartsFirst) { - assert.deepEqual([task.last_instance_id,task.last_running_time,task.pid],[settled.id,1,live.pid]); + assert.deepEqual( + [task.last_instance_id, task.last_running_time, task.pid], + [settled.id, 1, live.pid], + ); await reportNew(true); } - const current = await instances.findOne({where:{pid:88802}}); + const current = await instances.findOne({ where: { pid: 88802 } }); await task.reload(); - assert.deepEqual([task.last_instance_id,task.last_running_time,task.pid,task.log_path],[current.id,null,88802,'new.log']); + assert.deepEqual( + [task.last_instance_id, task.last_running_time, task.pid, task.log_path], + [current.id, null, 88802, 'new.log'], + ); await reportNew(false); - assert.deepEqual([(await task.reload()).pid,task.last_running_time],[live.pid,2]); - await Promise.all([reportOld(gone,27,17),reportOld(live,33,9),reportOld(settled,51,17), - history.reconcileInstances(),reportOld(gone,27,17),reportOld(live,33,9)]); + assert.deepEqual( + [(await task.reload()).pid, task.last_running_time], + [live.pid, 2], + ); + await Promise.all([ + reportOld(gone, 27, 17), + reportOld(live, 33, 9), + reportOld(settled, 51, 17), + history.reconcileInstances(), + reportOld(gone, 27, 17), + reportOld(live, 33, 9), + ]); await history.reconcileInstances(); - assert.deepEqual((await snapshot()).map(r=>[r.instance_id,r.state,r.counted,r.exit_code]),[ - [gone.id,'failed',1,17],[live.id,'failed',1,9],[settled.id,'finished',1,0],[current.id,'finished',1,0]]); + assert.deepEqual( + (await snapshot()).map((r) => [ + r.instance_id, + r.state, + r.counted, + r.exit_code, + ]), + [ + [gone.id, 'failed', 1, 17], + [live.id, 'failed', 1, 9], + [settled.id, 'finished', 1, 0], + [current.id, 'finished', 1, 0], + ], + ); await task.reload(); - assert.deepEqual([task.status,task.pid,task.last_execution_time,task.last_instance_id,task.last_running_time],[1,null,second,current.id,2]); - assert.deepEqual(await db.query('SELECT run_count,success_count,fail_count FROM CrontabStats',{type:QueryTypes.SELECT}), - [{run_count:4,success_count:2,fail_count:2}]); + assert.deepEqual( + [ + task.status, + task.pid, + task.last_execution_time, + task.last_instance_id, + task.last_running_time, + ], + [1, null, second, current.id, 2], + ); + assert.deepEqual( + await db.query( + 'SELECT run_count,success_count,fail_count FROM CrontabStats', + { type: QueryTypes.SELECT }, + ), + [{ run_count: 4, success_count: 2, fail_count: 2 }], + ); }); } -test('an exit delivered before adoption keeps the original start order and elapsed time', async t => { +test('an exit delivered before adoption keeps the original start order and elapsed time', async (t) => { const { history, db, models } = await fixture(t); const second = Math.floor(Date.now() / 1000); - const task = await models.CrontabModel.create({id:1, command:'true',status:0,last_execution_time:second}); - const first = await db.models.RunningInstance.create({cron_id:1,pid:process.pid,started_at:second,log_path:'first.log'}); - const last = await db.models.RunningInstance.create({cron_id:1,pid:2147483000,started_at:second,log_path:'last.log'}); - await history.reportLegacy(1,false,last.pid,last.log_path,second,7,17); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 0, + last_execution_time: second, + }); + const first = await db.models.RunningInstance.create({ + cron_id: 1, + pid: process.pid, + started_at: second, + log_path: 'first.log', + }); + const last = await db.models.RunningInstance.create({ + cron_id: 1, + pid: 2147483000, + started_at: second, + log_path: 'last.log', + }); + await history.reportLegacy(1, false, last.pid, last.log_path, second, 7, 17); await history.reconcileInstances(); - await history.reportLegacy(1,true,last.pid,last.log_path,second,0); - await history.reportLegacy(1,false,last.pid,last.log_path,second,99,0); + await history.reportLegacy(1, true, last.pid, last.log_path, second, 0); + await history.reportLegacy(1, false, last.pid, last.log_path, second, 99, 0); await task.reload(); - assert.deepEqual([task.pid,task.log_path,task.last_instance_id,task.last_execution_time,task.last_running_time], - [first.pid,first.log_path,last.id,second,7]); - assert.deepEqual((await history.recent(1,0)).map(r=>[r.log_path,r.state,r.exit_code]).sort(),[ - ['first.log','running',null],['last.log','failed',17]]); - assert.deepEqual(await db.query('SELECT run_count,fail_count FROM CrontabStats',{type:QueryTypes.SELECT}), - [{run_count:1,fail_count:1}]); + assert.deepEqual( + [ + task.pid, + task.log_path, + task.last_instance_id, + task.last_execution_time, + task.last_running_time, + ], + [first.pid, first.log_path, last.id, second, 7], + ); + assert.deepEqual( + (await history.recent(1, 0)) + .map((r) => [r.log_path, r.state, r.exit_code]) + .sort(), + [ + ['first.log', 'running', null], + ['last.log', 'failed', 17], + ], + ); + assert.deepEqual( + await db.query('SELECT run_count,fail_count FROM CrontabStats', { + type: QueryTypes.SELECT, + }), + [{ run_count: 1, fail_count: 1 }], + ); }); -test('upgrade repairs missing anonymous daily counts once without replaying elapsed time or a new client', async t => { +test('upgrade repairs missing anonymous daily counts once without replaying elapsed time or a new client', async (t) => { const { db, models, stats, history } = await fixture(t); - const { migrateSchema } = require('../../back/shared/schemaMigrations'); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); - const task = await models.CrontabModel.create({ id:1, command:'true', status:1, isDisabled:0 }); - const now = Math.floor(Date.now()/1000); - const day = require('dayjs')(now*1000).format('YYYY-MM-DD'); - const ended = async (pid, code) => db.models.RunningInstance.create({ cron_id:1,pid,started_at:now-3, - finished_at:now,log_path:'shared.log',status:code ? 3 : 1,exit_code:code }); - await ended(101,0); await ended(102,0); await ended(103,17); await ended(104,null); - await ended(105,0); await ended(105,0); // Repeated anonymous start proves one additional exit. - await stats.CrontabStatModel.create({ref_id:1,date:day,run_count:1,success_count:1,total_time:9000,max_time:9000}); + const { migrateSchema } = require('../../back/data/schemaMigrations'); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); + const task = await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + isDisabled: 0, + }); + const now = Math.floor(Date.now() / 1000); + const day = require('dayjs')(now * 1000).format('YYYY-MM-DD'); + const ended = async (pid, code) => + db.models.RunningInstance.create({ + cron_id: 1, + pid, + started_at: now - 3, + finished_at: now, + log_path: 'shared.log', + status: code ? 3 : 1, + exit_code: code, + }); + await ended(101, 0); + await ended(102, 0); + await ended(103, 17); + await ended(104, null); + await ended(105, 0); + await ended(105, 0); // Repeated anonymous start proves one additional exit. + await stats.CrontabStatModel.create({ + ref_id: 1, + date: day, + run_count: 1, + success_count: 1, + total_time: 9000, + max_time: 9000, + }); const key = 'client-' + require('node:crypto').randomUUID(); - await history.reportInstance(key,1,true,106,'new.log',now,0); - await history.reportInstance(key,1,false,106,'new.log',now,2,0); - const query = () => db.query('SELECT run_count,success_count,fail_count,untimed_count,total_time,max_time FROM CrontabStats',{type:QueryTypes.SELECT}); - await db.query("CREATE TRIGGER reject_daily_repair BEFORE UPDATE ON CrontabStats BEGIN SELECT RAISE(ABORT,'repair failed'); END"); - await assert.rejects(migrateSchema(db), error => /repair failed/.test(error.original?.message)); - assert.equal((await history.recent(1,0)).length,1); + await history.reportInstance(key, 1, true, 106, 'new.log', now, 0); + await history.reportInstance(key, 1, false, 106, 'new.log', now, 2, 0); + const query = () => + db.query( + 'SELECT run_count,success_count,fail_count,untimed_count,total_time,max_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + await db.query( + "CREATE TRIGGER reject_daily_repair BEFORE UPDATE ON CrontabStats BEGIN SELECT RAISE(ABORT,'repair failed'); END", + ); + await assert.rejects(migrateSchema(db), (error) => + /repair failed/.test(error.original?.message), + ); + assert.equal((await history.recent(1, 0)).length, 1); await db.query('DROP TRIGGER reject_daily_repair'); - await Promise.all([migrateSchema(db),migrateSchema(db)]); - await Promise.all([history.reportLegacy(1,false,103,'shared.log',now-3,10,17), - history.reportLegacy(1,false,102,'shared.log',now-3,10,0),history.recordShellResult(key,1,0,2000,Date.now())]); - assert.deepEqual(await query(),[{run_count:5,success_count:4,fail_count:1,untimed_count:3,total_time:11000,max_time:9000}]); - assert.deepEqual([(await task.reload()).last_execution_time,task.last_running_time],[now,2]); - assert.equal((await history.recent(1,0)).filter(r=>r.exit_code===17).length,1); + await Promise.all([migrateSchema(db), migrateSchema(db)]); + await Promise.all([ + history.reportLegacy(1, false, 103, 'shared.log', now - 3, 10, 17), + history.reportLegacy(1, false, 102, 'shared.log', now - 3, 10, 0), + history.recordShellResult(key, 1, 0, 2000, Date.now()), + ]); + assert.deepEqual(await query(), [ + { + run_count: 5, + success_count: 4, + fail_count: 1, + untimed_count: 3, + total_time: 11000, + max_time: 9000, + }, + ]); + assert.deepEqual( + [(await task.reload()).last_execution_time, task.last_running_time], + [now, 2], + ); + assert.equal( + (await history.recent(1, 0)).filter((r) => r.exit_code === 17).length, + 1, + ); const router = express.Router(); load('back/api/dashboard.ts', { - '../data/cron': models, '../data/cronStats': stats, '../data/runningInstance': {}, - '../shared/i18n': { t: key => key, tf: (format,id) => format.replace('%s',id) }, + '../data/cron': models, + '../data/cronStats': stats, + '../data/runningInstance': {}, + '../shared/i18n': { + t: (key) => key, + tf: (format, id) => format.replace('%s', id), + }, }).default(router); const routes = router.stack[0].handle.stack; - for (const path of ['/overview','/top-time','/top-count','/labels']) { - const handler = routes.find(entry => entry.route?.path === path).route.stack[0].handle; + for (const path of ['/overview', '/top-time', '/top-count', '/labels']) { + const handler = routes.find((entry) => entry.route?.path === path).route + .stack[0].handle; let data; - await handler({}, { send: result => { data=result.data; } }, error => { throw error; }); - assert.equal((Array.isArray(data) ? data[0] : data).avgTime,5500,path); + await handler( + {}, + { + send: (result) => { + data = result.data; + }, + }, + (error) => { + throw error; + }, + ); + assert.equal((Array.isArray(data) ? data[0] : data).avgTime, 5500, path); } - await stats.CrontabStatModel.destroy({where:{ref_id:1}}); + await stats.CrontabStatModel.destroy({ where: { ref_id: 1 } }); await migrateSchema(db); - assert.deepEqual(await query(),[]); // A later retention cleanup stays effective. + assert.deepEqual(await query(), []); // A later retention cleanup stays effective. }); -test('upgrade spends a later anonymous count once per outcome and respects prior cleanup', async t => { +test('upgrade spends a later anonymous count once per outcome and respects prior cleanup', async (t) => { const { db, models, stats } = await fixture(t); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); - await models.CrontabModel.create({id:1,command:'true',status:1}); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); + await models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); const day = require('dayjs')().startOf('day'); let pid = 100; - async function exits(ago,count,code) { - const end=day.subtract(ago,'day').add(1,'second').unix(); - for (let i=0;i[r.date,r.run_count,r.success_count,r.fail_count]),[ - [3,4,4,0],[2,3,3,0],[0,5,2,3]].map(([ago,...counts])=>[day.subtract(ago,'day').format('YYYY-MM-DD'),...counts])); + await daily(3, 1, 0); + await daily(0, 2, 3); + await exits(4, 2, 0); + await exits(3, 4, 0); + await exits(2, 3, 0); + await exits(1, 1, 0); + await exits(0, 1, 0); + await exits(1, 1, 17); + await require('../../back/data/schemaMigrations').migrateSchema(db); + const rows = await db.query( + 'SELECT date,run_count,success_count,fail_count FROM CrontabStats ORDER BY date', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.map((r) => [r.date, r.run_count, r.success_count, r.fail_count]), + [ + [3, 4, 4, 0], + [2, 3, 3, 0], + [0, 5, 2, 3], + ].map(([ago, ...counts]) => [ + day.subtract(ago, 'day').format('YYYY-MM-DD'), + ...counts, + ]), + ); }); -test('already upgraded databases reconcile multi-day evidence against an independent one-use receipt matching model', async t => { - const { db,models,stats } = await fixture(t); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); +test('already upgraded databases reconcile multi-day evidence against an independent one-use receipt matching model', async (t) => { + const { db, models, stats } = await fixture(t); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); await db.query('DELETE FROM SchemaMigrations'); - await db.query("INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP)"); - const dates = Array.from({length:3},(_,i)=>require('dayjs')().startOf('day').subtract(2-i,'day')); - const crons=[], instances=[], saved=[], expected=[]; + await db.query( + "INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP)", + ); + const dates = Array.from({ length: 3 }, (_, i) => + require('dayjs')() + .startOf('day') + .subtract(2 - i, 'day'), + ); + const crons = [], + instances = [], + saved = [], + expected = []; // The oracle removes individual receipts. Nearest eligible exits take priority // and recorded daily totals are preserved, including pre-upgrade duplicates. - for (let mask=0;mask<216;mask++) { - const cron_id=mask+1; - crons.push({id:cron_id,command:String(cron_id),status:1}); - const exits=dates.map((_,i)=>1+Number(Boolean(mask & (1<Math.floor(Math.floor(mask/8)/3**i)%3); - const available=reports.flatMap((count,day)=>Array(count).fill(day)); - const repaired=reports.slice(); - for (let day=2;day>=0;day--) { - for (let n=0;narrived>=day); - if (receipt<0) repaired[day]++; - else available.splice(receipt,1); - const end=dates[day].add(12,'hour').unix(); - instances.push({cron_id,pid:200+n,started_at:end-2,finished_at:end,status:1,exit_code:0}); + for (let mask = 0; mask < 216; mask++) { + const cron_id = mask + 1; + crons.push({ id: cron_id, command: String(cron_id), status: 1 }); + const exits = dates.map((_, i) => 1 + Number(Boolean(mask & (1 << i)))); + const reports = dates.map( + (_, i) => Math.floor(Math.floor(mask / 8) / 3 ** i) % 3, + ); + const available = reports.flatMap((count, day) => Array(count).fill(day)); + const repaired = reports.slice(); + for (let day = 2; day >= 0; day--) { + for (let n = 0; n < exits[day]; n++) { + const receipt = available.findIndex((arrived) => arrived >= day); + if (receipt < 0) repaired[day]++; + else available.splice(receipt, 1); + const end = dates[day].add(12, 'hour').unix(); + instances.push({ + cron_id, + pid: 200 + n, + started_at: end - 2, + finished_at: end, + status: 1, + exit_code: 0, + }); } // Retain an explicit row even for a zero-count day. Missing rows after v1 // have no deletion provenance and are tested separately. - saved.push({ref_id:cron_id,date:dates[day].format('YYYY-MM-DD'), - run_count:reports[day],success_count:reports[day]}); - expected.push([cron_id,dates[day].format('YYYY-MM-DD'),repaired[day]]); + saved.push({ + ref_id: cron_id, + date: dates[day].format('YYYY-MM-DD'), + run_count: reports[day], + success_count: reports[day], + }); + expected.push([cron_id, dates[day].format('YYYY-MM-DD'), repaired[day]]); } } await models.CrontabModel.bulkCreate(crons); await db.models.RunningInstance.bulkCreate(instances); await stats.CrontabStatModel.bulkCreate(saved); // v1 has already imported some rows and counted one provably missing exit. - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,exit_code,counted) SELECT 'legacy-db-'||id,cron_id,'legacy','finished',started_at*1000,started_at*1000,finished_at*1000,id,0,1 FROM RunningInstances WHERE cron_id=1"); - await stats.CrontabStatModel.update({run_count:1,success_count:1,untimed_count:1}, - {where:{ref_id:1,date:dates[2].format('YYYY-MM-DD')}}); - const {migrateSchema}=require('../../back/shared/schemaMigrations'); - await Promise.all([migrateSchema(db),migrateSchema(db)]); - const rows=await db.query('SELECT ref_id,date,success_count FROM CrontabStats ORDER BY ref_id,date DESC',{type:QueryTypes.SELECT}); - assert.deepEqual(rows.map(Object.values),expected); - assert.equal(await db.models.RunningInstance.count(),instances.length); - const [count]=await db.query('SELECT COUNT(*) AS n FROM CronTriggers',{type:QueryTypes.SELECT}); - assert.equal(count.n,instances.length); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,exit_code,counted) SELECT 'legacy-db-'||id,cron_id,'legacy','finished',started_at*1000,started_at*1000,finished_at*1000,id,0,1 FROM RunningInstances WHERE cron_id=1", + ); + await stats.CrontabStatModel.update( + { run_count: 1, success_count: 1, untimed_count: 1 }, + { where: { ref_id: 1, date: dates[2].format('YYYY-MM-DD') } }, + ); + const { migrateSchema } = require('../../back/data/schemaMigrations'); + await Promise.all([migrateSchema(db), migrateSchema(db)]); + const rows = await db.query( + 'SELECT ref_id,date,success_count FROM CrontabStats ORDER BY ref_id,date DESC', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual(rows.map(Object.values), expected); + assert.equal(await db.models.RunningInstance.count(), instances.length); + const [count] = await db.query('SELECT COUNT(*) AS n FROM CronTriggers', { + type: QueryTypes.SELECT, + }); + assert.equal(count.n, instances.length); }); -test('duplicate bookings cannot cover future starts; later anonymous credit is spent once', async t => { +test('duplicate bookings cannot cover future starts; later anonymous credit is spent once', async (t) => { const { db, models, stats } = await fixture(t); - const { migrateSchema } = require('../../back/shared/schemaMigrations'); - const { readDailyResults } = require('../../back/shared/legacyDailyStatistics'); + const { migrateSchema } = require('../../back/data/schemaMigrations'); + const { + readDailyResults, + } = require('../../back/cron/settlement/legacyDailyStatistics'); const today = require('dayjs')().startOf('day'); const yesterday = today.subtract(1, 'day'); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); await db.query('DELETE FROM SchemaMigrations'); - await db.query("INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP)"); - for (const id of [1,2,3]) { - await models.CrontabModel.create({ id, command:'true' }); - const booked = yesterday.add(10,'hour'); + await db.query( + "INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP)", + ); + for (const id of [1, 2, 3]) { + await models.CrontabModel.create({ id, command: 'true' }); + const booked = yesterday.add(10, 'hour'); // Three starts precede or share the last booking second, two start later. - for (const [index,offset] of [-9,-5,0,2,5].entries()) { - const started = booked.add(offset,'second'); - const instance = await db.models.RunningInstance.create({ cron_id:id,pid:100+index, - started_at:started.unix(),finished_at:started.unix()+1,status:1,exit_code:0 }); - await db.query('UPDATE RunningInstances SET createdAt=$stamp WHERE id=$id', { - bind:{stamp:started.toISOString(),id:instance.id} }); + for (const [index, offset] of [-9, -5, 0, 2, 5].entries()) { + const started = booked.add(offset, 'second'); + const instance = await db.models.RunningInstance.create({ + cron_id: id, + pid: 100 + index, + started_at: started.unix(), + finished_at: started.unix() + 1, + status: 1, + exit_code: 0, + }); + await db.query( + 'UPDATE RunningInstances SET createdAt=$stamp WHERE id=$id', + { + bind: { stamp: started.toISOString(), id: instance.id }, + }, + ); } - const row = await stats.CrontabStatModel.create({ref_id:id,date:yesterday.format('YYYY-MM-DD'), - success_count:5,run_count:5,total_time:5000,max_time:1000}); - await db.query('UPDATE CrontabStats SET createdAt=$stamp,updatedAt=$stamp WHERE id=$id',{ - bind:{id:row.id,stamp:id===3 ? 'unknown' : booked.add(900,'ms').toISOString()}}); - if (id===2) await stats.CrontabStatModel.create({ref_id:id,date:today.format('YYYY-MM-DD'),run_count:1,success_count:1}); + const row = await stats.CrontabStatModel.create({ + ref_id: id, + date: yesterday.format('YYYY-MM-DD'), + success_count: 5, + run_count: 5, + total_time: 5000, + max_time: 1000, + }); + await db.query( + 'UPDATE CrontabStats SET createdAt=$stamp,updatedAt=$stamp WHERE id=$id', + { + bind: { + id: row.id, + stamp: id === 3 ? 'unknown' : booked.add(900, 'ms').toISOString(), + }, + }, + ); + if (id === 2) + await stats.CrontabStatModel.create({ + ref_id: id, + date: today.format('YYYY-MM-DD'), + run_count: 1, + success_count: 1, + }); } await migrateSchema(db); await migrateSchema(db); - const rows = await db.query('SELECT ref_id,success_count,untimed_count,total_time FROM CrontabStats WHERE date=$day ORDER BY ref_id', - {type:QueryTypes.SELECT,bind:{day:yesterday.format('YYYY-MM-DD')}}); - assert.deepEqual(rows.map(Object.values),[[1,7,2,5000],[2,6,1,5000],[3,5,0,5000]]); - const results = await readDailyResults(db,2); - assert.deepEqual(results.map(r=>[r.day,r.exitSuccess,r.exitFail,r.bookedSuccess,r.bookedFail,r.supplement]), - [[today.format('YYYY-MM-DD'),0,0,1,0,0],[yesterday.format('YYYY-MM-DD'),5,0,6,0,1]]); + const rows = await db.query( + 'SELECT ref_id,success_count,untimed_count,total_time FROM CrontabStats WHERE date=$day ORDER BY ref_id', + { type: QueryTypes.SELECT, bind: { day: yesterday.format('YYYY-MM-DD') } }, + ); + assert.deepEqual(rows.map(Object.values), [ + [1, 7, 2, 5000], + [2, 6, 1, 5000], + [3, 5, 0, 5000], + ]); + const results = await readDailyResults(db, 2); + assert.deepEqual( + results.map((r) => [ + r.day, + r.exitSuccess, + r.exitFail, + r.bookedSuccess, + r.bookedFail, + r.supplement, + ]), + [ + [today.format('YYYY-MM-DD'), 0, 0, 1, 0, 0], + [yesterday.format('YYYY-MM-DD'), 5, 0, 6, 0, 1], + ], + ); }); -test('v3 keeps v2 statistics cleanup and rejects ambiguous settled PID siblings on replay', async t => { - const { db,models,history } = await fixture(t); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); - await models.CrontabModel.create({id:1,command:'true'}); - const now = Math.floor(Date.now()/1000); - for (const [pid,log,start] of [[101,'kept',now-8],[102,'a',now-6],[102,'b',now-4]]) { - await db.models.RunningInstance.create({cron_id:1,pid,started_at:start,finished_at:now,status:1,log_path:log,exit_code:0}); - } - const { migrateSchema } = require('../../back/shared/schemaMigrations'); - await db.query('DELETE FROM SchemaMigrations'); - await db.query("INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP)"); - await migrateSchema(db); - await Promise.all([history.reportLegacy(1,false,102,'a',now-6,6,0),history.reportLegacy(1,false,102,'b',now-4,4,0)]); - assert.deepEqual((await history.recent(1,0)).map(row=>row.log_path),['kept']); - assert.equal(await db.models.CrontabStat.count(),0); -}); - -test('daily verified exits distinguish a spawn failure and previously adopted ambiguous legacy rows', async t => { - const { db,stats } = await fixture(t); - const second = Math.floor(Date.now()/1000) - 5; - const ms = second*1000; - for (const [id,source,state,reason,code,instance] of [ - ['spawn','node','failed','spawn',null,null], - ['signal','node','failed','SIGTERM',null,null], - ['first','legacy','finished',null,0,1],['second','legacy','finished',null,0,2], - ['identified','client','finished',null,0,3], +test('v3 keeps v2 statistics cleanup and rejects ambiguous settled PID siblings on replay', async (t) => { + const { db, models, history } = await fixture(t); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const now = Math.floor(Date.now() / 1000); + for (const [pid, log, start] of [ + [101, 'kept', now - 8], + [102, 'a', now - 6], + [102, 'b', now - 4], ]) { - if (instance) await db.models.RunningInstance.create({id:instance,cron_id:1,pid:44, - started_at:second-instance,finished_at:second,status:1,log_path:id,exit_code:0}); - await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,reason,started_at,observed_at,finished_at,exit_code,instance_id,counted) - VALUES ($id,1,$source,$state,$reason,$start,$start,$ms,$code,$instance,1)`, - {bind:{id,source,state,reason,code,instance,ms,start:ms-(instance||1)*1000}}); + await db.models.RunningInstance.create({ + cron_id: 1, + pid, + started_at: start, + finished_at: now, + status: 1, + log_path: log, + exit_code: 0, + }); } - const day=require('dayjs')(ms).format('YYYY-MM-DD'); - await stats.CrontabStatModel.create({ref_id:1,date:day,run_count:5,success_count:3,fail_count:2}); - assert.deepEqual(await require('../../back/shared/legacyDailyStatistics').readDailyResults(db,1), - [{day,exitSuccess:1,exitFail:1,bookedSuccess:3,bookedFail:2,supplement:0}]); + const { migrateSchema } = require('../../back/data/schemaMigrations'); + await db.query('DELETE FROM SchemaMigrations'); + await db.query( + "INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP)", + ); + await migrateSchema(db); + await Promise.all([ + history.reportLegacy(1, false, 102, 'a', now - 6, 6, 0), + history.reportLegacy(1, false, 102, 'b', now - 4, 4, 0), + ]); + assert.deepEqual( + (await history.recent(1, 0)).map((row) => row.log_path), + ['kept'], + ); + assert.equal(await db.models.CrontabStat.count(), 0); }); -test('a separately identified execution cannot hide an unlinked legacy exit sharing its PID and finish second', async t => { - const { db,models }=await fixture(t); - for (const table of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); - await models.CrontabModel.create({id:1,command:'true'}); - const end=Math.floor(Date.now()/1000); - const old=await db.models.RunningInstance.create({cron_id:1,pid:71,log_path:'old',started_at:end-3,finished_at:end,status:1,exit_code:0}); - const tagged=await db.models.RunningInstance.create({cron_id:1,pid:71,log_path:'tagged',started_at:end,finished_at:end,status:1,exit_code:0}); - await db.query("INSERT INTO CronTriggers(id,cron_id,instance_id,source,state,observed_at,started_at,finished_at,exit_code,counted) VALUES ('tagged',1,$instance,'client','finished',$end,$end,$end,0,1)", - {bind:{instance:tagged.id,end:end*1000}}); - await require('../../back/shared/schemaMigrations').migrateSchema(db); - assert.deepEqual(await db.query('SELECT instance_id FROM CronTriggers ORDER BY instance_id',{type:QueryTypes.SELECT}), - [{instance_id:old.id},{instance_id:tagged.id}]); +test('daily verified exits distinguish a spawn failure and previously adopted ambiguous legacy rows', async (t) => { + const { db, stats } = await fixture(t); + const second = Math.floor(Date.now() / 1000) - 5; + const ms = second * 1000; + for (const [id, source, state, reason, code, instance] of [ + ['spawn', 'node', 'failed', 'spawn', null, null], + ['signal', 'node', 'failed', 'SIGTERM', null, null], + ['first', 'legacy', 'finished', null, 0, 1], + ['second', 'legacy', 'finished', null, 0, 2], + ['identified', 'client', 'finished', null, 0, 3], + ]) { + if (instance) + await db.models.RunningInstance.create({ + id: instance, + cron_id: 1, + pid: 44, + started_at: second - instance, + finished_at: second, + status: 1, + log_path: id, + exit_code: 0, + }); + await db.query( + `INSERT INTO CronTriggers(id,cron_id,source,state,reason,started_at,observed_at,finished_at,exit_code,instance_id,counted) + VALUES ($id,1,$source,$state,$reason,$start,$start,$ms,$code,$instance,1)`, + { + bind: { + id, + source, + state, + reason, + code, + instance, + ms, + start: ms - (instance || 1) * 1000, + }, + }, + ); + } + const day = require('dayjs')(ms).format('YYYY-MM-DD'); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: day, + run_count: 5, + success_count: 3, + fail_count: 2, + }); + assert.deepEqual( + await require('../../back/cron/settlement/legacyDailyStatistics').readDailyResults( + db, + 1, + ), + [ + { + day, + exitSuccess: 1, + exitFail: 1, + bookedSuccess: 3, + bookedFail: 2, + supplement: 0, + }, + ], + ); }); -test('statistics cleanup persists its own cutoff and a delayed unknown exit cannot reopen a cleaned day', async t => { - const { db,models,stats,history } = await fixture(t); +test('a separately identified execution cannot hide an unlinked legacy exit sharing its PID and finish second', async (t) => { + const { db, models } = await fixture(t); + for (const table of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${table}(id INTEGER PRIMARY KEY)`); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const end = Math.floor(Date.now() / 1000); + const old = await db.models.RunningInstance.create({ + cron_id: 1, + pid: 71, + log_path: 'old', + started_at: end - 3, + finished_at: end, + status: 1, + exit_code: 0, + }); + const tagged = await db.models.RunningInstance.create({ + cron_id: 1, + pid: 71, + log_path: 'tagged', + started_at: end, + finished_at: end, + status: 1, + exit_code: 0, + }); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,instance_id,source,state,observed_at,started_at,finished_at,exit_code,counted) VALUES ('tagged',1,$instance,'client','finished',$end,$end,$end,0,1)", + { bind: { instance: tagged.id, end: end * 1000 } }, + ); + await require('../../back/data/schemaMigrations').migrateSchema(db); + assert.deepEqual( + await db.query( + 'SELECT instance_id FROM CronTriggers ORDER BY instance_id', + { type: QueryTypes.SELECT }, + ), + [{ instance_id: old.id }, { instance_id: tagged.id }], + ); +}); + +test('statistics cleanup persists its own cutoff and a delayed unknown exit cannot reopen a cleaned day', async (t) => { + const { db, models, stats, history } = await fixture(t); const day = require('dayjs')().startOf('day'); - const expired = day.subtract(3,'day'); - const cutoff = day.subtract(1,'day'); - await models.CrontabModel.create({id:1,command:'true'}); + const expired = day.subtract(3, 'day'); + const cutoff = day.subtract(1, 'day'); + await models.CrontabModel.create({ id: 1, command: 'true' }); const key = 'client-' + require('node:crypto').randomUUID(); - await history.reportInstance(key,1,true,123,'old.log',expired.unix(),0); - await db.query("UPDATE CronTriggers SET state='unknown',finished_at=$end WHERE id=$key", {bind:{key,end:expired.add(10,'minute').valueOf()}}); - await stats.CrontabStatModel.create({ref_id:1,date:expired.format('YYYY-MM-DD'),run_count:2,success_count:2,untimed_count:1}); - const Service=load('back/services/retention.ts',{ - '../data':{sequelize:db},'../data/cronStats':stats,'../data/runningInstance':{RunningInstanceModel:db.models.RunningInstance,InstanceStatus:{running:0}}, - '../data/system':{},'../config':{}, + await history.reportInstance(key, 1, true, 123, 'old.log', expired.unix(), 0); + await db.query( + "UPDATE CronTriggers SET state='unknown',finished_at=$end WHERE id=$key", + { bind: { key, end: expired.add(10, 'minute').valueOf() } }, + ); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: expired.format('YYYY-MM-DD'), + run_count: 2, + success_count: 2, + untimed_count: 1, + }); + const Service = load('back/services/retention.ts', { + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default; - const cleanup = days => new Service().cleanup({cronStatRetentionDays:days,runningInstanceRetentionDays:0}); - await db.query("CREATE TRIGGER reject_stat_cutoff BEFORE INSERT ON CronStatRetention BEGIN SELECT RAISE(ABORT,'test rollback'); END"); - await assert.rejects(cleanup(1), error => error.original?.message.includes('test rollback')); - assert.equal(await stats.CrontabStatModel.count(),1); + const cleanup = (days) => + new Service().cleanup({ + cronStatRetentionDays: days, + runningInstanceRetentionDays: 0, + }); + await db.query( + "CREATE TRIGGER reject_stat_cutoff BEFORE INSERT ON CronStatRetention BEGIN SELECT RAISE(ABORT,'test rollback'); END", + ); + await assert.rejects(cleanup(1), (error) => + error.original?.message.includes('test rollback'), + ); + assert.equal(await stats.CrontabStatModel.count(), 1); await db.query('DROP TRIGGER reject_stat_cutoff'); - await cleanup(1); await cleanup(30); - await Promise.all([history.recordShellResult(key,1,17,1000,Date.now()),history.reportInstance(key,1,false,123,'old.log',expired.unix(),1,17)]); - const [row]=await history.recent(1,0); - assert.deepEqual([row.state,row.finished_at],['failed',expired.add(10,'minute').valueOf()]); + await cleanup(1); + await cleanup(30); + await Promise.all([ + history.recordShellResult(key, 1, 17, 1000, Date.now()), + history.reportInstance( + key, + 1, + false, + 123, + 'old.log', + expired.unix(), + 1, + 17, + ), + ]); + const [row] = await history.recent(1, 0); + assert.deepEqual( + [row.state, row.finished_at], + ['failed', expired.add(10, 'minute').valueOf()], + ); // An independently retried statistics packet must also use the stored end. - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,exit_code) VALUES ('unclaimed',1,'client','finished',$start,$start,$end,0)", - {bind:{start:expired.valueOf(),end:expired.add(1,'hour').valueOf()}}); - await history.recordShellResult('unclaimed',1,0,1000,Date.now()); - assert.equal(await stats.CrontabStatModel.count(),0); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,exit_code) VALUES ('unclaimed',1,'client','finished',$start,$start,$end,0)", + { + bind: { start: expired.valueOf(), end: expired.add(1, 'hour').valueOf() }, + }, + ); + await history.recordShellResult('unclaimed', 1, 0, 1000, Date.now()); + assert.equal(await stats.CrontabStatModel.count(), 0); // A live process that started before the cutoff may still finish today. - const live='client-'+require('node:crypto').randomUUID(); - await history.reportInstance(live,1,true,124,'live.log',expired.unix(),0); - await history.reportInstance(live,1,false,124,'live.log',expired.unix(),1,0); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(row=>[row.date,row.run_count]),[[day.format('YYYY-MM-DD'),1]]); - assert.deepEqual(await db.query('SELECT first_day FROM CronStatRetention',{type:QueryTypes.SELECT}),[{first_day:cutoff.format('YYYY-MM-DD')}]); + const live = 'client-' + require('node:crypto').randomUUID(); + await history.reportInstance( + live, + 1, + true, + 124, + 'live.log', + expired.unix(), + 0, + ); + await history.reportInstance( + live, + 1, + false, + 124, + 'live.log', + expired.unix(), + 1, + 0, + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((row) => [ + row.date, + row.run_count, + ]), + [[day.format('YYYY-MM-DD'), 1]], + ); + assert.deepEqual( + await db.query('SELECT first_day FROM CronStatRetention', { + type: QueryTypes.SELECT, + }), + [{ first_day: cutoff.format('YYYY-MM-DD') }], + ); }); -test('an expired unknown orphan or an undated standalone retry cannot recreate a pruned trigger', async t => { - const { db,models,history }=await fixture(t); - await models.CrontabModel.create({id:1,command:'true'}); - const now=Math.floor(Date.now()/1000)-5, start=now-10, cutoff=now*1000+500; - await db.models.RunningInstance.create({cron_id:1,pid:44,log_path:'expired',started_at:start,finished_at:now,status:4}); - const key='client-'+require('node:crypto').randomUUID(); - await history.reportInstance(key,1,false,88,'tagged',start,1,0); - await db.query('UPDATE CronTriggers SET finished_at=$time WHERE id=$key',{bind:{time:now*1000,key}}); - await db.transaction(tx=>history.deleteExpired(cutoff,tx)); - const count=await db.models.CrontabStat.count(); - await Promise.all([history.reportLegacy(1,false,44,'expired',start,1,0),history.reportInstance(key,1,false,88,'tagged',0,1,0)]); - assert.deepEqual(await history.recent(1,0),[]); - assert.equal(await db.models.CrontabStat.count(),count); +test('an expired unknown orphan or an undated standalone retry cannot recreate a pruned trigger', async (t) => { + const { db, models, history } = await fixture(t); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const now = Math.floor(Date.now() / 1000) - 5, + start = now - 10, + cutoff = now * 1000 + 500; + await db.models.RunningInstance.create({ + cron_id: 1, + pid: 44, + log_path: 'expired', + started_at: start, + finished_at: now, + status: 4, + }); + const key = 'client-' + require('node:crypto').randomUUID(); + await history.reportInstance(key, 1, false, 88, 'tagged', start, 1, 0); + await db.query('UPDATE CronTriggers SET finished_at=$time WHERE id=$key', { + bind: { time: now * 1000, key }, + }); + await db.transaction((tx) => history.deleteExpired(cutoff, tx)); + const count = await db.models.CrontabStat.count(); + await Promise.all([ + history.reportLegacy(1, false, 44, 'expired', start, 1, 0), + history.reportInstance(key, 1, false, 88, 'tagged', 0, 1, 0), + ]); + assert.deepEqual(await history.recent(1, 0), []); + assert.equal(await db.models.CrontabStat.count(), count); }); -test('v1 upgrade after deleting a previously supplemented day does not issue that supplement again', async t => { - const {db,models,stats}=await fixture(t); - for(const name of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${name}(id INTEGER PRIMARY KEY)`); - await models.CrontabModel.create({id:1,command:'true'}); - const day=require('dayjs')().startOf('day').subtract(1,'day'); - const i=await db.models.RunningInstance.create({cron_id:1,pid:22,started_at:day.unix(),finished_at:day.unix()+1,status:1,exit_code:0}); - await db.query("INSERT INTO CronTriggers(id,cron_id,instance_id,source,state,observed_at,started_at,finished_at,exit_code,counted) VALUES ('legacy-db-'||$id,1,$id,'legacy','finished',$start,$start,$end,0,1)",{bind:{id:i.id,start:day.valueOf(),end:day.valueOf()+1000}}); +test('v1 upgrade after deleting a previously supplemented day does not issue that supplement again', async (t) => { + const { db, models, stats } = await fixture(t); + for (const name of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${name}(id INTEGER PRIMARY KEY)`); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const day = require('dayjs')().startOf('day').subtract(1, 'day'); + const i = await db.models.RunningInstance.create({ + cron_id: 1, + pid: 22, + started_at: day.unix(), + finished_at: day.unix() + 1, + status: 1, + exit_code: 0, + }); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,instance_id,source,state,observed_at,started_at,finished_at,exit_code,counted) VALUES ('legacy-db-'||$id,1,$id,'legacy','finished',$start,$start,$end,0,1)", + { bind: { id: i.id, start: day.valueOf(), end: day.valueOf() + 1000 } }, + ); await db.query('DELETE FROM SchemaMigrations'); - await db.query("INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP)"); - await stats.CrontabStatModel.create({ref_id:1,date:day.format('YYYY-MM-DD'),run_count:1,success_count:1,untimed_count:1}); - await stats.CrontabStatModel.destroy({where:{ref_id:1}}); - await require('../../back/shared/schemaMigrations').migrateSchema(db); - assert.equal(await stats.CrontabStatModel.count(),0); + await db.query( + "INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP)", + ); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: day.format('YYYY-MM-DD'), + run_count: 1, + success_count: 1, + untimed_count: 1, + }); + await stats.CrontabStatModel.destroy({ where: { ref_id: 1 } }); + await require('../../back/data/schemaMigrations').migrateSchema(db); + assert.equal(await stats.CrontabStatModel.count(), 0); }); -test('upgrading a v3 database with old statistics cleanup protects a retained unknown from its first late exit', async t => { - const { db,models,stats,history }=await fixture(t); - for(const name of ['Envs','Subscriptions','CrontabViews']) await db.query(`CREATE TABLE ${name}(id INTEGER PRIMARY KEY)`); - await models.CrontabModel.create({id:1,command:'true'}); - const today=require('dayjs')().startOf('day'), old=today.subtract(3,'day'); +test('upgrading a v3 database with old statistics cleanup protects a retained unknown from its first late exit', async (t) => { + const { db, models, stats, history } = await fixture(t); + for (const name of ['Envs', 'Subscriptions', 'CrontabViews']) + await db.query(`CREATE TABLE ${name}(id INTEGER PRIMARY KEY)`); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const today = require('dayjs')().startOf('day'), + old = today.subtract(3, 'day'); await db.query('DELETE FROM SchemaMigrations'); - await db.query("INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v3',CURRENT_TIMESTAMP)"); - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at) VALUES ('pending',1,'client','unknown',$old,$old,$end)",{ - bind:{old:old.valueOf(),end:old.add(5,'minute').valueOf()}}); - await stats.CrontabStatModel.create({ref_id:1,date:today.format('YYYY-MM-DD'),run_count:1,success_count:1}); - await require('../../back/shared/schemaMigrations').migrateSchema(db); - await Promise.all([history.recordShellResult('pending',1,0,300000,Date.now()),history.recordShellResult('pending',1,0,300000,Date.now())]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r=>[r.date,r.run_count]),[[today.format('YYYY-MM-DD'),1]]); - assert.equal((await history.recent(1,0))[0].state,'finished'); + await db.query( + "INSERT INTO SchemaMigrations VALUES ('repair-legacy-daily-statistics-v3',CURRENT_TIMESTAMP)", + ); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at) VALUES ('pending',1,'client','unknown',$old,$old,$end)", + { + bind: { old: old.valueOf(), end: old.add(5, 'minute').valueOf() }, + }, + ); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: today.format('YYYY-MM-DD'), + run_count: 1, + success_count: 1, + }); + await require('../../back/data/schemaMigrations').migrateSchema(db); + await Promise.all([ + history.recordShellResult('pending', 1, 0, 300000, Date.now()), + history.recordShellResult('pending', 1, 0, 300000, Date.now()), + ]); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [r.date, r.run_count]), + [[today.format('YYYY-MM-DD'), 1]], + ); + assert.equal((await history.recent(1, 0))[0].state, 'finished'); }); -test('cleanup uses one precision and cutoff for a linked exit on the boundary second', async t => { +test('cleanup uses one precision and cutoff for a linked exit on the boundary second', async (t) => { const { db, stats } = await fixture(t); const now = new Date(2026, 10, 19, 0, 0, 0, 900); t.mock.timers.enable({ apis: ['Date'], now: now.getTime() }); const boundary = new Date(2026, 10, 18, 0, 0, 0).getTime(); const instances = db.models.RunningInstance; - for (const [id, end] of [['expired', boundary-1], ['boundary', boundary+100]]) { - const instance = await instances.create({cron_id:1, pid:42, started_at:boundary/1000-100, - finished_at:Math.floor(end/1000), status:1, exit_code:0}); - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,counted) VALUES ($id,1,'manual','finished',$start,$start,$end,$instance,1)", - {bind:{id,start:boundary-100000,end,instance:instance.id}}); + for (const [id, end] of [ + ['expired', boundary - 1], + ['boundary', boundary + 100], + ]) { + const instance = await instances.create({ + cron_id: 1, + pid: 42, + started_at: boundary / 1000 - 100, + finished_at: Math.floor(end / 1000), + status: 1, + exit_code: 0, + }); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,counted) VALUES ($id,1,'manual','finished',$start,$start,$end,$instance,1)", + { bind: { id, start: boundary - 100000, end, instance: instance.id } }, + ); } const Service = load('back/services/retention.ts', { - '../data':{sequelize:db}, '../data/cronStats':stats, - '../data/runningInstance':{RunningInstanceModel:instances,InstanceStatus:{running:0}}, - '../data/system':{},'../config':{}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: instances, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default; const service = new Service(); - const policy = {runningInstanceRetentionDays:1,cronStatRetentionDays:1}; + const policy = { runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }; const preview = await service.preview(policy); - assert.deepEqual([preview.runningInstances,preview.triggers], [1,1]); + assert.deepEqual([preview.runningInstances, preview.triggers], [1, 1]); const result = await service.cleanup(policy); - assert.deepEqual([result.deleted.runningInstances,result.deleted.triggers], [1,1]); - assert.equal(await instances.count(),1); - assert.deepEqual(await db.query('SELECT t.id FROM CronTriggers t JOIN RunningInstances i ON i.id=t.instance_id', - {type:QueryTypes.SELECT}), [{id:'boundary'}]); + assert.deepEqual( + [result.deleted.runningInstances, result.deleted.triggers], + [1, 1], + ); + assert.equal(await instances.count(), 1); + assert.deepEqual( + await db.query( + 'SELECT t.id FROM CronTriggers t JOIN RunningInstances i ON i.id=t.instance_id', + { type: QueryTypes.SELECT }, + ), + [{ id: 'boundary' }], + ); }); -test('a dated exit racing retention, recovery and retries only books its actual retained day', async t => { - const {db,models,history,stats} = await fixture(t); - await models.CrontabModel.create({id:1,command:'true'}); - const day = require('dayjs')().startOf('day').subtract(1,'day'); - const old = day.subtract(1,'minute').valueOf(), kept = day.add(1,'minute').valueOf(); - const recent = Date.now()-1000; - const start = day.subtract(2,'day').unix(); - const keys = Array.from({length:3}, ()=>'client-'+require('node:crypto').randomUUID()); - const report = (index, running, end) => history.reportInstance(keys[index],1,running,210+index,'run'+index, - start,running?0:1,running?undefined:17,false,end); +test('a dated exit racing retention, recovery and retries only books its actual retained day', async (t) => { + const { db, models, history, stats } = await fixture(t); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const day = require('dayjs')().startOf('day').subtract(1, 'day'); + const old = day.subtract(1, 'minute').valueOf(), + kept = day.add(1, 'minute').valueOf(); + const recent = Date.now() - 1000; + const start = day.subtract(2, 'day').unix(); + const keys = Array.from( + { length: 3 }, + () => 'client-' + require('node:crypto').randomUUID(), + ); + const report = (index, running, end) => + history.reportInstance( + keys[index], + 1, + running, + 210 + index, + 'run' + index, + start, + running ? 0 : 1, + running ? undefined : 17, + false, + end, + ); // The last start was lost. Its first dated exit still belongs to a retained day. - await report(0,true); await report(1,true); + await report(0, true); + await report(1, true); const Service = load('back/services/retention.ts', { - '../data':{sequelize:db}, '../data/cronStats':stats, - '../data/runningInstance':{RunningInstanceModel:db.models.RunningInstance,InstanceStatus:{running:0}}, - '../data/system':{},'../config':{}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default; - const cleanup = () => new Service().cleanup({cronStatRetentionDays:1,runningInstanceRetentionDays:1}); - await Promise.all([cleanup(),history.interrupt('http'),report(0,false,old),report(1,false,kept), - history.recordShellResult(keys[1],1,17,1000,Date.now(),kept)]); - await report(2,false,recent); + const cleanup = () => + new Service().cleanup({ + cronStatRetentionDays: 1, + runningInstanceRetentionDays: 1, + }); + await Promise.all([ + cleanup(), + history.interrupt('http'), + report(0, false, old), + report(1, false, kept), + history.recordShellResult(keys[1], 1, 17, 1000, Date.now(), kept), + ]); + await report(2, false, recent); // Each exit must precede its retry, including for the now pruned trigger. await cleanup(); - await Promise.all([0,1,2].flatMap((n)=> { - const end = [old,kept,recent][n]; - return [history.recordShellResult(keys[n],1,17,1000,Date.now(),end), report(n,false,end)]; - })); - const totals = await stats.CrontabStatModel.findAll({order:[['date','ASC']]}); - assert.deepEqual(totals.map(x=>[x.date,x.run_count,x.fail_count]), - [[day.format('YYYY-MM-DD'),1,1],[require('dayjs')(recent).format('YYYY-MM-DD'),1,1]]); + await Promise.all( + [0, 1, 2].flatMap((n) => { + const end = [old, kept, recent][n]; + return [ + history.recordShellResult(keys[n], 1, 17, 1000, Date.now(), end), + report(n, false, end), + ]; + }), + ); + const totals = await stats.CrontabStatModel.findAll({ + order: [['date', 'ASC']], + }); + assert.deepEqual( + totals.map((x) => [x.date, x.run_count, x.fail_count]), + [ + [day.format('YYYY-MM-DD'), 1, 1], + [require('dayjs')(recent).format('YYYY-MM-DD'), 1, 1], + ], + ); }); -test('a managed command retains its exit after the log reader disappears, including a signalled exit', async t => { - const {root,db,history,models,stats}=await fixture(t); - const {spawnCronCommand,releaseCronCommand}=require('../../back/shared/cronCommandProcess'); - const {once}=require('node:events'); - const saved=process.env.QL_DATA_DIR; - process.env.QL_DATA_DIR=root; - t.after(()=>{if(saved===undefined)delete process.env.QL_DATA_DIR;else process.env.QL_DATA_DIR=saved;}); - await models.CrontabModel.create({id:1,command:'true'}); - for(const [id, command, code, signal] of [ - ['outer-failure', 'for i in {1..3000}; do echo output; echo error >&2; done; exit 17',17,null], - ['outer-signal', 'kill -TERM $$',null,'SIGTERM'], +test('a managed command retains its exit after the log reader disappears, including a signalled exit', async (t) => { + const { root, db, history, models, stats } = await fixture(t); + const { + spawnCronCommand, + releaseCronCommand, + } = require('../../back/cron/execution/cronCommandProcess'); + const { once } = require('node:events'); + const saved = process.env.QL_DATA_DIR; + process.env.QL_DATA_DIR = root; + t.after(() => { + if (saved === undefined) delete process.env.QL_DATA_DIR; + else process.env.QL_DATA_DIR = saved; + }); + await models.CrontabModel.create({ id: 1, command: 'true' }); + for (const [id, command, code, signal] of [ + [ + 'outer-failure', + 'for i in {1..3000}; do echo output; echo error >&2; done; exit 17', + 17, + null, + ], + ['outer-signal', 'kill -TERM $$', null, 'SIGTERM'], ]) { - await history.enqueue(id,1,'manual',null); + await history.enqueue(id, 1, 'manual', null); await history.start(id); - const proc=spawnCronCommand(command,id); - const closed=once(proc,'close'); - await once(proc,'spawn'); - await history.bindCommand(id,proc.pid); + const proc = spawnCronCommand(command, id); + const closed = once(proc, 'close'); + await once(proc, 'spawn'); + await history.bindCommand(id, proc.pid); await history.interrupt('http'); - proc.stdout.destroy();proc.stderr.destroy(); + proc.stdout.destroy(); + proc.stderr.destroy(); await releaseCronCommand(proc); - assert.deepEqual(await closed,[code,signal]); - const file=path.join(root,'db','cron-exits',id); - const receipt=JSON.parse(await fs.readFile(file,'utf8')); - assert.deepEqual([receipt.code,receipt.signal],[code,signal]); + assert.deepEqual(await closed, [code, signal]); + const file = path.join(root, 'db', 'cron-exits', id); + const receipt = JSON.parse(await fs.readFile(file, 'utf8')); + assert.deepEqual([receipt.code, receipt.signal], [code, signal]); // Rolling back the database write must leave the independent receipt replayable. - await db.query("CREATE TRIGGER reject_result BEFORE INSERT ON CrontabStats BEGIN SELECT RAISE(ABORT,'rollback'); END"); - await assert.rejects(history.recoverSystemOwners(1),error=>error.original?.message.includes('rollback')); + await db.query( + "CREATE TRIGGER reject_result BEFORE INSERT ON CrontabStats BEGIN SELECT RAISE(ABORT,'rollback'); END", + ); + await assert.rejects(history.recoverSystemOwners(1), (error) => + error.original?.message.includes('rollback'), + ); await fs.access(file); await db.query('DROP TRIGGER reject_result'); - await Promise.all([history.interrupt('http'),history.complete(id,'unknown','restart',null)]); - const row=(await history.recent(1,0)).find(r=>r.id===id); - assert.deepEqual([row.state,row.exit_code,row.reason,row.finished_at],['failed',code,signal,receipt.time]); - await assert.rejects(fs.access(file),{code:'ENOENT'}); + await Promise.all([ + history.interrupt('http'), + history.complete(id, 'unknown', 'restart', null), + ]); + const row = (await history.recent(1, 0)).find((r) => r.id === id); + assert.deepEqual( + [row.state, row.exit_code, row.reason, row.finished_at], + ['failed', code, signal, receipt.time], + ); + await assert.rejects(fs.access(file), { code: 'ENOENT' }); } - assert.equal((await stats.CrontabStatModel.findOne()).fail_count,2); + assert.equal((await stats.CrontabStatModel.findOne()).fail_count, 2); }); -test('HTTP restart recovers ownerless CLI starts, keeping only the verified live process running', async t => { - const {history,models,db}=await fixture(t); - await models.CrontabModel.create({id:1,command:'true'}); - const start=Math.floor(Date.now()/1000)-5; - const [live,gone]=[0,1].map(()=>'client-'+require('node:crypto').randomUUID()); - await history.reportInstance(live,1,true,process.pid,'live',start,0); - await history.reportInstance(gone,1,true,2147483647,'gone',start,0); +test('HTTP restart recovers ownerless CLI starts, keeping only the verified live process running', async (t) => { + const { history, models, db } = await fixture(t); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const start = Math.floor(Date.now() / 1000) - 5; + const [live, gone] = [0, 1].map( + () => 'client-' + require('node:crypto').randomUUID(), + ); + await history.reportInstance(live, 1, true, process.pid, 'live', start, 0); + await history.reportInstance(gone, 1, true, 2147483647, 'gone', start, 0); await history.interrupt('grpc'); - assert.deepEqual((await history.recent(1,0)).map(r=>r.state),['running','running']); - await history.interrupt('http'); await history.reconcileInstances(); - const rows=await db.query('SELECT t.id,t.state,i.status FROM CronTriggers t JOIN RunningInstances i ON i.id=t.instance_id', - {type:QueryTypes.SELECT}); - assert.deepEqual(rows.find(r=>r.id===live),{id:live,state:'running',status:0}); - assert.deepEqual(rows.find(r=>r.id===gone),{id:gone,state:'unknown',status:4}); - assert.equal(await db.models.CrontabStat.count(),0); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => r.state), + ['running', 'running'], + ); + await history.interrupt('http'); + await history.reconcileInstances(); + const rows = await db.query( + 'SELECT t.id,t.state,i.status FROM CronTriggers t JOIN RunningInstances i ON i.id=t.instance_id', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.find((r) => r.id === live), + { id: live, state: 'running', status: 0 }, + ); + assert.deepEqual( + rows.find((r) => r.id === gone), + { id: gone, state: 'unknown', status: 4 }, + ); + assert.equal(await db.models.CrontabStat.count(), 0); }); -test('stopping a supervisor still draining stdout preserves its already observed natural exit', async t => { - const {root,history,db,models}=await fixture(t); - const saved=process.env.QL_DATA_DIR;process.env.QL_DATA_DIR=root; - t.after(()=>{if(saved===undefined) delete process.env.QL_DATA_DIR;else process.env.QL_DATA_DIR=saved;}); - await models.CrontabModel.create({id:1,command:'true'}); - const id='already-exited'; - await history.enqueue(id,1,'manual',null);await history.start(id); - await history.bindCommand(id,process.pid); - const instance=await db.models.RunningInstance.findOne(); - require('../../back/shared/managedExit.cjs').writeExit(id,0,null,Date.now()); - let signals=0; - await assert.rejects(history.requestInstanceStop(instance.id,process.pid,()=>{signals++;},[systemOwner(process.pid)]),{code:'ESRCH'}); +test('stopping a supervisor still draining stdout preserves its already observed natural exit', async (t) => { + const { root, history, db, models } = await fixture(t); + const saved = process.env.QL_DATA_DIR; + process.env.QL_DATA_DIR = root; + t.after(() => { + if (saved === undefined) delete process.env.QL_DATA_DIR; + else process.env.QL_DATA_DIR = saved; + }); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const id = 'already-exited'; + await history.enqueue(id, 1, 'manual', null); + await history.start(id); + await history.bindCommand(id, process.pid); + const instance = await db.models.RunningInstance.findOne(); + require('../../back/cron/settlement/exitReceipt.cjs').writeExit( + id, + 0, + null, + Date.now(), + ); + let signals = 0; + await assert.rejects( + history.requestInstanceStop( + instance.id, + process.pid, + () => { + signals++; + }, + [systemOwner(process.pid)], + ), + { code: 'ESRCH' }, + ); await history.forgetStop(instance.id); - await history.complete(id,'failed',null,17); - assert.equal(signals,0); - assert.deepEqual((await history.recent(1,0)).map(r=>[r.state,r.exit_code]),[['finished',0]]); - assert.equal((await db.models.CrontabStat.findOne()).success_count,1); + await history.complete(id, 'failed', null, 17); + assert.equal(signals, 0); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.state, r.exit_code]), + [['finished', 0]], + ); + assert.equal((await db.models.CrontabStat.findOne()).success_count, 1); }); async function journalFixture(t) { @@ -2716,17 +4864,24 @@ async function journalFixture(t) { }); } await f.models.CrontabModel.create({ id: 1, command: 'true', status: 1 }); - return { ...f, ...require('../../back/shared/managedExit.cjs') }; + return { ...f, ...require('../../back/cron/settlement/exitReceipt.cjs') }; } // Older publishers left only the canonical file. Keep that on-disk layout // explicit in damage and mixed-version tests even as current writers evolve. function writeSingleFileExit(id, code, signal, time) { - const file = require('../../back/shared/managedExit.cjs').receiptPath(id); - const checksum = require('node:crypto').createHash('sha256') - .update(JSON.stringify([id, code, signal, time])).digest('hex'); + const file = + require('../../back/cron/settlement/exitReceipt.cjs').receiptPath(id); + const checksum = require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, code, signal, time])) + .digest('hex'); require('node:fs').mkdirSync(path.dirname(file), { recursive: true }); - require('node:fs').writeFileSync(file, JSON.stringify({ version: 1, code, signal, time, checksum }), { flag: 'wx' }); + require('node:fs').writeFileSync( + file, + JSON.stringify({ version: 1, code, signal, time, checksum }), + { flag: 'wx' }, + ); } test('duplicate supervisor publications preserve the first complete exit', async (t) => { @@ -2909,19 +5064,33 @@ test('replay can retire unreadable committed and pruned exits while a new instan await history.bindCommand(id, process.pid); } await history.complete('booked', 'failed', null, 17, start + 100); - for (const id of ['booked', 'pruned', 'new-exit']) writeExit(id, 0, null, start + 200); + for (const id of ['booked', 'pruned', 'new-exit']) + writeExit(id, 0, null, start + 200); const open = fs.open.bind(fs); t.mock.method(fs, 'open', (file, ...args) => { if ([receiptPath('booked'), receiptPath('pruned')].includes(file)) - throw Object.assign(new Error('stale receipt cannot be read'), { code: 'EACCES' }); + throw Object.assign(new Error('stale receipt cannot be read'), { + code: 'EACCES', + }); return open(file, ...args); }); - await Promise.all([history.interrupt('http'), history.complete('booked', 'finished', null, 0), - history.complete('pruned', 'failed', null, 99)]); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.id, r.exit_code]).sort(), - [['booked', 17], ['new-exit', 0]]); + await Promise.all([ + history.interrupt('http'), + history.complete('booked', 'finished', null, 0), + history.complete('pruned', 'failed', null, 99), + ]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.id, r.exit_code]).sort(), + [ + ['booked', 17], + ['new-exit', 0], + ], + ); const stat = await stats.CrontabStatModel.findOne(); - assert.deepEqual([stat.run_count, stat.fail_count, stat.success_count], [2, 1, 1]); + assert.deepEqual( + [stat.run_count, stat.fail_count, stat.success_count], + [2, 1, 1], + ); for (const id of ['booked', 'pruned', 'new-exit']) await assert.rejects(fs.stat(receiptPath(id)), { code: 'ENOENT' }); }); @@ -2929,7 +5098,7 @@ test('replay can retire unreadable committed and pruned exits while a new instan test('restart retires a committed script entry sample without consuming another execution’s pending sample', async (t) => { const { root, history, stats, writeExit } = await journalFixture(t); await fs.mkdir(path.join(root, '.tmp')); - const sample = id => path.join(root, '.tmp', 'cron-start-' + id); + const sample = (id) => path.join(root, '.tmp', 'cron-start-' + id); const start = Date.now() - 5000; for (const id of ['old', 'new']) { await history.enqueue(id, 1, 'manual', null, start); @@ -2939,61 +5108,107 @@ test('restart retires a committed script entry sample without consuming another } const unlink = fs.unlink.bind(fs); const hook = t.mock.method(fs, 'unlink', (file, ...args) => - file === sample('old') ? Promise.reject(new Error('interrupted unlink')) : unlink(file, ...args)); + file === sample('old') + ? Promise.reject(new Error('interrupted unlink')) + : unlink(file, ...args), + ); await history.complete('old', 'failed', null, 17, start + 200); hook.mock.restore(); - assert.equal((await history.visibleTriggers(1, ['old']))[0].script_started_at, start + 100); + assert.equal( + (await history.visibleTriggers(1, ['old']))[0].script_started_at, + start + 100, + ); await fs.writeFile(sample('unregistered'), String(start)); await fs.writeFile(sample('pruned'), String(start)); writeExit('pruned', 17, null, start + 100); await history.interrupt('grpc'); for (const id of ['old', 'pruned']) await assert.rejects(fs.stat(sample(id)), { code: 'ENOENT' }); - for (const id of ['new', 'unregistered']) assert.equal((await fs.stat(sample(id))).isFile(), true); + for (const id of ['new', 'unregistered']) + assert.equal((await fs.stat(sample(id))).isFile(), true); await history.complete('new', 'finished', null, 0, start + 300); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 2); }); test('delayed post-commit deletion only retires its own exit while cleanup and a later exit overlap', async (t) => { - const { db, history, stats, receiptPath, readExit, writeExit } = await journalFixture(t); + const { db, history, stats, receiptPath, readExit, writeExit } = + await journalFixture(t); const midnight = require('dayjs')().startOf('day'); - const old = midnight.subtract(3, 'day').valueOf(), fresh = midnight.valueOf(); - for (const [id, time] of [['old-run', old], ['new-run', fresh]]) { + const old = midnight.subtract(3, 'day').valueOf(), + fresh = midnight.valueOf(); + for (const [id, time] of [ + ['old-run', old], + ['new-run', fresh], + ]) { await history.enqueue(id, 1, 'manual', null, time); await history.start(id, time, true); await history.bindCommand(id, process.pid); } let reachedDeletion, allowDeletion; - const entered = new Promise(resolve => { reachedDeletion = resolve; }); - const resume = new Promise(resolve => { allowDeletion = resolve; }); + const entered = new Promise((resolve) => { + reachedDeletion = resolve; + }); + const resume = new Promise((resolve) => { + allowDeletion = resolve; + }); const rename = fs.rename.bind(fs); t.mock.method(fs, 'rename', async (file, ...args) => { - if (file === receiptPath('old-run')) { reachedDeletion(); await resume; } + if (file === receiptPath('old-run')) { + reachedDeletion(); + await resume; + } return rename(file, ...args); }); writeExit('old-run', 17, null, old + 50); const settling = history.complete('old-run', 'failed', null, 17); try { - await Promise.race([entered, settling.then(() => { throw Error('missing post-commit barrier'); })]); + await Promise.race([ + entered, + settling.then(() => { + throw Error('missing post-commit barrier'); + }), + ]); assert.equal((await stats.CrontabStatModel.findOne()).fail_count, 1); writeExit('new-run', 23, null, fresh + 150); assert.equal((await readExit('old-run')).code, 17); - } finally { allowDeletion(); } + } finally { + allowDeletion(); + } await settling; assert.equal((await readExit('new-run')).code, 23); writeExit('old-run', 17, null, old + 50); const cleanup = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - await Promise.all([cleanup.cleanup({runningInstanceRetentionDays: 1, cronStatRetentionDays: 1}), - history.complete('new-run', 'finished', null, 0), history.complete('old-run', 'finished', null, 0)]); + await Promise.all([ + cleanup.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }), + history.complete('new-run', 'finished', null, 0), + history.complete('old-run', 'finished', null, 0), + ]); writeExit('old-run', 17, null, old + 50); await history.interrupt('http'); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.id, r.exit_code]), [['new-run', 23]]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count, r.fail_count]), - [[midnight.format('YYYY-MM-DD'), 1, 1]]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.id, r.exit_code]), + [['new-run', 23]], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.fail_count, + ]), + [[midnight.format('YYYY-MM-DD'), 1, 1]], + ); assert.equal(await readExit('old-run'), undefined); assert.equal(await readExit('new-run'), undefined); }); @@ -3001,7 +5216,8 @@ test('delayed post-commit deletion only retires its own exit while cleanup and a test('an unavailable script sampling directory does not block replay of a pending command exit', async (t) => { const { root, history, writeExit, readExit } = await journalFixture(t); await fs.writeFile(path.join(root, '.tmp'), 'not a directory'); - const id = 'pending-supervisor', start = Date.now() - 1000; + const id = 'pending-supervisor', + start = Date.now() - 1000; await history.enqueue(id, 1, 'manual', null, start); await history.start(id, start, true); await history.bindCommand(id, process.pid); @@ -3021,7 +5237,9 @@ for (const fault of [ 'copied sibling receipt', ]) { test(`a pending exit with ${fault} survives cleanup and restarts while a sibling settles`, async (t) => { - const { db, history, stats, writeExit, receiptPath } = await journalFixture(t); + const { db, history, stats, writeExit, receiptPath } = await journalFixture( + t, + ); const day = require('dayjs')().startOf('day'); const start = day.subtract(4, 'day').valueOf(); const end = day.subtract(2, 'day').valueOf() + 500; @@ -3038,7 +5256,8 @@ for (const fault of [ for (const method of ['open', 'readFile']) { const fn = fs[method].bind(fs); t.mock.method(fs, method, (path, ...args) => { - if (path === file) throw Object.assign(new Error('denied'), { code: 'EACCES' }); + if (path === file) + throw Object.assign(new Error('denied'), { code: 'EACCES' }); return fn(path, ...args); }); } @@ -3046,9 +5265,16 @@ for (const fault of [ const contents = { 'truncated JSON': '{"code":', 'invalid fields': '{"code":true,"signal":null,"time":1}', - 'end before start': JSON.stringify({ code: 0, signal: null, time: start - 1 }), + 'end before start': JSON.stringify({ + code: 0, + signal: null, + time: start - 1, + }), 'changed code': JSON.stringify({ ...JSON.parse(original), code: 24 }), - 'copied sibling receipt': await fs.readFile(receiptPath('sibling-exit'), 'utf8'), + 'copied sibling receipt': await fs.readFile( + receiptPath('sibling-exit'), + 'utf8', + ), }; await fs.writeFile(file, contents[fault]); } @@ -3064,9 +5290,12 @@ for (const fault of [ assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); // Age the provisional observation past the history cutoff. The real // execution and its linked process row must still be available for repair. - await db.query("UPDATE CronTriggers SET finished_at=$end WHERE id='broken-exit'", { - bind: { end }, - }); + await db.query( + "UPDATE CronTriggers SET finished_at=$end WHERE id='broken-exit'", + { + bind: { end }, + }, + ); await db.query( "UPDATE RunningInstances SET finished_at=$end WHERE id=(SELECT instance_id FROM CronTriggers WHERE id='broken-exit')", { bind: { end: Math.floor(end / 1000) } }, @@ -3081,7 +5310,10 @@ for (const fault of [ '../data/system': {}, '../config': {}, }).default)(); - const policy = { runningInstanceRetentionDays: 1, cronStatRetentionDays: 7 }; + const policy = { + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 7, + }; for (let i = 0; i < 2; i++) { await history.interrupt('http'); await cleanup.cleanup(policy); @@ -3099,16 +5331,21 @@ for (const fault of [ history.complete('broken-exit', 'finished', null, 0), ]); const row = await result('broken-exit'); - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['failed', 23, end]); - const instance = await db.models.RunningInstance.findOne({ where: { exit_code: 23 } }); - assert.deepEqual([instance.status, instance.finished_at], [3, Math.floor(end / 1000)]); assert.deepEqual( - (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })).map((x) => [ - x.date, - x.run_count, - x.success_count, - x.fail_count, - ]), + [row.state, row.exit_code, row.finished_at], + ['failed', 23, end], + ); + const instance = await db.models.RunningInstance.findOne({ + where: { exit_code: 23 }, + }); + assert.deepEqual( + [instance.status, instance.finished_at], + [3, Math.floor(end / 1000)], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })).map( + (x) => [x.date, x.run_count, x.success_count, x.fail_count], + ), [ [day.subtract(2, 'day').format('YYYY-MM-DD'), 1, 0, 1], [day.format('YYYY-MM-DD'), 1, 1, 0], @@ -3133,14 +5370,24 @@ test('a repaired exit from an older supervisor respects a daily ledger that was await db.query('INSERT INTO CronStatRetention(id,first_day) VALUES(1,$day)', { bind: { day: day.format('YYYY-MM-DD') }, }); - await fs.writeFile(file, JSON.stringify({ code: 0, signal: null, time: start + 300 })); + await fs.writeFile( + file, + JSON.stringify({ code: 0, signal: null, time: start + 300 }), + ); await Promise.all([history.retryPendingExits(), history.interrupt('http')]); assert.equal((await history.recent(1, 0))[0].state, 'unknown'); await history.complete(id, 'finished', null, 0, start + 300); const [row] = await history.recent(1, 0); - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['finished', 0, start + 300]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['finished', 0, start + 300], + ); assert.equal( - (await db.query('SELECT counted FROM CronTriggers', { type: QueryTypes.SELECT }))[0].counted, + ( + await db.query('SELECT counted FROM CronTriggers', { + type: QueryTypes.SELECT, + }) + )[0].counted, 1, ); assert.equal(await stats.CrontabStatModel.count(), 0); @@ -3155,7 +5402,9 @@ test('a damaged stop receipt keeps the signalled tree tracked until verification await history.start(id, start, true); await history.bindCommand(id, process.pid); const instance = await db.models.RunningInstance.findOne(); - await history.requestInstanceStop(instance.id, process.pid, () => {}, [systemOwner(process.pid)]); + await history.requestInstanceStop(instance.id, process.pid, () => {}, [ + systemOwner(process.pid), + ]); writeSingleFileExit(id, 17, null, start + 500); const file = receiptPath(id), bytes = await fs.readFile(file); @@ -3169,7 +5418,10 @@ test('a damaged stop receipt keeps the signalled tree tracked until verification await fs.writeFile(file, bytes); await history.retryPendingExits(); const [row] = await history.recent(1, 0); - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['stopped', 17, start + 500]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['stopped', 17, start + 500], + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); }); @@ -3196,10 +5448,13 @@ test('an unverifiable exit prevents unconfirmed signals; a legacy instance witho await history.enqueue(id, 1, 'manual', null, start); await history.start(id, start, true); await history.bindCommand(id, process.pid); - const [linked] = await db.query('SELECT instance_id FROM CronTriggers WHERE id=$id', { - bind: { id }, - type: QueryTypes.SELECT, - }); + const [linked] = await db.query( + 'SELECT instance_id FROM CronTriggers WHERE id=$id', + { + bind: { id }, + type: QueryTypes.SELECT, + }, + ); writeSingleFileExit(id, 0, null, start + 100); await fs.writeFile(receiptPath(id), 'bad'); await assert.rejects( @@ -3241,9 +5496,15 @@ test('repair books a checksummed exit on the observed day even when the clock mo ); }); -for (const damage of ['swapped files', 'changed legal code', 'removed checksum']) { +for (const damage of [ + 'swapped files', + 'changed legal code', + 'removed checksum', +]) { test(`unbound legacy exits with ${damage} need independent per-execution evidence`, async (t) => { - const { history, db, stats, writeExit, receiptPath } = await journalFixture(t); + const { history, db, stats, writeExit, receiptPath } = await journalFixture( + t, + ); const end = Math.floor(Date.now() / 1000) * 1000 - 2000; const oldA = { code: 0, signal: null, time: end + 11 }; const oldB = { code: 23, signal: null, time: end + 22 }; @@ -3253,11 +5514,19 @@ for (const damage of ['swapped files', 'changed legal code', 'removed checksum'] await history.bindCommand(id, process.pid); } writeExit('new-c', 0, null, end + 33); - if (damage === 'removed checksum') writeSingleFileExit('old-a', 0, null, oldA.time); + if (damage === 'removed checksum') + writeSingleFileExit('old-a', 0, null, oldA.time); const a = damage === 'swapped files' ? oldB : { ...oldA, code: 24 }; await fs.writeFile(receiptPath('old-a'), JSON.stringify(a)); - await fs.writeFile(receiptPath('old-b'), JSON.stringify(damage === 'swapped files' ? oldA : oldB)); - const rows = () => db.query('SELECT id,state,exit_code,counted FROM CronTriggers ORDER BY id', { type: QueryTypes.SELECT }); + await fs.writeFile( + receiptPath('old-b'), + JSON.stringify(damage === 'swapped files' ? oldA : oldB), + ); + const rows = () => + db.query( + 'SELECT id,state,exit_code,counted FROM CronTriggers ORDER BY id', + { type: QueryTypes.SELECT }, + ); const first = [ { id: 'new-c', state: 'finished', exit_code: 0, counted: 1 }, { id: 'old-a', state: 'unknown', exit_code: null, counted: 0 }, @@ -3275,76 +5544,129 @@ for (const damage of ['swapped files', 'changed legal code', 'removed checksum'] assert.deepEqual(await rows(), first); } await fs.writeFile(receiptPath('old-b'), JSON.stringify(oldB)); - await Promise.all([1, 2].map(() => history.complete('old-b', 'failed', null, 23, oldB.time))); + await Promise.all( + [1, 2].map(() => + history.complete('old-b', 'failed', null, 23, oldB.time), + ), + ); assert.deepEqual(await rows(), first); await fs.unlink(receiptPath('old-b')); writeExit('old-b', 23, null, oldB.time); await history.retryPendingExits(); - assert.deepEqual(await rows(), [first[0], first[1], { id: 'old-b', state: 'failed', exit_code: 23, counted: 1 }]); + assert.deepEqual(await rows(), [ + first[0], + first[1], + { id: 'old-b', state: 'failed', exit_code: 23, counted: 1 }, + ]); const stat = await stats.CrontabStatModel.findOne(); - assert.deepEqual([stat.run_count, stat.success_count, stat.fail_count], [2, 1, 1]); + assert.deepEqual( + [stat.run_count, stat.success_count, stat.fail_count], + [2, 1, 1], + ); }); } for (const witnessed of [false, true]) { test(`restart during stop preserves the provenance of a legacy exit (witnessed=${witnessed})`, async (t) => { const { history, db, stats, receiptPath } = await journalFixture(t); - const id = 'old-stop', end = Date.now() - 1000; + const id = 'old-stop', + end = Date.now() - 1000; await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); const instance = await db.models.RunningInstance.findOne(); - await history.requestInstanceStop(instance.id, process.pid, () => {}, [systemOwner(process.pid)]); + await history.requestInstanceStop(instance.id, process.pid, () => {}, [ + systemOwner(process.pid), + ]); writeSingleFileExit(id, 0, null, end); const file = receiptPath(id); - await fs.writeFile(file, JSON.stringify({ code: null, signal: 'SIGTERM', time: end })); + await fs.writeFile( + file, + JSON.stringify({ code: null, signal: 'SIGTERM', time: end }), + ); // Upgrades can inherit a staged exit copied from the old, unchecked file. - await db.query('UPDATE CronTriggers SET stop_exit_at=$end,exit_code=24 WHERE id=$id', { - bind: { end: end - 5, id }, - }); + await db.query( + 'UPDATE CronTriggers SET stop_exit_at=$end,exit_code=24 WHERE id=$id', + { + bind: { end: end - 5, id }, + }, + ); if (witnessed) await history.complete(id, 'failed', 'SIGTERM', null, end); - await fs.writeFile(file, JSON.stringify({ code: 24, signal: null, time: end - 5 })); + await fs.writeFile( + file, + JSON.stringify({ code: 24, signal: null, time: end - 5 }), + ); await history.interrupt('http'); await history.interrupt('http'); assert.equal(await stats.CrontabStatModel.count(), 0); await history.stopVerifiedInstance(instance.id); const [row] = await history.recent(1, 0); - assert.deepEqual([row.state, row.exit_code, row.finished_at], - witnessed ? ['stopped', null, end] : ['unknown', null, null]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + witnessed ? ['stopped', null, end] : ['unknown', null, null], + ); assert.equal(await stats.CrontabStatModel.count(), Number(witnessed)); }); } test('a stored terminal result keeps its exit and day when a conflicting legacy marker replays', async (t) => { const { history, db, stats, receiptPath } = await journalFixture(t); - const id = 'stored-terminal', midnight = require('dayjs')().startOf('day'), + const id = 'stored-terminal', + midnight = require('dayjs')().startOf('day'), end = midnight.subtract(1, 'second').valueOf(); await history.enqueue(id, 1, 'manual', null, end - 2000); await history.start(id, end - 2000, true); await history.bindCommand(id, process.pid); await history.finish(id, 'failed', null, 17, undefined, end); writeSingleFileExit(id, 0, null, end + 2000); - await fs.writeFile(receiptPath(id), JSON.stringify({ code: 0, signal: null, time: end + 2000 })); - await Promise.all([history.interrupt('http'), history.complete(id, 'finished', null, 0)]); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.state, r.exit_code, r.finished_at]), [['failed', 17, end]]); + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 0, signal: null, time: end + 2000 }), + ); + await Promise.all([ + history.interrupt('http'), + history.complete(id, 'finished', null, 0), + ]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [ + r.state, + r.exit_code, + r.finished_at, + ]), + [['failed', 17, end]], + ); assert.equal((await db.models.RunningInstance.findOne()).exit_code, 17); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count, r.fail_count]), - [[midnight.subtract(1, 'day').format('YYYY-MM-DD'), 1, 1]]); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.fail_count, + ]), + [[midnight.subtract(1, 'day').format('YYYY-MM-DD'), 1, 1]], + ); }); test('the orphan reporter rejects a versioned message copied from a sibling before opening the database', async (t) => { const { receiptPath, writeExit } = await journalFixture(t); writeExit('sibling', 23, null, Date.now()); - const result = require('node:child_process').spawnSync(process.execPath, [ - require.resolve('../../back/shared/managedExit.cjs'), await fs.readFile(receiptPath('sibling'), 'utf8'), - ], { env: { ...process.env, QL_TRIGGER_ID: 'target' }, encoding: 'utf8' }); + const result = require('node:child_process').spawnSync( + process.execPath, + [ + require.resolve('../../back/shared/managedExit.cjs'), + await fs.readFile(receiptPath('sibling'), 'utf8'), + ], + { env: { ...process.env, QL_TRIGGER_ID: 'target' }, encoding: 'utf8' }, + ); assert.notEqual(result.status, 0); assert.match(result.stderr, /Invalid supervisor exit receipt/); }); test('crond retries confirm their registered system execution and leave other tasks and sources alone', async (t) => { - const { history, root, receiptPath, writeExit, stats } = await journalFixture(t); - const manual = 'system-1-manual', system = 'older-wrapper-id'; + const { history, root, receiptPath, writeExit, stats } = await journalFixture( + t, + ); + const manual = 'system-1-manual', + system = 'older-wrapper-id'; const start = Date.now() - 5000; await history.enqueue(manual, 1, 'manual', null, start); await history.start(manual, start, true); @@ -3352,44 +5674,83 @@ test('crond retries confirm their registered system execution and leave other ta await history.enqueue(system, 1, 'system', null, start); await history.start(system, start, true); const db = stats.CrontabStatModel.sequelize; - await db.query('UPDATE CronTriggers SET owner=$owner WHERE id=$id', { bind: { owner: systemOwner(process.pid), id: system } }); + await db.query('UPDATE CronTriggers SET owner=$owner WHERE id=$id', { + bind: { owner: systemOwner(process.pid), id: system }, + }); const end = Date.now(); writeSingleFileExit(system, 17, null, end); - await fs.writeFile(receiptPath(system), JSON.stringify({ code: 17, signal: null, time: end })); + await fs.writeFile( + receiptPath(system), + JSON.stringify({ code: 17, signal: null, time: end }), + ); await history.interrupt('http'); // Use the normal config path for the child process's independent connection. await fs.writeFile(path.join(root, '.env'), ''); - await fs.symlink(path.join(root, 'database.sqlite'), path.join(root, 'db', 'database.sqlite')); + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), + ); const report = (task, id, code) => { - const { status, stderr } = require('node:child_process').spawnSync(process.execPath, [ - '-r', 'ts-node/register/transpile-only', require.resolve('../../back/bootstrap/systemCron.ts'), - 'finish', String(task), '0', id, String(code), String(end), - ], { env: { ...process.env, QL_TRIGGER_ID: '', ID: '' }, encoding: 'utf8' }); + const { status, stderr } = require('node:child_process').spawnSync( + process.execPath, + [ + '-r', + 'ts-node/register/transpile-only', + require.resolve('../../back/bootstrap/systemCron.ts'), + 'finish', + String(task), + '0', + id, + String(code), + String(end), + ], + { env: { ...process.env, QL_TRIGGER_ID: '', ID: '' }, encoding: 'utf8' }, + ); assert.equal(status, 0, stderr); }; report(1, manual, 0); report(2, system, 17); assert.equal(await stats.CrontabStatModel.count(), 0); - assert.equal((await history.visibleTriggers(1, [system]))[0].state, 'unknown'); - assert.equal((await history.visibleTriggers(1, [manual]))[0].state, 'running'); + assert.equal( + (await history.visibleTriggers(1, [system]))[0].state, + 'unknown', + ); + assert.equal( + (await history.visibleTriggers(1, [manual]))[0].state, + 'running', + ); const original = await fs.readFile(receiptPath(system)); await fs.unlink(receiptPath(system)); report(1, system, 99); - assert.equal((await history.visibleTriggers(1, [system]))[0].state, 'unknown'); + assert.equal( + (await history.visibleTriggers(1, [system]))[0].state, + 'unknown', + ); await assert.rejects(fs.stat(receiptPath(system)), { code: 'ENOENT' }); await fs.writeFile(receiptPath(system), original); report(1, system, 17); report(1, system, 17); - assert.equal((await history.visibleTriggers(1, [system]))[0].reason, 'exit_conflict'); + assert.equal( + (await history.visibleTriggers(1, [system]))[0].reason, + 'exit_conflict', + ); await fs.unlink(receiptPath(system)); writeExit(system, 17, null, end); await history.retryPendingExits(); - assert.deepEqual((await history.visibleTriggers(1, [system])).map(row => [row.exit_code, row.finished_at]), [[17, end]]); + assert.deepEqual( + (await history.visibleTriggers(1, [system])).map((row) => [ + row.exit_code, + row.finished_at, + ]), + [[17, end]], + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); }); test('a valid bound supervisor message recovers its own damaged legacy file and disputes a conflicting bound publication', async (t) => { - const { history, root, receiptPath, writeExit, stats } = await journalFixture(t); + const { history, root, receiptPath, writeExit, stats } = await journalFixture( + t, + ); const end = Date.now() - 1000; await fs.writeFile(path.join(root, '.env'), ''); for (const id of ['weak-disk', 'strong-disk']) { @@ -3397,30 +5758,45 @@ test('a valid bound supervisor message recovers its own damaged legacy file and await history.start(id, end - 2000, true); await history.bindCommand(id, process.pid); writeExit(id, 17, null, end); - const file = receiptPath(id), observed = await fs.readFile(file, 'utf8'); + const file = receiptPath(id), + observed = await fs.readFile(file, 'utf8'); await fs.unlink(file); if (id === 'weak-disk') { - await fs.writeFile(file, JSON.stringify({ code: 24, signal: null, time: end })); + await fs.writeFile( + file, + JSON.stringify({ code: 24, signal: null, time: end }), + ); await history.interrupt('http'); - await fs.symlink(path.join(root, 'database.sqlite'), path.join(root, 'db', 'database.sqlite')); + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), + ); } else { writeExit(id, 23, null, end - 10); } - const { status, stderr } = require('node:child_process').spawnSync(process.execPath, [ - require.resolve('../../back/shared/managedExit.cjs'), observed, - ], { env: { ...process.env, QL_TRIGGER_ID: id }, encoding: 'utf8' }); + const { status, stderr } = require('node:child_process').spawnSync( + process.execPath, + [require.resolve('../../back/shared/managedExit.cjs'), observed], + { env: { ...process.env, QL_TRIGGER_ID: id }, encoding: 'utf8' }, + ); assert.equal(status, 0, stderr); } const rows = await history.recent(1, 0); - assert.deepEqual(rows.map(r => [r.id, r.exit_code, r.finished_at]).sort(), [ - ['strong-disk', null, null], ['weak-disk', 17, end], + assert.deepEqual(rows.map((r) => [r.id, r.exit_code, r.finished_at]).sort(), [ + ['strong-disk', null, null], + ['weak-disk', 17, end], ]); - assert.equal(rows.find(r => r.id === 'strong-disk').reason, 'exit_conflict'); + assert.equal( + rows.find((r) => r.id === 'strong-disk').reason, + 'exit_conflict', + ); assert.equal((await stats.CrontabStatModel.findOne()).fail_count, 1); }); for (const [initial, recovery] of [ - ['missing', 'poll'], ['damaged', 'restart'], ['swapped', 'cleanup'], + ['missing', 'poll'], + ['damaged', 'restart'], + ['swapped', 'cleanup'], ]) { test(`an early independent exit survives a ${initial} file, cleanup and two restarts until ${recovery}`, async (t) => { const { history, db, root, receiptPath, stats } = await journalFixture(t); @@ -3435,27 +5811,61 @@ for (const [initial, recovery] of [ } await fs.mkdir(path.dirname(receiptPath('early-a')), { recursive: true }); await fs.writeFile(path.join(root, '.env'), ''); - await fs.symlink(path.join(root, 'database.sqlite'), path.join(root, 'db', 'database.sqlite')); - const fileA = receiptPath('early-a'), fileB = receiptPath('early-b'); - if (initial !== 'missing') await fs.writeFile(fileA, initial === 'damaged' ? '{' : JSON.stringify(b)); - await fs.writeFile(fileB, JSON.stringify(a)); - const report = (id, observation) => require('node:util').promisify(require('node:child_process').execFile)( - process.execPath, [require.resolve('../../back/shared/managedExit.cjs'), JSON.stringify(observation)], - { env: { ...process.env, QL_TRIGGER_ID: id } }, + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), ); - await Promise.all([report('early-a', a), report('early-a', a), report('early-b', b)]); - const states = async () => (await history.recent(1, 0)).map(r => [r.id, r.state, r.exit_code, r.finished_at]).sort(); - const unknown = [['early-a', 'unknown', null, null], ['early-b', 'unknown', null, null]]; + const fileA = receiptPath('early-a'), + fileB = receiptPath('early-b'); + if (initial !== 'missing') + await fs.writeFile( + fileA, + initial === 'damaged' ? '{' : JSON.stringify(b), + ); + await fs.writeFile(fileB, JSON.stringify(a)); + const report = (id, observation) => + require('node:util').promisify(require('node:child_process').execFile)( + process.execPath, + [ + require.resolve('../../back/shared/managedExit.cjs'), + JSON.stringify(observation), + ], + { env: { ...process.env, QL_TRIGGER_ID: id } }, + ); + await Promise.all([ + report('early-a', a), + report('early-a', a), + report('early-b', b), + ]); + const states = async () => + (await history.recent(1, 0)) + .map((r) => [r.id, r.state, r.exit_code, r.finished_at]) + .sort(); + const unknown = [ + ['early-a', 'unknown', null, null], + ['early-b', 'unknown', null, null], + ]; assert.deepEqual(await states(), unknown); // Neither sibling can use the other's observation, even at the exact same millisecond. await history.retryPendingExits(); - await db.query('UPDATE CronTriggers SET finished_at=$start', { bind: { start } }); + await db.query('UPDATE CronTriggers SET finished_at=$start', { + bind: { start }, + }); const cleanup = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - const clean = () => cleanup.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 7 }); + const clean = () => + cleanup.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 7, + }); for (let pass = 0; pass < 2; pass++) { await history.interrupt('http'); await clean(); @@ -3464,27 +5874,48 @@ for (const [initial, recovery] of [ assert.equal(await stats.CrontabStatModel.count(), 0); // Restore only A's bytes. No successful A observation will be sent again. await fs.writeFile(fileA, JSON.stringify(a)); - const recover = { poll: () => history.retryPendingExits(), restart: () => history.interrupt('http'), cleanup: clean }; + const recover = { + poll: () => history.retryPendingExits(), + restart: () => history.interrupt('http'), + cleanup: clean, + }; await Promise.all([recover[recovery](), report('early-b', b)]); // Cleanup may legitimately prune A's old detail in the transaction that books it. if (recovery !== 'cleanup') { const [row] = await history.visibleTriggers(1, ['early-a']); - assert.deepEqual([row.state, row.reason, row.exit_code, row.finished_at], ['failed', 'SIGTERM', null, a.time]); + assert.deepEqual( + [row.state, row.reason, row.exit_code, row.finished_at], + ['failed', 'SIGTERM', null, a.time], + ); } const [sibling] = await history.visibleTriggers(1, ['early-b']); assert.equal(sibling.state, 'unknown'); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count, r.fail_count]), - [[midnight.format('YYYY-MM-DD'), 1, 1]]); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.fail_count, + ]), + [[midnight.format('YYYY-MM-DD'), 1, 1]], + ); await fs.writeFile(fileB, JSON.stringify(b)); - await Promise.all([history.retryPendingExits(), history.interrupt('http'), report('early-b', b)]); + await Promise.all([ + history.retryPendingExits(), + history.interrupt('http'), + report('early-b', b), + ]); const stat = await stats.CrontabStatModel.findOne(); - assert.deepEqual([stat.run_count, stat.success_count, stat.fail_count], [2, 1, 1]); + assert.deepEqual( + [stat.run_count, stat.success_count, stat.fail_count], + [2, 1, 1], + ); }); } test('a failed booking retains the early observation; a later retry respects the pruned daily ledger', async (t) => { const { history, db, stats, receiptPath } = await journalFixture(t); - const id = 'early-commit', day = require('dayjs')().startOf('day'), + const id = 'early-commit', + day = require('dayjs')().startOf('day'), end = day.subtract(3, 'day').valueOf(); await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); @@ -3492,26 +5923,48 @@ test('a failed booking retains the early observation; a later retry respects the writeSingleFileExit(id, 0, null, end); const file = receiptPath(id); await fs.writeFile(file, '{'); - await Promise.all([1, 2].map(() => history.complete(id, 'finished', null, 0, end))); - const observed = () => db.query('SELECT trigger_id,outcome,finished_at FROM CronExitObservations', { type: QueryTypes.SELECT }); + await Promise.all( + [1, 2].map(() => history.complete(id, 'finished', null, 0, end)), + ); + const observed = () => + db.query( + 'SELECT trigger_id,outcome,finished_at FROM CronExitObservations', + { type: QueryTypes.SELECT }, + ); const expected = [{ trigger_id: id, outcome: '0', finished_at: end }]; assert.deepEqual(await observed(), expected); // A malformed timestamp or an incomplete callback cannot corroborate a file. await history.complete(id, 'failed', null, 99); await history.complete(id, 'failed', null, 99, end - 2000); assert.deepEqual(await observed(), expected); - await fs.writeFile(file, JSON.stringify({ code: 0, signal: null, time: end })); + await fs.writeFile( + file, + JSON.stringify({ code: 0, signal: null, time: end }), + ); await db.query('CREATE TABLE needed(id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE deferred_ref(id INTEGER REFERENCES needed(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER fail_booking AFTER INSERT ON CrontabStats BEGIN INSERT INTO deferred_ref VALUES (1); END'); + await db.query( + 'CREATE TABLE deferred_ref(id INTEGER REFERENCES needed(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_booking AFTER INSERT ON CrontabStats BEGIN INSERT INTO deferred_ref VALUES (1); END', + ); await assert.rejects(history.retryPendingExits(), /constraint|foreign key/i); assert.deepEqual(await observed(), expected); assert.equal((await history.recent(1, 0))[0].state, 'unknown'); assert.equal(await stats.CrontabStatModel.count(), 0); await db.query('DROP TRIGGER fail_booking'); - await db.query('INSERT INTO CronStatRetention(id,first_day) VALUES(1,$day)', { bind: { day: day.format('YYYY-MM-DD') } }); + await db.query('INSERT INTO CronStatRetention(id,first_day) VALUES(1,$day)', { + bind: { day: day.format('YYYY-MM-DD') }, + }); await Promise.all([history.retryPendingExits(), history.interrupt('http')]); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.state, r.exit_code, r.finished_at]), [['finished', 0, end]]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [ + r.state, + r.exit_code, + r.finished_at, + ]), + [['finished', 0, end]], + ); assert.deepEqual(await observed(), []); assert.equal(await stats.CrontabStatModel.count(), 0); await assert.rejects(fs.stat(file), { code: 'ENOENT' }); @@ -3520,55 +5973,100 @@ test('a failed booking retains the early observation; a later retry respects the test('a timestamped crond retry saved during replacement only corroborates its registered task', async (t) => { const { history, db, root, stats, receiptPath } = await journalFixture(t); const id = 'older-crond-witness'; - assert.equal(await history.startSystem(id, 1, systemOwner(process.pid)), true); + assert.equal( + await history.startSystem(id, 1, systemOwner(process.pid)), + true, + ); const end = Date.now(); await fs.mkdir(path.dirname(receiptPath(id)), { recursive: true }); await fs.writeFile(path.join(root, '.env'), ''); - await fs.symlink(path.join(root, 'database.sqlite'), path.join(root, 'db', 'database.sqlite')); - const send = (task) => require('node:util').promisify(require('node:child_process').execFile)( - process.execPath, ['-r', 'ts-node/register/transpile-only', require.resolve('../../back/bootstrap/systemCron.ts'), - 'finish', String(task), '0', id, '19', String(end)], - { env: { ...process.env, QL_TRIGGER_ID: '', ID: '' } }, + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), ); + const send = (task) => + require('node:util').promisify(require('node:child_process').execFile)( + process.execPath, + [ + '-r', + 'ts-node/register/transpile-only', + require.resolve('../../back/bootstrap/systemCron.ts'), + 'finish', + String(task), + '0', + id, + '19', + String(end), + ], + { env: { ...process.env, QL_TRIGGER_ID: '', ID: '' } }, + ); await send(2); - assert.deepEqual(await db.query('SELECT * FROM CronExitObservations', { type: QueryTypes.SELECT }), []); + assert.deepEqual( + await db.query('SELECT * FROM CronExitObservations', { + type: QueryTypes.SELECT, + }), + [], + ); await send(1); await history.interrupt('http'); assert.equal((await history.recent(1, 0))[0].state, 'unknown'); - await fs.writeFile(receiptPath(id), JSON.stringify({ code: 19, signal: null, time: end })); + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 19, signal: null, time: end }), + ); await history.retryPendingExits(); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.exit_code, r.finished_at]), [[19, end]]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.exit_code, r.finished_at]), + [[19, end]], + ); assert.equal((await stats.CrontabStatModel.findOne()).fail_count, 1); }); test('a stopping legacy instance hides its provisional exit code until the early observation is corroborated', async (t) => { const { history, db, stats, receiptPath } = await journalFixture(t); - const id = 'early-stopping', end = Date.now() - 500; + const id = 'early-stopping', + end = Date.now() - 500; await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); const instance = await db.models.RunningInstance.findOne(); - await history.requestInstanceStop(instance.id, process.pid, () => {}, [systemOwner(process.pid)]); - await db.query('UPDATE CronTriggers SET exit_code=24,stop_exit_at=$end WHERE id=$id', { bind: { id, end: end - 1 } }); + await history.requestInstanceStop(instance.id, process.pid, () => {}, [ + systemOwner(process.pid), + ]); + await db.query( + 'UPDATE CronTriggers SET exit_code=24,stop_exit_at=$end WHERE id=$id', + { bind: { id, end: end - 1 } }, + ); writeSingleFileExit(id, 17, null, end); const file = receiptPath(id); await fs.writeFile(file, '{'); await history.complete(id, 'failed', null, 17, end); const [pending] = await history.visibleTriggers(1, [id]); - assert.deepEqual([pending.state, pending.reason, pending.exit_code, pending.finished_at], ['running', 'exit_pending', null, null]); + assert.deepEqual( + [pending.state, pending.reason, pending.exit_code, pending.finished_at], + ['running', 'exit_pending', null, null], + ); await history.interrupt('http'); - await fs.writeFile(file, JSON.stringify({ code: 17, signal: null, time: end })); + await fs.writeFile( + file, + JSON.stringify({ code: 17, signal: null, time: end }), + ); await history.retryPendingExits(); assert.equal(await stats.CrontabStatModel.count(), 0); await history.stopVerifiedInstance(instance.id); const [final] = await history.recent(1, 0); - assert.deepEqual([final.state, final.exit_code, final.finished_at], ['stopped', 17, end]); + assert.deepEqual( + [final.state, final.exit_code, final.finished_at], + ['stopped', 17, end], + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); }); for (const field of ['code', 'millisecond']) { test(`conflicting independent legacy reports (${field}) converge across all file and report orders`, async (t) => { - const { db, history, stats, receiptPath, writeExit } = await journalFixture(t); + const { db, history, stats, receiptPath, writeExit } = await journalFixture( + t, + ); const start = require('dayjs')().startOf('day').valueOf() - 5000; const a = { code: 17, signal: null, time: start + 5000 }; const b = field === 'code' ? { ...a, code: 0 } : { ...a, time: a.time - 1 }; @@ -3583,36 +6081,70 @@ for (const field of ['code', 'millisecond']) { for (const order of ['ABF', 'BAF', 'AFB', 'BFA', 'FAB', 'FBA']) { const id = 'conflict-' + order.toLowerCase(); await launch(id); - const report = r => history.complete(id, r.code ? 'failed' : 'finished', null, r.code, r.time, 'legacy'); + const report = (r) => + history.complete( + id, + r.code ? 'failed' : 'finished', + null, + r.code, + r.time, + 'legacy', + ); for (const event of order) { - if (event === 'F') await fs.writeFile(receiptPath(id), JSON.stringify(a)); + if (event === 'F') + await fs.writeFile(receiptPath(id), JSON.stringify(a)); else await report(event === 'A' ? a : b); await history.interrupt('http'); } await Promise.all([report(a), report(b), history.retryPendingExits()]); const [row] = await history.visibleTriggers(1, [id]); - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['unknown', null, null], order); - const [linked] = await db.query('SELECT i.status,i.exit_code FROM RunningInstances i JOIN CronTriggers t ON t.instance_id=i.id WHERE t.id=$id', - { bind: { id }, type: QueryTypes.SELECT }); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['unknown', null, null], + order, + ); + const [linked] = await db.query( + 'SELECT i.status,i.exit_code FROM RunningInstances i JOIN CronTriggers t ON t.instance_id=i.id WHERE t.id=$id', + { bind: { id }, type: QueryTypes.SELECT }, + ); assert.deepEqual(linked, { status: 4, exit_code: null }, order); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.run_count,r.success_count,r.fail_count,r.total_time,r.max_time]), - [[1,1,0,5000,5000]], order); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.run_count, + r.success_count, + r.fail_count, + r.total_time, + r.max_time, + ]), + [[1, 1, 0, 5000, 5000]], + order, + ); } }); } test('a failed COMMIT replacing a reversible legacy booking preserves the bound exit for a retry', async (t) => { - const { db, history, stats, receiptPath, writeExit, readExit } = await journalFixture(t); - const id = 'weak-before-commit', end = Date.now() - 500; - await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); + const { db, history, stats, receiptPath, writeExit, readExit } = + await journalFixture(t); + const id = 'weak-before-commit', + end = Date.now() - 500; + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); writeSingleFileExit(id, 0, null, end); - await fs.writeFile(receiptPath(id), JSON.stringify({ code: 0, signal: null, time: end })); + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 0, signal: null, time: end }), + ); await history.complete(id, 'finished', null, 0, end, 'legacy'); writeExit(id, 23, null, end + 10); await db.query('CREATE TABLE needed(id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE blocked(id INTEGER REFERENCES needed(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER fail_replacement AFTER INSERT ON CrontabStats BEGIN INSERT INTO blocked VALUES(1); END'); + await db.query( + 'CREATE TABLE blocked(id INTEGER REFERENCES needed(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_replacement AFTER INSERT ON CrontabStats BEGIN INSERT INTO blocked VALUES(1); END', + ); await assert.rejects(history.interrupt('http'), /constraint|foreign key/i); assert.equal((await stats.CrontabStatModel.findOne()).success_count, 1); assert.equal((await readExit(id))?.code, 23); @@ -3620,124 +6152,243 @@ test('a failed COMMIT replacing a reversible legacy booking preserves the bound await history.interrupt('http'); await history.complete(id, 'finished', null, 0, end, 'legacy'); const [result] = await history.recent(1, 0); - assert.deepEqual([result.exit_code,result.finished_at], [23,end + 10]); + assert.deepEqual([result.exit_code, result.finished_at], [23, end + 10]); const stat = await stats.CrontabStatModel.findOne(); - assert.deepEqual([stat.run_count,stat.success_count,stat.fail_count,stat.max_time], [1,0,1,1010]); + assert.deepEqual( + [stat.run_count, stat.success_count, stat.fail_count, stat.max_time], + [1, 0, 1, 1010], + ); }); test('archived legacy corrections preserve anonymous and sibling maxima without recreating history or pruned days', async (t) => { - const { db, history, stats, receiptPath, writeExit } = await journalFixture(t); - const day = require('dayjs')().startOf('day').subtract(3, 'day'), start = day.valueOf(); + const { db, history, stats, receiptPath, writeExit } = await journalFixture( + t, + ); + const day = require('dayjs')().startOf('day').subtract(3, 'day'), + start = day.valueOf(); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - await stats.CrontabStatModel.create({ ref_id:1,date:day.format('YYYY-MM-DD'),run_count:2,success_count:2,total_time:120,max_time:80 }); - for (const [id, ms] of [['a',500],['b',220],['strong',150]]) { - await history.enqueue(id, 1, 'manual', null, start); await history.start(id,start,true); - await history.bindCommand(id,process.pid); writeSingleFileExit(id,0,null,start+ms); - if (id !== 'strong') await fs.writeFile(receiptPath(id),JSON.stringify({code:0,signal:null,time:start+ms})); - await history.complete(id,'finished',null,0,start+ms); + await stats.CrontabStatModel.create({ + ref_id: 1, + date: day.format('YYYY-MM-DD'), + run_count: 2, + success_count: 2, + total_time: 120, + max_time: 80, + }); + for (const [id, ms] of [ + ['a', 500], + ['b', 220], + ['strong', 150], + ]) { + await history.enqueue(id, 1, 'manual', null, start); + await history.start(id, start, true); + await history.bindCommand(id, process.pid); + writeSingleFileExit(id, 0, null, start + ms); + if (id !== 'strong') + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 0, signal: null, time: start + ms }), + ); + await history.complete(id, 'finished', null, 0, start + ms); } - const totals = async () => (await stats.CrontabStatModel.findAll({order:[['date','ASC']]})).map(s=>[s.date,s.run_count,s.total_time,s.max_time]); - const old = day.format('YYYY-MM-DD'), kept = day.add(3,'day'); - await policy.cleanup({runningInstanceRetentionDays:1,cronStatRetentionDays:7}); - assert.equal((await history.recent(1,0)).length,0); - await Promise.all([1,2].map(()=>history.complete('a','failed',null,17,start+500,'legacy'))); - assert.deepEqual(await totals(),[[old,4,490,220]]); - await history.complete('b','finished',null,0,start+221,'legacy'); - assert.deepEqual(await totals(),[[old,3,270,150]]); - writeExit('a',17,null,kept.valueOf()+10); + const totals = async () => + (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })).map( + (s) => [s.date, s.run_count, s.total_time, s.max_time], + ); + const old = day.format('YYYY-MM-DD'), + kept = day.add(3, 'day'); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 7, + }); + assert.equal((await history.recent(1, 0)).length, 0); + await Promise.all( + [1, 2].map(() => + history.complete('a', 'failed', null, 17, start + 500, 'legacy'), + ), + ); + assert.deepEqual(await totals(), [[old, 4, 490, 220]]); + await history.complete('b', 'finished', null, 0, start + 221, 'legacy'); + assert.deepEqual(await totals(), [[old, 3, 270, 150]]); + writeExit('a', 17, null, kept.valueOf() + 10); await history.interrupt('http'); - assert.deepEqual(await totals(),[[old,3,270,150],[kept.format('YYYY-MM-DD'),1,kept.valueOf()+10-start,kept.valueOf()+10-start]]); - assert.equal((await history.recent(1,0)).length,0); - await policy.cleanup({runningInstanceRetentionDays:1,cronStatRetentionDays:1}); - await history.complete('b','finished',null,0,start+220,'legacy'); - assert.equal((await totals()).length,1); - assert.equal((await totals())[0][0],kept.format('YYYY-MM-DD')); + assert.deepEqual(await totals(), [ + [old, 3, 270, 150], + [ + kept.format('YYYY-MM-DD'), + 1, + kept.valueOf() + 10 - start, + kept.valueOf() + 10 - start, + ], + ]); + assert.equal((await history.recent(1, 0)).length, 0); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); + await history.complete('b', 'finished', null, 0, start + 220, 'legacy'); + assert.equal((await totals()).length, 1); + assert.equal((await totals())[0][0], kept.format('YYYY-MM-DD')); }); test('a conflict invalidates a staged legacy stop while its process tree still needs verification', async (t) => { - const { db, history, stats, receiptPath, writeExit } = await journalFixture(t); - const id='staged-conflict', end=Date.now()-100; - await history.enqueue(id,1,'manual',null,end-500); await history.start(id,end-500,true); - await history.bindCommand(id,process.pid); - const instance=await db.models.RunningInstance.findOne(); - await history.requestInstanceStop(instance.id,process.pid,()=>{},[systemOwner(process.pid)]); - writeSingleFileExit(id,17,null,end); - await fs.writeFile(receiptPath(id),JSON.stringify({code:17,signal:null,time:end})); - await history.complete(id,'failed',null,17,end,'legacy'); - await history.complete(id,'failed',null,23,end,'legacy'); + const { db, history, stats, receiptPath, writeExit } = await journalFixture( + t, + ); + const id = 'staged-conflict', + end = Date.now() - 100; + await history.enqueue(id, 1, 'manual', null, end - 500); + await history.start(id, end - 500, true); + await history.bindCommand(id, process.pid); + const instance = await db.models.RunningInstance.findOne(); + await history.requestInstanceStop(instance.id, process.pid, () => {}, [ + systemOwner(process.pid), + ]); + writeSingleFileExit(id, 17, null, end); + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 17, signal: null, time: end }), + ); + await history.complete(id, 'failed', null, 17, end, 'legacy'); + await history.complete(id, 'failed', null, 23, end, 'legacy'); await history.interrupt('http'); - assert.equal((await history.recent(1,0))[0].state,'running'); + assert.equal((await history.recent(1, 0))[0].state, 'running'); await history.stopVerifiedInstance(instance.id); - assert.equal((await history.recent(1,0))[0].reason,'exit_conflict'); - assert.equal(await stats.CrontabStatModel.count(),0); - await fs.unlink(receiptPath(id)); writeExit(id,17,null,end); + assert.equal((await history.recent(1, 0))[0].reason, 'exit_conflict'); + assert.equal(await stats.CrontabStatModel.count(), 0); + await fs.unlink(receiptPath(id)); + writeExit(id, 17, null, end); await history.retryPendingExits(); - assert.deepEqual((await history.recent(1,0)).map(r=>[r.state,r.exit_code]),[['stopped',17]]); - const stat=await stats.CrontabStatModel.findOne(); - assert.deepEqual([stat.run_count,stat.fail_count,stat.success_count],[1,0,0]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [r.state, r.exit_code]), + [['stopped', 17]], + ); + const stat = await stats.CrontabStatModel.findOne(); + assert.deepEqual( + [stat.run_count, stat.fail_count, stat.success_count], + [1, 0, 0], + ); }); -test('instance history hides provisional exits and preserves confirmed siblings', async t => { +test('instance history hides provisional exits and preserves confirmed siblings', async (t) => { const { db, history } = await fixture(t); const model = db.models.RunningInstance; - const make = (cron_id, status) => model.create({ cron_id, status, started_at: 100, finished_at: 102, exit_code: 17 }); + const make = (cron_id, status) => + model.create({ + cron_id, + status, + started_at: 100, + finished_at: 102, + exit_code: 17, + }); const pending = await make(1, 4); const confirmed = await make(1, 3); const interrupted = await make(1, 4); const unrelated = await make(2, 3); // A later start can belong to a lower ID (e.g. an imported execution). await model.update({ started_at: 101 }, { where: { id: pending.id } }); - await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,reason,observed_at,instance_id,finished_at,exit_code) - VALUES ('interrupted',1,'manual','unknown','restart',100000,$instance,102000,17)`, { bind: { instance: interrupted.id } }); - const [row] = await history.visibleTriggers(1,['interrupted']); - assert.deepEqual([row.reason,row.finished_at,row.exit_code], ['restart',null,null]); - await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,instance_id,exit_pending) - VALUES ('disputed',1,'manual','unknown',100000,$instance,1)`, { bind: { instance: pending.id } }); + await db.query( + `INSERT INTO CronTriggers(id,cron_id,source,state,reason,observed_at,instance_id,finished_at,exit_code) + VALUES ('interrupted',1,'manual','unknown','restart',100000,$instance,102000,17)`, + { bind: { instance: interrupted.id } }, + ); + const [row] = await history.visibleTriggers(1, ['interrupted']); + assert.deepEqual( + [row.reason, row.finished_at, row.exit_code], + ['restart', null, null], + ); + await db.query( + `INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,instance_id,exit_pending) + VALUES ('disputed',1,'manual','unknown',100000,$instance,1)`, + { bind: { instance: pending.id } }, + ); const api = load('back/api/cron.ts', { - '../services/cron': class {}, '../services/cronView': class {}, + '../services/cron': class {}, + '../services/cronView': class {}, '../data/runningInstance': { RunningInstanceModel: model }, - '../schedule/client': {}, '../validation/schedule': { commonCronSchema: {} }, + '../schedule/client': {}, + '../validation/schedule': { commonCronSchema: {} }, }); const app = express().use(express.json()); api.default(app); app.use(require('celebrate').errors()); const server = app.listen(0, '127.0.0.1'); await require('node:events').once(server, 'listening'); - t.after(() => new Promise(resolve => server.close(resolve))); - const response = await fetch('http://127.0.0.1:' + server.address().port + '/crons/1/instances'); + t.after(() => new Promise((resolve) => server.close(resolve))); + const response = await fetch( + 'http://127.0.0.1:' + server.address().port + '/crons/1/instances', + ); assert.equal(response.status, 200); const { data } = await response.json(); - assert.deepEqual(data.sort((a, b) => a.id - b.id).map(row => [row.id, row.status, row.finished_at, row.exit_code]), - [[pending.id, 4, null, null], [confirmed.id, 3, 102, 17], [interrupted.id, 4, null, null]]); - const page = async query => (await fetch(response.url + '?' + query)).json(); + assert.deepEqual( + data + .sort((a, b) => a.id - b.id) + .map((row) => [row.id, row.status, row.finished_at, row.exit_code]), + [ + [pending.id, 4, null, null], + [confirmed.id, 3, 102, 17], + [interrupted.id, 4, null, null], + ], + ); + const page = async (query) => + (await fetch(response.url + '?' + query)).json(); const legacy = await page(''); assert.equal(legacy.data[0].id, pending.id); - for (const query of ['limit=1', 'ids=invalid&before=no', 'paged=false&limit=0']) { + for (const query of [ + 'limit=1', + 'ids=invalid&before=no', + 'paged=false&limit=0', + ]) { assert.deepEqual(await page(query), legacy); } assert.equal(Object.hasOwn(legacy, 'next'), false); const first = await page('paged=true&limit=2'); - assert.deepEqual(first.data.map(row => row.id), [interrupted.id, confirmed.id]); + assert.deepEqual( + first.data.map((row) => row.id), + [interrupted.id, confirmed.id], + ); assert.equal(first.next, confirmed.id); await make(1, 3); const second = await page('paged=true&limit=2&before=' + first.next); - assert.deepEqual(second.data.map(row => row.id), [pending.id]); + assert.deepEqual( + second.data.map((row) => row.id), + [pending.id], + ); assert.equal(second.next, null); - const refreshed = await page('paged=true&ids=' + [pending.id, unrelated.id].join(',')); - assert.deepEqual(refreshed.data.map(row => [row.id, row.exit_code]), [[pending.id, null]]); + const refreshed = await page( + 'paged=true&ids=' + [pending.id, unrelated.id].join(','), + ); + assert.deepEqual( + refreshed.data.map((row) => [row.id, row.exit_code]), + [[pending.id, null]], + ); assert.equal((await page('paged=true')).next, null); for (const invalid of ['limit=0', 'before=bad', 'ids=bad', 'ids=1&limit=2']) { - assert.equal((await fetch(response.url + '?paged=true&' + invalid)).status, 400); + assert.equal( + (await fetch(response.url + '?paged=true&' + invalid)).status, + 400, + ); } }); -for (const scenario of ['archive then dispute', 'expire both then dispute', 'dispute with retained history', 'correct to an expired day']) { - test(`cross-day correction after ${scenario} survives cleanup, restart and mixed receipt replay`, async t => { - const { db, history, stats, receiptPath, writeExit, readExit } = await journalFixture(t); +for (const scenario of [ + 'archive then dispute', + 'expire both then dispute', + 'dispute with retained history', + 'correct to an expired day', +]) { + test(`cross-day correction after ${scenario} survives cleanup, restart and mixed receipt replay`, async (t) => { + const { db, history, stats, receiptPath, writeExit, readExit } = + await journalFixture(t); const today = require('dayjs')().startOf('day'); const original = today.subtract(3, 'day'); const expiredTarget = scenario === 'correct to an expired day'; @@ -3748,14 +6399,40 @@ for (const scenario of ['archive then dispute', 'expire both then dispute', 'dis const id = 'old-execution'; const keepHistory = scenario === 'dispute with retained history'; const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - const cleanup = (historyDays, statDays) => policy.cleanup({ runningInstanceRetentionDays: historyDays, cronStatRetentionDays: statDays }); - const oldReport = code => history.complete(id, code ? 'failed' : 'finished', null, code, end, 'legacy'); - const ledger = async () => (await stats.CrontabStatModel.findAll({ order: [['date','ASC']] })) - .map(row => [row.date, row.run_count, row.success_count, row.fail_count, row.total_time, row.max_time]); + const cleanup = (historyDays, statDays) => + policy.cleanup({ + runningInstanceRetentionDays: historyDays, + cronStatRetentionDays: statDays, + }); + const oldReport = (code) => + history.complete( + id, + code ? 'failed' : 'finished', + null, + code, + end, + 'legacy', + ); + const ledger = async () => + (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })).map( + (row) => [ + row.date, + row.run_count, + row.success_count, + row.fail_count, + row.total_time, + row.max_time, + ], + ); async function startRun(key, time) { await history.enqueue(key, 1, 'manual', null, time); await history.start(key, time, true); @@ -3770,59 +6447,105 @@ for (const scenario of ['archive then dispute', 'expire both then dispute', 'dis writeExit('retained-sibling', 0, null, siblingStart + 400); await history.interrupt('http'); await startRun(id, start); - await fs.writeFile(receiptPath(id), JSON.stringify({ code: 0, signal: null, time: end })); + await fs.writeFile( + receiptPath(id), + JSON.stringify({ code: 0, signal: null, time: end }), + ); await oldReport(0); - assert.deepEqual((await ledger())[0], [original.format('YYYY-MM-DD'), 2, 2, 0, 2300, 2000]); - if (!keepHistory) await cleanup(1, scenario === 'expire both then dispute' ? 1 : 7); + assert.deepEqual((await ledger())[0], [ + original.format('YYYY-MM-DD'), + 2, + 2, + 0, + 2300, + 2000, + ]); + if (!keepHistory) + await cleanup(1, scenario === 'expire both then dispute' ? 1 : 7); await Promise.all([oldReport(17), oldReport(17)]); if (scenario !== 'expire both then dispute') { - assert.deepEqual((await ledger())[0], [original.format('YYYY-MM-DD'), 1, 1, 0, 300, 300]); + assert.deepEqual((await ledger())[0], [ + original.format('YYYY-MM-DD'), + 1, + 1, + 0, + 300, + 300, + ]); } await cleanup(keepHistory ? 7 : 1, 1); await history.interrupt('http'); await history.interrupt('http'); - assert.equal((await history.visibleTriggers(1, [id])).length, Number(keepHistory)); + assert.equal( + (await history.visibleTriggers(1, [id])).length, + Number(keepHistory), + ); writeExit(id, 23, null, newEnd); const bound = await readExit(id); if (scenario === 'archive then dispute') { // No trigger remains. A failed COMMIT must leave the sole recovered receipt usable. await db.query('CREATE TABLE required_parent(id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER fail_correction AFTER UPDATE ON CrontabStats BEGIN INSERT INTO deferred_child VALUES(1); END'); - await assert.rejects(history.retryPendingExits(), /constraint|foreign key/i); + await db.query( + 'CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_correction AFTER UPDATE ON CrontabStats BEGIN INSERT INTO deferred_child VALUES(1); END', + ); + await assert.rejects( + history.retryPendingExits(), + /constraint|foreign key/i, + ); assert.equal((await readExit(id)).time, newEnd); assert.equal((await ledger())[0][1], 1); await db.query('DROP TRIGGER fail_correction'); } if (scenario === 'expire both then dispute') { - await Promise.all([history.retryPendingExits(), oldReport(0), oldReport(17), cleanup(1, 1), - history.complete(id, 'failed', null, 23, newEnd, bound), history.interrupt('http')]); + await Promise.all([ + history.retryPendingExits(), + oldReport(0), + oldReport(17), + cleanup(1, 1), + history.complete(id, 'failed', null, 23, newEnd, bound), + history.interrupt('http'), + ]); } else { // A file restored after startup must also settle without another callback. await history.retryPendingExits(); } const retainedDay = today.subtract(1, 'day').format('YYYY-MM-DD'); const duration = newEnd - start; - const expected = expiredTarget ? [[retainedDay, 1, 1, 0, 400, 400]] : - [[retainedDay, 2, 1, 1, duration + 400, duration]]; + const expected = expiredTarget + ? [[retainedDay, 1, 1, 0, 400, 400]] + : [[retainedDay, 2, 1, 1, duration + 400, duration]]; assert.deepEqual(await ledger(), expected); assert.equal(await readExit(id), undefined); writeExit(id, 23, null, newEnd); - await Promise.all([oldReport(0), oldReport(17), history.complete(id, 'failed', null, 23, newEnd, bound), - history.interrupt('http'), cleanup(keepHistory ? 7 : 1, 1)]); + await Promise.all([ + oldReport(0), + oldReport(17), + history.complete(id, 'failed', null, 23, newEnd, bound), + history.interrupt('http'), + cleanup(keepHistory ? 7 : 1, 1), + ]); assert.deepEqual(await ledger(), expected); const visible = await history.visibleTriggers(1, [id]); - assert.deepEqual(visible.map(row => [row.state, row.exit_code, row.finished_at]), keepHistory ? [['failed', 23, newEnd]] : []); + assert.deepEqual( + visible.map((row) => [row.state, row.exit_code, row.finished_at]), + keepHistory ? [['failed', 23, newEnd]] : [], + ); const summary = await db.models.Crontab.findByPk(1); assert.equal(summary.last_execution_time, Math.floor(siblingStart / 1000)); }); } -test('a restored bound receipt survives replacement at the instant the weak receipt is retired', async t => { - const { db, history, stats, writeExit, receiptPath } = await journalFixture(t); +test('a restored bound receipt survives replacement at the instant the weak receipt is retired', async (t) => { + const { db, history, stats, writeExit, receiptPath } = await journalFixture( + t, + ); const midnight = require('dayjs')().startOf('day').valueOf(); - const id = 'replaced-at-retirement', file = receiptPath(id); + const id = 'replaced-at-retirement', + file = receiptPath(id); await history.enqueue(id, 1, 'manual', null, midnight - 3000); await history.start(id, midnight - 3000, true); await history.bindCommand(id, process.pid); @@ -3831,14 +6554,20 @@ test('a restored bound receipt survives replacement at the instant the weak rece const remove = fs.rm.bind(fs); const restored = file + '.test-restore'; await rename(file, restored); - await fs.writeFile(file, JSON.stringify({ code: 0, signal: null, time: midnight - 10 })); + await fs.writeFile( + file, + JSON.stringify({ code: 0, signal: null, time: midnight - 10 }), + ); let replaced = false; async function restore(source) { if (source !== file || replaced) return; replaced = true; await rename(restored, file); } - t.mock.method(fs, 'rm', async (source, options) => { await restore(source); return remove(source, options); }); + t.mock.method(fs, 'rm', async (source, options) => { + await restore(source); + return remove(source, options); + }); t.mock.method(fs, 'rename', async (source, dest) => { await restore(source); await rename(source, dest); @@ -3850,12 +6579,26 @@ test('a restored bound receipt survives replacement at the instant the weak rece await history.complete(id, 'failed', null, 23, midnight - 10, 'legacy'); await new TriggerHistory(db).interrupt('http'); await history.interrupt('http'); - assert.deepEqual((await history.recent(1, 0)).map(r => [r.state, r.exit_code, r.finished_at]), [['failed', 17, midnight + 100]]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count, r.success_count, r.fail_count]), - [[require('dayjs')(midnight).format('YYYY-MM-DD'), 1, 0, 1]]); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => [ + r.state, + r.exit_code, + r.finished_at, + ]), + [['failed', 17, midnight + 100]], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.success_count, + r.fail_count, + ]), + [[require('dayjs')(midnight).format('YYYY-MM-DD'), 1, 0, 1]], + ); }); -test('unavailable retirement storage cannot block a sibling exit during restart or polling', async t => { +test('unavailable retirement storage cannot block a sibling exit during restart or polling', async (t) => { const { history, stats, writeExit, receiptPath } = await journalFixture(t); const end = Date.now(); const ids = ['retiring', 'confirmed-sibling']; @@ -3866,30 +6609,45 @@ test('unavailable retirement storage cannot block a sibling exit during restart writeExit(id, 0, null, end); } const root = path.dirname(receiptPath(ids[0])); - const moved = path.join(root, '.retiring.retiring.' + require('node:crypto').randomUUID()); - await fs.writeFile(moved, JSON.stringify({ code: 0, signal: null, time: end })); + const moved = path.join( + root, + '.retiring.retiring.' + require('node:crypto').randomUUID(), + ); + await fs.writeFile( + moved, + JSON.stringify({ code: 0, signal: null, time: end }), + ); const remove = fs.unlink.bind(fs); let disposalAttempts = 0; t.mock.method(fs, 'unlink', (file) => { - if (!path.basename(file).startsWith('.pending.retiring.')) return remove(file); + if (!path.basename(file).startsWith('.pending.retiring.')) + return remove(file); disposalAttempts++; - return Promise.reject(Object.assign(new Error('temporarily busy'), { code: 'EBUSY' })); + return Promise.reject( + Object.assign(new Error('temporarily busy'), { code: 'EBUSY' }), + ); }); const list = fs.readdir.bind(fs); t.mock.method(fs, 'readdir', async (dir, options) => { - if (path.dirname(dir) === root) throw Object.assign(new Error('unreadable'), { code: 'EACCES' }); + if (path.dirname(dir) === root) + throw Object.assign(new Error('unreadable'), { code: 'EACCES' }); return list(dir, options); }); await history.interrupt('http'); await history.retryPendingExits(); assert.ok(disposalAttempts >= 2); - assert.deepEqual((await history.recent(1, 0)).map(r => r.state), ['finished', 'finished']); + assert.deepEqual( + (await history.recent(1, 0)).map((r) => r.state), + ['finished', 'finished'], + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 2); }); for (const difference of ['code', 'day', 'identical']) { - test(`canonical and retiring bound receipts converge across reads and replays: ${difference}`, async t => { - const { history, db, stats, writeExit, receiptPath } = await journalFixture(t); + test(`canonical and retiring bound receipts converge across reads and replays: ${difference}`, async (t) => { + const { history, db, stats, writeExit, receiptPath } = await journalFixture( + t, + ); const midnight = require('dayjs')().startOf('day').valueOf(); const start = midnight - 4000; async function launch(id) { @@ -3905,10 +6663,17 @@ for (const difference of ['code', 'day', 'identical']) { const id = 'clash-' + order; await launch(id); const canonical = receiptPath(id); - const moved = path.join(path.dirname(canonical), '.retiring.' + id + '.' + require('node:crypto').randomUUID()); + const moved = path.join( + path.dirname(canonical), + '.retiring.' + id + '.' + require('node:crypto').randomUUID(), + ); const a = [0, null, midnight - 1]; - const b = [difference === 'code' ? 23 : 0, null, difference === 'day' ? midnight + 1 : midnight - 1]; - const [first, second] = order === 'opposite' ? [b,a] : [a,b]; + const b = [ + difference === 'code' ? 23 : 0, + null, + difference === 'day' ? midnight + 1 : midnight - 1, + ]; + const [first, second] = order === 'opposite' ? [b, a] : [a, b]; writeExit(id, ...first); const stagedBytes = await fs.readFile(canonical); await fs.rename(canonical, moved); @@ -3920,7 +6685,11 @@ for (const difference of ['code', 'day', 'identical']) { await history.complete(id, 'unknown', null, null); await fs.writeFile(moved, stagedBytes); } - await Promise.all([history.interrupt('http'),history.retryPendingExits(),history.complete(id, 'unknown', null, null)]); + await Promise.all([ + history.interrupt('http'), + history.retryPendingExits(), + history.complete(id, 'unknown', null, null), + ]); for (let attempt = 0; attempt < 2; attempt++) { await fs.writeFile(moved, stagedBytes); await fs.writeFile(canonical, publishedBytes); @@ -3928,50 +6697,89 @@ for (const difference of ['code', 'day', 'identical']) { } const [row] = await history.visibleTriggers(1, [id]); if (difference === 'identical') { - assert.deepEqual([row.state,row.finished_at,row.exit_code], ['finished',midnight-1,0], order); - await assert.rejects(fs.stat(moved), {code:'ENOENT'}); - await assert.rejects(fs.stat(canonical), {code:'ENOENT'}); + assert.deepEqual( + [row.state, row.finished_at, row.exit_code], + ['finished', midnight - 1, 0], + order, + ); + await assert.rejects(fs.stat(moved), { code: 'ENOENT' }); + await assert.rejects(fs.stat(canonical), { code: 'ENOENT' }); } else { - assert.deepEqual([row.state,row.reason,row.finished_at,row.exit_code], ['unknown','exit_conflict',null,null], order); + assert.deepEqual( + [row.state, row.reason, row.finished_at, row.exit_code], + ['unknown', 'exit_conflict', null, null], + order, + ); assert.deepEqual(await fs.readFile(canonical), publishedBytes); assert.deepEqual(await fs.readFile(moved), stagedBytes); } } const [total] = await stats.CrontabStatModel.findAll(); const count = difference === 'identical' ? orders.length : 0; - assert.deepEqual([total.run_count,total.success_count,total.fail_count,total.total_time,total.max_time], - [1+count,1+count,0,300+count*3999,count ? 3999 : 300]); + assert.deepEqual( + [ + total.run_count, + total.success_count, + total.fail_count, + total.total_time, + total.max_time, + ], + [1 + count, 1 + count, 0, 300 + count * 3999, count ? 3999 : 300], + ); assert.equal(await stats.CrontabStatModel.count(), 1); }); } -test('late bound conflict after pruning debits only a retained contribution and keeps both dates closed to replay', async t => { - const { db, history, stats, writeExit, receiptPath } = await journalFixture(t); - const today = require('dayjs')().startOf('day'), old = today.subtract(3, 'day'); +test('late bound conflict after pruning debits only a retained contribution and keeps both dates closed to replay', async (t) => { + const { db, history, stats, writeExit, receiptPath } = await journalFixture( + t, + ); + const today = require('dayjs')().startOf('day'), + old = today.subtract(3, 'day'); const retained = today.subtract(1, 'day').valueOf() + 100; const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - for (const [id, end] of [['system-cli-expired-bound',old.valueOf()+100], ['system-cli-archived-bound',retained]]) { + for (const [id, end] of [ + ['system-cli-expired-bound', old.valueOf() + 100], + ['system-cli-archived-bound', retained], + ]) { await history.enqueue(id, 1, 'manual', null, old.valueOf()); await history.start(id, old.valueOf(), true); await history.bindCommand(id, process.pid); writeExit(id, 0, null, end); await history.complete(id, 'unknown', null, null); } - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); await clean(); assert.equal((await history.recent(1, 0)).length, 0); for (const id of ['system-cli-expired-bound', 'system-cli-archived-bound']) { const file = receiptPath(id); - const end = id === 'system-cli-expired-bound' ? old.valueOf()+100 : retained; + const end = + id === 'system-cli-expired-bound' ? old.valueOf() + 100 : retained; writeExit(id, 0, null, end); - const moved = path.join(path.dirname(file), '.retiring.'+id+'.'+require('node:crypto').randomUUID()); + const moved = path.join( + path.dirname(file), + '.retiring.' + id + '.' + require('node:crypto').randomUUID(), + ); await fs.rename(file, moved); - writeExit(id, 17, null, today.valueOf()+100); - await Promise.all([history.interrupt('http'), history.retryPendingExits(), clean()]); + writeExit(id, 17, null, today.valueOf() + 100); + await Promise.all([ + history.interrupt('http'), + history.retryPendingExits(), + clean(), + ]); await history.interrupt('http'); assert.equal(JSON.parse(await fs.readFile(moved)).code, 0); assert.equal(JSON.parse(await fs.readFile(file)).code, 17); @@ -3979,9 +6787,22 @@ test('late bound conflict after pruning debits only a retained contribution and // the trigger and its entire original ledger had expired before detection. await fs.unlink(moved); const now = Date.now(); - await Promise.all([history.interrupt('http'), - history.reportInstance(id, 1, false, process.pid, 'replayed.log', Math.floor(now/1000), 1, 0, false, now), - history.recordShellResult(id, 1, 0, 1000, now, now)]); + await Promise.all([ + history.interrupt('http'), + history.reportInstance( + id, + 1, + false, + process.pid, + 'replayed.log', + Math.floor(now / 1000), + 1, + 0, + false, + now, + ), + history.recordShellResult(id, 1, 0, 1000, now, now), + ]); assert.equal(JSON.parse(await fs.readFile(file)).code, 17); } @@ -3989,22 +6810,32 @@ test('late bound conflict after pruning debits only a retained contribution and assert.equal((await history.recent(1, 0)).length, 0); }); -test('a failed conflict commit retains both bound files and rolls back its debit and evidence together', async t => { - const { history, db, stats, writeExit, receiptPath } = await journalFixture(t); - const id = 'bound-conflict-rollback', end = Date.now() - 100; - await history.enqueue(id, 1, 'manual', null, end-500); - await history.start(id, end-500, true); +test('a failed conflict commit retains both bound files and rolls back its debit and evidence together', async (t) => { + const { history, db, stats, writeExit, receiptPath } = await journalFixture( + t, + ); + const id = 'bound-conflict-rollback', + end = Date.now() - 100; + await history.enqueue(id, 1, 'manual', null, end - 500); + await history.start(id, end - 500, true); await history.bindCommand(id, process.pid); writeExit(id, 0, null, end); await history.complete(id, 'finished', null, 0); writeExit(id, 0, null, end); const file = receiptPath(id); - const moved = path.join(path.dirname(file), '.retiring.'+id+'.'+require('node:crypto').randomUUID()); + const moved = path.join( + path.dirname(file), + '.retiring.' + id + '.' + require('node:crypto').randomUUID(), + ); await fs.rename(file, moved); - writeExit(id, 17, null, end+10); + writeExit(id, 17, null, end + 10); await db.query('CREATE TABLE required_parent(id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER fail_dispute AFTER INSERT ON CronBoundExitConflicts BEGIN INSERT INTO deferred_child VALUES(1); END'); + await db.query( + 'CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_dispute AFTER INSERT ON CronBoundExitConflicts BEGIN INSERT INTO deferred_child VALUES(1); END', + ); await assert.rejects(history.interrupt('http'), /constraint|foreign key/i); assert.equal((await stats.CrontabStatModel.findOne()).success_count, 1); assert.equal((await history.visibleTriggers(1, [id]))[0].state, 'finished'); @@ -4013,33 +6844,54 @@ test('a failed conflict commit retains both bound files and rolls back its debit await db.query('DROP TRIGGER fail_dispute'); await Promise.all([history.retryPendingExits(), history.interrupt('http')]); assert.equal(await stats.CrontabStatModel.count(), 0); - assert.equal((await history.visibleTriggers(1, [id]))[0].reason, 'exit_conflict'); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); }); -test('a pre-upgrade aggregate without a per-execution booking survives conflicting bound evidence', async t => { - const { history, db, stats, writeExit, receiptPath } = await journalFixture(t); - const id = 'pre-upgrade-conflict', end = Date.now()-100; - await history.enqueue(id, 1, 'manual', null, end-1000); - await history.start(id, end-1000, true); +test('a pre-upgrade aggregate without a per-execution booking survives conflicting bound evidence', async (t) => { + const { history, db, stats, writeExit, receiptPath } = await journalFixture( + t, + ); + const id = 'pre-upgrade-conflict', + end = Date.now() - 100; + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); // This models a panel that committed a terminal row and aggregate without recording the receipt provenance. await history.complete(id, 'finished', null, 0, end); writeExit(id, 0, null, end); const file = receiptPath(id); - await fs.rename(file, path.join(path.dirname(file), '.retiring.'+id+'.'+require('node:crypto').randomUUID())); + await fs.rename( + file, + path.join( + path.dirname(file), + '.retiring.' + id + '.' + require('node:crypto').randomUUID(), + ), + ); writeExit(id, 23, null, end); await history.interrupt('http'); await history.interrupt('http'); - assert.equal((await history.visibleTriggers(1, [id]))[0].reason, 'exit_conflict'); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); const daily = await stats.CrontabStatModel.findOne(); - assert.deepEqual([daily.run_count,daily.success_count,daily.fail_count,daily.total_time], [1,1,0,1000]); + assert.deepEqual( + [daily.run_count, daily.success_count, daily.fail_count, daily.total_time], + [1, 1, 0, 1000], + ); }); for (const rollback of [false, true]) { - test(`third bound receipt during withdrawal survives commit, replay and history cleanup: rollback=${rollback}`, async t => { - const { db, history, writeExit, receiptPath, readExit, stats } = await journalFixture(t); - const id = 'three-receipts', midnight = require('dayjs')().startOf('day').valueOf(); - const old = midnight - 3 * 86400000, file = receiptPath(id); + test(`third bound receipt during withdrawal survives commit, replay and history cleanup: rollback=${rollback}`, async (t) => { + const { db, history, writeExit, receiptPath, readExit, stats } = + await journalFixture(t); + const id = 'three-receipts', + midnight = require('dayjs')().startOf('day').valueOf(); + const old = midnight - 3 * 86400000, + file = receiptPath(id); for (const task of [id, 'independent']) { await history.enqueue(task, 1, 'manual', null, old); await history.start(task, old, true); @@ -4050,20 +6902,34 @@ for (const rollback of [false, true]) { writeExit(id, 17, null, midnight - 1); const second = await readExit(id); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); if (rollback) { await db.query('CREATE TABLE third_parent(id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE third_child(id INTEGER REFERENCES third_parent(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER third_failure AFTER INSERT ON CronBoundExitConflicts BEGIN INSERT INTO third_child VALUES(1); END'); + await db.query( + 'CREATE TABLE third_child(id INTEGER REFERENCES third_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER third_failure AFTER INSERT ON CronBoundExitConflicts BEGIN INSERT INTO third_child VALUES(1); END', + ); } let injected = false; const query = db.query.bind(db); const hook = t.mock.method(db, 'query', async (sql, ...args) => { const result = await query(sql, ...args); - if (!injected && String(sql).includes('DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id')) { + if ( + !injected && + String(sql).includes( + 'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id', + ) + ) { injected = true; writeExit(id, 23, null, midnight + 1); writeExit(id, 23, null, midnight + 1); @@ -4071,50 +6937,91 @@ for (const rollback of [false, true]) { return result; }); if (rollback) { - await assert.rejects(history.interrupt('http'), /constraint|foreign key/i); + await assert.rejects( + history.interrupt('http'), + /constraint|foreign key/i, + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 2); await db.query('DROP TRIGGER third_failure'); } else await history.interrupt('http'); assert.ok(injected); hook.mock.restore(); for (let pass = 0; pass < 2; pass++) { - await Promise.all([new TriggerHistory(db).interrupt('http'), history.retryPendingExits(), - history.complete(id, 'failed', null, second.code, second.time, second)]); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + history.complete(id, 'failed', null, second.code, second.time, second), + ]); const day = await stats.CrontabStatModel.findOne(); - assert.deepEqual([day.run_count, day.success_count, day.total_time], [1, 1, 200]); + assert.deepEqual( + [day.run_count, day.success_count, day.total_time], + [1, 1, 200], + ); } - assert.equal((await history.visibleTriggers(1, [id]))[0].reason, 'exit_conflict'); - await policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); // When only the canonical path is restored later, polling must still ingest it. - for (const entry of await fs.readdir(path.dirname(file))) await fs.unlink(path.join(path.dirname(file), entry)); + for (const entry of await fs.readdir(path.dirname(file))) + await fs.unlink(path.join(path.dirname(file), entry)); writeExit(id, null, 'SIGTERM', midnight + 2); await history.retryPendingExits(); await fs.unlink(file); await new TriggerHistory(db).interrupt('http'); - const evidence = await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - { bind: { id }, type: QueryTypes.SELECT }); - assert.deepEqual(evidence.map(e => [e.outcome, e.finished_at]), [ - ['0', old+200], ['17', midnight-1], ['23', midnight+1], ['SIGTERM', midnight+2], - ]); + const evidence = await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ); + assert.deepEqual( + evidence.map((e) => [e.outcome, e.finished_at]), + [ + ['0', old + 200], + ['17', midnight - 1], + ['23', midnight + 1], + ['SIGTERM', midnight + 2], + ], + ); assert.equal(await stats.CrontabStatModel.count(), 0); }); } -test('a stale collector cannot unlink a third bound publication restored at the retirement path', async t => { - const { db, history, receiptPath, writeExit, readExit, retiringExits, stats } = await journalFixture(t); - const id = 'collector-race', end = Date.now() - 1000, file = receiptPath(id); +test('a stale collector cannot unlink a third bound publication restored at the retirement path', async (t) => { + const { + db, + history, + receiptPath, + writeExit, + readExit, + retiringExits, + stats, + } = await journalFixture(t); + const id = 'collector-race', + end = Date.now() - 1000, + file = receiptPath(id); await history.enqueue(id, 1, 'manual', null, end - 200); await history.start(id, end - 200, true); await history.bindCommand(id, process.pid); writeExit(id, 0, null, end); await history.complete(id, 'finished', null, 0); writeExit(id, 0, null, end); - const restored = path.join(path.dirname(file), '.retiring.' + id + '.' + require('node:crypto').randomUUID()); + const restored = path.join( + path.dirname(file), + '.retiring.' + id + '.' + require('node:crypto').randomUUID(), + ); await fs.rename(file, restored); const rename = fs.rename.bind(fs); let resume, entered; - const paused = new Promise(resolve => { entered = resolve; }); - const release = new Promise(resolve => { resume = resolve; }); + const paused = new Promise((resolve) => { + entered = resolve; + }); + const release = new Promise((resolve) => { + resume = resolve; + }); let intercepted = false; t.mock.method(fs, 'rename', async (src, dest) => { if (src === restored && !intercepted) { @@ -4126,88 +7033,206 @@ test('a stale collector cannot unlink a third bound publication restored at the }); const stale = history.retryPendingExits(); try { - await Promise.race([paused, stale.then(() => { throw Error('missing retirement barrier'); })]); - writeExit(id, 17, null, end+1); + await Promise.race([ + paused, + stale.then(() => { + throw Error('missing retirement barrier'); + }), + ]); + writeExit(id, 17, null, end + 1); await history.complete(id, 'unknown', null, null); - assert.equal((await history.visibleTriggers(1,[id]))[0].reason, 'exit_conflict'); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); // Replace the exact public path that the stale worker is about to claim. - const third = { code: 23, signal: null, time: end+2, version: 1, checksum: require('node:crypto').createHash('sha256') - .update(JSON.stringify([id,23,null,end+2])).digest('hex') }; - await fs.writeFile(restored+'.restore', JSON.stringify(third)); - await rename(restored+'.restore', restored); - } finally { resume(); } + const third = { + code: 23, + signal: null, + time: end + 2, + version: 1, + checksum: require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, 23, null, end + 2])) + .digest('hex'), + }; + await fs.writeFile(restored + '.restore', JSON.stringify(third)); + await rename(restored + '.restore', restored); + } finally { + resume(); + } await stale; - assert.ok((await Promise.all((await retiringExits()).map(copy => readExit(id,copy.file)))).some(exit => exit?.code===23)); - await Promise.all([new TriggerHistory(db).interrupt('http'), history.retryPendingExits()]); - assert.deepEqual((await db.query('SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at', {type:QueryTypes.SELECT})).map(v=>v.outcome), - ['0','17','23']); + assert.ok( + ( + await Promise.all( + (await retiringExits()).map((copy) => readExit(id, copy.file)), + ) + ).some((exit) => exit?.code === 23), + ); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + ]); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ) + ).map((v) => v.outcome), + ['0', '17', '23'], + ); assert.equal(await stats.CrontabStatModel.count(), 0); }); -test('upgrading the two-tuple conflict journal retains both outcomes when a third arrives only as a supervisor message', async t => { +test('upgrading the two-tuple conflict journal retains both outcomes when a third arrives only as a supervisor message', async (t) => { const { db, history } = await journalFixture(t); const id = 'archived-conflict'; await db.query('DROP TABLE CronBoundExitConflicts'); - await db.query('CREATE TABLE CronBoundExitConflicts(trigger_id TEXT PRIMARY KEY,outcome TEXT,finished_at INTEGER,other_outcome TEXT,other_finished_at INTEGER) WITHOUT ROWID'); - await db.query("INSERT INTO CronBoundExitConflicts VALUES($id,'0',1000,'17',1001)", {bind:{id}}); - await db.transaction(tx => installTriggerHistory(db,tx)); - const third = { code:null, signal:'SIGTERM',time:1002,version:1 }; - await Promise.all([history.complete(id,'failed','SIGTERM',null,1002,third),history.complete(id,'failed','SIGTERM',null,1002,third)]); - await db.transaction(tx => installTriggerHistory(db,tx)); - assert.deepEqual((await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at',{type:QueryTypes.SELECT})) - .map(v=>[v.outcome,v.finished_at]), [['0',1000],['17',1001],['SIGTERM',1002]]); - assert.deepEqual(await history.visibleTriggers(1,[id]), []); + await db.query( + 'CREATE TABLE CronBoundExitConflicts(trigger_id TEXT PRIMARY KEY,outcome TEXT,finished_at INTEGER,other_outcome TEXT,other_finished_at INTEGER) WITHOUT ROWID', + ); + await db.query( + "INSERT INTO CronBoundExitConflicts VALUES($id,'0',1000,'17',1001)", + { bind: { id } }, + ); + await db.transaction((tx) => installTriggerHistory(db, tx)); + const third = { code: null, signal: 'SIGTERM', time: 1002, version: 1 }; + await Promise.all([ + history.complete(id, 'failed', 'SIGTERM', null, 1002, third), + history.complete(id, 'failed', 'SIGTERM', null, 1002, third), + ]); + await db.transaction((tx) => installTriggerHistory(db, tx)); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ) + ).map((v) => [v.outcome, v.finished_at]), + [ + ['0', 1000], + ['17', 1001], + ['SIGTERM', 1002], + ], + ); + assert.deepEqual(await history.visibleTriggers(1, [id]), []); assert.equal(await db.models.CrontabStat.count(), 0); }); -test('a Python supervisor and a reporter killed before SQLite accepts its message preserve every distinct exit', async t => { - const { db, history, root, writeExit, receiptPath, readExit, retiringExits } = await journalFixture(t); - const id = 'orphan-withdrawal', time = Date.now()-5000; +test('a Python supervisor and a reporter killed before SQLite accepts its message preserve every distinct exit', async (t) => { + const { db, history, root, writeExit, receiptPath, readExit, retiringExits } = + await journalFixture(t); + const id = 'orphan-withdrawal', + time = Date.now() - 5000; const file = receiptPath(id); writeExit(id, 0, null, time); - writeExit(id, 17, null, time+1); + writeExit(id, 17, null, time + 1); await history.interrupt('http'); const env = { ...process.env, QL_TRIGGER_ID: id }; const { spawnSync, spawn } = require('node:child_process'); - const supervisor = spawnSync('python3', ['-I', '-S', path.resolve('shell/cron-command.py'), 'exit 23', - String(process.pid), file, process.execPath, require.resolve('../../back/shared/managedExit.cjs')], - { env, input: 'run\n', encoding:'utf8' }); + const supervisor = spawnSync( + 'python3', + [ + '-I', + '-S', + path.resolve('shell/cron-command.py'), + 'exit 23', + String(process.pid), + file, + process.execPath, + require.resolve('../../back/shared/managedExit.cjs'), + ], + { env, input: 'run\n', encoding: 'utf8' }, + ); assert.equal(supervisor.status, 23, supervisor.stderr); - const copies = await Promise.all((await retiringExits()).map(c => readExit(id,c.file))); - assert.ok(copies.some(copy => copy?.code === 23)); - await fs.writeFile(path.join(root,'.env'),''); - await fs.symlink(path.join(root,'database.sqlite'),path.join(root,'db','database.sqlite')); - const code = 29, end = time + 2; - const checksum = require('node:crypto').createHash('sha256').update(JSON.stringify([id,code,null,end])).digest('hex'); - const message = JSON.stringify({code,signal:null,time:end,checksum,version:1}); + const copies = await Promise.all( + (await retiringExits()).map((c) => readExit(id, c.file)), + ); + assert.ok(copies.some((copy) => copy?.code === 23)); + await fs.writeFile(path.join(root, '.env'), ''); + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), + ); + const code = 29, + end = time + 2; + const checksum = require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, code, null, end])) + .digest('hex'); + const message = JSON.stringify({ + code, + signal: null, + time: end, + checksum, + version: 1, + }); await db.transaction(async () => { - const child = spawn(process.execPath,[require.resolve('../../back/shared/managedExit.cjs'),message], {env,stdio:'ignore'}); - const closed = new Promise(resolve => child.once('close', resolve)); + const child = spawn( + process.execPath, + [require.resolve('../../back/shared/managedExit.cjs'), message], + { env, stdio: 'ignore' }, + ); + const closed = new Promise((resolve) => child.once('close', resolve)); try { - const until = Date.now()+5000; + const until = Date.now() + 5000; let found = false; - while (!found && Date.now() readExit(id,copy.file))); - found = copies.some(copy => copy?.code === code && copy.time === end); - if (!found) await new Promise(resolve => setTimeout(resolve,25)); + while (!found && Date.now() < until) { + const copies = await Promise.all( + (await retiringExits()).map((copy) => readExit(id, copy.file)), + ); + found = copies.some((copy) => copy?.code === code && copy.time === end); + if (!found) await new Promise((resolve) => setTimeout(resolve, 25)); } assert.ok(found, 'the message is on disk before SQLite accepts it'); - } finally { child.kill('SIGKILL'); await closed; } + } finally { + child.kill('SIGKILL'); + await closed; + } }); await new TriggerHistory(db).interrupt('http'); - assert.deepEqual((await db.query('SELECT outcome FROM CronBoundExitConflicts ORDER BY CAST(outcome AS INTEGER)',{type:QueryTypes.SELECT})) - .map(v=>v.outcome), ['0','17','23','29']); - assert.equal(await db.models.CrontabStat.count(),0); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome FROM CronBoundExitConflicts ORDER BY CAST(outcome AS INTEGER)', + { type: QueryTypes.SELECT }, + ) + ).map((v) => v.outcome), + ['0', '17', '23', '29'], + ); + assert.equal(await db.models.CrontabStat.count(), 0); }); -for (const occupied of ['damaged', 'different valid result', 'symlink to a sibling receipt']) { - test(`concurrent orphan reports survive a kill before SQLite with an occupied alternate: ${occupied}`, async t => { - const { history, db, root, writeExit, readExit, receiptPath, retiringExits, stats } = await journalFixture(t); - const id = 'occupied-alternate', midnight = require('dayjs')().startOf('day').valueOf(); - const file = receiptPath(id), end = midnight + 100; +for (const occupied of [ + 'damaged', + 'different valid result', + 'symlink to a sibling receipt', +]) { + test(`concurrent orphan reports survive a kill before SQLite with an occupied alternate: ${occupied}`, async (t) => { + const { + history, + db, + root, + writeExit, + readExit, + receiptPath, + retiringExits, + stats, + } = await journalFixture(t); + const id = 'occupied-alternate', + midnight = require('dayjs')().startOf('day').valueOf(); + const file = receiptPath(id), + end = midnight + 100; const make = (code, time) => ({ - version: 1, code, signal: null, time, checksum: require('node:crypto').createHash('sha256') - .update(JSON.stringify([id,code,null,time])).digest('hex'), + version: 1, + code, + signal: null, + time, + checksum: require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, code, null, time])) + .digest('hex'), }); for (const key of [id, 'healthy-sibling']) { await history.enqueue(key, 1, 'manual', null, midnight - 1000); @@ -4217,140 +7242,274 @@ for (const occupied of ['damaged', 'different valid result', 'symlink to a sibli } writeExit(id, 17, null, end); await history.interrupt('http'); - const third = make(23, end+100), fourth = make(31,end+200); - const alternate = path.join(path.dirname(file), '.published.' + id + '.' + third.checksum); - const occupant = occupied === 'damaged' ? '{"version":' : JSON.stringify(fourth); + const third = make(23, end + 100), + fourth = make(31, end + 200); + const alternate = path.join( + path.dirname(file), + '.published.' + id + '.' + third.checksum, + ); + const occupant = + occupied === 'damaged' ? '{"version":' : JSON.stringify(fourth); if (occupied === 'symlink to a sibling receipt') { - const sibling = path.join(root,'sibling-receipt'); - const checksum = require('node:crypto').createHash('sha256') - .update(JSON.stringify(['healthy-sibling',fourth.code,null,fourth.time])).digest('hex'); - await fs.writeFile(sibling, JSON.stringify({...fourth,checksum})); - await fs.symlink(sibling,alternate); + const sibling = path.join(root, 'sibling-receipt'); + const checksum = require('node:crypto') + .createHash('sha256') + .update( + JSON.stringify(['healthy-sibling', fourth.code, null, fourth.time]), + ) + .digest('hex'); + await fs.writeFile(sibling, JSON.stringify({ ...fourth, checksum })); + await fs.symlink(sibling, alternate); } else await fs.writeFile(alternate, occupant); const originalBytes = await fs.readFile(alternate); // Stop at the real reporter's first database import, after its filesystem publication. const barrier = path.join(root, 'before-database.cjs'); - await fs.writeFile(barrier, `const Module=require('node:module'), load=Module._load; + await fs.writeFile( + barrier, + `const Module=require('node:module'), load=Module._load; Module._load=function(name,...args) { - if (name === './triggerHistory') { + if (name === '../cron/history') { require('node:fs').writeFileSync(process.env.ARRIVED, 'ready'); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0); } return load.call(this,name,...args); - };`); - const children = [1,2].map(index => { - const arrived = path.join(root, 'reporter-'+index); - const child = require('node:child_process').spawn(process.execPath, ['--require',barrier, - require.resolve('../../back/shared/managedExit.cjs'),JSON.stringify(third)], - {env:{...process.env, QL_TRIGGER_ID:id, ARRIVED:arrived},stdio:'ignore'}); - return {arrived,child,closed:new Promise(resolve => child.once('close',resolve))}; + };`, + ); + const children = [1, 2].map((index) => { + const arrived = path.join(root, 'reporter-' + index); + const child = require('node:child_process').spawn( + process.execPath, + [ + '--require', + barrier, + require.resolve('../../back/shared/managedExit.cjs'), + JSON.stringify(third), + ], + { + env: { ...process.env, QL_TRIGGER_ID: id, ARRIVED: arrived }, + stdio: 'ignore', + }, + ); + return { + arrived, + child, + closed: new Promise((resolve) => child.once('close', resolve)), + }; }); try { - const deadline = Date.now()+10000; - while (Date.now()require('node:fs').existsSync(c.arrived))) - await new Promise(resolve=>setTimeout(resolve,25)); - assert.ok(children.every(c=>require('node:fs').existsSync(c.arrived))); + const deadline = Date.now() + 10000; + while ( + Date.now() < deadline && + !children.every((c) => require('node:fs').existsSync(c.arrived)) + ) + await new Promise((resolve) => setTimeout(resolve, 25)); + assert.ok( + children.every((c) => require('node:fs').existsSync(c.arrived)), + ); } finally { for (const c of children) c.child.kill('SIGKILL'); - await Promise.all(children.map(c=>c.closed)); + await Promise.all(children.map((c) => c.closed)); } - const diskEvidence = async () => (await Promise.all((await retiringExits()).map(c=>readExit(id,c.file)))) - .filter(c=>c?.code===third.code && c.time===third.time); - assert.ok((await diskEvidence()).length > 0, 'third tuple must already be recoverable without a database commit'); - assert.deepEqual(await fs.readFile(alternate),originalBytes); - for (let attempt=0; attempt<3; attempt++) { - writeExit(id,third.code,null,third.time); - await Promise.all([new TriggerHistory(db).interrupt('http'),history.retryPendingExits()]); - assert.equal((await diskEvidence()).length,1, 'retain one physical witness per distinct retry result'); + const diskEvidence = async () => + ( + await Promise.all( + (await retiringExits()).map((c) => readExit(id, c.file)), + ) + ).filter((c) => c?.code === third.code && c.time === third.time); + assert.ok( + (await diskEvidence()).length > 0, + 'third tuple must already be recoverable without a database commit', + ); + assert.deepEqual(await fs.readFile(alternate), originalBytes); + for (let attempt = 0; attempt < 3; attempt++) { + writeExit(id, third.code, null, third.time); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + ]); + assert.equal( + (await diskEvidence()).length, + 1, + 'retain one physical witness per distinct retry result', + ); } - const rows = await db.query('SELECT outcome FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - {bind:{id},type:QueryTypes.SELECT}); - assert.deepEqual(rows.map(row=>row.outcome),occupied==='different valid result'?['0','17','23','31']:['0','17','23']); - assert.deepEqual(await fs.readFile(alternate),originalBytes); - assert.equal((await fs.lstat(alternate)).isSymbolicLink(),occupied==='symlink to a sibling receipt'); - assert.equal((await history.visibleTriggers(1,[id]))[0].reason,'exit_conflict'); + const rows = await db.query( + 'SELECT outcome FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.map((row) => row.outcome), + occupied === 'different valid result' + ? ['0', '17', '23', '31'] + : ['0', '17', '23'], + ); + assert.deepEqual(await fs.readFile(alternate), originalBytes); + assert.equal( + (await fs.lstat(alternate)).isSymbolicLink(), + occupied === 'symlink to a sibling receipt', + ); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); const [stat] = await stats.CrontabStatModel.findAll(); - assert.deepEqual([stat.run_count,stat.success_count,stat.total_time],[1,1,990]); - assert.equal(await stats.CrontabStatModel.count(),1); + assert.deepEqual( + [stat.run_count, stat.success_count, stat.total_time], + [1, 1, 990], + ); + assert.equal(await stats.CrontabStatModel.count(), 1); }); } for (const runtime of ['node', 'python']) { - test(`a fully written ${runtime} receipt survives SIGKILL before its first link`, async t => { - const { history, db, writeExit, receiptPath, retiringExits, readExit } = await journalFixture(t); - const id = 'prelink-' + runtime, file = receiptPath(id), end = Date.now()-10; - writeExit(id, 0, null, end-2); - writeExit(id, 17, null, end-1); + test(`a fully written ${runtime} receipt survives SIGKILL before its first link`, async (t) => { + const { history, db, writeExit, receiptPath, retiringExits, readExit } = + await journalFixture(t); + const id = 'prelink-' + runtime, + file = receiptPath(id), + end = Date.now() - 10; + writeExit(id, 0, null, end - 2); + writeExit(id, 17, null, end - 1); await history.interrupt('http'); - const checksum = require('node:crypto').createHash('sha256').update(JSON.stringify([id,23,null,end])).digest('hex'); - const oldPath = path.join(path.dirname(file),'.published.'+id+'.'+checksum); - await fs.writeFile(oldPath,'damaged'); + const checksum = require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, 23, null, end])) + .digest('hex'); + const oldPath = path.join( + path.dirname(file), + '.published.' + id + '.' + checksum, + ); + await fs.writeFile(oldPath, 'damaged'); await fs.unlink(file); // Exercise first-link publication at an unoccupied compatibility path. - const result = runtime === 'node' - ? require('node:child_process').spawnSync(process.execPath,['-e',` + const result = + runtime === 'node' + ? require('node:child_process').spawnSync(process.execPath, [ + '-e', + ` require('node:fs').linkSync=()=>process.kill(process.pid,'SIGKILL'); require(process.argv[1]).writeExit(process.argv[2],23,null,Number(process.argv[3])); - `,require.resolve('../../back/shared/managedExit.cjs'),id,String(end)]) - : require('node:child_process').spawnSync('python3',['-I','-S','-c',` + `, + require.resolve('../../back/cron/settlement/exitReceipt.cjs'), + id, + String(end), + ]) + : require('node:child_process').spawnSync( + 'python3', + [ + '-I', + '-S', + '-c', + ` import os,runpy,sys,time,signal fixed_time=int(sys.argv[-1])*1000000 time.time_ns=lambda: fixed_time os.link=lambda *args: os.kill(os.getpid(),signal.SIGKILL) sys.argv=sys.argv[1:-1] runpy.run_path(sys.argv[0],run_name='__main__') - `,path.resolve('shell/cron-command.py'),'exit 23',String(process.pid),file,process.execPath,'unused',String(end)], - {env:{...process.env,QL_TRIGGER_ID:id},input:'run\n',encoding:'utf8'}); - assert.equal(result.signal,'SIGKILL',String(result.stderr)); - const copies = await Promise.all((await retiringExits()).map(copy=>readExit(id,copy.file))); - assert.ok(copies.some(copy=>copy?.code===23 && copy.time===end)); + `, + path.resolve('shell/cron-command.py'), + 'exit 23', + String(process.pid), + file, + process.execPath, + 'unused', + String(end), + ], + { + env: { ...process.env, QL_TRIGGER_ID: id }, + input: 'run\n', + encoding: 'utf8', + }, + ); + assert.equal(result.signal, 'SIGKILL', String(result.stderr)); + const copies = await Promise.all( + (await retiringExits()).map((copy) => readExit(id, copy.file)), + ); + assert.ok(copies.some((copy) => copy?.code === 23 && copy.time === end)); await new TriggerHistory(db).interrupt('http'); - assert.equal(await fs.readFile(oldPath,'utf8'),'damaged'); - const rows = await db.query('SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at',{type:QueryTypes.SELECT}); - assert.deepEqual(rows.map(r=>r.outcome),['0','17','23']); + assert.equal(await fs.readFile(oldPath, 'utf8'), 'damaged'); + const rows = await db.query( + 'SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + rows.map((r) => r.outcome), + ['0', '17', '23'], + ); }); } -test('a failed append to an existing dispute cannot reclaim uncommitted retries', async t => { - const { history, db, writeExit, retiringExits, readExit } = await journalFixture(t); - const id = 'failed-retry-commit', time = Date.now()-100; - writeExit(id,0,null,time); - writeExit(id,17,null,time); +test('a failed append to an existing dispute cannot reclaim uncommitted retries', async (t) => { + const { history, db, writeExit, retiringExits, readExit } = + await journalFixture(t); + const id = 'failed-retry-commit', + time = Date.now() - 100; + writeExit(id, 0, null, time); + writeExit(id, 17, null, time); await history.interrupt('http'); - writeExit(id,23,null,time); - writeExit(id,23,null,time); - const copies = async () => (await Promise.all((await retiringExits()).map(c=>readExit(id,c.file)))).filter(c=>c?.code===23); - const before = (await copies()).map(copy => copy.file).sort(); + writeExit(id, 23, null, time); + writeExit(id, 23, null, time); + const copies = async () => + ( + await Promise.all( + (await retiringExits()).map((c) => readExit(id, c.file)), + ) + ).filter((c) => c?.code === 23); + const before = (await copies()).map((copy) => copy.file).sort(); assert.equal(before.length, 6); // Each retry has a marker, JSON body and legacy-compatible link. await db.query('CREATE TABLE failed_append_parent (id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE failed_append_child (id INTEGER REFERENCES failed_append_parent(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query("CREATE TRIGGER reject_append AFTER INSERT ON CronBoundExitConflicts WHEN NEW.outcome='23' BEGIN INSERT INTO failed_append_child VALUES(1); END"); - await assert.rejects(history.interrupt('http'),/constraint|foreign key/i); - assert.deepEqual((await copies()).map(copy => copy.file).sort(), before); + await db.query( + 'CREATE TABLE failed_append_child (id INTEGER REFERENCES failed_append_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + "CREATE TRIGGER reject_append AFTER INSERT ON CronBoundExitConflicts WHEN NEW.outcome='23' BEGIN INSERT INTO failed_append_child VALUES(1); END", + ); + await assert.rejects(history.interrupt('http'), /constraint|foreign key/i); + assert.deepEqual((await copies()).map((copy) => copy.file).sort(), before); await db.query('DROP TRIGGER reject_append'); await new TriggerHistory(db).interrupt('http'); - assert.equal((await copies()).length,1); - assert.equal((await db.query('SELECT outcome FROM CronBoundExitConflicts',{type:QueryTypes.SELECT})).length,3); + assert.equal((await copies()).length, 1); + assert.equal( + ( + await db.query('SELECT outcome FROM CronBoundExitConflicts', { + type: QueryTypes.SELECT, + }) + ).length, + 3, + ); }); -test('replacing the selected witness before duplicate cleanup preserves the other verified copy', async t => { - const { history, db, writeExit, retiringExits, readExit, isMetadataReceipt } = await journalFixture(t); - const id = 'replace-before-cleanup', time = Date.now(); - writeExit(id,0,null,time); - writeExit(id,17,null,time); +test('replacing the selected witness before duplicate cleanup preserves the other verified copy', async (t) => { + const { history, db, writeExit, retiringExits, readExit, isMetadataReceipt } = + await journalFixture(t); + const id = 'replace-before-cleanup', + time = Date.now(); + writeExit(id, 0, null, time); + writeExit(id, 17, null, time); await history.interrupt('http'); - writeExit(id,23,null,time); - writeExit(id,23,null,time); - const witnesses = (await Promise.all((await retiringExits()).map(c=>readExit(id,c.file)))) - .filter(c=>c?.code===23 && !isMetadataReceipt(c.file)).map(c=>c.file).sort(); - assert.equal(witnesses.length,2); + writeExit(id, 23, null, time); + writeExit(id, 23, null, time); + const witnesses = ( + await Promise.all((await retiringExits()).map((c) => readExit(id, c.file))) + ) + .filter((c) => c?.code === 23 && !isMetadataReceipt(c.file)) + .map((c) => c.file) + .sort(); + assert.equal(witnesses.length, 2); const query = db.query.bind(db); let replaced = false; - const hook = t.mock.method(db,'query',async (sql,...args) => { - const result = await query(sql,...args); - if (!replaced && String(sql).includes('INSERT OR IGNORE INTO CronBoundExitConflicts')) { + const hook = t.mock.method(db, 'query', async (sql, ...args) => { + const result = await query(sql, ...args); + if ( + !replaced && + String(sql).includes('INSERT OR IGNORE INTO CronBoundExitConflicts') + ) { replaced = true; - await fs.writeFile(witnesses[0]+'.restore','{"code":0,"signal":null,"time":123}'); - await fs.rename(witnesses[0]+'.restore',witnesses[0]); + await fs.writeFile( + witnesses[0] + '.restore', + '{"code":0,"signal":null,"time":123}', + ); + await fs.rename(witnesses[0] + '.restore', witnesses[0]); } return result; }); @@ -4358,189 +7517,401 @@ test('replacing the selected witness before duplicate cleanup preserves the othe hook.mock.restore(); await history.retryPendingExits(); assert.ok(replaced); - assert.equal((await readExit(id,witnesses[1])).code,23); - assert.equal((await readExit(id,witnesses[0])).version,undefined); - assert.deepEqual((await db.query('SELECT outcome FROM CronBoundExitConflicts ORDER BY CAST(outcome AS INTEGER)', - {type:QueryTypes.SELECT})).map(r=>r.outcome),['0','17','23']); + assert.equal((await readExit(id, witnesses[1])).code, 23); + assert.equal((await readExit(id, witnesses[0])).version, undefined); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome FROM CronBoundExitConflicts ORDER BY CAST(outcome AS INTEGER)', + { type: QueryTypes.SELECT }, + ) + ).map((r) => r.outcome), + ['0', '17', '23'], + ); }); -test('an incomplete private publication cannot book the supervisor exit while the real result is unavailable', async t => { - const { history, db, receiptPath, writeExit, stats } = await journalFixture(t); - const id = 'incomplete-retry', end = Date.now()-3*86400000; - await history.enqueue(id,1,'manual',null,end-1000); - await history.start(id,end-1000,true); - const file = receiptPath(id), dir = path.dirname(file); - await fs.mkdir(dir,{recursive:true}); - const pending = path.join(dir,'.pending.'+id+'.'+require('node:crypto').randomUUID()); - await fs.writeFile(pending,'{"code":23'); - await history.complete(id,'failed','SIGKILL',null,end+1); - const [unresolved] = await history.visibleTriggers(1,[id]); - assert.deepEqual([unresolved.state,unresolved.reason,unresolved.finished_at],['unknown','exit_pending',null]); - assert.equal(await stats.CrontabStatModel.count(),0); +test('an incomplete private publication cannot book the supervisor exit while the real result is unavailable', async (t) => { + const { history, db, receiptPath, writeExit, stats } = await journalFixture( + t, + ); + const id = 'incomplete-retry', + end = Date.now() - 3 * 86400000; + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); + const file = receiptPath(id), + dir = path.dirname(file); + await fs.mkdir(dir, { recursive: true }); + const pending = path.join( + dir, + '.pending.' + id + '.' + require('node:crypto').randomUUID(), + ); + await fs.writeFile(pending, '{"code":23'); + await history.complete(id, 'failed', 'SIGKILL', null, end + 1); + const [unresolved] = await history.visibleTriggers(1, [id]); + assert.deepEqual( + [unresolved.state, unresolved.reason, unresolved.finished_at], + ['unknown', 'exit_pending', null], + ); + assert.equal(await stats.CrontabStatModel.count(), 0); // An earlier worker may already have recorded unknown without the pending flag. - await db.query('UPDATE CronTriggers SET exit_pending=NULL,finished_at=$end WHERE id=$id',{bind:{id,end}}); + await db.query( + 'UPDATE CronTriggers SET exit_pending=NULL,finished_at=$end WHERE id=$id', + { bind: { id, end } }, + ); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - await policy.cleanup({runningInstanceRetentionDays:1,cronStatRetentionDays:7}); - assert.equal((await history.visibleTriggers(1,[id]))[0].reason,'exit_pending'); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 7, + }); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_pending', + ); await new TriggerHistory(db).interrupt('http'); - writeExit(id,23,null,end); - await fs.rename(file,pending); + writeExit(id, 23, null, end); + await fs.rename(file, pending); await history.retryPendingExits(); - const [row] = await history.visibleTriggers(1,[id]); - assert.deepEqual([row.state,row.exit_code,row.finished_at],['failed',23,end]); - assert.equal((await stats.CrontabStatModel.findOne()).run_count,1); + const [row] = await history.visibleTriggers(1, [id]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['failed', 23, end], + ); + assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); }); function publishFromPeer(id, code, time) { const { execFile } = require('node:child_process'); return require('node:util').promisify(execFile)(process.execPath, [ - '-e', 'require(process.argv[1]).writeExit(process.argv[2],Number(process.argv[3]),null,Number(process.argv[4]))', - require.resolve('../../back/shared/managedExit.cjs'), id, String(code), String(time), + '-e', + 'require(process.argv[1]).writeExit(process.argv[2],Number(process.argv[3]),null,Number(process.argv[4]))', + require.resolve('../../back/cron/settlement/exitReceipt.cjs'), + id, + String(code), + String(time), ]); } const receiptBoundaries = { - settle: ['booking', 'claim', 'increment', 'commit', 'move', 'readClaim', 'unlink'], + settle: [ + 'booking', + 'claim', + 'increment', + 'commit', + 'move', + 'readClaim', + 'unlink', + ], withdraw: ['dispute', 'debit', 'commit'], - prune: ['deleteDay', 'cutoff', 'historyCutoff', 'deleteHistory', 'pruneBooking', 'commit'], + prune: [ + 'deleteDay', + 'cutoff', + 'historyCutoff', + 'deleteHistory', + 'pruneBooking', + 'commit', + ], }; for (const [operation, stages] of Object.entries(receiptBoundaries)) { - for (const stage of stages) for (const side of ['before', 'after']) { - test(`receipt boundary ${operation}/${stage}/${side}: kill with a replacement and two retry processes`, async t => { - const { root, db, history, receiptPath, writeExit, stats } = await journalFixture(t); - const id = 'boundary', day = require('dayjs')().startOf('day'); - const old = day.subtract(3, 'day').valueOf() + 1000, fresh = day.valueOf() + 1; - for (const [key, time] of [['sibling', fresh], [id, old]]) { - await history.enqueue(key, 1, 'manual', null, time - 1000); - await history.start(key, time - 1000, true); - writeExit(key, 0, null, time); - if (key === 'sibling' || operation !== 'settle') await history.complete(key, 'unknown', null, null); - } - if (operation === 'withdraw') writeExit(id, 17, null, old + 1); - const child = require('node:child_process').spawn(process.execPath, [ - '-r', 'ts-node/register/transpile-only', require.resolve('../helpers/receipt-boundary-worker.cjs'), - operation, stage, side, id, - ], { stdio: ['ignore', 'ignore', 'pipe'] }); - let stderr = ''; - child.stderr.on('data', data => { stderr += data; }); - const closed = new Promise(resolve => child.once('close', (code, signal) => resolve({ code, signal }))); - let wasGone; - let receiptsSettled; - try { - const marker = path.join(root, 'at-barrier'); - const deadline = Date.now() + 15000; - while (!require('node:fs').existsSync(marker) && child.exitCode === null && Date.now() < deadline) - await new Promise(resolve => setTimeout(resolve, 20)); - assert.equal(await fs.readFile(marker, 'utf8').catch(() => stderr), stage + '/' + side); - // Read through an independent connection while the worker is stopped - // at the barrier. Partial SQL effects must remain invisible. - const committed = stage === 'commit' && side === 'after'; - const inCollector = ['move', 'readClaim', 'unlink'].includes(stage); - const oldDayVisible = operation === 'settle' ? committed || inCollector : !committed; - const ledger = (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })) - .map(r => [r.date, r.run_count, r.success_count]); - const oldDay = require('dayjs')(old).format('YYYY-MM-DD'); - assert.deepEqual(ledger, [...(oldDayVisible ? [[oldDay, 1, 1]] : []), [day.format('YYYY-MM-DD'), 1, 1]]); - wasGone = !(await history.visibleTriggers(1, [id])).length; - const canonical = receiptPath(id); - // Replace atomically using the genuine SHA256 tuple for this ID. Two - // other processes publish the competing tuple before killing the worker. - const replacement = { code: 23, signal: null, time: fresh, version: 1, - checksum: require('node:crypto').createHash('sha256').update(JSON.stringify([id,23,null,fresh])).digest('hex') }; - await fs.writeFile(canonical + '.restore', JSON.stringify(replacement)); - await fs.rename(canonical + '.restore', canonical); - await Promise.all([publishFromPeer(id, 0, old), publishFromPeer(id, 0, old)]); - // Let two independent SQLite connections start retrying while the - // interrupted worker is still alive, including after its COMMIT. - let began = 0, release; - const bothAtBegin = new Promise(resolve => { release = resolve; }); - const query = db.query.bind(db); - const gate = t.mock.method(db, 'query', (sql, ...args) => { - const pending = query(sql, ...args); - if (String(sql).startsWith('BEGIN') && ++began === 2) release(); - return pending; - }); - receiptsSettled = Promise.allSettled([1, 2].map(() => - new TriggerHistory(db).complete(id, 'finished', null, 0, old, - { version: 1, code: 0, signal: null, time: old }))); - let timeout; - try { - await Promise.race([bothAtBegin, new Promise((_, reject) => { - timeout = setTimeout(() => reject(Error('Concurrent retry transactions never started')), 5000); - })]); - } finally { - clearTimeout(timeout); - gate.mock.restore(); + for (const stage of stages) + for (const side of ['before', 'after']) { + test(`receipt boundary ${operation}/${stage}/${side}: kill with a replacement and two retry processes`, async (t) => { + const { root, db, history, receiptPath, writeExit, stats } = + await journalFixture(t); + const id = 'boundary', + day = require('dayjs')().startOf('day'); + const old = day.subtract(3, 'day').valueOf() + 1000, + fresh = day.valueOf() + 1; + for (const [key, time] of [ + ['sibling', fresh], + [id, old], + ]) { + await history.enqueue(key, 1, 'manual', null, time - 1000); + await history.start(key, time - 1000, true); + writeExit(key, 0, null, time); + if (key === 'sibling' || operation !== 'settle') + await history.complete(key, 'unknown', null, null); } - } finally { - child.kill('SIGKILL'); - const result = await closed; - if (!stderr) assert.equal(result.signal, 'SIGKILL'); - if (receiptsSettled) for (const retry of await receiptsSettled) assert.equal(retry.status, 'fulfilled', retry.reason); - } - const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, - }).default)(); - for (let i = 0; i < 2; i++) { - await new TriggerHistory(db).interrupt('http'); - await Promise.all([history.retryPendingExits(), history.complete(id, 'unknown', null, null)]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count]), - [[day.format('YYYY-MM-DD'), 1]], 'replay must converge even before the next pruning pass'); - await policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); - const tuples = await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - { bind: { id }, type: QueryTypes.SELECT }); - const expected = [['0', old], ...(operation === 'withdraw' ? [['17', old + 1]] : []), ['23', fresh]]; - assert.deepEqual(tuples.map(r => [r.outcome, r.finished_at]), expected); - const [row] = await history.visibleTriggers(1, [id]); - if (wasGone) assert.equal(row, undefined); - else assert.deepEqual([row.state, row.reason, row.exit_code], ['unknown', 'exit_conflict', null]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date, r.run_count, r.success_count, r.fail_count]), - [[day.format('YYYY-MM-DD'), 1, 1, 0]]); - } - }); - } + if (operation === 'withdraw') writeExit(id, 17, null, old + 1); + const child = require('node:child_process').spawn( + process.execPath, + [ + '-r', + 'ts-node/register/transpile-only', + require.resolve('../helpers/receipt-boundary-worker.cjs'), + operation, + stage, + side, + id, + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, + ); + let stderr = ''; + child.stderr.on('data', (data) => { + stderr += data; + }); + const closed = new Promise((resolve) => + child.once('close', (code, signal) => resolve({ code, signal })), + ); + let wasGone; + let receiptsSettled; + try { + const marker = path.join(root, 'at-barrier'); + const deadline = Date.now() + 15000; + while ( + !require('node:fs').existsSync(marker) && + child.exitCode === null && + Date.now() < deadline + ) + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal( + await fs.readFile(marker, 'utf8').catch(() => stderr), + stage + '/' + side, + ); + // Read through an independent connection while the worker is stopped + // at the barrier. Partial SQL effects must remain invisible. + const committed = stage === 'commit' && side === 'after'; + const inCollector = ['move', 'readClaim', 'unlink'].includes(stage); + const oldDayVisible = + operation === 'settle' ? committed || inCollector : !committed; + const ledger = ( + await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] }) + ).map((r) => [r.date, r.run_count, r.success_count]); + const oldDay = require('dayjs')(old).format('YYYY-MM-DD'); + assert.deepEqual(ledger, [ + ...(oldDayVisible ? [[oldDay, 1, 1]] : []), + [day.format('YYYY-MM-DD'), 1, 1], + ]); + wasGone = !(await history.visibleTriggers(1, [id])).length; + const canonical = receiptPath(id); + // Replace atomically using the genuine SHA256 tuple for this ID. Two + // other processes publish the competing tuple before killing the worker. + const replacement = { + code: 23, + signal: null, + time: fresh, + version: 1, + checksum: require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, 23, null, fresh])) + .digest('hex'), + }; + await fs.writeFile( + canonical + '.restore', + JSON.stringify(replacement), + ); + await fs.rename(canonical + '.restore', canonical); + await Promise.all([ + publishFromPeer(id, 0, old), + publishFromPeer(id, 0, old), + ]); + // Let two independent SQLite connections start retrying while the + // interrupted worker is still alive, including after its COMMIT. + let began = 0, + release; + const bothAtBegin = new Promise((resolve) => { + release = resolve; + }); + const query = db.query.bind(db); + const gate = t.mock.method(db, 'query', (sql, ...args) => { + const pending = query(sql, ...args); + if (String(sql).startsWith('BEGIN') && ++began === 2) release(); + return pending; + }); + receiptsSettled = Promise.allSettled( + [1, 2].map(() => + new TriggerHistory(db).complete(id, 'finished', null, 0, old, { + version: 1, + code: 0, + signal: null, + time: old, + }), + ), + ); + let timeout; + try { + await Promise.race([ + bothAtBegin, + new Promise((_, reject) => { + timeout = setTimeout( + () => + reject( + Error('Concurrent retry transactions never started'), + ), + 5000, + ); + }), + ]); + } finally { + clearTimeout(timeout); + gate.mock.restore(); + } + } finally { + child.kill('SIGKILL'); + const result = await closed; + if (!stderr) assert.equal(result.signal, 'SIGKILL'); + if (receiptsSettled) + for (const retry of await receiptsSettled) + assert.equal(retry.status, 'fulfilled', retry.reason); + } + const policy = new (load('back/services/retention.ts', { + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, + }).default)(); + for (let i = 0; i < 2; i++) { + await new TriggerHistory(db).interrupt('http'); + await Promise.all([ + history.retryPendingExits(), + history.complete(id, 'unknown', null, null), + ]); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + ]), + [[day.format('YYYY-MM-DD'), 1]], + 'replay must converge even before the next pruning pass', + ); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); + const tuples = await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ); + const expected = [ + ['0', old], + ...(operation === 'withdraw' ? [['17', old + 1]] : []), + ['23', fresh], + ]; + assert.deepEqual( + tuples.map((r) => [r.outcome, r.finished_at]), + expected, + ); + const [row] = await history.visibleTriggers(1, [id]); + if (wasGone) assert.equal(row, undefined); + else + assert.deepEqual( + [row.state, row.reason, row.exit_code], + ['unknown', 'exit_conflict', null], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.success_count, + r.fail_count, + ]), + [[day.format('YYYY-MM-DD'), 1, 1, 0]], + ); + } + }); + } } for (const runtime of ['node', 'python']) { - for (const stage of ['before-write', 'partial', 'after-write', 'before-mirror', 'after-mirror', 'before-link', 'after-link', 'published']) { - test(`receipt publication ${runtime}/${stage} with replacement, concurrent retries and SIGKILL`, async t => { + for (const stage of [ + 'before-write', + 'partial', + 'after-write', + 'before-mirror', + 'after-mirror', + 'before-link', + 'after-link', + 'published', + ]) { + test(`receipt publication ${runtime}/${stage} with replacement, concurrent retries and SIGKILL`, async (t) => { const { root, db, history, receiptPath, stats } = await journalFixture(t); - const id = 'publication', file = receiptPath(id), end = Date.now() - 100; + const id = 'publication', + file = receiptPath(id), + end = Date.now() - 100; await history.enqueue(id, 1, 'manual', null, end - 200); await history.start(id, end - 200, true); const node = runtime === 'node'; - const args = node ? [require.resolve('../helpers/receipt-publisher-barrier.cjs'), stage, String(end)] - : ['-I', '-S', path.resolve('test/helpers/receipt-publisher-barrier.py'), stage, String(end), - path.resolve('shell/cron-command.py'), file, String(process.pid)]; - const child = require('node:child_process').spawn(node ? process.execPath : 'python3', args, - { env: { ...process.env, QL_TRIGGER_ID: id }, stdio: ['pipe', 'ignore', 'pipe'] }); - const closed = new Promise(resolve => child.once('close', (code, signal) => resolve(signal))); + const args = node + ? [ + require.resolve('../helpers/receipt-publisher-barrier.cjs'), + stage, + String(end), + ] + : [ + '-I', + '-S', + path.resolve('test/helpers/receipt-publisher-barrier.py'), + stage, + String(end), + path.resolve('shell/cron-command.py'), + file, + String(process.pid), + ]; + const child = require('node:child_process').spawn( + node ? process.execPath : 'python3', + args, + { + env: { ...process.env, QL_TRIGGER_ID: id }, + stdio: ['pipe', 'ignore', 'pipe'], + }, + ); + const closed = new Promise((resolve) => + child.once('close', (code, signal) => resolve(signal)), + ); child.stdin.end('run\n'); let stderr = ''; - child.stderr.on('data', chunk => { stderr += chunk; }); + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); const complete = stage !== 'before-write'; try { - const deadline = Date.now() + 10000, ready = path.join(root, 'publisher-ready'); - while (!require('node:fs').existsSync(ready) && child.exitCode === null && Date.now() < deadline) - await new Promise(resolve => setTimeout(resolve, 20)); - assert.equal(await fs.readFile(ready, 'utf8').catch(() => stderr), stage); + const deadline = Date.now() + 10000, + ready = path.join(root, 'publisher-ready'); + while ( + !require('node:fs').existsSync(ready) && + child.exitCode === null && + Date.now() < deadline + ) + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal( + await fs.readFile(ready, 'utf8').catch(() => stderr), + stage, + ); await history.bindCommand(id, child.pid); - const replacement = { version: 1, code: 17, signal: null, time: end + 1, - checksum: require('node:crypto').createHash('sha256').update(JSON.stringify([id,17,null,end+1])).digest('hex') }; + const replacement = { + version: 1, + code: 17, + signal: null, + time: end + 1, + checksum: require('node:crypto') + .createHash('sha256') + .update(JSON.stringify([id, 17, null, end + 1])) + .digest('hex'), + }; // After link, overwrite the compatibility inode in place as well as // testing atomic replacement after the publisher has returned. - if (stage === 'after-link') await fs.writeFile(file, JSON.stringify(replacement)); + if (stage === 'after-link') + await fs.writeFile(file, JSON.stringify(replacement)); else { await fs.writeFile(file + '.restore', JSON.stringify(replacement)); await fs.rename(file + '.restore', file); } - await Promise.all([publishFromPeer(id, 17, end + 1), publishFromPeer(id, 17, end + 1)]); + await Promise.all([ + publishFromPeer(id, 17, end + 1), + publishFromPeer(id, 17, end + 1), + ]); } finally { child.kill('SIGKILL'); assert.equal(await closed, 'SIGKILL', stderr); @@ -4550,12 +7921,27 @@ for (const runtime of ['node', 'python']) { await new TriggerHistory(db).interrupt('http'); const [row] = await history.visibleTriggers(1, [id]); if (complete) { - assert.deepEqual([row.state, row.reason, row.exit_code], ['unknown', 'exit_conflict', null]); - const tuples = await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', { type: QueryTypes.SELECT }); - assert.deepEqual(tuples.map(r => [r.outcome, r.finished_at]), [['23', end], ['17', end+1]]); + assert.deepEqual( + [row.state, row.reason, row.exit_code], + ['unknown', 'exit_conflict', null], + ); + const tuples = await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ); + assert.deepEqual( + tuples.map((r) => [r.outcome, r.finished_at]), + [ + ['23', end], + ['17', end + 1], + ], + ); assert.equal(await stats.CrontabStatModel.count(), 0); } else { - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['failed', 17, end + 1]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['failed', 17, end + 1], + ); assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); } } @@ -4563,16 +7949,20 @@ for (const runtime of ['node', 'python']) { } } -test('a bound supervisor killed without any command receipt stays unknown until its actual exit arrives', async t => { +test('a bound supervisor killed without any command receipt stays unknown until its actual exit arrives', async (t) => { const { db, history, writeExit, stats } = await journalFixture(t); - const id = 'killed-before-any-bytes', end = Date.now() - 50; - await history.enqueue(id, 1, 'manual', null, end-1000); - await history.start(id, end-1000, true); + const id = 'killed-before-any-bytes', + end = Date.now() - 50; + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); await history.complete(id, 'stopped', 'SIGKILL', null); await new TriggerHistory(db).interrupt('http'); const [unknown] = await history.visibleTriggers(1, [id]); - assert.deepEqual([unknown.state, unknown.reason, unknown.finished_at], ['unknown','exit_pending',null]); + assert.deepEqual( + [unknown.state, unknown.reason, unknown.finished_at], + ['unknown', 'exit_pending', null], + ); assert.equal(await stats.CrontabStatModel.count(), 0); writeExit(id, 23, null, end); await Promise.all([history.retryPendingExits(), history.retryPendingExits()]); @@ -4581,45 +7971,66 @@ test('a bound supervisor killed without any command receipt stays unknown until }); for (const canonical of ['absent', 'damaged']) { - test(`a verified private receipt with ${canonical} canonical path blocks a stop signal`, async t => { + test(`a verified private receipt with ${canonical} canonical path blocks a stop signal`, async (t) => { const { db, history, receiptPath, writeExit } = await journalFixture(t); - const id = 'stop-after-publication', end = Date.now(); - await history.enqueue(id, 1, 'manual', null, end-1000); - await history.start(id, end-1000, true); + const id = 'stop-after-publication', + end = Date.now(); + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); const instance = await db.models.RunningInstance.findOne(); writeExit(id, 0, null, end); if (canonical === 'absent') await fs.unlink(receiptPath(id)); else await fs.writeFile(receiptPath(id), 'damaged'); let signals = 0; - await assert.rejects(history.requestInstanceStop(instance.id, process.pid, () => { signals++; }), { code: 'ESRCH' }); + await assert.rejects( + history.requestInstanceStop(instance.id, process.pid, () => { + signals++; + }), + { code: 'ESRCH' }, + ); assert.equal(signals, 0); assert.equal((await history.visibleTriggers(1, [id]))[0].state, 'finished'); assert.equal((await db.models.CrontabStat.findOne()).success_count, 1); }); } -test('replacing a public collecting file at the last unlink preserves the new bytes', async t => { - const { history, db, receiptPath, retireLegacyFile } = await journalFixture(t); - const id = 'collector-replacement', end = Date.now(); +test('replacing a public collecting file at the last unlink preserves the new bytes', async (t) => { + const { history, db, receiptPath, retireLegacyFile } = await journalFixture( + t, + ); + const id = 'collector-replacement', + end = Date.now(); writeSingleFileExit(id, 0, null, end); const canonical = receiptPath(id); - const publicName = path.join(path.dirname(canonical), '.collecting.' + id + '.' + require('node:crypto').randomUUID()); + const publicName = path.join( + path.dirname(canonical), + '.collecting.' + id + '.' + require('node:crypto').randomUUID(), + ); await fs.rename(canonical, publicName); writeSingleFileExit(id, 23, null, end + 1); const replacement = await fs.readFile(canonical); - const unlink = fs.unlink.bind(fs), remove = fs.rm.bind(fs); + const unlink = fs.unlink.bind(fs), + remove = fs.rm.bind(fs); let injected = false; - const inject = async target => { + const inject = async (target) => { if (injected) return; injected = true; // Both old public collection names and the canonical name can be restored. // A collector-private disposal slot is outside the publication namespace. - const destination = path.basename(target).startsWith('.collecting.') ? target : publicName; + const destination = path.basename(target).startsWith('.collecting.') + ? target + : publicName; await fs.rename(canonical, destination); }; - const deleteFile = t.mock.method(fs, 'unlink', async file => { await inject(file); return unlink(file); }); - const removeFile = t.mock.method(fs, 'rm', async (file, ...args) => { await inject(file); return remove(file, ...args); }); + const deleteFile = t.mock.method(fs, 'unlink', async (file) => { + await inject(file); + return unlink(file); + }); + const removeFile = t.mock.method(fs, 'rm', async (file, ...args) => { + await inject(file); + return remove(file, ...args); + }); await retireLegacyFile(id, publicName, { outcome: '0', time: end }); deleteFile.mock.restore(); removeFile.mock.restore(); @@ -4627,71 +8038,137 @@ test('replacing a public collecting file at the last unlink preserves the new by assert.deepEqual(await fs.readFile(publicName), replacement); writeSingleFileExit(id, 0, null, end); await history.interrupt('http'); - assert.deepEqual((await db.query('SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at', - { type: QueryTypes.SELECT })).map(row => row.outcome), ['0','23']); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ) + ).map((row) => row.outcome), + ['0', '23'], + ); }); -test('a verified stop settles from the private receipt while the scheduler owner is still live', async t => { +test('a verified stop settles from the private receipt while the scheduler owner is still live', async (t) => { const { db, history, receiptPath, writeExit } = await journalFixture(t); - const id = 'private-stop-result', end = Date.now(); + const id = 'private-stop-result', + end = Date.now(); await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); await history.bindCommand(id, process.pid); const instance = await db.models.RunningInstance.findOne(); - await history.requestInstanceStop(instance.id, process.pid, () => {}, [systemOwner(process.pid)]); + await history.requestInstanceStop(instance.id, process.pid, () => {}, [ + systemOwner(process.pid), + ]); writeExit(id, 143, null, end); await fs.unlink(receiptPath(id)); for (let retry = 0; retry < 2; retry++) { await history.stopVerifiedInstance(instance.id); const [row] = await history.visibleTriggers(1, [id]); - assert.deepEqual([row.state, row.exit_code, row.finished_at], ['stopped', 143, end]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['stopped', 143, end], + ); assert.equal((await db.models.CrontabStat.findOne()).run_count, 1); } }); for (const full of ['ENOSPC', 'EDQUOT']) { - test(`a short JSON write with ${full} replays the exact day once and reclaims both publications`, async t => { - const { history, db, stats, readExit, retiringExits, receiptPath, writeExit } = await journalFixture(t); - const id = 'short-body', day = require('dayjs')().startOf('day'), end = day.valueOf() - 100; + test(`a short JSON write with ${full} replays the exact day once and reclaims both publications`, async (t) => { + const { + history, + db, + stats, + readExit, + retiringExits, + receiptPath, + writeExit, + } = await journalFixture(t); + const id = 'short-body', + day = require('dayjs')().startOf('day'), + end = day.valueOf() - 100; await history.enqueue(id, 1, 'manual', null, end - 1000); await history.start(id, end - 1000, true); - const sync = require('node:fs'), write = sync.writeFileSync; - const hook = t.mock.method(sync, 'writeFileSync', (file, content, options) => { - if (content && path.dirname(file) === path.dirname(receiptPath(id))) { - write(file, content.slice(0, 12), options); - throw Object.assign(Error('no data blocks'), { code: full }); - } - return write(file, content, options); - }); + const sync = require('node:fs'), + write = sync.writeFileSync; + const hook = t.mock.method( + sync, + 'writeFileSync', + (file, content, options) => { + if (content && path.dirname(file) === path.dirname(receiptPath(id))) { + write(file, content.slice(0, 12), options); + throw Object.assign(Error('no data blocks'), { code: full }); + } + return write(file, content, options); + }, + ); writeExit(id, 23, null, end); hook.mock.restore(); const files = await retiringExits(); - assert.deepEqual((await Promise.all(files.map(copy => fs.stat(copy.file)))).map(s => s.size).sort((a,b) => a-b), [0,12]); + assert.deepEqual( + (await Promise.all(files.map((copy) => fs.stat(copy.file)))) + .map((s) => s.size) + .sort((a, b) => a - b), + [0, 12], + ); for (const copy of files) { const observed = await readExit(id, copy.file); assert.deepEqual([observed.code, observed.time], [23, end]); } - await Promise.all([new TriggerHistory(db).interrupt('http'), history.retryPendingExits()]); - await Promise.all([publishFromPeer(id, 23, end), publishFromPeer(id, 23, end)]); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + ]); + await Promise.all([ + publishFromPeer(id, 23, end), + publishFromPeer(id, 23, end), + ]); await new TriggerHistory(db).interrupt('http'); const [result] = await history.visibleTriggers(1, [id]); - assert.deepEqual([result.state, result.exit_code, result.finished_at], ['failed', 23, end]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r => [r.date,r.run_count,r.fail_count]), - [[day.subtract(1, 'day').format('YYYY-MM-DD'),1,1]]); + assert.deepEqual( + [result.state, result.exit_code, result.finished_at], + ['failed', 23, end], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.fail_count, + ]), + [[day.subtract(1, 'day').format('YYYY-MM-DD'), 1, 1]], + ); assert.deepEqual(await fs.readdir(path.dirname(receiptPath(id))), []); }); } -test('a zero-byte receipt requires the correct execution ID, checksum, and a regular file', async t => { - const { readExit, receiptPath, retiringExits, writeExit } = await journalFixture(t); - const id = 'metadata-check', end = Date.now(); +test('a zero-byte receipt requires the correct execution ID, checksum, and a regular file', async (t) => { + const { readExit, receiptPath, retiringExits, writeExit } = + await journalFixture(t); + const id = 'metadata-check', + end = Date.now(); writeExit(id, null, 'SIGTERM', end); - const [marker] = (await Promise.all((await retiringExits()).map(async c => - (await fs.stat(c.file)).size === 0 ? c.file : undefined))).filter(Boolean); + const [marker] = ( + await Promise.all( + ( + await retiringExits() + ).map(async (c) => + (await fs.stat(c.file)).size === 0 ? c.file : undefined, + ), + ) + ).filter(Boolean); assert.equal((await readExit(id, marker)).signal, 'SIGTERM'); - for (const invalid of [marker.replace(id, 'other-execution'), marker.replace('SIGTERM','SIGKILL')]) { + for (const invalid of [ + marker.replace(id, 'other-execution'), + marker.replace('SIGTERM', 'SIGKILL'), + ]) { await fs.copyFile(marker, invalid); - assert.equal(await readExit(invalid.includes('other-execution') ? 'other-execution' : id, invalid), null); + assert.equal( + await readExit( + invalid.includes('other-execution') ? 'other-execution' : id, + invalid, + ), + null, + ); } await fs.writeFile(marker, '{"code":7'); assert.equal(await readExit(id, marker), null); @@ -4701,16 +8178,23 @@ test('a zero-byte receipt requires the correct execution ID, checksum, and a reg }); for (const fault of ['rename', 'unlink']) { - test(`receipt collection ${fault} fails with ENOSPC after commit; pruning and retries keep the old day absent`, async t => { - const { db, history, stats, writeExit, retiringExits, receiptPath } = await journalFixture(t); - const id = 'collector-full', today = require('dayjs')().startOf('day'), old = today.subtract(3,'day').valueOf() + 123; + test(`receipt collection ${fault} fails with ENOSPC after commit; pruning and retries keep the old day absent`, async (t) => { + const { db, history, stats, writeExit, retiringExits, receiptPath } = + await journalFixture(t); + const id = 'collector-full', + today = require('dayjs')().startOf('day'), + old = today.subtract(3, 'day').valueOf() + 123; await history.enqueue(id, 1, 'manual', null, old - 1000); await history.start(id, old - 1000, true); writeExit(id, 17, null, old); let attempts = 0; const original = fs[fault].bind(fs); const hook = t.mock.method(fs, fault, (file, ...args) => { - if (file.startsWith(path.dirname(receiptPath(id)) + path.sep) || (fault === 'unlink' && path.basename(file).startsWith('.pending.' + id + '.'))) { + if ( + file.startsWith(path.dirname(receiptPath(id)) + path.sep) || + (fault === 'unlink' && + path.basename(file).startsWith('.pending.' + id + '.')) + ) { attempts++; throw Object.assign(Error('directory full'), { code: 'ENOSPC' }); } @@ -4721,181 +8205,337 @@ for (const fault of ['rename', 'unlink']) { assert.equal((await stats.CrontabStatModel.findOne()).run_count, 1); assert.ok((await retiringExits()).length); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - await policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); hook.mock.restore(); - await Promise.all([publishFromPeer(id,17,old),publishFromPeer(id,17,old)]); - for (let i=0; i<2; i++) { + await Promise.all([ + publishFromPeer(id, 17, old), + publishFromPeer(id, 17, old), + ]); + for (let i = 0; i < 2; i++) { await new TriggerHistory(db).interrupt('http'); assert.equal(await stats.CrontabStatModel.count(), 0); - assert.deepEqual(await history.visibleTriggers(1,[id]), []); + assert.deepEqual(await history.visibleTriggers(1, [id]), []); assert.deepEqual(await fs.readdir(path.dirname(receiptPath(id))), []); } }); } -test('native SQLITE_FULL rolls back the counter claim and preserves the receipt until capacity returns', async t => { +test('native SQLITE_FULL rolls back the counter claim and preserves the receipt until capacity returns', async (t) => { const { db, history, stats, writeExit, readExit } = await journalFixture(t); - const id = 'sqlite-full', end = Date.now(); - await history.enqueue(id,1,'manual',null,end-1000); - await history.start(id,end-1000,true); - writeExit(id,0,null,end); + const id = 'sqlite-full', + end = Date.now(); + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); + writeExit(id, 0, null, end); await db.query('CREATE TABLE force_page_growth (body BLOB)'); - await db.query('CREATE TRIGGER exhaust_pages AFTER INSERT ON CrontabStats BEGIN INSERT INTO force_page_growth VALUES(zeroblob(2097152)); END'); - const before = await db.query('PRAGMA page_count',{type:QueryTypes.SELECT}); + await db.query( + 'CREATE TRIGGER exhaust_pages AFTER INSERT ON CrontabStats BEGIN INSERT INTO force_page_growth VALUES(zeroblob(2097152)); END', + ); + const before = await db.query('PRAGMA page_count', { + type: QueryTypes.SELECT, + }); const query = db.query.bind(db); const hook = t.mock.method(db, 'query', async (sql, options) => { if (String(sql).startsWith('INSERT INTO "CrontabStats"')) - await query('PRAGMA max_page_count=' + before[0].page_count, {transaction:options.transaction}); + await query('PRAGMA max_page_count=' + before[0].page_count, { + transaction: options.transaction, + }); return query(sql, options); }); - await assert.rejects(history.complete(id,'unknown',null,null), error => error.original?.code === 'SQLITE_FULL'); + await assert.rejects( + history.complete(id, 'unknown', null, null), + (error) => error.original?.code === 'SQLITE_FULL', + ); hook.mock.restore(); - assert.equal((await readExit(id)).code,0); - assert.equal(await stats.CrontabStatModel.count(),0); - assert.deepEqual(await query('SELECT counted,state FROM CronTriggers WHERE id=$id',{type:QueryTypes.SELECT,bind:{id}}), - [{counted:0,state:'running'}]); + assert.equal((await readExit(id)).code, 0); + assert.equal(await stats.CrontabStatModel.count(), 0); + assert.deepEqual( + await query('SELECT counted,state FROM CronTriggers WHERE id=$id', { + type: QueryTypes.SELECT, + bind: { id }, + }), + [{ counted: 0, state: 'running' }], + ); await db.query('DROP TRIGGER exhaust_pages'); - await Promise.all([publishFromPeer(id,0,end),publishFromPeer(id,0,end)]); - await Promise.all([new TriggerHistory(db).interrupt('http'),history.retryPendingExits()]); - assert.equal((await stats.CrontabStatModel.findOne()).success_count,1); + await Promise.all([publishFromPeer(id, 0, end), publishFromPeer(id, 0, end)]); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + ]); + assert.equal((await stats.CrontabStatModel.findOne()).success_count, 1); }); for (const producer of ['python', 'crond']) { - test(`a live ${producer} producer with no free inode books the original timestamp through SQLite`, async t => { + test(`a live ${producer} producer with no free inode books the original timestamp through SQLite`, async (t) => { const { db, history, root, stats, receiptPath } = await journalFixture(t); const day = require('dayjs')().startOf('day'); - const end = day.valueOf() - 300, id = 'system-1-no-inode'; + const end = day.valueOf() - 300, + id = 'system-1-no-inode'; await fs.mkdir(path.dirname(receiptPath(id)), { recursive: true }); - await fs.symlink(path.join(root,'database.sqlite'),path.join(root,'db','database.sqlite')); - await fs.writeFile(path.join(root,'.env'), ''); - await history.enqueue(id,1,producer === 'crond' ? 'system' : 'manual',null,end-1000); - await history.start(id,end-1000,true); - await history.bindCommand(id,process.pid); + await fs.symlink( + path.join(root, 'database.sqlite'), + path.join(root, 'db', 'database.sqlite'), + ); + await fs.writeFile(path.join(root, '.env'), ''); + await history.enqueue( + id, + 1, + producer === 'crond' ? 'system' : 'manual', + null, + end - 1000, + ); + await history.start(id, end - 1000, true); + await history.bindCommand(id, process.pid); const failWrites = path.join(root, 'full-inodes.cjs'); - await fs.writeFile(failWrites, `const fs=require('node:fs'), write=fs.writeFileSync; + await fs.writeFile( + failWrites, + `const fs=require('node:fs'), write=fs.writeFileSync; fs.writeFileSync=function(file,...args){ if (typeof file==='string' && file.includes('/cron-exits/')) throw Object.assign(Error('no free inode'),{code:'ENOSPC'}); return write.call(this,file,...args); - };`); - const env = { ...process.env, QL_TRIGGER_ID:id, ID:'1', TS_NODE_PROJECT:path.resolve('back/tsconfig.json') }; + };`, + ); + const env = { + ...process.env, + QL_TRIGGER_ID: id, + ID: '1', + TS_NODE_PROJECT: path.resolve('back/tsconfig.json'), + }; const { spawnSync } = require('node:child_process'); if (producer === 'crond') { - const args = ['-r',failWrites,'-r','ts-node/register/transpile-only',require.resolve('../../back/bootstrap/systemCron.ts'), - 'finish','1',String(process.pid),id,'23',String(end)]; - for (let attempt=0; attempt<2; attempt++) { - const result = spawnSync(process.execPath,args,{env,encoding:'utf8'}); - assert.equal(result.status,0,result.stderr); + const args = [ + '-r', + failWrites, + '-r', + 'ts-node/register/transpile-only', + require.resolve('../../back/bootstrap/systemCron.ts'), + 'finish', + '1', + String(process.pid), + id, + '23', + String(end), + ]; + for (let attempt = 0; attempt < 2; attempt++) { + const result = spawnSync(process.execPath, args, { + env, + encoding: 'utf8', + }); + assert.equal(result.status, 0, result.stderr); } } else { // The Python parent is still alive. Force the independent reporter to // return its capacity-retry code once before it reaches the real DB. - const wrapper = path.join(root,'reporter.cjs'), attempts = path.join(root,'attempts'); - await fs.writeFile(wrapper, `require('node:fs').appendFileSync(process.env.ATTEMPTS,process.argv[2]+'\\n'); + const wrapper = path.join(root, 'reporter.cjs'), + attempts = path.join(root, 'attempts'); + await fs.writeFile( + wrapper, + `require('node:fs').appendFileSync(process.env.ATTEMPTS,process.argv[2]+'\\n'); if(require('node:fs').readFileSync(process.env.ATTEMPTS,'utf8').trim().split('\\n').length===1)process.exit(75); const cmd=require('node:child_process').spawnSync(process.execPath,['-r',process.env.FULL_WRITES,process.env.REAL_REPORTER,process.argv[2]],{stdio:'inherit',env:process.env}); - process.exit(cmd.status);`); - const result = spawnSync('python3',['-I','-S','-c',` + process.exit(cmd.status);`, + ); + const result = spawnSync( + 'python3', + [ + '-I', + '-S', + '-c', + ` import errno,os,runpy,sys,tempfile,time def full(*args,**kwargs):raise OSError(errno.ENOSPC,'no free inode') tempfile.NamedTemporaryFile=full time.time_ns=lambda: int(os.environ['FINISH'])*1000000 sys.argv=sys.argv[1:] sys.exit(runpy.run_path(sys.argv[0])['main']()) -`,path.resolve('shell/cron-command.py'),'exit 23',String(process.pid),receiptPath(id),process.execPath,wrapper], - {input:'run\n',encoding:'utf8',env:{...env,ATTEMPTS:attempts,FULL_WRITES:failWrites,FINISH:String(end), - REAL_REPORTER:require.resolve('../../back/shared/managedExit.cjs')}}); - assert.equal(result.status,23,result.stderr); - const messages = (await fs.readFile(attempts,'utf8')).trim().split('\n'); - assert.equal(messages.length,2); - assert.equal(messages[0],messages[1]); +`, + path.resolve('shell/cron-command.py'), + 'exit 23', + String(process.pid), + receiptPath(id), + process.execPath, + wrapper, + ], + { + input: 'run\n', + encoding: 'utf8', + env: { + ...env, + ATTEMPTS: attempts, + FULL_WRITES: failWrites, + FINISH: String(end), + REAL_REPORTER: require.resolve('../../back/shared/managedExit.cjs'), + }, + }, + ); + assert.equal(result.status, 23, result.stderr); + const messages = (await fs.readFile(attempts, 'utf8')).trim().split('\n'); + assert.equal(messages.length, 2); + assert.equal(messages[0], messages[1]); } assert.deepEqual(await fs.readdir(path.dirname(receiptPath(id))), []); - await history.complete(id,'failed',null,23); // The ordinary late supervisor-close callback. - const [row] = await history.visibleTriggers(1,[id]); - assert.deepEqual([row.state,row.exit_code,row.finished_at], ['failed',23,end]); - assert.deepEqual((await stats.CrontabStatModel.findAll()).map(r=>[r.date,r.run_count,r.fail_count]), - [[day.subtract(1,'day').format('YYYY-MM-DD'),1,1]]); + await history.complete(id, 'failed', null, 23); // The ordinary late supervisor-close callback. + const [row] = await history.visibleTriggers(1, [id]); + assert.deepEqual( + [row.state, row.exit_code, row.finished_at], + ['failed', 23, end], + ); + assert.deepEqual( + (await stats.CrontabStatModel.findAll()).map((r) => [ + r.date, + r.run_count, + r.fail_count, + ]), + [[day.subtract(1, 'day').format('YYYY-MM-DD'), 1, 1]], + ); }); } -test('a full-volume marker restored with a different valid body preserves both observed exits', async t => { - const { db, history, stats, writeExit, retiringExits, receiptPath } = await journalFixture(t); - const id='restored-metadata', end=Date.now()-500; - await history.enqueue(id,1,'manual',null,end-500); - await history.start(id,end-500,true); - const noBlocks=t.mock.method(require('node:fs'),'statfsSync',()=>({bavail:0})); - writeExit(id,0,null,end); +test('a full-volume marker restored with a different valid body preserves both observed exits', async (t) => { + const { db, history, stats, writeExit, retiringExits, receiptPath } = + await journalFixture(t); + const id = 'restored-metadata', + end = Date.now() - 500; + await history.enqueue(id, 1, 'manual', null, end - 500); + await history.start(id, end - 500, true); + const noBlocks = t.mock.method(require('node:fs'), 'statfsSync', () => ({ + bavail: 0, + })); + writeExit(id, 0, null, end); noBlocks.mock.restore(); - const [{file}]=await retiringExits(); - writeSingleFileExit(id,17,null,end+1); - await fs.rename(receiptPath(id),file); - await Promise.all([history.retryPendingExits(),new TriggerHistory(db).interrupt('http')]); - assert.deepEqual((await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', - {type:QueryTypes.SELECT})).map(r=>[r.outcome,r.finished_at]),[['0',end],['17',end+1]]); - assert.equal((await history.visibleTriggers(1,[id]))[0].reason,'exit_conflict'); - assert.equal(await stats.CrontabStatModel.count(),0); - assert.equal(JSON.parse(await fs.readFile(file,'utf8')).code,17); + const [{ file }] = await retiringExits(); + writeSingleFileExit(id, 17, null, end + 1); + await fs.rename(receiptPath(id), file); + await Promise.all([ + history.retryPendingExits(), + new TriggerHistory(db).interrupt('http'), + ]); + assert.deepEqual( + ( + await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', + { type: QueryTypes.SELECT }, + ) + ).map((r) => [r.outcome, r.finished_at]), + [ + ['0', end], + ['17', end + 1], + ], + ); + assert.equal( + (await history.visibleTriggers(1, [id]))[0].reason, + 'exit_conflict', + ); + assert.equal(await stats.CrontabStatModel.count(), 0); + assert.equal(JSON.parse(await fs.readFile(file, 'utf8')).code, 17); }); -test('SQLite cannot open its rollback journal on an inode-exhausted database filesystem', async t => { +test('SQLite cannot open its rollback journal on an inode-exhausted database filesystem', async (t) => { const { storageFull, receiptPath } = await journalFixture(t); const sync = require('node:fs'); const error = { original: { code: 'SQLITE_CANTOPEN' } }; const dbDir = path.dirname(path.dirname(receiptPath('capacity'))); let capacity = { files: 64, ffree: 0, bavail: 100 }; - t.mock.method(sync, 'statfsSync', dir => { assert.equal(dir, dbDir); return capacity; }); + t.mock.method(sync, 'statfsSync', (dir) => { + assert.equal(dir, dbDir); + return capacity; + }); assert.equal(storageFull(error), true); capacity = { files: 64, ffree: 13, bavail: 0 }; assert.equal(storageFull(error), true); capacity = { files: 64, ffree: 13, bavail: 100 }; assert.equal(storageFull(error), false); - assert.equal(storageFull({original:{code:'SQLITE_CONSTRAINT'}}),false); + assert.equal(storageFull({ original: { code: 'SQLITE_CONSTRAINT' } }), false); }); -test('a full SQLite volume at crond start reports failure and keeps the overlap exit code for actual overlap', async t => { +test('a full SQLite volume at crond start reports failure and keeps the overlap exit code for actual overlap', async (t) => { const { root } = await journalFixture(t); - const hook=path.join(root,'reject-registration.cjs'); - await fs.writeFile(path.join(root,'.env'),''); - await fs.writeFile(hook,`require(${JSON.stringify(require.resolve('sequelize'))}).Sequelize.prototype.query = async () => { + const hook = path.join(root, 'reject-registration.cjs'); + await fs.writeFile(path.join(root, '.env'), ''); + await fs.writeFile( + hook, + `require(${JSON.stringify( + require.resolve('sequelize'), + )}).Sequelize.prototype.query = async () => { throw Object.assign(Error('registration failed'),{original:{code:'SQLITE_FULL'}}); - };`); - const result=require('node:child_process').spawnSync(process.execPath,['-r',hook,'-r','ts-node/register/transpile-only', - require.resolve('../../back/bootstrap/systemCron.ts'),'start','1',String(process.pid),'system-1-missing',String(process.pid)], - {env:process.env,encoding:'utf8'}); - assert.equal(result.status,1,result.stderr); - assert.match(result.stderr,/registration failed/); + };`, + ); + const result = require('node:child_process').spawnSync( + process.execPath, + [ + '-r', + hook, + '-r', + 'ts-node/register/transpile-only', + require.resolve('../../back/bootstrap/systemCron.ts'), + 'start', + '1', + String(process.pid), + 'system-1-missing', + String(process.pid), + ], + { env: process.env, encoding: 'utf8' }, + ); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /registration failed/); }); -test('the first ext4 receipt and its containing directory must be durable before publication succeeds', async t => { +test('the first ext4 receipt and its containing directory must be durable before publication succeeds', async (t) => { const { writeExit, receiptPath } = await journalFixture(t); const native = require('node:fs'); const directory = path.dirname(receiptPath('power-cut')); const synced = []; const realSync = native.fsyncSync; - const hook = t.mock.method(native, 'fsyncSync', fd => { + const hook = t.mock.method(native, 'fsyncSync', (fd) => { const stat = native.fstatSync(fd); if (stat.isDirectory()) synced.push(stat.ino); return realSync(fd); }); writeExit('power-cut', 17, null, Date.now()); for (const dir of [directory, path.dirname(directory)]) { - assert.ok(synced.includes((await fs.stat(dir)).ino), 'publication did not sync ' + dir); + assert.ok( + synced.includes((await fs.stat(dir)).ino), + 'publication did not sync ' + dir, + ); } hook.mock.restore(); - t.mock.method(native, 'fsyncSync', () => { throw Object.assign(Error('writeback full'), { code: 'ENOSPC' }); }); - assert.throws(() => writeExit('failed-barrier', 0, null, Date.now()), { code: 'ENOSPC' }); + t.mock.method(native, 'fsyncSync', () => { + throw Object.assign(Error('writeback full'), { code: 'ENOSPC' }); + }); + assert.throws(() => writeExit('failed-barrier', 0, null, Date.now()), { + code: 'ENOSPC', + }); }); -test('the Python supervisor reports the original exit when its directory sync fails', async t => { +test('the Python supervisor reports the original exit when its directory sync fails', async (t) => { const { root, receiptPath } = await journalFixture(t); - const id = 'failed-directory-flush', finish = Date.now(), output = path.join(root, 'reported.json'); + const id = 'failed-directory-flush', + finish = Date.now(), + output = path.join(root, 'reported.json'); const reporter = path.join(root, 'report.cjs'); - await fs.writeFile(reporter, "require('fs').writeFileSync(process.env.REPORT, process.argv[2])"); - const run = require('node:child_process').spawnSync('python3', ['-I', '-S', '-c', ` + await fs.writeFile( + reporter, + "require('fs').writeFileSync(process.env.REPORT, process.argv[2])", + ); + const run = require('node:child_process').spawnSync( + 'python3', + [ + '-I', + '-S', + '-c', + ` import errno, os, runpy, stat, sys, time original = os.fsync def no_space(fd): @@ -4906,382 +8546,636 @@ os.fsync = no_space time.time_ns = lambda: int(os.environ['FINISH']) * 1000000 sys.argv = sys.argv[1:] sys.exit(runpy.run_path(sys.argv[0])['main']()) -`, path.resolve('shell/cron-command.py'), 'exit 23', String(process.pid), receiptPath(id), process.execPath, reporter], - { input: 'run\n', encoding: 'utf8', env: { ...process.env, QL_TRIGGER_ID:id, FINISH:String(finish), REPORT:output } }); +`, + path.resolve('shell/cron-command.py'), + 'exit 23', + String(process.pid), + receiptPath(id), + process.execPath, + reporter, + ], + { + input: 'run\n', + encoding: 'utf8', + env: { + ...process.env, + QL_TRIGGER_ID: id, + FINISH: String(finish), + REPORT: output, + }, + }, + ); assert.equal(run.status, 23, run.stderr); const receipt = JSON.parse(await fs.readFile(output, 'utf8')); assert.deepEqual([receipt.code, receipt.time], [23, finish]); }); -test('SQLite syncs rollback-journal removal on every panel connection before work starts', async t => { +test('SQLite syncs rollback-journal removal on every panel connection before work starts', async (t) => { const { db } = await fixture(t, true); - const level = async tx => (await db.query('PRAGMA synchronous', { transaction:tx, type:QueryTypes.SELECT }))[0].synchronous; + const level = async (tx) => + ( + await db.query('PRAGMA synchronous', { + transaction: tx, + type: QueryTypes.SELECT, + }) + )[0].synchronous; assert.deepEqual(await Promise.all([level(), level()]), [3, 3]); - for (let retry = 0; retry < 2; retry++) assert.equal(await db.transaction(level), 3); + for (let retry = 0; retry < 2; retry++) + assert.equal(await db.transaction(level), 3); }); -test('the legacy JSON body is flushed before linking, and its published name is synced before return', async t => { +test('the legacy JSON body is flushed before linking, and its published name is synced before return', async (t) => { const { writeExit } = await journalFixture(t); - const native = require('node:fs'), order = []; - const write = native.writeFileSync, link = native.linkSync, sync = native.fsyncSync; + const native = require('node:fs'), + order = []; + const write = native.writeFileSync, + link = native.linkSync, + sync = native.fsyncSync; t.mock.method(native, 'writeFileSync', (file, body, options) => { - if (body) { assert.equal(options.flush, true); order.push('JSON'); } + if (body) { + assert.equal(options.flush, true); + order.push('JSON'); + } return write(file, body, options); }); - t.mock.method(native, 'linkSync', (...args) => { link(...args); order.push('link'); }); - t.mock.method(native, 'fsyncSync', fd => { + t.mock.method(native, 'linkSync', (...args) => { + link(...args); + order.push('link'); + }); + t.mock.method(native, 'fsyncSync', (fd) => { if (native.fstatSync(fd).isDirectory()) order.push('directory'); return sync(fd); }); for (let attempt = 0; attempt < 2; attempt++) { order.length = 0; writeExit('legacy-fence', 23, null, 1790000000123); - assert.deepEqual(order, ['directory', 'directory', 'JSON', 'link', 'directory']); + assert.deepEqual(order, [ + 'directory', + 'directory', + 'JSON', + 'link', + 'directory', + ]); } }); -test('concurrent first queries wait for the SQLite durability setting and retry a failed initialization', async t => { +test('concurrent first queries wait for the SQLite durability setting and retry a failed initialization', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-sqlite-barrier-')); - const db = load('back/data/index.ts', { '../config/index': { dbPath: root } }).sequelize; - t.after(async () => { await db.close(); await fs.rm(root, { recursive:true, force:true }); }); + const db = load('back/data/index.ts', { + '../config/index': { dbPath: root }, + }).sequelize; + t.after(async () => { + await db.close(); + await fs.rm(root, { recursive: true, force: true }); + }); // Open the handle before either caller starts its first query. - await db.connectionManager.getConnection({ type:'read' }); - const native = require('sqlite3').Database.prototype, run = native.run; - let attempts = 0, fail; - t.mock.method(native, 'run', function(sql, ...args) { + await db.connectionManager.getConnection({ type: 'read' }); + const native = require('sqlite3').Database.prototype, + run = native.run; + let attempts = 0, + fail; + t.mock.method(native, 'run', function (sql, ...args) { if (sql === 'PRAGMA synchronous=EXTRA' && ++attempts === 1) { - fail = () => args.at(-1)(Object.assign(Error('full'), { code:'SQLITE_FULL' })); + fail = () => + args.at(-1)(Object.assign(Error('full'), { code: 'SQLITE_FULL' })); return this; } return run.call(this, sql, ...args); }); - const query = () => db.query('PRAGMA synchronous', { type:QueryTypes.SELECT }); + const query = () => + db.query('PRAGMA synchronous', { type: QueryTypes.SELECT }); const first = Promise.allSettled([query(), query()]); - await new Promise(resolve => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); assert.equal(typeof fail, 'function'); fail(); - assert.deepEqual((await first).map(r => [r.status,r.reason?.code]), - [['rejected','SQLITE_FULL'],['rejected','SQLITE_FULL']]); - assert.deepEqual(await Promise.all([query(),query()]), [[{synchronous:3}],[{synchronous:3}]]); + assert.deepEqual( + (await first).map((r) => [r.status, r.reason?.code]), + [ + ['rejected', 'SQLITE_FULL'], + ['rejected', 'SQLITE_FULL'], + ], + ); + assert.deepEqual(await Promise.all([query(), query()]), [ + [{ synchronous: 3 }], + [{ synchronous: 3 }], + ]); assert.equal(attempts, 2); }); -test('Linux full-volume retry unlinks only from the directory it inspected when a claim name is reused', { - skip: process.platform !== 'linux', -}, async t => { - const { receiptPath, readExit, retireLegacyFile } = await journalFixture(t); - const id = 'full-claim-reuse', end = Date.now(); - writeSingleFileExit(id, 23, null, end); - const publicFile = receiptPath(id), root = path.dirname(publicFile); - const claim = await fs.mkdtemp(path.join(root, '.claim.' + id + '.')); - const slot = path.join(claim, 'receipt'); - await fs.rename(publicFile, slot); - writeSingleFileExit(id, 17, null, end + 1); - t.mock.method(fs, 'mkdtemp', async () => { throw Object.assign(Error('no inodes'), { code:'ENOSPC' }); }); - const unlink = fs.unlink.bind(fs); - let switched = false; - t.mock.method(fs, 'unlink', async target => { - if (!switched) { - switched = true; - await fs.rename(claim, claim + '-original'); - await fs.mkdir(claim); - await fs.copyFile(publicFile, slot); - } - return unlink(target); - }); - await retireLegacyFile(id, slot, {outcome:'23',time:end}); - assert.equal(switched, true); - assert.equal(await readExit(id, path.join(claim + '-original', 'receipt')), undefined); - assert.equal((await readExit(id, slot)).code, 17); - assert.equal((await readExit(id, publicFile)).time, end + 1); -}); - -test('Linux full-volume recovery verifies the private marker name and preserves a contradictory body', { - skip: process.platform !== 'linux', -}, async t => { - const { receiptPath, readExit, retireLegacyFile, retiringExits, writeExit } = await journalFixture(t); - const id = 'full-claim-metadata', end = Date.now(); - writeExit(id, 17, null, end); - const publicFile = receiptPath(id); - const files = await retiringExits(); - const marker = (await Promise.all(files.map(async row => (await fs.stat(row.file)).size === 0 ? row.file : null))).find(Boolean); - const claim = marker + 'ABC'; - const slot = path.join(claim, '.pending.claimed'); - await fs.mkdir(claim); - await fs.rename(marker, slot); - const full = () => { throw Object.assign(Error('quota'), { code:'EDQUOT' }); }; - t.mock.method(fs, 'mkdtemp', full); - await retireLegacyFile(id, publicFile, {outcome:'17', time:end}); - assert.equal(await readExit(id,publicFile), undefined); - await retireLegacyFile(id, slot, {outcome:'0', time:end}); - assert.equal((await readExit(id, slot)).code, 17); - writeSingleFileExit(id, 23, null, end + 1); - await fs.copyFile(publicFile, slot); - await retireLegacyFile(id, slot, {outcome:'23', time:end + 1}); - const both = await readExit(id, slot); - assert.deepEqual([both.code, both.namedExit.code], [23,17]); - await fs.truncate(slot, 0); - await retireLegacyFile(id, slot, {outcome:'17', time:end}); - assert.equal(await readExit(id, slot), undefined); - assert.equal((await readExit(id, publicFile)).code, 23); -}); - -for (const operation of ['rename','unlink']) { - test('a '+operation+' capacity error preserves replacement and replay evidence for a pruned day', async t => { - const { history, db, receiptPath, writeExit, readExit, stats } = await journalFixture(t); - const id = 'pruned-full-' + operation, end = require('dayjs')().subtract(4,'day').valueOf(); - await history.enqueue(id,1,'manual',null,end-1000); - await history.start(id,end-1000,true); - writeSingleFileExit(id,23,null,end); - await history.complete(id,'unknown',null,null); - const policy = new (load('back/services/retention.ts',{ - '../data':{sequelize:db}, '../data/cronStats':stats, - '../data/runningInstance':{RunningInstanceModel:db.models.RunningInstance,InstanceStatus:{running:0}}, - '../data/system':{}, '../config':{}, - }).default)(); - await policy.cleanup({runningInstanceRetentionDays:1,cronStatRetentionDays:1}); - const file = receiptPath(id), now = Date.now(); - writeSingleFileExit(id,23,null,end); - const original = fs[operation].bind(fs); - let failed = false; - const hook = t.mock.method(fs,operation,async (src,...args) => { - if ((operation==='rename' ? src===file : path.basename(src).startsWith('.pending.' + id + '.')) && !failed) { - failed = true; - writeExit(id,42,null,now); - throw Object.assign(Error('capacity exhausted'),{code:'ENOSPC'}); - } - return original(src,...args); +test( + 'Linux full-volume retry unlinks only from the directory it inspected when a claim name is reused', + { + skip: process.platform !== 'linux', + }, + async (t) => { + const { receiptPath, readExit, retireLegacyFile } = await journalFixture(t); + const id = 'full-claim-reuse', + end = Date.now(); + writeSingleFileExit(id, 23, null, end); + const publicFile = receiptPath(id), + root = path.dirname(publicFile); + const claim = await fs.mkdtemp(path.join(root, '.claim.' + id + '.')); + const slot = path.join(claim, 'receipt'); + await fs.rename(publicFile, slot); + writeSingleFileExit(id, 17, null, end + 1); + t.mock.method(fs, 'mkdtemp', async () => { + throw Object.assign(Error('no inodes'), { code: 'ENOSPC' }); }); - await history.complete(id,'unknown',null,null); - assert.equal(failed,true); - hook.mock.restore(); - await Promise.all([publishFromPeer(id,23,end),publishFromPeer(id,42,now),history.retryPendingExits()]); - await new TriggerHistory(db).interrupt('http'); - const evidence = await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - {bind:{id},type:QueryTypes.SELECT}); - assert.deepEqual(evidence.map(v=>[v.outcome,v.finished_at]),[['23',end],['42',now]]); - assert.deepEqual(await history.visibleTriggers(1,[id]),[]); - assert.equal(await stats.CrontabStatModel.count(),0); - }); + const unlink = fs.unlink.bind(fs); + let switched = false; + t.mock.method(fs, 'unlink', async (target) => { + if (!switched) { + switched = true; + await fs.rename(claim, claim + '-original'); + await fs.mkdir(claim); + await fs.copyFile(publicFile, slot); + } + return unlink(target); + }); + await retireLegacyFile(id, slot, { outcome: '23', time: end }); + assert.equal(switched, true); + assert.equal( + await readExit(id, path.join(claim + '-original', 'receipt')), + undefined, + ); + assert.equal((await readExit(id, slot)).code, 17); + assert.equal((await readExit(id, publicFile)).time, end + 1); + }, +); + +test( + 'Linux full-volume recovery verifies the private marker name and preserves a contradictory body', + { + skip: process.platform !== 'linux', + }, + async (t) => { + const { + receiptPath, + readExit, + retireLegacyFile, + retiringExits, + writeExit, + } = await journalFixture(t); + const id = 'full-claim-metadata', + end = Date.now(); + writeExit(id, 17, null, end); + const publicFile = receiptPath(id); + const files = await retiringExits(); + const marker = ( + await Promise.all( + files.map(async (row) => + (await fs.stat(row.file)).size === 0 ? row.file : null, + ), + ) + ).find(Boolean); + const claim = marker + 'ABC'; + const slot = path.join(claim, '.pending.claimed'); + await fs.mkdir(claim); + await fs.rename(marker, slot); + const full = () => { + throw Object.assign(Error('quota'), { code: 'EDQUOT' }); + }; + t.mock.method(fs, 'mkdtemp', full); + await retireLegacyFile(id, publicFile, { outcome: '17', time: end }); + assert.equal(await readExit(id, publicFile), undefined); + await retireLegacyFile(id, slot, { outcome: '0', time: end }); + assert.equal((await readExit(id, slot)).code, 17); + writeSingleFileExit(id, 23, null, end + 1); + await fs.copyFile(publicFile, slot); + await retireLegacyFile(id, slot, { outcome: '23', time: end + 1 }); + const both = await readExit(id, slot); + assert.deepEqual([both.code, both.namedExit.code], [23, 17]); + await fs.truncate(slot, 0); + await retireLegacyFile(id, slot, { outcome: '17', time: end }); + assert.equal(await readExit(id, slot), undefined); + assert.equal((await readExit(id, publicFile)).code, 23); + }, +); + +for (const operation of ['rename', 'unlink']) { + test( + 'a ' + + operation + + ' capacity error preserves replacement and replay evidence for a pruned day', + async (t) => { + const { history, db, receiptPath, writeExit, readExit, stats } = + await journalFixture(t); + const id = 'pruned-full-' + operation, + end = require('dayjs')().subtract(4, 'day').valueOf(); + await history.enqueue(id, 1, 'manual', null, end - 1000); + await history.start(id, end - 1000, true); + writeSingleFileExit(id, 23, null, end); + await history.complete(id, 'unknown', null, null); + const policy = new (load('back/services/retention.ts', { + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, + }).default)(); + await policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); + const file = receiptPath(id), + now = Date.now(); + writeSingleFileExit(id, 23, null, end); + const original = fs[operation].bind(fs); + let failed = false; + const hook = t.mock.method(fs, operation, async (src, ...args) => { + if ( + (operation === 'rename' + ? src === file + : path.basename(src).startsWith('.pending.' + id + '.')) && + !failed + ) { + failed = true; + writeExit(id, 42, null, now); + throw Object.assign(Error('capacity exhausted'), { code: 'ENOSPC' }); + } + return original(src, ...args); + }); + await history.complete(id, 'unknown', null, null); + assert.equal(failed, true); + hook.mock.restore(); + await Promise.all([ + publishFromPeer(id, 23, end), + publishFromPeer(id, 42, now), + history.retryPendingExits(), + ]); + await new TriggerHistory(db).interrupt('http'); + const evidence = await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ); + assert.deepEqual( + evidence.map((v) => [v.outcome, v.finished_at]), + [ + ['23', end], + ['42', now], + ], + ); + assert.deepEqual(await history.visibleTriggers(1, [id]), []); + assert.equal(await stats.CrontabStatModel.count(), 0); + }, + ); } -for (const replace of ['directory','file','file-before-final-unlink']) test('two Linux collectors retry after replacing the verified '+replace, { - skip: process.platform !== 'linux', timeout: 25000, -}, async t => { - const { receiptPath, readExit, retiringExits } = await journalFixture(t); - const id = 'reappeared', end = Date.now(); - writeSingleFileExit(id, 17, null, end); - const file = receiptPath(id), root = path.dirname(file); - const claim = await fs.mkdtemp(path.join(root, '.claim.' + id + '.')); - const slot = path.join(claim, 'receipt'); - await fs.rename(file, slot); - const original = await fs.stat(claim); - const workers = ['first','second'].map(label => { - const barrier = path.join(root,label); - const child = require('node:child_process').spawn(process.execPath, [ - path.resolve('test/helpers/receipt-claim-reuse-worker.cjs'), path.resolve('back/shared/managedExit.cjs'), - slot, id, '17', String(end), barrier, '', replace === 'file-before-final-unlink' ? 'holdUnlink' : '', - ], {stdio:'inherit'}); - t.after(() => { if (child.exitCode === null) child.kill(); }); - return { barrier, done: new Promise(resolve => child.once('exit',resolve)) }; - }); - for (const {barrier} of workers) { - const limit = Date.now() + 10000; - while (!require('node:fs').existsSync(barrier + '.ready')) { - assert.ok(Date.now() < limit, 'collector did not reach the verified inode'); - await new Promise(resolve => setTimeout(resolve, 10)); - } - assert.equal(JSON.parse(await fs.readFile(barrier + '.ready','utf8')).directoryInode, original.ino); - } - if (replace === 'file-before-final-unlink') { - const {barrier} = workers[0]; - await fs.writeFile(barrier+'.go',''); - const limit = Date.now()+5000; - while (!require('node:fs').existsSync(barrier+'.checked')) { - assert.ok(Date.now() setTimeout(resolve,10)); - } - } - if (replace === 'directory') { - await fs.rename(claim, claim + '-old'); - await fs.mkdir(claim); - } - writeSingleFileExit(id, 42, null, end+1); - await fs.rename(file, slot); - if (replace === 'file-before-final-unlink') await fs.writeFile(workers[0].barrier+'.release',''); - for (const {barrier} of workers) await fs.writeFile(barrier + '.go',''); - assert.deepEqual(await Promise.all(workers.map(w => w.done)), [0,0]); - assert.equal(await readExit(id,path.join(claim + '-old','receipt')), undefined); - const recovered = await Promise.all((await retiringExits()).map(f => readExit(f.id,f.file))); - assert.deepEqual(recovered.map(r => r?.code), [42]); -}); +for (const replace of ['directory', 'file', 'file-before-final-unlink']) + test( + 'two Linux collectors retry after replacing the verified ' + replace, + { + skip: process.platform !== 'linux', + timeout: 25000, + }, + async (t) => { + const { receiptPath, readExit, retiringExits } = await journalFixture(t); + const id = 'reappeared', + end = Date.now(); + writeSingleFileExit(id, 17, null, end); + const file = receiptPath(id), + root = path.dirname(file); + const claim = await fs.mkdtemp(path.join(root, '.claim.' + id + '.')); + const slot = path.join(claim, 'receipt'); + await fs.rename(file, slot); + const original = await fs.stat(claim); + const workers = ['first', 'second'].map((label) => { + const barrier = path.join(root, label); + const child = require('node:child_process').spawn( + process.execPath, + [ + path.resolve('test/helpers/receipt-claim-reuse-worker.cjs'), + path.resolve('back/cron/settlement/exitReceipt.cjs'), + slot, + id, + '17', + String(end), + barrier, + '', + replace === 'file-before-final-unlink' ? 'holdUnlink' : '', + ], + { stdio: 'inherit' }, + ); + t.after(() => { + if (child.exitCode === null) child.kill(); + }); + return { + barrier, + done: new Promise((resolve) => child.once('exit', resolve)), + }; + }); + for (const { barrier } of workers) { + const limit = Date.now() + 10000; + while (!require('node:fs').existsSync(barrier + '.ready')) { + assert.ok( + Date.now() < limit, + 'collector did not reach the verified inode', + ); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.equal( + JSON.parse(await fs.readFile(barrier + '.ready', 'utf8')) + .directoryInode, + original.ino, + ); + } + if (replace === 'file-before-final-unlink') { + const { barrier } = workers[0]; + await fs.writeFile(barrier + '.go', ''); + const limit = Date.now() + 5000; + while (!require('node:fs').existsSync(barrier + '.checked')) { + assert.ok(Date.now() < limit, 'collector never reached final unlink'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + } + if (replace === 'directory') { + await fs.rename(claim, claim + '-old'); + await fs.mkdir(claim); + } + writeSingleFileExit(id, 42, null, end + 1); + await fs.rename(file, slot); + if (replace === 'file-before-final-unlink') + await fs.writeFile(workers[0].barrier + '.release', ''); + for (const { barrier } of workers) + await fs.writeFile(barrier + '.go', ''); + assert.deepEqual(await Promise.all(workers.map((w) => w.done)), [0, 0]); + assert.equal( + await readExit(id, path.join(claim + '-old', 'receipt')), + undefined, + ); + const recovered = await Promise.all( + (await retiringExits()).map((f) => readExit(f.id, f.file)), + ); + assert.deepEqual( + recovered.map((r) => r?.code), + [42], + ); + }, + ); -for (const first of [17,42]) { - test(`pruned exit stores a lone bound tuple across restart before the other arrives: ${first}`, async t => { - const { db, history, receiptPath, readExit, stats } = await journalFixture(t); - const id = 'pruned-sequential', end = Date.now(), other = first === 17 ? 42 : 17; - const time = code => code === 17 ? end - 86400000 : end; +for (const first of [17, 42]) { + test(`pruned exit stores a lone bound tuple across restart before the other arrives: ${first}`, async (t) => { + const { db, history, receiptPath, readExit, stats } = await journalFixture( + t, + ); + const id = 'pruned-sequential', + end = Date.now(), + other = first === 17 ? 42 : 17; + const time = (code) => (code === 17 ? end - 86400000 : end); // No booking or trigger survives pruning. The only new bytes reside in // the private directory restored by ext4. - writeSingleFileExit(id,first,null,time(first)); - const file = receiptPath(id), claim = await fs.mkdtemp(path.join(path.dirname(file),'.claim.'+id+'.')); - const slot = path.join(claim,'receipt'); - await fs.rename(file,slot); + writeSingleFileExit(id, first, null, time(first)); + const file = receiptPath(id), + claim = await fs.mkdtemp( + path.join(path.dirname(file), '.claim.' + id + '.'), + ); + const slot = path.join(claim, 'receipt'); + await fs.rename(file, slot); await db.query('CREATE TABLE missing_parent (id INTEGER PRIMARY KEY)'); - await db.query('CREATE TABLE deferred_exit (id INTEGER REFERENCES missing_parent(id) DEFERRABLE INITIALLY DEFERRED)'); - await db.query('CREATE TRIGGER fail_unmatched AFTER INSERT ON CronUnmatchedBoundExits BEGIN INSERT INTO deferred_exit VALUES(1); END'); - await assert.rejects(history.complete(id,'unknown',null,null), /constraint|foreign key/i); - assert.equal((await readExit(id,slot)).code,first); + await db.query( + 'CREATE TABLE deferred_exit (id INTEGER REFERENCES missing_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_unmatched AFTER INSERT ON CronUnmatchedBoundExits BEGIN INSERT INTO deferred_exit VALUES(1); END', + ); + await assert.rejects( + history.complete(id, 'unknown', null, null), + /constraint|foreign key/i, + ); + assert.equal((await readExit(id, slot)).code, first); await db.query('DROP TRIGGER fail_unmatched'); await history.interrupt('http'); - assert.equal(await readExit(id,slot),undefined); - const evidence = table => db.query('SELECT outcome,finished_at FROM '+table+' WHERE trigger_id=$id ORDER BY finished_at', - {bind:{id},type:QueryTypes.SELECT}); - assert.deepEqual(await evidence('CronUnmatchedBoundExits'),[{outcome:String(first),finished_at:time(first)}]); - writeSingleFileExit(id,other,null,time(other)); + assert.equal(await readExit(id, slot), undefined); + const evidence = (table) => + db.query( + 'SELECT outcome,finished_at FROM ' + + table + + ' WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ); + assert.deepEqual(await evidence('CronUnmatchedBoundExits'), [ + { outcome: String(first), finished_at: time(first) }, + ]); + writeSingleFileExit(id, other, null, time(other)); await new TriggerHistory(db).retryPendingExits(); - await Promise.all([publishFromPeer(id,first,time(first)),publishFromPeer(id,other,time(other))]); - assert.deepEqual(await evidence('CronBoundExitConflicts'),[17,42].map(code=>({outcome:String(code),finished_at:time(code)}))); - assert.deepEqual(await evidence('CronUnmatchedBoundExits'),[]); - assert.deepEqual(await history.visibleTriggers(1,[id]),[]); - assert.equal(await stats.CrontabStatModel.count(),0); + await Promise.all([ + publishFromPeer(id, first, time(first)), + publishFromPeer(id, other, time(other)), + ]); + assert.deepEqual( + await evidence('CronBoundExitConflicts'), + [17, 42].map((code) => ({ + outcome: String(code), + finished_at: time(code), + })), + ); + assert.deepEqual(await evidence('CronUnmatchedBoundExits'), []); + assert.deepEqual(await history.visibleTriggers(1, [id]), []); + assert.equal(await stats.CrontabStatModel.count(), 0); }); } -test('concurrent collectors use distinct disposal names outside the occupied private directory', { - skip: process.platform !== 'linux', timeout: 15000, -}, async t => { - const { receiptPath, readExit, retireLegacyFile } = await journalFixture(t); - const id = 'allocator-reuse', time = Date.now(); - writeSingleFileExit(id, 17, null, time); - const older = receiptPath(id), root = path.dirname(older); - const newer = path.join(root,'.collecting.' + id + '.' + require('node:crypto').randomUUID()); - await fs.rename(older,newer); - writeSingleFileExit(id,42,null,time+1); - const claim = await fs.mkdtemp(path.join(root,'.claim.' + id + '.')); - const slot = path.join(claim,'receipt'); - await fs.copyFile(older,slot); - const targets = []; - const rename = fs.rename.bind(fs); - t.mock.method(fs,'rename', async (from,to) => { targets.push(to); return rename(from,to); }); - await Promise.all([retireLegacyFile(id,older,{outcome:'0',time}), - retireLegacyFile(id,newer,{outcome:'17',time})]); - assert.equal(new Set(targets).size,2); - assert.ok(targets.every(f => path.dirname(f) === path.dirname(root))); - assert.equal((await readExit(id,slot)).code,42); - const retained = await Promise.all(targets.map(f => readExit(id,f))); - assert.deepEqual(retained.filter(Boolean).map(r => r.code),[42]); -}); - -test('Linux uses the supervisor Python runtime for the inode lock when flock is absent', { - skip: process.platform !== 'linux', -}, async t => { - const {receiptPath,retireLegacyFile} = await journalFixture(t); - const id = 'python-lock', when = Date.now(); - writeSingleFileExit(id,0,null,when); - const proc = require('node:child_process'), spawn = proc.spawn; - const programs = []; - t.mock.method(proc,'spawn',(name,args,options) => { - programs.push(name); - return spawn(name === 'flock' ? '/missing-flock-on-test-panel' : name,args,options); - }); - const file = receiptPath(id), claim = await fs.mkdtemp(path.join(path.dirname(file),'.claim.' + id + '.')); - const slot = path.join(claim,'receipt'); - await fs.rename(file,slot); - await retireLegacyFile(id,slot,{outcome:'0',time:when}); - assert.deepEqual(programs,['flock','python3']); - assert.deepEqual(await fs.readdir(path.dirname(receiptPath(id))),[]); -}); - -for (const replacement of ['changed-code','changed-millis','torn','bound']) { - test('recovery preserves a replacement in an unbound slot across retries: '+replacement, async t => { - const {receiptPath,readExit,retiringExits,retireLegacyFile} = await journalFixture(t); - const id = 'weak-slot', file = receiptPath(id), time = Date.now(); - const claim = path.join(path.dirname(file),'.claim.'+id+'.ab1234'); - const slot = path.join(claim,'receipt'); - await fs.mkdir(claim,{recursive:true}); - await fs.writeFile(slot,JSON.stringify({code:0,signal:null,time})); - writeSingleFileExit(id,17,null,time); - let body = await fs.readFile(file,'utf8'); - if (replacement !== 'bound') body = replacement === 'torn' ? '{"code":' : - JSON.stringify({code:replacement === 'changed-code' ? 17 : 0,signal:null,time:time+Number(replacement==='changed-millis')}); - await fs.writeFile(file,body); +test( + 'concurrent collectors use distinct disposal names outside the occupied private directory', + { + skip: process.platform !== 'linux', + timeout: 15000, + }, + async (t) => { + const { receiptPath, readExit, retireLegacyFile } = await journalFixture(t); + const id = 'allocator-reuse', + time = Date.now(); + writeSingleFileExit(id, 17, null, time); + const older = receiptPath(id), + root = path.dirname(older); + const newer = path.join( + root, + '.collecting.' + id + '.' + require('node:crypto').randomUUID(), + ); + await fs.rename(older, newer); + writeSingleFileExit(id, 42, null, time + 1); + const claim = await fs.mkdtemp(path.join(root, '.claim.' + id + '.')); + const slot = path.join(claim, 'receipt'); + await fs.copyFile(older, slot); + const targets = []; const rename = fs.rename.bind(fs); - const hook = t.mock.method(fs,'rename',async (src,dest) => { - await rename(file,slot); - await rename(src,dest); - throw Object.assign(Error('interrupted after capture'),{code:'EIO'}); + t.mock.method(fs, 'rename', async (from, to) => { + targets.push(to); + return rename(from, to); }); - await assert.rejects(retireLegacyFile(id,slot),{code:'EIO'}); - hook.mock.restore(); - const [capture] = await retiringExits(); - assert.equal(capture.id,id); - for (let i=0;i<2;i++) { - const value = await readExit(id,capture.file); - if (replacement==='bound') assert.equal(value.code,17); - else assert.equal(value,null); - await retireLegacyFile(id,capture.file); - assert.equal(await fs.readFile(capture.file,'utf8'),body); - } - }); + await Promise.all([ + retireLegacyFile(id, older, { outcome: '0', time }), + retireLegacyFile(id, newer, { outcome: '17', time }), + ]); + assert.equal(new Set(targets).size, 2); + assert.ok(targets.every((f) => path.dirname(f) === path.dirname(root))); + assert.equal((await readExit(id, slot)).code, 42); + const retained = await Promise.all(targets.map((f) => readExit(id, f))); + assert.deepEqual( + retained.filter(Boolean).map((r) => r.code), + [42], + ); + }, +); + +test( + 'Linux uses the supervisor Python runtime for the inode lock when flock is absent', + { + skip: process.platform !== 'linux', + }, + async (t) => { + const { receiptPath, retireLegacyFile } = await journalFixture(t); + const id = 'python-lock', + when = Date.now(); + writeSingleFileExit(id, 0, null, when); + const proc = require('node:child_process'), + spawn = proc.spawn; + const programs = []; + t.mock.method(proc, 'spawn', (name, args, options) => { + programs.push(name); + return spawn( + name === 'flock' ? '/missing-flock-on-test-panel' : name, + args, + options, + ); + }); + const file = receiptPath(id), + claim = await fs.mkdtemp( + path.join(path.dirname(file), '.claim.' + id + '.'), + ); + const slot = path.join(claim, 'receipt'); + await fs.rename(file, slot); + await retireLegacyFile(id, slot, { outcome: '0', time: when }); + assert.deepEqual(programs, ['flock', 'python3']); + assert.deepEqual(await fs.readdir(path.dirname(receiptPath(id))), []); + }, +); + +for (const replacement of ['changed-code', 'changed-millis', 'torn', 'bound']) { + test( + 'recovery preserves a replacement in an unbound slot across retries: ' + + replacement, + async (t) => { + const { receiptPath, readExit, retiringExits, retireLegacyFile } = + await journalFixture(t); + const id = 'weak-slot', + file = receiptPath(id), + time = Date.now(); + const claim = path.join(path.dirname(file), '.claim.' + id + '.ab1234'); + const slot = path.join(claim, 'receipt'); + await fs.mkdir(claim, { recursive: true }); + await fs.writeFile(slot, JSON.stringify({ code: 0, signal: null, time })); + writeSingleFileExit(id, 17, null, time); + let body = await fs.readFile(file, 'utf8'); + if (replacement !== 'bound') + body = + replacement === 'torn' + ? '{"code":' + : JSON.stringify({ + code: replacement === 'changed-code' ? 17 : 0, + signal: null, + time: time + Number(replacement === 'changed-millis'), + }); + await fs.writeFile(file, body); + const rename = fs.rename.bind(fs); + const hook = t.mock.method(fs, 'rename', async (src, dest) => { + await rename(file, slot); + await rename(src, dest); + throw Object.assign(Error('interrupted after capture'), { + code: 'EIO', + }); + }); + await assert.rejects(retireLegacyFile(id, slot), { code: 'EIO' }); + hook.mock.restore(); + const [capture] = await retiringExits(); + assert.equal(capture.id, id); + for (let i = 0; i < 2; i++) { + const value = await readExit(id, capture.file); + if (replacement === 'bound') assert.equal(value.code, 17); + else assert.equal(value, null); + await retireLegacyFile(id, capture.file); + assert.equal(await fs.readFile(capture.file, 'utf8'), body); + } + }, + ); } -test('a separately mounted journal retains the replacement in a recoverable same-device directory', async t => { - const {receiptPath,retiringExits,readExit,retireLegacyFile} = await journalFixture(t); - const id='external-spool', time=Date.now(), file=receiptPath(id); - writeSingleFileExit(id,17,null,time); - const spool = path.dirname(file), db = path.dirname(spool), claim = await fs.mkdtemp(path.join(spool,'.claim.'+id+'.')); - const slot=path.join(claim,'receipt'); - await fs.rename(file,slot); - writeSingleFileExit(id,42,null,time+1); +test('a separately mounted journal retains the replacement in a recoverable same-device directory', async (t) => { + const { receiptPath, retiringExits, readExit, retireLegacyFile } = + await journalFixture(t); + const id = 'external-spool', + time = Date.now(), + file = receiptPath(id); + writeSingleFileExit(id, 17, null, time); + const spool = path.dirname(file), + db = path.dirname(spool), + claim = await fs.mkdtemp(path.join(spool, '.claim.' + id + '.')); + const slot = path.join(claim, 'receipt'); + await fs.rename(file, slot); + writeSingleFileExit(id, 42, null, time + 1); const rename = fs.rename.bind(fs); - const hook = t.mock.method(fs,'rename',async (from,to) => { - if (path.dirname(to)===db) { - await rename(file,slot); - throw Object.assign(Error('cross-device rename'),{code:'EXDEV'}); + const hook = t.mock.method(fs, 'rename', async (from, to) => { + if (path.dirname(to) === db) { + await rename(file, slot); + throw Object.assign(Error('cross-device rename'), { code: 'EXDEV' }); } - return rename(from,to); + return rename(from, to); }); - await retireLegacyFile(id,slot,{outcome:'17',time}); + await retireLegacyFile(id, slot, { outcome: '17', time }); hook.mock.restore(); - const [capture]=await retiringExits(); - assert.equal(path.dirname(capture.file),path.join(spool,'.reclaim')); - assert.equal((await readExit(id,capture.file)).code,42); - await retireLegacyFile(id,capture.file,{outcome:'42',time:time+1}); - assert.deepEqual(await retiringExits(),[]); + const [capture] = await retiringExits(); + assert.equal(path.dirname(capture.file), path.join(spool, '.reclaim')); + assert.equal((await readExit(id, capture.file)).code, 42); + await retireLegacyFile(id, capture.file, { outcome: '42', time: time + 1 }); + assert.deepEqual(await retiringExits(), []); }); -test('an unbound receipt cannot become disposable after an unreadable source changes during capture',async t => { - const {receiptPath,retireLegacyFile,retiringExits,history} = await journalFixture(t); - const id='blind-capture', file=receiptPath(id); - await fs.mkdir(path.dirname(file),{recursive:true}); - await fs.writeFile(file,'damaged'); - const bytes = JSON.stringify({code:17,signal:null,time:Date.now()}); +test('an unbound receipt cannot become disposable after an unreadable source changes during capture', async (t) => { + const { receiptPath, retireLegacyFile, retiringExits, history } = + await journalFixture(t); + const id = 'blind-capture', + file = receiptPath(id); + await fs.mkdir(path.dirname(file), { recursive: true }); + await fs.writeFile(file, 'damaged'); + const bytes = JSON.stringify({ code: 17, signal: null, time: Date.now() }); const rename = fs.rename.bind(fs); - const hook=t.mock.method(fs,'rename',async (from,to) => { - await fs.writeFile(file+'.restored',bytes); - await rename(file+'.restored',file); - await rename(from,to); + const hook = t.mock.method(fs, 'rename', async (from, to) => { + await fs.writeFile(file + '.restored', bytes); + await rename(file + '.restored', file); + await rename(from, to); }); - await retireLegacyFile(id,file); + await retireLegacyFile(id, file); hook.mock.restore(); await history.interrupt('http'); await history.retryPendingExits(); - const [copy]=await retiringExits(); - assert.equal(await fs.readFile(copy.file,'utf8'),bytes); + const [copy] = await retiringExits(); + assert.equal(await fs.readFile(copy.file, 'utf8'), bytes); }); for (const fault of ['rename', 'directory-sync', 'unlink']) { test( - 'two collectors with a replaced private receipt recover after ENOSPC at ' + fault, + 'two collectors with a replaced private receipt recover after ENOSPC at ' + + fault, { timeout: 20000 }, async (t) => { - const { db, history, receiptPath, retireLegacyFile, retiringExits, readExit, stats } = - await journalFixture(t); + const { + db, + history, + receiptPath, + retireLegacyFile, + retiringExits, + readExit, + stats, + } = await journalFixture(t); const retained = fault === 'unlink'; const id = 'capacity-slot', today = require('dayjs')().startOf('day'); - const old = retained ? today.valueOf() + 2000 : today.subtract(4, 'day').valueOf(), + const old = retained + ? today.valueOf() + 2000 + : today.subtract(4, 'day').valueOf(), late = today.valueOf() + 2200; const policy = new (load('back/services/retention.ts', { '../data': { sequelize: db }, @@ -5293,7 +9187,11 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { '../data/system': {}, '../config': {}, }).default)(); - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); for (const [key, code, end] of [ [id, 17, old], ['sibling', 0, late], @@ -5305,14 +9203,19 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { await history.complete(key, 'unknown', null, null); } await clean(); - assert.equal((await history.visibleTriggers(1, [id])).length, Number(retained)); + assert.equal( + (await history.visibleTriggers(1, [id])).length, + Number(retained), + ); if (!retained) { // A late confirmation preserves the tuple after pruning. writeSingleFileExit(id, 17, null, old); await history.complete(id, 'unknown', null, null); } const file = receiptPath(id), - claim = await fs.mkdtemp(path.join(path.dirname(file), '.claim.' + id + '.')); + claim = await fs.mkdtemp( + path.join(path.dirname(file), '.claim.' + id + '.'), + ); const slot = path.join(claim, 'receipt'); writeSingleFileExit(id, 17, null, old); const rename = fs.rename.bind(fs); @@ -5320,7 +9223,8 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { writeSingleFileExit(id, 42, null, late); const staged = path.join(claim, 'third-party'); await rename(file, staged); - const full = () => Object.assign(Error('capacity exhausted'), { code: 'ENOSPC' }); + const full = () => + Object.assign(Error('capacity exhausted'), { code: 'ENOSPC' }); const collectors = [barrier(), barrier()]; const finalUnlink = barrier(); let entered = 0, @@ -5351,7 +9255,9 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { return sync(fd); }); const workers = Promise.allSettled( - [0, 1].map(() => retireLegacyFile(id, slot, { outcome: '17', time: old })) + [0, 1].map(() => + retireLegacyFile(id, slot, { outcome: '17', time: old }), + ), ); await Promise.all(collectors.map((gate) => gate.entered)); if (fault === 'unlink') { @@ -5367,19 +9273,34 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { syncing.mock.restore(); assert.equal(failures, fault === 'rename' ? 2 : 1); assert.deepEqual( - results.filter((r) => r.status === 'rejected').map((r) => r.reason.code), - Array(failures).fill('ENOSPC') + results + .filter((r) => r.status === 'rejected') + .map((r) => r.reason.code), + Array(failures).fill('ENOSPC'), + ); + const survivors = await Promise.all( + (await retiringExits()).map((row) => readExit(row.id, row.file)), + ); + assert.equal( + survivors.filter((r) => r?.code === 42 && r.time === late).length, + 1, ); - const survivors = await Promise.all((await retiringExits()).map((row) => readExit(row.id, row.file))); - assert.equal(survivors.filter((r) => r?.code === 42 && r.time === late).length, 1); // Only the old tuple is redelivered. The replacement must be found on disk. - if (fault === 'directory-sync') writeSingleFileExit('sibling', 0, null, late); - await Promise.all([publishFromPeer(id, 17, old), publishFromPeer(id, 17, old)]); - await Promise.all([new TriggerHistory(db).interrupt('http'), history.retryPendingExits(), clean()]); + if (fault === 'directory-sync') + writeSingleFileExit('sibling', 0, null, late); + await Promise.all([ + publishFromPeer(id, 17, old), + publishFromPeer(id, 17, old), + ]); + await Promise.all([ + new TriggerHistory(db).interrupt('http'), + history.retryPendingExits(), + clean(), + ]); await new TriggerHistory(db).retryPendingExits(); const conflicts = await db.query( 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - { bind: { id }, type: QueryTypes.SELECT } + { bind: { id }, type: QueryTypes.SELECT }, ); assert.deepEqual(conflicts, [ { outcome: '17', finished_at: old }, @@ -5388,20 +9309,23 @@ for (const fault of ['rename', 'directory-sync', 'unlink']) { const visible = await history.visibleTriggers(1, [id]); assert.deepEqual( visible.map((row) => [row.state, row.reason, row.exit_code]), - retained ? [['unknown', 'exit_conflict', null]] : [] + retained ? [['unknown', 'exit_conflict', null]] : [], ); const [sibling] = await history.visibleTriggers(1, ['sibling']); - assert.deepEqual([sibling.state, sibling.exit_code, sibling.finished_at], ['finished', 0, late]); + assert.deepEqual( + [sibling.state, sibling.exit_code, sibling.finished_at], + ['finished', 0, late], + ); const ledger = await stats.CrontabStatModel.findAll(); assert.deepEqual( ledger.map((r) => [r.date, r.run_count, r.success_count, r.fail_count]), - [[today.format('YYYY-MM-DD'), 1, 1, 0]] + [[today.format('YYYY-MM-DD'), 1, 1, 0]], ); - } + }, ); } -test('polling a restored canonical exit after an evidence-free restart isolates other unknown instances', async t => { +test('polling a restored canonical exit after an evidence-free restart isolates other unknown instances', async (t) => { const { db, history, stats } = await journalFixture(t); const end = Date.now() - 20; const ids = ['restored-after-startup', 'no-durable-exit']; @@ -5410,73 +9334,129 @@ test('polling a restored canonical exit after an evidence-free restart isolates await history.start(id, end - 1000, true); } await history.interrupt('http'); - const results = async () => (await history.visibleTriggers(1, ids)) - .sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) - .map(row => [row.state, row.exit_code, row.finished_at]); - assert.deepEqual(await results(), [['unknown', null, null], ['unknown', null, null]]); + const results = async () => + (await history.visibleTriggers(1, ids)) + .sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) + .map((row) => [row.state, row.exit_code, row.finished_at]); + assert.deepEqual(await results(), [ + ['unknown', null, null], + ['unknown', null, null], + ]); writeSingleFileExit(ids[0], 29, null, end); - await Promise.all([history.retryPendingExits(), new TriggerHistory(db).retryPendingExits()]); - assert.deepEqual(await results(), [['failed', 29, end], ['unknown', null, null]]); + await Promise.all([ + history.retryPendingExits(), + new TriggerHistory(db).retryPendingExits(), + ]); + assert.deepEqual(await results(), [ + ['failed', 29, end], + ['unknown', null, null], + ]); await new TriggerHistory(db).interrupt('http'); await history.retryPendingExits(); const [day] = await stats.CrontabStatModel.findAll(); - assert.deepEqual([day.run_count, day.success_count, day.fail_count], [1, 0, 1]); + assert.deepEqual( + [day.run_count, day.success_count, day.fail_count], + [1, 0, 1], + ); }); -test('first receipt creation fails before power loss and replay of a pruned sibling cannot book that run', async t => { - const { db, history, receiptPath, readExit, writeExit, stats } = await journalFixture(t); +test('first receipt creation fails before power loss and replay of a pruned sibling cannot book that run', async (t) => { + const { db, history, receiptPath, readExit, writeExit, stats } = + await journalFixture(t); const day = require('dayjs')().startOf('day'); const end = day.valueOf() + 1500; const expired = day.subtract(4, 'day').valueOf(); - const old = 'expired-execution', saved = 'last-free-inode', missing = 'no-free-inode'; - for (const [id, time] of [[old, expired], [saved, end], [missing, end]]) { + const old = 'expired-execution', + saved = 'last-free-inode', + missing = 'no-free-inode'; + for (const [id, time] of [ + [old, expired], + [saved, end], + [missing, end], + ]) { await history.enqueue(id, 1, 'manual', null, time - 2000); await history.start(id, time - 2000, true); } writeSingleFileExit(old, 0, null, expired); await history.complete(old, 'unknown', null, null); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); await clean(); const sync = require('node:fs'); const full = t.mock.method(sync, 'statfsSync', () => ({ bavail: 0 })); writeExit(saved, 29, null, end); full.mock.restore(); - const noInode = t.mock.method(sync, 'writeFileSync', file => { + const noInode = t.mock.method(sync, 'writeFileSync', (file) => { assert.ok(path.basename(file).startsWith('.pending.' + missing + '.full-')); throw Object.assign(Error('no free inode'), { code: 'ENOSPC' }); }); assert.throws(() => writeExit(missing, 0, null, end), { code: 'ENOSPC' }); noInode.mock.restore(); assert.equal(await readExit(missing), undefined); - assert.deepEqual((await fs.readdir(path.dirname(receiptPath(missing)))).filter(file => file.includes(missing)), []); + assert.deepEqual( + (await fs.readdir(path.dirname(receiptPath(missing)))).filter((file) => + file.includes(missing), + ), + [], + ); await new TriggerHistory(db).interrupt('http'); - await Promise.all([publishFromPeer(old, 0, expired), publishFromPeer(old, 0, expired), clean()]); + await Promise.all([ + publishFromPeer(old, 0, expired), + publishFromPeer(old, 0, expired), + clean(), + ]); await new TriggerHistory(db).interrupt('http'); const [unknown] = await history.visibleTriggers(1, [missing]); - assert.deepEqual([unknown.state, unknown.exit_code, unknown.finished_at], ['unknown', null, null]); + assert.deepEqual( + [unknown.state, unknown.exit_code, unknown.finished_at], + ['unknown', null, null], + ); const [recovered] = await history.visibleTriggers(1, [saved]); - assert.deepEqual([recovered.state, recovered.exit_code, recovered.finished_at], ['failed', 29, end]); + assert.deepEqual( + [recovered.state, recovered.exit_code, recovered.finished_at], + ['failed', 29, end], + ); assert.deepEqual(await history.visibleTriggers(1, [old]), []); const ledger = await stats.CrontabStatModel.findAll(); - assert.deepEqual(ledger.map(r => [r.date, r.run_count, r.fail_count]), [[day.format('YYYY-MM-DD'), 1, 1]]); + assert.deepEqual( + ledger.map((r) => [r.date, r.run_count, r.fail_count]), + [[day.format('YYYY-MM-DD'), 1, 1]], + ); }); -test('cleanup racing the return of a canonical receipt books its retained day even after both histories expire', async t => { +test('cleanup racing the return of a canonical receipt books its retained day even after both histories expire', async (t) => { const { db, history, stats } = await journalFixture(t); const today = require('dayjs')().startOf('day'); const end = today.subtract(2, 'day').valueOf() + 10000; const older = today.subtract(9, 'day').valueOf(); const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, }).default)(); - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 4 }); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 4, + }); const ids = ['late-canonical', 'lost-at-syscall', 'expired-replay']; for (const id of ids) { const start = id === ids[2] ? older : end - 2000; @@ -5487,31 +9467,47 @@ test('cleanup racing the return of a canonical receipt books its retained day ev await history.complete(ids[2], 'unknown', null, null); await history.interrupt('http'); // A later cleanup runs after the two restart observations have aged out. - await db.query("UPDATE CronTriggers SET finished_at=$observed WHERE state='unknown' AND reason='restart'", - { bind: { observed: end + 100 } }); + await db.query( + "UPDATE CronTriggers SET finished_at=$observed WHERE state='unknown' AND reason='restart'", + { bind: { observed: end + 100 } }, + ); await clean(); assert.deepEqual(await history.visibleTriggers(1, ids), []); assert.equal(await stats.CrontabStatModel.count(), 0); writeSingleFileExit(ids[0], 29, null, end); - await Promise.all([history.retryPendingExits(), clean(), publishFromPeer(ids[2], 0, older + 500)]); + await Promise.all([ + history.retryPendingExits(), + clean(), + publishFromPeer(ids[2], 0, older + 500), + ]); await new TriggerHistory(db).interrupt('http'); await publishFromPeer(ids[0], 29, end); const ledger = await stats.CrontabStatModel.findAll(); - assert.deepEqual(ledger.map(r => [r.date, r.run_count, r.fail_count, r.total_time]), - [[today.subtract(2, 'day').format('YYYY-MM-DD'), 1, 1, 2000]]); + assert.deepEqual( + ledger.map((r) => [r.date, r.run_count, r.fail_count, r.total_time]), + [[today.subtract(2, 'day').format('YYYY-MM-DD'), 1, 1, 2000]], + ); assert.deepEqual(await history.visibleTriggers(1, ids), []); - const bindings = () => db.query('SELECT trigger_id FROM CronPrunedUnknownRuns', { type: QueryTypes.SELECT }); + const bindings = () => + db.query('SELECT trigger_id FROM CronPrunedUnknownRuns', { + type: QueryTypes.SELECT, + }); assert.deepEqual(await bindings(), [{ trigger_id: ids[1] }]); - await policy.cleanup({ runningInstanceRetentionDays: 0, cronStatRetentionDays: 1 }); + await policy.cleanup({ + runningInstanceRetentionDays: 0, + cronStatRetentionDays: 1, + }); assert.deepEqual(await bindings(), []); await publishFromPeer(ids[0], 29, end); assert.equal(await stats.CrontabStatModel.count(), 0); }); -test('pruned unknown settlement rolls back with its booking and a later conflict withdraws only that contribution', async t => { +test('pruned unknown settlement rolls back with its booking and a later conflict withdraws only that contribution', async (t) => { const { db, history, stats, readExit } = await journalFixture(t); - const start = Date.now() - 4000, end = start + 1000; - const id = 'pruned-and-restored', sibling = 'already-booked-sibling'; + const start = Date.now() - 4000, + end = start + 1000; + const id = 'pruned-and-restored', + sibling = 'already-booked-sibling'; for (const key of [id, sibling]) { await history.enqueue(key, 1, 'manual', null, start); await history.start(key, start, true); @@ -5519,99 +9515,178 @@ test('pruned unknown settlement rolls back with its booking and a later conflict writeSingleFileExit(sibling, 0, null, end); await history.complete(sibling, 'unknown', null, null); await history.interrupt('http'); - await db.transaction(tx => history.deleteExpired(Date.now() + 10, tx)); + await db.transaction((tx) => history.deleteExpired(Date.now() + 10, tx)); writeSingleFileExit(id, 31, null, end); await db.query(`CREATE TRIGGER block_new_booking BEFORE INSERT ON CronLegacyExitBookings WHEN NEW.trigger_id='pruned-and-restored' BEGIN SELECT RAISE(ABORT, 'booking unavailable'); END`); - await assert.rejects(history.retryPendingExits(), error => /booking unavailable/.test(error.original?.message)); + await assert.rejects(history.retryPendingExits(), (error) => + /booking unavailable/.test(error.original?.message), + ); assert.equal((await readExit(id)).code, 31); - const daily = async () => (await stats.CrontabStatModel.findAll()).map(row => - [row.run_count, row.success_count, row.fail_count, row.total_time]); + const daily = async () => + (await stats.CrontabStatModel.findAll()).map((row) => [ + row.run_count, + row.success_count, + row.fail_count, + row.total_time, + ]); assert.deepEqual(await daily(), [[1, 1, 0, 1000]]); await db.query('DROP TRIGGER block_new_booking'); await new TriggerHistory(db).interrupt('http'); assert.deepEqual(await daily(), [[2, 1, 1, 2000]]); - await Promise.all([publishFromPeer(id, 0, end + 1), publishFromPeer(id, 31, end)]); + await Promise.all([ + publishFromPeer(id, 0, end + 1), + publishFromPeer(id, 31, end), + ]); await new TriggerHistory(db).interrupt('http'); await history.retryPendingExits(); assert.deepEqual(await daily(), [[1, 1, 0, 1000]]); assert.deepEqual(await history.visibleTriggers(1, [id, sibling]), []); - assert.deepEqual(await db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', - { bind: { id }, type: QueryTypes.SELECT }), [{outcome:'31', finished_at:end}, {outcome:'0', finished_at:end + 1}]); + assert.deepEqual( + await db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at', + { bind: { id }, type: QueryTypes.SELECT }, + ), + [ + { outcome: '31', finished_at: end }, + { outcome: '0', finished_at: end + 1 }, + ], + ); }); for (const cleanupFirst of [true, false]) { - test('committed pruned booking survives power loss and a conflicting replay with daily cleanup ' + - (cleanupFirst ? 'first' : 'last'), async t => { - const { db, history, stats, receiptPath, readExit } = await journalFixture(t); - const today = require('dayjs')().startOf('day'); - const end = today.subtract(2, 'day').valueOf() + 5000; - const other = today.valueOf() + 1000; - const id = 'late-at-commit', sameDay = 'same-day-peer', keep = 'later-peer'; - const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, - }).default)(); - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 0, cronStatRetentionDays: 1 }); - const start = end - 2000; - for (const key of [id, sameDay, keep]) { - await history.enqueue(key, 1, 'manual', null, start); - await history.start(key, start, true); - if (key !== id) { - writeSingleFileExit(key, 0, null, key === keep ? other : end - 500); - await history.complete(key, 'unknown', null, null); + test( + 'committed pruned booking survives power loss and a conflicting replay with daily cleanup ' + + (cleanupFirst ? 'first' : 'last'), + async (t) => { + const { db, history, stats, receiptPath, readExit } = + await journalFixture(t); + const today = require('dayjs')().startOf('day'); + const end = today.subtract(2, 'day').valueOf() + 5000; + const other = today.valueOf() + 1000; + const id = 'late-at-commit', + sameDay = 'same-day-peer', + keep = 'later-peer'; + const policy = new (load('back/services/retention.ts', { + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, + }).default)(); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 0, + cronStatRetentionDays: 1, + }); + const start = end - 2000; + for (const key of [id, sameDay, keep]) { + await history.enqueue(key, 1, 'manual', null, start); + await history.start(key, start, true); + if (key !== id) { + writeSingleFileExit(key, 0, null, key === keep ? other : end - 500); + await history.complete(key, 'unknown', null, null); + } } - } - await history.interrupt('http'); - await db.transaction(tx => history.deleteExpired(Math.max(Date.now(), other) + 10000, tx)); - writeSingleFileExit(id, 31, null, end); - // A separate connection sees the commit, but the original file has not - // been reclaimed when power is lost. The real VM also exercises this cut. - await db.transaction(async tx => { - t.mock.method(tx, 'afterCommit', () => {}); - await history.replayPublishedExits(tx); - }); - assert.equal((await readExit(id)).code, 31); - const totals = async () => (await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] })) - .map(row => [row.date, row.run_count, row.success_count, row.fail_count, row.total_time, row.max_time]); - const oldDay = today.subtract(2, 'day').format('YYYY-MM-DD'); - const retained = [today.format('YYYY-MM-DD'), 1, 1, 0, other - start, other - start]; - assert.deepEqual(await totals(), [[oldDay, 2, 1, 1, 3500, 2000], retained]); - assert.deepEqual(await db.query('SELECT outcome,finished_at FROM CronUnmatchedBoundExits WHERE trigger_id=$id', - { bind: { id }, type: QueryTypes.SELECT }), [{outcome: '31', finished_at: end}]); - // A previous panel can leave a committed booking and the canonical file - // as the only witnesses. Resume on that database and drain the duplicate. - if (cleanupFirst) await db.query('DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', { bind: { id } }); - const boot = new TriggerHistory(db); - await boot.interrupt('http'); - await assert.rejects(fs.access(receiptPath(id)), { code: 'ENOENT' }); - if (cleanupFirst) await clean(); - const conflictCode = cleanupFirst ? 31 : 0; - const conflictEnd = cleanupFirst ? other : end; - writeSingleFileExit(id, conflictCode, null, conflictEnd); - await boot.retryPendingExits(); - const conflicts = () => db.query('SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at,outcome', - { bind: { id }, type: QueryTypes.SELECT }); - const original = {outcome: '31', finished_at: end}; - const changed = {outcome: String(conflictCode), finished_at: conflictEnd}; - const expected = cleanupFirst ? [original, changed] : [changed, original]; - assert.deepEqual(await conflicts(), expected); - if (!cleanupFirst) { - assert.deepEqual(await totals(), [[oldDay, 1, 1, 0, 1500, 1500], retained]); - await clean(); - } - await Promise.all([clean(), publishFromPeer(id, 31, end), publishFromPeer(id, conflictCode, conflictEnd)]); - await new TriggerHistory(db).interrupt('http'); - assert.deepEqual(await conflicts(), expected); - assert.deepEqual(await totals(), [retained]); - assert.deepEqual(await boot.visibleTriggers(1, [id, sameDay, keep]), []); - }); + await history.interrupt('http'); + await db.transaction((tx) => + history.deleteExpired(Math.max(Date.now(), other) + 10000, tx), + ); + writeSingleFileExit(id, 31, null, end); + // A separate connection sees the commit, but the original file has not + // been reclaimed when power is lost. The real VM also exercises this cut. + await db.transaction(async (tx) => { + t.mock.method(tx, 'afterCommit', () => {}); + await history.replayPublishedExits(tx); + }); + assert.equal((await readExit(id)).code, 31); + const totals = async () => + ( + await stats.CrontabStatModel.findAll({ order: [['date', 'ASC']] }) + ).map((row) => [ + row.date, + row.run_count, + row.success_count, + row.fail_count, + row.total_time, + row.max_time, + ]); + const oldDay = today.subtract(2, 'day').format('YYYY-MM-DD'); + const retained = [ + today.format('YYYY-MM-DD'), + 1, + 1, + 0, + other - start, + other - start, + ]; + assert.deepEqual(await totals(), [ + [oldDay, 2, 1, 1, 3500, 2000], + retained, + ]); + assert.deepEqual( + await db.query( + 'SELECT outcome,finished_at FROM CronUnmatchedBoundExits WHERE trigger_id=$id', + { bind: { id }, type: QueryTypes.SELECT }, + ), + [{ outcome: '31', finished_at: end }], + ); + // A previous panel can leave a committed booking and the canonical file + // as the only witnesses. Resume on that database and drain the duplicate. + if (cleanupFirst) + await db.query( + 'DELETE FROM CronUnmatchedBoundExits WHERE trigger_id=$id', + { bind: { id } }, + ); + const boot = new TriggerHistory(db); + await boot.interrupt('http'); + await assert.rejects(fs.access(receiptPath(id)), { code: 'ENOENT' }); + if (cleanupFirst) await clean(); + const conflictCode = cleanupFirst ? 31 : 0; + const conflictEnd = cleanupFirst ? other : end; + writeSingleFileExit(id, conflictCode, null, conflictEnd); + await boot.retryPendingExits(); + const conflicts = () => + db.query( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id ORDER BY finished_at,outcome', + { bind: { id }, type: QueryTypes.SELECT }, + ); + const original = { outcome: '31', finished_at: end }; + const changed = { + outcome: String(conflictCode), + finished_at: conflictEnd, + }; + const expected = cleanupFirst ? [original, changed] : [changed, original]; + assert.deepEqual(await conflicts(), expected); + if (!cleanupFirst) { + assert.deepEqual(await totals(), [ + [oldDay, 1, 1, 0, 1500, 1500], + retained, + ]); + await clean(); + } + await Promise.all([ + clean(), + publishFromPeer(id, 31, end), + publishFromPeer(id, conflictCode, conflictEnd), + ]); + await new TriggerHistory(db).interrupt('http'); + assert.deepEqual(await conflicts(), expected); + assert.deepEqual(await totals(), [retained]); + assert.deepEqual(await boot.visibleTriggers(1, [id, sameDay, keep]), []); + }, + ); } -test('registered plans distinguish absent, skipped, queued, confirmed command starts and late recovery', async t => { +test('registered plans distinguish absent, skipped, queued, confirmed command starts and late recovery', async (t) => { const { db, history } = await fixture(t); - const { saveSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit'); + const { + saveSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); const start = new Date(2026, 0, 12, 8).getTime(); const rule = '* * * * * *'; const task = { id: '1', schedule: rule }; @@ -5619,132 +9694,267 @@ test('registered plans distinguish absent, skipped, queued, confirmed command st assert.equal(await audit(), null); await saveSchedulePlan(db, { crons: [task], replace: true }, start); let a = await audit(); - assert.deepEqual([a.expected,a.missing,a.onTime,a.dispatched], [5,5,0,0]); - const id = n => slotId('1', 0, rule, start + n*1000); - const enqueue = n => history.enqueue(id(n), 1, 'node', start+n*1000, start+n*1000+10); - for (const n of [2,3,4,5]) await enqueue(n); - await history.finish(id(2), 'skipped','pending',null); - await history.start(id(4),start+4010,true); - await history.recordCommandStart(id(4),start+4200); - await history.recordCommandStart(id(4),start+4800); - await history.start(id(5),start+5010,true); - await history.finish(id(5),'failed','spawn',127); - await history.enqueue('manual',1,'manual',null,start+100); - await history.enqueue('wrong-rule',1,'node',start+1000,start+1000); + assert.deepEqual( + [a.expected, a.missing, a.onTime, a.dispatched], + [5, 5, 0, 0], + ); + const id = (n) => slotId('1', 0, rule, start + n * 1000); + const enqueue = (n) => + history.enqueue(id(n), 1, 'node', start + n * 1000, start + n * 1000 + 10); + for (const n of [2, 3, 4, 5]) await enqueue(n); + await history.finish(id(2), 'skipped', 'pending', null); + await history.start(id(4), start + 4010, true); + await history.recordCommandStart(id(4), start + 4200); + await history.recordCommandStart(id(4), start + 4800); + await history.start(id(5), start + 5010, true); + await history.finish(id(5), 'failed', 'spawn', 127); + await history.enqueue('manual', 1, 'manual', null, start + 100); + await history.enqueue('wrong-rule', 1, 'node', start + 1000, start + 1000); a = await audit(); - assert.deepEqual([a.expected,a.observed,a.missing,a.skipped,a.queued,a.dispatched,a.unconfirmed,a.onTime], - [5,4,1,1,1,1,1,4]); - assert.deepEqual([a.commandStartP95,a.scriptStartP95,a.scriptSamples], [200,null,0]); - await history.enqueue(id(1),1,'recovery',start+1000,start+9200); + assert.deepEqual( + [ + a.expected, + a.observed, + a.missing, + a.skipped, + a.queued, + a.dispatched, + a.unconfirmed, + a.onTime, + ], + [5, 4, 1, 1, 1, 1, 1, 4], + ); + assert.deepEqual( + [a.commandStartP95, a.scriptStartP95, a.scriptSamples], + [200, null, 0], + ); + await history.enqueue(id(1), 1, 'recovery', start + 1000, start + 9200); a = await audit(); - assert.deepEqual([a.expected,a.observed,a.missing,a.onTime,a.triggerDeviationP95], [5,5,0,4,8200]); + assert.deepEqual( + [a.expected, a.observed, a.missing, a.onTime, a.triggerDeviationP95], + [5, 5, 0, 4, 8200], + ); // A verified exit proves launch after losing the timing pipe, without adding a duration sample. - await db.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound) - VALUES($id,1,'node',$start,$end,'127','2026-01-12',1)`,{bind:{id:id(5),start:start+5010,end:start+9000}}); + await db.query( + `INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound) + VALUES($id,1,'node',$start,$end,'127','2026-01-12',1)`, + { bind: { id: id(5), start: start + 5010, end: start + 9000 } }, + ); a = await audit(); - assert.deepEqual([a.dispatched,a.commandSamples,a.unconfirmed,a.commandStartP95], [2,1,0,200]); + assert.deepEqual( + [a.dispatched, a.commandSamples, a.unconfirmed, a.commandStartP95], + [2, 1, 0, 200], + ); // A new connection after restart must see the original plan, even if no timer ran. - const reopened = new Sequelize({dialect:'sqlite',storage:db.options.storage,logging:false}); - try { assert.deepEqual(await auditSchedule(reopened,start,start+10000),a); } - finally { await reopened.close(); } -}); - -test('plan revisions preserve prior slots, duplicate rules and a cross-midnight late receipt', async t => { - const { db, history } = await fixture(t); - const { saveSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit'); - const day = new Date(2026, 0, 13).getTime(); - const rule = '* * * * * *', task = {id:'2',schedule:rule,extra_schedules:[{schedule:rule}]}; - const save = (change, at) => saveSchedulePlan(db, change, day+at); - await save({crons:[task],replace:true},-1800); - await save({crons:[task],replace:true},300); - await history.enqueue(slotId('2',1,rule,day),2,'node',day,day+100); - await history.enqueue(slotId('2',0,rule,day-1000),2,'recovery',day-1000,day+500); - await save({crons:[{id:'2',schedule:'*/2 * * * * *'}],replace:false},1500); - await save({ids:['2']},2600); - await save({crons:[],replace:true},7500); - const a = await auditSchedule(db,day,day+16000); - // Two rules at midnight and at second 1, one edited rule at second 2. - assert.deepEqual([a.expected,a.observed,a.missing,a.onTime], [5,1,4,1]); - assert.equal((await db.query('SELECT * FROM CronPlanRules',{type:QueryTypes.SELECT})).length,3); -}); - -test('bounded audit calendars agree with scheduled slots at minute and day boundaries', () => { - const base = new Date(2026,0,11,23,59,50,950).getTime(); - for (const rule of ['*/2 * * * * *','2,7,59 * * * * *','0 * * * *','*/13 * * 12 * MON']) { - const reference = upcomingSlots(rule,base,33); - const last = reference[31]; - assert.deepEqual(upcomingSlots(rule,base,Infinity,last), reference.slice(0,32)); + const reopened = new Sequelize({ + dialect: 'sqlite', + storage: db.options.storage, + logging: false, + }); + try { + assert.deepEqual(await auditSchedule(reopened, start, start + 10000), a); + } finally { + await reopened.close(); } }); -test('scheduler registration acknowledges durable plans and serializes invalid edits, publication failures and deletes', async t => { +test('plan revisions preserve prior slots, duplicate rules and a cross-midnight late receipt', async (t) => { + const { db, history } = await fixture(t); + const { + saveSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); + const day = new Date(2026, 0, 13).getTime(); + const rule = '* * * * * *', + task = { id: '2', schedule: rule, extra_schedules: [{ schedule: rule }] }; + const save = (change, at) => saveSchedulePlan(db, change, day + at); + await save({ crons: [task], replace: true }, -1800); + await save({ crons: [task], replace: true }, 300); + await history.enqueue(slotId('2', 1, rule, day), 2, 'node', day, day + 100); + await history.enqueue( + slotId('2', 0, rule, day - 1000), + 2, + 'recovery', + day - 1000, + day + 500, + ); + await save( + { crons: [{ id: '2', schedule: '*/2 * * * * *' }], replace: false }, + 1500, + ); + await save({ ids: ['2'] }, 2600); + await save({ crons: [], replace: true }, 7500); + const a = await auditSchedule(db, day, day + 16000); + // Two rules at midnight and at second 1, one edited rule at second 2. + assert.deepEqual([a.expected, a.observed, a.missing, a.onTime], [5, 1, 4, 1]); + assert.equal( + (await db.query('SELECT * FROM CronPlanRules', { type: QueryTypes.SELECT })) + .length, + 3, + ); +}); + +test('bounded audit calendars agree with scheduled slots at minute and day boundaries', () => { + const base = new Date(2026, 0, 11, 23, 59, 50, 950).getTime(); + for (const rule of [ + '*/2 * * * * *', + '2,7,59 * * * * *', + '0 * * * *', + '*/13 * * 12 * MON', + ]) { + const reference = upcomingSlots(rule, base, 33); + const last = reference[31]; + assert.deepEqual( + upcomingSlots(rule, base, Infinity, last), + reference.slice(0, 32), + ); + } +}); + +test('scheduler registration acknowledges durable plans and serializes invalid edits, publication failures and deletes', async (t) => { const { db } = await fixture(t); const scheduleStacks = new Map(); - const mocks = {'./data': {scheduleStacks}, '../loaders/logger': logger, '../shared/runCron': {runCron() {}}}; - const { registeredAdd, registeredDelete } = load('back/schedule/registeredPlans.ts', { - '../data': {sequelize: db}, './addCron': load('back/schedule/addCron.ts', mocks), - './delCron': load('back/schedule/delCron.ts', mocks), + const mocks = { + './data': { scheduleStacks }, + '../loaders/logger': logger, + '../cron/execution/runCron': { runCron() {} }, + }; + const { registeredAdd, registeredDelete } = load( + 'back/schedule/registeredPlans.ts', + { + '../data': { sequelize: db }, + './addCron': load('back/schedule/addCron.ts', mocks), + './delCron': load('back/schedule/delCron.ts', mocks), + }, + ); + const apply = (request, handler = registeredAdd) => + new Promise((resolve, reject) => { + handler({ request }, (error) => (error ? reject(error) : resolve())); + }); + const id = '757575', + rule = '0 0 1 * *'; + const add = (schedule) => ({ + crons: [{ id, schedule, command: 'true' }], + replace: false, }); - const apply = (request, handler=registeredAdd) => new Promise((resolve,reject) => { - handler({request}, error => error ? reject(error) : resolve()); + t.after(() => { + scheduleStacks.get(id)?.forEach((job) => job.cancel()); + scheduleStacks.delete(id); + }); + await apply({ crons: [], replace: true }); + await apply({ + replace: false, + crons: [ + { id, schedule: '10 0 1 * *', command: 'true' }, + ...add(rule).crons, + ], }); - const id = '757575', rule = '0 0 1 * *'; - const add = schedule => ({crons:[{id,schedule,command:'true'}],replace:false}); - t.after(() => { scheduleStacks.get(id)?.forEach(job => job.cancel()); scheduleStacks.delete(id); }); - await apply({crons:[],replace:true}); - await apply({replace:false, crons:[{id,schedule:'10 0 1 * *',command:'true'}, ...add(rule).crons]}); const original = scheduleStacks.get(id); assert.ok(original?.length); - const active = () => db.query('SELECT schedule FROM CronPlanRules WHERE until IS NULL',{type:QueryTypes.SELECT}); + const active = () => + db.query('SELECT schedule FROM CronPlanRules WHERE until IS NULL', { + type: QueryTypes.SELECT, + }); await assert.rejects(apply(add('impossible ! !'))); - await db.query("CREATE TRIGGER reject_new_rule BEFORE INSERT ON CronPlanRules BEGIN SELECT RAISE(ABORT,'injected'); END"); - await assert.rejects(apply(add('10 0 1 * *')), err => err.original?.message.includes('injected')); - assert.equal(scheduleStacks.get(id),original); - assert.deepEqual(await active(),[{schedule:rule}]); + await db.query( + "CREATE TRIGGER reject_new_rule BEFORE INSERT ON CronPlanRules BEGIN SELECT RAISE(ABORT,'injected'); END", + ); + await assert.rejects(apply(add('10 0 1 * *')), (err) => + err.original?.message.includes('injected'), + ); + assert.equal(scheduleStacks.get(id), original); + assert.deepEqual(await active(), [{ schedule: rule }]); await db.query('DROP TRIGGER reject_new_rule'); - await Promise.all([apply({ids:[id]},registeredDelete),apply(add('10 0 1 * *'))]); - assert.deepEqual(await active(),[{schedule:'10 0 1 * *'}]); - assert.notEqual(scheduleStacks.get(id),original); + await Promise.all([ + apply({ ids: [id] }, registeredDelete), + apply(add('10 0 1 * *')), + ]); + assert.deepEqual(await active(), [{ schedule: '10 0 1 * *' }]); + assert.notEqual(scheduleStacks.get(id), original); }); -test('schedule audit uses the runtime cutover when saving rules crosses a due slot, and keeps a prior day bounded', async t => { +test('schedule audit uses the runtime cutover when saving rules crosses a due slot, and keeps a prior day bounded', async (t) => { const { db, history } = await fixture(t); - const { saveSchedulePlan, confirmSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit'); + const { + saveSchedulePlan, + confirmSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); const midnight = new Date(2026, 0, 13).getTime(); - const rule = '* * * * * *', replacement = '*/2 * * * * *'; - const apply = (schedule, at, token) => saveSchedulePlan(db,{replace:true, crons:[{id:'2', schedule}]},at, token); + const rule = '* * * * * *', + replacement = '*/2 * * * * *'; + const apply = (schedule, at, token) => + saveSchedulePlan( + db, + { replace: true, crons: [{ id: '2', schedule }] }, + at, + token, + ); await apply(rule, midnight - 4001); await apply(replacement, midnight - 2900, 'change'); - await history.enqueue(slotId('2',0,rule,midnight-1000),2,'node',midnight-1000,midnight+350); - await confirmSchedulePlan(db,'change',midnight-500,midnight-490,true); - await history.enqueue(slotId('2',0,replacement,midnight),2,'node',midnight,midnight+150); - const oldDay = await auditSchedule(db, midnight-86400000, midnight+10000); - assert.deepEqual([oldDay.expected,oldDay.observed,oldDay.missing,oldDay.through],[4,1,3,midnight-1]); - const today = await auditSchedule(db,midnight,midnight+10000); - assert.deepEqual([today.expected,today.observed,today.missing,today.partial],[3,1,2,false]); + await history.enqueue( + slotId('2', 0, rule, midnight - 1000), + 2, + 'node', + midnight - 1000, + midnight + 350, + ); + await confirmSchedulePlan(db, 'change', midnight - 500, midnight - 490, true); + await history.enqueue( + slotId('2', 0, replacement, midnight), + 2, + 'node', + midnight, + midnight + 150, + ); + const oldDay = await auditSchedule(db, midnight - 86400000, midnight + 10000); + assert.deepEqual( + [oldDay.expected, oldDay.observed, oldDay.missing, oldDay.through], + [4, 1, 3, midnight - 1], + ); + const today = await auditSchedule(db, midnight, midnight + 10000); + assert.deepEqual( + [today.expected, today.observed, today.missing, today.partial], + [3, 1, 2, false], + ); }); -test('an interrupted timer switch keeps uncertain slots separate across retries and full reconciliation', async t => { - const {db} = await fixture(t); - const {saveSchedulePlan,confirmSchedulePlan,auditSchedule} = require('../../back/shared/scheduleAudit'); - const base = new Date(2026,0,12,8).getTime(), schedule = '* * * * * *'; - const task = id => ({id,schedule}); - await saveSchedulePlan(db,{replace:true,crons:[task('1')]},base); - await saveSchedulePlan(db,{replace:false,crons:[task('2')]},base+100,'unacknowledged'); - const audit = () => auditSchedule(db,base,base+10000); - let a=await audit(); - assert.deepEqual([a.expected,a.missing,a.partial],[5,5,true]); - await saveSchedulePlan(db,{replace:true,crons:[task('1'),task('2')]},base+3400,'restart'); - await confirmSchedulePlan(db,'restart',base+3490,base+3500,true); - await confirmSchedulePlan(db,'restart',base+8490,base+8500,true); - a=await audit(); - assert.deepEqual([a.expected,a.missing,a.partial],[7,7,true]); +test('an interrupted timer switch keeps uncertain slots separate across retries and full reconciliation', async (t) => { + const { db } = await fixture(t); + const { + saveSchedulePlan, + confirmSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); + const base = new Date(2026, 0, 12, 8).getTime(), + schedule = '* * * * * *'; + const task = (id) => ({ id, schedule }); + await saveSchedulePlan(db, { replace: true, crons: [task('1')] }, base); + await saveSchedulePlan( + db, + { replace: false, crons: [task('2')] }, + base + 100, + 'unacknowledged', + ); + const audit = () => auditSchedule(db, base, base + 10000); + let a = await audit(); + assert.deepEqual([a.expected, a.missing, a.partial], [5, 5, true]); + await saveSchedulePlan( + db, + { replace: true, crons: [task('1'), task('2')] }, + base + 3400, + 'restart', + ); + await confirmSchedulePlan(db, 'restart', base + 3490, base + 3500, true); + await confirmSchedulePlan(db, 'restart', base + 8490, base + 8500, true); + a = await audit(); + assert.deepEqual([a.expected, a.missing, a.partial], [7, 7, true]); }); -test('periodic recovery accepts live and late entry samples by trigger ID without changing outcomes or daily counts', async t => { +test('periodic recovery accepts live and late entry samples by trigger ID without changing outcomes or daily counts', async (t) => { const { root, history, stats } = await journalFixture(t); await fs.mkdir(path.join(root, '.tmp')); - const marker = id => path.join(root, '.tmp', 'cron-start-' + id); + const marker = (id) => path.join(root, '.tmp', 'cron-start-' + id); const start = Date.now() - 5000; for (const id of ['live-entry', 'late-entry', 'past-exit']) { await history.enqueue(id, 1, 'manual', null, start); @@ -5756,7 +9966,7 @@ test('periodic recovery accepts live and late entry samples by trigger ID withou await fs.writeFile(marker('late-entry'), 'partial'); await fs.writeFile(marker('live-entry'), String(start + 50)); await fs.writeFile(marker('past-exit'), String(start + 1001)); - const read = async id => (await history.visibleTriggers(1, [id]))[0]; + const read = async (id) => (await history.visibleTriggers(1, [id]))[0]; await history.retryPendingExits(); assert.equal((await read('live-entry')).script_started_at, start + 50); assert.equal((await read('late-entry')).script_started_at, null); @@ -5764,9 +9974,11 @@ test('periodic recovery accepts live and late entry samples by trigger ID withou await fs.writeFile(marker('late-entry'), String(start + 70)); await history.retryPendingExits(); const late = await read('late-entry'); - assert.deepEqual([late.state,late.exit_code,late.finished_at,late.script_started_at], - ['failed',7,start+1000,start+70]); - await assert.rejects(fs.stat(marker('late-entry')), { code:'ENOENT' }); + assert.deepEqual( + [late.state, late.exit_code, late.finished_at, late.script_started_at], + ['failed', 7, start + 1000, start + 70], + ); + await assert.rejects(fs.stat(marker('late-entry')), { code: 'ENOENT' }); await fs.writeFile(marker('late-entry'), String(start + 90)); await history.retryPendingExits(); assert.equal((await read('late-entry')).script_started_at, start + 70); @@ -5776,192 +9988,466 @@ test('periodic recovery accepts live and late entry samples by trigger ID withou assert.equal(stat.fail_count, 1); }); -test('system crond reconciles confirmed minutes separately, preserving duplicates, skips and unidentified receipts', async t => { +test('system crond reconciles confirmed minutes separately, preserving duplicates, skips and unidentified receipts', async (t) => { const { db, history, models } = await fixture(t); - const { stageSystemPlan, confirmSystemPlan, suspendSystemPlan, systemScheduleAudit } = require('../../back/shared/systemScheduleAudit'); - const minute = 60000, start = new Date(2026, 10, 16, 0, 0).getTime(); + const { + stageSystemPlan, + confirmSystemPlan, + suspendSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const minute = 60000, + start = new Date(2026, 10, 16, 0, 0).getTime(); const rule = { id: 1, schedule: '* * * * *', name: 'per minute' }; - await models.CrontabModel.create({ id:1, command:'true', allow_multiple_instances:1 }); + await models.CrontabModel.create({ + id: 1, + command: 'true', + allow_multiple_instances: 1, + }); const first = await stageSystemPlan(db, [rule], start); await confirmSystemPlan(db, first, start + 3); const rows = [ - [1, 'started', 'running', rule.schedule], [1, 'duplicate', 'skipped', rule.schedule], - [2, 'skip', 'skipped', rule.schedule], [3, 'old-format', 'finished', null], + [1, 'started', 'running', rule.schedule], + [1, 'duplicate', 'skipped', rule.schedule], + [2, 'skip', 'skipped', rule.schedule], + [3, 'old-format', 'finished', null], [4, 'late-old-rule', 'finished', rule.schedule], ]; - for (const [offset,id,state,schedule] of rows) { - const at = start + offset*minute+200; - await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,system_rule,observed_at,command_started_at,system_dispatch_at) - VALUES($id,1,'system',$state,$schedule,$at,$launch,$dispatch)`, {bind:{id,state,schedule,at,launch:state==='running'?at:null,dispatch:offset<3?at:null}}); + for (const [offset, id, state, schedule] of rows) { + const at = start + offset * minute + 200; + await db.query( + `INSERT INTO CronTriggers(id,cron_id,source,state,system_rule,observed_at,command_started_at,system_dispatch_at) + VALUES($id,1,'system',$state,$schedule,$at,$launch,$dispatch)`, + { + bind: { + id, + state, + schedule, + at, + launch: state === 'running' ? at : null, + dispatch: offset < 3 ? at : null, + }, + }, + ); } - await stageSystemPlan(db, [], start+3*minute+3000); // install failed or crashed - const switched = await stageSystemPlan(db, [rule], start+5*minute-50); - await confirmSystemPlan(db, switched, start+5*minute+50); - const audit = await systemScheduleAudit(db,start,start+8*minute+6000); - assert.deepEqual([audit.expected,audit.observed,audit.missing,audit.dispatched,audit.actualStarts,audit.skipped,audit.duplicates,audit.unmatched], - [4,2,1,1,1,1,1,2]); - assert.equal(audit.actualSkips,2); - assert.deepEqual(audit.recent.filter(r => r.triggerCount).map(r => [r.triggerCount,r.startCount,r.skipCount]), [[1,0,1],[2,1,1]]); - assert.equal(audit.partial,true); - assert.deepEqual(audit.recent.map(r => [r.time-start,r.status]),[[8*minute,'awaiting'],[7*minute,'missing'],[6*minute,'switch'],[5*minute,'switch'],[4*minute,'switch'],[3*minute,'switch'],[2*minute,'skipped'],[minute,'started'],[0,'switch']]); - await db.query("UPDATE CronTriggers SET script_started_at=observed_at+1 WHERE id='old-format'"); - const withLegacy = await systemScheduleAudit(db,start,start+8*minute+6000); - assert.equal(withLegacy.actualStarts,2); - assert.equal(withLegacy.dispatched,1); - assert.equal(withLegacy.unmatched,2); - const legacy = await history.startSystem('legacy-system-untimed',1,'test'); - assert.equal(legacy,true); - assert.equal((await history.recent(1,0))[0].command_started_at,null); + await stageSystemPlan(db, [], start + 3 * minute + 3000); // install failed or crashed + const switched = await stageSystemPlan(db, [rule], start + 5 * minute - 50); + await confirmSystemPlan(db, switched, start + 5 * minute + 50); + const audit = await systemScheduleAudit(db, start, start + 8 * minute + 6000); + assert.deepEqual( + [ + audit.expected, + audit.observed, + audit.missing, + audit.dispatched, + audit.actualStarts, + audit.skipped, + audit.duplicates, + audit.unmatched, + ], + [4, 2, 1, 1, 1, 1, 1, 2], + ); + assert.equal(audit.actualSkips, 2); + assert.deepEqual( + audit.recent + .filter((r) => r.triggerCount) + .map((r) => [r.triggerCount, r.startCount, r.skipCount]), + [ + [1, 0, 1], + [2, 1, 1], + ], + ); + assert.equal(audit.partial, true); + assert.deepEqual( + audit.recent.map((r) => [r.time - start, r.status]), + [ + [8 * minute, 'awaiting'], + [7 * minute, 'missing'], + [6 * minute, 'switch'], + [5 * minute, 'switch'], + [4 * minute, 'switch'], + [3 * minute, 'switch'], + [2 * minute, 'skipped'], + [minute, 'started'], + [0, 'switch'], + ], + ); + await db.query( + "UPDATE CronTriggers SET script_started_at=observed_at+1 WHERE id='old-format'", + ); + const withLegacy = await systemScheduleAudit( + db, + start, + start + 8 * minute + 6000, + ); + assert.equal(withLegacy.actualStarts, 2); + assert.equal(withLegacy.dispatched, 1); + assert.equal(withLegacy.unmatched, 2); + const legacy = await history.startSystem('legacy-system-untimed', 1, 'test'); + assert.equal(legacy, true); + assert.equal((await history.recent(1, 0))[0].command_started_at, null); await suspendSystemPlan(db); await suspendSystemPlan(db); - const [last] = await db.query('SELECT COUNT(*) AS n FROM CronSystemPlans WHERE rules=\'[]\' AND confirmed IS NULL',{type:QueryTypes.SELECT}); - assert.equal(last.n,2); + const [last] = await db.query( + "SELECT COUNT(*) AS n FROM CronSystemPlans WHERE rules='[]' AND confirmed IS NULL", + { type: QueryTypes.SELECT }, + ); + assert.equal(last.n, 2); }); -test('queue admission captures only occupants in the same execution pool and freezes the wait on dispatch', async t => { +test('queue admission captures only occupants in the same execution pool and freezes the wait on dispatch', async (t) => { const { db, history, models } = await fixture(t); - const limit = load('back/shared/pLimit.ts', { - '../data/system': {SystemModel:{sync:async()=>{},findOne:async()=>null},AuthDataType:{}}, - '../loaders/logger':logger,'../services/notify':class {},'../config':{},'../config/grpcCerts':{},'../protos/api':{}, + const limit = load('back/cron/execution/cronLimit.ts', { + '../../data/system': { + SystemModel: { sync: async () => {}, findOne: async () => null }, + AuthDataType: {}, + }, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../config': {}, + '../../config/grpcCerts': {}, + '../../protos/api': {}, }).default; await limit.setCustomLimit(2); const holders = []; - const hold = (id, scheduled=false) => { - const job=()=>new Promise(resolve => holders.push({id,resolve})); - return scheduled ? limit.runWithCronLimit({id,name:id},job,undefined,()=>true,undefined,undefined,id,db) - : limit.manualRunWithCronLimit(job,undefined,{id,name:id},db); + const hold = (id, scheduled = false) => { + const job = () => new Promise((resolve) => holders.push({ id, resolve })); + return scheduled + ? limit.runWithCronLimit( + { id, name: id }, + job, + undefined, + () => true, + undefined, + undefined, + id, + db, + ) + : limit.manualRunWithCronLimit(job, undefined, { id, name: id }, db); }; - const work=[hold('A'),hold('B'),hold('scheduled-A',true)]; - t.after(async()=>{holders.forEach(x=>x.resolve());await Promise.all(work)}); - await models.CrontabModel.create({id:1,command:'true'}); - const queued=Date.now(); - await history.enqueue('short',1,'manual',null,queued); - const short=limit.manualRunWithCronLimit(async()=>{await history.start('short'); await history.complete('short','finished',null,0);}, - undefined,{id:'short',name:'C'},db); - const { oldestQueued }=require('../../back/shared/queueDiagnostics'); + const work = [hold('A'), hold('B'), hold('scheduled-A', true)]; + t.after(async () => { + holders.forEach((x) => x.resolve()); + await Promise.all(work); + }); + await models.CrontabModel.create({ id: 1, command: 'true' }); + const queued = Date.now(); + await history.enqueue('short', 1, 'manual', null, queued); + const short = limit.manualRunWithCronLimit( + async () => { + await history.start('short'); + await history.complete('short', 'finished', null, 0); + }, + undefined, + { id: 'short', name: 'C' }, + db, + ); + const { oldestQueued } = require('../../back/cron/queries/queueDiagnostics'); let row; - for(let i=0;i<100;i++){[row]=await oldestQueued(db);if(row?.queue_context)break;await new Promise(r=>setTimeout(r,10));} - const context=JSON.parse(row.queue_context); - assert.deepEqual(context,{queue:'manual',limit:2,occupied:2,holders:[{id:'A',name:'A'},{id:'B',name:'B'}]}); - holders.find(x=>x.id==='A').resolve(); + for (let i = 0; i < 100; i++) { + [row] = await oldestQueued(db); + if (row?.queue_context) break; + await new Promise((r) => setTimeout(r, 10)); + } + const context = JSON.parse(row.queue_context); + assert.deepEqual(context, { + queue: 'manual', + limit: 2, + occupied: 2, + holders: [ + { id: 'A', name: 'A' }, + { id: 'B', name: 'B' }, + ], + }); + holders.find((x) => x.id === 'A').resolve(); await short; - const [done]=await history.recent(1,0); - assert.equal(done.state,'finished');assert.equal(done.queue_context,row.queue_context); - assert.ok(done.started_at>=queued); assert.deepEqual(await oldestQueued(db),[]); + const [done] = await history.recent(1, 0); + assert.equal(done.state, 'finished'); + assert.equal(done.queue_context, row.queue_context); + assert.ok(done.started_at >= queued); + assert.deepEqual(await oldestQueued(db), []); }); -test('changing the limit resamples remaining holders and ends waiting at dequeue before command preparation', async t => { - const {db,history,models}=await fixture(t); - const limit=load('back/shared/pLimit.ts',{ - '../data/system':{SystemModel:{sync:async()=>{},findOne:async()=>null},AuthDataType:{}}, - '../loaders/logger':logger,'../services/notify':class {},'../config':{},'../config/grpcCerts':{},'../protos/api':{}, +test('changing the limit resamples remaining holders and ends waiting at dequeue before command preparation', async (t) => { + const { db, history, models } = await fixture(t); + const limit = load('back/cron/execution/cronLimit.ts', { + '../../data/system': { + SystemModel: { sync: async () => {}, findOne: async () => null }, + AuthDataType: {}, + }, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../config': {}, + '../../config/grpcCerts': {}, + '../../protos/api': {}, }).default; await limit.setCustomLimit(3); - await models.CrontabModel.create({id:1,command:'true'}); - const gates=new Map(), work=[]; - const gate=id=>new Promise(resolve=>gates.set(id,resolve)); - for(const id of ['A','B','C']) work.push(limit.manualRunWithCronLimit(()=>gate(id),undefined,{id,name:id},db)); - await history.enqueue('D',1,'manual',null,Date.now()); - work.push(limit.manualRunWithCronLimit(async()=>{await gate('prepare');await history.start('D');await history.complete('D','finished',null,0)},undefined,{id:'D',name:'D'},db)); - t.after(async()=>{for(const done of gates.values())done();}); - const read=async()=>(await history.recent(1,0))[0]; + await models.CrontabModel.create({ id: 1, command: 'true' }); + const gates = new Map(), + work = []; + const gate = (id) => new Promise((resolve) => gates.set(id, resolve)); + for (const id of ['A', 'B', 'C']) + work.push( + limit.manualRunWithCronLimit( + () => gate(id), + undefined, + { id, name: id }, + db, + ), + ); + await history.enqueue('D', 1, 'manual', null, Date.now()); + work.push( + limit.manualRunWithCronLimit( + async () => { + await gate('prepare'); + await history.start('D'); + await history.complete('D', 'finished', null, 0); + }, + undefined, + { id: 'D', name: 'D' }, + db, + ), + ); + t.after(async () => { + for (const done of gates.values()) done(); + }); + const read = async () => (await history.recent(1, 0))[0]; async function sample(check) { - for(let i=0;i<150;i++){const row=await read();if(check(row))return row;await new Promise(r=>setTimeout(r,5));} + for (let i = 0; i < 150; i++) { + const row = await read(); + if (check(row)) return row; + await new Promise((r) => setTimeout(r, 5)); + } assert.fail('queue did not publish expected sample'); } - await sample(r=>JSON.parse(r.queue_context)?.occupied===3); - await limit.setCustomLimit(1);gates.get('B')(); - const cut=await sample(r=>{const v=JSON.parse(r.queue_live_context);return v?.limit===1&&v.occupied===2;}); - assert.deepEqual(JSON.parse(cut.queue_live_context).holders.map(h=>h.id),['A','C']); - gates.get('A')();await sample(r=>JSON.parse(r.queue_live_context)?.occupied===1); + await sample((r) => JSON.parse(r.queue_context)?.occupied === 3); + await limit.setCustomLimit(1); + gates.get('B')(); + const cut = await sample((r) => { + const v = JSON.parse(r.queue_live_context); + return v?.limit === 1 && v.occupied === 2; + }); + assert.deepEqual( + JSON.parse(cut.queue_live_context).holders.map((h) => h.id), + ['A', 'C'], + ); + gates.get('A')(); + await sample((r) => JSON.parse(r.queue_live_context)?.occupied === 1); await limit.setCustomLimit(2); - const preparing=await sample(r=>r.dequeued_at!=null); - assert.equal(preparing.state,'queued');assert.equal(preparing.started_at,null);assert.equal(preparing.queue_live_context,null); - await new Promise(r=>setTimeout(r,30));gates.get('prepare')();gates.get('C')();await Promise.all(work); - const ended=await read();assert.equal(ended.dequeued_at,preparing.dequeued_at);assert.ok(ended.started_at-ended.dequeued_at>=25); - assert.deepEqual(JSON.parse(ended.queue_context).holders.map(h=>h.id),['A','B','C']); + const preparing = await sample((r) => r.dequeued_at != null); + assert.equal(preparing.state, 'queued'); + assert.equal(preparing.started_at, null); + assert.equal(preparing.queue_live_context, null); + await new Promise((r) => setTimeout(r, 30)); + gates.get('prepare')(); + gates.get('C')(); + await Promise.all(work); + const ended = await read(); + assert.equal(ended.dequeued_at, preparing.dequeued_at); + assert.ok(ended.started_at - ended.dequeued_at >= 25); + assert.deepEqual( + JSON.parse(ended.queue_context).holders.map((h) => h.id), + ['A', 'B', 'C'], + ); }); -test('a stamped late system receipt stays on its dispatch day and an unstamped one cannot claim the next minute', async t=>{ - const {db}=await fixture(t),{stageSystemPlan,confirmSystemPlan,systemScheduleAudit}=require('../../back/shared/systemScheduleAudit'); - const day=+new Date(2026,10,16), m=60000, rule={id:1,schedule:'* * * * *'}; - const id=await stageSystemPlan(db,[rule],day-4*m);await confirmSystemPlan(db,id,day-4*m+30); - const midnight=new Date(day);midnight.setHours(0,0,0,0);const prev=new Date(midnight);prev.setDate(prev.getDate()-1); - for(const [id,stamp,at] of [['late',day-m,day+2100],['legacy',null,day+m+500]]){ - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,system_rule,system_dispatch_at,observed_at,command_started_at) VALUES($id,1,'system','finished',$rule,$stamp,$at,$at)",{bind:{id,rule:rule.schedule,stamp,at}}); +test('a stamped late system receipt stays on its dispatch day and an unstamped one cannot claim the next minute', async (t) => { + const { db } = await fixture(t), + { + stageSystemPlan, + confirmSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const day = +new Date(2026, 10, 16), + m = 60000, + rule = { id: 1, schedule: '* * * * *' }; + const id = await stageSystemPlan(db, [rule], day - 4 * m); + await confirmSystemPlan(db, id, day - 4 * m + 30); + const midnight = new Date(day); + midnight.setHours(0, 0, 0, 0); + const prev = new Date(midnight); + prev.setDate(prev.getDate() - 1); + for (const [id, stamp, at] of [ + ['late', day - m, day + 2100], + ['legacy', null, day + m + 500], + ]) { + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,system_rule,system_dispatch_at,observed_at,command_started_at) VALUES($id,1,'system','finished',$rule,$stamp,$at,$at)", + { bind: { id, rule: rule.schedule, stamp, at } }, + ); } - const before=await systemScheduleAudit(db,+prev,day+3*m), after=await systemScheduleAudit(db,day,day+3*m+5000); - assert.equal(before.recent.find(r=>r.time===day-m).id,'late');assert.equal(after.observed,0); - assert.equal(after.unmatched,1);assert.equal(after.uncertain,2);assert.equal(after.missing,1);assert.equal(after.awaiting,1); + const before = await systemScheduleAudit(db, +prev, day + 3 * m), + after = await systemScheduleAudit(db, day, day + 3 * m + 5000); + assert.equal(before.recent.find((r) => r.time === day - m).id, 'late'); + assert.equal(after.observed, 0); + assert.equal(after.unmatched, 1); + assert.equal(after.uncertain, 2); + assert.equal(after.missing, 1); + assert.equal(after.awaiting, 1); }); -test('repeated failed installs retain the original uncertain interval across reopening the DB',async t=>{ - const {db,root}=await fixture(t); - const {stageSystemPlan,confirmSystemPlan}=require('../../back/shared/systemScheduleAudit'); - const rules=[{id:2,schedule:'* * * * *'},{id:1,schedule:'0 * * * *'}]; - const first=await stageSystemPlan(db,rules,1000); - const reopened=new Sequelize({dialect:'sqlite',storage:db.options.storage,logging:false}); +test('repeated failed installs retain the original uncertain interval across reopening the DB', async (t) => { + const { db, root } = await fixture(t); + const { + stageSystemPlan, + confirmSystemPlan, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const rules = [ + { id: 2, schedule: '* * * * *' }, + { id: 1, schedule: '0 * * * *' }, + ]; + const first = await stageSystemPlan(db, rules, 1000); + const reopened = new Sequelize({ + dialect: 'sqlite', + storage: db.options.storage, + logging: false, + }); try { - assert.equal(await stageSystemPlan(reopened,[...rules].reverse(),61000),first); - await confirmSystemPlan(reopened,first,64000); - const [[row]]=await db.query('SELECT * FROM CronSystemPlans'); - assert.equal(row.staged,1000);assert.equal(row.confirmed,64000); - const next=await stageSystemPlan(db,rules,65000);assert.notEqual(first,next); - assert.notEqual(await stageSystemPlan(db,[],66000),next); - }finally{await reopened.close()} + assert.equal( + await stageSystemPlan(reopened, [...rules].reverse(), 61000), + first, + ); + await confirmSystemPlan(reopened, first, 64000); + const [[row]] = await db.query('SELECT * FROM CronSystemPlans'); + assert.equal(row.staged, 1000); + assert.equal(row.confirmed, 64000); + const next = await stageSystemPlan(db, rules, 65000); + assert.notEqual(first, next); + assert.notEqual(await stageSystemPlan(db, [], 66000), next); + } finally { + await reopened.close(); + } }); -test('a delayed system dispatch reaching a disabled task records one skip in its original minute',async t=>{ - const {db,models,history}=await fixture(t); - const {stageSystemPlan,confirmSystemPlan,systemScheduleAudit}=require('../../back/shared/systemScheduleAudit'); - const start=+new Date(2026,10,16),minute=60000,schedule='* * * * *'; - await models.CrontabModel.create({id:1,isDisabled:1,command:'true'}); - const plan=await stageSystemPlan(db,[{id:1,schedule}],start-3*minute);await confirmSystemPlan(db,plan,start-3*minute+1); - const off=await stageSystemPlan(db,[],start+minute+50);await confirmSystemPlan(db,off,start+minute+100); - const wrapper={rule:schedule,dispatch:start+minute,at:start+2*minute+100}; - for(let i=0;i<2;i++)assert.equal(await history.startSystem('delayed',1,'test','test',wrapper),false); - const [row]=await history.recent(1,0);assert.equal(row.state,'skipped');assert.equal(row.reason,'changed');assert.equal(row.command_started_at,null); - const audit=await systemScheduleAudit(db,start,start+3*minute);assert.equal(audit.skipped,1);assert.equal(audit.actualStarts,0); - assert.equal(audit.recent.find(r=>r.id==='delayed').time,wrapper.dispatch); -}); - -test('recovery of an unclaimed trigger starts a new wait measurement without the previous holders',async t=>{ - const {db,history}=await fixture(t); - await history.enqueue('reclaim',1,'node',1000,1001); - await db.query("UPDATE CronTriggers SET state='skipped',reason='restart',dequeued_at=1030,queue_context='{}',queue_live_context='{}' WHERE id='reclaim'"); - assert.equal(await history.enqueue('reclaim',1,'recovery',1000,5000),true); - const [row]=await history.recent(1,0);assert.equal(row.queued_at,5000); - for(const col of ['dequeued_at','queue_context','queue_live_context'])assert.equal(row[col],null); -}); - -test('a late duplicate skip survives reopening and retries without moving to the next crond minute', async t => { +test('a delayed system dispatch reaching a disabled task records one skip in its original minute', async (t) => { const { db, models, history } = await fixture(t); - const { stageSystemPlan, confirmSystemPlan, systemScheduleAudit } = require('../../back/shared/systemScheduleAudit'); + const { + stageSystemPlan, + confirmSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const start = +new Date(2026, 10, 16), + minute = 60000, + schedule = '* * * * *'; + await models.CrontabModel.create({ id: 1, isDisabled: 1, command: 'true' }); + const plan = await stageSystemPlan( + db, + [{ id: 1, schedule }], + start - 3 * minute, + ); + await confirmSystemPlan(db, plan, start - 3 * minute + 1); + const off = await stageSystemPlan(db, [], start + minute + 50); + await confirmSystemPlan(db, off, start + minute + 100); + const wrapper = { + rule: schedule, + dispatch: start + minute, + at: start + 2 * minute + 100, + }; + for (let i = 0; i < 2; i++) + assert.equal( + await history.startSystem('delayed', 1, 'test', 'test', wrapper), + false, + ); + const [row] = await history.recent(1, 0); + assert.equal(row.state, 'skipped'); + assert.equal(row.reason, 'changed'); + assert.equal(row.command_started_at, null); + const audit = await systemScheduleAudit(db, start, start + 3 * minute); + assert.equal(audit.skipped, 1); + assert.equal(audit.actualStarts, 0); + assert.equal( + audit.recent.find((r) => r.id === 'delayed').time, + wrapper.dispatch, + ); +}); + +test('recovery of an unclaimed trigger starts a new wait measurement without the previous holders', async (t) => { + const { db, history } = await fixture(t); + await history.enqueue('reclaim', 1, 'node', 1000, 1001); + await db.query( + "UPDATE CronTriggers SET state='skipped',reason='restart',dequeued_at=1030,queue_context='{}',queue_live_context='{}' WHERE id='reclaim'", + ); + assert.equal( + await history.enqueue('reclaim', 1, 'recovery', 1000, 5000), + true, + ); + const [row] = await history.recent(1, 0); + assert.equal(row.queued_at, 5000); + for (const col of ['dequeued_at', 'queue_context', 'queue_live_context']) + assert.equal(row[col], null); +}); + +test('a late duplicate skip survives reopening and retries without moving to the next crond minute', async (t) => { + const { db, models, history } = await fixture(t); + const { + stageSystemPlan, + confirmSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); const minute = 60000; - const first = +new Date(2026, 10, 16), next = first + minute; + const first = +new Date(2026, 10, 16), + next = first + minute; const schedule = '* * * * *'; - await models.CrontabModel.create({ id: 1, command: 'true', allow_multiple_instances: 0 }); - const plan = await stageSystemPlan(db, [{ id: 1, schedule }], first - 3 * minute); + await models.CrontabModel.create({ + id: 1, + command: 'true', + allow_multiple_instances: 0, + }); + const plan = await stageSystemPlan( + db, + [{ id: 1, schedule }], + first - 3 * minute, + ); await confirmSystemPlan(db, plan, first - 2 * minute); const start = (store, id, dispatch, at) => - store.startSystem(id, 1, 'test-owner', 'test-command', { rule: schedule, dispatch, at }); + store.startSystem(id, 1, 'test-owner', 'test-command', { + rule: schedule, + dispatch, + at, + }); async function check(connection, now, duplicates, slots) { const audit = await systemScheduleAudit(connection, first, now); - assert.deepEqual(audit.recent.map(r => [r.time, r.triggerCount, r.startCount, r.skipCount]), slots); - assert.deepEqual([audit.expected, audit.observed, audit.actualStarts, audit.actualSkips, - audit.duplicates, audit.missing, audit.unmatched], [slots.length, slots.length, slots.length, duplicates, duplicates, 0, 0]); + assert.deepEqual( + audit.recent.map((r) => [ + r.time, + r.triggerCount, + r.startCount, + r.skipCount, + ]), + slots, + ); + assert.deepEqual( + [ + audit.expected, + audit.observed, + audit.actualStarts, + audit.actualSkips, + audit.duplicates, + audit.missing, + audit.unmatched, + ], + [slots.length, slots.length, slots.length, duplicates, duplicates, 0, 0], + ); } assert.equal(await start(history, 'first', first, first + 100), true); await history.finish('first', 'finished', null, 0); - const original = [first, 1, 1, 0], following = [next, 1, 1, 0]; + const original = [first, 1, 1, 0], + following = [next, 1, 1, 0]; await check(db, first + 8000, 0, [original]); - const reopened = new Sequelize({ dialect: 'sqlite', storage: db.options.storage, logging: false }); + const reopened = new Sequelize({ + dialect: 'sqlite', + storage: db.options.storage, + logging: false, + }); try { const recovered = new TriggerHistory(reopened); assert.equal(await start(recovered, 'following', next, next + 100), true); await check(reopened, next + 8000, 0, [following, original]); - assert.equal(await start(recovered, 'duplicate', first, next + 10000), false); + assert.equal( + await start(recovered, 'duplicate', first, next + 10000), + false, + ); await check(db, next + 11000, 1, [following, [first, 2, 1, 1]]); await recovered.finish('following', 'finished', null, 0); assert.equal(await start(history, 'duplicate', first, next + 15000), false); @@ -5971,16 +10457,20 @@ test('a late duplicate skip survives reopening and retries without moving to the } }); -test('system crond publishes an exit only for a claimed command, including command exit 75', async t => { +test('system crond publishes an exit only for a claimed command, including command exit 75', async (t) => { const { root } = await fixture(t); const client = path.join(root, 'node'); const trace = path.join(root, 'receipts'); - await fs.writeFile(client, [ - '#!/bin/sh', - 'if [ "$1" = -p ]; then echo uuid; exit 0; fi', - 'if [ "$2" = start ]; then echo start >> "$TRACE"; exit "$CLAIM_STATUS"; fi', - 'echo "finish $6" >> "$TRACE"', - ].join('\n'), { mode: 0o755 }); + await fs.writeFile( + client, + [ + '#!/bin/sh', + 'if [ "$1" = -p ]; then echo uuid; exit 0; fi', + 'if [ "$2" = start ]; then echo start >> "$TRACE"; exit "$CLAIM_STATUS"; fi', + 'echo "finish $6" >> "$TRACE"', + ].join('\n'), + { mode: 0o755 }, + ); for (const [claim, exit, expectedStatus, receipts] of [ [75, 0, 0, ['start']], [1, 0, 1, ['start']], @@ -5988,37 +10478,72 @@ test('system crond publishes an exit only for a claimed command, including comma [0, 0, 0, ['start', 'finish 0']], ]) { await fs.writeFile(trace, ''); - const run = require('node:child_process').spawnSync('/bin/bash', [ - path.resolve('shell/system-cron.sh'), 'echo task-output; exit "$EXIT_STATUS"', - ], { - env: { ...process.env, QL_DIR: root, ID: '7', TRACE: trace, CLAIM_STATUS: String(claim), - EXIT_STATUS: String(exit), PATH: root + ':' + process.env.PATH }, - encoding: 'utf8', - }); + const run = require('node:child_process').spawnSync( + '/bin/bash', + [ + path.resolve('shell/system-cron.sh'), + 'echo task-output; exit "$EXIT_STATUS"', + ], + { + env: { + ...process.env, + QL_DIR: root, + ID: '7', + TRACE: trace, + CLAIM_STATUS: String(claim), + EXIT_STATUS: String(exit), + PATH: root + ':' + process.env.PATH, + }, + encoding: 'utf8', + }, + ); assert.equal(run.status, expectedStatus, run.stderr); assert.equal(run.stdout, claim === 0 ? 'task-output\n' : ''); - assert.deepEqual((await fs.readFile(trace, 'utf8')).trim().split('\n'), receipts); + assert.deepEqual( + (await fs.readFile(trace, 'utf8')).trim().split('\n'), + receipts, + ); } }); -test('crond restart keeps an interrupted run unknown and only counts committed duplicate skips', async t => { +test('crond restart keeps an interrupted run unknown and only counts committed duplicate skips', async (t) => { const { db, models, history } = await fixture(t); - const { stageSystemPlan, confirmSystemPlan, systemScheduleAudit } = require('../../back/shared/systemScheduleAudit'); + const { + stageSystemPlan, + confirmSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); const minute = 60000; - const first = +new Date(2026, 10, 16), next = first + minute; - const schedule = '* * * * *', owner = systemOwner(process.pid); + const first = +new Date(2026, 10, 16), + next = first + minute; + const schedule = '* * * * *', + owner = systemOwner(process.pid); await models.CrontabModel.create({ id: 1, command: 'true', isDisabled: 0 }); - const plan = await stageSystemPlan(db, [{ id: 1, schedule }], first - 3 * minute); + const plan = await stageSystemPlan( + db, + [{ id: 1, schedule }], + first - 3 * minute, + ); await confirmSystemPlan(db, plan, first - 2 * minute); const start = (store, id, dispatch, birth) => - store.startSystem(id, 1, birth, birth, { rule: schedule, dispatch, at: dispatch + 50 }); + store.startSystem(id, 1, birth, birth, { + rule: schedule, + dispatch, + at: dispatch + 50, + }); assert.equal(await start(history, 'old-run', first, owner + '-old'), true); // The insert has succeeded inside the transaction, but even an interrupted // skip decision must leave no durable trigger if the transaction rolls back. await db.query(`CREATE TRIGGER abort_duplicate BEFORE UPDATE OF state ON CronTriggers WHEN OLD.id='unsaved' AND NEW.state='skipped' BEGIN SELECT RAISE(ABORT,'interrupted skip'); END`); - await assert.rejects(start(history, 'unsaved', first, owner), error => /interrupted skip/.test(error.parent?.message)); - const reopened = new Sequelize({ dialect: 'sqlite', storage: db.options.storage, logging: false }); + await assert.rejects(start(history, 'unsaved', first, owner), (error) => + /interrupted skip/.test(error.parent?.message), + ); + const reopened = new Sequelize({ + dialect: 'sqlite', + storage: db.options.storage, + logging: false, + }); try { const recovered = new TriggerHistory(reopened); await recovered.interrupt('http'); @@ -6027,27 +10552,62 @@ test('crond restart keeps an interrupted run unknown and only counts committed d for (let retry = 0; retry < 2; retry++) { assert.equal(await start(recovered, 'old-run', first, owner), false); await recovered.interrupt('http'); - const rows = await recovered.visibleTriggers(1, ['unsaved', 'old-run', 'new-run', 'confirmed-skip']); - assert.deepEqual(rows.map(r => [r.id,r.state,r.exit_code]).sort(), [ - ['confirmed-skip','skipped',null], ['new-run','running',null], ['old-run','unknown',null], + const rows = await recovered.visibleTriggers(1, [ + 'unsaved', + 'old-run', + 'new-run', + 'confirmed-skip', + ]); + assert.deepEqual(rows.map((r) => [r.id, r.state, r.exit_code]).sort(), [ + ['confirmed-skip', 'skipped', null], + ['new-run', 'running', null], + ['old-run', 'unknown', null], ]); const audit = await systemScheduleAudit(reopened, first, next + 8000); - assert.deepEqual([audit.expected,audit.observed,audit.actualStarts,audit.actualSkips,audit.duplicates,audit.missing,audit.unmatched], - [2,2,2,1,1,0,0]); - assert.deepEqual(audit.recent.map(r => [r.time,r.triggerCount,r.startCount,r.skipCount,r.unknownExitCount]), - [[next,2,1,1,0], [first,1,1,0,1]]); + assert.deepEqual( + [ + audit.expected, + audit.observed, + audit.actualStarts, + audit.actualSkips, + audit.duplicates, + audit.missing, + audit.unmatched, + ], + [2, 2, 2, 1, 1, 0, 0], + ); + assert.deepEqual( + audit.recent.map((r) => [ + r.time, + r.triggerCount, + r.startCount, + r.skipCount, + r.unknownExitCount, + ]), + [ + [next, 2, 1, 1, 0], + [first, 1, 1, 0, 1], + ], + ); } } finally { await reopened.close(); } }); -test('a late skipped timer affects trigger deviation but only valid queue endpoints enter wait P95', async t => { +test('a late skipped timer affects trigger deviation but only valid queue endpoints enter wait P95', async (t) => { const { db, history } = await fixture(t); - const { saveSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit'); + const { + saveSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); const day = +new Date(2026, 10, 16); const rule = '* * * * *'; - await saveSchedulePlan(db, { crons: [{ id: '1', schedule: rule }], replace: true }, day); + await saveSchedulePlan( + db, + { crons: [{ id: '1', schedule: rule }], replace: true }, + day, + ); for (const [minute, deviation, dequeue, start, state] of [ [1, 1703994, null, null, 'skipped'], [2, 18, null, 136, 'finished'], @@ -6058,13 +10618,21 @@ test('a late skipped timer affects trigger deviation but only valid queue endpoi ]) { const scheduled = day + minute * 60000; const observed = scheduled + deviation; - await db.query(`INSERT INTO CronTriggers + await db.query( + `INSERT INTO CronTriggers (id,cron_id,source,state,scheduled_at,observed_at,queued_at,dequeued_at,started_at) - VALUES($id,1,'node',$state,$scheduled,$observed,$observed,$dequeue,$start)`, { - bind: { id: slotId('1', 0, rule, scheduled), state, scheduled, observed, - dequeue: dequeue == null ? null : observed + dequeue, - start: start == null ? null : observed + start }, - }); + VALUES($id,1,'node',$state,$scheduled,$observed,$observed,$dequeue,$start)`, + { + bind: { + id: slotId('1', 0, rule, scheduled), + state, + scheduled, + observed, + dequeue: dequeue == null ? null : observed + dequeue, + start: start == null ? null : observed + start, + }, + }, + ); } const audit = await auditSchedule(db, day, day + 60 * 60000); assert.equal(audit.observed, 6); @@ -6076,7 +10644,7 @@ test('a late skipped timer affects trigger deviation but only valid queue endpoi assert.equal(metrics.waitP95, 136); }); -test('overview clock pins the original server day when its data query crosses midnight', async t => { +test('overview clock pins the original server day when its data query crosses midnight', async (t) => { const { root, models, stats } = await fixture(t); const day = require('dayjs')().startOf('day'); const midnight = day.add(1, 'day').valueOf(); @@ -6084,303 +10652,649 @@ test('overview clock pins the original server day when its data query crosses mi t.mock.method(Date, 'now', () => clock); const router = express.Router(); load('back/api/dashboard.ts', { - '../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats, - '../shared/triggerHistory': { TriggerHistory: class { - async metrics(since) { - assert.equal(since, day.valueOf()); - clock = midnight + 100; - return { audit: { through: midnight - 5100 } }; - } - } }, + '../config': { logPath: root }, + '../data/cron': models, + '../data/cronStats': stats, + '../cron/history': { + TriggerHistory: class { + async metrics(since) { + assert.equal(since, day.valueOf()); + clock = midnight + 100; + return { audit: { through: midnight - 5100 } }; + } + }, + }, }).default(router); - const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/overview').route.stack.at(-1).handle; + const handler = router.stack[0].handle.stack + .find((x) => x.route?.path === '/overview') + .route.stack.at(-1).handle; let result; - await handler({}, { send(value) { result = value; } }, error => { throw error; }); + await handler( + {}, + { + send(value) { + result = value; + }, + }, + (error) => { + throw error; + }, + ); assert.equal(result.code, 200); assert.equal(result.data.serverNow, midnight - 100); assert.equal(result.data.expiresAt, midnight); assert.equal(result.data.todayRuns, 0); }); -test('panel anomaly pages match scheduled counts, isolate overlapping rules and restart paging on late evidence', async t => { +test('panel anomaly pages match scheduled counts, isolate overlapping rules and restart paging on late evidence', async (t) => { const { db, history } = await fixture(t); - const { AnomalyPage } = require('../../back/shared/scheduleAnomalies'); - const { saveSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit'); - const start = new Date(2026, 1, 1, 9).getTime(), rule = '* * * * * *'; - await saveSchedulePlan(db, { replace: true, crons: [{ id:'9', schedule:rule, extra_schedules:[{schedule:rule}] }] }, start); + const { AnomalyPage } = require('../../back/cron/queries/scheduleAnomalies'); + const { + saveSchedulePlan, + auditSchedule, + } = require('../../back/cron/scheduling/scheduleAudit'); + const start = new Date(2026, 1, 1, 9).getTime(), + rule = '* * * * * *'; + await saveSchedulePlan( + db, + { + replace: true, + crons: [ + { id: '9', schedule: rule, extra_schedules: [{ schedule: rule }] }, + ], + }, + start, + ); const read = async (kind, page = 1, revision) => { const rows = new AnomalyPage(kind, page, revision); - const audit = await auditSchedule(db,start,start+35000,rows); + const audit = await auditSchedule(db, start, start + 35000, rows); const result = rows.result(); assert.equal(result.total, audit[kind]); return result; }; - const put = (i,n,source='node') => { - const at=start+n*1000; - return history.enqueue(slotId('9',i,rule,at),9,source,at,at); + const put = (i, n, source = 'node') => { + const at = start + n * 1000; + return history.enqueue(slotId('9', i, rule, at), 9, source, at, at); }; - const first=await read('missing'), second=await read('missing',2,first.revision); - assert.equal(first.total,60); assert.equal(second.page,2); - assert.equal(new Set([...first.rows,...second.rows].map(r=>r.ruleIndex+'/'+r.time)).size,50); - await put(0,1,'recovery'); await put(1,1); await put(0,2); await put(1,2); - const id=(i,n)=>slotId('9',i,rule,start+n*1000); - await history.finish(id(0,1),'skipped','overlap',null); - await history.start(id(1,1),start+1100,true); - await history.finish(id(1,1),'failed','spawn',127); - await db.query("UPDATE CronTriggers SET log_path='one.log' WHERE id=$id",{bind:{id:id(1,1)}}); - await history.recordCommandStart(id(0,2),start+2100); - const late=await read('missing',2,first.revision); - assert.deepEqual([late.changed,late.page,late.total],[true,1,56]); - assert.ok(late.rows.every(r=>r.trigger===null && !r.logPath)); - assert.deepEqual((await read('skipped')).rows.map(r=>[r.trigger,r.reason,r.source]),[[id(0,1),'overlap','recovery']]); - assert.deepEqual((await read('unconfirmed')).rows.map(r=>[r.trigger,!!r.logPath]),[[id(1,1),true]]); + const first = await read('missing'), + second = await read('missing', 2, first.revision); + assert.equal(first.total, 60); + assert.equal(second.page, 2); + assert.equal( + new Set( + [...first.rows, ...second.rows].map((r) => r.ruleIndex + '/' + r.time), + ).size, + 50, + ); + await put(0, 1, 'recovery'); + await put(1, 1); + await put(0, 2); + await put(1, 2); + const id = (i, n) => slotId('9', i, rule, start + n * 1000); + await history.finish(id(0, 1), 'skipped', 'overlap', null); + await history.start(id(1, 1), start + 1100, true); + await history.finish(id(1, 1), 'failed', 'spawn', 127); + await db.query("UPDATE CronTriggers SET log_path='one.log' WHERE id=$id", { + bind: { id: id(1, 1) }, + }); + await history.recordCommandStart(id(0, 2), start + 2100); + const late = await read('missing', 2, first.revision); + assert.deepEqual([late.changed, late.page, late.total], [true, 1, 56]); + assert.ok(late.rows.every((r) => r.trigger === null && !r.logPath)); + assert.deepEqual( + (await read('skipped')).rows.map((r) => [r.trigger, r.reason, r.source]), + [[id(0, 1), 'overlap', 'recovery']], + ); + assert.deepEqual( + (await read('unconfirmed')).rows.map((r) => [r.trigger, !!r.logPath]), + [[id(1, 1), true]], + ); }); -test('crond anomaly details count individual duplicate and unmatched receipts without inventing their schedule', async t => { +test('crond anomaly details count individual duplicate and unmatched receipts without inventing their schedule', async (t) => { const { db } = await fixture(t); - const { AnomalyPage } = require('../../back/shared/scheduleAnomalies'); - const { stageSystemPlan, confirmSystemPlan, systemScheduleAudit } = require('../../back/shared/systemScheduleAudit'); - const m=60000, start=new Date(2026,1,1,9).getTime(), schedule='* * * * *'; - const plan=await stageSystemPlan(db,[{id:1,name:'minute',schedule}],start-2*m); - await confirmSystemPlan(db,plan,start-2*m+1); - for (const [id,state,launch,rule,dispatch,observed,log] of [ - ['ran','finished',start+1,schedule,start,start,null], ['skip','skipped',null,schedule,start,start+m+7,null], - ['unknown','unknown',null,schedule,start,start+2,null], ['old','skipped',null,null,null,start+3,'/dev/null'], - ['unmatched','unknown',null,'0 0 * * *',start+m,start+m+4,'task/x.log'], - ]) await db.query('INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,system_rule,system_dispatch_at,command_started_at,log_path) VALUES($id,1,\'system\',$state,$observed,$rule,$dispatch,$launch,$log)',{bind:{id,state,launch,rule,dispatch,observed,log}}); - for (const [kind,field,count] of [['missing','missing',2],['skipped','actualSkips',2],['unconfirmed','actualUnconfirmed',2]]) { - const page=new AnomalyPage(kind,1); - const audit=await systemScheduleAudit(db,start,start+4*m+6000,page), report=page.result(); - assert.equal(report.total,count);assert.equal(audit[field],count); - assert.equal(audit.actualStarts+audit.actualSkips+audit.actualUnconfirmed,5); - if (kind==='missing') assert.deepEqual(report.rows.map(r=>r.time),[start+2*m,start+3*m]); - if (kind==='skipped') assert.deepEqual(report.rows.map(r=>[r.trigger,r.time,r.logPath]),[['old',null,'/dev/null'],['skip',start,null]]); - if (kind==='unconfirmed') assert.deepEqual(report.rows.map(r=>[r.trigger,r.time,r.logPath]),[['unknown',start,null],['unmatched',null,'task/x.log']]); + const { AnomalyPage } = require('../../back/cron/queries/scheduleAnomalies'); + const { + stageSystemPlan, + confirmSystemPlan, + systemScheduleAudit, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const m = 60000, + start = new Date(2026, 1, 1, 9).getTime(), + schedule = '* * * * *'; + const plan = await stageSystemPlan( + db, + [{ id: 1, name: 'minute', schedule }], + start - 2 * m, + ); + await confirmSystemPlan(db, plan, start - 2 * m + 1); + for (const [id, state, launch, rule, dispatch, observed, log] of [ + ['ran', 'finished', start + 1, schedule, start, start, null], + ['skip', 'skipped', null, schedule, start, start + m + 7, null], + ['unknown', 'unknown', null, schedule, start, start + 2, null], + ['old', 'skipped', null, null, null, start + 3, '/dev/null'], + [ + 'unmatched', + 'unknown', + null, + '0 0 * * *', + start + m, + start + m + 4, + 'task/x.log', + ], + ]) + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,system_rule,system_dispatch_at,command_started_at,log_path) VALUES($id,1,'system',$state,$observed,$rule,$dispatch,$launch,$log)", + { bind: { id, state, launch, rule, dispatch, observed, log } }, + ); + for (const [kind, field, count] of [ + ['missing', 'missing', 2], + ['skipped', 'actualSkips', 2], + ['unconfirmed', 'actualUnconfirmed', 2], + ]) { + const page = new AnomalyPage(kind, 1); + const audit = await systemScheduleAudit( + db, + start, + start + 4 * m + 6000, + page, + ), + report = page.result(); + assert.equal(report.total, count); + assert.equal(audit[field], count); + assert.equal( + audit.actualStarts + audit.actualSkips + audit.actualUnconfirmed, + 5, + ); + if (kind === 'missing') + assert.deepEqual( + report.rows.map((r) => r.time), + [start + 2 * m, start + 3 * m], + ); + if (kind === 'skipped') + assert.deepEqual( + report.rows.map((r) => [r.trigger, r.time, r.logPath]), + [ + ['old', null, '/dev/null'], + ['skip', start, null], + ], + ); + if (kind === 'unconfirmed') + assert.deepEqual( + report.rows.map((r) => [r.trigger, r.time, r.logPath]), + [ + ['unknown', start, null], + ['unmatched', null, 'task/x.log'], + ], + ); } }); -test('anomaly endpoint resolves task names and offers only the retained log for the exact trigger', async t => { +test('anomaly endpoint resolves task names and offers only the retained log for the exact trigger', async (t) => { const { root, db, models, stats } = await fixture(t); const at = require('dayjs')().subtract(1, 'day').hour(12).valueOf(); - await models.CrontabModel.create({ id: 4, name: 'Report', command: 'echo report' }); + await models.CrontabModel.create({ + id: 4, + name: 'Report', + command: 'echo report', + }); const logs = path.join(root, 'logs'); await fs.mkdir(logs); await fs.writeFile(path.join(logs, 'one.log'), 'only for run one'); await fs.symlink(path.join(root, 'panel.sqlite'), path.join(logs, 'outside')); - for (const [id, file] of [['one', 'one.log'], ['two', 'missing.log'], ['three', 'outside'], ['four', '/dev/null']]) { - await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,log_path) - VALUES($id,4,'system','unknown',$at,$file)`, { bind: { id, at: at - 10000, file } }); + for (const [id, file] of [ + ['one', 'one.log'], + ['two', 'missing.log'], + ['three', 'outside'], + ['four', '/dev/null'], + ]) { + await db.query( + `INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,log_path) + VALUES($id,4,'system','unknown',$at,$file)`, + { bind: { id, at: at - 10000, file } }, + ); } const router = express.Router(); load('back/api/dashboard.ts', { - '../config': { logPath: logs }, '../data/cron': models, '../data/cronStats': stats, + '../config': { logPath: logs }, + '../data/cron': models, + '../data/cronStats': stats, }).default(router); - const handle = router.stack[0].handle.stack.find(layer => layer.route?.path === '/schedule-anomalies').route.stack.at(-1).handle; + const handle = router.stack[0].handle.stack + .find((layer) => layer.route?.path === '/schedule-anomalies') + .route.stack.at(-1).handle; const read = async () => { let result; - await handle({ query: { source: 'system', kind: 'unconfirmed', page: 1, at } }, - { send(value) { result = value.data; } }, error => { throw error; }); + await handle( + { query: { source: 'system', kind: 'unconfirmed', page: 1, at } }, + { + send(value) { + result = value.data; + }, + }, + (error) => { + throw error; + }, + ); assert.equal(result.total, 4); - assert.ok(result.rows.every(row => row.name === 'Report' && row.time === null && !('logPath' in row))); - return result.rows.filter(row => row.hasLog).map(row => row.trigger); + assert.ok( + result.rows.every( + (row) => + row.name === 'Report' && row.time === null && !('logPath' in row), + ), + ); + return result.rows.filter((row) => row.hasLog).map((row) => row.trigger); }; assert.deepEqual(await read(), ['one']); await fs.unlink(path.join(logs, 'one.log')); assert.deepEqual(await read(), []); }); -for (const source of ['node', 'system']) test(source + ' anomaly pages reset after late reports and expose the same summary as starts are confirmed', async t => { - const { root, db, models, stats, history } = await fixture(t); - const { saveSchedulePlan } = require('../../back/shared/scheduleAudit'); - const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit'); - const day = require('dayjs')().subtract(1, 'day').startOf('day').valueOf(); - const start = day + 9 * 3600000; - const period = source === 'node' ? 1000 : 60000; - const rule = source === 'node' ? '* * * * * *' : '* * * * *'; - const at = start + 61 * period + 5000; - await models.CrontabModel.create({ id: 7, name: 'Late', command: 'echo late' }); - if (source === 'node') await saveSchedulePlan(db, { replace: true, crons: [{ id: '7', schedule: rule }] }, start); - else { - const plan = await stageSystemPlan(db, [{ id: 7, name: 'Late', schedule: rule }], start); - await confirmSystemPlan(db, plan, start + 1); - } - const router = express.Router(); - load('back/api/dashboard.ts', { '../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats }).default(router); - const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle; - const read = async (kind, page = 1, revision) => { - let result; - await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page, revision } }, - { send(value) { result = value.data; } }, error => { throw error; }); - const summary = result.summary[source === 'node' ? 'audit' : 'systemAudit']; - const field = source === 'node' || kind === 'missing' ? kind : kind === 'skipped' ? 'actualSkips' : 'actualUnconfirmed'; - assert.equal(result.total, summary[field]); - return result; - }; - const first = await read('missing'); - assert.ok(first.total > 50); - const second = await read('missing', 2, first.revision); - const third = await read('missing', 3, first.revision); - assert.equal(new Set([...first.rows, ...second.rows, ...third.rows].map(r => r.time)).size, first.total); - const slot = first.rows[0]; - const id = source === 'node' ? slotId('7', 0, rule, slot.time) : 'system-late'; - await history.enqueue(id, 7, source, slot.time, at); - await history.start(id, at, true); - if (source === 'system') await db.query('UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id', - { bind: { rule, time: slot.time, id } }); - await history.finish(id, 'failed', 'spawn', 127); - const filled = await read('missing', 3, first.revision); - assert.equal(filled.page, 1); - assert.equal(filled.changed, true); - assert.equal(filled.total, first.total - 1); - assert.ok(filled.rows.every(row => row.time !== slot.time)); - const unknown = await read('unconfirmed'); - assert.deepEqual(unknown.rows.map(r => r.trigger), [id]); - await history.recordCommandStart(id, at); - const started = await read('unconfirmed', 1, unknown.revision); - assert.equal(started.changed, true); - assert.equal(started.total, 0); - assert.deepEqual(started.rows, []); - const summary = started.summary[source === 'node' ? 'audit' : 'systemAudit']; - assert.equal(summary[source === 'node' ? 'dispatched' : 'actualStarts'], 1); - // Same count with a different member must also invalidate page offsets. - await db.query('DELETE FROM CronTriggers WHERE id=$id', { bind: { id } }); - const nextSlot = second.rows[0]; - const nextId = source === 'node' ? slotId('7', 0, rule, nextSlot.time) : 'system-other'; - await history.enqueue(nextId, 7, source, nextSlot.time, at); - if (source === 'system') await db.query('UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id', - { bind: { rule, time: nextSlot.time, id: nextId } }); - const replaced = await read('missing', 2, filled.revision); - assert.equal(replaced.total, filled.total); - assert.equal(replaced.changed, true); - assert.equal(replaced.page, 1); - const retried = await read('missing', 2, replaced.revision); - assert.equal(retried.page, 2); - assert.equal(retried.changed, false); - assert.equal(new Set([...replaced.rows, ...retried.rows].map(r => r.time)).size, 50); -}); - -for (const source of ['node', 'system']) test(source + ' partial history cleanup fences in-flight anomaly pages and preserves retained pagination', async t => { - const { root, db, models, stats, history } = await fixture(t); - const dayjs = require('dayjs'); - const at = dayjs().startOf('day').hour(12).valueOf(), start = at - 70 * 60000, rule = '* * * * *'; - t.mock.method(Date, 'now', () => at + 1000); - await models.CrontabModel.create({ id: 12, name: 'Partial cleanup', command: 'echo retained' }); - if (source === 'node') await require('../../back/shared/scheduleAudit').saveSchedulePlan(db, - { replace: true, crons: [{ id: '12', schedule: rule }] }, start); - else { - const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit'); - const plan = await stageSystemPlan(db, [{ id: 12, schedule: rule }], start - 60000); - await confirmSystemPlan(db, plan, start - 60000 + 1); - } - const ids = []; - for (let n = 1; n <= 60; n++) { - const time = start + n * 60000; - const id = source === 'node' ? slotId('12', 0, rule, time) : 'partial-system-' + n; - ids.push(id); - await history.enqueue(id, 12, source, time, time + 10); - await history.start(id, time + 20, true); - await history.finish(id, 'failed', 'spawn', 127); - await db.query("UPDATE CronTriggers SET finished_at=$end,log_path='retained.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id", - { bind: { id, time, rule, end: time + 1000 } }); - } - await fs.writeFile(path.join(root, 'retained.log'), 'retained log'); - // After an upgrade the earliest known installation can be newer than - // retained unmatched receipts. Plan coverage is not the retention boundary. - if (source === 'system') await db.query('UPDATE CronSystemPlans SET staged=$time,confirmed=$confirmed', - { bind: { time: start + 40 * 60000, confirmed: start + 40 * 60000 + 1 } }); - let cleanOnStat = false; - const cutoff = start + 20 * 60000 + 2000; - const router = express.Router(); - load('back/api/dashboard.ts', { - '../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats, - 'fs/promises': { stat: async file => { - if (cleanOnStat) { - cleanOnStat = false; - await db.transaction(transaction => history.deleteExpired(cutoff, transaction)); +for (const source of ['node', 'system']) + test( + source + + ' anomaly pages reset after late reports and expose the same summary as starts are confirmed', + async (t) => { + const { root, db, models, stats, history } = await fixture(t); + const { + saveSchedulePlan, + } = require('../../back/cron/scheduling/scheduleAudit'); + const { + stageSystemPlan, + confirmSystemPlan, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const day = require('dayjs')() + .subtract(1, 'day') + .startOf('day') + .valueOf(); + const start = day + 9 * 3600000; + const period = source === 'node' ? 1000 : 60000; + const rule = source === 'node' ? '* * * * * *' : '* * * * *'; + const at = start + 61 * period + 5000; + await models.CrontabModel.create({ + id: 7, + name: 'Late', + command: 'echo late', + }); + if (source === 'node') + await saveSchedulePlan( + db, + { replace: true, crons: [{ id: '7', schedule: rule }] }, + start, + ); + else { + const plan = await stageSystemPlan( + db, + [{ id: 7, name: 'Late', schedule: rule }], + start, + ); + await confirmSystemPlan(db, plan, start + 1); } - return fs.stat(file); - } }, - }).default(router); - const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle; - const read = async (page = 1, revision, kind = 'unconfirmed') => { - let result; - await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page, revision, live: true } }, - { send(value) { result = value.data; } }, error => { throw error; }); - return result; - }; - const first = await read(); - assert.equal(first.total, 60); - assert.equal((await read(3, first.revision)).rows.length, 10); - cleanOnStat = true; - assert.deepEqual(await read(2, first.revision), { status: 'unavailable' }); - const retained = await read(3, first.revision); - assert.equal(retained.total, 40); - assert.equal(retained.page, 1); - assert.equal(retained.changed, true); - const second = await read(2, retained.revision); - const rows = [...retained.rows, ...second.rows]; - assert.equal(new Set(rows.map(r => r.trigger)).size, 40); - assert.deepEqual(rows.map(r => r.trigger).sort(), ids.slice(20).sort()); - assert.ok(rows.every(r => r.hasLog)); - for (const kind of ['missing', 'skipped', 'unconfirmed']) { - const result = await read(1, undefined, kind); - const summary = result.summary[source === 'node' ? 'audit' : 'systemAudit']; - const field = source === 'node' || kind === 'missing' ? kind : kind === 'skipped' ? 'actualSkips' : 'actualUnconfirmed'; - assert.equal(result.total, summary[field]); - assert.ok(result.rows.every(r => r.time == null || r.time >= cutoff)); - } - assert.deepEqual(await history.visibleTriggers(12, ids.slice(0, 20)), []); -}); + const router = express.Router(); + load('back/api/dashboard.ts', { + '../config': { logPath: root }, + '../data/cron': models, + '../data/cronStats': stats, + }).default(router); + const handler = router.stack[0].handle.stack + .find((x) => x.route?.path === '/schedule-anomalies') + .route.stack.at(-1).handle; + const read = async (kind, page = 1, revision) => { + let result; + await handler( + { + query: { + source: source === 'node' ? 'panel' : 'system', + kind, + at, + page, + revision, + }, + }, + { + send(value) { + result = value.data; + }, + }, + (error) => { + throw error; + }, + ); + const summary = + result.summary[source === 'node' ? 'audit' : 'systemAudit']; + const field = + source === 'node' || kind === 'missing' + ? kind + : kind === 'skipped' + ? 'actualSkips' + : 'actualUnconfirmed'; + assert.equal(result.total, summary[field]); + return result; + }; + const first = await read('missing'); + assert.ok(first.total > 50); + const second = await read('missing', 2, first.revision); + const third = await read('missing', 3, first.revision); + assert.equal( + new Set( + [...first.rows, ...second.rows, ...third.rows].map((r) => r.time), + ).size, + first.total, + ); + const slot = first.rows[0]; + const id = + source === 'node' ? slotId('7', 0, rule, slot.time) : 'system-late'; + await history.enqueue(id, 7, source, slot.time, at); + await history.start(id, at, true); + if (source === 'system') + await db.query( + 'UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id', + { bind: { rule, time: slot.time, id } }, + ); + await history.finish(id, 'failed', 'spawn', 127); + const filled = await read('missing', 3, first.revision); + assert.equal(filled.page, 1); + assert.equal(filled.changed, true); + assert.equal(filled.total, first.total - 1); + assert.ok(filled.rows.every((row) => row.time !== slot.time)); + const unknown = await read('unconfirmed'); + assert.deepEqual( + unknown.rows.map((r) => r.trigger), + [id], + ); + await history.recordCommandStart(id, at); + const started = await read('unconfirmed', 1, unknown.revision); + assert.equal(started.changed, true); + assert.equal(started.total, 0); + assert.deepEqual(started.rows, []); + const summary = + started.summary[source === 'node' ? 'audit' : 'systemAudit']; + assert.equal( + summary[source === 'node' ? 'dispatched' : 'actualStarts'], + 1, + ); + // Same count with a different member must also invalidate page offsets. + await db.query('DELETE FROM CronTriggers WHERE id=$id', { bind: { id } }); + const nextSlot = second.rows[0]; + const nextId = + source === 'node' + ? slotId('7', 0, rule, nextSlot.time) + : 'system-other'; + await history.enqueue(nextId, 7, source, nextSlot.time, at); + if (source === 'system') + await db.query( + 'UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id', + { bind: { rule, time: nextSlot.time, id: nextId } }, + ); + const replaced = await read('missing', 2, filled.revision); + assert.equal(replaced.total, filled.total); + assert.equal(replaced.changed, true); + assert.equal(replaced.page, 1); + const retried = await read('missing', 2, replaced.revision); + assert.equal(retried.page, 2); + assert.equal(retried.changed, false); + assert.equal( + new Set([...replaced.rows, ...retried.rows].map((r) => r.time)).size, + 50, + ); + }, + ); -for (const source of ['node', 'system']) test(source + ' live anomaly sessions expire across midnight and after retained history is cleared', async t => { - const { root, db, models, stats, history } = await fixture(t); - const dayjs = require('dayjs'); - const { saveSchedulePlan } = require('../../back/shared/scheduleAudit'); - const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit'); - const at = dayjs().startOf('day').hour(12).valueOf(), start = at - 180000, rule = '* * * * *'; - const expiresAt = dayjs(at).startOf('day').add(1, 'day').valueOf(); - let clock = at + 10000, crossOnStat = false; - t.mock.method(Date, 'now', () => clock); - await models.CrontabModel.create({ id: 11, name: 'Midnight', command: 'echo midnight' }); - if (source === 'node') await saveSchedulePlan(db, { replace: true, crons: [{ id: '11', schedule: rule }] }, start); - else { - const plan = await stageSystemPlan(db, [{ id: 11, schedule: rule }], start - 60000); - await confirmSystemPlan(db, plan, start - 60000 + 1); - } - const time = Math.ceil((start + 60000) / 60000) * 60000; - const id = source === 'node' ? slotId('11', 0, rule, time) : 'system-midnight'; - await history.enqueue(id, 11, source, time, time + 10); - await history.start(id, time + 20, true); - await history.finish(id, 'failed', 'spawn', 127); - await fs.writeFile(path.join(root, 'midnight.log'), id); - await db.query("UPDATE CronTriggers SET finished_at=$end,log_path='midnight.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id", - { bind: { end: time + 1000, id, rule, time } }); - const router = express.Router(); - load('back/api/dashboard.ts', { - '../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats, - 'fs/promises': { stat: async file => { if (crossOnStat) clock = expiresAt; return fs.stat(file); } }, - }).default(router); - const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle; - const read = async kind => { - let result; - const res = { status() { return this; }, send(value) { result = value; } }; - await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page: 1, live: true } }, res, error => { throw error; }); - assert.equal(result.code, 200); - return result.data; - }; - const first = await read('unconfirmed'); - assert.deepEqual(first.rows.map(row => row.trigger), [id]); - assert.equal(first.expiresAt, expiresAt); - crossOnStat = true; - assert.deepEqual(await read('unconfirmed'), { status: 'expired' }); - crossOnStat = false; - assert.deepEqual(await read('missing'), { status: 'expired' }); - clock = at + 10000; - await db.transaction(transaction => history.deleteExpired(at + 1000, transaction)); - assert.deepEqual(await history.visibleTriggers(11, [id]), []); - for (const kind of ['missing', 'skipped', 'unconfirmed']) - assert.deepEqual(await read(kind), { status: 'unavailable' }); - // Repeated reads do not reconstitute the missing plan or the old log entry. - assert.deepEqual(await read('unconfirmed'), { status: 'unavailable' }); - assert.deepEqual(await history.visibleTriggers(11, [id]), []); -}); +for (const source of ['node', 'system']) + test( + source + + ' partial history cleanup fences in-flight anomaly pages and preserves retained pagination', + async (t) => { + const { root, db, models, stats, history } = await fixture(t); + const dayjs = require('dayjs'); + const at = dayjs().startOf('day').hour(12).valueOf(), + start = at - 70 * 60000, + rule = '* * * * *'; + t.mock.method(Date, 'now', () => at + 1000); + await models.CrontabModel.create({ + id: 12, + name: 'Partial cleanup', + command: 'echo retained', + }); + if (source === 'node') + await require('../../back/cron/scheduling/scheduleAudit').saveSchedulePlan( + db, + { replace: true, crons: [{ id: '12', schedule: rule }] }, + start, + ); + else { + const { + stageSystemPlan, + confirmSystemPlan, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const plan = await stageSystemPlan( + db, + [{ id: 12, schedule: rule }], + start - 60000, + ); + await confirmSystemPlan(db, plan, start - 60000 + 1); + } + const ids = []; + for (let n = 1; n <= 60; n++) { + const time = start + n * 60000; + const id = + source === 'node' + ? slotId('12', 0, rule, time) + : 'partial-system-' + n; + ids.push(id); + await history.enqueue(id, 12, source, time, time + 10); + await history.start(id, time + 20, true); + await history.finish(id, 'failed', 'spawn', 127); + await db.query( + "UPDATE CronTriggers SET finished_at=$end,log_path='retained.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id", + { bind: { id, time, rule, end: time + 1000 } }, + ); + } + await fs.writeFile(path.join(root, 'retained.log'), 'retained log'); + // After an upgrade the earliest known installation can be newer than + // retained unmatched receipts. Plan coverage is not the retention boundary. + if (source === 'system') + await db.query( + 'UPDATE CronSystemPlans SET staged=$time,confirmed=$confirmed', + { + bind: { + time: start + 40 * 60000, + confirmed: start + 40 * 60000 + 1, + }, + }, + ); + let cleanOnStat = false; + const cutoff = start + 20 * 60000 + 2000; + const router = express.Router(); + load('back/api/dashboard.ts', { + '../config': { logPath: root }, + '../data/cron': models, + '../data/cronStats': stats, + 'fs/promises': { + stat: async (file) => { + if (cleanOnStat) { + cleanOnStat = false; + await db.transaction((transaction) => + history.deleteExpired(cutoff, transaction), + ); + } + return fs.stat(file); + }, + }, + }).default(router); + const handler = router.stack[0].handle.stack + .find((x) => x.route?.path === '/schedule-anomalies') + .route.stack.at(-1).handle; + const read = async (page = 1, revision, kind = 'unconfirmed') => { + let result; + await handler( + { + query: { + source: source === 'node' ? 'panel' : 'system', + kind, + at, + page, + revision, + live: true, + }, + }, + { + send(value) { + result = value.data; + }, + }, + (error) => { + throw error; + }, + ); + return result; + }; + const first = await read(); + assert.equal(first.total, 60); + assert.equal((await read(3, first.revision)).rows.length, 10); + cleanOnStat = true; + assert.deepEqual(await read(2, first.revision), { + status: 'unavailable', + }); + const retained = await read(3, first.revision); + assert.equal(retained.total, 40); + assert.equal(retained.page, 1); + assert.equal(retained.changed, true); + const second = await read(2, retained.revision); + const rows = [...retained.rows, ...second.rows]; + assert.equal(new Set(rows.map((r) => r.trigger)).size, 40); + assert.deepEqual(rows.map((r) => r.trigger).sort(), ids.slice(20).sort()); + assert.ok(rows.every((r) => r.hasLog)); + for (const kind of ['missing', 'skipped', 'unconfirmed']) { + const result = await read(1, undefined, kind); + const summary = + result.summary[source === 'node' ? 'audit' : 'systemAudit']; + const field = + source === 'node' || kind === 'missing' + ? kind + : kind === 'skipped' + ? 'actualSkips' + : 'actualUnconfirmed'; + assert.equal(result.total, summary[field]); + assert.ok(result.rows.every((r) => r.time == null || r.time >= cutoff)); + } + assert.deepEqual(await history.visibleTriggers(12, ids.slice(0, 20)), []); + }, + ); + +for (const source of ['node', 'system']) + test( + source + + ' live anomaly sessions expire across midnight and after retained history is cleared', + async (t) => { + const { root, db, models, stats, history } = await fixture(t); + const dayjs = require('dayjs'); + const { + saveSchedulePlan, + } = require('../../back/cron/scheduling/scheduleAudit'); + const { + stageSystemPlan, + confirmSystemPlan, + } = require('../../back/cron/scheduling/systemScheduleAudit'); + const at = dayjs().startOf('day').hour(12).valueOf(), + start = at - 180000, + rule = '* * * * *'; + const expiresAt = dayjs(at).startOf('day').add(1, 'day').valueOf(); + let clock = at + 10000, + crossOnStat = false; + t.mock.method(Date, 'now', () => clock); + await models.CrontabModel.create({ + id: 11, + name: 'Midnight', + command: 'echo midnight', + }); + if (source === 'node') + await saveSchedulePlan( + db, + { replace: true, crons: [{ id: '11', schedule: rule }] }, + start, + ); + else { + const plan = await stageSystemPlan( + db, + [{ id: 11, schedule: rule }], + start - 60000, + ); + await confirmSystemPlan(db, plan, start - 60000 + 1); + } + const time = Math.ceil((start + 60000) / 60000) * 60000; + const id = + source === 'node' ? slotId('11', 0, rule, time) : 'system-midnight'; + await history.enqueue(id, 11, source, time, time + 10); + await history.start(id, time + 20, true); + await history.finish(id, 'failed', 'spawn', 127); + await fs.writeFile(path.join(root, 'midnight.log'), id); + await db.query( + "UPDATE CronTriggers SET finished_at=$end,log_path='midnight.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id", + { bind: { end: time + 1000, id, rule, time } }, + ); + const router = express.Router(); + load('back/api/dashboard.ts', { + '../config': { logPath: root }, + '../data/cron': models, + '../data/cronStats': stats, + 'fs/promises': { + stat: async (file) => { + if (crossOnStat) clock = expiresAt; + return fs.stat(file); + }, + }, + }).default(router); + const handler = router.stack[0].handle.stack + .find((x) => x.route?.path === '/schedule-anomalies') + .route.stack.at(-1).handle; + const read = async (kind) => { + let result; + const res = { + status() { + return this; + }, + send(value) { + result = value; + }, + }; + await handler( + { + query: { + source: source === 'node' ? 'panel' : 'system', + kind, + at, + page: 1, + live: true, + }, + }, + res, + (error) => { + throw error; + }, + ); + assert.equal(result.code, 200); + return result.data; + }; + const first = await read('unconfirmed'); + assert.deepEqual( + first.rows.map((row) => row.trigger), + [id], + ); + assert.equal(first.expiresAt, expiresAt); + crossOnStat = true; + assert.deepEqual(await read('unconfirmed'), { status: 'expired' }); + crossOnStat = false; + assert.deepEqual(await read('missing'), { status: 'expired' }); + clock = at + 10000; + await db.transaction((transaction) => + history.deleteExpired(at + 1000, transaction), + ); + assert.deepEqual(await history.visibleTriggers(11, [id]), []); + for (const kind of ['missing', 'skipped', 'unconfirmed']) + assert.deepEqual(await read(kind), { status: 'unavailable' }); + // Repeated reads do not reconstitute the missing plan or the old log entry. + assert.deepEqual(await read('unconfirmed'), { status: 'unavailable' }); + assert.deepEqual(await history.visibleTriggers(11, [id]), []); + }, + ); diff --git a/test/back/cron-macros.test.cjs b/test/back/cron-macros.test.cjs index ae102863..260704b5 100644 --- a/test/back/cron-macros.test.cjs +++ b/test/back/cron-macros.test.cjs @@ -1,7 +1,9 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const { createCronJob } = require('../../back/shared/cronScheduler'); -const { isValidCronSchedule } = require('../../back/shared/cronSchedule'); +const { createCronJob } = require('../../back/cron/scheduling/cronScheduler'); +const { + isValidCronSchedule, +} = require('../../back/cron/scheduling/cronSchedule'); // node-cron caches timezone formatters; model each deployment in a fresh process. if (!process.env.QL_MACRO_TEST_TZ) { @@ -9,30 +11,65 @@ if (!process.env.QL_MACRO_TEST_TZ) { test(`macro execution in ${tz}`, () => { const env = { ...process.env, TZ: tz, QL_MACRO_TEST_TZ: tz }; delete env.NODE_TEST_CONTEXT; - const result = require('node:child_process').spawnSync(process.execPath, + const result = require('node:child_process').spawnSync( + process.execPath, ['-r', 'ts-node/register/transpile-only', '--test', __filename], - { env, encoding: 'utf8' }); + { env, encoding: 'utf8' }, + ); assert.equal(result.status, 0, result.stdout + result.stderr); - assert.match(result.stdout, /@annually fires at the expected local times/); + assert.match( + result.stdout, + /@annually fires at the expected local times/, + ); }); } } -for (const tz of process.env.QL_MACRO_TEST_TZ ? [process.env.QL_MACRO_TEST_TZ] : []) { +for (const tz of process.env.QL_MACRO_TEST_TZ + ? [process.env.QL_MACRO_TEST_TZ] + : []) { for (const [macro, start, next] of [ - ['@annually', [2026, 11, 31, 23, 59, 59], [[2027, 0, 1, 0, 0, 0], [2028, 0, 1, 0, 0, 0]]], - ['@midnight', [2026, 8, 27, 23, 59, 59], [[2026, 8, 28, 0, 0, 0], [2026, 8, 29, 0, 0, 0]]], - ['@minutely', [2026, 8, 27, 12, 34, 59], [[2026, 8, 27, 12, 35, 0], [2026, 8, 27, 12, 36, 0]]], + [ + '@annually', + [2026, 11, 31, 23, 59, 59], + [ + [2027, 0, 1, 0, 0, 0], + [2028, 0, 1, 0, 0, 0], + ], + ], + [ + '@midnight', + [2026, 8, 27, 23, 59, 59], + [ + [2026, 8, 28, 0, 0, 0], + [2026, 8, 29, 0, 0, 0], + ], + ], + [ + '@minutely', + [2026, 8, 27, 12, 34, 59], + [ + [2026, 8, 27, 12, 35, 0], + [2026, 8, 27, 12, 36, 0], + ], + ], ]) { test(`${macro} fires at the expected local times in ${tz}`, async (t) => { const previousTZ = process.env.TZ; process.env.TZ = tz; - t.after(() => { if (previousTZ === undefined) delete process.env.TZ; else process.env.TZ = previousTZ; }); - t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date(...start) }); + t.after(() => { + if (previousTZ === undefined) delete process.env.TZ; + else process.env.TZ = previousTZ; + }); + t.mock.timers.enable({ + apis: ['Date', 'setTimeout', 'setInterval'], + now: new Date(...start), + }); const expected = next.map((parts) => new Date(...parts).getTime()); const actual = []; assert.equal(isValidCronSchedule(` ${macro} `), true); const job = createCronJob(macro, (date) => actual.push(date.getTime()), { - name: macro, logger: { warn() {}, error() {} }, + name: macro, + logger: { warn() {}, error() {} }, }); t.after(() => job.cancel()); for (const time of expected) { @@ -48,7 +85,15 @@ for (const tz of process.env.QL_MACRO_TEST_TZ ? [process.env.QL_MACRO_TEST_TZ] : } test('new aliases do not enable unknown macros or raw parser extensions', () => { - for (const schedule of ['@annuallyx', '@midnightx', '@minutelyx', '@secondly', '@reboot', 'H * * * *', '0 /5 * * * *']) { + for (const schedule of [ + '@annuallyx', + '@midnightx', + '@minutelyx', + '@secondly', + '@reboot', + 'H * * * *', + '0 /5 * * * *', + ]) { assert.equal(isValidCronSchedule(schedule), false, schedule); } }); diff --git a/test/back/cron-module-paths.test.cjs b/test/back/cron-module-paths.test.cjs new file mode 100644 index 00000000..42717a98 --- /dev/null +++ b/test/back/cron-module-paths.test.cjs @@ -0,0 +1,58 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const { spawnSync } = require('node:child_process'); + +test('the compiled orphan reporter loads cron history without a legacy forwarding entry', async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-reporter-path-')); + t.after(() => fs.rm(root, { recursive: true, force: true })); + for (const directory of ['shared', 'cron/settlement', 'data']) { + await fs.mkdir(path.join(root, directory), { recursive: true }); + } + const reporter = path.join(root, 'shared/managedExit.cjs'); + const report = path.join(root, 'report.json'); + await fs.copyFile(path.resolve('back/shared/managedExit.cjs'), reporter); + await fs.copyFile( + path.resolve('back/cron/settlement/exitReceipt.cjs'), + path.join(root, 'cron/settlement/exitReceipt.cjs'), + ); + await fs.writeFile( + path.join(root, 'cron/history.js'), + ` + exports.triggerHistory = () => ({ complete: (...args) => { + require('node:fs').writeFileSync(process.env.REPORT, JSON.stringify(args)); + return Promise.resolve(); + } }); + `, + ); + await fs.writeFile( + path.join(root, 'data/index.js'), + 'exports.sequelize = { close: async () => {} };', + ); + const time = Date.now(); + const result = spawnSync( + process.execPath, + [reporter, JSON.stringify({ code: 7, signal: null, time })], + { + env: { + ...process.env, + NODE_OPTIONS: '', + QL_TRIGGER_ID: 'compiled-report', + REPORT: report, + }, + encoding: 'utf8', + timeout: 10000, + }, + ); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(await fs.readFile(report, 'utf8')), [ + 'compiled-report', + 'failed', + null, + 7, + time, + 'legacy', + ]); +}); diff --git a/test/back/cron-parser-compatibility.test.cjs b/test/back/cron-parser-compatibility.test.cjs index eaf8c1a8..4c7eff9b 100644 --- a/test/back/cron-parser-compatibility.test.cjs +++ b/test/back/cron-parser-compatibility.test.cjs @@ -5,8 +5,8 @@ const { parseCronSchedule, isValidCronSchedule, getInvalidCronSchedules, -} = require('../../back/shared/cronSchedule'); -const { createCronJob } = require('../../back/shared/cronScheduler'); +} = require('../../back/cron/scheduling/cronSchedule'); +const { createCronJob } = require('../../back/cron/scheduling/cronScheduler'); const logger = { warn() {}, error() {} }; @@ -132,7 +132,7 @@ for (const [schedule, patterns, maxValidations] of [ test(`supported expressions skip field validation: ${schedule}`, () => { const load = require('../helpers/load-security-module.cjs'); const validations = []; - const isolated = load('back/shared/cronSchedule.ts', { + const isolated = load('back/cron/scheduling/cronSchedule.ts', { 'node-cron': { validate(pattern) { validations.push(pattern); diff --git a/test/back/cron-run-receipt.test.cjs b/test/back/cron-run-receipt.test.cjs new file mode 100644 index 00000000..de57cb32 --- /dev/null +++ b/test/back/cron-run-receipt.test.cjs @@ -0,0 +1,184 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { once } = require('node:events'); +const express = require('express'); +const { Sequelize, Transaction } = require('sequelize'); +const load = require('../helpers/load-security-module.cjs'); +const { + TriggerHistory, + installTriggerHistory, +} = require('../../back/cron/history'); + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-run-receipt-')); + const db = new Sequelize({ + dialect: 'sqlite', + storage: path.join(root, 'panel.sqlite'), + logging: false, + transactionType: Transaction.TYPES.IMMEDIATE, + }); + t.after(async () => { + await db.close(); + await fs.rm(root, { recursive: true, force: true }); + }); + const models = load('back/data/cron.ts', { './index': { sequelize: db } }); + const instances = load('back/data/runningInstance.ts', { + './index': { sequelize: db }, + }); + load('back/data/cronStats.ts', { './index': { sequelize: db } }); + await db.sync(); + await db.transaction((transaction) => installTriggerHistory(db, transaction)); + const history = new TriggerHistory(db); + const Service = load('back/services/cron.ts', { + '../data/cron': models, + '../data/runningInstance': instances, + '../config/index': { logPath: root }, + '../cron/execution/cronLimit': {}, + '../schedule/client': {}, + '../shared/logStreamManager': {}, + '../config/util': { + fileExist: async (file) => { + try { + await fs.access(file); + return true; + } catch { + return false; + } + }, + }, + }).default; + const service = new Service({ error() {}, info() {}, warn() {} }); + const launched = []; + service.runSingle = async (...args) => { + launched.push(args); + }; + await models.CrontabModel.bulkCreate([ + { + id: 1, + command: 'true', + isDisabled: 0, + status: 1, + allow_multiple_instances: 1, + }, + { + id: 2, + command: 'sleep 1', + isDisabled: 0, + status: 0, + pid: process.pid, + allow_multiple_instances: 0, + }, + ]); + return { root, db, models, history, service, launched }; +} + +test('run returns committed per-task receipts including overlap skips and preserves dispatch identity', async (t) => { + const { service, launched, history, models } = await fixture(t); + const receipts = await service.run([1, 2, 1, 999]); + assert.equal(receipts.length, 2); + const queued = receipts.find((row) => row.taskId === 1); + const skipped = receipts.find((row) => row.taskId === 2); + assert.deepEqual( + { ...queued, triggerId: 'id' }, + { taskId: 1, triggerId: 'id', state: 'queued', reason: null }, + ); + assert.deepEqual( + { ...skipped, triggerId: 'id' }, + { taskId: 2, triggerId: 'id', state: 'skipped', reason: 'overlap' }, + ); + for (const receipt of receipts) { + const [row] = await history.visibleTriggers(receipt.taskId, [ + receipt.triggerId, + ]); + assert.equal(row.state, receipt.state); + assert.equal(row.reason, receipt.reason); + } + assert.equal(launched.length, 1); + assert.equal(launched[0][0], 1); + assert.equal(launched[0][2], queued.triggerId); + assert.equal( + (await models.CrontabModel.findByPk(1)).queued_token, + launched[0][1], + ); + const [next] = await service.run([1]); + assert.notEqual(next.triggerId, queued.triggerId); + assert.deepEqual(await service.run([999]), []); + const [boot] = await service.run([1], 'boot'); + assert.equal( + (await history.visibleTriggers(1, [boot.triggerId]))[0].source, + 'boot', + ); +}); + +test('transaction failure publishes neither a receipt nor a dispatch', async (t) => { + const { service, launched, history, models } = await fixture(t); + t.mock.method(models.CrontabModel, 'update', async () => { + throw new Error('write failed'); + }); + await assert.rejects(service.run([1]), /write failed/); + assert.deepEqual(await history.recent(1, 0), []); + assert.deepEqual(launched, []); +}); + +test('HTTP run receipts select their own history and logs despite a newer sibling run', async (t) => { + const { service, history, db, root } = await fixture(t); + const router = express.Router(); + load('back/api/cron.ts', { + typedi: { Container: { get: () => service } }, + '../services/cron': class {}, + '../services/cronView': class {}, + '../schedule/client': { readiness: { ensureReady: async () => {} } }, + '../validation/schedule': { commonCronSchema: {} }, + '../cron/history': { triggerHistory: () => history }, + }).default(router); + const server = express() + .use(express.json()) + .use('/api', router) + .listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.after(() => { + server.closeAllConnections(); + server.close(); + }); + const base = `http://127.0.0.1:${server.address().port}/api/crons`; + const run = () => + fetch(`${base}/run`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: '[1]', + }).then((r) => r.json()); + const first = await run(); + const second = await run(); + assert.equal(first.code, 200); + const a = first.data[0].triggerId, + b = second.data[0].triggerId; + assert.notEqual(a, b); + for (const [id, name] of [ + [a, 'first'], + [b, 'second'], + ]) { + await fs.writeFile(path.join(root, `${name}.log`), `${name} execution\n`); + await db.query( + "UPDATE CronTriggers SET state='finished',exit_code=0,log_path=$file WHERE id=$id", + { bind: { id, file: `${name}.log` } }, + ); + } + const selected = await fetch( + `${base}/1/triggers?${new URLSearchParams({ ids: a })}`, + ).then((r) => r.json()); + assert.equal(selected.data.length, 1); + assert.equal(selected.data[0].id, a); + const log = await fetch( + `${base}/1/log?${new URLSearchParams({ triggerId: a })}`, + ).then((r) => r.json()); + assert.equal(log.triggerId, a); + assert.equal(log.data, 'first execution\n'); + const wrongTask = await fetch( + `${base}/2/log?${new URLSearchParams({ triggerId: a })}`, + ).then((r) => r.json()); + assert.equal(wrongTask.logStatus, 'notFound'); + assert.doesNotMatch(wrongTask.data, /first execution|second execution/); +}); diff --git a/test/back/cron-schedule-compatibility.test.cjs b/test/back/cron-schedule-compatibility.test.cjs index 7619111c..21f2cdb8 100644 --- a/test/back/cron-schedule-compatibility.test.cjs +++ b/test/back/cron-schedule-compatibility.test.cjs @@ -1,7 +1,9 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const { isValidCronSchedule } = require('../../back/shared/cronSchedule'); -const { createCronJob } = require('../../back/shared/cronScheduler'); +const { + isValidCronSchedule, +} = require('../../back/cron/scheduling/cronSchedule'); +const { createCronJob } = require('../../back/cron/scheduling/cronScheduler'); const legacy = require('../fixtures/legacy-cron.json'); const logger = { warn() {}, error() {} }; const flush = () => new Promise(setImmediate); @@ -10,7 +12,11 @@ test('validation preserves legacy syntax except the explicitly added macros', () const addedMacros = new Set(['@annually', '@midnight', '@minutely']); assert.ok(legacy.validation.length > 250); for (const { schedule, accepted } of legacy.validation) { - assert.equal(isValidCronSchedule(schedule), accepted || addedMacros.has(schedule), schedule); + assert.equal( + isValidCronSchedule(schedule), + accepted || addedMacros.has(schedule), + schedule, + ); } }); @@ -18,10 +24,20 @@ for (const sample of legacy.times) { test(`calendar compatibility: ${sample.schedule} from ${sample.currentDate}`, async (t) => { const previousTZ = process.env.TZ; process.env.TZ = 'UTC'; - t.after(() => { if (previousTZ === undefined) delete process.env.TZ; else process.env.TZ = previousTZ; }); - t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date(sample.currentDate) }); + t.after(() => { + if (previousTZ === undefined) delete process.env.TZ; + else process.env.TZ = previousTZ; + }); + t.mock.timers.enable({ + apis: ['Date', 'setTimeout', 'setInterval'], + now: new Date(sample.currentDate), + }); const actual = []; - const job = createCronJob(sample.schedule, (date) => actual.push(date.toISOString()), { name: 'calendar', logger }); + const job = createCronJob( + sample.schedule, + (date) => actual.push(date.toISOString()), + { name: 'calendar', logger }, + ); t.after(() => job.cancel()); for (const expected of sample.next) { t.mock.timers.tick(new Date(expected).getTime() - Date.now()); @@ -32,13 +48,22 @@ for (const sample of legacy.times) { } test('late callbacks catch up exactly once and cancellation destroys native tasks', async (t) => { - t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-09-27T00:00:00Z') }); + t.mock.timers.enable({ + apis: ['Date', 'setTimeout', 'setInterval'], + now: new Date('2026-09-27T00:00:00Z'), + }); const native = require('node-cron'); const before = native.getTasks().size; - const dates = [], warnings = []; - const job = createCronJob('* * * * * *', (date) => dates.push(date.getTime()), { - name: 'late', logger: { warn: (...args) => warnings.push(args), error() {} }, - }); + const dates = [], + warnings = []; + const job = createCronJob( + '* * * * * *', + (date) => dates.push(date.getTime()), + { + name: 'late', + logger: { warn: (...args) => warnings.push(args), error() {} }, + }, + ); t.after(() => job.cancel()); t.mock.timers.tick(8000); await flush(); @@ -53,12 +78,23 @@ test('late callbacks catch up exactly once and cancellation destroys native task }); test('callback rejection is logged and future executions continue', async (t) => { - t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-09-27T00:00:00Z') }); + t.mock.timers.enable({ + apis: ['Date', 'setTimeout', 'setInterval'], + now: new Date('2026-09-27T00:00:00Z'), + }); const errors = []; let count = 0; - const job = createCronJob('* * * * * *', async () => { count++; throw Error('callback failed'); }, { - name: 'failure', logger: { warn() {}, error: (...args) => errors.push(args) }, - }); + const job = createCronJob( + '* * * * * *', + async () => { + count++; + throw Error('callback failed'); + }, + { + name: 'failure', + logger: { warn() {}, error: (...args) => errors.push(args) }, + }, + ); t.after(() => job.cancel()); t.mock.timers.tick(1000); await flush(); diff --git a/test/back/cron-scheduler-routing.test.cjs b/test/back/cron-scheduler-routing.test.cjs index 2d7de6f8..64d676ab 100644 --- a/test/back/cron-scheduler-routing.test.cjs +++ b/test/back/cron-scheduler-routing.test.cjs @@ -1,26 +1,55 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const ts = require('typescript'); -const { ScheduleType } = require('../../back/interface/schedule'); +const load = require('../helpers/load-security-module.cjs'); +const { + makeCommand, + nodeCron, +} = require('../../back/cron/scheduling/cronScheduling'); + +function fixture(mode, failAt) { + const events = []; + const step = (name, ...args) => { + events.push([name, ...args]); + if (name === failAt) throw Error(`failed ${name}`); + }; + const Service = load('back/services/cron.ts', { + '../config/index': { crontabFile: '/unused' }, + '../config/util': {}, + '../data/cron': { + CrontabModel: { + sequelize: {}, + update: async (values, options) => step('saved', values, options.where), + }, + }, + '../data/runningInstance': {}, + '../cron/execution/cronLimit': {}, + '../shared/logStreamManager': {}, + '../schedule/client': { + readiness: { invalidate: () => step('invalidate') }, + }, + '../shared/utils': { + writeFileWithLock: async (file, contents) => + step('write', file, contents), + }, + '../cron/scheduling/systemScheduleAudit': { + stageSystemPlan: async (db, rules) => { + step('stage', rules); + return 42; + }, + confirmSystemPlan: async (db, plan) => step('confirm', plan), + suspendSystemPlan: async () => step('suspend'), + }, + child_process: { execFileSync: (...args) => step('install', ...args) }, + '../shared/i18n': { t: (value) => value }, + }).default; + const service = new Service({ error: (...args) => step('error', ...args) }); + Object.defineProperty(service, 'schedulerMode', { value: mode }); + return { service, events }; +} test('system and node modes route extended cron once and keep portable rules in crontab', async () => { - const source = fs.readFileSync('back/services/cron.ts', 'utf8'); - const begin = source.indexOf(' private isNodeCron('); - const end = source.indexOf(' private async getLogName', begin); - const saveBegin = source.indexOf(' private async setCrontab('); - const saveEnd = source.indexOf(' public importCrontab(', saveBegin); - const js = ts.transpileModule(`class Fixture {${source.slice(begin, end)}${source.slice(saveBegin, saveEnd)}}; module.exports = Fixture;`, { - compilerOptions: { target: ts.ScriptTarget.ES2020 }, - }).outputText; for (const mode of ['system', 'node']) { - const module = { exports: {} }; - let file = '', installs = 0; - new Function('module', 'process', 'execFileSync', 'ScheduleType', 'config', 'writeFileWithLock', 'CrontabModel', 'shellQuote', 'stageSystemPlan', 'confirmSystemPlan', 'suspendSystemPlan', js)( - module, { env: { QL_SCHEDULER: mode } }, () => { installs++; }, ScheduleType, - { crontabFile: '/unused' }, async (_, data) => { file = data; }, { update: async () => {} }, require('../../back/shared/shellQuote').shellQuote, async () => 1, async () => {}, async () => {}, - ); - const service = new module.exports(); + const { service, events } = fixture(mode); service.makeCommand = (row) => `task ${row.id}.js`; const rows = [ { id: 'plain', schedule: '*/5 0-23 * * 1,3' }, @@ -40,20 +69,221 @@ test('system and node modes route extended cron once and keep portable rules in { id: 'named', schedule: '0 0 * JAN MON' }, { id: 'macro', schedule: '@daily' }, { id: 'short', schedule: '*' }, - { id: 'extra', schedule: '* * * * *', extra_schedules: [{ schedule: '0 * * * *' }] }, + { + id: 'extra', + schedule: '* * * * *', + extra_schedules: [{ schedule: '0 * * * *' }], + }, + { id: 'wait', schedule: '* * * * *', max_queue_wait: 30 }, + { id: 'catchup', schedule: '* * * * *', catchup_seconds: 60 }, + { id: 'pending', schedule: '* * * * *', skip_if_pending: 1 }, { id: 'once', schedule: '@once' }, { id: 'boot', schedule: '@boot' }, ]; for (const row of rows) { const special = ['once', 'boot'].includes(row.id); const portable = ['plain', 'spaces'].includes(row.id); - assert.equal(service.shouldUseCronClient(row), !special && (mode === 'node' || !portable), `${mode}: ${row.id}`); + assert.equal( + service.shouldUseCronClient(row), + !special && (mode === 'node' || !portable), + `${mode}: ${row.id}`, + ); } await service.setCrontab({ data: rows, total: rows.length }); - assert.equal(installs, mode === 'system' ? 1 : 0); - for (const id of ['numeric-step', 'sunday-seven', 'day-step', 'restricted-days', 'restricted-week', 'annually', 'midnight', 'minutely', 'seconds', 'question', 'last', 'nth', 'named', 'macro', 'short', 'extra', 'once', 'boot']) { - const line = file.split('\n').find((line) => line.endsWith(`task ${id}.js`)); - assert.ok(line.startsWith('# '), `${mode}: ${id} cannot also run from system crontab`); + assert.deepEqual( + events.map(([name]) => name), + mode === 'system' + ? ['stage', 'write', 'install', 'confirm'] + : ['suspend', 'write'], + ); + const file = events.find(([name]) => name === 'write')[2]; + for (const id of rows + .filter((row) => !['plain', 'spaces'].includes(row.id)) + .map((row) => row.id)) { + const line = file + .split('\n') + .find((line) => line.endsWith(`task ${id}.js`)); + assert.ok( + line.startsWith('# '), + `${mode}: ${id} cannot also run from system crontab`, + ); + } + for (const id of ['plain', 'spaces']) { + const line = file.split('\n').find((line) => line.includes(`ID=${id} `)); + assert.ok(!line.startsWith('# ')); + assert.ok(line.includes('QL_SYSTEM_DISPATCHED=$(date +\\%s)')); + assert.ok( + line.includes( + 'QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh"', + ), + ); } } }); + +test('only acknowledged registrations become saved after system publication completes', async () => { + const { service, events } = fixture('system'); + const rows = [ + { id: 1, name: 'portable', command: 'a.js', schedule: '* * * * *' }, + { id: 2, command: 'b.js', schedule: '@minutely' }, + ]; + await service.setCrontab({ data: rows, total: rows.length }, [1]); + assert.deepEqual( + events.map(([name]) => name), + ['stage', 'write', 'install', 'confirm', 'saved'], + ); + assert.deepEqual(events[0][1], [ + { id: 1, name: 'portable', schedule: '* * * * *' }, + ]); + assert.deepEqual(events.at(-1), [ + 'saved', + { saved: true }, + { id: [1], saved: false }, + ]); +}); + +for (const mode of ['system', 'node']) { + for (const phase of mode === 'system' + ? ['stage', 'write', 'install', 'confirm'] + : ['suspend', 'write']) { + test(`${mode} publication failure at ${phase} invalidates readiness without acknowledging schedules`, async () => { + const { service, events } = fixture(mode, phase); + const rows = [ + { id: 1, command: 'a.js', schedule: '* * * * *' }, + { id: 2, command: 'b.js', schedule: '* * * * *', isDisabled: 1 }, + { id: 3, command: 'c.js', schedule: '@minutely' }, + { id: 4, command: 'd.js', schedule: '@boot' }, + ]; + await assert.rejects( + service.setCrontab({ data: rows, total: rows.length }, [1, 3]), + (error) => + error.status === 503 && /旧规则可能仍在运行/.test(error.message), + ); + const sequence = + mode === 'system' + ? ['stage', 'write', 'install', 'confirm'] + : ['suspend', 'write']; + assert.deepEqual( + events.map(([name]) => name), + [ + ...sequence.slice(0, sequence.indexOf(phase) + 1), + 'error', + 'invalidate', + ...(mode === 'system' ? ['saved'] : []), + ], + ); + if (mode === 'system') { + assert.deepEqual(events.at(-1), [ + 'saved', + { saved: false }, + { id: [1, 2] }, + ]); + } + }); + } +} + +test('manual and scheduled commands preserve the shell contract and Node registration fields', () => { + const doc = { + id: 7, + name: 'task', + command: 'ql repo https://example.test/repo', + schedule: '* * * * *', + log_name: "logs/it's a task", + work_dir: "/scripts/it's here", + task_before: 'echo before;\necho ready', + task_after: 'echo done', + extra_schedules: [{ schedule: '0 0 * * *' }], + max_queue_wait: 30, + catchup_seconds: 60, + skip_if_pending: 1, + recovery_from: 1234, + }; + const scheduled = makeCommand(doc); + assert.equal( + scheduled, + "QL_CRON_REVISION=1234 real_time=false no_tee=true ID=7 log_name='logs/it'\\''s a task' task_before='echo before;echo ready' task_after='echo done' work_dir='/scripts/it'\\''s here' ql repo https://example.test/repo", + ); + assert.equal( + makeCommand(doc, true), + scheduled.replace('real_time=false', 'real_time=true'), + ); + assert.deepEqual(nodeCron(doc, scheduled), { + id: '7', + name: 'task', + command: scheduled, + schedule: '* * * * *', + extra_schedules: [{ schedule: '0 0 * * *' }], + max_queue_wait: 30, + catchup_seconds: 60, + skip_if_pending: true, + recovery_from: 1234, + }); + assert.equal( + makeCommand({ id: 8, command: 'script.js' }), + 'real_time=false no_tee=true ID=8 task script.js', + ); + assert.equal( + makeCommand({ id: 8, command: 'task script.js', log_name: '/dev/null' }), + 'real_time=false no_tee=true ID=8 log_name=/dev/null task script.js', + ); +}); + +test('scheduler mode honors explicit overrides and probes crond again for automatic selection', (t) => { + const previous = process.env.QL_SCHEDULER; + t.after(() => { + if (previous === undefined) delete process.env.QL_SCHEDULER; + else process.env.QL_SCHEDULER = previous; + }); + let installed = true, + probes = 0; + const { schedulerMode } = load('back/cron/scheduling/cronScheduling.ts', { + child_process: { + execSync: (command, options) => { + probes++; + assert.equal(command, 'which crond'); + assert.deepEqual(options, { stdio: 'ignore' }); + if (!installed) throw Error('missing crond'); + }, + }, + }); + for (const mode of ['system', 'node']) { + process.env.QL_SCHEDULER = mode; + assert.equal(schedulerMode(), mode); + } + assert.equal(probes, 0); + delete process.env.QL_SCHEDULER; + assert.equal(schedulerMode(), 'system'); + installed = false; + assert.equal(schedulerMode(), 'node'); + process.env.QL_SCHEDULER = 'auto'; + installed = true; + assert.equal(schedulerMode(), 'system'); + assert.equal(probes, 3); +}); + +test('a gRPC worker still notifies its parent when system installation fails', async (t) => { + const previousType = process.env.SERVICE_TYPE; + const previousSend = process.send; + const messages = []; + process.env.SERVICE_TYPE = 'grpc'; + process.send = (message) => { + messages.push(message); + return true; + }; + t.after(() => { + if (previousType === undefined) delete process.env.SERVICE_TYPE; + else process.env.SERVICE_TYPE = previousType; + if (previousSend === undefined) delete process.send; + else process.send = previousSend; + }); + const { service } = fixture('system', 'install'); + await assert.rejects( + service.setCrontab({ + data: [{ id: 1, command: 'a.js', schedule: '* * * * *' }], + total: 1, + }), + (error) => error.status === 503, + ); + assert.deepEqual(messages, ['crontab-install-failed']); +}); diff --git a/test/back/cron-supervisor-log.test.cjs b/test/back/cron-supervisor-log.test.cjs index 32b5ccf0..621511b2 100644 --- a/test/back/cron-supervisor-log.test.cjs +++ b/test/back/cron-supervisor-log.test.cjs @@ -4,7 +4,10 @@ const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const { once } = require('node:events'); -const { spawnCronCommand, releaseCronCommand } = require('../../back/shared/cronCommandProcess'); +const { + spawnCronCommand, + releaseCronCommand, +} = require('../../back/cron/execution/cronCommandProcess'); const { observeChildProcess } = require('../../back/shared/childProcess'); const { shellQuote } = require('../../back/shared/shellQuote'); @@ -24,38 +27,72 @@ function nodeCommand(code) { return `${shellQuote(process.execPath)} -e ${shellQuote(code)}`; } -test('supervisor appends complete merged output once and preserves start telemetry and exit status', { timeout: 10000 }, async t => { - const root = await fixture(t); - const log = path.join(root, "log's $name.log"); - const output = '尾行 '.repeat(100000); - await fs.writeFile(log, 'previous\n'); - let started; - let forwarded = ''; - const child = spawnCronCommand(nodeCommand(`const fs=require('node:fs');const b=Buffer.from('尾行 '.repeat(100000));let i=0;while(i { started = value; }, log); - const result = await observeChildProcess(child, { - onStart: () => releaseCronCommand(child), - onStdout: async text => { forwarded += text; }, - onStderr: async text => { forwarded += text; }, - }).completed; - assert.equal(result.code, 17); - assert.equal(result.error, undefined); - assert.equal(forwarded, ''); - assert.ok(Number.isInteger(started) && Math.abs(Date.now() - started) < 10000); - assert.equal(await fs.readFile(log, 'utf8'), 'previous\n' + output + 'STDERR\n'); -}); +test( + 'supervisor appends complete merged output once and preserves start telemetry and exit status', + { timeout: 10000 }, + async (t) => { + const root = await fixture(t); + const log = path.join(root, "log's $name.log"); + const output = '尾行 '.repeat(100000); + await fs.writeFile(log, 'previous\n'); + let started; + let forwarded = ''; + const child = spawnCronCommand( + nodeCommand( + `const fs=require('node:fs');const b=Buffer.from('尾行 '.repeat(100000));let i=0;while(i { + started = value; + }, + log, + ); + const result = await observeChildProcess(child, { + onStart: () => releaseCronCommand(child), + onStdout: async (text) => { + forwarded += text; + }, + onStderr: async (text) => { + forwarded += text; + }, + }).completed; + assert.equal(result.code, 17); + assert.equal(result.error, undefined); + assert.equal(forwarded, ''); + assert.ok( + Number.isInteger(started) && Math.abs(Date.now() - started) < 10000, + ); + assert.equal( + await fs.readFile(log, 'utf8'), + 'previous\n' + output + 'STDERR\n', + ); + }, +); for (const fault of ['open', 'full']) { for (const disconnected of [false, true]) { - test(`log ${fault} failure drains output without interrupting command (reader disconnected=${disconnected})`, - { timeout: 10000, skip: fault === 'full' && process.platform !== 'linux' }, async t => { + test( + `log ${fault} failure drains output without interrupting command (reader disconnected=${disconnected})`, + { + timeout: 10000, + skip: fault === 'full' && process.platform !== 'linux', + }, + async (t) => { const root = await fixture(t); const marker = path.join(root, 'completed'); // A directory fails at open; /dev/full opens but every write fails ENOSPC. const log = fault === 'open' ? root : '/dev/full'; - const code = `const fs=require('node:fs');const b=Buffer.alloc(65536,120);for(let n=0;n<64;n++){let i=0;while(i releaseCronCommand(child), - onStderr: async text => { errors += text; }, + onStderr: async (text) => { + errors += text; + }, }).completed; assert.equal(result.error, undefined); - assert.equal((errors.match(/Could not write command log/g) || []).length, 1); - assert.match(errors, fault === 'full' ? /No space left/ : /Is a directory/); + assert.equal( + (errors.match(/Could not write command log/g) || []).length, + 1, + ); + assert.match( + errors, + fault === 'full' ? /No space left/ : /Is a directory/, + ); } assert.equal(result.code, 0); assert.equal(result.signal, null); assert.equal(await fs.readFile(marker, 'utf8'), 'completed'); - }); + }, + ); } } -test('cancelled launch neither creates a log nor executes the command', { timeout: 10000 }, async t => { - const root = await fixture(t); - const marker = path.join(root, 'executed'); - const log = path.join(root, 'cancelled.log'); - const child = spawnCronCommand(nodeCommand(`require('node:fs').writeFileSync(${JSON.stringify(marker)},'bad')`), - 'log-cancel', undefined, log); - const closed = once(child, 'close'); - child.stdin.end(); - assert.equal((await closed)[0], 125); - await assert.rejects(fs.access(log), { code: 'ENOENT' }); - await assert.rejects(fs.access(marker), { code: 'ENOENT' }); -}); +test( + 'cancelled launch neither creates a log nor executes the command', + { timeout: 10000 }, + async (t) => { + const root = await fixture(t); + const marker = path.join(root, 'executed'); + const log = path.join(root, 'cancelled.log'); + const child = spawnCronCommand( + nodeCommand( + `require('node:fs').writeFileSync(${JSON.stringify(marker)},'bad')`, + ), + 'log-cancel', + undefined, + log, + ); + const closed = once(child, 'close'); + child.stdin.end(); + assert.equal((await closed)[0], 125); + await assert.rejects(fs.access(log), { code: 'ENOENT' }); + await assert.rejects(fs.access(marker), { code: 'ENOENT' }); + }, +); diff --git a/test/back/cron-validation.test.cjs b/test/back/cron-validation.test.cjs index 54f2fab8..b7b6d00c 100644 --- a/test/back/cron-validation.test.cjs +++ b/test/back/cron-validation.test.cjs @@ -74,7 +74,9 @@ test('create and update reject invalid extra schedules before calling the servic const load = require('../helpers/load-security-module.cjs'); const mutations = []; const service = { - async status(value) { return value; }, + async status(value) { + return value; + }, async create(value) { mutations.push(value); return { id: 1, ...value }; @@ -113,17 +115,31 @@ test('create and update reject invalid extra schedules before calling the servic // Released CLI wrappers reuse this execution_id for start and exit; both must reach the same receipt. const uuid = require('node:crypto').randomUUID(); - const statusRequest = (status, extra = {}) => fetch(`http://127.0.0.1:${server.address().port}/crons/status`, { - method: 'PUT', headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ ids: [1], pid: '122', status, execution_id: `legacy-system:123:${uuid}`, ...extra }), - }); + const statusRequest = (status, extra = {}) => + fetch(`http://127.0.0.1:${server.address().port}/crons/status`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + ids: [1], + pid: '122', + status, + execution_id: `legacy-system:123:${uuid}`, + ...extra, + }), + }); for (const status of ['0', '1']) { const res = await statusRequest(status); assert.equal(res.status, 200); assert.equal((await res.json()).data.trigger_id, `system-cli-123-${uuid}`); } - assert.equal((await statusRequest('1', { trigger_id: 'another' })).status, 400); - assert.equal((await statusRequest('1', { execution_id: 'broken' })).status, 400); + assert.equal( + (await statusRequest('1', { trigger_id: 'another' })).status, + 400, + ); + assert.equal( + (await statusRequest('1', { execution_id: 'broken' })).status, + 400, + ); for (const method of ['POST', 'PUT']) { const payload = { @@ -184,9 +200,16 @@ test('create and update reject invalid extra schedules before calling the servic }); test('saving a migrated task accepts a null pending policy and rejects invalid input', () => { - const task = { name: 'legacy', command: 'task old.sh', schedule: '1 * * * *' }; + const task = { + name: 'legacy', + command: 'task old.sh', + schedule: '1 * * * *', + }; for (const value of [null, false, true]) { - assert.equal(schema.validate({ ...task, skip_if_pending: value }).error, undefined); + assert.equal( + schema.validate({ ...task, skip_if_pending: value }).error, + undefined, + ); } assert.ok(schema.validate({ ...task, skip_if_pending: 'invalid' }).error); }); diff --git a/test/back/database-bootstrap.test.cjs b/test/back/database-bootstrap.test.cjs index 6ed6bc21..630a9d8b 100644 --- a/test/back/database-bootstrap.test.cjs +++ b/test/back/database-bootstrap.test.cjs @@ -19,7 +19,9 @@ function fixture(t) { fs.mkdirSync(path.join(dir, 'data/syslog'), { recursive: true }); fs.writeFileSync(path.join(dir, '.env'), ''); const wrapper = path.join(dir, 'parent.cjs'); - fs.writeFileSync(wrapper, ` + fs.writeFileSync( + wrapper, + ` const cp = require('node:child_process'); const original = cp.fork; cp.fork = (...args) => { @@ -35,24 +37,39 @@ function fixture(t) { console.error(error.message); process.exitCode = 1; }).finally(() => { if (process.connected) process.disconnect(); }); - `); + `, + ); return { dir, storage: path.join(dir, 'data/db/database.sqlite'), run(entrypoint = initializer) { const child = fork(wrapper, [entrypoint], { - env: { ...process.env, QL_DIR: dir, QL_DATA_DIR: path.join(dir, 'data') }, + env: { + ...process.env, + QL_DIR: dir, + QL_DATA_DIR: path.join(dir, 'data'), + }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'], }); const messages = []; let output = ''; child.on('message', (message) => messages.push(message)); - child.stdout.on('data', (data) => { output += data; }); - child.stderr.on('data', (data) => { output += data; }); - t.after(() => { - if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); + child.stdout.on('data', (data) => { + output += data; }); - const done = once(child, 'close').then(([code, signal]) => ({ code, signal, output, messages })); + child.stderr.on('data', (data) => { + output += data; + }); + t.after(() => { + if (child.exitCode === null && child.signalCode === null) + child.kill('SIGKILL'); + }); + const done = once(child, 'close').then(([code, signal]) => ({ + code, + signal, + output, + messages, + })); return { child, done, messages }; }, }; @@ -62,132 +79,242 @@ async function waitFor(predicate) { const deadline = Date.now() + 10000; while (!predicate()) { assert.ok(Date.now() < deadline, 'timed out waiting for child'); - await new Promise(resolve => setTimeout(resolve, 20)); + await new Promise((resolve) => setTimeout(resolve, 20)); } } -test('isolated initialization creates a fresh database and does not retain ORM modules in the parent', { timeout: 20000 }, async t => { - const f = fixture(t); - const result = await f.run().done; - assert.equal(result.code, 0, result.output); - const done = result.messages.find(message => message.done); - assert.ok(done); - assert.equal(done.modules.some(file => /[\\/]sequelize[\\/]|[\\/]data[\\/]index\.ts$/.test(file)), false); - const db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false }); - try { - const tables = await db.getQueryInterface().showAllTables(); - for (const table of ['Crontabs', 'Envs', 'RunningInstances', 'SchemaMigrations', 'CronLegacyExitBookings']) assert.ok(tables.includes(table), table); - const migrations = await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT }); - assert.ok(migrations.some(row => row.id === 'preserve-pruned-bound-exits-v1')); - assert.equal(migrations.length, 27); - } finally { await db.close(); } -}); - -test('isolated initialization upgrades an existing database and remains idempotent', { timeout: 30000 }, async t => { - const f = fixture(t); - let db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false }); - await db.query('CREATE TABLE Crontabs (id INTEGER PRIMARY KEY, name TEXT)'); - await db.query("INSERT INTO Crontabs (id, name) VALUES (1, 'keep-me')"); - await db.close(); - for (let i = 0; i < 2; i++) { +test( + 'isolated initialization creates a fresh database and does not retain ORM modules in the parent', + { timeout: 20000 }, + async (t) => { + const f = fixture(t); const result = await f.run().done; assert.equal(result.code, 0, result.output); - } - db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false }); - try { - const rows = await db.query('SELECT * FROM Crontabs', { type: QueryTypes.SELECT }); - assert.equal(rows[0].name, 'keep-me'); - assert.ok(Object.hasOwn(rows[0], 'queued_token')); - assert.ok(Object.hasOwn(await db.getQueryInterface().describeTable('CrontabStats'), 'fixed_max_time')); - const migrations = await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT }); - assert.ok(migrations.some(row => row.id === 'preserve-pruned-bound-exits-v1')); - assert.equal(migrations.length, 27); - } finally { await db.close(); } -}); + const done = result.messages.find((message) => message.done); + assert.ok(done); + assert.equal( + done.modules.some((file) => + /[\\/]sequelize[\\/]|[\\/]data[\\/]index\.ts$/.test(file), + ), + false, + ); + const db = new Sequelize({ + dialect: 'sqlite', + storage: f.storage, + logging: false, + }); + try { + const tables = await db.getQueryInterface().showAllTables(); + for (const table of [ + 'Crontabs', + 'Envs', + 'RunningInstances', + 'SchemaMigrations', + 'CronLegacyExitBookings', + ]) + assert.ok(tables.includes(table), table); + const migrations = await db.query('SELECT id FROM SchemaMigrations', { + type: QueryTypes.SELECT, + }); + assert.ok( + migrations.some((row) => row.id === 'preserve-pruned-bound-exits-v1'), + ); + assert.equal(migrations.length, 27); + } finally { + await db.close(); + } + }, +); -test('database errors and missing initializer files reject startup', { timeout: 20000 }, async t => { - const f = fixture(t); - fs.writeFileSync(f.storage, 'invalid SQLite database'); - const invalid = await f.run().done; - assert.equal(invalid.code, 1); - assert.match(invalid.output, /SQLITE_NOTADB/); - assert.equal(invalid.messages.some(message => message.done), false); - const missing = await f.run(path.join(f.dir, 'missing.cjs')).done; - assert.equal(missing.code, 1); - assert.match(missing.output, /MODULE_NOT_FOUND/); -}); +test( + 'isolated initialization upgrades an existing database and remains idempotent', + { timeout: 30000 }, + async (t) => { + const f = fixture(t); + let db = new Sequelize({ + dialect: 'sqlite', + storage: f.storage, + logging: false, + }); + await db.query('CREATE TABLE Crontabs (id INTEGER PRIMARY KEY, name TEXT)'); + await db.query("INSERT INTO Crontabs (id, name) VALUES (1, 'keep-me')"); + await db.close(); + for (let i = 0; i < 2; i++) { + const result = await f.run().done; + assert.equal(result.code, 0, result.output); + } + db = new Sequelize({ + dialect: 'sqlite', + storage: f.storage, + logging: false, + }); + try { + const rows = await db.query('SELECT * FROM Crontabs', { + type: QueryTypes.SELECT, + }); + assert.equal(rows[0].name, 'keep-me'); + assert.ok(Object.hasOwn(rows[0], 'queued_token')); + assert.ok( + Object.hasOwn( + await db.getQueryInterface().describeTable('CrontabStats'), + 'fixed_max_time', + ), + ); + const migrations = await db.query('SELECT id FROM SchemaMigrations', { + type: QueryTypes.SELECT, + }); + assert.ok( + migrations.some((row) => row.id === 'preserve-pruned-bound-exits-v1'), + ); + assert.equal(migrations.length, 27); + } finally { + await db.close(); + } + }, +); + +test( + 'database errors and missing initializer files reject startup', + { timeout: 20000 }, + async (t) => { + const f = fixture(t); + fs.writeFileSync(f.storage, 'invalid SQLite database'); + const invalid = await f.run().done; + assert.equal(invalid.code, 1); + assert.match(invalid.output, /SQLITE_NOTADB/); + assert.equal( + invalid.messages.some((message) => message.done), + false, + ); + const missing = await f.run(path.join(f.dir, 'missing.cjs')).done; + assert.equal(missing.code, 1); + assert.match(missing.output, /MODULE_NOT_FOUND/); + }, +); for (const signal of ['SIGTERM', 'SIGINT']) { - test(`startup ${signal} terminates the initializer and never reports success`, { timeout: 15000 }, async t => { - const f = fixture(t); - const target = path.join(f.dir, 'waiting.cjs'); - const ready = path.join(f.dir, 'ready'); - fs.writeFileSync(target, ` - require('node:fs').writeFileSync(${JSON.stringify(ready)}, String(process.pid)); + test( + `startup ${signal} terminates the initializer and never reports success`, + { timeout: 15000 }, + async (t) => { + const f = fixture(t); + const target = path.join(f.dir, 'waiting.cjs'); + const ready = path.join(f.dir, 'ready'); + fs.writeFileSync( + target, + ` + require('node:fs').writeFileSync(${JSON.stringify( + ready, + )}, String(process.pid)); setInterval(() => {}, 1000); - `); - const running = f.run(target); - await waitFor(() => fs.existsSync(ready)); - const pid = Number(fs.readFileSync(ready, 'utf8')); - running.child.kill(signal); - const result = await running.done; - assert.equal(result.code, 1, result.output); - assert.match(result.output, new RegExp(signal)); - assert.equal(result.messages.some(message => message.done), false); - assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' }); - }); + `, + ); + const running = f.run(target); + await waitFor(() => fs.existsSync(ready)); + const pid = Number(fs.readFileSync(ready, 'utf8')); + running.child.kill(signal); + const result = await running.done; + assert.equal(result.code, 1, result.output); + assert.match(result.output, new RegExp(signal)); + assert.equal( + result.messages.some((message) => message.done), + false, + ); + assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' }); + }, + ); } -test('a database initializer blocked on SQLite exits when its parent disappears', { timeout: 20000 }, async t => { - const f = fixture(t); - const db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false }); - await db.query('BEGIN EXCLUSIVE'); - try { - const running = f.run(); - await waitFor(() => running.messages.some(message => message.childPid)); - const pid = running.messages.find(message => message.childPid).childPid; - // Allow the real initializer to enter the database operation before losing IPC. - await new Promise(resolve => setTimeout(resolve, 1000)); - running.child.kill('SIGKILL'); - await running.done; - await waitFor(() => { - try { process.kill(pid, 0); return false; } - catch (error) { if (error.code === 'ESRCH') return true; throw error; } +test( + 'a database initializer blocked on SQLite exits when its parent disappears', + { timeout: 20000 }, + async (t) => { + const f = fixture(t); + const db = new Sequelize({ + dialect: 'sqlite', + storage: f.storage, + logging: false, }); - } finally { - await db.query('ROLLBACK'); - await db.close(); - } -}); + await db.query('BEGIN EXCLUSIVE'); + try { + const running = f.run(); + await waitFor(() => running.messages.some((message) => message.childPid)); + const pid = running.messages.find((message) => message.childPid).childPid; + // Allow the real initializer to enter the database operation before losing IPC. + await new Promise((resolve) => setTimeout(resolve, 1000)); + running.child.kill('SIGKILL'); + await running.done; + await waitFor(() => { + try { + process.kill(pid, 0); + return false; + } catch (error) { + if (error.code === 'ESRCH') return true; + throw error; + } + }); + } finally { + await db.query('ROLLBACK'); + await db.close(); + } + }, +); test('application waits for isolated initialization and does not fork workers after a failure', async () => { const file = path.resolve('back/app.ts'); const source = fs.readFileSync(file, 'utf8'); - const compiled = ts.transpileModule(source.slice(0, source.indexOf('\nconst app = new Application();')) + '\nmodule.exports = Application;', { - compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true }, - }).outputText; + const compiled = ts.transpileModule( + source.slice(0, source.indexOf('\nconst app = new Application();')) + + '\nmodule.exports = Application;', + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }, + ).outputText; for (const fail of [false, true]) { let complete; - const pending = new Promise((resolve, reject) => { complete = () => fail ? reject(new Error('migration failed')) : resolve(); }); - const exits = [], calls = []; + const pending = new Promise((resolve, reject) => { + complete = () => + fail ? reject(new Error('migration failed')) : resolve(); + }); + const exits = [], + calls = []; const localRequire = createRequire(file); const mocks = { cluster: { isPrimary: true }, './config': {}, './loaders/logger': { error() {} }, - './shared/startupProcess': { runStartupProcess: entry => { assert.equal(entry, initializer); return pending; } }, + './shared/startupProcess': { + runStartupProcess: (entry) => { + assert.equal(entry, initializer); + return pending; + }, + }, }; - const req = Object.assign(name => { - calls.push(name); - return Object.hasOwn(mocks, name) ? mocks[name] : localRequire(name); - }, { resolve: localRequire.resolve }); + const req = Object.assign( + (name) => { + calls.push(name); + return Object.hasOwn(mocks, name) ? mocks[name] : localRequire(name); + }, + { resolve: localRequire.resolve }, + ); const module = { exports: {} }; - new Function('require', 'module', 'exports', 'process', compiled)(req, module, module.exports, { exit: code => exits.push(code) }); + new Function('require', 'module', 'exports', 'process', compiled)( + req, + module, + module.exports, + { exit: (code) => exits.push(code) }, + ); const app = new module.exports(); let started = false; - app.startMasterProcess = () => { started = true; }; + app.startMasterProcess = () => { + started = true; + }; const start = app.start(); - await new Promise(resolve => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); assert.equal(started, false); complete(); await start; diff --git a/test/back/dev-startup.test.cjs b/test/back/dev-startup.test.cjs index 83a0cd2d..8d6d4ff1 100644 --- a/test/back/dev-startup.test.cjs +++ b/test/back/dev-startup.test.cjs @@ -10,9 +10,15 @@ test('development launcher preserves cluster loading, decorator metadata and sou const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-dev-start-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); fs.mkdirSync(path.join(root, 'back')); - fs.symlinkSync(path.resolve('node_modules'), path.join(root, 'node_modules'), 'dir'); + fs.symlinkSync( + path.resolve('node_modules'), + path.join(root, 'node_modules'), + 'dir', + ); fs.copyFileSync('back/tsconfig.json', path.join(root, 'back/tsconfig.json')); - fs.writeFileSync(path.join(root, 'back/app.ts'), ` + fs.writeFileSync( + path.join(root, 'back/app.ts'), + ` import 'reflect-metadata'; import cluster from 'node:cluster'; class Dependency {} @@ -29,18 +35,24 @@ test('development launcher preserves cluster loading, decorator metadata and sou stack: new Error('source location').stack })); process.disconnect!(); } - `); + `, + ); const config = JSON.parse(fs.readFileSync('nodemon.json', 'utf8')); const [command, ...args] = config.execMap.ts.split(' '); assert.equal(command, 'node'); const env = { ...process.env, ...config.env }; delete env.NODE_OPTIONS; const result = spawnSync(process.execPath, [...args, 'back/app.ts'], { - cwd: root, env, encoding: 'utf8', timeout: 20000, + cwd: root, + env, + encoding: 'utf8', + timeout: 20000, }); assert.ifError(result.error); assert.equal(result.status, 0, result.stdout + result.stderr); - const output = JSON.parse(result.stdout.split('FIXTURE_RESULT=')[1].split('\n')[0]); + const output = JSON.parse( + result.stdout.split('FIXTURE_RESULT=')[1].split('\n')[0], + ); assert.equal(output.value, 42); assert.equal(output.metadata, true); assert.match(output.stack, /back[/\\]app\.ts:\d+:\d+/); @@ -67,16 +79,41 @@ test('startup timing preserves results and failures with timing enabled or disab const value = {}; const failure = new Error('startup failed'); let calls = 0; - assert.equal(await startupStage('success', async () => { calls++; return value; }), value); - await assert.rejects(startupStage('failure', async () => { calls++; throw failure; }), - (error) => error === failure); - await assert.rejects(startupStage('sync-failure', () => { calls++; throw failure; }), - (error) => error === failure); + assert.equal( + await startupStage('success', async () => { + calls++; + return value; + }), + value, + ); + await assert.rejects( + startupStage('failure', async () => { + calls++; + throw failure; + }), + (error) => error === failure, + ); + await assert.rejects( + startupStage('sync-failure', () => { + calls++; + throw failure; + }), + (error) => error === failure, + ); assert.equal(calls, 3); assert.equal(logs.length, enabled === '1' ? 3 : 0); if (enabled === '1') { - for (const [index, stage] of ['success', 'failure', 'sync-failure'].entries()) { - assert.match(logs[index], new RegExp('^\\[boot:timing\\] grpc:' + stage + ' \\d+ms \\(PID: \\d+\\)$')); + for (const [index, stage] of [ + 'success', + 'failure', + 'sync-failure', + ].entries()) { + assert.match( + logs[index], + new RegExp( + '^\\[boot:timing\\] grpc:' + stage + ' \\d+ms \\(PID: \\d+\\)$', + ), + ); } } } @@ -84,18 +121,33 @@ test('startup timing preserves results and failures with timing enabled or disab test('frontend gzip assets are enabled for production only', () => { const source = ts.transpileModule(fs.readFileSync('.umirc.ts', 'utf8'), { - compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + }, }).outputText; for (const mode of ['development', 'production']) { const module = { exports: {} }; - class Compression { constructor(options) { this.options = options; } } + class Compression { + constructor(options) { + this.options = options; + } + } new Function('require', 'module', 'exports', 'process', source)( - (name) => name === '@umijs/max' ? { defineConfig: (config) => config } : Compression, - module, module.exports, { env: { NODE_ENV: mode } }, + (name) => + name === '@umijs/max' + ? { defineConfig: (config) => config } + : Compression, + module, + module.exports, + { env: { NODE_ENV: mode } }, ); const plugins = []; - module.exports.default.chainWebpack({ plugin: (name) => ({ use: (plugin) => plugins.push({ name, plugin }) }) }); + module.exports.default.chainWebpack({ + plugin: (name) => ({ use: (plugin) => plugins.push({ name, plugin }) }), + }); assert.equal(plugins.length, mode === 'production' ? 1 : 0); - if (mode === 'production') assert.equal(plugins[0].plugin.options.algorithm, 'gzip'); + if (mode === 'production') + assert.equal(plugins[0].plugin.options.algorithm, 'gzip'); } }); diff --git a/test/back/directory-page.test.cjs b/test/back/directory-page.test.cjs index 01b3e036..1b153dd0 100644 --- a/test/back/directory-page.test.cjs +++ b/test/back/directory-page.test.cjs @@ -3,51 +3,110 @@ const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); -const { checkDirectoryVersions, readDirectoryPage } = require('../../back/shared/directoryPage'); +const { + checkDirectoryVersions, + readDirectoryPage, +} = require('../../back/shared/directoryPage'); -test('directory cursors survive inserts and deletes and search reaches unloaded folders', async t => { +test('directory cursors survive inserts and deletes and search reaches unloaded folders', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-file-page-')); t.after(() => fs.rm(root, { recursive: true, force: true })); - await fs.mkdir(path.join(root,'dir')); - await fs.mkdir(path.join(root,'.tmp')); - await fs.writeFile(path.join(root,'.tmp','secret'),''); - await fs.symlink(os.tmpdir(), path.join(root,'outside')); - for (const name of ['a','c','e','dir/needle#&.js','dir/needle2.js']) await fs.writeFile(path.join(root,name),'1'); - const read = (after='', search='', dir='', folders=false, newest=false) => readDirectoryPage(root,['.tmp'],dir,after,search,folders,newest,2); + await fs.mkdir(path.join(root, 'dir')); + await fs.mkdir(path.join(root, '.tmp')); + await fs.writeFile(path.join(root, '.tmp', 'secret'), ''); + await fs.symlink(os.tmpdir(), path.join(root, 'outside')); + for (const name of ['a', 'c', 'e', 'dir/needle#&.js', 'dir/needle2.js']) + await fs.writeFile(path.join(root, name), '1'); + const read = ( + after = '', + search = '', + dir = '', + folders = false, + newest = false, + ) => + readDirectoryPage(root, ['.tmp'], dir, after, search, folders, newest, 2); const first = await read(); - assert.deepEqual(first.data.map(x=>x.key),['dir','a']); - await fs.unlink(path.join(root,'a')); - await fs.writeFile(path.join(root,'b'),'2'); + assert.deepEqual( + first.data.map((x) => x.key), + ['dir', 'a'], + ); + await fs.unlink(path.join(root, 'a')); + await fs.writeFile(path.join(root, 'b'), '2'); const second = await read(first.next); - assert.deepEqual(second.data.map(x=>x.key),['b','c']); - assert.deepEqual((await read(second.next)).data.map(x=>x.key),['e']); - assert.deepEqual((await read('','','',false,true)).data.map(x=>x.key),['dir','e']); - assert.deepEqual((await read('','','',true)).data.map(x=>x.key),['dir']); - assert.deepEqual((await read('','needle')).data.map(x=>x.key),['dir/needle#&.js','dir/needle2.js']); - assert.deepEqual((await read('','secret')).data,[]); - for (const dir of ['../','.tmp','outside']) await assert.rejects(read('','',dir), { status:403 }); + assert.deepEqual( + second.data.map((x) => x.key), + ['b', 'c'], + ); + assert.deepEqual( + (await read(second.next)).data.map((x) => x.key), + ['e'], + ); + assert.deepEqual( + (await read('', '', '', false, true)).data.map((x) => x.key), + ['dir', 'e'], + ); + assert.deepEqual( + (await read('', '', '', true)).data.map((x) => x.key), + ['dir'], + ); + assert.deepEqual( + (await read('', 'needle')).data.map((x) => x.key), + ['dir/needle#&.js', 'dir/needle2.js'], + ); + assert.deepEqual((await read('', 'secret')).data, []); + for (const dir of ['../', '.tmp', 'outside']) + await assert.rejects(read('', '', dir), { status: 403 }); }); -test('a sparse cross-directory search resumes after an empty batch', async t => { +test('a sparse cross-directory search resumes after an empty batch', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-file-search-')); t.after(() => fs.rm(root, { recursive: true, force: true })); - for (let i=0; i<513; i++) await fs.writeFile(path.join(root, 'a'+i), ''); - await fs.mkdir(path.join(root,'z')); await fs.writeFile(path.join(root,'z','needle'),''); - const page = after => readDirectoryPage(root,[], '',after,'needle',false,false); + for (let i = 0; i < 513; i++) + await fs.writeFile(path.join(root, 'a' + i), ''); + await fs.mkdir(path.join(root, 'z')); + await fs.writeFile(path.join(root, 'z', 'needle'), ''); + const page = (after) => + readDirectoryPage(root, [], '', after, 'needle', false, false); const first = await page(''); - assert.deepEqual(first.data,[]); assert.ok(first.next); - assert.deepEqual((await page(first.next)).data.map(x=>x.key),['z/needle']); + assert.deepEqual(first.data, []); + assert.ok(first.next); + assert.deepEqual( + (await page(first.next)).data.map((x) => x.key), + ['z/needle'], + ); }); -test('a delayed terminal page detects changes on either side of its cursor, including a previously traversed sibling', async t => { +test('a delayed terminal page detects changes on either side of its cursor, including a previously traversed sibling', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-moved-page-')); t.after(() => fs.rm(root, { recursive: true, force: true })); for (const dir of ['a', 'b']) await fs.mkdir(path.join(root, dir)); - for (const key of ['a/one.js', 'b/two.js']) await fs.writeFile(path.join(root, key), key); - const first = await readDirectoryPage(root, [], '', '', '.js', false, false, 1); - const last = await readDirectoryPage(root, [], '', first.next, '.js', false, false, 2); + for (const key of ['a/one.js', 'b/two.js']) + await fs.writeFile(path.join(root, key), key); + const first = await readDirectoryPage( + root, + [], + '', + '', + '.js', + false, + false, + 1, + ); + const last = await readDirectoryPage( + root, + [], + '', + first.next, + '.js', + false, + false, + 2, + ); assert.equal(last.next, null); - assert.deepEqual(last.data.map(r => r.key), ['b/two.js']); + assert.deepEqual( + last.data.map((r) => r.key), + ['b/two.js'], + ); const versions = [...first.versions, ...last.versions]; assert.equal(await checkDirectoryVersions(root, [], versions), true); await fs.rename(path.join(root, 'b/two.js'), path.join(root, 'a/first.js')); @@ -55,11 +114,14 @@ test('a delayed terminal page detects changes on either side of its cursor, incl await fs.writeFile(path.join(root, 'b/new.js'), 'new'); assert.equal(await checkDirectoryVersions(root, [], versions), false); const fresh = await readDirectoryPage(root, [], '', '', '.js', false, false); - assert.deepEqual(fresh.data.map(r => r.key), ['a/first.js', 'b/new.js']); + assert.deepEqual( + fresh.data.map((r) => r.key), + ['a/first.js', 'b/new.js'], + ); assert.equal(await checkDirectoryVersions(root, [], fresh.versions), true); }); -test('deleting and replacing the open directory invalidates its pages and a missing path can be checked again', async t => { +test('deleting and replacing the open directory invalidates its pages and a missing path can be checked again', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-replaced-page-')); t.after(() => fs.rm(root, { recursive: true, force: true })); const dir = path.join(root, 'open'); @@ -75,5 +137,15 @@ test('deleting and replacing the open directory invalidates its pages and a miss assert.equal(await checkDirectoryVersions(root, [], missing.versions), false); assert.equal(await checkDirectoryVersions(root, [], before.versions), false); await fs.symlink(os.tmpdir(), path.join(root, 'external')); - assert.equal(await checkDirectoryVersions(root, [], [['external', null], ['../escape', null]]), false); + assert.equal( + await checkDirectoryVersions( + root, + [], + [ + ['external', null], + ['../escape', null], + ], + ), + false, + ); }); diff --git a/test/back/draft-path-security.test.cjs b/test/back/draft-path-security.test.cjs index 9d00fe10..1bf34be1 100644 --- a/test/back/draft-path-security.test.cjs +++ b/test/back/draft-path-security.test.cjs @@ -104,11 +104,13 @@ test('script creation supports root and nested parents in both writable director for (const root of [config.scriptPath, config.configPath]) { for (const filename of ['ordinary.js', 'nested/deeper/script.js']) { assert.equal( - (await invoke('post', '/', { - path: root, - filename, - content: 'safe', - })).code, + ( + await invoke('post', '/', { + path: root, + filename, + content: 'safe', + }) + ).code, 200, ); assert.equal(fs.readFileSync(path.join(root, filename), 'utf8'), 'safe'); @@ -124,11 +126,13 @@ test('script parent creation rejects sibling prefixes and external symlinks', as fs.symlinkSync(outside, path.join(config.scriptPath, 'escape')); for (const parent of [sibling, path.join(config.scriptPath, 'escape')]) { assert.equal( - (await invoke('post', '/', { - path: parent, - filename: 'nested/poc.js', - content: 'blocked', - })).code, + ( + await invoke('post', '/', { + path: parent, + filename: 'nested/poc.js', + content: 'blocked', + }) + ).code, 403, ); } diff --git a/test/back/execution-lifecycle.test.cjs b/test/back/execution-lifecycle.test.cjs index afa945e6..25a6a965 100644 --- a/test/back/execution-lifecycle.test.cjs +++ b/test/back/execution-lifecycle.test.cjs @@ -19,11 +19,11 @@ test( async () => { let releases = 0; let active = 0; - const { runCron } = load(path.resolve('back/shared/runCron.ts'), { + const { runCron } = load(path.resolve('back/cron/execution/runCron.ts'), { 'cross-spawn': { spawn: () => spawn('true', { shell: '/nonexistent-ql-test-shell' }), }, - './pLimit': { + './cronLimit': { runWithCronLimit: async (_cron, fn) => { active++; try { @@ -34,16 +34,16 @@ test( }, removeQueuedCron: () => releases++, }, - '../loaders/logger': logger, - '../data/cron': { + '../../loaders/logger': logger, + '../../data/cron': { CrontabModel: { findOne: async () => ({ isDisabled: 0 }) }, CrontabStatus: {}, }, - '../data/runningInstance': { + '../../data/runningInstance': { RunningInstanceModel: {}, InstanceStatus: {}, }, - '../config/util': { killTask: async () => {} }, + '../../config/util': { killTask: async () => {} }, }); await runCron('true', { id: '1' }); await runCron('true', { id: '2' }); diff --git a/test/back/http-exclusive-listen.test.cjs b/test/back/http-exclusive-listen.test.cjs index da2157d8..030c6306 100644 --- a/test/back/http-exclusive-listen.test.cjs +++ b/test/back/http-exclusive-listen.test.cjs @@ -3,29 +3,52 @@ const assert = require('node:assert/strict'); const express = require('express'); const load = require('../helpers/load-security-module.cjs'); const Http = load('back/services/http.ts', { - '../config': {bindHost: '127.0.0.1'}, - '../loaders/logger': {debug(){},warn(){},error(){}}, - './metrics': {metricsService: {record(){}}}, - typedi: {Service:()=>x=>x}, + '../config': { bindHost: '127.0.0.1' }, + '../loaders/logger': { debug() {}, warn() {}, error() {} }, + './metrics': { metricsService: { record() {} } }, + typedi: { Service: () => (x) => x }, }).HttpServerService; -test('HTTP listener preserves private binding and releases its port after shutdown',async(t)=>{ - const app=express();app.get('/',(_q,r)=>r.send('ok')); - const first=new Http();const server=await first.initialize(app,0); - t.after(()=>first.shutdown()); - assert.equal(server.address().address,'127.0.0.1'); - const port=server.address().port; - const response=await fetch(`http://127.0.0.1:${port}/`,{headers:{connection:'close'}});assert.equal(await response.text(),'ok'); - await assert.rejects(new Http().initialize(app,port),e=>e.code==='EADDRINUSE'); - await first.shutdown();const replacement=new Http();t.after(()=>replacement.shutdown()); - const next=await replacement.initialize(app,port);assert.equal(next.address().port,port); +test('HTTP listener preserves private binding and releases its port after shutdown', async (t) => { + const app = express(); + app.get('/', (_q, r) => r.send('ok')); + const first = new Http(); + const server = await first.initialize(app, 0); + t.after(() => first.shutdown()); + assert.equal(server.address().address, '127.0.0.1'); + const port = server.address().port; + const response = await fetch(`http://127.0.0.1:${port}/`, { + headers: { connection: 'close' }, + }); + assert.equal(await response.text(), 'ok'); + await assert.rejects( + new Http().initialize(app, port), + (e) => e.code === 'EADDRINUSE', + ); + await first.shutdown(); + const replacement = new Http(); + t.after(() => replacement.shutdown()); + const next = await replacement.initialize(app, port); + assert.equal(next.address().port, port); }); -test('custom cluster deployments can restore shared listening',async(t)=>{ - const previous=process.env.QL_HTTP_SHARED_LISTEN; - t.after(()=>{if(previous===undefined)delete process.env.QL_HTTP_SHARED_LISTEN;else process.env.QL_HTTP_SHARED_LISTEN=previous;}); - for(const value of [undefined,'true']){ - if(value===undefined)delete process.env.QL_HTTP_SHARED_LISTEN;else process.env.QL_HTTP_SHARED_LISTEN=value; - let options;const service=new Http();const app=express();const listen=app.listen.bind(app); - app.listen=(opts,cb)=>{options=opts;return listen(opts,cb);}; - await service.initialize(app,0);assert.equal(options.exclusive,value!=='true');await service.shutdown(); - } +test('custom cluster deployments can restore shared listening', async (t) => { + const previous = process.env.QL_HTTP_SHARED_LISTEN; + t.after(() => { + if (previous === undefined) delete process.env.QL_HTTP_SHARED_LISTEN; + else process.env.QL_HTTP_SHARED_LISTEN = previous; + }); + for (const value of [undefined, 'true']) { + if (value === undefined) delete process.env.QL_HTTP_SHARED_LISTEN; + else process.env.QL_HTTP_SHARED_LISTEN = value; + let options; + const service = new Http(); + const app = express(); + const listen = app.listen.bind(app); + app.listen = (opts, cb) => { + options = opts; + return listen(opts, cb); + }; + await service.initialize(app, 0); + assert.equal(options.exclusive, value !== 'true'); + await service.shutdown(); + } }); diff --git a/test/back/http-security.test.cjs b/test/back/http-security.test.cjs index 49f4effa..a7736cb3 100644 --- a/test/back/http-security.test.cjs +++ b/test/back/http-security.test.cjs @@ -55,7 +55,9 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec }, { scopes: ['configs:read'], - tokens: [{ value: 'config-read-app', expiration: Date.now() / 1000 + 3600 }], + tokens: [ + { value: 'config-read-app', expiration: Date.now() / 1000 + 3600 }, + ], }, { scopes: ['configs', 'scripts'], @@ -69,7 +71,9 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec }, { scopes: ['scripts:read'], - tokens: [{ value: 'script-read-app', expiration: Date.now() / 1000 + 3600 }], + tokens: [ + { value: 'script-read-app', expiration: Date.now() / 1000 + 3600 }, + ], }, { scopes: ['envs'], @@ -87,17 +91,27 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec { name: 'system', scopes: ['system'], - tokens: [{ value: 'internal-system', expiration: Date.now() / 1000 + 3600 }], + tokens: [ + { value: 'internal-system', expiration: Date.now() / 1000 + 3600 }, + ], }, ]; - for (const scope of ['crons', 'subscriptions', 'dependencies', 'logs', 'dashboard']) { + for (const scope of [ + 'crons', + 'subscriptions', + 'dependencies', + 'logs', + 'dashboard', + ]) { for (const suffix of ['', ':read']) { apps.push({ scopes: [`${scope}${suffix}`], - tokens: [{ - value: `${scope}${suffix}-app`, - expiration: Date.now() / 1000 + 3600, - }], + tokens: [ + { + value: `${scope}${suffix}-app`, + expiration: Date.now() / 1000 + 3600, + }, + ], }); } } @@ -111,7 +125,10 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec const User = class {}; const Script = class { getFile(folder, filename) { - return fs.promises.readFile(path.join(config.scriptPath, folder, filename), 'utf8'); + return fs.promises.readFile( + path.join(config.scriptPath, folder, filename), + 'utf8', + ); } checkFilePath(folder, filename) { return path.join(config.scriptPath, folder || '', filename); @@ -167,7 +184,13 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec ...mocks.typedi, Container: { get: (x) => - x === User ? user : x === History ? history : x === Script ? script : configService, + x === User + ? user + : x === History + ? history + : x === Script + ? script + : configService, }, }; mocks['../api'] = () => { @@ -187,7 +210,11 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec res.json({ code: 200 }); }); for (const route of [ - '/crons', '/subscriptions', '/dependencies', '/logs', '/dashboard/overview', + '/crons', + '/subscriptions', + '/dependencies', + '/logs', + '/dashboard/overview', ]) { router.get(route, (_req, res) => res.json({ code: 200 })); } @@ -344,17 +371,21 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec assert.equal((await request('/open/envs', 'env-read-app')).body.code, 200); for (const prefix of ['/open', '/panel/open']) { assert.equal( - (await request(`${prefix}/envs`, 'env-read-app', 'POST', [ - { name: 'SAFE_VALUE', value: 'kept' }, - ])).status, + ( + await request(`${prefix}/envs`, 'env-read-app', 'POST', [ + { name: 'SAFE_VALUE', value: 'kept' }, + ]) + ).status, 401, ); } assert.equal(envWriteCalls, 0); assert.equal( - (await request('/open/envs', 'env-app', 'POST', [ - { name: 'SAFE_VALUE', value: 'kept' }, - ])).body.code, + ( + await request('/open/envs', 'env-app', 'POST', [ + { name: 'SAFE_VALUE', value: 'kept' }, + ]) + ).body.code, 200, ); assert.equal(envWriteCalls, 1); @@ -388,8 +419,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec 401, ); assert.equal( - (await request(`${prefix}/logs/download`, 'logs:read-app', 'POST')) - .body.data, + (await request(`${prefix}/logs/download`, 'logs:read-app', 'POST')).body + .data, 'downloaded', ); for (const [namespace, ownToken, otherToken] of [ @@ -398,8 +429,14 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec ]) { const url = `${prefix}/${namespace}/entries/check`; const versions = [['absent-directory', null]]; - assert.equal((await request(url, ownToken, 'POST', versions)).body.current, true); - assert.equal((await request(url, otherToken, 'POST', versions)).status, 401); + assert.equal( + (await request(url, ownToken, 'POST', versions)).body.current, + true, + ); + assert.equal( + (await request(url, otherToken, 'POST', versions)).status, + 401, + ); } } const importedWithHead = await fetch( @@ -429,47 +466,61 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec for (const prefix of ['/open', '/panel/open']) { for (const name of ['normal.txt', 'config.sh', 'task_before.sh']) { assert.equal( - (await request(`${prefix}/configs/save`, 'config-read-app', 'POST', { - name, - content: 'untrusted', - })).status, + ( + await request(`${prefix}/configs/save`, 'config-read-app', 'POST', { + name, + content: 'untrusted', + }) + ).status, 401, ); } } - assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'original'); + assert.equal( + fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), + 'original', + ); assert.equal((await request('/open/system', 'system-app')).body.code, 200); assert.equal( - (await request('/open/system/notify', 'system-app', 'PUT', { - title: 'title', - content: 'content', - })).body.code, + ( + await request('/open/system/notify', 'system-app', 'PUT', { + title: 'title', + content: 'content', + }) + ).body.code, 200, ); for (const prefix of ['/open', '/panel/open']) { assert.equal( - (await request(`${prefix}/system/auth/reset`, 'system-app', 'PUT', { - password: 'changed', - })).status, + ( + await request(`${prefix}/system/auth/reset`, 'system-app', 'PUT', { + password: 'changed', + }) + ).status, 401, ); assert.equal( - (await request(`${prefix}/system/command-run`, 'system-app', 'PUT', { - command: 'id', - })).status, + ( + await request(`${prefix}/system/command-run`, 'system-app', 'PUT', { + command: 'id', + }) + ).status, 401, ); } assert.equal(resetCalls, 0); assert.equal(commandCalls, 0); assert.equal( - (await request('/open/system/auth/reset', 'internal-system', 'PUT', { - retries: 0, - })).body.code, + ( + await request('/open/system/auth/reset', 'internal-system', 'PUT', { + retries: 0, + }) + ).body.code, 200, ); assert.equal( - (await request('/api/system/auth/reset', valid, 'PUT', { retries: 0 })).body.code, + (await request('/api/system/auth/reset', valid, 'PUT', { retries: 0 })).body + .code, 200, ); assert.equal(resetCalls, 2); @@ -539,13 +590,18 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec 200, ); assert.equal( - (await request('/api/configs/save', valid, 'POST', { - name: 'config.sh', - content: 'owner config', - })).body.code, + ( + await request('/api/configs/save', valid, 'POST', { + name: 'config.sh', + content: 'owner config', + }) + ).body.code, 200, ); - assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'owner config'); + assert.equal( + fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), + 'owner config', + ); assert.equal( ( await request('/api/configs/save', valid, 'POST', { @@ -608,17 +664,23 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec assert.equal(await downloaded.text(), 'authorized script'); for (const method of ['PUT', 'DELETE']) { assert.equal( - (await request('/open/scripts', 'script-read-app', method, { - filename: 'test.js', content: 'unauthorized', - })).status, + ( + await request('/open/scripts', 'script-read-app', method, { + filename: 'test.js', + content: 'unauthorized', + }) + ).status, 401, ); } for (const path of ['run', 'stop', 'rename', 'history/restore']) { assert.equal( - (await request(`/open/scripts/${path}`, 'script-read-app', 'PUT', { - filename: 'test.js', content: 'unauthorized', - })).status, + ( + await request(`/open/scripts/${path}`, 'script-read-app', 'PUT', { + filename: 'test.js', + content: 'unauthorized', + }) + ).status, 401, ); } diff --git a/test/back/legacy-client-adapter.test.cjs b/test/back/legacy-client-adapter.test.cjs new file mode 100644 index 00000000..98f66876 --- /dev/null +++ b/test/back/legacy-client-adapter.test.cjs @@ -0,0 +1,288 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { randomUUID } = require('node:crypto'); +const { QueryTypes } = require('sequelize'); +const load = require('../helpers/load-security-module.cjs'); +const { installTriggerHistory } = require('../../back/cron/history'); +const { + TriggerLifecycle, +} = require('../../back/cron/execution/triggerLifecycle'); +const { + TriggerSettlement, +} = require('../../back/cron/settlement/triggerSettlement'); + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-legacy-adapter-')); + const db = load('back/data/index.ts', { + '../config/index': { dbPath: root }, + }).sequelize; + const { CrontabModel } = load('back/data/cron.ts', { + '.': { sequelize: db }, + }); + const { RunningInstanceModel } = load('back/data/runningInstance.ts', { + '.': { sequelize: db }, + }); + load('back/data/cronStats.ts', { '.': { sequelize: db } }); + for (const key of ['QL_DIR', 'QL_DATA_DIR']) { + const previous = process.env[key]; + process.env[key] = root; + t.after(() => { + if (previous === undefined) delete process.env[key]; + else process.env[key] = previous; + }); + } + t.after(async () => { + await db.close(); + await fs.rm(root, { recursive: true, force: true }); + }); + await db.sync(); + await db.transaction((tx) => installTriggerHistory(db, tx)); + const task = await CrontabModel.create({ id: 1, command: 'true', status: 1 }); + let lifecycle; + const settlement = new TriggerSettlement(db, { + finish: (...args) => lifecycle.finish(...args), + shouldStop: (...args) => lifecycle.shouldStop(...args), + }); + lifecycle = new TriggerLifecycle(db, settlement); + const { LegacyClientAdapter } = load( + 'back/cron/compatibility/legacyClient.ts', + { + '../execution/cronProcess': { + systemOwner: (pid) => 'fixture:' + pid, + legacyProcessOwner: (pid) => 'fixture:' + pid, + isProcessDescendant: () => false, + }, + }, + ); + const adapter = new LegacyClientAdapter(db, lifecycle, settlement); + const rows = () => + db.query('SELECT * FROM CronTriggers ORDER BY started_at,id', { + type: QueryTypes.SELECT, + }); + const stats = () => + db.query( + 'SELECT run_count,success_count,fail_count,total_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + const seconds = Math.floor(Date.now() / 1000) - 30; + return { + db, + adapter, + lifecycle, + task, + instances: RunningInstanceModel, + rows, + stats, + seconds, + }; +} + +test('identified Shell admission and settlement roll back with the caller transaction', async (t) => { + const { db, adapter, rows, stats, seconds } = await fixture(t); + const id = 'client-' + randomUUID(); + await assert.rejects( + db.transaction(async (tx) => { + await adapter.shellReport( + id, + 1, + false, + true, + 'client.log', + seconds, + undefined, + false, + tx, + ); + await adapter.shellReport( + id, + 1, + false, + false, + 'client.log', + seconds, + 17, + false, + tx, + 2000, + (seconds + 2) * 1000, + ); + const [row] = await db.query('SELECT state,counted FROM CronTriggers', { + transaction: tx, + type: QueryTypes.SELECT, + }); + assert.deepEqual(row, { state: 'failed', counted: 1 }); + throw Error('caller rollback'); + }), + /caller rollback/, + ); + assert.deepEqual(await rows(), []); + assert.deepEqual(await stats(), []); +}); + +test('PID-only retries leave unknown exits uncounted and cannot overwrite the replacement execution', async (t) => { + const { adapter, task, rows, stats, instances, seconds } = await fixture(t); + const old = (running, code) => + adapter.reportLegacy(1, running, 123, 'same.log', seconds, 2, code); + await Promise.all([old(true), old(true)]); + await old(false); + await old(true); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['unknown', null, 0]], + ); + assert.deepEqual(await stats(), []); + await adapter.reportLegacy(1, true, 123, 'same.log', seconds + 10, 0); + const replacement = (await task.reload()).last_instance_id; + await Promise.all([old(false, 17), old(false, 17)]); + await old(false, 0); + await old(true); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [ + ['failed', 17, 1], + ['running', null, 0], + ], + ); + assert.deepEqual(await stats(), [ + { run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 }, + ]); + assert.equal((await task.reload()).last_instance_id, replacement); + assert.equal(task.last_execution_time, seconds + 10); + assert.equal((await instances.findByPk(replacement)).status, 0); +}); + +test('failed legacy accounting rolls back the receipt and instance before retrying once', async (t) => { + const { db, adapter, task, rows, stats, instances, seconds } = await fixture( + t, + ); + await adapter.reportLegacy(1, true, 123, 'legacy.log', seconds, 0); + await db.query( + "CREATE TRIGGER reject_legacy_stat BEFORE INSERT ON CrontabStats BEGIN SELECT RAISE(ABORT,'blocked accounting'); END", + ); + await assert.rejects( + adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17), + (error) => { + assert.match(error.original.message, /blocked accounting/); + return true; + }, + ); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.counted]), + [['running', 0]], + ); + assert.equal((await instances.findOne()).status, 0); + assert.equal((await task.reload()).status, 0); + assert.deepEqual(await stats(), []); + await db.query('DROP TRIGGER reject_legacy_stat'); + await adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17); + await adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17); + assert.deepEqual(await stats(), [ + { run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 }, + ]); + assert.equal((await instances.findOne()).status, 3); +}); + +test('an exit before its identified start stays unknown until a statistics receipt resolves it once', async (t) => { + const { adapter, task, rows, stats, instances, seconds } = await fixture(t); + const id = 'client-' + randomUUID(); + await adapter.reportInstance(id, 1, false, 123, 'early.log', seconds, 2); + await adapter.reportInstance(id, 1, true, 123, 'early.log', seconds, 0); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.counted]), + [['unknown', 0]], + ); + assert.equal((await instances.findOne()).status, 4); + assert.equal((await task.reload()).status, 1); + assert.deepEqual(await stats(), []); + await adapter.recordShellResult(id, 1, 17, 2000, Date.now()); + await adapter.recordShellResult(id, 1, 0, 2000, Date.now()); + await adapter.reportInstance(id, 1, true, 123, 'early.log', seconds, 0); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['failed', 17, 1]], + ); + assert.equal(await instances.count(), 1); + assert.equal((await instances.findOne()).status, 3); + assert.deepEqual(await stats(), [ + { run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 }, + ]); +}); + +test('successful wrapper reports cannot settle a managed command with an unknown result', async (t) => { + const { adapter, lifecycle, rows, stats, seconds } = await fixture(t); + await lifecycle.enqueue('managed', 1, 'manual', null, seconds * 1000); + await lifecycle.start('managed', seconds * 1000); + await lifecycle.finish('managed', 'unknown', 'restart'); + await adapter.reportInstance( + 'managed', + 1, + false, + 123, + 'wrapper.log', + seconds, + 2, + 0, + ); + await adapter.recordShellResult('managed', 1, 0, 2000, Date.now()); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['unknown', null, 0]], + ); + assert.deepEqual(await stats(), []); +}); + +test('upgrade adoption preserves prior accounting and pending stops across repeated reconciliation', async (t) => { + const { db, adapter, lifecycle, task, rows, stats, instances, seconds } = + await fixture(t); + const old = await instances.create({ + cron_id: 1, + pid: 111, + status: 1, + started_at: seconds, + finished_at: seconds + 2, + exit_code: 0, + log_path: 'old.log', + }); + const live = await instances.create({ + cron_id: 1, + pid: 222, + status: 0, + started_at: seconds, + log_path: 'live.log', + }); + const stopping = await instances.create({ + cron_id: 1, + pid: 333, + status: 0, + started_at: seconds, + log_path: 'stopping.log', + }); + await task.update({ status: 0, pid: 222, log_path: 'live.log' }); + await db.models.CrontabStat.create({ + ref_id: 1, + date: '2026-01-01', + run_count: 1, + success_count: 1, + fail_count: 0, + total_time: 2000, + }); + await lifecycle.queueInstanceStop(stopping.id, 1, 333); + await adapter.reconcileInstances(); + await adapter.reconcileInstances(); + const linked = await rows(); + assert.equal(linked.length, 2); + assert.deepEqual( + linked.find((r) => r.instance_id === old.id).state, + 'finished', + ); + assert.equal(linked.find((r) => r.instance_id === old.id).counted, 1); + assert.equal(linked.find((r) => r.instance_id === live.id).state, 'running'); + assert.equal((await stopping.reload()).status, 0); + assert.ok(await lifecycle.pendingStop(stopping.id)); + assert.deepEqual(await stats(), [ + { run_count: 1, success_count: 1, fail_count: 0, total_time: 2000 }, + ]); +}); diff --git a/test/back/legacy-cron-recovery.test.cjs b/test/back/legacy-cron-recovery.test.cjs index 8f862b94..0ad82d67 100644 --- a/test/back/legacy-cron-recovery.test.cjs +++ b/test/back/legacy-cron-recovery.test.cjs @@ -2,7 +2,9 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { format } = require('node:util'); const load = require('../helpers/load-security-module.cjs'); -const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness'); +const { + SchedulerReadiness, +} = require('../../back/cron/scheduling/schedulerReadiness'); const { getTasks } = require('node-cron'); @@ -24,7 +26,12 @@ test('API accepts legacy question-mark schedules but rejects malformed cron', () for (const schedule of [...legacySchedules, '@once', '@boot']) { assert.equal(scheduleSchema.validate(schedule).error, undefined, schedule); } - for (const schedule of ['@bogus', '0 /5 * * * ?', '0 70 * * * ?', 'not a cron']) { + for (const schedule of [ + '@bogus', + '0 /5 * * * ?', + '0 70 * * * ?', + 'not a cron', + ]) { assert.ok(scheduleSchema.validate(schedule).error, schedule); } }); @@ -36,18 +43,23 @@ test('legacy main and extra schedules restore real jobs and healthy readiness', }); const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/runCron': { runCron() {} }, + '../cron/execution/runCron': { runCron() {} }, '../loaders/logger': { info() {}, warn() {} }, '../shared/i18n': { t: (s) => s, tf: format }, }); const crons = legacySchedules.map((schedule, index) => ({ - id: `legacy-${index}`, name: 'legacy', schedule, command: 'true', + id: `legacy-${index}`, + name: 'legacy', + schedule, + command: 'true', extra_schedules: [{ schedule: '0 0/30 * * * ?' }], })); - const register = (rows) => new Promise((resolve, reject) => { - addCron({ request: { replace: true, crons: rows } }, (error) => - error ? reject(error) : resolve()); - }); + const register = (rows) => + new Promise((resolve, reject) => { + addCron({ request: { replace: true, crons: rows } }, (error) => + error ? reject(error) : resolve(), + ); + }); const readiness = new SchedulerReadiness(async () => {}, 60000); t.after(() => clearTimeout(readiness.retry)); readiness.configure(() => register(crons)); diff --git a/test/back/linux-dependency-uninstall.test.cjs b/test/back/linux-dependency-uninstall.test.cjs index 95e42391..72ca1566 100644 --- a/test/back/linux-dependency-uninstall.test.cjs +++ b/test/back/linux-dependency-uninstall.test.cjs @@ -13,16 +13,31 @@ const util = load('back/config/util.ts', { }); for (const specifier of [ - 'tree', ' tree=2.3.2-r0 ', 'tree>=2.3', 'tree<=2.3', 'tree~2.3', - 'tree>2', 'tree<3', 'tree@testing', 'tree@testing=2.3.2-r0', + 'tree', + ' tree=2.3.2-r0 ', + 'tree>=2.3', + 'tree<=2.3', + 'tree~2.3', + 'tree>2', + 'tree<3', + 'tree@testing', + 'tree@testing=2.3.2-r0', ]) { test(`apk uninstall removes the constraint from ${specifier}`, () => { - assert.equal(util.getUninstallCommand(2, specifier, 'Alpine'), 'apk del -- tree'); + assert.equal( + util.getUninstallCommand(2, specifier, 'Alpine'), + 'apk del -- tree', + ); }); } for (const osType of ['Debian', 'Ubuntu']) { - for (const specifier of ['tree', 'tree=2.1.0-1', 'tree:amd64=1:2.1.0-1+b1', 'tree/stable']) { + for (const specifier of [ + 'tree', + 'tree=2.1.0-1', + 'tree:amd64=1:2.1.0-1+b1', + 'tree/stable', + ]) { test(`${osType} uninstall preserves ${specifier}, including sudo selection`, (t) => { const original = process.env.QL_CONTAINER; t.after(() => { @@ -31,8 +46,12 @@ for (const osType of ['Debian', 'Ubuntu']) { }); for (const container of ['false', 'true']) { process.env.QL_CONTAINER = container; - assert.equal(util.getUninstallCommand(2, specifier, osType), - `${container === 'true' ? 'sudo ' : ''}apt-get remove -y ${specifier}`); + assert.equal( + util.getUninstallCommand(2, specifier, osType), + `${ + container === 'true' ? 'sudo ' : '' + }apt-get remove -y ${specifier}`, + ); } }); } @@ -57,9 +76,19 @@ for (const osType of ['Alpine', 'Debian', 'Ubuntu']) { if (original === undefined) delete process.env.QL_CONTAINER; else process.env.QL_CONTAINER = original; }); - const install = `${osType === 'Alpine' ? 'apk add --no-check-certificate' : 'apt-get install -y'} ${specifier}`; - const uninstall = osType === 'Alpine' ? 'apk del -- tree' : `apt-get remove -y ${specifier}`; - const spawned = [], lookedUp = [], killed = [], removed = []; + const install = `${ + osType === 'Alpine' + ? 'apk add --no-check-certificate' + : 'apt-get install -y' + } ${specifier}`; + const uninstall = + osType === 'Alpine' + ? 'apk del -- tree' + : `apt-get remove -y ${specifier}`; + const spawned = [], + lookedUp = [], + killed = [], + removed = []; const dep = { id: 1, name: specifier, type: 2, status: 1, log: [] }; const Service = load('back/services/dependence.ts', { '../config': {}, @@ -76,7 +105,14 @@ for (const osType of ['Alpine', 'Debian', 'Ubuntu']) { '../data/dependence': { Dependence: class {}, DependenceTypes: types, - DependenceStatus: { installed: 1, installing: 0, removing: 3, removed: 4, removeFailed: 5, cancelled: 7 }, + DependenceStatus: { + installed: 1, + installing: 0, + removing: 3, + removed: 4, + removeFailed: 5, + cancelled: 7, + }, versionDependenceCommandTypes: { 0: '@', 1: '==', 2: '=' }, DependenceModel: { findAll: async () => [dep], diff --git a/test/back/linux-mirror-result.test.cjs b/test/back/linux-mirror-result.test.cjs index 8964d2a4..5cc4a96e 100644 --- a/test/back/linux-mirror-result.test.cjs +++ b/test/back/linux-mirror-result.test.cjs @@ -27,7 +27,7 @@ for (const scenario of [ test(`Linux mirror persistence follows the process result: ${scenario.name}`, async () => { const logger = { info() {}, error() {} }; const ScheduleService = load('back/services/schedule.ts', { - '../shared/cronScheduler': {}, + '../cron/scheduling/cronScheduler': {}, '../shared/pLimit': { runWithSystemLimit: async (_params, fn) => fn() }, 'cross-spawn': { spawn: () => @@ -53,9 +53,9 @@ for (const scenario of [ '../data/notify': {}, '../data/system': {}, '../schedule/client': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../shared/i18n': {}, - '../shared/schedulerMutationLock': {}, + '../cron/scheduling/schedulerMutationLock': {}, './notify': class {}, './schedule': ScheduleService, './sock': class {}, diff --git a/test/back/log-path-security.test.cjs b/test/back/log-path-security.test.cjs index b0436a1a..bcd26605 100644 --- a/test/back/log-path-security.test.cjs +++ b/test/back/log-path-security.test.cjs @@ -66,6 +66,11 @@ test('log initialization rejects unsafe paths before mkdir or file writes', asyn './share': {}, '../loaders/logger': {}, '../shared/utils': { + fileExist: (file) => + fs.access(file).then( + () => true, + () => false, + ), writeFileWithLock: (file, data) => fs.writeFile(file, data), }, '../data/dependence': { DependenceTypes: {} }, @@ -103,7 +108,7 @@ test('manual execution rejects escaping log names before creating directories or '../config/util': {}, '../config/const': {}, '../schedule/client': {}, - '../shared/pLimit': { + '../cron/execution/cronLimit': { manualRunWithCronLimit: async (fn) => { try { return await fn(); @@ -157,48 +162,89 @@ test('manual execution rejects escaping log names before creating directories or assert.deepEqual(await fs.readdir(outside), ['victim.log']); }); -test('creating log folders normalizes valid absolute paths and rejects sibling or symlink escapes before mkdir', async t => { +test('creating log folders normalizes valid absolute paths and rejects sibling or symlink escapes before mkdir', async (t) => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-root-')); t.after(() => fs.rm(root, { recursive: true, force: true })); - const logs = path.join(root, 'log'), outside = path.join(root, 'log-other'); + const logs = path.join(root, 'log'), + outside = path.join(root, 'log-other'); await Promise.all([fs.mkdir(logs), fs.mkdir(outside)]); await fs.symlink(outside, path.join(logs, 'escape')); const Service = load(path.resolve('back/services/cron.ts'), { - '../config': { logPath: logs }, '../config/util': {}, '../data/cron': {}, - '../data/runningInstance': {}, '../schedule/client': {}, '../shared/pLimit': {}, - '../shared/logStreamManager': {}, '../loaders/logger': {}, + '../config': { logPath: logs }, + '../config/util': {}, + '../data/cron': {}, + '../data/runningInstance': {}, + '../schedule/client': {}, + '../cron/execution/cronLimit': {}, + '../shared/logStreamManager': {}, + '../loaders/logger': {}, }).default; const service = new Service({}); - for (const candidate of [path.join(outside, 'new'), 'escape/new', '../log-other/new']) - await assert.rejects(service.getLogName({ log_name: candidate }), { status: 400 }); + for (const candidate of [ + path.join(outside, 'new'), + 'escape/new', + '../log-other/new', + ]) + await assert.rejects(service.getLogName({ log_name: candidate }), { + status: 400, + }); assert.deepEqual(await fs.readdir(outside), []); - assert.equal(await service.getLogName({ log_name: path.join(logs, 'safe') }), 'safe'); + assert.equal( + await service.getLogName({ log_name: path.join(logs, 'safe') }), + 'safe', + ); assert.ok((await fs.stat(path.join(logs, 'safe'))).isDirectory()); }); -test('a cursor from the previous run reads the tail of the current log instead of splicing two files', async t => { +test('a cursor from the previous run reads the tail of the current log instead of splicing two files', async (t) => { const { root } = await fixture(t); const Service = load(path.resolve('back/services/cron.ts'), { - '../config': {logPath: root}, '../config/util': {fileExist: async p => (await fs.stat(p)).isFile()}, - '../data/cron': {CrontabStatus: {running: 0, queued: 3}}, '../data/runningInstance': {}, - '../schedule/client': {}, '../shared/pLimit': {}, '../shared/logStreamManager': {}, '../loaders/logger': {}, + '../config': { logPath: root }, + '../config/util': { fileExist: async (p) => (await fs.stat(p)).isFile() }, + '../data/cron': { CrontabStatus: { running: 0, queued: 3 } }, + '../data/runningInstance': {}, + '../schedule/client': {}, + '../cron/execution/cronLimit': {}, + '../shared/logStreamManager': {}, + '../loaders/logger': {}, }).default; const service = new Service({}); - service.getDb = async () => ({status: 0, log_path: 'current.log'}); + service.getDb = async () => ({ status: 0, log_path: 'current.log' }); await fs.writeFile(path.join(root, 'current.log'), 'current example'); - const resumed = await service.log(1, {offset: 3, previousPath: 'current.log', limit: 7}); + const resumed = await service.log(1, { + offset: 3, + previousPath: 'current.log', + limit: 7, + }); assert.equal(resumed.content, 'rent ex'); - const switched = await service.log(1, {offset: 3, previousPath: '../previous.log', limit: 7}); + const switched = await service.log(1, { + offset: 3, + previousPath: '../previous.log', + limit: 7, + }); assert.equal(switched.content, 'example'); assert.equal(switched.logPath, 'current.log'); - const followed = await service.log(1, { offset: 3, previousPath: 'previous.log', limit: 7, follow: true }); + const followed = await service.log(1, { + offset: 3, + previousPath: 'previous.log', + limit: 7, + follow: true, + }); assert.equal(followed.offset, 0); assert.equal(followed.content, 'current'); - const rest = await service.log(1, { offset: followed.nextOffset, cursor: followed.cursor, previousPath: followed.logPath }); + const rest = await service.log(1, { + offset: followed.nextOffset, + cursor: followed.cursor, + previousPath: followed.logPath, + }); assert.equal(rest.reset, false); assert.equal(followed.content + rest.content, 'current example'); - service.getDb = async () => ({ status: 3, queued_token: 'new-run', log_path: 'current.log' }); + service.getDb = async () => ({ + status: 3, + queued_token: 'new-run', + log_path: 'current.log', + }); const queued = await service.log(1, { follow: true, tail: true }); assert.equal(queued.status, 'running'); assert.equal(queued.nextOffset, 0); diff --git a/test/back/logReader.test.cjs b/test/back/logReader.test.cjs index 98d1b99c..37e1c255 100644 --- a/test/back/logReader.test.cjs +++ b/test/back/logReader.test.cjs @@ -57,7 +57,10 @@ test('log reader preserves UTF-8 characters across byte boundaries', async (t) = }); assert.equal(first.content + second.content + third.content, 'aaaaa中文日志'); - assert.equal((first.content + second.content + third.content).includes('�'), false); + assert.equal( + (first.content + second.content + third.content).includes('�'), + false, + ); }); test('missing logs return an empty chunk', async () => { @@ -71,14 +74,15 @@ test('missing logs return an empty chunk', async () => { }); }); -test('following a file distinguishes append, same-inode rewrites, and replacement', async t => { +test('following a file distinguishes append, same-inode rewrites, and replacement', async (t) => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-follow-')); t.after(() => fs.rm(dir, { recursive: true, force: true })); const file = path.join(dir, 'run.log'); const original = 'A\n' + '相同内容🚀\n'.repeat(80); await fs.writeFile(file, original); const first = await readLogChunk(file, { follow: true, offset: 0 }); - const resume = chunk => readLogChunk(file, { cursor: chunk.cursor, offset: chunk.nextOffset }); + const resume = (chunk) => + readLogChunk(file, { cursor: chunk.cursor, offset: chunk.nextOffset }); assert.equal((await resume(first)).cursor, first.cursor); await fs.appendFile(file, '追加\n'); const appended = await resume(first); diff --git a/test/back/manual-execution.test.cjs b/test/back/manual-execution.test.cjs index d60897e2..cc136d9c 100644 --- a/test/back/manual-execution.test.cjs +++ b/test/back/manual-execution.test.cjs @@ -36,7 +36,7 @@ test( '../config/util': { getUniqPath: async () => 'task' }, '../config/const': { TASK_PREFIX: 'task ', QL_PREFIX: 'ql ' }, '../schedule/client': {}, - '../shared/pLimit': { + '../cron/execution/cronLimit': { manualRunWithCronLimit: async (fn) => { active++; try { diff --git a/test/back/manual-log-survival.test.cjs b/test/back/manual-log-survival.test.cjs index 52a53bfd..348f2060 100644 --- a/test/back/manual-log-survival.test.cjs +++ b/test/back/manual-log-survival.test.cjs @@ -9,53 +9,80 @@ const { once } = require('node:events'); async function waitFor(read, predicate) { const deadline = Date.now() + 10000; while (Date.now() < deadline) { - const value = await read().catch(error => { + const value = await read().catch((error) => { if (error.code !== 'ENOENT') throw error; }); if (predicate(value)) return value; - await new Promise(resolve => setTimeout(resolve, 20)); + await new Promise((resolve) => setTimeout(resolve, 20)); } throw Error('Timed out waiting for command evidence'); } for (const crash of [false, true]) { - test(`manual compound command keeps complete, nonduplicated logs (worker crash=${crash})`, { timeout: 20000 }, async t => { - const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-survival-')); - const gate = path.join(root, 'continue'); - const script = path.join(root, 'command.sh'); - await fs.writeFile(script, `#!/bin/bash\necho BEFORE\nwhile [ ! -f '${gate}' ]; do sleep 0.02; done\necho '尾行 AFTER'\necho STDERR >&2\n`); - const command = `bash '${script}'; echo COMPOUND; exit 17`; - const worker = fork(path.resolve('test/helpers/manual-log-worker.cjs'), [root, command], { - execArgv: ['-r', require.resolve('ts-node/register/transpile-only')], - env: { ...process.env, TS_NODE_PROJECT: 'back/tsconfig.json' }, - stdio: ['ignore', 'ignore', 'inherit', 'ipc'], - }); - let supervisor; - const messages = []; - worker.on('message', value => messages.push(value)); - const exited = once(worker, 'exit'); - t.after(async () => { + test( + `manual compound command keeps complete, nonduplicated logs (worker crash=${crash})`, + { timeout: 20000 }, + async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-survival-')); + const gate = path.join(root, 'continue'); + const script = path.join(root, 'command.sh'); + await fs.writeFile( + script, + `#!/bin/bash\necho BEFORE\nwhile [ ! -f '${gate}' ]; do sleep 0.02; done\necho '尾行 AFTER'\necho STDERR >&2\n`, + ); + const command = `bash '${script}'; echo COMPOUND; exit 17`; + const worker = fork( + path.resolve('test/helpers/manual-log-worker.cjs'), + [root, command], + { + execArgv: ['-r', require.resolve('ts-node/register/transpile-only')], + env: { ...process.env, TS_NODE_PROJECT: 'back/tsconfig.json' }, + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + }, + ); + let supervisor; + const messages = []; + worker.on('message', (value) => messages.push(value)); + const exited = once(worker, 'exit'); + t.after(async () => { + await fs.writeFile(gate, 'continue'); + worker.kill('SIGKILL'); + if (supervisor) { + try { + process.kill(supervisor, 'SIGKILL'); + } catch {} + } + await fs.rm(root, { recursive: true, force: true }); + }); + const launched = await waitFor( + async () => messages.find((x) => x.pid), + Boolean, + ); + supervisor = launched.pid; + const log = path.join(root, launched.log); + await waitFor( + () => fs.readFile(log, 'utf8'), + (text) => text?.includes('BEFORE'), + ); + if (crash) { + worker.kill('SIGKILL'); + await exited; + } await fs.writeFile(gate, 'continue'); - worker.kill('SIGKILL'); - if (supervisor) { try { process.kill(supervisor, 'SIGKILL'); } catch {} } - await fs.rm(root, { recursive: true, force: true }); - }); - const launched = await waitFor(async () => messages.find(x => x.pid), Boolean); - supervisor = launched.pid; - const log = path.join(root, launched.log); - await waitFor(() => fs.readFile(log, 'utf8'), text => text?.includes('BEFORE')); - if (crash) { - worker.kill('SIGKILL'); - await exited; - } - await fs.writeFile(gate, 'continue'); - if (crash) { - const receipt = await waitFor(() => fs.readFile(path.join(root, 'receipt.json'), 'utf8'), Boolean); - assert.equal(JSON.parse(receipt).code, 17); - } else { - await exited; - assert.equal(messages.find(x => x.result)?.result.code, 17); - } - assert.equal(await fs.readFile(log, 'utf8'), 'BEFORE\n尾行 AFTER\nSTDERR\nCOMPOUND\n'); - }); + if (crash) { + const receipt = await waitFor( + () => fs.readFile(path.join(root, 'receipt.json'), 'utf8'), + Boolean, + ); + assert.equal(JSON.parse(receipt).code, 17); + } else { + await exited; + assert.equal(messages.find((x) => x.result)?.result.code, 17); + } + assert.equal( + await fs.readFile(log, 'utf8'), + 'BEFORE\n尾行 AFTER\nSTDERR\nCOMPOUND\n', + ); + }, + ); } diff --git a/test/back/manual-stop-claim.test.cjs b/test/back/manual-stop-claim.test.cjs index f0f6bf25..3f2fe135 100644 --- a/test/back/manual-stop-claim.test.cjs +++ b/test/back/manual-stop-claim.test.cjs @@ -39,7 +39,9 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) { pid: DataTypes.INTEGER, }); await db.sync(); - await db.transaction((tx) => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx)); + await db.transaction((tx) => + require('../../back/cron/history').installTriggerHistory(db, tx), + ); await crons.create({ id: 1, status: 3, @@ -75,7 +77,7 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) { }, '../config/const': {}, '../schedule/client': {}, - '../shared/pLimit': { + '../cron/execution/cronLimit': { manualRunWithCronLimit: async (fn) => { try { return await fn(); @@ -112,7 +114,8 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) { await service.stop([1]); // Queue again through the real API; leave the new runner pending. const pendingRuns = []; - service.runSingle = async (id, token) => pendingRuns.push({ id, token }); + service.runSingle = async (id, token) => + pendingRuns.push({ id, token }); await service.run([1]); assert.equal(pendingRuns.length, 1); assert.equal( @@ -176,7 +179,9 @@ test('a runner waiting for a concurrency slot cannot adopt a newer queued genera last_execution_time: DataTypes.INTEGER, }); await db.sync(); - await db.transaction((tx) => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx)); + await db.transaction((tx) => + require('../../back/cron/history').installTriggerHistory(db, tx), + ); await crons.create({ id: 1, status: 1, log_path: 'same.log' }); const waiting = []; const CronService = load('back/services/cron.ts', { @@ -194,7 +199,7 @@ test('a runner waiting for a concurrency slot cannot adopt a newer queued genera }, '../config/const': {}, '../schedule/client': {}, - '../shared/pLimit': { + '../cron/execution/cronLimit': { manualRunWithCronLimit: (fn) => { waiting.push(fn); return Promise.resolve(); diff --git a/test/back/mirror-status.test.cjs b/test/back/mirror-status.test.cjs index 31180604..e46cb188 100644 --- a/test/back/mirror-status.test.cjs +++ b/test/back/mirror-status.test.cjs @@ -60,10 +60,23 @@ test('mirror verification selects GNU timeout when the default is another implem assert.ok(realTimeout, 'The mirror script requires GNU timeout'); const bin = path.join(tmp, 'bin'); fs.mkdirSync(bin); - fs.symlinkSync(execFileSync('which', [realTimeout], { encoding: 'utf8' }).trim(), path.join(bin, 'gnutimeout')); - fs.symlinkSync(execFileSync('which', ['git'], { encoding: 'utf8' }).trim(), path.join(bin, 'git')); - fs.symlinkSync(execFileSync('which', ['sort'], { encoding: 'utf8' }).trim(), path.join(bin, 'sort')); - fs.writeFileSync(path.join(bin, 'timeout'), '#!/bin/sh\nif [ "$1" = --version ]; then echo "timeout (uutils coreutils)"; exit 0; fi\nexit 98\n', { mode: 0o755 }); + fs.symlinkSync( + execFileSync('which', [realTimeout], { encoding: 'utf8' }).trim(), + path.join(bin, 'gnutimeout'), + ); + fs.symlinkSync( + execFileSync('which', ['git'], { encoding: 'utf8' }).trim(), + path.join(bin, 'git'), + ); + fs.symlinkSync( + execFileSync('which', ['sort'], { encoding: 'utf8' }).trim(), + path.join(bin, 'sort'), + ); + fs.writeFileSync( + path.join(bin, 'timeout'), + '#!/bin/sh\nif [ "$1" = --version ]; then echo "timeout (uutils coreutils)"; exit 0; fi\nexit 98\n', + { mode: 0o755 }, + ); const args = [script, source, mirror, 'develop']; const result = spawnSync('/bin/bash', args, options({ PATH: bin })); assert.equal(result.status, 0, result.stderr + result.stdout); @@ -270,10 +283,7 @@ test('Gitee workflows verify both mirrors and do not gate image publication', () JSON.stringify(backfill), /GITEE_TOKEN|git@gitee|sync-static|ssh-keyscan/, ); - for (const name of [ - 'build-alpine', - 'build-debian', - ]) { + for (const name of ['build-alpine', 'build-debian']) { assert.equal(workflow.jobs[name].needs, 'build-static'); } }); diff --git a/test/back/node-cron-migration.test.cjs b/test/back/node-cron-migration.test.cjs index 1b2f70d9..26ab4a84 100644 --- a/test/back/node-cron-migration.test.cjs +++ b/test/back/node-cron-migration.test.cjs @@ -1,16 +1,26 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const load = require('../helpers/load-security-module.cjs'); -const { createCronJob } = require('../../back/shared/cronScheduler'); +const { createCronJob } = require('../../back/cron/scheduling/cronScheduler'); const logger = { info() {}, warn() {}, error() {} }; test('native calendar skips nonexistent spring time and duplicate fall hour', async (t) => { const previous = process.env.TZ; process.env.TZ = 'America/New_York'; - t.after(() => { if (previous === undefined) delete process.env.TZ; else process.env.TZ = previous; }); - t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-03-08T05:00:00Z') }); + t.after(() => { + if (previous === undefined) delete process.env.TZ; + else process.env.TZ = previous; + }); + t.mock.timers.enable({ + apis: ['Date', 'setTimeout', 'setInterval'], + now: new Date('2026-03-08T05:00:00Z'), + }); const springRuns = []; - const spring = createCronJob('0 30 2 * * *', (date) => springRuns.push(date.toISOString()), { name: 'spring', logger }); + const spring = createCronJob( + '0 30 2 * * *', + (date) => springRuns.push(date.toISOString()), + { name: 'spring', logger }, + ); t.after(() => spring.cancel()); t.mock.timers.tick(new Date('2026-03-09T06:30:00Z') - Date.now()); await new Promise(setImmediate); @@ -18,7 +28,11 @@ test('native calendar skips nonexistent spring time and duplicate fall hour', as spring.cancel(); t.mock.timers.setTime(new Date('2026-11-01T05:30:00Z').getTime()); const fallRuns = []; - const fall = createCronJob('0 30 1 * * *', (date) => fallRuns.push(date.toISOString()), { name: 'fall', logger }); + const fall = createCronJob( + '0 30 1 * * *', + (date) => fallRuns.push(date.toISOString()), + { name: 'fall', logger }, + ); t.after(() => fall.cancel()); t.mock.timers.tick(new Date('2026-11-02T06:30:00Z') - Date.now()); await new Promise(setImmediate); @@ -31,28 +45,65 @@ test('construction failure cleans staged jobs and preserves the running snapshot let count = 0; const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/cronScheduler': { createCronJob: () => { - if (++count === 2) throw Error('construction failed'); - return { start() { throw Error('must not start'); }, cancel: () => cancelled.push('staged') }; - } }, - '../shared/runCron': {}, '../loaders/logger': logger, '../shared/i18n': { tf: require('node:util').format }, + '../cron/scheduling/cronScheduler': { + createCronJob: () => { + if (++count === 2) throw Error('construction failed'); + return { + start() { + throw Error('must not start'); + }, + cancel: () => cancelled.push('staged'), + }; + }, + }, + '../cron/execution/runCron': {}, + '../loaders/logger': logger, + '../shared/i18n': { tf: require('node:util').format }, }); - await assert.rejects(new Promise((resolve, reject) => addCron({ request: { - replace: true, crons: [{ id: 'new', schedule: '* * * * *', extra_schedules: [{ schedule: '0 * * * *' }] }], - } }, (error) => error ? reject(error) : resolve())), /construction failed/); + await assert.rejects( + new Promise((resolve, reject) => + addCron( + { + request: { + replace: true, + crons: [ + { + id: 'new', + schedule: '* * * * *', + extra_schedules: [{ schedule: '0 * * * *' }], + }, + ], + }, + }, + (error) => (error ? reject(error) : resolve()), + ), + ), + /construction failed/, + ); assert.deepEqual([...stacks.keys()], ['old']); assert.deepEqual(cancelled, ['staged']); }); test('invalid subscription schedules are isolated and immediate runs without a schedule survive', async () => { - const warnings = [], runs = []; + const warnings = [], + runs = []; const Service = load('back/services/schedule.ts', { typedi: { Service: () => (x) => x, Inject: () => () => {} }, '../shared/pLimit': {}, }).default; - const service = new Service({ ...logger, warn: (...args) => warnings.push(args) }); - service.runTask = async (...args) => { runs.push(args); }; - const item = { id: 123, name: 'subscription', command: 'true', runOrigin: 'subscription' }; + const service = new Service({ + ...logger, + warn: (...args) => warnings.push(args), + }); + service.runTask = async (...args) => { + runs.push(args); + }; + const item = { + id: 123, + name: 'subscription', + command: 'true', + runOrigin: 'subscription', + }; await service.createCronTask({ ...item, schedule: 'not a cron' }); assert.equal(warnings.length, 1); assert.equal(service.scheduleStacks.size, 0); diff --git a/test/back/node-dependency-uninstall.test.cjs b/test/back/node-dependency-uninstall.test.cjs index 4408aa63..01442e38 100644 --- a/test/back/node-dependency-uninstall.test.cjs +++ b/test/back/node-dependency-uninstall.test.cjs @@ -29,7 +29,10 @@ for (const [specifier, installedName] of [ const args = execFileSync('/bin/sh', [ '-c', 'pnpm() { printf "%s\\0" "$@"; }; ' + command, - ]).toString().split('\0').slice(0, -1); + ]) + .toString() + .split('\0') + .slice(0, -1); assert.deepEqual(args, ['remove', '-g', '--', installedName]); }); } @@ -37,9 +40,11 @@ for (const [specifier, installedName] of [ test('cancel can locate an uninstall process after shell argument parsing', async (t) => { const name = `@ql-uninstall-fixture/worker-${process.pid}`; const command = api.getUninstallCommand(0, `${name}@1.0.0`); - const worker = spawn(process.execPath, [ - '-e', 'setInterval(() => {}, 1000)', 'pnpm', 'remove', '-g', '--', name, - ], { stdio: 'ignore' }); + const worker = spawn( + process.execPath, + ['-e', 'setInterval(() => {}, 1000)', 'pnpm', 'remove', '-g', '--', name], + { stdio: 'ignore' }, + ); t.after(() => worker.kill()); await new Promise((resolve, reject) => { worker.once('spawn', resolve); diff --git a/test/back/node-path-cache.test.cjs b/test/back/node-path-cache.test.cjs index 06f272d2..d81eac2a 100644 --- a/test/back/node-path-cache.test.cjs +++ b/test/back/node-path-cache.test.cjs @@ -70,14 +70,26 @@ test('alternating Node/crond working directories retain independent cached roots fs.mkdirSync(path.join(f.root, 'child')); fs.writeFileSync(path.join(f.root, 'child', '.npmrc'), 'global-dir=/child\n'); for (let i = 0; i < 4; i++) { - assert.equal(f.run({ ANSWER: '/parent/modules' }).stdout.trim(), '/parent/modules'); assert.equal( - f.run({ ANSWER: '/child/modules' }, 'cd child; ' + f.command).stdout.trim(), + f.run({ ANSWER: '/parent/modules' }).stdout.trim(), + '/parent/modules', + ); + assert.equal( + f + .run({ ANSWER: '/child/modules' }, 'cd child; ' + f.command) + .stdout.trim(), '/child/modules', ); } - assert.equal(f.count(), 2, 'each working directory should discover only once'); - assert.equal(fs.readdirSync(f.env.dir_tmp).filter((x) => x.endsWith('.cache')).length, 2); + assert.equal( + f.count(), + 2, + 'each working directory should discover only once', + ); + assert.equal( + fs.readdirSync(f.env.dir_tmp).filter((x) => x.endsWith('.cache')).length, + 2, + ); }); test('refresh retires old per-environment records without removing locks or unrelated files', (t) => { const f = fixture(t); @@ -92,7 +104,8 @@ test('refresh retires old per-environment records without removing locks or unre } assert.equal(f.run().status, 0); assert.equal(fs.existsSync(path.join(f.env.dir_tmp, names[0])), false); - for (const name of names.slice(1)) assert.ok(fs.existsSync(path.join(f.env.dir_tmp, name))); + for (const name of names.slice(1)) + assert.ok(fs.existsSync(path.join(f.env.dir_tmp, name))); }); test('expired or malformed records refresh and failed lookups are not cached', (t) => { const f = fixture(t); diff --git a/test/back/node-runtime-probe.test.cjs b/test/back/node-runtime-probe.test.cjs index 9b394ae3..5544826c 100644 --- a/test/back/node-runtime-probe.test.cjs +++ b/test/back/node-runtime-probe.test.cjs @@ -36,12 +36,25 @@ test('emulated Node probes have a bounded two-minute budget and reject a timeout t.mock.method(childProcess, 'spawnSync', (_program, args, options) => { assert.equal(options.timeout, 120000); assert.equal(options.env.NODE_OPTIONS, ''); - return { status: null, signal: 'SIGTERM', error: Object.assign(new Error('probe timed out'), { code: 'ETIMEDOUT' }) }; + return { + status: null, + signal: 'SIGTERM', + error: Object.assign(new Error('probe timed out'), { code: 'ETIMEDOUT' }), + }; }); delete require.cache[modulePath]; - t.after(() => { delete require.cache[modulePath]; }); + t.after(() => { + delete require.cache[modulePath]; + }); const probe = require(modulePath).probeNodeRuntime; - assert.throws(() => probe(), /Node URL runtime probe failed.*SIGTERM.*probe timed out/); + assert.throws( + () => probe(), + /Node URL runtime probe failed.*SIGTERM.*probe timed out/, + ); assert.ok(directory); - assert.equal(fs.existsSync(directory), false, 'Timed-out probes must remove their temporary source files'); + assert.equal( + fs.existsSync(directory), + false, + 'Timed-out probes must remove their temporary source files', + ); }); diff --git a/test/back/notification-audit.test.cjs b/test/back/notification-audit.test.cjs index d88cdae1..862c7f1c 100644 --- a/test/back/notification-audit.test.cjs +++ b/test/back/notification-audit.test.cjs @@ -30,7 +30,7 @@ async function fixture(t) { './schedule': class {}, './sock': class {}, './notify': class {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../config/index': {}, '../shared/store': {}, @@ -47,12 +47,11 @@ async function fixture(t) { NotifyStatus: { success: 0, fail: 1 }, }, '../shared/i18n': { t: (s) => s }, - './user': {}, + '../data/notificationSettings': { + readNotificationMode: async () => ({ type: 'email' }), + }, }).default)(), }); - service.notificationService.userService = { - getNotificationMode: async () => ({ type: 'email' }), - }; service.notificationService.modeMap.set('email', async () => true); service.getDb = async () => ({ info: { type: 'email' } }); return { rows, service }; diff --git a/test/back/notification-settings.test.cjs b/test/back/notification-settings.test.cjs new file mode 100644 index 00000000..6a5ac40e --- /dev/null +++ b/test/back/notification-settings.test.cjs @@ -0,0 +1,33 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const load = require('../helpers/load-security-module.cjs'); + +test('notification settings keep missing-row errors, empty defaults and fresh reads', async () => { + let row; + const { readNotificationMode } = load('back/data/notificationSettings.ts', { + './system': { + AuthDataType: { notification: 'notification' }, + SystemModel: { + findOne: async (query) => { + assert.deepEqual(query, { where: { type: 'notification' } }); + return row; + }, + }, + }, + }); + await assert.rejects(readNotificationMode(), { + message: '{"type":"notification"} not found', + }); + let info = null; + row = { + get(options) { + assert.deepEqual(options, { plain: true }); + return { info }; + }, + }; + assert.deepEqual(await readNotificationMode(), {}); + info = { type: 'wpush', wpushApiKey: 'saved-key' }; + assert.deepEqual(await readNotificationMode(), info); + info = { type: 'email' }; + assert.deepEqual(await readNotificationMode(), info); +}); diff --git a/test/back/npm-package.test.cjs b/test/back/npm-package.test.cjs index 284bdf8b..82017e1d 100644 --- a/test/back/npm-package.test.cjs +++ b/test/back/npm-package.test.cjs @@ -12,24 +12,43 @@ const { restorePackageLock } = require('../../shell/install-package.cjs'); const { restoreEnvironment } = require('../../shell/install-package.cjs'); async function packageFixture(t) { - const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-contract-'))); + const temp = await fs.realpath( + await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-contract-')), + ); t.after(() => fs.rm(temp, { recursive: true, force: true })); - const root = path.join(temp, 'source'), output = path.join(temp, 'archives'); + const root = path.join(temp, 'source'), + output = path.join(temp, 'archives'); await fs.mkdir(root); await fs.mkdir(output); const copy = async (name) => { await fs.mkdir(path.dirname(path.join(root, name)), { recursive: true }); await fs.copyFile(path.resolve(name), path.join(root, name)); }; - for (const name of ['.gitignore', 'docker/verify-build.cjs', 'docker/build-manifest.cjs', '.env.example', 'ecosystem.config.js', 'version.yaml', 'README.md', 'LICENSE', 'scripts/prepare-npm-package.cjs', 'back/protos/api.proto']) await copy(name); + for (const name of [ + '.gitignore', + 'docker/verify-build.cjs', + 'docker/build-manifest.cjs', + '.env.example', + 'ecosystem.config.js', + 'version.yaml', + 'README.md', + 'LICENSE', + 'scripts/prepare-npm-package.cjs', + 'back/protos/api.proto', + ]) + await copy(name); for (const directory of ['shell', 'sample', 'cli/src/internal/maintenance']) { await fs.cp(directory, path.join(root, directory), { recursive: true, - filter: (source) => !/[/\\](?:__pycache__|node_modules)(?:[/\\]|$)|[/\\]preload[/\\](?:env\.|notify\.|__ql_notify__\.|lang_env\.sh)/.test(source), + filter: (source) => + !/[/\\](?:__pycache__|node_modules)(?:[/\\]|$)|[/\\]preload[/\\](?:env\.|notify\.|__ql_notify__\.|lang_env\.sh)/.test( + source, + ), }); } const metadata = JSON.parse(await fs.readFile('package.json', 'utf8')); - for (const name of Object.values(metadata.pnpm?.patchedDependencies || {})) await copy(name); + for (const name of Object.values(metadata.pnpm?.patchedDependencies || {})) + await copy(name); // The structural test stays offline; full production installation and service // upgrades run against the unmodified package in verify-panel-package.cjs. metadata.dependencies = {}; @@ -38,13 +57,50 @@ async function packageFixture(t) { const lock = 'lockfileVersion: 6.0\n'; await fs.writeFile(path.join(root, 'pnpm-lock.yaml'), lock); const files = {}; - for (const name of ['build/app.js', 'build/token.js', 'build/shared/managedExit.cjs', 'build/bootstrap/upgradeProbe.js', 'dist/index.html', 'build/app.js.map', 'dist/app.js.gz']) { + for (const name of [ + 'build/app.js', + 'build/token.js', + 'build/shared/managedExit.cjs', + 'build/cron/settlement/exitReceipt.cjs', + 'build/bootstrap/upgradeProbe.js', + 'dist/index.html', + 'build/app.js.map', + 'dist/app.js.gz', + ]) { const bytes = name.endsWith('.html') ? 'pack fixture' : '{}'; - await fs.mkdir(path.dirname(path.join(root, 'static', name)), { recursive: true }); + await fs.mkdir(path.dirname(path.join(root, 'static', name)), { + recursive: true, + }); await fs.writeFile(path.join(root, 'static', name), bytes); files[name] = createHash('sha256').update(bytes).digest('hex'); } - for (const name of ['.env', '.env.local', '.env.production', '.aws/credentials', '.ssh/id_rsa', '.vscode/settings.json', '.github/workflows/private.yml', '.tmp/private.json', '.DS_Store', 'output/private.json', 'data/config/auth.json', 'back/private.json', 'back/private.ts', 'sample/tool.ts', 'sample/private.json', 'sample/__pycache__/notify.pyc', 'shell/preload/env.js', 'shell/preload/env.py', 'shell/preload/notify.js', 'shell/preload/__ql_notify__.js', 'shell/preload/lang_env.sh', 'shell/preload/task-notify.json', 'shell/preload/__pycache__/env.pyc', 'cli/dist/npm/ql.js', 'cli/src/internal/private.cjs']) { + for (const name of [ + '.env', + '.env.local', + '.env.production', + '.aws/credentials', + '.ssh/id_rsa', + '.vscode/settings.json', + '.github/workflows/private.yml', + '.tmp/private.json', + '.DS_Store', + 'output/private.json', + 'data/config/auth.json', + 'back/private.json', + 'back/private.ts', + 'sample/tool.ts', + 'sample/private.json', + 'sample/__pycache__/notify.pyc', + 'shell/preload/env.js', + 'shell/preload/env.py', + 'shell/preload/notify.js', + 'shell/preload/__ql_notify__.js', + 'shell/preload/lang_env.sh', + 'shell/preload/task-notify.json', + 'shell/preload/__pycache__/env.pyc', + 'cli/dist/npm/ql.js', + 'cli/src/internal/private.cjs', + ]) { await fs.mkdir(path.dirname(path.join(root, name)), { recursive: true }); await fs.writeFile(path.join(root, name), 'DO_NOT_PUBLISH'); } @@ -52,65 +108,177 @@ async function packageFixture(t) { const env = { ...process.env, HOME: temp, NODE_ENV: 'production' }; await execute('git', ['init', '-q'], { cwd: root, env }); await execute('git', ['add', '-A'], { cwd: root, env }); - await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'fixture'], { cwd: root, env }); - await fs.writeFile(path.join(root, 'static/build-info.json'), JSON.stringify({ - version: 1, dirty: false, sourceCommit: (await execute('git', ['rev-parse', 'HEAD'], { cwd: root })).stdout.trim(), files, - lockfileSha256: createHash('sha256').update(lock).digest('hex'), - })); - const pack = () => execute('npm', ['pack', '--json', '--cache', path.join(temp, 'cache'), '--pack-destination', output], { cwd: root, env, timeout: 60000, maxBuffer: 4 * 1024 * 1024 }); + await execute( + 'git', + [ + '-c', + 'user.name=Package Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'core.hooksPath=/dev/null', + 'commit', + '-qm', + 'fixture', + ], + { cwd: root, env }, + ); + await fs.writeFile( + path.join(root, 'static/build-info.json'), + JSON.stringify({ + version: 1, + dirty: false, + sourceCommit: ( + await execute('git', ['rev-parse', 'HEAD'], { cwd: root }) + ).stdout.trim(), + files, + lockfileSha256: createHash('sha256').update(lock).digest('hex'), + }), + ); + const pack = () => + execute( + 'npm', + [ + 'pack', + '--json', + '--cache', + path.join(temp, 'cache'), + '--pack-destination', + output, + ], + { cwd: root, env, timeout: 60000, maxBuffer: 4 * 1024 * 1024 }, + ); return { root, output, temp, env, lock, files, pack }; } test('real npm pack excludes local state and its installed lifecycle restores verified runtime files', async (t) => { - const { root, output, temp, env, lock, files, pack } = await packageFixture(t); + const { root, output, temp, env, lock, files, pack } = await packageFixture( + t, + ); // The whitelist must work by itself, even for artifacts ignored by Git. - await assert.rejects(fs.access(path.join(root, '.npmignore')), { code: 'ENOENT' }); + await assert.rejects(fs.access(path.join(root, '.npmignore')), { + code: 'ENOENT', + }); const packed = await pack(); const [archive] = JSON.parse(packed.stdout); checkPackedFiles(archive.files); - const patches = Object.values(JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).pnpm?.patchedDependencies || {}); + const patches = Object.values( + JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).pnpm + ?.patchedDependencies || {}, + ); for (const patch of patches) { - assert.throws(() => checkPackedFiles(archive.files.filter((file) => file.path !== patch)), /Missing npm runtime/); + assert.throws( + () => + checkPackedFiles(archive.files.filter((file) => file.path !== patch)), + /Missing npm runtime/, + ); } - assert.throws(() => checkPackedFiles([...archive.files, { path: 'patches/undeclared.patch' }]), /Unexpected npm file/); + assert.throws( + () => + checkPackedFiles([ + ...archive.files, + { path: 'patches/undeclared.patch' }, + ]), + /Unexpected npm file/, + ); const names = new Set(archive.files.map((file) => file.path)); assert.ok(names.has('shell/upgrade-lock.yaml')); assert.ok(names.has('shell/subscription-files.py')); for (const name of Object.keys(files)) assert.ok(names.has('static/' + name)); - await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), { code: 'ENOENT' }); + await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), { + code: 'ENOENT', + }); const prefix = path.join(temp, 'installed'); - await execute('npm', ['install', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), '--prefix', prefix, path.join(output, archive.filename)], { cwd: temp, env, timeout: 60000 }); + await execute( + 'npm', + [ + 'install', + '--offline', + '--omit=dev', + '--no-audit', + '--no-fund', + '--cache', + path.join(temp, 'cache'), + '--prefix', + prefix, + path.join(output, archive.filename), + ], + { cwd: temp, env, timeout: 60000 }, + ); const installed = path.join(prefix, 'node_modules/@whyour/qinglong'); - for (const patch of patches) assert.deepEqual(await fs.readFile(path.join(installed, patch)), await fs.readFile(path.join(root, patch))); + for (const patch of patches) + assert.deepEqual( + await fs.readFile(path.join(installed, patch)), + await fs.readFile(path.join(root, patch)), + ); for (const { path: name } of archive.files) - assert.equal((await fs.readFile(path.join(installed, name))).includes(Buffer.from('DO_NOT_PUBLISH')), false, `Private fixture content in npm package: ${name}`); - await assert.rejects(fs.access(path.join(installed, '.env')), { code: 'ENOENT' }); - assert.equal(await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), lock); - assert.equal(typeof require(path.join(installed, 'shell/upgrade.cjs')).stageUpgrade, 'function'); - assert.ok((await fs.stat(path.join(installed, 'shell/update.sh'))).mode & 0o111); - for (const [name, file] of Object.entries(JSON.parse(await fs.readFile(path.join(installed, 'package.json'), 'utf8')).bin)) { + assert.equal( + (await fs.readFile(path.join(installed, name))).includes( + Buffer.from('DO_NOT_PUBLISH'), + ), + false, + `Private fixture content in npm package: ${name}`, + ); + await assert.rejects(fs.access(path.join(installed, '.env')), { + code: 'ENOENT', + }); + assert.equal( + await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), + lock, + ); + assert.equal( + typeof require(path.join(installed, 'shell/upgrade.cjs')).stageUpgrade, + 'function', + ); + assert.ok( + (await fs.stat(path.join(installed, 'shell/update.sh'))).mode & 0o111, + ); + for (const [name, file] of Object.entries( + JSON.parse(await fs.readFile(path.join(installed, 'package.json'), 'utf8')) + .bin, + )) { await fs.access(path.join(prefix, 'node_modules/.bin', name)); assert.ok((await fs.stat(path.join(installed, file))).mode & 0o111, file); } - await fs.writeFile(path.join(installed, 'shell/upgrade-lock.yaml'), 'tampered'); + await fs.writeFile( + path.join(installed, 'shell/upgrade-lock.yaml'), + 'tampered', + ); assert.throws(() => restorePackageLock(installed), /does not match/); - assert.equal(await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), lock); - assert.ok(!(await fs.readdir(installed)).some((name) => name.startsWith('.upgrade-lock-'))); + assert.equal( + await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), + lock, + ); + assert.ok( + !(await fs.readdir(installed)).some((name) => + name.startsWith('.upgrade-lock-'), + ), + ); }); test('postinstall still supports minimal Docker dependency stages before shell files are copied', async (t) => { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-builder-')); t.after(() => fs.rm(temp, { recursive: true, force: true })); const metadata = JSON.parse(await fs.readFile('package.json', 'utf8')); - await fs.writeFile(path.join(temp, 'package.json'), JSON.stringify({ scripts: { postinstall: metadata.scripts.postinstall } })); + await fs.writeFile( + path.join(temp, 'package.json'), + JSON.stringify({ scripts: { postinstall: metadata.scripts.postinstall } }), + ); await fs.writeFile(path.join(temp, 'pnpm-lock.yaml'), 'source lock'); - await execute('npm', ['run', 'postinstall', '--cache', path.join(temp, 'cache')], { cwd: temp, timeout: 30000 }); + await execute( + 'npm', + ['run', 'postinstall', '--cache', path.join(temp, 'cache')], + { cwd: temp, timeout: 30000 }, + ); }); test('a missing npm runtime lockfile fails instead of claiming an installed package is ready', async (t) => { const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-lock-missing-')); t.after(() => fs.rm(temp, { recursive: true, force: true })); - assert.throws(() => restorePackageLock(temp), /Missing npm package upgrade lockfile/); + assert.throws( + () => restorePackageLock(temp), + /Missing npm package upgrade lockfile/, + ); }); test('real npm overwrites preserve .env automatically and failed installs restore the old package', async (t) => { @@ -119,62 +287,165 @@ test('real npm overwrites preserve .env automatically and failed installs restor const archive = path.join(output, packed.filename); const legacy = path.join(temp, 'legacy'); await fs.mkdir(legacy); - await fs.writeFile(path.join(legacy, 'package.json'), JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' })); + await fs.writeFile( + path.join(legacy, 'package.json'), + JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' }), + ); await fs.writeFile(path.join(legacy, 'old-package-marker'), 'legacy'); - const [old] = JSON.parse((await execute('npm', ['pack', '--ignore-scripts', '--json', '--cache', path.join(temp, 'cache')], { cwd: legacy, env })).stdout); + const [old] = JSON.parse( + ( + await execute( + 'npm', + [ + 'pack', + '--ignore-scripts', + '--json', + '--cache', + path.join(temp, 'cache'), + ], + { cwd: legacy, env }, + ) + ).stdout, + ); const broken = path.join(temp, 'broken'); await fs.mkdir(broken); await fs.cp(root, broken, { recursive: true }); - await fs.writeFile(path.join(broken, 'shell/upgrade-lock.yaml'), 'invalid lock'); - const [bad] = JSON.parse((await execute('npm', ['pack', '--ignore-scripts', '--json', '--cache', path.join(temp, 'cache')], { cwd: broken, env })).stdout); + await fs.writeFile( + path.join(broken, 'shell/upgrade-lock.yaml'), + 'invalid lock', + ); + const [bad] = JSON.parse( + ( + await execute( + 'npm', + [ + 'pack', + '--ignore-scripts', + '--json', + '--cache', + path.join(temp, 'cache'), + ], + { cwd: broken, env }, + ) + ).stdout, + ); for (const global of [false, true]) { - await t.test(global ? 'global npm install' : 'local npm install', async () => { - const prefix = path.join(temp, global ? 'global' : 'local'); - const linkedPrefix = prefix + '-link'; - await fs.mkdir(prefix); - await fs.symlink(prefix, linkedPrefix); - const installed = path.join(prefix, global ? 'lib/node_modules/@whyour/qinglong' : 'node_modules/@whyour/qinglong'); - const install = (file) => execute('npm', ['install', ...(global ? ['--global'] : []), '--prefix', linkedPrefix, '--force', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), file], { cwd: temp, env, timeout: 60000 }); - await install(path.join(legacy, old.filename)); - const bytes = Buffer.from('QL_DATA_DIR=/external/data\r\nSECRET="配置 test"\r\n# no trailing newline'); - const external = path.join(prefix, 'external.env'); - await fs.writeFile(external, bytes); - await fs.symlink(external, path.join(installed, '.env')); - await assert.rejects(install(archive), (error) => { - assert.match(error.stderr, /must be a regular file/); - return true; - }); - assert.equal(JSON.parse(await fs.readFile(path.join(installed, 'package.json'))).version, '2.22.0'); - assert.equal(await fs.readlink(path.join(installed, '.env')), external); - assert.deepEqual(await fs.readFile(external), bytes); - await fs.rm(path.join(installed, '.env')); - await fs.writeFile(path.join(installed, '.env'), bytes, { mode: 0o644 }); - await assert.rejects(install(path.join(broken, bad.filename)), (error) => { - assert.match(error.stderr, /does not match its build manifest/); - return true; - }); - assert.equal(JSON.parse(await fs.readFile(path.join(installed, 'package.json'))).version, '2.22.0'); - assert.equal(await fs.readFile(path.join(installed, 'old-package-marker'), 'utf8'), 'legacy'); - assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes); - await install(archive); - assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes); - assert.equal((await fs.stat(path.join(installed, '.env'))).mode & 0o777, 0o600); - await assert.rejects(fs.access(path.join(installed, 'old-package-marker')), { code: 'ENOENT' }); - // Same-version forced reinstall must also retain custom configuration. - await install(archive); - assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes); - assert.ok(!(await fs.readdir(installed)).some((name) => name.startsWith('.upgrade-env-'))); - }); + await t.test( + global ? 'global npm install' : 'local npm install', + async () => { + const prefix = path.join(temp, global ? 'global' : 'local'); + const linkedPrefix = prefix + '-link'; + await fs.mkdir(prefix); + await fs.symlink(prefix, linkedPrefix); + const installed = path.join( + prefix, + global + ? 'lib/node_modules/@whyour/qinglong' + : 'node_modules/@whyour/qinglong', + ); + const install = (file) => + execute( + 'npm', + [ + 'install', + ...(global ? ['--global'] : []), + '--prefix', + linkedPrefix, + '--force', + '--offline', + '--omit=dev', + '--no-audit', + '--no-fund', + '--cache', + path.join(temp, 'cache'), + file, + ], + { cwd: temp, env, timeout: 60000 }, + ); + await install(path.join(legacy, old.filename)); + const bytes = Buffer.from( + 'QL_DATA_DIR=/external/data\r\nSECRET="配置 test"\r\n# no trailing newline', + ); + const external = path.join(prefix, 'external.env'); + await fs.writeFile(external, bytes); + await fs.symlink(external, path.join(installed, '.env')); + await assert.rejects(install(archive), (error) => { + assert.match(error.stderr, /must be a regular file/); + return true; + }); + assert.equal( + JSON.parse(await fs.readFile(path.join(installed, 'package.json'))) + .version, + '2.22.0', + ); + assert.equal(await fs.readlink(path.join(installed, '.env')), external); + assert.deepEqual(await fs.readFile(external), bytes); + await fs.rm(path.join(installed, '.env')); + await fs.writeFile(path.join(installed, '.env'), bytes, { + mode: 0o644, + }); + await assert.rejects( + install(path.join(broken, bad.filename)), + (error) => { + assert.match(error.stderr, /does not match its build manifest/); + return true; + }, + ); + assert.equal( + JSON.parse(await fs.readFile(path.join(installed, 'package.json'))) + .version, + '2.22.0', + ); + assert.equal( + await fs.readFile(path.join(installed, 'old-package-marker'), 'utf8'), + 'legacy', + ); + assert.deepEqual( + await fs.readFile(path.join(installed, '.env')), + bytes, + ); + await install(archive); + assert.deepEqual( + await fs.readFile(path.join(installed, '.env')), + bytes, + ); + assert.equal( + (await fs.stat(path.join(installed, '.env'))).mode & 0o777, + 0o600, + ); + await assert.rejects( + fs.access(path.join(installed, 'old-package-marker')), + { code: 'ENOENT' }, + ); + // Same-version forced reinstall must also retain custom configuration. + await install(archive); + assert.deepEqual( + await fs.readFile(path.join(installed, '.env')), + bytes, + ); + assert.ok( + !(await fs.readdir(installed)).some((name) => + name.startsWith('.upgrade-env-'), + ), + ); + }, + ); } }); test('environment recovery uses only the exact retired package and never overwrites existing configuration', async (t) => { - const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-env-'))); + const temp = await fs.realpath( + await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-env-')), + ); t.after(() => fs.rm(temp, { recursive: true, force: true })); const root = path.join(temp, 'node_modules/@whyour/qinglong'); await fs.mkdir(root, { recursive: true }); - const suffix = createHash('sha1').update(root).digest('base64').replace(/[^a-zA-Z0-9]+/g, '').slice(0, 8); + const suffix = createHash('sha1') + .update(root) + .digest('base64') + .replace(/[^a-zA-Z0-9]+/g, '') + .slice(0, 8); const retired = path.join(path.dirname(root), `.qinglong-${suffix}`); const destination = path.join(root, '.env'); const other = path.join(path.dirname(root), '.qinglong-unrelated'); @@ -183,10 +454,19 @@ test('environment recovery uses only the exact retired package and never overwri restoreEnvironment(root); await assert.rejects(fs.access(destination), { code: 'ENOENT' }); await fs.mkdir(retired); - await fs.writeFile(path.join(retired, 'package.json'), JSON.stringify({ name: 'another-package' })); + await fs.writeFile( + path.join(retired, 'package.json'), + JSON.stringify({ name: 'another-package' }), + ); await fs.writeFile(path.join(retired, '.env'), 'private'); - assert.throws(() => restoreEnvironment(root), /Unexpected retired npm package/); - await fs.writeFile(path.join(retired, 'package.json'), JSON.stringify({ name: '@whyour/qinglong' })); + assert.throws( + () => restoreEnvironment(root), + /Unexpected retired npm package/, + ); + await fs.writeFile( + path.join(retired, 'package.json'), + JSON.stringify({ name: '@whyour/qinglong' }), + ); await fs.rm(path.join(retired, '.env')); restoreEnvironment(root); await assert.rejects(fs.access(destination), { code: 'ENOENT' }); @@ -203,62 +483,159 @@ test('environment recovery uses only the exact retired package and never overwri await fs.writeFile(destination, 'new custom configuration'); await fs.writeFile(path.join(retired, '.env'), 'old configuration'); restoreEnvironment(root); - assert.equal(await fs.readFile(destination, 'utf8'), 'new custom configuration'); - assert.ok(!(await fs.readdir(root)).some((name) => name.startsWith('.upgrade-env-'))); + assert.equal( + await fs.readFile(destination, 'utf8'), + 'new custom configuration', + ); + assert.ok( + !(await fs.readdir(root)).some((name) => name.startsWith('.upgrade-env-')), + ); }); test('npm publication consumes the exact archive whose isolated installation passed', () => { const yaml = require('js-yaml'); const sync = require('node:fs'); - const workflow = yaml.load(sync.readFileSync('.github/workflows/build-docker-image.yml', 'utf8')); + const workflow = yaml.load( + sync.readFileSync('.github/workflows/build-docker-image.yml', 'utf8'), + ); const verify = workflow.jobs['verify-npm-package']; - assert.deepEqual(verify.needs, ['build-static', 'build-npm-migration-bundle']); - assert.ok(verify.steps.some((step) => step.with?.name === 'npm-migration-bundle-${{ github.sha }}')); + assert.deepEqual(verify.needs, [ + 'build-static', + 'build-npm-migration-bundle', + ]); + assert.ok( + verify.steps.some( + (step) => step.with?.name === 'npm-migration-bundle-${{ github.sha }}', + ), + ); const migration = workflow.jobs['build-npm-migration-bundle']; assert.equal(migration.needs, 'build-debian'); - assert.ok(migration.steps.some((step) => /Dockerfile.upgrade-bundle/.test(step.run || ''))); - assert.ok(!migration.steps.some((step) => /publish-upgrade-bundles/.test(step.run || ''))); + assert.ok( + migration.steps.some((step) => + /Dockerfile.upgrade-bundle/.test(step.run || ''), + ), + ); + assert.ok( + !migration.steps.some((step) => + /publish-upgrade-bundles/.test(step.run || ''), + ), + ); assert.deepEqual(verify.strategy.matrix.node, ['20.18.1', '24']); assert.match(verify.container, /node:.*bookworm/); - const tools = verify.steps.find((step) => step.name === 'Install isolated service test tools'); - assert.match(tools.run, /npm install --global --prefix \/usr\/local.*pm2@6\.0\.14/); - const service = verify.steps.find((step) => step.name === 'Install and upgrade the exact npm archive'); + const tools = verify.steps.find( + (step) => step.name === 'Install isolated service test tools', + ); + assert.match( + tools.run, + /npm install --global --prefix \/usr\/local.*pm2@6\.0\.14/, + ); + const service = verify.steps.find( + (step) => step.name === 'Install and upgrade the exact npm archive', + ); assert.equal(service.env.QL_PANEL_TEST_PM2, '/usr/local/bin/pm2'); assert.ok(workflow.jobs.publish.needs.includes('verify-npm-package')); - const download = workflow.jobs.publish.steps.find((step) => step.uses?.startsWith('actions/download-artifact@')); + const download = workflow.jobs.publish.steps.find((step) => + step.uses?.startsWith('actions/download-artifact@'), + ); assert.equal(download.with.name, 'qinglong-npm-${{ github.sha }}'); - const publication = workflow.jobs.publish.steps.find((step) => step.name === 'Publish npm package with OIDC'); + const publication = workflow.jobs.publish.steps.find( + (step) => step.name === 'Publish npm package with OIDC', + ); assert.match(publication.run, /npm publish "\.\/\$archive" --ignore-scripts/); - assert.ok(!workflow.jobs.publish.steps.some((step) => /pnpm build/.test(step.run || ''))); + assert.ok( + !workflow.jobs.publish.steps.some((step) => + /pnpm build/.test(step.run || ''), + ), + ); }); -for (const scenario of ['dirty-source', 'stale-commit', 'dirty-build', 'changed-lock', 'changed-output', 'missing-output', 'extra-output']) { +for (const scenario of [ + 'dirty-source', + 'stale-commit', + 'dirty-build', + 'changed-lock', + 'changed-output', + 'missing-output', + 'extra-output', +]) { test(`native npm pack rejects ${scenario} before producing an archive`, async (t) => { const { root, output, pack } = await packageFixture(t); const manifestFile = path.join(root, 'static/build-info.json'); const manifest = JSON.parse(await fs.readFile(manifestFile, 'utf8')); - if (scenario === 'dirty-source') await fs.appendFile(path.join(root, 'shell/start.sh'), '\n# uncommitted change\n'); + if (scenario === 'dirty-source') + await fs.appendFile( + path.join(root, 'shell/start.sh'), + '\n# uncommitted change\n', + ); if (scenario === 'stale-commit') { - await fs.appendFile(path.join(root, 'shell/start.sh'), '\n# committed change after build\n'); + await fs.appendFile( + path.join(root, 'shell/start.sh'), + '\n# committed change after build\n', + ); await execute('git', ['add', '-A'], { cwd: root }); - await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'new source'], { cwd: root }); + await execute( + 'git', + [ + '-c', + 'user.name=Package Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'core.hooksPath=/dev/null', + 'commit', + '-qm', + 'new source', + ], + { cwd: root }, + ); } - if (scenario === 'dirty-build') { manifest.dirty = true; await fs.writeFile(manifestFile, JSON.stringify(manifest)); } - if (scenario === 'changed-lock') { - await fs.appendFile(path.join(root, 'pnpm-lock.yaml'), '# changed lock\n'); - await execute('git', ['add', '-A'], { cwd: root }); - await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'new lock'], { cwd: root }); - manifest.sourceCommit = (await execute('git', ['rev-parse', 'HEAD'], { cwd: root })).stdout.trim(); + if (scenario === 'dirty-build') { + manifest.dirty = true; await fs.writeFile(manifestFile, JSON.stringify(manifest)); } - if (scenario === 'changed-output') await fs.appendFile(path.join(root, 'static/build/app.js'), 'changed'); - if (scenario === 'missing-output') await fs.rm(path.join(root, 'static/build/app.js')); - if (scenario === 'extra-output') await fs.writeFile(path.join(root, 'static/build/leftover.js'), 'old'); + if (scenario === 'changed-lock') { + await fs.appendFile( + path.join(root, 'pnpm-lock.yaml'), + '# changed lock\n', + ); + await execute('git', ['add', '-A'], { cwd: root }); + await execute( + 'git', + [ + '-c', + 'user.name=Package Test', + '-c', + 'user.email=test@example.invalid', + '-c', + 'core.hooksPath=/dev/null', + 'commit', + '-qm', + 'new lock', + ], + { cwd: root }, + ); + manifest.sourceCommit = ( + await execute('git', ['rev-parse', 'HEAD'], { cwd: root }) + ).stdout.trim(); + await fs.writeFile(manifestFile, JSON.stringify(manifest)); + } + if (scenario === 'changed-output') + await fs.appendFile(path.join(root, 'static/build/app.js'), 'changed'); + if (scenario === 'missing-output') + await fs.rm(path.join(root, 'static/build/app.js')); + if (scenario === 'extra-output') + await fs.writeFile(path.join(root, 'static/build/leftover.js'), 'old'); await assert.rejects(pack(), (error) => { - assert.match(error.stderr, /clean source|do not match|checksum mismatch|file set mismatch/i); + assert.match( + error.stderr, + /clean source|do not match|checksum mismatch|file set mismatch/i, + ); return true; }); assert.deepEqual(await fs.readdir(output), []); - await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), { code: 'ENOENT' }); + await assert.rejects( + fs.access(path.join(root, 'shell/upgrade-lock.yaml')), + { code: 'ENOENT' }, + ); }); } diff --git a/test/back/npm-publication.test.cjs b/test/back/npm-publication.test.cjs index 41e2a68f..603311d4 100644 --- a/test/back/npm-publication.test.cjs +++ b/test/back/npm-publication.test.cjs @@ -13,10 +13,7 @@ const publication = workflow.jobs.publish.steps.find( ).run; test('npm publication waits for every supported release image', () => { - for (const name of [ - 'build-alpine', - 'build-debian', - ]) + for (const name of ['build-alpine', 'build-debian']) assert.ok(workflow.jobs.publish.needs.includes(name), name); }); @@ -42,7 +39,11 @@ for (const [scenario, expectedStatus, published] of [ path.join(root, 'package/package.json'), JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' }), ); - const packed = spawnSync('tar', ['-czf', 'npm-panel/verified.tgz', 'package'], { cwd: root }); + const packed = spawnSync( + 'tar', + ['-czf', 'npm-panel/verified.tgz', 'package'], + { cwd: root }, + ); assert.equal(packed.status, 0, String(packed.stderr)); fs.writeFileSync( path.join(bin, 'npm'), @@ -77,8 +78,15 @@ case 'network': console.log('upstream unavailable'); process.exit(1); assert.equal(result.status, expectedStatus, result.stdout + result.stderr); assert.equal(fs.existsSync(path.join(root, 'published')), published); if (published) - assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'published'), 'utf8')), [ - './npm-panel/verified.tgz', '--ignore-scripts', '--access', 'public', '--registry=https://registry.npmjs.org', - ]); + assert.deepEqual( + JSON.parse(fs.readFileSync(path.join(root, 'published'), 'utf8')), + [ + './npm-panel/verified.tgz', + '--ignore-scripts', + '--access', + 'public', + '--registry=https://registry.npmjs.org', + ], + ); }); } diff --git a/test/back/offline-upgrade-recovery.test.cjs b/test/back/offline-upgrade-recovery.test.cjs index f796a07a..13ee28ae 100644 --- a/test/back/offline-upgrade-recovery.test.cjs +++ b/test/back/offline-upgrade-recovery.test.cjs @@ -9,22 +9,36 @@ const artifacts = require('../../cli/src/internal/maintenance/upgradeArtifacts.c const { installBundle } = require('../../shell/install-bundle.cjs'); test('offline environment loading treats installation paths as data and preserves the caller directory', async (t) => { - const directory = await fs.mkdtemp(path.join(require('node:os').tmpdir(), 'ql-offline-path-')); + const directory = await fs.mkdtemp( + path.join(require('node:os').tmpdir(), 'ql-offline-path-'), + ); t.after(() => fs.rm(directory, { recursive: true, force: true })); - const root = path.join(directory, 'panel space \' " $(echo injected) `echo injected`;'); + const root = path.join( + directory, + 'panel space \' " $(echo injected) `echo injected`;', + ); await fs.mkdir(path.join(root, 'shell'), { recursive: true }); - await fs.writeFile(path.join(root, 'shell/share.sh'), 'import_config() { ql_port=5789; ql_base_url=/panel/; }\n'); - await fs.writeFile(path.join(root, 'shell/env.sh'), 'export QL_BRANCH=develop\n'); + await fs.writeFile( + path.join(root, 'shell/share.sh'), + 'import_config() { ql_port=5789; ql_base_url=/panel/; }\n', + ); + await fs.writeFile( + path.join(root, 'shell/env.sh'), + 'export QL_BRANCH=develop\n', + ); const cwd = process.cwd(); let captured; t.mock.method(artifacts, 'stageUpgrade', async ({ env }) => { captured = env; throw new Error('reached staging'); }); - await assert.rejects(installBundle( - ['--file', path.join(root, 'unused.tar.gz'), '--download-only'], - { ...process.env, QL_DIR: root }, - ), /reached staging/); + await assert.rejects( + installBundle( + ['--file', path.join(root, 'unused.tar.gz'), '--download-only'], + { ...process.env, QL_DIR: root }, + ), + /reached staging/, + ); assert.equal(captured.QL_DIR, root); assert.equal(captured.QlPort, '5789'); assert.equal(captured.QlBaseUrl, '/panel/'); diff --git a/test/back/panel-upgrade.test.cjs b/test/back/panel-upgrade.test.cjs index 367e8bc7..fdc37d77 100644 --- a/test/back/panel-upgrade.test.cjs +++ b/test/back/panel-upgrade.test.cjs @@ -245,7 +245,12 @@ test('a terminal state published between the status read and PID probe wins', as const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-finished-job-')); t.after(() => fs.rm(tmp, { recursive: true, force: true })); const file = path.join(tmp, 'panel-upgrade.json'); - const running = { id: 'finishing', status: 'running', pid: 123456, startedAt: 1 }; + const running = { + id: 'finishing', + status: 'running', + pid: 123456, + startedAt: 1, + }; await fs.writeFile(file, JSON.stringify(running)); const kill = process.kill; t.mock.method(process, 'kill', (pid, signal) => { diff --git a/test/back/preload-lazy-notify.test.cjs b/test/back/preload-lazy-notify.test.cjs index 8863ca25..fd932d58 100644 --- a/test/back/preload-lazy-notify.test.cjs +++ b/test/back/preload-lazy-notify.test.cjs @@ -9,14 +9,29 @@ function fixture(t, language) { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-lazy-notify-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const extension = language === 'python' ? 'py' : 'js'; - fs.copyFileSync(`shell/preload/sitecustomize.${extension}`, path.join(root, `sitecustomize.${extension}`)); + fs.copyFileSync( + `shell/preload/sitecustomize.${extension}`, + path.join(root, `sitecustomize.${extension}`), + ); fs.writeFileSync(path.join(root, `env.${extension}`), ''); fs.writeFileSync(path.join(root, 'before.sh'), 'export FROM_SHELL=before\n'); - fs.writeFileSync(path.join(root, 'before.js'), 'process.env.FROM_LANGUAGE = "javascript";\n'); - fs.writeFileSync(path.join(root, 'task_before.py'), 'import os\nos.environ["FROM_LANGUAGE"] = "python"\n'); - fs.writeFileSync(path.join(root, 'client.js'), 'module.exports = { getEnvs: () => "client-ready" };\n'); + fs.writeFileSync( + path.join(root, 'before.js'), + 'process.env.FROM_LANGUAGE = "javascript";\n', + ); + fs.writeFileSync( + path.join(root, 'task_before.py'), + 'import os\nos.environ["FROM_LANGUAGE"] = "python"\n', + ); + fs.writeFileSync( + path.join(root, 'client.js'), + 'module.exports = { getEnvs: () => "client-ready" };\n', + ); fs.copyFileSync('shell/preload/client.py', path.join(root, 'client.py')); - fs.copyFileSync('shell/preload/esm-loader.mjs', path.join(root, 'esm-loader.mjs')); + fs.copyFileSync( + 'shell/preload/esm-loader.mjs', + path.join(root, 'esm-loader.mjs'), + ); const env = { ...process.env, PYTHONPATH: root, @@ -37,9 +52,13 @@ function fixture(t, language) { const entry = path.join(root, `entry.${extensionOverride}`); write(path.basename(entry), body); const python = language === 'python'; - const result = spawnSync(python ? 'python3' : process.execPath, - python ? [entry] : ['--require', path.join(root, 'sitecustomize.js'), entry], - { cwd: root, env, encoding: 'utf8', timeout: 15000 }); + const result = spawnSync( + python ? 'python3' : process.execPath, + python + ? [entry] + : ['--require', path.join(root, 'sitecustomize.js'), entry], + { cwd: root, env, encoding: 'utf8', timeout: 15000 }, + ); assert.equal(result.status, 0, result.stderr + result.stdout); return result.stdout; }; @@ -49,29 +68,42 @@ function fixture(t, language) { for (const extension of ['js', 'mjs']) { test(`${extension} startup preserves hooks, environment selection and client without importing notifications`, (t) => { const f = fixture(t, 'javascript'); - f.write('__ql_notify__.js', 'throw Error("notification dependencies must not load at startup");'); - f.run(` - const assert = ${extension === 'mjs' ? '(await import("node:assert/strict")).default' : 'require("node:assert/strict")'}; + f.write( + '__ql_notify__.js', + 'throw Error("notification dependencies must not load at startup");', + ); + f.run( + ` + const assert = ${ + extension === 'mjs' + ? '(await import("node:assert/strict")).default' + : 'require("node:assert/strict")' + }; assert.equal(process.env.FROM_SHELL, 'before'); assert.equal(process.env.FROM_LANGUAGE, 'javascript'); assert.equal(process.env.FROM_COMMAND, 'command'); assert.equal(process.env.ACCOUNTS, 'second&third'); assert.equal(QLAPI.getEnvs(), 'client-ready'); assert.equal(typeof QLAPI.notify, 'function'); - `, extension); + `, + extension, + ); }); } test('JavaScript first notification imports once and preserves arguments, this, promises and errors', (t) => { const f = fixture(t, 'javascript'); - f.write('__ql_notify__.js', ` + f.write( + '__ql_notify__.js', + ` global.notificationLoads = (global.notificationLoads || 0) + 1; exports.sendNotify = function (...args) { if (args[0] === 'fail') throw new Error('send failed'); global.notificationResult = Promise.resolve({ args, receiver: this }); return global.notificationResult; }; - `); + `, + ); f.run(` const assert = require('node:assert/strict'); assert.equal(global.notificationLoads, undefined); @@ -91,10 +123,13 @@ test('JavaScript first notification imports once and preserves arguments, this, test('JavaScript reports import failures on notify and permits a later retry', (t) => { const f = fixture(t, 'javascript'); - f.write('__ql_notify__.js', ` + f.write( + '__ql_notify__.js', + ` if (!process.env.NOTIFY_READY) throw Error('notification dependency unavailable'); exports.sendNotify = (...args) => args; - `); + `, + ); f.run(` const assert = require('node:assert/strict'); assert.equal(QLAPI.getEnvs(), 'client-ready'); @@ -106,7 +141,10 @@ test('JavaScript reports import failures on notify and permits a later retry', ( test('Python startup preserves hooks, environment selection and client without importing notifications', (t) => { const f = fixture(t, 'python'); - f.write('__ql_notify__.py', 'raise RuntimeError("notification dependencies must not load at startup")\n'); + f.write( + '__ql_notify__.py', + 'raise RuntimeError("notification dependencies must not load at startup")\n', + ); f.run(` import os, sys assert os.environ['FROM_SHELL'] == 'before' @@ -121,14 +159,17 @@ assert callable(QLAPI.getEnvs) test('Python first notification imports once and preserves args, kwargs, return values and errors', (t) => { const f = fixture(t, 'python'); - f.write('__ql_notify__.py', ` + f.write( + '__ql_notify__.py', + ` import builtins builtins.notification_loads = getattr(builtins, 'notification_loads', 0) + 1 def send(*args, **kwargs): if args[0] == 'fail': raise ValueError('send failed') return args, kwargs -`); +`, + ); f.run(` import builtins, sys assert '__ql_notify__' not in sys.modules @@ -146,13 +187,16 @@ else: test('Python reports import failures on notify and permits a later retry', (t) => { const f = fixture(t, 'python'); - f.write('__ql_notify__.py', ` + f.write( + '__ql_notify__.py', + ` import os if not os.environ.get('NOTIFY_READY'): raise RuntimeError('notification dependency unavailable') def send(*args, **kwargs): return args -`); +`, + ); f.run(` import os, sys assert '__ql_notify__' not in sys.modules @@ -172,16 +216,37 @@ for (const extension of ['js', 'mjs', 'py']) { const f = fixture(t, extension === 'py' ? 'python' : 'javascript'); const marker = path.join(f.root, 'started'); f.env.QL_SCRIPT_START_FILE = marker; - f.env.QL_SCRIPT_ENTRY = path.join(fs.realpathSync(f.root), 'entry.' + extension); - fs.copyFileSync('shell/preload/script-start.cjs', path.join(f.root, 'script-start.cjs')); - f.write('before.sh', 'test ! -e "$QL_SCRIPT_START_FILE" && touch "$dir_scripts/hook-ran"\n'); - const read = "const stamp = Number(fs.readFileSync(process.env.QL_SCRIPT_START_FILE, 'utf8'));"; - const check = "if (!Number.isSafeInteger(stamp) || stamp <= 0 || stamp > Date.now()) throw Error('invalid entry timestamp');"; + f.env.QL_SCRIPT_ENTRY = path.join( + fs.realpathSync(f.root), + 'entry.' + extension, + ); + fs.copyFileSync( + 'shell/preload/script-start.cjs', + path.join(f.root, 'script-start.cjs'), + ); + f.write( + 'before.sh', + 'test ! -e "$QL_SCRIPT_START_FILE" && touch "$dir_scripts/hook-ran"\n', + ); + const read = + "const stamp = Number(fs.readFileSync(process.env.QL_SCRIPT_START_FILE, 'utf8'));"; + const check = + "if (!Number.isSafeInteger(stamp) || stamp <= 0 || stamp > Date.now()) throw Error('invalid entry timestamp');"; if (extension === 'py') { - f.run("assert 0 < int(open(__import__('os').environ['QL_SCRIPT_START_FILE']).read()) <= __import__('time').time_ns() // 1000000\n"); + f.run( + "assert 0 < int(open(__import__('os').environ['QL_SCRIPT_START_FILE']).read()) <= __import__('time').time_ns() // 1000000\n", + ); } else if (extension === 'mjs') { - f.write('dependency.mjs', "import fs from 'node:fs'; if (fs.existsSync(process.env.QL_SCRIPT_START_FILE)) throw Error('entry reported during dependency evaluation');"); - f.run("import './dependency.mjs';\nimport fs from 'node:fs';\n" + read + check, extension); + f.write( + 'dependency.mjs', + "import fs from 'node:fs'; if (fs.existsSync(process.env.QL_SCRIPT_START_FILE)) throw Error('entry reported during dependency evaluation');", + ); + f.run( + "import './dependency.mjs';\nimport fs from 'node:fs';\n" + + read + + check, + extension, + ); } else { f.run("const fs = require('node:fs'); " + read + check); } @@ -199,14 +264,25 @@ test('the panel client defers gRPC until an API call, uses panel dependencies an fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'index.js'), source); } - packageFile(f.env.QL_NODE_GLOBAL_PATH, '@grpc/grpc-js', 'exports.fromGlobal = true;'); - packageFile(f.root, '@grpc/proto-loader', ` + packageFile( + f.env.QL_NODE_GLOBAL_PATH, + '@grpc/grpc-js', + 'exports.fromGlobal = true;', + ); + packageFile( + f.root, + '@grpc/proto-loader', + ` exports.loadSync = () => { if (process.env.FAIL_PROTO === '1') throw Error('missing proto'); return {}; }; - `); - packageFile(f.root, '@grpc/grpc-js', ` + `, + ); + packageFile( + f.root, + '@grpc/grpc-js', + ` global.grpcLoads = (global.grpcLoads || 0) + 1; exports.credentials = { createInsecure: () => ({}) }; exports.Metadata = class {}; @@ -216,7 +292,8 @@ test('the panel client defers gRPC until an API call, uses panel dependencies an close() { global.closes = (global.closes || 0) + 1; } } exports.loadPackageDefinition = () => ({com: { ql: { api: {Api} }}}); - `); + `, + ); f.run(` const assert = require('node:assert/strict'); (async () => { diff --git a/test/back/primary-apm.test.cjs b/test/back/primary-apm.test.cjs index 7da791a4..8dc6cd08 100644 --- a/test/back/primary-apm.test.cjs +++ b/test/back/primary-apm.test.cjs @@ -2,24 +2,72 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const vm = require('node:vm'); const fs = require('node:fs'); -const configRequire = require('node:module').createRequire(require('node:path').resolve('ecosystem.config.js')); +const configRequire = require('node:module').createRequire( + require('node:path').resolve('ecosystem.config.js'), +); const source = fs.readFileSync('ecosystem.config.js', 'utf8'); const appSource = fs.readFileSync('back/app.ts', 'utf8'); const ts = require('typescript'); -const compiled = ts.transpileModule(appSource.slice(0, appSource.indexOf('\nconst app = new Application();')) + '\nmodule.exports = Application;', {compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText; -function config(env) {const module={exports:{}};vm.runInNewContext(source,{module,process:{env},require:configRequire});return module.exports.apps[0];} +const compiled = ts.transpileModule( + appSource.slice(0, appSource.indexOf('\nconst app = new Application();')) + + '\nmodule.exports = Application;', + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + esModuleInterop: true, + }, + }, +).outputText; +function config(env) { + const module = { exports: {} }; + vm.runInNewContext(source, { + module, + process: { env }, + require: configRequire, + }); + return module.exports.apps[0]; +} test('container APM policy keeps worker isolation and can restore all inherited probes', () => { - for (const primary of [undefined, 'true']) for (const workers of [undefined, 'true']) { - const env={QL_CONTAINER:'true',QL_PRIMARY_APM:primary,QL_WORKER_APM:workers}; - const conf=config(env);env.pm_id='0';env.pmx=String(conf.pmx); - const calls=[],module={exports:{}}; - vm.runInNewContext(compiled,{module,exports:module.exports,process:{env},require(name){if(name==='cluster')return {fork(options){calls.push({...env,...options});return {id:1,process:{pid:123},on(){}}}};if(name==='express')return ()=>({use(){}});return {};}}); - new module.exports().forkWorker('http'); - assert.equal(conf.pmx,primary==='true'); - assert.equal(calls[0].pmx,primary==='true'&&workers==='true'?'true':'false'); - assert.equal(conf.max_restarts,5);assert.equal(conf.script,'static/build/app.js'); - } + for (const primary of [undefined, 'true']) + for (const workers of [undefined, 'true']) { + const env = { + QL_CONTAINER: 'true', + QL_PRIMARY_APM: primary, + QL_WORKER_APM: workers, + }; + const conf = config(env); + env.pm_id = '0'; + env.pmx = String(conf.pmx); + const calls = [], + module = { exports: {} }; + vm.runInNewContext(compiled, { + module, + exports: module.exports, + process: { env }, + require(name) { + if (name === 'cluster') + return { + fork(options) { + calls.push({ ...env, ...options }); + return { id: 1, process: { pid: 123 }, on() {} }; + }, + }; + if (name === 'express') return () => ({ use() {} }); + return {}; + }, + }); + new module.exports().forkWorker('http'); + assert.equal(conf.pmx, primary === 'true'); + assert.equal( + calls[0].pmx, + primary === 'true' && workers === 'true' ? 'true' : 'false', + ); + assert.equal(conf.max_restarts, 5); + assert.equal(conf.script, 'static/build/app.js'); + } }); test('standalone PM2 monitoring stays enabled', () => { - for(const QL_PRIMARY_APM of [undefined,'true','false']) assert.equal(config({QL_PRIMARY_APM}).pmx,true); + for (const QL_PRIMARY_APM of [undefined, 'true', 'false']) + assert.equal(config({ QL_PRIMARY_APM }).pmx, true); }); diff --git a/test/back/process-stop-signal.test.cjs b/test/back/process-stop-signal.test.cjs index c705f2f5..0c6353c1 100644 --- a/test/back/process-stop-signal.test.cjs +++ b/test/back/process-stop-signal.test.cjs @@ -8,12 +8,14 @@ test('BSD identity and parent lookups distinguish a vanished PID from ps failure const platform = Object.getOwnPropertyDescriptor(process, 'platform'); const pid = process.pid; let result, field; - const probes = load('back/shared/cronProcess.ts', { - child_process: { spawnSync(command, args) { - assert.equal(command, 'ps'); - assert.deepEqual(args, ['-p', String(pid), '-o', field + '=']); - return result; - } }, + const probes = load('back/cron/execution/cronProcess.ts', { + child_process: { + spawnSync(command, args) { + assert.equal(command, 'ps'); + assert.deepEqual(args, ['-p', String(pid), '-o', field + '=']); + return result; + }, + }, }); Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' }); try { @@ -30,7 +32,12 @@ test('BSD identity and parent lookups distinguish a vanished PID from ps failure { status: null, signal: 'SIGTERM', stdout: '', stderr: '' }, { error: Object.assign(Error('spawn ps ENOENT'), { code: 'ENOENT' }) }, ]) { - assert.throws(probe, error => !['ESRCH', 'ENOENT'].includes(error.code) && /ps|PID/.test(error.message)); + assert.throws( + probe, + (error) => + !['ESRCH', 'ENOENT'].includes(error.code) && + /ps|PID/.test(error.message), + ); } } } finally { @@ -51,7 +58,16 @@ function fixture(descendants, probe = () => {}, birth, descendant) { }).outputText; const signals = []; const exports = {}; - new Function('exports', 'process', 'psTree', 'fs', 'setTimeout', 'systemOwner', 'isProcessDescendant', code)( + new Function( + 'exports', + 'process', + 'psTree', + 'fs', + 'setTimeout', + 'systemOwner', + 'isProcessDescendant', + code, + )( exports, { platform: 'linux', @@ -63,7 +79,9 @@ function fixture(descendants, probe = () => {}, birth, descendant) { }, async () => [...descendants], {}, - setTimeout, birth, descendant, + setTimeout, + birth, + descendant, ); return { killTask: exports.killTask, signals }; } @@ -114,41 +132,83 @@ test('a leaf retains SIGINT and a process tree retains child-first SIGTERM', asy test('verified stop ignores reused, vanished and reparented descendants from the tree snapshot', async () => { const seen = new Set(); let rootExited = false; - const birth = pid => { - if (pid === 102 || (pid === 100 && rootExited)) throw Object.assign(Error('gone'), { code: 'ESRCH' }); + const birth = (pid) => { + if (pid === 102 || (pid === 100 && rootExited)) + throw Object.assign(Error('gone'), { code: 'ESRCH' }); if (pid === 101 && seen.has(pid)) return 'replacement'; seen.add(pid); return 'original-' + pid; }; - const f = fixture([101, 102, 103], (pid, sig) => { - if (pid === 100 && sig === 'SIGTERM') rootExited = true; - }, birth, pid => pid !== 103); - await f.killTask(100, true, () => {}, async signal => signal()); + const f = fixture( + [101, 102, 103], + (pid, sig) => { + if (pid === 100 && sig === 'SIGTERM') rootExited = true; + }, + birth, + (pid) => pid !== 103, + ); + await f.killTask( + 100, + true, + () => {}, + async (signal) => signal(), + ); assert.deepEqual(f.signals, [[100, 'SIGTERM']]); }); test('a root exiting immediately before TERM cannot claim a stop or signal a surviving child', async () => { - const f = fixture([101], (pid, sig) => { - if (pid === 100 && sig === 'SIGTERM') throw Object.assign(Error('gone'), { code: 'ESRCH' }); - }, pid => 'birth-' + pid, () => true); + const f = fixture( + [101], + (pid, sig) => { + if (pid === 100 && sig === 'SIGTERM') + throw Object.assign(Error('gone'), { code: 'ESRCH' }); + }, + (pid) => 'birth-' + pid, + () => true, + ); let committed = false; - await assert.rejects(f.killTask(100, true, () => {}, async signal => { - signal(); - committed = true; - }), { code: 'ESRCH' }); + await assert.rejects( + f.killTask( + 100, + true, + () => {}, + async (signal) => { + signal(); + committed = true; + }, + ), + { code: 'ESRCH' }, + ); assert.equal(committed, false); assert.deepEqual(f.signals, [[100, 'SIGTERM']]); }); test('a descendant delivery failure after root TERM preserves the claim and still signals siblings', async () => { const denied = Object.assign(Error('denied'), { code: 'EPERM' }); - const f = fixture([101, 102], (pid, signal) => { - if (pid === 102 && signal === 'SIGTERM') throw denied; - }, pid => 'birth-' + pid, () => true); - await assert.rejects(f.killTask(100, true, () => {}, async signal => { - const delivery = signal(); - assert.equal(delivery, denied); - throw delivery; - }), error => error === denied); - assert.deepEqual(f.signals, [[100, 'SIGTERM'], [102, 'SIGTERM'], [101, 'SIGTERM']]); + const f = fixture( + [101, 102], + (pid, signal) => { + if (pid === 102 && signal === 'SIGTERM') throw denied; + }, + (pid) => 'birth-' + pid, + () => true, + ); + await assert.rejects( + f.killTask( + 100, + true, + () => {}, + async (signal) => { + const delivery = signal(); + assert.equal(delivery, denied); + throw delivery; + }, + ), + (error) => error === denied, + ); + assert.deepEqual(f.signals, [ + [100, 'SIGTERM'], + [102, 'SIGTERM'], + [101, 'SIGTERM'], + ]); }); diff --git a/test/back/protected-path-case.test.cjs b/test/back/protected-path-case.test.cjs index f4e290bc..2cb1adec 100644 --- a/test/back/protected-path-case.test.cjs +++ b/test/back/protected-path-case.test.cjs @@ -1,9 +1,8 @@ const assert = require('node:assert/strict'); const test = require('node:test'); -const protectedPathCase = require( - '../../back/middlewares/protectedPathCase', -).default; +const protectedPathCase = + require('../../back/middlewares/protectedPathCase').default; function runMiddleware(path) { let status; diff --git a/test/back/qlServiceLogCommand.test.cjs b/test/back/qlServiceLogCommand.test.cjs index fa28585d..eea62426 100644 --- a/test/back/qlServiceLogCommand.test.cjs +++ b/test/back/qlServiceLogCommand.test.cjs @@ -77,7 +77,9 @@ test('ql log reads the requested system log history without PM2', () => { test('ql log follows the current Winston system log without PM2', () => { const { binDir, shellDir, testRoot } = prepareFixture('container'); const systemLogDir = path.join(testRoot, 'data/syslog'); - const currentDate = spawnSync('date', ['+%F'], { encoding: 'utf8' }).stdout.trim(); + const currentDate = spawnSync('date', ['+%F'], { + encoding: 'utf8', + }).stdout.trim(); const currentLog = path.join(systemLogDir, `${currentDate}.log`); fs.mkdirSync(systemLogDir, { recursive: true }); fs.writeFileSync(currentLog, 'system-one\n'); diff --git a/test/back/queued-cron-invalidation.test.cjs b/test/back/queued-cron-invalidation.test.cjs index 026e1c63..c5281b00 100644 --- a/test/back/queued-cron-invalidation.test.cjs +++ b/test/back/queued-cron-invalidation.test.cjs @@ -2,97 +2,241 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const load = require('../helpers/load-security-module.cjs'); const tick = () => new Promise(setImmediate); -function gate() { let release; const promise = new Promise(r => release = r); return { promise, release }; } - -async function fixture() { - const logger = { info() {}, error() {}, warn() {} }, notices = []; - const limit = load('back/shared/pLimit.ts', { - '../data/system': { AuthDataType: { systemConfig: 'systemConfig' }, SystemModel: { sync: async () => {}, findOne: async () => ({ info: { cronConcurrency: 1 } }) } }, - '../loaders/logger': logger, - '../services/notify': class {}, - '../shared/i18n': { t: s => s, tf: s => s }, - '../config': { grpcPort: 1 }, - '../protos/api': { ApiClient: class { systemNotify(value, cb) { notices.push(value); cb(); } } }, - '../config/grpcCerts': { getGrpcCerts: () => null }, - }).default; - await tick(); - const spawned = [], records = new Map(), jobs = new Map(); - let readGate, killGate; - const { runCron } = load('back/shared/runCron.ts', { - 'cross-spawn': { spawn: command => { spawned.push(command); return {}; } }, - './pLimit': limit, - '../loaders/logger': logger, - '../data/cron': { CrontabModel: { findOne: async ({ where }) => { const row = records.get(String(where.id)); if (readGate) await readGate.promise; return row; }, update: async () => {} }, CrontabStatus: { running: 0, queued: 3, idle: 1 } }, - '../data/runningInstance': { RunningInstanceModel: { update: async () => {} }, InstanceStatus: { running: 0, stopped: 2 } }, - '../config/util': { killTask: async () => { if (killGate) await killGate.promise; } }, - './childProcess': { observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }), asError: e => e }, - }); - const { addCron } = load('back/schedule/addCron.ts', { - '../shared/cronScheduler': { createCronJob: (schedule, callback) => ({ start() {}, cancel() {}, fire: callback }) }, - '../shared/cronSchedule': { isValidCronSchedule: x => x !== 'invalid' }, - './data': { scheduleStacks: jobs }, '../shared/runCron': { runCron }, '../loaders/logger': logger, - '../shared/i18n': { t: (s) => s, tf: s => s }, - }); - const { delCron } = load('back/schedule/delCron.ts', { './data': { scheduleStacks: jobs }, '../loaders/logger': logger }); - function add(id = '1', command = 'old', replace = false) { - records.set(id, { isDisabled: 0, allow_multiple_instances: 1 }); - addCron({ request: { crons: [{ id, command, schedule: '* * * * * *' }], replace } }, err => assert.ifError(err)); - return jobs.get(id)[0]; - } - function remove(id = '1') { delCron({ request: { ids: [id] } }, err => assert.ifError(err)); } - async function block() { const g = gate(); const done = limit.runWithCronLimit({ id: 'blocker' }, async () => { await g.promise; }); await tick(); return { release: async () => { g.release(); await done; } }; } - return { limit, spawned, records, jobs, add, remove, block, notices, setReadGate: g => readGate = g, setKillGate: g => killGate = g }; +function gate() { + let release; + const promise = new Promise((r) => (release = r)); + return { promise, release }; } -for (const operation of ['disable', 'delete', 'update', 'replace', 'disable-enable']) { +async function fixture() { + const logger = { info() {}, error() {}, warn() {} }, + notices = []; + const limit = load('back/cron/execution/cronLimit.ts', { + '../../data/system': { + AuthDataType: { systemConfig: 'systemConfig' }, + SystemModel: { + sync: async () => {}, + findOne: async () => ({ info: { cronConcurrency: 1 } }), + }, + }, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../shared/i18n': { t: (s) => s, tf: (s) => s }, + '../../config': { grpcPort: 1 }, + '../../protos/api': { + ApiClient: class { + systemNotify(value, cb) { + notices.push(value); + cb(); + } + }, + }, + '../../config/grpcCerts': { getGrpcCerts: () => null }, + }).default; + await tick(); + const spawned = [], + records = new Map(), + jobs = new Map(); + let readGate, killGate; + const { runCron } = load('back/cron/execution/runCron.ts', { + 'cross-spawn': { + spawn: (command) => { + spawned.push(command); + return {}; + }, + }, + './cronLimit': limit, + '../../loaders/logger': logger, + '../../data/cron': { + CrontabModel: { + findOne: async ({ where }) => { + const row = records.get(String(where.id)); + if (readGate) await readGate.promise; + return row; + }, + update: async () => {}, + }, + CrontabStatus: { running: 0, queued: 3, idle: 1 }, + }, + '../../data/runningInstance': { + RunningInstanceModel: { update: async () => {} }, + InstanceStatus: { running: 0, stopped: 2 }, + }, + '../../config/util': { + killTask: async () => { + if (killGate) await killGate.promise; + }, + }, + '../../shared/childProcess': { + observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }), + asError: (e) => e, + }, + }); + const { addCron } = load('back/schedule/addCron.ts', { + '../cron/scheduling/cronScheduler': { + createCronJob: (schedule, callback) => ({ + start() {}, + cancel() {}, + fire: callback, + }), + }, + '../cron/scheduling/cronSchedule': { + isValidCronSchedule: (x) => x !== 'invalid', + }, + './data': { scheduleStacks: jobs }, + '../cron/execution/runCron': { runCron }, + '../loaders/logger': logger, + '../shared/i18n': { t: (s) => s, tf: (s) => s }, + }); + const { delCron } = load('back/schedule/delCron.ts', { + './data': { scheduleStacks: jobs }, + '../loaders/logger': logger, + }); + function add(id = '1', command = 'old', replace = false) { + records.set(id, { isDisabled: 0, allow_multiple_instances: 1 }); + addCron( + { + request: { crons: [{ id, command, schedule: '* * * * * *' }], replace }, + }, + (err) => assert.ifError(err), + ); + return jobs.get(id)[0]; + } + function remove(id = '1') { + delCron({ request: { ids: [id] } }, (err) => assert.ifError(err)); + } + async function block() { + const g = gate(); + const done = limit.runWithCronLimit({ id: 'blocker' }, async () => { + await g.promise; + }); + await tick(); + return { + release: async () => { + g.release(); + await done; + }, + }; + } + return { + limit, + spawned, + records, + jobs, + add, + remove, + block, + notices, + setReadGate: (g) => (readGate = g), + setKillGate: (g) => (killGate = g), + }; +} + +for (const operation of [ + 'disable', + 'delete', + 'update', + 'replace', + 'disable-enable', +]) { test(`queued scheduled execution is invalidated by ${operation}`, async () => { - const f = await fixture(), old = f.add(), blocker = await f.block(); + const f = await fixture(), + old = f.add(), + blocker = await f.block(); const queued = old.fire(); - if (operation === 'disable' || operation === 'disable-enable') { f.records.get('1').isDisabled = 1; f.remove(); } - if (operation === 'delete') { f.records.delete('1'); f.remove(); } + if (operation === 'disable' || operation === 'disable-enable') { + f.records.get('1').isDisabled = 1; + f.remove(); + } + if (operation === 'delete') { + f.records.delete('1'); + f.remove(); + } if (operation === 'update') f.add('1', 'new'); if (operation === 'replace') f.add('1', 'new', true); if (operation === 'disable-enable') f.add('1', 'old'); const next = f.jobs.get('1')?.[0].fire(); - await blocker.release(); await queued; await next; - assert.deepEqual(f.spawned, ['update', 'replace'].includes(operation) ? ['new'] : operation === 'disable-enable' ? ['old'] : []); + await blocker.release(); + await queued; + await next; + assert.deepEqual( + f.spawned, + ['update', 'replace'].includes(operation) + ? ['new'] + : operation === 'disable-enable' + ? ['old'] + : [], + ); assert.equal(f.limit.cronLimitPendingCount, 0); assert.equal(f.limit.cronLimitActiveCount, 0); }); } test('stale callbacks cannot re-enqueue after cancellation', async () => { - const f = await fixture(), old = f.add(); f.remove(); await old.fire(); + const f = await fixture(), + old = f.add(); + f.remove(); + await old.fire(); assert.deepEqual(f.spawned, []); }); test('invalidation during an asynchronous database read prevents spawning', async () => { - const f = await fixture(), old = f.add(), pending = gate(); f.setReadGate(pending); - const run = old.fire(); await tick(); f.remove(); pending.release(); await run; + const f = await fixture(), + old = f.add(), + pending = gate(); + f.setReadGate(pending); + const run = old.fire(); + await tick(); + f.remove(); + pending.release(); + await run; assert.deepEqual(f.spawned, []); }); test('invalidation while replacing a running instance prevents the old spawn', async () => { - const f = await fixture(), old = f.add(), pending = gate(); - f.records.set('1', { isDisabled: 0, allow_multiple_instances: 0, pid: 10, status: 0 }); f.setKillGate(pending); - const run = old.fire(); await tick(); f.remove(); pending.release(); await run; + const f = await fixture(), + old = f.add(), + pending = gate(); + f.records.set('1', { + isDisabled: 0, + allow_multiple_instances: 0, + pid: 10, + status: 0, + }); + f.setKillGate(pending); + const run = old.fire(); + await tick(); + f.remove(); + pending.release(); + await run; assert.deepEqual(f.spawned, []); }); test('database removal or disable is respected before scheduler RPC arrives', async () => { for (const disabled of [true, false]) { - const f = await fixture(), old = f.add(), blocker = await f.block(); const run = old.fire(); - if (disabled) f.records.get('1').isDisabled = 1; else f.records.delete('1'); - await blocker.release(); await run; assert.deepEqual(f.spawned, []); + const f = await fixture(), + old = f.add(), + blocker = await f.block(); + const run = old.fire(); + if (disabled) f.records.get('1').isDisabled = 1; + else f.records.delete('1'); + await blocker.release(); + await run; + assert.deepEqual(f.spawned, []); } }); test('five stale runs do not suppress the new revision or erase its repeat accounting', async () => { - const f = await fixture(), old = f.add(), blocker = await f.block(); + const f = await fixture(), + old = f.add(), + blocker = await f.block(); const pending = Array.from({ length: 5 }, () => old.fire()); - const current = f.add('1', 'new'); pending.push(...Array.from({ length: 5 }, () => current.fire())); + const current = f.add('1', 'new'); + pending.push(...Array.from({ length: 5 }, () => current.fire())); assert.equal(f.notices.length, 0); - await blocker.release(); await Promise.all(pending); + await blocker.release(); + await Promise.all(pending); assert.deepEqual(f.spawned, Array(5).fill('new')); - await current.fire(); assert.equal(f.spawned.length, 6); + await current.fire(); + assert.equal(f.spawned.length, 6); }); diff --git a/test/back/release-runtime-alignment.test.cjs b/test/back/release-runtime-alignment.test.cjs index 184ff938..dccb2fd7 100644 --- a/test/back/release-runtime-alignment.test.cjs +++ b/test/back/release-runtime-alignment.test.cjs @@ -18,43 +18,82 @@ test('CI uses the pinned production Node, retaining explicit compatibility cover for (const file of ['docker/Dockerfile', 'docker/Dockerfile.310']) { const versions = [...read(file).matchAll(/\bnode:(\d+\.\d+\.\d+)-alpine/g)]; assert.ok(versions.length >= 2, file); - for (const [, version] of versions) assert.equal(version, productionNode, file); + for (const [, version] of versions) + assert.equal(version, productionNode, file); const packageVersion = read(file).match(/\bnodejs=(\d+\.\d+\.\d+)-r\d+/); assert.ok(packageVersion, `${file}: pin the Alpine Node package`); assert.equal(packageVersion[1], productionNode, file); - assert.ok(read(file).includes(`test "$(node --version)" = "v${productionNode}"`), file); + assert.ok( + read(file).includes(`test "$(node --version)" = "v${productionNode}"`), + file, + ); } - assert.equal(read('docker/install-node-debian.sh').match(/^version=(.*)$/m)[1], productionNode); - for (const file of ['docker/Dockerfile.debian', 'docker/Dockerfile.debian310']) { + assert.equal( + read('docker/install-node-debian.sh').match(/^version=(.*)$/m)[1], + productionNode, + ); + for (const file of [ + 'docker/Dockerfile.debian', + 'docker/Dockerfile.debian310', + ]) { const versions = [...read(file).matchAll(/"v(\d+\.\d+\.\d+)"/g)]; assert.ok(versions.length >= 2, file); - for (const [, version] of versions) assert.equal(version, productionNode, file); + for (const [, version] of versions) + assert.equal(version, productionNode, file); } - for (const name of ['validate', 'release-readiness', 'build-docker-image', 'cli-package']) { + for (const name of [ + 'validate', + 'release-readiness', + 'build-docker-image', + 'cli-package', + ]) { for (const [jobName, job] of Object.entries(workflow(name).jobs)) { const steps = job.steps || []; for (const [index, step] of steps.entries()) { if (!step.uses?.startsWith('actions/setup-node@')) continue; - assert.equal(step.with['node-version-file'], '.nvmrc', `${name}/${jobName}`); - assert.ok(steps.slice(0, index).some((s) => s.uses?.startsWith('actions/checkout@')), `${name}/${jobName}: checkout before version file`); + assert.equal( + step.with['node-version-file'], + '.nvmrc', + `${name}/${jobName}`, + ); + assert.ok( + steps + .slice(0, index) + .some((s) => s.uses?.startsWith('actions/checkout@')), + `${name}/${jobName}: checkout before version file`, + ); const version = step.with['node-version']; if (!version) continue; assert.equal(name, 'cli-package'); assert.equal(jobName, 'package'); for (const node of job.strategy.matrix.node) { - const resolved = vm.runInNewContext(version.slice(3, -2), { matrix: { node } }); - assert.equal(resolved || productionNode, node === '22.12.0' ? node : productionNode); + const resolved = vm.runInNewContext(version.slice(3, -2), { + matrix: { node }, + }); + assert.equal( + resolved || productionNode, + node === '22.12.0' ? node : productionNode, + ); } } } } const build = workflow('build-docker-image'); - const runtime = build.jobs['build-static'].steps.find((s) => s.id === 'runtime'); + const runtime = build.jobs['build-static'].steps.find( + (s) => s.id === 'runtime', + ); assert.match(runtime.run, /cat \.nvmrc/); - assert.equal(build.jobs['build-static'].outputs['node-version'], '${{ steps.runtime.outputs.node-version }}'); + assert.equal( + build.jobs['build-static'].outputs['node-version'], + '${{ steps.runtime.outputs.node-version }}', + ); const verify = build.jobs['verify-npm-package']; - const expression = verify.container.match(/\$\{\{(.*?)\}\}/)[1] - .replace('needs.build-static.outputs.node-version', JSON.stringify(productionNode)); + const expression = verify.container + .match(/\$\{\{(.*?)\}\}/)[1] + .replace( + 'needs.build-static.outputs.node-version', + JSON.stringify(productionNode), + ); for (const node of verify.strategy.matrix.node) { const version = vm.runInNewContext(expression, { matrix: { node } }); assert.equal(version, node === '20.18.1' ? node : productionNode); @@ -63,10 +102,19 @@ test('CI uses the pinned production Node, retaining explicit compatibility cover test('release readiness runs the source verifier offline and watches its inputs', () => { const readiness = workflow('release-readiness'); - for (const file of ['.nvmrc', '.github/workflows/validate.yml', 'docker/install-node-debian.sh', 'scripts/verify-runtime-dependencies.cjs', 'test/back/release-runtime-alignment.test.cjs']) { + for (const file of [ + '.nvmrc', + '.github/workflows/validate.yml', + 'docker/install-node-debian.sh', + 'scripts/verify-runtime-dependencies.cjs', + 'test/back/release-runtime-alignment.test.cjs', + ]) { assert.ok(readiness.on.pull_request.paths.includes(file), file); } - const step = readiness.jobs.images.steps.find((s) => s.name === 'Verify native production runtime without external networking'); + const step = readiness.jobs.images.steps.find( + (s) => + s.name === 'Verify native production runtime without external networking', + ); assert.match(step.run, /docker run --rm -i --network none --entrypoint node/); assert.match(step.run, /< scripts\/verify-runtime-dependencies\.cjs/); }); @@ -79,33 +127,56 @@ function fixture(t) { const write = (file, data) => { const target = path.join(directory, file); fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, typeof data === 'string' ? data : JSON.stringify(data)); + fs.writeFileSync( + target, + typeof data === 'string' ? data : JSON.stringify(data), + ); }; const install = (name, version, parent) => { - const prefix = `node_modules/${parent ? `${parent}/node_modules/` : ''}${name}`; + const prefix = `node_modules/${ + parent ? `${parent}/node_modules/` : '' + }${name}`; write(`${prefix}/package.json`, { name, version, main: 'index.js' }); write(`${prefix}/index.js`, 'module.exports = {};'); }; - for (const name of ['@grpc/grpc-js', 'compression', 'multer', 'sequelize', 'express', 'sockjs']) { + for (const name of [ + '@grpc/grpc-js', + 'compression', + 'multer', + 'sequelize', + 'express', + 'sockjs', + ]) { manifest.dependencies[name] = '1.0.0'; lock.dependencies[name] = { specifier: '1.0.0', version: '1.0.0' }; install(name, '1.0.0'); } - for (const [parent, name] of [['express', 'proxy-addr'], ['sockjs', 'websocket-driver']]) { + for (const [parent, name] of [ + ['express', 'proxy-addr'], + ['sockjs', 'websocket-driver'], + ]) { lock.packages[`/${parent}@1.0.0`] = { dependencies: { [name]: '1.0.0' } }; install(name, '1.0.0', parent); // A healthy root copy must not mask a stale copy resolved by the parent. install(name, '1.0.0'); } - for (const name of ['sqlite3', 'nodemailer', 'undici']) install(name, '1.0.0'); + for (const name of ['sqlite3', 'nodemailer', 'undici']) + install(name, '1.0.0'); write('.nvmrc', process.versions.node); lock.dependencies.sequelize.version = '1.0.0(@whyour/sqlite3@1.1.5)'; const run = (stdin = false) => { write('package.json', manifest); write('pnpm-lock.yaml', yaml.dump(lock)); return spawnSync(process.execPath, stdin ? [] : [verifier], { - cwd: directory, encoding: 'utf8', timeout: 10000, - ...(stdin ? { input: fs.readFileSync(verifier, 'utf8'), env: { ...process.env, NODE_PATH: path.join(root, 'node_modules') } } : {}), + cwd: directory, + encoding: 'utf8', + timeout: 10000, + ...(stdin + ? { + input: fs.readFileSync(verifier, 'utf8'), + env: { ...process.env, NODE_PATH: path.join(root, 'node_modules') }, + } + : {}), }); }; return { manifest, lock, install, run, write }; @@ -124,7 +195,14 @@ test('runtime verification follows dependency upgrades without a second version } }); -for (const scenario of ['node-version', 'manifest', 'direct', 'transitive', 'missing-lock', 'missing-import']) { +for (const scenario of [ + 'node-version', + 'manifest', + 'direct', + 'transitive', + 'missing-lock', + 'missing-import', +]) { test(`runtime verification rejects ${scenario} drift`, (t) => { const f = fixture(t); let expected; @@ -144,7 +222,10 @@ for (const scenario of ['node-version', 'manifest', 'direct', 'transitive', 'mis delete f.lock.packages['/sockjs@1.0.0']; expected = /sockjs > websocket-driver: missing lock entry/; } else { - f.write('node_modules/sqlite3/index.js', 'throw new Error("native binding unavailable")'); + f.write( + 'node_modules/sqlite3/index.js', + 'throw new Error("native binding unavailable")', + ); expected = /native binding unavailable/; } const result = f.run(); diff --git a/test/back/restart-instance-recovery.test.cjs b/test/back/restart-instance-recovery.test.cjs index 72075a42..59fed693 100644 --- a/test/back/restart-instance-recovery.test.cjs +++ b/test/back/restart-instance-recovery.test.cjs @@ -19,26 +19,42 @@ test('startup closes interrupted instances without inventing exit codes or rewri finished_at: DataTypes.INTEGER, exit_code: DataTypes.INTEGER, }); - const crons = db.define('Crontab', { status: DataTypes.INTEGER, pid: DataTypes.INTEGER, queued_token: DataTypes.STRING, command: DataTypes.STRING }); + const crons = db.define('Crontab', { + status: DataTypes.INTEGER, + pid: DataTypes.INTEGER, + queued_token: DataTypes.STRING, + command: DataTypes.STRING, + }); await db.sync(); - await db.transaction(tx => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx)); + await db.transaction((tx) => + require('../../back/cron/history').installTriggerHistory(db, tx), + ); await instances.bulkCreate([ { id: 1, status: 0, started_at: 100 }, { id: 2, status: 1, started_at: 100, finished_at: 110, exit_code: 0 }, { id: 3, status: 2, started_at: 100, finished_at: 120, exit_code: 143 }, { id: 4, status: 3, started_at: 100, finished_at: 130, exit_code: 7 }, ]); - const {TriggerHistory, systemOwner} = require('../../back/shared/triggerHistory'); + const { TriggerHistory, systemOwner } = require('../../back/cron/history'); const history = new TriggerHistory(db); - await crons.create({id: 9, status: 0, pid: process.pid, command: 'task live.sh'}); - await instances.create({id: 9, status: 0, started_at: 100}); - await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,owner,instance_id,observed_at) VALUES ('live',9,'system','running',$owner,9,100)", - {bind:{owner:systemOwner(process.pid)}}); + await crons.create({ + id: 9, + status: 0, + pid: process.pid, + command: 'task live.sh', + }); + await instances.create({ id: 9, status: 0, started_at: 100 }); + await db.query( + "INSERT INTO CronTriggers(id,cron_id,source,state,owner,instance_id,observed_at) VALUES ('live',9,'system','running',$owner,9,100)", + { bind: { owner: systemOwner(process.pid) } }, + ); await history.interrupt('http'); const systemConfig = { info: { lang: 'en-US' } }; const startupEvents = []; const service = { - set_envs: async () => { startupEvents.push('environment'); }, + set_envs: async () => { + startupEvents.push('environment'); + }, getAuthInfo: async () => ({}), initializeSystemApp: async () => {}, refreshApps: async () => {}, @@ -52,7 +68,11 @@ test('startup closes interrupted instances without inventing exit codes or rewri '../services/user': class {}, '../services/open': class {}, '../data/cron': { - CrontabModel: { sequelize: db, update: async () => {}, findAll: async () => [] }, + CrontabModel: { + sequelize: db, + update: async () => {}, + findAll: async () => [], + }, CrontabStatus: { idle: 1 }, }, '../data/dependence': { @@ -85,7 +105,9 @@ test('startup closes interrupted instances without inventing exit codes or rewri '../schedule/client': { readiness: { configure() {}, - recover: async () => { startupEvents.push('scheduler'); }, + recover: async () => { + startupEvents.push('scheduler'); + }, }, }, }).default; @@ -99,9 +121,13 @@ test('startup closes interrupted instances without inventing exit codes or rewri global.setTimeout = originalTimeout; } assert.deepEqual(startupEvents, ['environment', 'scheduler']); - assert.equal((await instances.findByPk(9)).status,0); - assert.equal((await crons.findByPk(9)).pid,process.pid); - const rows = await instances.findAll({ where:{id:[1,2,3,4]}, order: [['id', 'ASC']], raw: true }); + assert.equal((await instances.findByPk(9)).status, 0); + assert.equal((await crons.findByPk(9)).pid, process.pid); + const rows = await instances.findAll({ + where: { id: [1, 2, 3, 4] }, + order: [['id', 'ASC']], + raw: true, + }); assert.equal(rows[0].status, 2); assert.ok( rows[0].finished_at >= before && @@ -129,10 +155,17 @@ test('startup closes interrupted instances without inventing exit codes or rewri global.setTimeout = originalTimeout; } assert.deepEqual(startupEvents, [ - 'environment', 'scheduler', 'environment', 'scheduler', + 'environment', + 'scheduler', + 'environment', + 'scheduler', ]); assert.deepEqual( - await instances.findAll({ where:{id:[1,2,3,4]}, order: [['id', 'ASC']], raw: true }), + await instances.findAll({ + where: { id: [1, 2, 3, 4] }, + order: [['id', 'ASC']], + raw: true, + }), rows, ); }); diff --git a/test/back/retention.test.cjs b/test/back/retention.test.cjs index 1f872673..46ede2ee 100644 --- a/test/back/retention.test.cjs +++ b/test/back/retention.test.cjs @@ -107,7 +107,8 @@ test('cleanup previews first, protects running instances, and uses explicit opti CrontabStatModel.destroy = async () => 3; sequelize.transaction = async (callback) => callback({}); sequelize.query = async (query) => { - if (query.startsWith('SELECT COUNT(*) AS count FROM CronTriggers')) return [{count: 4}]; + if (query.startsWith('SELECT COUNT(*) AS count FROM CronTriggers')) + return [{ count: 4 }]; if (query.startsWith('DELETE FROM CronTriggers')) return 4; vacuumed = query === 'VACUUM'; return []; diff --git a/test/back/scheduler-bulk-recovery.test.cjs b/test/back/scheduler-bulk-recovery.test.cjs index 2bc91151..677c7084 100644 --- a/test/back/scheduler-bulk-recovery.test.cjs +++ b/test/back/scheduler-bulk-recovery.test.cjs @@ -2,39 +2,103 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const grpc = require('@grpc/grpc-js'); const load = require('../helpers/load-security-module.cjs'); -const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness'); +const { + SchedulerReadiness, +} = require('../../back/cron/scheduling/schedulerReadiness'); for (const [name, rows, delay, succeeds] of [ - ['large distinct snapshot', Array.from({length:10000}, (_, i) => ({id:String(i), schedule:`${i%60} ${Math.floor(i/60)%60} ${Math.floor(i/3600)} * * *`})), 10000, true], - ['extra schedules', [{id:'extra', schedule:'* * * * *', extra_schedules:Array.from({length:2000},()=>({schedule:'0 * * * *'}))}], 10000, true], - ['unresponsive small write', [{id:'small', schedule:'* * * * *'}], 30000, false], - ['unresponsive large write remains bounded', Array.from({length:30000},()=>({schedule:'* * * * *'})), 180000, false], + [ + 'large distinct snapshot', + Array.from({ length: 10000 }, (_, i) => ({ + id: String(i), + schedule: `${i % 60} ${Math.floor(i / 60) % 60} ${Math.floor( + i / 3600, + )} * * *`, + })), + 10000, + true, + ], + [ + 'extra schedules', + [ + { + id: 'extra', + schedule: '* * * * *', + extra_schedules: Array.from({ length: 2000 }, () => ({ + schedule: '0 * * * *', + })), + }, + ], + 10000, + true, + ], + [ + 'unresponsive small write', + [{ id: 'small', schedule: '* * * * *' }], + 30000, + false, + ], + [ + 'unresponsive large write remains bounded', + Array.from({ length: 30000 }, () => ({ schedule: '* * * * *' })), + 180000, + false, + ], ]) { test(`recovery deadline: ${name}`, async (t) => { - t.mock.timers.enable({apis:['Date','setTimeout'], now:0}); - let calls=0, deadline; - const fake={waitForReady:(_,cb)=>cb(), addCron:(_req,_meta,options,cb)=>{ - calls++; deadline=options.deadline; - const budget=deadline-Date.now(); - setTimeout(()=>cb(delay<=budget ? null : Object.assign(Error('deadline'),{code:grpc.status.DEADLINE_EXCEEDED}), {}), Math.min(delay,budget)); - }}; - const client=load('back/schedule/client.ts', { - '../protos/cron':{...require('../../back/protos/cron'),CronClient:class{constructor(){return fake}}}, - '../config':{grpcPort:5500}, - '../config/grpcCerts':{getGrpcCerts:()=>({caCert:'ca',clientKey:'key',clientCert:'cert'})}, - '@grpc/grpc-js':{...grpc,credentials:{createSsl:()=>({})}}, + t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 0 }); + let calls = 0, + deadline; + const fake = { + waitForReady: (_, cb) => cb(), + addCron: (_req, _meta, options, cb) => { + calls++; + deadline = options.deadline; + const budget = deadline - Date.now(); + setTimeout( + () => + cb( + delay <= budget + ? null + : Object.assign(Error('deadline'), { + code: grpc.status.DEADLINE_EXCEEDED, + }), + {}, + ), + Math.min(delay, budget), + ); + }, + }; + const client = load('back/schedule/client.ts', { + '../protos/cron': { + ...require('../../back/protos/cron'), + CronClient: class { + constructor() { + return fake; + } + }, + }, + '../config': { grpcPort: 5500 }, + '../config/grpcCerts': { + getGrpcCerts: () => ({ + caCert: 'ca', + clientKey: 'key', + clientCert: 'cert', + }), + }, + '@grpc/grpc-js': { ...grpc, credentials: { createSsl: () => ({}) } }, }).default; - const readiness=new SchedulerReadiness(async()=>{}, 60000); - t.after(()=>clearTimeout(readiness.retry)); - client.readiness=readiness; - readiness.configure(()=>client.addCron(rows,true)); - const recovering=readiness.recover(); + const readiness = new SchedulerReadiness(async () => {}, 60000); + t.after(() => clearTimeout(readiness.retry)); + client.readiness = readiness; + readiness.configure(() => client.addCron(rows, true)); + const recovering = readiness.recover(); await new Promise(setImmediate); - assert.equal(calls,1); - assert.ok(deadline<=120000); - t.mock.timers.tick(Math.min(delay,deadline)); - assert.equal(await recovering,succeeds); - assert.equal(calls,1,'uncertain writes are not replayed inline'); - assert.equal(await readiness.check(),succeeds); + assert.equal(calls, 1); + assert.ok(deadline <= 120000); + t.mock.timers.tick(Math.min(delay, deadline)); + assert.equal(await recovering, succeeds); + assert.equal(calls, 1, 'uncertain writes are not replayed inline'); + assert.equal(await readiness.check(), succeeds); }); } diff --git a/test/back/scheduler-concurrency.test.cjs b/test/back/scheduler-concurrency.test.cjs index 05e81954..e63b2fd8 100644 --- a/test/back/scheduler-concurrency.test.cjs +++ b/test/back/scheduler-concurrency.test.cjs @@ -8,20 +8,20 @@ const load = require('../helpers/load-security-module.cjs'); const logger = { info() {}, debug() {}, warn() {}, error() {} }; const tick = () => new Promise(setImmediate); function createLimit() { - return load('back/shared/pLimit.ts', { - '../data/system': { + return load('back/cron/execution/cronLimit.ts', { + '../../data/system': { AuthDataType: { systemConfig: 'systemConfig' }, SystemModel: { sync: async () => {}, findOne: async () => ({ info: { cronConcurrency: 1 } }), }, }, - '../loaders/logger': logger, - '../services/notify': class {}, - '../shared/i18n': { t: (x) => x, tf: (x) => x }, - '../config': {}, - '../config/grpcCerts': { getGrpcCerts: () => null }, - '../protos/api': {}, + '../../loaders/logger': logger, + '../../services/notify': class {}, + '../../shared/i18n': { t: (x) => x, tf: (x) => x }, + '../../config': {}, + '../../config/grpcCerts': { getGrpcCerts: () => null }, + '../../protos/api': {}, }).default; } function createSystem(client, limit, options = {}) { @@ -35,9 +35,9 @@ function createSystem(client, limit, options = {}) { const writes = []; const Service = load('back/services/system.ts', { '../config': options.config || {}, - '../shared/schedulerMutationLock': options.config - ? load('back/shared/schedulerMutationLock.ts', { - '../config': options.config, + '../cron/scheduling/schedulerMutationLock': options.config + ? load('back/cron/scheduling/schedulerMutationLock.ts', { + '../../config/index': options.config, }) : { withSchedulerMutation: (operation) => operation() }, '../config/const': {}, @@ -57,7 +57,7 @@ function createSystem(client, limit, options = {}) { }, }, }, - '../shared/pLimit': limit, + '../cron/execution/cronLimit': limit, '../schedule/client': client, '../shared/i18n': { t: (x) => x }, './notify': class {}, @@ -82,7 +82,7 @@ async function rpcFixture(t) { apiLimit = createLimit(); await tick(); const handler = load('back/schedule/setConcurrency.ts', { - '../shared/pLimit': schedulerLimit, + '../cron/execution/cronLimit': schedulerLimit, }); let port; const Grpc = load('back/services/grpc.ts', { @@ -214,7 +214,7 @@ test('invalid concurrency is rejected before configuration writes or queue chang assert.deepEqual(f.writes, []); assert.deepEqual(mutations, []); const handler = load('back/schedule/setConcurrency.ts', { - '../shared/pLimit': { + '../cron/execution/cronLimit': { setCustomLimit: async (value) => mutations.push(value), }, }).setConcurrency; diff --git a/test/back/scheduler-file-lock.test.cjs b/test/back/scheduler-file-lock.test.cjs index b469478b..928abfa7 100644 --- a/test/back/scheduler-file-lock.test.cjs +++ b/test/back/scheduler-file-lock.test.cjs @@ -17,9 +17,9 @@ for (const failOperation of [false, true]) { const config = { crontabFile: path.join(root, 'crontab.list') }; await fs.writeFile(config.crontabFile, ''); const { withSchedulerMutation } = load( - 'back/shared/schedulerMutationLock.ts', + 'back/cron/scheduling/schedulerMutationLock.ts', { - '../config': config, + '../../config/index': config, }, ); const { writeFileWithLock } = load('back/shared/utils.ts', { diff --git a/test/back/scheduler-mutation.test.cjs b/test/back/scheduler-mutation.test.cjs index 432a3949..0258f6e8 100644 --- a/test/back/scheduler-mutation.test.cjs +++ b/test/back/scheduler-mutation.test.cjs @@ -66,7 +66,7 @@ async function fixture(t) { '../config/util': { isDemoEnv: () => false }, '../config/const': {}, '../schedule/client': client, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../shared/utils': {}, '../shared/i18n': { t: (s) => s }, '../shared/logReader': {}, @@ -179,7 +179,8 @@ for (const operation of ['create', 'update', 'enabled']) { await assert.rejects( mutation, (err) => - err.status === 503 && err.cause === cause && + err.status === 503 && + err.cause === cause && (operation === 'update' ? /原调度未能恢复/ : /回滚/).test(err.message), ); if (operation === 'create') assert.equal(await crons.count(), 0); @@ -204,8 +205,8 @@ test( t.after(() => fs.rm(root, { recursive: true, force: true })); const config = { crontabFile: path.join(root, 'crontab.list') }; const { withSchedulerMutation } = load( - 'back/shared/schedulerMutationLock.ts', - { '../config': config }, + 'back/cron/scheduling/schedulerMutationLock.ts', + { '../../config/index': config }, ); const entered = gate(), release = gate(); @@ -220,7 +221,7 @@ test( '-e', ` const load = require('./test/helpers/load-security-module.cjs'); - const { withSchedulerMutation } = load('back/shared/schedulerMutationLock.ts', {'../config': JSON.parse(process.argv[1])}); + const { withSchedulerMutation } = load('back/cron/scheduling/schedulerMutationLock.ts', {"../../config/index": JSON.parse(process.argv[1])}); process.send('attempting'); withSchedulerMutation(async () => process.send('entered')).then(() => process.disconnect()).catch(err => { console.error(err); process.exit(1); }); `, @@ -257,13 +258,20 @@ for (const operation of ['update', 'remove', 'disabled']) { test(`${operation} aborts on RPC ${code} with deletion applied=${applied} and reconciles the original DB`, async (t) => { const { service, crons, client, jobs } = await fixture(t); await crons.create({ - id: 1, command: 'old', schedule: '* * * * *', isDisabled: 0, + id: 1, + command: 'old', + schedule: '* * * * *', + isDisabled: 0, }); jobs.set('1', 'old'); // Only a handoff out of Node needs a deletion RPC before the DB write. - if (operation === 'update') service.shouldUseCronClient = row => row.schedule !== '@once'; + if (operation === 'update') + service.shouldUseCronClient = (row) => row.schedule !== '@once'; const before = await crons.findAll({ raw: true }); - const failure = Object.assign(Error('uncertain deletion'), { code, status: 503 }); + const failure = Object.assign(Error('uncertain deletion'), { + code, + status: 503, + }); let deletes = 0; client.delCron = async (ids) => { deletes++; @@ -271,8 +279,10 @@ for (const operation of ['update', 'remove', 'disabled']) { throw failure; }; const add = client.addCron; - client.addCron = async () => assert.fail('must not register after failed deletion'); - service.setCrontab = async () => assert.fail('must not publish after failed deletion'); + client.addCron = async () => + assert.fail('must not register after failed deletion'); + service.setCrontab = async () => + assert.fail('must not publish after failed deletion'); await assert.rejects( operation === 'update' ? service.update({ id: 1, command: 'new', schedule: '@once' }) diff --git a/test/back/scheduler-readiness.test.cjs b/test/back/scheduler-readiness.test.cjs index 97301c73..d6e62994 100644 --- a/test/back/scheduler-readiness.test.cjs +++ b/test/back/scheduler-readiness.test.cjs @@ -1,98 +1,250 @@ -const test=require('node:test'); -const assert=require('node:assert/strict'); -const {setTimeout:sleep}=require('node:timers/promises'); -const {SchedulerReadiness}=require('../../back/shared/schedulerReadiness'); -const load=require('../helpers/load-security-module.cjs'); -const fs=require('node:fs'); -const ts=require('typescript'); +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { setTimeout: sleep } = require('node:timers/promises'); +const { + SchedulerReadiness, +} = require('../../back/cron/scheduling/schedulerReadiness'); +const load = require('../helpers/load-security-module.cjs'); +const fs = require('node:fs'); +const ts = require('typescript'); -test('readiness stays false through failed restoration and retries without idle polling',async()=>{ - let probes=0,restores=0,fail=true; - const state=new SchedulerReadiness(async()=>{probes++;},10); - state.configure(async()=>{restores++;if(fail)throw Error('registration failed');}); - assert.equal(await state.recover(),false);assert.equal(await state.check(),false); - fail=false;await sleep(40);assert.equal(await state.check(),true);assert.ok(restores>=2); - const before=probes;await sleep(40);assert.equal(probes,before); +test('readiness stays false through failed restoration and retries without idle polling', async () => { + let probes = 0, + restores = 0, + fail = true; + const state = new SchedulerReadiness(async () => { + probes++; + }, 10); + state.configure(async () => { + restores++; + if (fail) throw Error('registration failed'); + }); + assert.equal(await state.recover(), false); + assert.equal(await state.check(), false); + fail = false; + await sleep(40); + assert.equal(await state.check(), true); + assert.ok(restores >= 2); + const before = probes; + await sleep(40); + assert.equal(probes, before); }); -test('single-flight recovery cannot mark an invalidated generation ready',async()=>{ - let release,restores=0; - const state=new SchedulerReadiness(async()=>{},10); - state.configure(async()=>{if(++restores===1)await new Promise(r=>release=r);}); - const a=state.recover();assert.equal(state.recover(),a);await sleep(1); - state.invalidate();release();assert.equal(await a,false);assert.equal(await state.check(),false); - await sleep(30);assert.equal(await state.check(),true);assert.equal(restores,2); +test('single-flight recovery cannot mark an invalidated generation ready', async () => { + let release, + restores = 0; + const state = new SchedulerReadiness(async () => {}, 10); + state.configure(async () => { + if (++restores === 1) await new Promise((r) => (release = r)); + }); + const a = state.recover(); + assert.equal(state.recover(), a); + await sleep(1); + state.invalidate(); + release(); + assert.equal(await a, false); + assert.equal(await state.check(), false); + await sleep(30); + assert.equal(await state.check(), true); + assert.equal(restores, 2); }); -test('mutation waiting is bounded, a later recovery can succeed',async()=>{ - let release; - const state=new SchedulerReadiness(async()=>{},10);state.configure(()=>new Promise(r=>release=r)); - await assert.rejects(state.ensureReady(15),e=>e.status===503); - release();await sleep(1);assert.equal(await state.check(),true); +test('mutation waiting is bounded, a later recovery can succeed', async () => { + let release; + const state = new SchedulerReadiness(async () => {}, 10); + state.configure(() => new Promise((r) => (release = r))); + await assert.rejects(state.ensureReady(15), (e) => e.status === 503); + release(); + await sleep(1); + assert.equal(await state.check(), true); }); -test('probe failure immediately invalidates a previously ready scheduler',async()=>{ - let fail=false; - const state=new SchedulerReadiness(async()=>{if(fail)throw Error('unavailable');},10); - state.configure(async()=>{});assert.equal(await state.recover(),true); - fail=true;assert.equal(await state.check(),false); - fail=false;await sleep(40);assert.equal(await state.check(),true); +test('probe failure immediately invalidates a previously ready scheduler', async () => { + let fail = false; + const state = new SchedulerReadiness(async () => { + if (fail) throw Error('unavailable'); + }, 10); + state.configure(async () => {}); + assert.equal(await state.recover(), true); + fail = true; + assert.equal(await state.check(), false); + fail = false; + await sleep(40); + assert.equal(await state.check(), true); }); -test('health uses actual readiness and returns HTTP 503 until recovery',async(t)=>{ - let ready=false;const express=require('express'); - const {HealthService}=load('back/services/health.ts',{ - typedi:{Service:()=>x=>x},'../loaders/logger':{error(){}},'./http':{}, - '../schedule/client':{readiness:{check:async()=>ready}}, - }); - const service=new HealthService({getServer:()=>({})}); - const app=express();load('back/api/health.ts',{ - typedi:{get:()=>service},'../services/health':{HealthService},'../loaders/logger':{error(){}}, - }).default(app); - const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r)); - t.after(()=>new Promise(r=>{server.close(r);server.closeAllConnections();})); - for(const expected of [503,200,503]){ - ready=expected===200;const r=await fetch(`http://127.0.0.1:${server.address().port}/health`);const b=await r.json(); - assert.equal(r.status,expected);assert.equal(b.code,expected);assert.equal(b.data.services.grpc,ready); - } +test('health uses actual readiness and returns HTTP 503 until recovery', async (t) => { + let ready = false; + const express = require('express'); + const { HealthService } = load('back/services/health.ts', { + typedi: { Service: () => (x) => x }, + '../loaders/logger': { error() {} }, + './http': {}, + '../schedule/client': { readiness: { check: async () => ready } }, + }); + const service = new HealthService({ getServer: () => ({}) }); + const app = express(); + load('back/api/health.ts', { + typedi: { get: () => service }, + '../services/health': { HealthService }, + '../loaders/logger': { error() {} }, + }).default(app); + const server = app.listen(0, '127.0.0.1'); + await new Promise((r) => server.once('listening', r)); + t.after( + () => + new Promise((r) => { + server.close(r); + server.closeAllConnections(); + }), + ); + for (const expected of [503, 200, 503]) { + ready = expected === 200; + const r = await fetch(`http://127.0.0.1:${server.address().port}/health`); + const b = await r.json(); + assert.equal(r.status, expected); + assert.equal(b.code, expected); + assert.equal(b.data.services.grpc, ready); + } }); -test('health failure does not reveal internal error details',async(t)=>{ - const express=require('express'); - const HealthService=class{}; - const app=express();load('back/api/health.ts',{ - typedi:{get:()=>({check:async()=>{throw Error('sensitive health detail');}})}, - '../services/health':{HealthService},'../loaders/logger':{error(){}}, - }).default(app); - const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r)); - t.after(()=>new Promise(r=>{server.close(r);server.closeAllConnections();})); - const response=await fetch(`http://127.0.0.1:${server.address().port}/health`); - assert.equal(response.status,500); - assert.deepEqual(await response.json(),{code:500,message:'Health check failed'}); +test('health failure does not reveal internal error details', async (t) => { + const express = require('express'); + const HealthService = class {}; + const app = express(); + load('back/api/health.ts', { + typedi: { + get: () => ({ + check: async () => { + throw Error('sensitive health detail'); + }, + }), + }, + '../services/health': { HealthService }, + '../loaders/logger': { error() {} }, + }).default(app); + const server = app.listen(0, '127.0.0.1'); + await new Promise((r) => server.once('listening', r)); + t.after( + () => + new Promise((r) => { + server.close(r); + server.closeAllConnections(); + }), + ); + const response = await fetch( + `http://127.0.0.1:${server.address().port}/health`, + ); + assert.equal(response.status, 500); + assert.deepEqual(await response.json(), { + code: 500, + message: 'Health check failed', + }); }); -test('recovery registration errors propagate while ordinary autosave retains file synchronization',async()=>{ - const source=fs.readFileSync('back/services/cron.ts','utf8');const a=source.indexOf(' public async autosave_crontab('),z=source.indexOf(' public async bootTask',a); - const js=ts.transpileModule('class Fixture {\n'+source.slice(a,z)+'}\nmodule.exports=Fixture;', {compilerOptions:{target:ts.ScriptTarget.ES2020}}).outputText; - const module={exports:{}};let files=0; - new Function('module','isDemoEnv','cronClient','withSchedulerMutation',js)(module,()=>false,{addCron:async()=>{throw Error('registration unavailable');}},fn=>fn()); - const fixture=new module.exports();fixture.crontabs=async()=>({data:[]});fixture.setCrontab=async()=>{files++;};fixture.logger={warn(){}}; - await fixture.autosave_crontab();assert.equal(files,1); - await assert.rejects(fixture.autosave_crontab(true),/registration unavailable/);assert.equal(files,2); +test('recovery registration errors propagate while ordinary autosave retains file synchronization', async () => { + const source = fs.readFileSync('back/services/cron.ts', 'utf8'); + const a = source.indexOf(' public async autosave_crontab('), + z = source.indexOf(' public async bootTask', a); + const js = ts.transpileModule( + 'class Fixture {\n' + source.slice(a, z) + '}\nmodule.exports=Fixture;', + { compilerOptions: { target: ts.ScriptTarget.ES2020 } }, + ).outputText; + const module = { exports: {} }; + let files = 0; + new Function( + 'module', + 'isDemoEnv', + 'cronClient', + 'withSchedulerMutation', + js, + )( + module, + () => false, + { + addCron: async () => { + throw Error('registration unavailable'); + }, + }, + (fn) => fn(), + ); + const fixture = new module.exports(); + fixture.crontabs = async () => ({ data: [] }); + fixture.setCrontab = async () => { + files++; + }; + fixture.logger = { warn() {} }; + await fixture.autosave_crontab(); + assert.equal(files, 1); + await assert.rejects( + fixture.autosave_crontab(true), + /registration unavailable/, + ); + assert.equal(files, 2); }); -test('scheduler probe uses the cron channel and failed writes are not replayed',async()=>{ - const calls=[];const fake={ - waitForReady(deadline,cb){calls.push(['wait',deadline]);cb();}, - makeUnaryRequest(path,serialize,deserialize,request,options,cb){calls.push(['probe',path,request,options]);cb(null,{status:1});}, - addCron(request,metadata,options,cb){calls.push(['add',request,options]);cb(Object.assign(Error('invalid'),{code:3}));}, - }; - const client=load('back/schedule/client.ts',{ - '../protos/cron':{...require('../../back/protos/cron'),CronClient:class{constructor(){return fake;}}}, - '../config':{grpcPort:5500},'../config/grpcCerts':{getGrpcCerts:()=>({caCert:'ca',clientKey:'key',clientCert:'cert'})}, - '@grpc/grpc-js':{...require('@grpc/grpc-js'),credentials:{createSsl:()=>({})},status:{UNAVAILABLE:14},Metadata:class{}}, - }).default; - client.readiness.configure(async()=>{});assert.equal(await client.readiness.recover(),true); - assert.ok(calls.filter(x=>x[0]==='probe').every(x=>x[1]==='/com.ql.health.Health/Check'&&x[2].service==='scheduler'&&x[3].deadline>Date.now())); - await assert.rejects(client.addCron([]),/invalid/);assert.equal(calls.filter(x=>x[0]==='add').length,1); +test('scheduler probe uses the cron channel and failed writes are not replayed', async () => { + const calls = []; + const fake = { + waitForReady(deadline, cb) { + calls.push(['wait', deadline]); + cb(); + }, + makeUnaryRequest(path, serialize, deserialize, request, options, cb) { + calls.push(['probe', path, request, options]); + cb(null, { status: 1 }); + }, + addCron(request, metadata, options, cb) { + calls.push(['add', request, options]); + cb(Object.assign(Error('invalid'), { code: 3 })); + }, + }; + const client = load('back/schedule/client.ts', { + '../protos/cron': { + ...require('../../back/protos/cron'), + CronClient: class { + constructor() { + return fake; + } + }, + }, + '../config': { grpcPort: 5500 }, + '../config/grpcCerts': { + getGrpcCerts: () => ({ + caCert: 'ca', + clientKey: 'key', + clientCert: 'cert', + }), + }, + '@grpc/grpc-js': { + ...require('@grpc/grpc-js'), + credentials: { createSsl: () => ({}) }, + status: { UNAVAILABLE: 14 }, + Metadata: class {}, + }, + }).default; + client.readiness.configure(async () => {}); + assert.equal(await client.readiness.recover(), true); + assert.ok( + calls + .filter((x) => x[0] === 'probe') + .every( + (x) => + x[1] === '/com.ql.health.Health/Check' && + x[2].service === 'scheduler' && + x[3].deadline > Date.now(), + ), + ); + await assert.rejects(client.addCron([]), /invalid/); + assert.equal(calls.filter((x) => x[0] === 'add').length, 1); }); -test('scheduler health probe never calls back into HTTP health',async()=>{ - const {check}=load('back/schedule/health.ts',{ - '../config':{},undici:{request:()=>{throw Error('recursive HTTP health call');}}, - }); - const result=await new Promise(resolve=>check({request:{service:'scheduler'}},(error,response)=>resolve({error,response}))); - assert.equal(result.error,null);assert.deepEqual(result.response,{status:1}); +test('scheduler health probe never calls back into HTTP health', async () => { + const { check } = load('back/schedule/health.ts', { + '../config': {}, + undici: { + request: () => { + throw Error('recursive HTTP health call'); + }, + }, + }); + const result = await new Promise((resolve) => + check({ request: { service: 'scheduler' } }, (error, response) => + resolve({ error, response }), + ), + ); + assert.equal(result.error, null); + assert.deepEqual(result.response, { status: 1 }); }); diff --git a/test/back/scheduler-reconciliation.test.cjs b/test/back/scheduler-reconciliation.test.cjs index 11324a23..9231c381 100644 --- a/test/back/scheduler-reconciliation.test.cjs +++ b/test/back/scheduler-reconciliation.test.cjs @@ -3,9 +3,14 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const ts = require('typescript'); const load = require('../helpers/load-security-module.cjs'); -const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness'); +const { + SchedulerReadiness, +} = require('../../back/cron/scheduling/schedulerReadiness'); const { AddCronRequest } = require('../../back/protos/cron'); -const { getInvalidCronSchedules } = require('../../back/shared/cronSchedule'); +const { + getInvalidCronSchedules, +} = require('../../back/cron/scheduling/cronSchedule'); +const { nodeCron } = require('../../back/cron/scheduling/cronScheduling'); function fixture(client) { const source = fs.readFileSync('back/services/cron.ts', 'utf8'); @@ -16,12 +21,21 @@ function fixture(client) { { compilerOptions: { target: ts.ScriptTarget.ES2020 } }, ).outputText; const module = { exports: {} }; - new Function('module', 'isDemoEnv', 'cronClient', 'withSchedulerMutation', 'getInvalidCronSchedules', js)( + new Function( + 'module', + 'isDemoEnv', + 'cronClient', + 'withSchedulerMutation', + 'getInvalidCronSchedules', + 'nodeCron', + js, + )( module, () => false, client, (fn) => fn(), getInvalidCronSchedules, + nodeCron, ); const service = new module.exports(); service.setCrontab = async () => {}; @@ -42,12 +56,13 @@ test('recovery reconciles a surviving scheduler after missed deletes and disable ); const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/cronScheduler': { + '../cron/scheduling/cronScheduler': { createCronJob: (_schedule, _callback, options) => ({ - start() {}, cancel: () => cancelled.push(options.name.split(':')[0]), + start() {}, + cancel: () => cancelled.push(options.name.split(':')[0]), }), }, - '../shared/runCron': {}, + '../cron/execution/runCron': {}, '../loaders/logger': { info() {}, warn() {} }, '../shared/i18n': { t: (s) => s, tf: (s) => s }, }); @@ -96,7 +111,7 @@ test('invalid replacement leaves the previous schedule intact', async () => { ]); const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/runCron': {}, + '../cron/execution/runCron': {}, '../loaders/logger': {}, '../shared/i18n': { t: (s) => s, tf: (s) => s }, }); @@ -121,22 +136,41 @@ test('invalid persisted schedules cannot block recovery, valid jobs or HTTP heal const warnings = []; const { addCron } = load('back/schedule/addCron.ts', { './data': { scheduleStacks: stacks }, - '../shared/runCron': {}, + '../cron/execution/runCron': {}, '../loaders/logger': { info() {}, warn() {} }, '../shared/i18n': { t: (s) => s, tf: require('node:util').format }, }); - const client = { addCron: (crons, replace) => new Promise((resolve, reject) => { - addCron({ request: { crons, replace } }, (error) => error ? reject(error) : resolve()); - }) }; + const client = { + addCron: (crons, replace) => + new Promise((resolve, reject) => { + addCron({ request: { crons, replace } }, (error) => + error ? reject(error) : resolve(), + ); + }), + }; const service = fixture(client); let snapshot; - service.setCrontab = async (tabs) => { snapshot = tabs.data; }; - service.logger.warn = (...args) => warnings.push(require('node:util').format(...args)); + service.setCrontab = async (tabs) => { + snapshot = tabs.data; + }; + service.logger.warn = (...args) => + warnings.push(require('node:util').format(...args)); let rows = [ { id: 'good', name: 'valid', schedule: '0 0/30 * * * ?', isDisabled: 0 }, { id: 'bad-main', name: 'bad main', schedule: 'not a cron', isDisabled: 0 }, - { id: 'bad-extra', name: 'bad extra', schedule: '* * * * *', extra_schedules: [{ schedule: '0 70 * * * ?' }], isDisabled: 0 }, - { id: 'unsupported', name: 'unsupported', schedule: 'H * * * *', isDisabled: 0 }, + { + id: 'bad-extra', + name: 'bad extra', + schedule: '* * * * *', + extra_schedules: [{ schedule: '0 70 * * * ?' }], + isDisabled: 0, + }, + { + id: 'unsupported', + name: 'unsupported', + schedule: 'H * * * *', + isDisabled: 0, + }, { id: 'disabled', name: 'disabled', schedule: 'bad', isDisabled: 1 }, ]; service.crontabs = async () => ({ data: rows }); @@ -148,20 +182,29 @@ test('invalid persisted schedules cannot block recovery, valid jobs or HTTP heal state.configure(() => service.autosave_crontab(true)); assert.equal(await state.recover(), true); assert.deepEqual([...stacks.keys()], ['good']); - assert.deepEqual(snapshot.map((x) => x.id), ['good', 'disabled']); + assert.deepEqual( + snapshot.map((x) => x.id), + ['good', 'disabled'], + ); assert.equal(rows.length, 5, 'persisted rows are preserved for editing'); assert.equal(rows[1].isDisabled, 0); assert.equal(warnings.length, 3); assert.match(warnings.join('\n'), /bad-main.*bad main.*not a cron/); assert.match(warnings.join('\n'), /bad-extra.*0 70/); const { HealthService } = load('back/services/health.ts', { - typedi: { Service: () => (x) => x }, './http': {}, - '../schedule/client': { readiness: state }, '../loaders/logger': { error() {} }, + typedi: { Service: () => (x) => x }, + './http': {}, + '../schedule/client': { readiness: state }, + '../loaders/logger': { error() {} }, }); const health = new HealthService({ getServer: () => ({}) }); assert.equal((await health.check()).status, 'ok'); rows = rows.filter((x) => x.id !== 'good'); - assert.equal(await state.recover(), true, 'even all-invalid snapshots can recover'); + assert.equal( + await state.recover(), + true, + 'even all-invalid snapshots can recover', + ); assert.equal(stacks.size, 0); assert.equal((await health.check()).status, 'ok'); }); diff --git a/test/back/scheduler-rpc-timeout.test.cjs b/test/back/scheduler-rpc-timeout.test.cjs index d810b1ac..7180a4b3 100644 --- a/test/back/scheduler-rpc-timeout.test.cjs +++ b/test/back/scheduler-rpc-timeout.test.cjs @@ -61,13 +61,24 @@ test('registration serializes nullable SQLite scheduling fields as absent', asyn }, }; const legacy = { - id: '1', extra_schedules: null, max_queue_wait: null, catchup_seconds: null, recovery_from: null, + id: '1', + extra_schedules: null, + max_queue_wait: null, + catchup_seconds: null, + recovery_from: null, }; const configured = { - id: '2', schedule: '* * * * *', extra_schedules: [{ schedule: '0 1 * * *' }], - max_queue_wait: 0, catchup_seconds: 60, recovery_from: 1700000000000, + id: '2', + schedule: '* * * * *', + extra_schedules: [{ schedule: '0 1 * * *' }], + max_queue_wait: 0, + catchup_seconds: 60, + recovery_from: 1700000000000, }; await client.addCron([legacy, configured], true); assert.equal(received.replace, true); - assert.deepEqual(received.crons, [ICron.create({ id: '1' }), ICron.create(configured)]); + assert.deepEqual(received.crons, [ + ICron.create({ id: '1' }), + ICron.create(configured), + ]); }); diff --git a/test/back/schema-migrations.test.cjs b/test/back/schema-migrations.test.cjs index 34078999..203c1d69 100644 --- a/test/back/schema-migrations.test.cjs +++ b/test/back/schema-migrations.test.cjs @@ -4,7 +4,7 @@ const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); const { Sequelize, DataTypes, QueryTypes, Transaction } = require('sequelize'); -const { migrateSchema } = require('../../back/shared/schemaMigrations'); +const { migrateSchema } = require('../../back/data/schemaMigrations'); const load = require('../helpers/load-security-module.cjs'); async function createLegacy(storage = ':memory:', omitEnvs = false) { @@ -27,8 +27,12 @@ async function createLegacy(storage = ':memory:', omitEnvs = false) { await database.query( 'INSERT INTO "Crontabs" (id, name) VALUES (1, \'keep-me\')', ); - await database.query('ALTER TABLE Crontabs ADD COLUMN last_execution_time INTEGER'); - await database.query('ALTER TABLE Crontabs ADD COLUMN last_running_time INTEGER'); + await database.query( + 'ALTER TABLE Crontabs ADD COLUMN last_execution_time INTEGER', + ); + await database.query( + 'ALTER TABLE Crontabs ADD COLUMN last_running_time INTEGER', + ); load('back/data/runningInstance.ts', { '.': { sequelize: database } }); load('back/data/cronStats.ts', { '.': { sequelize: database } }); await database.sync(); @@ -50,7 +54,12 @@ test('legacy database upgrades without losing rows and repeated migration is ide type: QueryTypes.SELECT, }); assert.equal(applied.length, 27); - assert.ok(Object.hasOwn(await database.getQueryInterface().describeTable('CrontabStats'), 'fixed_max_time')); + assert.ok( + Object.hasOwn( + await database.getQueryInterface().describeTable('CrontabStats'), + 'fixed_max_time', + ), + ); assert.equal(rows[0].last_instance_id, null); assert.equal(rows[0].catchup_seconds, null); assert.equal(rows[0].max_queue_wait, null); @@ -67,26 +76,40 @@ test('migration repairs malformed environment labels before ORM reads', async (t [4, '{}'], [5, '["keep"]'], ]) { - await database.query('INSERT INTO "Envs" (id, name, labels) VALUES (?, ?, ?)', { - replacements: [id, `env-${id}`, labels], - }); + await database.query( + 'INSERT INTO "Envs" (id, name, labels) VALUES (?, ?, ?)', + { + replacements: [id, `env-${id}`, labels], + }, + ); } - const EnvModel = database.define('Env', { - name: DataTypes.STRING, - labels: DataTypes.JSON, - }, { timestamps: false }); + const EnvModel = database.define( + 'Env', + { + name: DataTypes.STRING, + labels: DataTypes.JSON, + }, + { timestamps: false }, + ); await assert.rejects(EnvModel.findAll(), /Unexpected end of JSON input/); await migrateSchema(database); const rows = await EnvModel.findAll({ order: [['id', 'ASC']] }); - assert.deepEqual(rows.map((row) => row.labels), [[], [], [], [], ['keep']]); + assert.deepEqual( + rows.map((row) => row.labels), + [[], [], [], [], ['keep']], + ); await migrateSchema(database); - const repaired = await database.query('SELECT id, labels FROM "Envs" ORDER BY id', { - type: QueryTypes.SELECT, - }); - assert.deepEqual(repaired.map(({ labels }) => labels), [ - '[]', '[]', '[]', '[]', '["keep"]', - ]); + const repaired = await database.query( + 'SELECT id, labels FROM "Envs" ORDER BY id', + { + type: QueryTypes.SELECT, + }, + ); + assert.deepEqual( + repaired.map(({ labels }) => labels), + ['[]', '[]', '[]', '[]', '["keep"]'], + ); }); test('migration failure rolls back added columns and can be retried after repair', async (t) => { @@ -160,7 +183,7 @@ test('database loader rejects initialization failure rather than allowing worker ]) mocks[`../data/${file}`] = { [model]: { sync: async () => {} } }; mocks['../data'] = { sequelize: {} }; - mocks['../shared/schemaMigrations'] = { + mocks['../data/schemaMigrations'] = { migrateSchema: async () => { throw new Error('SQLITE_FULL'); }, @@ -169,121 +192,234 @@ test('database loader rejects initialization failure rather than allowing worker await assert.rejects(initialize(), /SQLITE_FULL/); }); -test('upgrading stop batches preserves completed and pending idempotency bindings', async t => { +test('upgrading stop batches preserves completed and pending idempotency bindings', async (t) => { const database = await createLegacy(); t.after(() => database.close()); - await database.query('CREATE TABLE CronStopBatches (request_id TEXT PRIMARY KEY,cron_ids TEXT NOT NULL,snapshot TEXT)'); - await database.query("INSERT INTO CronStopBatches VALUES ('done','[1]',NULL),('retry','[2]','{}')"); + await database.query( + 'CREATE TABLE CronStopBatches (request_id TEXT PRIMARY KEY,cron_ids TEXT NOT NULL,snapshot TEXT)', + ); + await database.query( + "INSERT INTO CronStopBatches VALUES ('done','[1]',NULL),('retry','[2]','{}')", + ); await migrateSchema(database); await migrateSchema(database); - const rows = await database.query('SELECT request_id,cron_ids,snapshot,status_code FROM CronStopBatches ORDER BY request_id', - { type: QueryTypes.SELECT }); + const rows = await database.query( + 'SELECT request_id,cron_ids,snapshot,status_code FROM CronStopBatches ORDER BY request_id', + { type: QueryTypes.SELECT }, + ); assert.deepEqual(rows, [ { request_id: 'done', cron_ids: '[1]', snapshot: null, status_code: 200 }, { request_id: 'retry', cron_ids: '[2]', snapshot: '{}', status_code: 200 }, ]); }); -test('upgrade preserves an already pruned bound booking when its canonical file was reclaimed before restart', async t => { +test('upgrade preserves an already pruned bound booking when its canonical file was reclaimed before restart', async (t) => { const database = await createLegacy(); t.after(() => database.close()); await migrateSchema(database); // Previous panel committed both bookings, then removed the files. An // unbound result by itself cannot authenticate a later versioned receipt. - await database.query("DELETE FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'"); + await database.query( + "DELETE FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'", + ); await database.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound) VALUES ('bound-before-upgrade',1,'manual',1000,2000,'31','1970-01-01',1), ('legacy-before-upgrade',1,'manual',1000,2000,'0','1970-01-01',0)`); await migrateSchema(database); await database.query('DELETE FROM CronLegacyExitBookings'); await migrateSchema(database); - assert.deepEqual(await database.query('SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits', - { type: QueryTypes.SELECT }), [{trigger_id:'bound-before-upgrade', outcome:'31', finished_at:2000}]); - assert.deepEqual(await database.query('SELECT * FROM CrontabStats', { type: QueryTypes.SELECT }), []); + assert.deepEqual( + await database.query( + 'SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits', + { type: QueryTypes.SELECT }, + ), + [{ trigger_id: 'bound-before-upgrade', outcome: '31', finished_at: 2000 }], + ); + assert.deepEqual( + await database.query('SELECT * FROM CrontabStats', { + type: QueryTypes.SELECT, + }), + [], + ); }); for (const committed of [false, true]) { - test('pruned booking evidence and its marker survive cleanup after migration ' + - (committed ? 'commit' : 'rollback'), async t => { - const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-migration-cut-')); - const previousDataDir = process.env.QL_DATA_DIR; - process.env.QL_DATA_DIR = directory; - await fs.mkdir(path.join(directory, 'db')); - await fs.writeFile(path.join(directory, '.env'), ''); - const db = await createLegacy(path.join(directory, 'db/database.sqlite')); - t.after(async () => { - if (previousDataDir === undefined) delete process.env.QL_DATA_DIR; - else process.env.QL_DATA_DIR = previousDataDir; - await db.close(); - await fs.rm(directory, { recursive: true, force: true }); - }); - await migrateSchema(db); - const marker = 'preserve-pruned-bound-exits-v1', id = 'old-bound'; - const select = sql => db.query(sql, { type: QueryTypes.SELECT }); - const late = Date.now(); - const retainedDay = require('dayjs')(late).format('YYYY-MM-DD'); - const stats = db.models.CrontabStat; - const expired = await stats.create({ ref_id: 1, date: '1970-01-01', run_count: 1, fail_count: 1, total_time: 1000, max_time: 1000 }); - await stats.create({ ref_id: 1, date: retainedDay, run_count: 1, success_count: 1, total_time: 333, max_time: 333 }); - const daily = () => select('SELECT date,run_count,success_count,fail_count,total_time,max_time FROM CrontabStats ORDER BY date'); - const sibling = { date: retainedDay, run_count: 1, success_count: 1, fail_count: 0, total_time: 333, max_time: 333 }; - await db.query('DELETE FROM SchemaMigrations WHERE id=$marker', { bind: { marker } }); - await db.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound,stat_id) - VALUES ($id,1,'manual',1000,2000,'31','1970-01-01',1,$stat)`, { bind: { id, stat: expired.id } }); - const side = committed ? 'after' : 'before'; - const gate = path.join(directory, 'checkpoint'); - const worker = require('node:child_process').spawn(process.execPath, [ - '-r', 'ts-node/register/transpile-only', require.resolve('../helpers/receipt-migration-worker.cjs'), - path.resolve(__dirname, '../../back'), side, gate, - ], { env: { ...process.env, QL_DIR: directory }, stdio: ['ignore', 'ignore', 'pipe'] }); - let errorOutput = ''; - worker.stderr.on('data', data => { errorOutput += data; }); - const closed = require('node:events').once(worker, 'close'); - try { - const deadline = Date.now() + 30000; - while (!require('node:fs').existsSync(gate)) { - assert.ok(worker.exitCode === null && worker.signalCode === null && Date.now() < deadline, - 'Migration worker failed to reach COMMIT boundary: ' + errorOutput); - await new Promise(resolve => setTimeout(resolve, 25)); + test( + 'pruned booking evidence and its marker survive cleanup after migration ' + + (committed ? 'commit' : 'rollback'), + async (t) => { + const directory = await fs.mkdtemp( + path.join(os.tmpdir(), 'ql-migration-cut-'), + ); + const previousDataDir = process.env.QL_DATA_DIR; + process.env.QL_DATA_DIR = directory; + await fs.mkdir(path.join(directory, 'db')); + await fs.writeFile(path.join(directory, '.env'), ''); + const db = await createLegacy(path.join(directory, 'db/database.sqlite')); + t.after(async () => { + if (previousDataDir === undefined) delete process.env.QL_DATA_DIR; + else process.env.QL_DATA_DIR = previousDataDir; + await db.close(); + await fs.rm(directory, { recursive: true, force: true }); + }); + await migrateSchema(db); + const marker = 'preserve-pruned-bound-exits-v1', + id = 'old-bound'; + const select = (sql) => db.query(sql, { type: QueryTypes.SELECT }); + const late = Date.now(); + const retainedDay = require('dayjs')(late).format('YYYY-MM-DD'); + const stats = db.models.CrontabStat; + const expired = await stats.create({ + ref_id: 1, + date: '1970-01-01', + run_count: 1, + fail_count: 1, + total_time: 1000, + max_time: 1000, + }); + await stats.create({ + ref_id: 1, + date: retainedDay, + run_count: 1, + success_count: 1, + total_time: 333, + max_time: 333, + }); + const daily = () => + select( + 'SELECT date,run_count,success_count,fail_count,total_time,max_time FROM CrontabStats ORDER BY date', + ); + const sibling = { + date: retainedDay, + run_count: 1, + success_count: 1, + fail_count: 0, + total_time: 333, + max_time: 333, + }; + await db.query('DELETE FROM SchemaMigrations WHERE id=$marker', { + bind: { marker }, + }); + await db.query( + `INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound,stat_id) + VALUES ($id,1,'manual',1000,2000,'31','1970-01-01',1,$stat)`, + { bind: { id, stat: expired.id } }, + ); + const side = committed ? 'after' : 'before'; + const gate = path.join(directory, 'checkpoint'); + const worker = require('node:child_process').spawn( + process.execPath, + [ + '-r', + 'ts-node/register/transpile-only', + require.resolve('../helpers/receipt-migration-worker.cjs'), + path.resolve(__dirname, '../../back'), + side, + gate, + ], + { + env: { ...process.env, QL_DIR: directory }, + stdio: ['ignore', 'ignore', 'pipe'], + }, + ); + let errorOutput = ''; + worker.stderr.on('data', (data) => { + errorOutput += data; + }); + const closed = require('node:events').once(worker, 'close'); + try { + const deadline = Date.now() + 30000; + while (!require('node:fs').existsSync(gate)) { + assert.ok( + worker.exitCode === null && + worker.signalCode === null && + Date.now() < deadline, + 'Migration worker failed to reach COMMIT boundary: ' + errorOutput, + ); + await new Promise((resolve) => setTimeout(resolve, 25)); + } + const checkpoint = JSON.parse(await fs.readFile(gate, 'utf8')); + assert.deepEqual(checkpoint, { + side, + pid: worker.pid, + marker: 1, + proofs: 1, + }); + // Observe from the parent's independent connection while the writer is still frozen. + assert.equal( + (await select('SELECT trigger_id FROM CronUnmatchedBoundExits')) + .length, + Number(committed), + ); + } finally { + worker.kill('SIGKILL'); + await closed; } - const checkpoint = JSON.parse(await fs.readFile(gate, 'utf8')); - assert.deepEqual(checkpoint, { side, pid: worker.pid, marker: 1, proofs: 1 }); - // Observe from the parent's independent connection while the writer is still frozen. - assert.equal((await select('SELECT trigger_id FROM CronUnmatchedBoundExits')).length, Number(committed)); - } finally { - worker.kill('SIGKILL'); - await closed; - } - const proof = () => select('SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits'); - const expected = [{trigger_id:id, outcome:'31', finished_at:2000}]; - assert.deepEqual(await proof(), committed ? expected : []); - assert.equal((await select("SELECT id FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'")).length, +committed); + const proof = () => + select( + 'SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits', + ); + const expected = [{ trigger_id: id, outcome: '31', finished_at: 2000 }]; + assert.deepEqual(await proof(), committed ? expected : []); + assert.equal( + ( + await select( + "SELECT id FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'", + ) + ).length, + +committed, + ); - const policy = new (load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': { CrontabStatModel: db.models.CrontabStat }, - '../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } }, - '../data/system': {}, '../config': {}, - }).default)(); - const clean = () => policy.cleanup({ runningInstanceRetentionDays: 0, cronStatRetentionDays: 1 }); - await clean(); // This writer acquires the lock before the migration retry. - assert.deepEqual(await daily(), [sibling]); - assert.deepEqual(await select('SELECT trigger_id FROM CronLegacyExitBookings'), committed ? [] : [{trigger_id:id}]); - await migrateSchema(db); - await clean(); - await migrateSchema(db); - assert.deepEqual(await proof(), expected); - assert.deepEqual(await select('SELECT trigger_id FROM CronLegacyExitBookings'), []); - const { writeExit } = require('../../back/shared/managedExit.cjs'); - const { TriggerHistory } = require('../../back/shared/triggerHistory'); - const history = new TriggerHistory(db); - writeExit(id, 0, null, late); - await history.retryPendingExits(); - writeExit(id, 31, null, 2000); - await Promise.all([clean(), history.retryPendingExits()]); - await history.interrupt('http'); - assert.deepEqual(await select('SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at'), - [{outcome: '31', finished_at: 2000}, {outcome: '0', finished_at: late}]); - assert.deepEqual(await daily(), [sibling]); - assert.deepEqual(await select('SELECT id FROM CronTriggers'), []); - }); + const policy = new (load('back/services/retention.ts', { + '../data': { sequelize: db }, + '../data/cronStats': { CrontabStatModel: db.models.CrontabStat }, + '../data/runningInstance': { + RunningInstanceModel: db.models.RunningInstance, + InstanceStatus: { running: 0 }, + }, + '../data/system': {}, + '../config': {}, + }).default)(); + const clean = () => + policy.cleanup({ + runningInstanceRetentionDays: 0, + cronStatRetentionDays: 1, + }); + await clean(); // This writer acquires the lock before the migration retry. + assert.deepEqual(await daily(), [sibling]); + assert.deepEqual( + await select('SELECT trigger_id FROM CronLegacyExitBookings'), + committed ? [] : [{ trigger_id: id }], + ); + await migrateSchema(db); + await clean(); + await migrateSchema(db); + assert.deepEqual(await proof(), expected); + assert.deepEqual( + await select('SELECT trigger_id FROM CronLegacyExitBookings'), + [], + ); + const { + writeExit, + } = require('../../back/cron/settlement/exitReceipt.cjs'); + const { TriggerHistory } = require('../../back/cron/history'); + const history = new TriggerHistory(db); + writeExit(id, 0, null, late); + await history.retryPendingExits(); + writeExit(id, 31, null, 2000); + await Promise.all([clean(), history.retryPendingExits()]); + await history.interrupt('http'); + assert.deepEqual( + await select( + 'SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at', + ), + [ + { outcome: '31', finished_at: 2000 }, + { outcome: '0', finished_at: late }, + ], + ); + assert.deepEqual(await daily(), [sibling]); + assert.deepEqual(await select('SELECT id FROM CronTriggers'), []); + }, + ); } diff --git a/test/back/script-file-access.test.cjs b/test/back/script-file-access.test.cjs index b90ba37d..c5abedc7 100644 --- a/test/back/script-file-access.test.cjs +++ b/test/back/script-file-access.test.cjs @@ -47,7 +47,7 @@ test('script file operations allow token.json while protecting panel configurati './sock': {}, './cron': {}, './schedule': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, typedi: { Service: () => (x) => x, Inject: () => () => {} }, }; const cache = new Map(); diff --git a/test/back/script-notification-rpc.test.cjs b/test/back/script-notification-rpc.test.cjs index e99013cd..887e687d 100644 --- a/test/back/script-notification-rpc.test.cjs +++ b/test/back/script-notification-rpc.test.cjs @@ -131,7 +131,11 @@ assert len(children[0])==3,children .filter((x) => x.title === 'Concurrent cold startup') .map((x) => [x.notifyType, x.success]) .sort(), - [['accepted', true], ['no_result', false], ['rejected', false]], + [ + ['accepted', true], + ['no_result', false], + ['rejected', false], + ], ); // Missing certificates and an older/unavailable backend must not kill scripts. await run( diff --git a/test/back/shell-api-parsing.test.cjs b/test/back/shell-api-parsing.test.cjs index aefaa7f8..55f7c2d8 100644 --- a/test/back/shell-api-parsing.test.cjs +++ b/test/back/shell-api-parsing.test.cjs @@ -183,7 +183,7 @@ test('success-shaped invalid documents retain the raw-response error fallback', assert.equal(f.count(), cases.length * 2); }); -test('Shell retries the same identified receipt after a timeout and starts the next run with a fresh ID', t => { +test('Shell retries the same identified receipt after a timeout and starts the next run with a fresh ID', (t) => { const f = fixture(t); const result = f.run(` ID=7; unset QL_TRIGGER_ID @@ -203,29 +203,35 @@ test('Shell retries the same identified receipt after a timeout and starts the n assert.equal(result.status, 0, result.stderr); const lines = fs.readFileSync(f.response, 'utf8').trim().split('\n'); assert.equal(lines.length, 12); - for (let i = 0; i < lines.length; i += 2) assert.equal(lines[i], lines[i+1]); - const ids = lines.map(line => JSON.parse(line).execution_id); + for (let i = 0; i < lines.length; i += 2) + assert.equal(lines[i], lines[i + 1]); + const ids = lines.map((line) => JSON.parse(line).execution_id); assert.match(ids[0], /^client-[0-9a-f-]{36}$/); - assert.ok(ids.slice(0, 6).every(id => id === ids[0])); - assert.ok(ids.slice(6).every(id => id === ids[6])); + assert.ok(ids.slice(0, 6).every((id) => id === ids[0])); + assert.ok(ids.slice(6).every((id) => id === ids[6])); assert.notEqual(ids[0], ids[6]); }); -test('a standalone shell reuses the observed end for both receipts, including timeout retries', t => { +test('a standalone shell reuses the observed end for both receipts, including timeout retries', (t) => { const f = fixture(t); - const result = f.run([ - 'ql_execution_id="client-123"; directory=$(dirname "$RESPONSE_FILE");', - 'ql_api_request() {', - ' local arg; for arg in "$@"; do case "$arg" in "X-QL-Finished-At:"*) printf "%s\\n" "$arg" >> "$directory/headers";; esac; done;', - ' if [[ ! -e "$directory/retried" ]]; then touch "$directory/retried"; return 28; fi;', - ' printf \'{"code":200}\';', - '}', - 'update_cron 5 0 501 task.log 1700000000;', - 'rm -f "$directory/retried";', - 'update_cron 5 1 501 task.log 1700000000 60 17 1700000060;', - 'record_cron_stat 5 17 60 1700000060;', - 'cat "$directory/headers";', - ].join('\n')); - assert.equal(result.status,0,result.stderr); - assert.deepEqual(result.stdout.trim().split('\n'),Array(3).fill('X-QL-Finished-At: 1700000060000')); + const result = f.run( + [ + 'ql_execution_id="client-123"; directory=$(dirname "$RESPONSE_FILE");', + 'ql_api_request() {', + ' local arg; for arg in "$@"; do case "$arg" in "X-QL-Finished-At:"*) printf "%s\\n" "$arg" >> "$directory/headers";; esac; done;', + ' if [[ ! -e "$directory/retried" ]]; then touch "$directory/retried"; return 28; fi;', + ' printf \'{"code":200}\';', + '}', + 'update_cron 5 0 501 task.log 1700000000;', + 'rm -f "$directory/retried";', + 'update_cron 5 1 501 task.log 1700000000 60 17 1700000060;', + 'record_cron_stat 5 17 60 1700000060;', + 'cat "$directory/headers";', + ].join('\n'), + ); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual( + result.stdout.trim().split('\n'), + Array(3).fill('X-QL-Finished-At: 1700000060000'), + ); }); diff --git a/test/back/shell-compatibility.test.cjs b/test/back/shell-compatibility.test.cjs index 3e41f922..34f94570 100644 --- a/test/back/shell-compatibility.test.cjs +++ b/test/back/shell-compatibility.test.cjs @@ -54,7 +54,8 @@ for (const [label, args] of [ f.write(`shell/${name}`, source(`shell/${name}`)); f.write( 'shell/api.sh', - extract('shell/api.sh', 'init_execution_id') + '\nupdate_cron(){ :; }; record_cron_stat(){ :; }\n', + extract('shell/api.sh', 'init_execution_id') + + '\nupdate_cron(){ :; }; record_cron_stat(){ :; }\n', ); f.write('shell/preload/env.sh', 'export QA_PANEL="one&two"\n'); f.write('shell/preload/sitecustomize.js', '// fixture preloader\n'); @@ -557,46 +558,89 @@ for (const version of ['2.23.0', '2.23.0-beta.1+build.2', 'invalid']) { }); } -test('ql extra propagates a sourced script failure through every logging mode', t => { +test('ql extra propagates a sourced script failure through every logging mode', (t) => { const f = fixture(t); f.write('shell/update.sh', source('shell/update.sh')); f.write('shell/env.sh', ''); - f.write('shell/share.sh', [ - 'load_ql_envs() { :; }; import_config() { :; }; make_dir() { mkdir -p "$1"; }', - 't() { :; }; format_timestamp() { echo 1; }; format_time() { echo now; }', - ].join('\n')); - f.write('shell/api.sh', [ - extract('shell/api.sh', 'init_execution_id'), - 'update_cron() { echo "status:$2:${7:-}" >> "$QL_DIR/records"; }', - 'record_cron_stat() { echo "stat:$2" >> "$QL_DIR/records"; }', - ].join('\n')); - for (const [real_time, no_tee] of [['false','false'], ['false','true'], ['true','false']]) { - for (const [script, code] of [['return 17', 17], ['exit 17', 17], ['return 0', 0], - ['false | true', 0], ['set -o pipefail; false | true', 1]]) { + f.write( + 'shell/share.sh', + [ + 'load_ql_envs() { :; }; import_config() { :; }; make_dir() { mkdir -p "$1"; }', + 't() { :; }; format_timestamp() { echo 1; }; format_time() { echo now; }', + ].join('\n'), + ); + f.write( + 'shell/api.sh', + [ + extract('shell/api.sh', 'init_execution_id'), + 'update_cron() { echo "status:$2:${7:-}" >> "$QL_DIR/records"; }', + 'record_cron_stat() { echo "stat:$2" >> "$QL_DIR/records"; }', + ].join('\n'), + ); + for (const [real_time, no_tee] of [ + ['false', 'false'], + ['false', 'true'], + ['true', 'false'], + ]) { + for (const [script, code] of [ + ['return 17', 17], + ['exit 17', 17], + ['return 0', 0], + ['false | true', 0], + ['set -o pipefail; false | true', 1], + ]) { f.write('records', ''); const result = f.run('exec "$QA_BASH" "$QL_DIR/shell/update.sh" extra', { - QA_BASH: bash, QL_DIR: f.root, ID: '42', real_time, no_tee, - dir_log: path.join(f.root, 'log'), file_extra_shell: f.write('extra.sh', script), + QA_BASH: bash, + QL_DIR: f.root, + ID: '42', + real_time, + no_tee, + dir_log: path.join(f.root, 'log'), + file_extra_shell: f.write('extra.sh', script), }); assert.equal(result.status, code, result.stderr); - assert.equal(fs.readFileSync(path.join(f.root, 'records'), 'utf8'), - `status:0:\nstatus:1:${code}\nstat:${code}\n`); + assert.equal( + fs.readFileSync(path.join(f.root, 'records'), 'utf8'), + `status:0:\nstatus:1:${code}\nstat:${code}\n`, + ); } } }); -test('raw sync recognizes the exact quoted operand in a wrapped crontab across repeated downloads', t => { - const f = fixture(t), file = "raw_owner_what's new.js"; +test('raw sync recognizes the exact quoted operand in a wrapped crontab across repeated downloads', (t) => { + const f = fixture(t), + file = "raw_owner_what's new.js"; const { shellQuote } = require('../../back/shared/shellQuote'); - f.write('raw/.keep', ''); f.write('scripts/.keep', ''); - f.write('crontab.list', '1 * * * * ID=7 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + - shellQuote('QL_CRON_REVISION=10 real_time=false ID=7 task ' + shellQuote(file)) + '\n'); - const result = f.run([extract('shell/update.sh', 'update_raw'), 't(){ :; }; set_proxy(){ :; }; unset_proxy(){ :; }', - 'wget(){ printf "body" > "$4"; }; add_cron(){ exit 55; }', - 'update_raw https://fixture.invalid/script.js "" true false'].join('\n'), { - dir_shell: path.resolve('shell'), dir_raw: path.join(f.root, 'raw'), dir_scripts: path.join(f.root, 'scripts'), - list_crontab_user: path.join(f.root, 'crontab.list'), cmd_task: 'task', uniq_path: "owner_what's new", - }); + f.write('raw/.keep', ''); + f.write('scripts/.keep', ''); + f.write( + 'crontab.list', + '1 * * * * ID=7 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + + shellQuote( + 'QL_CRON_REVISION=10 real_time=false ID=7 task ' + shellQuote(file), + ) + + '\n', + ); + const result = f.run( + [ + extract('shell/update.sh', 'update_raw'), + 't(){ :; }; set_proxy(){ :; }; unset_proxy(){ :; }', + 'wget(){ printf "body" > "$4"; }; add_cron(){ exit 55; }', + 'update_raw https://fixture.invalid/script.js "" true false', + ].join('\n'), + { + dir_shell: path.resolve('shell'), + dir_raw: path.join(f.root, 'raw'), + dir_scripts: path.join(f.root, 'scripts'), + list_crontab_user: path.join(f.root, 'crontab.list'), + cmd_task: 'task', + uniq_path: "owner_what's new", + }, + ); assert.equal(result.status, 0, result.stderr); - assert.equal(fs.readFileSync(path.join(f.root, 'scripts', file), 'utf8'), 'body'); + assert.equal( + fs.readFileSync(path.join(f.root, 'scripts', file), 'utf8'), + 'body', + ); }); diff --git a/test/back/shell-translation-output.test.cjs b/test/back/shell-translation-output.test.cjs index a44edb1f..c9fdf7f7 100644 --- a/test/back/shell-translation-output.test.cjs +++ b/test/back/shell-translation-output.test.cjs @@ -3,14 +3,23 @@ const assert = require('node:assert/strict'); const { spawnSync } = require('node:child_process'); test('shell translations print leading dashes, placeholders and newlines', () => { - const result = spawnSync('bash', ['-c', String.raw` + const result = spawnSync( + 'bash', + [ + '-c', + String.raw` source shell/share.sh t '---> 服务诊断信息' t '---> 最近的系统日志: %s' '/tmp/test.log' t 'first\nsecond' - `], { encoding: 'utf8', env: { ...process.env, QL_DIR: process.cwd() } }); + `, + ], + { encoding: 'utf8', env: { ...process.env, QL_DIR: process.cwd() } }, + ); assert.equal(result.status, 0, result.stderr); assert.equal(result.stderr, ''); - assert.equal(result.stdout, - '---> 服务诊断信息\n---> 最近的系统日志: /tmp/test.log\nfirst\nsecond\n'); + assert.equal( + result.stdout, + '---> 服务诊断信息\n---> 最近的系统日志: /tmp/test.log\nfirst\nsecond\n', + ); }); diff --git a/test/back/shell-upgrade.test.cjs b/test/back/shell-upgrade.test.cjs index b3db4511..6f45dc60 100644 --- a/test/back/shell-upgrade.test.cjs +++ b/test/back/shell-upgrade.test.cjs @@ -225,7 +225,10 @@ for (const branch of ['master', 'develop', 'debian', 'debian-dev']) const f = await fixture(t, { branch, lockChange: true, tee: true }); let result = await f.execute('update', 'false'); assert.equal(result.code, 0, result.stdout + result.stderr); - assert.ok(result.stdout.includes('     '), 'update logs retain the completion marker'); + assert.ok( + result.stdout.includes('     '), + 'update logs retain the completion marker', + ); assert.equal(f.read('version.yaml'), 'version: 2.21.0'); assert.equal(fs.existsSync(path.join(f.root, 'stops')), false); assert.match( diff --git a/test/back/shellApiToken.test.cjs b/test/back/shellApiToken.test.cjs index 29294138..794ae7d6 100644 --- a/test/back/shellApiToken.test.cjs +++ b/test/back/shellApiToken.test.cjs @@ -9,47 +9,84 @@ const apiFile = path.resolve(__dirname, '../../shell/api.sh'); const endpoints = { status: { - method: 'PUT', url: /\/open\/crons\/status\?t=\d+$/, - body: { ids: ['37'], status: '1', pid: '4321', log_path: 'task/run.log', - last_execution_time: 1787004000, last_running_time: 90, exit_code: 0 }, - success: '', failure: (message) => message, + method: 'PUT', + url: /\/open\/crons\/status\?t=\d+$/, + body: { + ids: ['37'], + status: '1', + pid: '4321', + log_path: 'task/run.log', + last_execution_time: 1787004000, + last_running_time: 90, + exit_code: 0, + }, + success: '', + failure: (message) => message, }, statistics: { - method: 'POST', url: /\/open\/dashboard\/record$/, + method: 'POST', + url: /\/open\/dashboard\/record$/, body: { ref_id: 37, code: 0, elapsed: 90 }, - success: '', failure: (message) => message, + success: '', + failure: (message) => message, }, add: { - method: 'POST', url: /\/open\/crons\?t=\d+$/, - body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', sub_id: null }, - success: 'sample job -> 添加成功', failure: (message) => `sample job -> 添加失败(${message})`, + method: 'POST', + url: /\/open\/crons\?t=\d+$/, + body: { + name: 'sample job', + command: 'task job.py', + schedule: '0 * * * *', + sub_id: null, + }, + success: 'sample job -> 添加成功', + failure: (message) => `sample job -> 添加失败(${message})`, }, update: { - method: 'PUT', url: /\/open\/crons\?t=\d+$/, - body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', id: '37' }, - success: 'sample job -> 更新成功', failure: (message) => `sample job -> 更新失败(${message})`, + method: 'PUT', + url: /\/open\/crons\?t=\d+$/, + body: { + name: 'sample job', + command: 'task job.py', + schedule: '0 * * * *', + id: '37', + }, + success: 'sample job -> 更新成功', + failure: (message) => `sample job -> 更新失败(${message})`, }, command: { - method: 'PUT', url: /\/open\/crons\?t=\d+$/, + method: 'PUT', + url: /\/open\/crons\?t=\d+$/, body: { command: 'task job.py', id: '37' }, - success: 'task job.py -> 更新成功', failure: (message) => `task job.py -> 更新失败(${message})`, + success: 'task job.py -> 更新成功', + failure: (message) => `task job.py -> 更新失败(${message})`, }, delete: { - method: 'DELETE', url: /\/open\/crons\?t=\d+$/, - body: [37, 38], success: '成功', failure: (message) => `失败(${message})`, + method: 'DELETE', + url: /\/open\/crons\?t=\d+$/, + body: [37, 38], + success: '成功', + failure: (message) => `失败(${message})`, }, notify: { - method: 'PUT', url: /\/open\/system\/notify\?t=\d+$/, + method: 'PUT', + url: /\/open\/system\/notify\?t=\d+$/, body: { title: 'title', content: 'body' }, - success: '通知发送成功🎉', failure: (message) => `通知失败(${message})`, + success: '通知发送成功🎉', + failure: (message) => `通知失败(${message})`, }, find: { - method: 'GET', url: /\/open\/crons\/detail\?log_path=task\/run.log&t=\d+$/, - body: null, success: 'sample job', failure: () => '', + method: 'GET', + url: /\/open\/crons\/detail\?log_path=task\/run.log&t=\d+$/, + body: null, + success: 'sample job', + failure: () => '', }, auth: { - method: 'PUT', url: /\/open\/system\/auth\/reset\?t=\d+$/, - body: { retries: 0 }, success: '重置登录错误次数成功🎉', + method: 'PUT', + url: /\/open\/system\/auth\/reset\?t=\d+$/, + body: { retries: 0 }, + success: '重置登录错误次数成功🎉', failure: (message) => `重置登录错误次数失败(${message})`, }, }; @@ -58,10 +95,18 @@ function runCallback(endpoint, scenario) { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-api-token-')); try { const tokenFile = path.join(directory, 'token.json'); - fs.writeFileSync(tokenFile, JSON.stringify({ - value: 'initial-token', expiration: Math.floor(Date.now() / 1000) + 3600, - })); - const child = spawnSync('bash', ['-c', ` + fs.writeFileSync( + tokenFile, + JSON.stringify({ + value: 'initial-token', + expiration: Math.floor(Date.now() / 1000) + 3600, + }), + ); + const child = spawnSync( + 'bash', + [ + '-c', + ` . "$API_FILE" create_token() { printf 'refresh\\n' >> "$CAPTURE" @@ -106,22 +151,46 @@ function runCallback(endpoint, scenario) { find) find_cron_api 'log_path=task/run.log' ;; auth) update_auth_config '"retries":0' '重置登录错误次数' ;; esac - `], { - env: { ...process.env, PATH: `/usr/bin:/bin:${process.env.PATH}`, API_FILE: apiFile, file_auth_token: tokenFile, - CAPTURE: path.join(directory, 'requests'), SCENARIO: scenario, - ENDPOINT: endpoint, ql_port: '5700' }, - encoding: 'utf8', timeout: 10_000, - }); - const denied = ['persistent', 'forbidden', 'unavailable'].includes(scenario); - assert.equal(child.status, denied && ['add', 'delete'].includes(endpoint) ? 1 : 0, child.stderr); + `, + ], + { + env: { + ...process.env, + PATH: `/usr/bin:/bin:${process.env.PATH}`, + API_FILE: apiFile, + file_auth_token: tokenFile, + CAPTURE: path.join(directory, 'requests'), + SCENARIO: scenario, + ENDPOINT: endpoint, + ql_port: '5700', + }, + encoding: 'utf8', + timeout: 10_000, + }, + ); + const denied = ['persistent', 'forbidden', 'unavailable'].includes( + scenario, + ); + assert.equal( + child.status, + denied && ['add', 'delete'].includes(endpoint) ? 1 : 0, + child.stderr, + ); assert.equal(child.stderr, ''); - const lines = fs.readFileSync(path.join(directory, 'requests'), 'utf8').trim().split('\n'); + const lines = fs + .readFileSync(path.join(directory, 'requests'), 'utf8') + .trim() + .split('\n'); const refreshes = lines.filter((line) => line === 'refresh').length; const requests = lines.filter((line) => line !== 'refresh'); const captures = []; for (let i = 0; i < requests.length; i += 4) { - captures.push({ auth: requests[i], method: requests[i + 1], - url: requests[i + 2], body: JSON.parse(requests[i + 3]) }); + captures.push({ + auth: requests[i], + method: requests[i + 1], + url: requests[i + 2], + body: JSON.parse(requests[i + 3]), + }); } return { output: child.stdout, refreshes, captures }; } finally { @@ -130,12 +199,23 @@ function runCallback(endpoint, scenario) { } for (const [endpoint, expected] of Object.entries(endpoints)) { - for (const scenario of ['valid', 'expired', 'replaced', 'rejected', 'persistent', 'forbidden', 'unavailable']) { + for (const scenario of [ + 'valid', + 'expired', + 'replaced', + 'rejected', + 'persistent', + 'forbidden', + 'unavailable', + ]) { test(`${endpoint} API handles ${scenario} token without unbounded retries`, () => { const { output, refreshes, captures } = runCallback(endpoint, scenario); const retries = ['rejected', 'persistent'].includes(scenario); assert.equal(captures.length, retries ? 2 : 1); - assert.equal(refreshes, ['expired', 'rejected', 'persistent'].includes(scenario) ? 1 : 0); + assert.equal( + refreshes, + ['expired', 'rejected', 'persistent'].includes(scenario) ? 1 : 0, + ); for (const capture of captures) { assert.deepEqual(capture.body, expected.body); assert.equal(capture.method, expected.method); @@ -144,9 +224,18 @@ for (const [endpoint, expected] of Object.entries(endpoints)) { if (['expired', 'replaced', 'rejected'].includes(scenario)) { assert.equal(captures.at(-1).auth, 'Authorization: Bearer fresh-token'); } - const error = scenario === 'persistent' ? 'Token 已失效' - : scenario === 'forbidden' ? 'forbidden' : scenario === 'unavailable' ? 'unavailable' : ''; - assert.equal(output.trim(), error ? expected.failure(error) : expected.success); + const error = + scenario === 'persistent' + ? 'Token 已失效' + : scenario === 'forbidden' + ? 'forbidden' + : scenario === 'unavailable' + ? 'unavailable' + : ''; + assert.equal( + output.trim(), + error ? expected.failure(error) : expected.success, + ); }); } } diff --git a/test/back/single-instance-skip.test.cjs b/test/back/single-instance-skip.test.cjs index c9ad3e70..d4241847 100644 --- a/test/back/single-instance-skip.test.cjs +++ b/test/back/single-instance-skip.test.cjs @@ -8,8 +8,8 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) { cronWrites = [], instanceWrites = [], instanceReads = []; - const { runCron } = load('back/shared/runCron.ts', { - './i18n': { t: (s) => s }, + const { runCron } = load('back/cron/execution/runCron.ts', { + '../../shared/i18n': { t: (s) => s }, 'cross-spawn': { spawn: (cmd) => { spawned.push(cmd); @@ -17,12 +17,12 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) { return { pid: process.pid }; }, }, - './pLimit': { + './cronLimit': { runWithCronLimit: (_cron, execute) => execute(), removeQueuedCron() {}, }, - '../loaders/logger': { info() {}, error() {} }, - '../data/cron': { + '../../loaders/logger': { info() {}, error() {} }, + '../../data/cron': { CrontabModel: { findOne: async () => row, update: async (...args) => { @@ -34,7 +34,7 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) { }, CrontabStatus: { running: 0, idle: 1, queued: 3 }, }, - '../data/runningInstance': { + '../../data/runningInstance': { RunningInstanceModel: { findAll: async (options) => { instanceReads.push(options); @@ -45,7 +45,7 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) { InstanceStatus: { running: 0, stopped: 2 }, }, dayjs: () => ({ unix: () => 123 }), - './childProcess': { + '../../shared/childProcess': { observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }), asError: (e) => e, }, diff --git a/test/back/start-certificate-preparation.test.cjs b/test/back/start-certificate-preparation.test.cjs index 3edd9c96..bc2ef275 100644 --- a/test/back/start-certificate-preparation.test.cjs +++ b/test/back/start-certificate-preparation.test.cjs @@ -6,12 +6,15 @@ const path = require('node:path'); const { spawnSync } = require('node:child_process'); const startup = fs.readFileSync('shell/start-simplify.sh', 'utf8'); -const runtimeLoader = fs.readFileSync('shell/share.sh', 'utf8') +const runtimeLoader = fs + .readFileSync('shell/share.sh', 'utf8') .match(/^load_node_runtime_args\(\) \{[\s\S]*?^\}/m)[0]; -const preparation = `${runtimeLoader}\ndir_root="$QL_DIR"\n` + startup.slice( - startup.indexOf('\nfix_config\n'), - startup.indexOf('log_with_style "INFO" "$(t \'🔄'), -); +const preparation = + `${runtimeLoader}\ndir_root="$QL_DIR"\n` + + startup.slice( + startup.indexOf('\nfix_config\n'), + startup.indexOf('log_with_style "INFO" "$(t \'🔄'), + ); for (const fails of [false, true]) { test(`manual startup ${ fails diff --git a/test/back/stop-failure-feedback.test.cjs b/test/back/stop-failure-feedback.test.cjs index 8f1ecc8e..1d23c115 100644 --- a/test/back/stop-failure-feedback.test.cjs +++ b/test/back/stop-failure-feedback.test.cjs @@ -56,7 +56,7 @@ function scriptFixture(killTask, pid = 100) { '../config': { scriptPath: '/scripts' }, '../config/const': { TASK_COMMAND: 'task' }, '../config/util': { killTask, getPid: async () => pid }, - '../shared/pLimit': { removeQueuedCron() {} }, + '../cron/execution/cronLimit': { removeQueuedCron() {} }, './sock': {}, './cron': {}, './schedule': {}, diff --git a/test/back/stop-race.test.cjs b/test/back/stop-race.test.cjs index ed4fb181..0d77b764 100644 --- a/test/back/stop-race.test.cjs +++ b/test/back/stop-race.test.cjs @@ -35,7 +35,9 @@ async function fixture(t, onKill = async () => {}) { }); load('back/data/cronStats.ts', { '.': { sequelize: db } }); await db.sync(); - await db.transaction(tx => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx)); + await db.transaction((tx) => + require('../../back/cron/history').installTriggerHistory(db, tx), + ); await crons.bulkCreate([ { id: 1, command: 'task one.js', status: 0, pid: 101, log_path: 'one.log' }, { id: 2, command: 'task two.js', status: 0, pid: 201, log_path: 'two.log' }, @@ -59,8 +61,9 @@ async function fixture(t, onKill = async () => {}) { RunningInstanceModel: instances, InstanceStatus: { running: 0, finished: 1, stopped: 2, error: 3 }, }, - '../shared/cronProcess': { - pidNamespaceOwner: require('../../back/shared/cronProcess').pidNamespaceOwner, + '../cron/execution/cronProcess': { + pidNamespaceOwner: require('../../back/cron/execution/cronProcess') + .pidNamespaceOwner, verifyCronProcess() {}, }, '../config/util': { @@ -75,7 +78,7 @@ async function fixture(t, onKill = async () => {}) { }, '../config/const': {}, '../schedule/client': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../shared/utils': {}, '../shared/i18n': { t: (s) => s }, '../shared/logReader': {}, @@ -180,19 +183,21 @@ test('failed termination is not finalized as stopped', async (t) => { }); test('stop instance verifies cron ownership, waits for exit and never confirms a failed signal', async (t) => { - const f = await fixture(t, async ({pid}) => { if (pid===102) throw Error('still alive'); }); - assert.equal((await f.service.stopInstance(2,1)).code,404); + const f = await fixture(t, async ({ pid }) => { + if (pid === 102) throw Error('still alive'); + }); + assert.equal((await f.service.stopInstance(2, 1)).code, 404); await f.instances.create({ id: 6, cron_id: 1, status: 0, pid: null }); - assert.equal((await f.service.stopInstance(1,6)).code,409); - assert.deepEqual(f.killed,[]); - await assert.rejects(f.service.stopInstance(1,2), /still alive/); - assert.equal((await f.instances.findByPk(2)).status,0); - assert.equal((await f.service.stopInstance(1,1)).code,200); - assert.equal((await f.service.stopInstance(1,1)).data.outcome,'stopped'); - assert.equal((await f.instances.findByPk(1)).status,2); + assert.equal((await f.service.stopInstance(1, 6)).code, 409); + assert.deepEqual(f.killed, []); + await assert.rejects(f.service.stopInstance(1, 2), /still alive/); + assert.equal((await f.instances.findByPk(2)).status, 0); + assert.equal((await f.service.stopInstance(1, 1)).code, 200); + assert.equal((await f.service.stopInstance(1, 1)).data.outcome, 'stopped'); + assert.equal((await f.instances.findByPk(1)).status, 2); }); -test('legacy instances sharing a numeric PID cannot be individually signalled', async t => { +test('legacy instances sharing a numeric PID cannot be individually signalled', async (t) => { const f = await fixture(t); await f.instances.create({ id: 6, cron_id: 1, pid: 101, status: 0 }); assert.equal((await f.service.stopInstance(1, 1)).code, 409); @@ -200,40 +205,68 @@ test('legacy instances sharing a numeric PID cannot be individually signalled', assert.equal((await f.instances.findByPk(6)).status, 0); }); -test('concurrent single stops join only the same task and instance; failures release a retry', async t => { - let release, entered, fail = true; - const waiting = new Promise(resolve => { entered = resolve; }); - const gate = new Promise(resolve => { release = resolve; }); +test('concurrent single stops join only the same task and instance; failures release a retry', async (t) => { + let release, + entered, + fail = true; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); const f = await fixture(t, async ({ pid }) => { - if (pid === 101 && fail) { entered(); await gate; throw Error('denied'); } + if (pid === 101 && fail) { + entered(); + await gate; + throw Error('denied'); + } }); const first = f.service.stopInstance(1, 1); - const duplicates = Array.from({ length: 8 }, () => f.service.stopInstance(1, 1)); + const duplicates = Array.from({ length: 8 }, () => + f.service.stopInstance(1, 1), + ); await waiting; assert.equal((await f.service.stopInstance(2, 1)).code, 404); assert.equal((await f.instances.findByPk(2)).status, 0); assert.deepEqual(f.killed, [101]); fail = false; release(); - for (const r of await Promise.allSettled([first, ...duplicates])) assert.match(r.reason.message, /denied/); - const second = await Promise.all([f.service.stopInstance(1, 1), f.service.stopInstance(1, 1)]); - assert.deepEqual(second.map(r => r.data.outcome), ['stopped', 'stopped']); + for (const r of await Promise.allSettled([first, ...duplicates])) + assert.match(r.reason.message, /denied/); + const second = await Promise.all([ + f.service.stopInstance(1, 1), + f.service.stopInstance(1, 1), + ]); + assert.deepEqual( + second.map((r) => r.data.outcome), + ['stopped', 'stopped'], + ); assert.deepEqual(f.killed, [101, 101]); assert.equal((await f.service.stopInstance(1, 3)).data.outcome, 'ended'); assert.equal((await f.instances.findByPk(3)).exit_code, 0); }); -test('single and batch stop share the in-flight termination and keep the batch snapshot across retries', async t => { +test('single and batch stop share the in-flight termination and keep the batch snapshot across retries', async (t) => { let release, entered; - const gate = new Promise(resolve => { release = resolve; }); - const firstSignal = new Promise(resolve => { entered = resolve; }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const firstSignal = new Promise((resolve) => { + entered = resolve; + }); const f = await fixture(t, async ({ pid }) => { - if (pid === 101) { entered(); await gate; } + if (pid === 101) { + entered(); + await gate; + } }); const single = f.service.stopInstance(1, 1); await firstSignal; let captured; - const batchJoined = new Promise(resolve => { captured = resolve; }); + const batchJoined = new Promise((resolve) => { + captured = resolve; + }); const stopInstance = f.service.stopInstance.bind(f.service); f.service.stopInstance = (cronId, id) => { if (id === 1) captured(); @@ -241,24 +274,41 @@ test('single and batch stop share the in-flight termination and keep the batch s }; const bulk = f.service.stop([1]); await batchJoined; - const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize); - assert.deepEqual((await history.pendingStops()).map(r => r.instance_id), [1, 2]); + const history = new (require('../../back/cron/history').TriggerHistory)( + f.crons.sequelize, + ); + assert.deepEqual( + (await history.pendingStops()).map((r) => r.instance_id), + [1, 2], + ); await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 }); const duplicate = stopInstance(1, 1); release(); await Promise.all([single, bulk, duplicate]); assert.deepEqual(f.killed, [101, 102]); - assert.deepEqual((await f.instances.findAll({ order: [['id', 'ASC']] })).map(r => r.status), [2, 2, 1, 3, 0, 0]); + assert.deepEqual( + (await f.instances.findAll({ order: [['id', 'ASC']] })).map( + (r) => r.status, + ), + [2, 2, 1, 3, 0, 0], + ); assert.deepEqual(await history.pendingStops(), []); }); -test('a single stop is durable before asynchronous tree traversal and a replacement worker resumes it', async t => { +test('a single stop is durable before asynchronous tree traversal and a replacement worker resumes it', async (t) => { let interrupted = true; - const f = await fixture(t, async () => { if (interrupted) throw Error('interrupted while enumerating tree'); }); + const f = await fixture(t, async () => { + if (interrupted) throw Error('interrupted while enumerating tree'); + }); await assert.rejects(f.service.stopInstance(1, 2), /interrupted/); - const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize); + const history = new (require('../../back/cron/history').TriggerHistory)( + f.crons.sequelize, + ); const pending = await history.pendingStops(); - assert.deepEqual(pending.map(r => [r.cron_id, r.instance_id, r.pid, r.targets]), [[1, 2, 102, null]]); + assert.deepEqual( + pending.map((r) => [r.cron_id, r.instance_id, r.pid, r.targets]), + [[1, 2, 102, null]], + ); interrupted = false; const replacement = new f.service.constructor({ error() {}, warn() {} }); await replacement.resumePendingStops(history, pending); @@ -267,10 +317,14 @@ test('a single stop is durable before asynchronous tree traversal and a replacem assert.equal((await f.instances.findByPk(1)).status, 0); }); -test('an interrupted batch replays its original instances and leaves later queued and live runs alone', async t => { +test('an interrupted batch replays its original instances and leaves later queued and live runs alone', async (t) => { let blocked = true; - const f = await fixture(t, async ({ pid }) => { if (pid === 102 && blocked) throw Error('interrupted'); }); - const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize); + const f = await fixture(t, async ({ pid }) => { + if (pid === 102 && blocked) throw Error('interrupted'); + }); + const history = new (require('../../back/cron/history').TriggerHistory)( + f.crons.sequelize, + ); const key = require('node:crypto').randomUUID(); await history.enqueue('before', 1, 'manual', null); await assert.rejects(f.service.stop([1], key), /interrupted/); @@ -278,10 +332,18 @@ test('an interrupted batch replays its original instances and leaves later queue assert.deepEqual(pending, [{ request_id: key, cron_ids: '[1]' }]); await history.enqueue('after', 1, 'manual', null); await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 }); - await f.crons.update({ status: 3, queued_token: 'later' }, { where: { id: 1 } }); + await f.crons.update( + { status: 3, queued_token: 'later' }, + { where: { id: 1 } }, + ); blocked = false; - const replacement = () => new f.service.constructor({ warn() {}, error() {} }); - await replacement().resumePendingStops(history, await history.pendingStops(), pending); + const replacement = () => + new f.service.constructor({ warn() {}, error() {} }); + await replacement().resumePendingStops( + history, + await history.pendingStops(), + pending, + ); await replacement().resumePendingStops(history, [], pending); await replacement().stop([1, 1], key); await assert.rejects(replacement().stop([2], key), { status: 409 }); @@ -290,14 +352,17 @@ test('an interrupted batch replays its original instances and leaves later queue assert.equal((await f.instances.findByPk(6)).status, 0); assert.equal((await f.crons.findByPk(1)).queued_token, 'later'); const rows = await history.recent(1, 0); - assert.equal(rows.find(r => r.id === 'before').state, 'stopped'); - assert.equal(rows.find(r => r.id === 'after').state, 'queued'); + assert.equal(rows.find((r) => r.id === 'before').state, 'stopped'); + assert.equal(rows.find((r) => r.id === 'after').state, 'queued'); await replacement().stop([1], require('node:crypto').randomUUID()); assert.equal((await f.instances.findByPk(6)).status, 2); - assert.equal((await history.recent(1, 0)).find(r => r.id === 'after').state, 'stopped'); + assert.equal( + (await history.recent(1, 0)).find((r) => r.id === 'after').state, + 'stopped', + ); }); -test('replaying an empty original snapshot never targets the first later run', async t => { +test('replaying an empty original snapshot never targets the first later run', async (t) => { const f = await fixture(t); const key = require('node:crypto').randomUUID(); await f.service.stop([3], key); @@ -309,12 +374,16 @@ test('replaying an empty original snapshot never targets the first later run', a assert.deepEqual(f.killed, [301]); }); -test('a second restart rolls back receipt deletion when settling a legacy instance fails', async t => { +test('a second restart rolls back receipt deletion when settling a legacy instance fails', async (t) => { const f = await fixture(t); - const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize); + const history = new (require('../../back/cron/history').TriggerHistory)( + f.crons.sequelize, + ); await history.queueInstanceStop(1, 1, 101); const stop = () => f.service.stopInstance(1, 1); - const transactionError = () => { throw Error('interrupted during settlement'); }; + const transactionError = () => { + throw Error('interrupted during settlement'); + }; f.instances.addHook('beforeBulkUpdate', 'crash', transactionError); await assert.rejects(stop(), /interrupted during settlement/); f.instances.removeHook('beforeBulkUpdate', 'crash'); @@ -324,31 +393,47 @@ test('a second restart rolls back receipt deletion when settling a legacy instan assert.deepEqual(await history.pendingStops(), []); }); -test('simultaneous first submissions share a partial failure, then retry only the original instances', async t => { - let entered, release, fail = true; - const reached = new Promise(resolve => { entered = resolve; }); - const gate = new Promise(resolve => { release = resolve; }); +test('simultaneous first submissions share a partial failure, then retry only the original instances', async (t) => { + let entered, + release, + fail = true; + const reached = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); const f = await fixture(t, async ({ pid }) => { - if (pid === 102 && fail) { entered(); await gate; throw Error('partial failure'); } + if (pid === 102 && fail) { + entered(); + await gate; + throw Error('partial failure'); + } }); const key = require('node:crypto').randomUUID(); - const calls = Array.from({ length: 6 }, (_, i) => f.service.stop(i % 2 ? [1, 1] : [1], key)); + const calls = Array.from({ length: 6 }, (_, i) => + f.service.stop(i % 2 ? [1, 1] : [1], key), + ); const results = Promise.allSettled(calls); await reached; await assert.rejects(f.service.stop([2], key), { status: 409 }); await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 }); release(); - for (const result of await results) assert.match(result.reason.message, /partial failure/); + for (const result of await results) + assert.match(result.reason.message, /partial failure/); assert.deepEqual(f.killed, [101, 102]); fail = false; const replacement = new f.service.constructor({ error() {}, warn() {} }); - await Promise.all([replacement.stop([1], key), replacement.stop([1, 1], key)]); + await Promise.all([ + replacement.stop([1], key), + replacement.stop([1, 1], key), + ]); assert.deepEqual(f.killed, [101, 102, 102]); assert.equal((await f.instances.findByPk(6)).status, 0); assert.equal((await f.instances.findByPk(5)).status, 0); }); -test('a legacy task pointing to a different task’s PID cannot consume its stop result', async t => { +test('a legacy task pointing to a different task’s PID cannot consume its stop result', async (t) => { const f = await fixture(t); await f.crons.create({ id: 3, status: 0, pid: 101 }); const key = require('node:crypto').randomUUID(); diff --git a/test/back/subscription-review-regression.test.cjs b/test/back/subscription-review-regression.test.cjs index 825c2713..5e9f7a2f 100644 --- a/test/back/subscription-review-regression.test.cjs +++ b/test/back/subscription-review-regression.test.cjs @@ -305,7 +305,11 @@ git_clone_scripts() { mkdir -p "$2"; cp "$QA_ROOT/template/"* "$2/"; exit_status ql() { get_uniq_path "$2" "$6"; update_repo "${'${@:2}'}"; } ${formatCommand(doc)}`; execFileSync('/bin/bash', ['-c', code], { - env: { ...process.env, dir_shell: path.resolve('shell'), QA_ROOT: root }, + env: { + ...process.env, + dir_shell: path.resolve('shell'), + QA_ROOT: root, + }, encoding: 'utf8', timeout: 5000, }); @@ -457,7 +461,11 @@ function cancellationFixture(t, subscriptions) { events.push(['createInterval', doc.command, interval, immediately]), }; const service = new Subscription( - {}, schedule, {}, { removeSSHKey: async () => {} }, {}, + {}, + schedule, + {}, + { removeSSHKey: async () => {} }, + {}, ); service.setSshConfig = async () => {}; return { service, docs, events }; @@ -466,25 +474,44 @@ function cancellationFixture(t, subscriptions) { async function sshLifecycleFixture(t, initial) { const root = temporary(t); const ssh = sshService(root); - let docs = [{ ...initial, get() { return { ...this }; } }]; - const SubscriptionService = load(path.resolve('back/services/subscription.ts'), { - '../config': { scriptPath: root, repoPath: root }, - '../data/subscription': { - Subscription: class { constructor(value) { Object.assign(this, value); } }, - SubscriptionModel: { - findAll: async () => docs, - destroy: async () => { docs = []; }, + let docs = [ + { + ...initial, + get() { + return { ...this }; }, }, - '../data/cron': { CrontabModel: { findAll: async () => [] } }, - '../config/util': { - rmPath: (p) => fs.promises.rm(p, { recursive: true, force: true }), + ]; + const SubscriptionService = load( + path.resolve('back/services/subscription.ts'), + { + '../config': { scriptPath: root, repoPath: root }, + '../data/subscription': { + Subscription: class { + constructor(value) { + Object.assign(this, value); + } + }, + SubscriptionModel: { + findAll: async () => docs, + destroy: async () => { + docs = []; + }, + }, + }, + '../data/cron': { CrontabModel: { findAll: async () => [] } }, + '../config/util': { + rmPath: (p) => fs.promises.rm(p, { recursive: true, force: true }), + }, + '../config/const': {}, + '../shared/i18n': { t: (x) => x, tf: (x) => x }, + '../shared/pLimit': {}, + './schedule': {}, + './sock': {}, + './sshKey': {}, + './cron': {}, }, - '../config/const': {}, - '../shared/i18n': { t: (x) => x, tf: (x) => x }, - '../shared/pLimit': {}, - './schedule': {}, './sock': {}, './sshKey': {}, './cron': {}, - }).default; + ).default; const service = new SubscriptionService({}, {}, {}, ssh, {}); service.handleTask = async () => {}; service.getDb = async () => ({ ...docs[0] }); @@ -503,8 +530,14 @@ test('editing an SSH subscription removes the old alias key and configuration', await f.service.update({ ...initial, alias }); const mapped = paths.getSubscriptionSshAlias(alias); assert.equal(fs.existsSync(path.join(f.root, initial.alias)), false); - assert.equal(fs.existsSync(path.join(f.root, initial.alias + '.config')), false); - assert.equal(fs.readFileSync(path.join(f.root, mapped), 'utf8').trim(), 'fixture-key'); + assert.equal( + fs.existsSync(path.join(f.root, initial.alias + '.config')), + false, + ); + assert.equal( + fs.readFileSync(path.join(f.root, mapped), 'utf8').trim(), + 'fixture-key', + ); assert.ok(fs.existsSync(path.join(f.root, mapped + '.config'))); }); @@ -606,112 +639,202 @@ test('valid subscription scheduling still creates quoted commands for both sched } }); -test('repeated subscription sync recognizes installed system-wrapper and legacy rules', t => { +test('repeated subscription sync recognizes installed system-wrapper and legacy rules', (t) => { const f = updateFixture(t); const { shellQuote } = load(path.resolve('back/shared/shellQuote.ts')); - const wrapped = shellQuote("real_time=false ID=1 task_before='task owner_repo/hook.js' task node 'owner_repo/keep.js' -- 'one two'"); - fs.writeFileSync(path.join(f.root, 'crontab'), [ - '1 * * * * ID=1 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + wrapped, - '# 2 * * * * ID=2 task owner_repo/keep.py', - '3 * * * * ID=3 other-task owner_repo/unrelated.js', - ].join('\n')); + const wrapped = shellQuote( + "real_time=false ID=1 task_before='task owner_repo/hook.js' task node 'owner_repo/keep.js' -- 'one two'", + ); + fs.writeFileSync( + path.join(f.root, 'crontab'), + [ + '1 * * * * ID=1 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + + wrapped, + '# 2 * * * * ID=2 task owner_repo/keep.py', + '3 * * * * ID=3 other-task owner_repo/unrelated.js', + ].join('\n'), + ); const lists = path.join(f.root, 'lists'); for (let sync = 0; sync < 2; sync++) { f.run('js|py'); - assert.deepEqual(fs.readFileSync(path.join(lists, 'owner_repo_user.list'), 'utf8').trim().split('\n'), - ['owner_repo/keep.js', 'owner_repo/keep.py']); - execFileSync('/bin/bash', ['-c', shellFunction('diff_cron') + '\ndiff_cron owner_repo_scripts.list owner_repo_user.list added removed'], { cwd: lists }); - for (const name of ['added', 'removed']) assert.equal(fs.readFileSync(path.join(lists, name), 'utf8'), ''); + assert.deepEqual( + fs + .readFileSync(path.join(lists, 'owner_repo_user.list'), 'utf8') + .trim() + .split('\n'), + ['owner_repo/keep.js', 'owner_repo/keep.py'], + ); + execFileSync( + '/bin/bash', + [ + '-c', + shellFunction('diff_cron') + + '\ndiff_cron owner_repo_scripts.list owner_repo_user.list added removed', + ], + { cwd: lists }, + ); + for (const name of ['added', 'removed']) + assert.equal(fs.readFileSync(path.join(lists, name), 'utf8'), ''); } }); -test('subscription cleanup deletes only exact script operands and keeps files outside its repository', t => { +test('subscription cleanup deletes only exact script operands and keeps files outside its repository', (t) => { const f = updateFixture(t); const { shellQuote } = load(path.resolve('back/shared/shellQuote.ts')); - const wrapper = cmd => '1 * * * * ID=12 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + shellQuote(cmd); - fs.writeFileSync(path.join(f.root, 'crontab'), [ - '1 * * * * ID=10 task consumer.js owner_repo/drop.js', - wrapper('real_time=false ID=12 task node owner_repo/drop.js -- argument'), - '1 * * * * ID=13 task owner_repo/../../outside', - '1 * * * * ID=14 task owner_repo/link/outside', - '1 * * * * ID=15 task consumer.js owner_repo/../../outside', - '1 * * * * ID=16 task owner_repo/keep.js', - '1 * * * * ID=17 task owner_repo/keep.py', - '1 * * * * ID=18 task owner_repo/keepXjs', - '1 * * * * ID=19 task "owner_repo/keep spaces.js"', - '1 * * * * ID=20 task consumer.js bash "$QL_DIR/shell/system-cron.sh" "ID=21 task owner_repo/wrong.js"', - wrapper('real_time=false ID=22 task owner_repo/foreign.js'), - ].join('\n')); + const wrapper = (cmd) => + '1 * * * * ID=12 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + + shellQuote(cmd); + fs.writeFileSync( + path.join(f.root, 'crontab'), + [ + '1 * * * * ID=10 task consumer.js owner_repo/drop.js', + wrapper('real_time=false ID=12 task node owner_repo/drop.js -- argument'), + '1 * * * * ID=13 task owner_repo/../../outside', + '1 * * * * ID=14 task owner_repo/link/outside', + '1 * * * * ID=15 task consumer.js owner_repo/../../outside', + '1 * * * * ID=16 task owner_repo/keep.js', + '1 * * * * ID=17 task owner_repo/keep.py', + '1 * * * * ID=18 task owner_repo/keepXjs', + '1 * * * * ID=19 task "owner_repo/keep spaces.js"', + '1 * * * * ID=20 task consumer.js bash "$QL_DIR/shell/system-cron.sh" "ID=21 task owner_repo/wrong.js"', + wrapper('real_time=false ID=22 task owner_repo/foreign.js'), + ].join('\n'), + ); fs.writeFileSync(path.join(f.root, 'template', 'keep spaces.js'), 'keep'); const scripts = f.run('js|py'); fs.writeFileSync(path.join(f.root, 'outside'), 'keep'); fs.symlinkSync(f.root, path.join(scripts, 'link')); fs.writeFileSync(path.join(scripts, 'drop.js'), 'old'); const lists = path.join(f.root, 'lists'); - execFileSync('/bin/bash', ['-c', [ - shellFunction('diff_cron'), shellFunction('del_cron'), 't(){ :; }; notify_api(){ :; }', - 'del_cron_api(){ echo "$1" > deleted; }', - 'diff_cron owner_repo_scripts.list owner_repo_user.list added removed', - 'del_cron removed owner_repo', - ].join('\n')], { cwd: lists, env: { ...process.env, dir_shell: path.resolve('shell'), dir_list_tmp: lists, dir_scripts: path.dirname(scripts) } }); - assert.deepEqual(fs.readFileSync(path.join(lists, 'deleted'), 'utf8').trim().split(',').sort(), ['12', '18']); + execFileSync( + '/bin/bash', + [ + '-c', + [ + shellFunction('diff_cron'), + shellFunction('del_cron'), + 't(){ :; }; notify_api(){ :; }', + 'del_cron_api(){ echo "$1" > deleted; }', + 'diff_cron owner_repo_scripts.list owner_repo_user.list added removed', + 'del_cron removed owner_repo', + ].join('\n'), + ], + { + cwd: lists, + env: { + ...process.env, + dir_shell: path.resolve('shell'), + dir_list_tmp: lists, + dir_scripts: path.dirname(scripts), + }, + }, + ); + assert.deepEqual( + fs + .readFileSync(path.join(lists, 'deleted'), 'utf8') + .trim() + .split(',') + .sort(), + ['12', '18'], + ); assert.equal(fs.readFileSync(path.join(f.root, 'outside'), 'utf8'), 'keep'); assert.equal(fs.existsSync(path.join(scripts, 'drop.js')), false); assert.ok(fs.existsSync(path.join(scripts, 'keep.js'))); assert.ok(fs.existsSync(path.join(scripts, 'keep spaces.js'))); }); -test('subscription creation retains schedule and passes a quoted script name as one operand', t => { +test('subscription creation retains schedule and passes a quoted script name as one operand', (t) => { const root = temporary(t); fs.mkdirSync(path.join(root, 'repo')); const filename = "repo/what's new.js"; fs.writeFileSync(path.join(root, filename), "// 7 6 * * * what's new.js\n"); fs.writeFileSync(path.join(root, 'added'), filename + '\n'); const instructions = [ - shellFunction('add_cron'), 'cmd_task=task; dir_scripts=$1', + shellFunction('add_cron'), + 'cmd_task=task; dir_scripts=$1', 'notify_api(){ :; }; t(){ :; }', 'add_cron_api(){ printf "%s\\n%s\\n" "$1" "$2" > "$dir_scripts/result"; }', 'add_cron "$1/added" repo', ].join('\n'); execFileSync('/bin/bash', ['-c', instructions, '--', root], { cwd: root }); - const [rule, command] = fs.readFileSync(path.join(root, 'result'), 'utf8').trimEnd().split('\n'); + const [rule, command] = fs + .readFileSync(path.join(root, 'result'), 'utf8') + .trimEnd() + .split('\n'); assert.equal(rule, '7 6 * * *'); - assert.equal(command, 'task ' + load(path.resolve('back/shared/shellQuote.ts')).shellQuote(filename)); + assert.equal( + command, + 'task ' + + load(path.resolve('back/shared/shellQuote.ts')).shellQuote(filename), + ); }); -test('invalid include, exclude or dependency filters never become an empty successful sync', t => { +test('invalid include, exclude or dependency filters never become an empty successful sync', (t) => { const f = updateFixture(t); const scripts = f.run('js|py'); const listing = path.join(f.root, 'lists', 'owner_repo_scripts.list'); const original = fs.readFileSync(listing, 'utf8'); - const code = shellFunction('gen_list_repo') + '\ngen_list_repo "$QA_ROOT/template" owner "$1" "$2" "$3" js'; - for (const filters of [['[', '', ''], ['', '[', ''], ['no-match', '', '[']]) { - const result = require('node:child_process').spawnSync('/bin/bash', ['-c', code, '--', ...filters], { env: { - ...process.env, dir_shell: path.resolve('shell'), QA_ROOT: f.root, uniq_path: 'owner_repo', - dir_list_tmp: path.dirname(listing), dir_scripts: path.dirname(scripts), - } }); + const code = + shellFunction('gen_list_repo') + + '\ngen_list_repo "$QA_ROOT/template" owner "$1" "$2" "$3" js'; + for (const filters of [ + ['[', '', ''], + ['', '[', ''], + ['no-match', '', '['], + ]) { + const result = require('node:child_process').spawnSync( + '/bin/bash', + ['-c', code, '--', ...filters], + { + env: { + ...process.env, + dir_shell: path.resolve('shell'), + QA_ROOT: f.root, + uniq_path: 'owner_repo', + dir_list_tmp: path.dirname(listing), + dir_scripts: path.dirname(scripts), + }, + }, + ); assert.notEqual(result.status, 0); assert.match(result.stderr.toString(), /invalid subscription filter/); assert.equal(fs.readFileSync(listing, 'utf8'), original); - assert.equal(fs.readFileSync(path.join(scripts, 'keep.js'), 'utf8'), 'keep.js'); + assert.equal( + fs.readFileSync(path.join(scripts, 'keep.js'), 'utf8'), + 'keep.js', + ); } }); -test('subscription writes reject destination links and replace hardlinks without altering the other inode name', t => { +test('subscription writes reject destination links and replace hardlinks without altering the other inode name', (t) => { const f = updateFixture(t); - const scripts = path.join(f.root, 'scripts'), repo = path.join(scripts, 'owner_repo'); + const scripts = path.join(f.root, 'scripts'), + repo = path.join(scripts, 'owner_repo'); const outside = path.join(f.root, 'outside'); fs.mkdirSync(outside); const file = path.join(outside, 'keep.js'); fs.writeFileSync(file, 'protected'); const helper = path.resolve('shell/subscription-files.py'); - const install = (dest) => require('node:child_process').spawnSync('python3', [helper, 'copy', path.join(f.root, 'template/keep.js'), scripts, dest]); + const install = (dest) => + require('node:child_process').spawnSync('python3', [ + helper, + 'copy', + path.join(f.root, 'template/keep.js'), + scripts, + dest, + ]); fs.symlinkSync(outside, repo); assert.notEqual(install('owner_repo/keep.js').status, 0); - fs.unlinkSync(repo); fs.mkdirSync(repo); + fs.unlinkSync(repo); + fs.mkdirSync(repo); fs.symlinkSync(outside, path.join(repo, 'nested')); assert.notEqual(install('owner_repo/nested/keep.js').status, 0); - for (const dest of ['owner_repo/notify.js', 'owner_repo/dep.js', 'owner_repo/keep.js', 'raw_test.js']) { + for (const dest of [ + 'owner_repo/notify.js', + 'owner_repo/dep.js', + 'owner_repo/keep.js', + 'raw_test.js', + ]) { fs.symlinkSync(file, path.join(scripts, dest)); assert.notEqual(install(dest).status, 0); assert.equal(fs.readFileSync(file, 'utf8'), 'protected'); @@ -723,22 +846,41 @@ test('subscription writes reject destination links and replace hardlinks without assert.equal(fs.readFileSync(file, 'utf8'), 'protected'); }); -test('a rejected guarded deletion preserves its file and propagates failure to subscription sync', t => { +test('a rejected guarded deletion preserves its file and propagates failure to subscription sync', (t) => { const f = updateFixture(t); const scripts = f.run('js'); - const lists = path.join(f.root, 'lists'), operand = "owner_repo/what's old.js"; + const lists = path.join(f.root, 'lists'), + operand = "owner_repo/what's old.js"; fs.writeFileSync(path.join(f.root, 'scripts', operand), 'old contents'); - fs.writeFileSync(path.join(lists, 'owner_repo_registered.list'), '37\t' + operand + '\t1234\n'); + fs.writeFileSync( + path.join(lists, 'owner_repo_registered.list'), + '37\t' + operand + '\t1234\n', + ); fs.writeFileSync(path.join(lists, 'removed'), operand + '\n'); const shell = [ - shellFunction('del_cron'), 't(){ :; }; notify_api(){ :; }', + shellFunction('del_cron'), + 't(){ :; }; notify_api(){ :; }', 'del_cron_api(){ printf "%s" "$2" > "$dir_list_tmp/request"; return 1; }', 'del_cron "$dir_list_tmp/removed" owner_repo', ].join('\n'); - const result = require('node:child_process').spawnSync('/bin/bash', ['-c', shell], { - env: { ...process.env, dir_shell: path.resolve('shell'), dir_scripts: path.dirname(scripts), dir_list_tmp: lists }, - }); + const result = require('node:child_process').spawnSync( + '/bin/bash', + ['-c', shell], + { + env: { + ...process.env, + dir_shell: path.resolve('shell'), + dir_scripts: path.dirname(scripts), + dir_list_tmp: lists, + }, + }, + ); assert.notEqual(result.status, 0); - assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lists, 'request'))), [{id: 37, script: operand, revision: 1234}]); - assert.equal(fs.readFileSync(path.join(f.root, 'scripts', operand), 'utf8'), 'old contents'); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lists, 'request'))), [ + { id: 37, script: operand, revision: 1234 }, + ]); + assert.equal( + fs.readFileSync(path.join(f.root, 'scripts', operand), 'utf8'), + 'old contents', + ); }); diff --git a/test/back/subscription-storage-regression.test.cjs b/test/back/subscription-storage-regression.test.cjs index a27230a1..39edc661 100644 --- a/test/back/subscription-storage-regression.test.cjs +++ b/test/back/subscription-storage-regression.test.cjs @@ -478,7 +478,12 @@ test('an unrelated dangling or outside symlink reference does not block safe cle }); test('URL-derived storage accepts legal directory names longer than user aliases and containing spaces', async (t) => { - const doc = { ...cases[0], id: 1, alias: 'short-alias', url: `/tmp/owner/${'r'.repeat(205)} repo.git` }; + const doc = { + ...cases[0], + id: 1, + alias: 'short-alias', + url: `/tmp/owner/${'r'.repeat(205)} repo.git`, + }; const f = fixture(t, [doc]); const files = f.paths(doc).map((p) => path.join(p, 'job.js')); files.forEach(f.write); @@ -506,7 +511,12 @@ test('an unrepresentable unused Shell filename does not block valid CLI raw clea }); test('cleanup retains each representable path when only its prefixed Shell script name is too long', async (t) => { - const doc = { id: 1, alias: 'partial-raw', type: 'file', url: 'https://example.com/job.js?token=' }; + const doc = { + id: 1, + alias: 'partial-raw', + type: 'file', + url: 'https://example.com/job.js?token=', + }; const prefix = getSubscriptionStorageNames(doc).raw; doc.url += 'a'.repeat(255 - Buffer.byteLength(prefix)); const shell = getSubscriptionStorageNames(doc); @@ -536,7 +546,12 @@ test('a legal Unicode alias with an unrepresentable unused directory does not bl }); test('Unicode storage follows filesystem limits rather than imposing a UTF-8 byte cap', async (t) => { - const doc = { ...cases[0], id: 1, alias: 'short-alias', url: `/tmp/owner/${'中'.repeat(86)}.git` }; + const doc = { + ...cases[0], + id: 1, + alias: 'short-alias', + url: `/tmp/owner/${'中'.repeat(86)}.git`, + }; const f = fixture(t, [doc]); const files = f.paths(doc).map((p) => path.join(p, 'job.js')); for (const file of files) { diff --git a/test/back/system-dependence-cache.test.cjs b/test/back/system-dependence-cache.test.cjs index 1df6006d..efe55f16 100644 --- a/test/back/system-dependence-cache.test.cjs +++ b/test/back/system-dependence-cache.test.cjs @@ -60,7 +60,7 @@ test('clearing a dependency cache marks installed entries for reinstall', async SystemModel: {}, }); stubModule('../../back/schedule/client', { __esModule: true, default: {} }); - stubModule('../../back/shared/pLimit', { + stubModule('../../back/cron/execution/cronLimit', { __esModule: true, default: {}, }); diff --git a/test/back/system-export-history.test.cjs b/test/back/system-export-history.test.cjs index 4994a8cb..3d017603 100644 --- a/test/back/system-export-history.test.cjs +++ b/test/back/system-export-history.test.cjs @@ -23,7 +23,7 @@ async function fixture(t) { '../data/dependence': {}, '../data/notify': {}, '../data/system': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../shared/i18n': { t: (x) => x }, './notify': class {}, diff --git a/test/back/system-log-clear.test.cjs b/test/back/system-log-clear.test.cjs index 296125f2..70b5a2cd 100644 --- a/test/back/system-log-clear.test.cjs +++ b/test/back/system-log-clear.test.cjs @@ -19,7 +19,7 @@ async function fixture(t) { '../data/dependence': {}, '../data/notify': {}, '../data/system': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../shared/i18n': { t: (x) => x }, './notify': class {}, @@ -36,7 +36,10 @@ test('clearing system logs preserves append handles used by existing workers', a await fs.writeFile(active, 'old active logs\n'); await fs.writeFile(rotated, 'old rotated logs\n'); await fs.writeFile(path.join(root, 'audit.json'), 'rotation metadata'); - const workers = await Promise.all([fs.open(active, 'a'), fs.open(active, 'a')]); + const workers = await Promise.all([ + fs.open(active, 'a'), + fs.open(active, 'a'), + ]); t.after(async () => { await Promise.all(workers.map((worker) => worker.close())); }); diff --git a/test/back/systemTokenRenewal.test.cjs b/test/back/systemTokenRenewal.test.cjs index 99251413..0b028663 100644 --- a/test/back/systemTokenRenewal.test.cjs +++ b/test/back/systemTokenRenewal.test.cjs @@ -37,12 +37,17 @@ function fixture(t, initialTokens = []) { }); let now = START; let app = { - name: 'system', client_id: 'system-client', client_secret: 'system-secret', - scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens, + name: 'system', + client_id: 'system-client', + client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], + tokens: initialTokens, }; t.mock.method(Date, 'now', () => now * 1000); t.mock.method(shareStore, 'getApps', async () => [app]); - t.mock.method(shareStore, 'updateApps', async (apps) => { [app] = apps; }); + t.mock.method(shareStore, 'updateApps', async (apps) => { + [app] = apps; + }); t.mock.method(AppModel, 'findOne', async ({ where }) => { if (where.name) assert.equal(where.name, app.name); else { @@ -58,8 +63,12 @@ function fixture(t, initialTokens = []) { t.mock.method(AppModel, 'findAll', async () => [{ get: () => app }]); return { service: new OpenService({}), - atDay(day) { now = START + day * DAY; }, - tokens() { return app.tokens; }, + atDay(day) { + now = START + day * DAY; + }, + tokens() { + return app.tokens; + }, }; } @@ -93,7 +102,8 @@ test('startup generation renews before a restarted 28-day interval', async (t) = test('generation at the five-token limit extends the reused token without revoking active tokens', async (t) => { const initial = Array.from({ length: 5 }, (_, index) => ({ - value: `token-${index}`, expiration: START + 2 * DAY, + value: `token-${index}`, + expiration: START + 2 * DAY, })); const state = fixture(t, initial); const renewed = await state.service.generateSystemToken(true); @@ -117,7 +127,9 @@ test('ordinary acquisition reuses the newest valid database token and republishe assert.equal(token.value, 'newer-token'); assert.deepEqual(state.tokens(), initial); assert.deepEqual( - JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8')), + JSON.parse( + fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8'), + ), token, ); }); @@ -125,10 +137,21 @@ test('ordinary acquisition reuses the newest valid database token and republishe test('a failed generation releases its lock and does not publish a token', async (t) => { const state = fixture(t); const update = AppModel.update; - AppModel.update = async () => { throw new Error('generation failed'); }; - await assert.rejects(state.service.generateSystemToken(), /generation failed/); - assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false); - assert.equal(fs.existsSync(path.join(config.configPath, 'token.json.refresh.lock')), false); + AppModel.update = async () => { + throw new Error('generation failed'); + }; + await assert.rejects( + state.service.generateSystemToken(), + /generation failed/, + ); + assert.equal( + fs.existsSync(path.join(config.configPath, 'token.json')), + false, + ); + assert.equal( + fs.existsSync(path.join(config.configPath, 'token.json.refresh.lock')), + false, + ); AppModel.update = update; const token = await state.service.generateSystemToken(); assert.ok(state.tokens().some((current) => current.value === token.value)); @@ -142,8 +165,14 @@ test('acquisition recovers an authentication cache failure after the database co if (++attempts === 1) throw new Error('authentication cache failed'); return updateCache(apps); }; - await assert.rejects(state.service.generateSystemToken(), /authentication cache failed/); - assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false); + await assert.rejects( + state.service.generateSystemToken(), + /authentication cache failed/, + ); + assert.equal( + fs.existsSync(path.join(config.configPath, 'token.json')), + false, + ); const committed = state.tokens()[0]; const token = await state.service.generateSystemToken(); assert.equal(token.value, committed.value); @@ -156,12 +185,20 @@ async function processFixture(t, initialTokens = []) { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-token-process-')); t.after(() => fs.rmSync(directory, { recursive: true, force: true })); const databaseFile = path.join(directory, 'database.json'); - fs.writeFileSync(databaseFile, JSON.stringify({ - name: 'system', client_id: 'system-client', client_secret: 'system-secret', - scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens, - })); + fs.writeFileSync( + databaseFile, + JSON.stringify({ + name: 'system', + client_id: 'system-client', + client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], + tokens: initialTokens, + }), + ); const worker = path.join(directory, 'worker.cjs'); - fs.writeFileSync(worker, ` + fs.writeFileSync( + worker, + ` const fs = require('node:fs/promises'); const path = require('node:path'); const root = process.cwd(); @@ -195,26 +232,46 @@ async function processFixture(t, initialTokens = []) { shareStore.getApps = async () => { throw new Error('stale cache must not be read'); }; shareStore.updateApps = async () => {}; require(path.join(root, 'back/token')); - `); + `, + ); return { directory, run(renew = false, fail = false, hold = false) { - return execute(process.execPath, [ - '-r', require.resolve('ts-node/register/transpile-only'), worker, - ...(renew ? ['--renew'] : []), - ], { - cwd: root, timeout: 20_000, - env: { ...process.env, QL_TOKEN_TEST_FAIL: fail ? '1' : '0', QL_TOKEN_TEST_HOLD: hold ? '1' : '0' }, - }); + return execute( + process.execPath, + [ + '-r', + require.resolve('ts-node/register/transpile-only'), + worker, + ...(renew ? ['--renew'] : []), + ], + { + cwd: root, + timeout: 20_000, + env: { + ...process.env, + QL_TOKEN_TEST_FAIL: fail ? '1' : '0', + QL_TOKEN_TEST_HOLD: hold ? '1' : '0', + }, + }, + ); + }, + tokens() { + return JSON.parse(fs.readFileSync(databaseFile, 'utf8')).tokens; + }, + cached() { + return JSON.parse( + fs.readFileSync(path.join(directory, 'token.json'), 'utf8'), + ); }, - tokens() { return JSON.parse(fs.readFileSync(databaseFile, 'utf8')).tokens; }, - cached() { return JSON.parse(fs.readFileSync(path.join(directory, 'token.json'), 'utf8')); }, }; } test('four independent token processes converge on one usable token when the cache is missing', async (t) => { const state = await processFixture(t); - const results = await Promise.all(Array.from({ length: 4 }, () => state.run())); + const results = await Promise.all( + Array.from({ length: 4 }, () => state.run()), + ); const issued = results.map(({ stdout, stderr }) => { assert.equal(stderr, ''); return stdout.trim(); @@ -223,13 +280,24 @@ test('four independent token processes converge on one usable token when the cac assert.equal(state.tokens().length, 1); assert.equal(state.tokens()[0].value, issued[0]); assert.equal(state.cached().value, issued[0]); - assert.equal(fs.existsSync(path.join(state.directory, 'token.json.refresh.lock')), false); + assert.equal( + fs.existsSync(path.join(state.directory, 'token.json.refresh.lock')), + false, + ); }); test('concurrent scheduled renewal and ordinary acquisition preserve all returned tokens', async (t) => { - const original = { value: 'original-token', expiration: Math.round(Date.now() / 1000) + DAY }; + const original = { + value: 'original-token', + expiration: Math.round(Date.now() / 1000) + DAY, + }; const state = await processFixture(t, [original]); - const results = await Promise.all([state.run(true), state.run(), state.run(true), state.run()]); + const results = await Promise.all([ + state.run(true), + state.run(), + state.run(true), + state.run(), + ]); const tokens = state.tokens(); assert.equal(tokens.length, 3); assert.ok(tokens.some((token) => token.value === original.value)); @@ -258,16 +326,23 @@ test('startup configures the 28-day token task with explicit renewal', async (t) const initialize = require('../../back/loaders/initTask').default; const SystemService = require('../../back/services/system').default; const ScheduleService = require('../../back/services/schedule').default; - const SubscriptionService = require('../../back/services/subscription').default; + const SubscriptionService = + require('../../back/services/subscription').default; const SshKeyService = require('../../back/services/sshKey').default; const scheduled = []; const services = new Map([ [SystemService, { getSystemConfig: async () => undefined }], - [ScheduleService, { - cancelIntervalTask: async () => {}, - createIntervalTask: (...args) => scheduled.push(args), - }], - [SubscriptionService, { setSshConfig: async () => {}, list: async () => [] }], + [ + ScheduleService, + { + cancelIntervalTask: async () => {}, + createIntervalTask: (...args) => scheduled.push(args), + }, + ], + [ + SubscriptionService, + { setSshConfig: async () => {}, list: async () => [] }, + ], [SshKeyService, {}], ]); t.mock.method(Container, 'get', (service) => { @@ -285,7 +360,9 @@ test('startup configures the 28-day token task with explicit renewal', async (t) function appsFixture(t) { const previousConfigPath = config.configPath; - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-apps-concurrency-')); + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), 'ql-apps-concurrency-'), + ); config.configPath = directory; t.after(() => { config.configPath = previousConfigPath; @@ -294,14 +371,28 @@ function appsFixture(t) { t.mock.method(Date, 'now', () => START * 1000); const clone = (value) => JSON.parse(JSON.stringify(value)); let apps = [ - { id: 1, name: 'system', client_id: 'system-client', client_secret: 'system-secret', - scopes: ['crons', 'system', 'dashboard'], tokens: [{ value: 'system-token', expiration: START + DAY }] }, - { id: 2, name: 'external', client_id: 'external-client', client_secret: 'external-secret', - scopes: ['crons'], tokens: [] }, + { + id: 1, + name: 'system', + client_id: 'system-client', + client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], + tokens: [{ value: 'system-token', expiration: START + DAY }], + }, + { + id: 2, + name: 'external', + client_id: 'external-client', + client_secret: 'external-secret', + scopes: ['crons'], + tokens: [], + }, ]; let cached = clone(apps); - const matches = (app, where) => Object.entries(where).every(([key, value]) => - Array.isArray(value) ? value.includes(app[key]) : app[key] === value); + const matches = (app, where) => + Object.entries(where).every(([key, value]) => + Array.isArray(value) ? value.includes(app[key]) : app[key] === value, + ); t.mock.method(AppModel, 'findOne', async ({ where }) => { const app = apps.find((app) => matches(app, where)); if (!app) return null; @@ -309,22 +400,36 @@ function appsFixture(t) { await new Promise((resolve) => setTimeout(resolve, 10)); return { ...snapshot, get: () => snapshot }; }); - t.mock.method(AppModel, 'findAll', async () => clone(apps).map((app) => ({ get: () => app }))); + t.mock.method(AppModel, 'findAll', async () => + clone(apps).map((app) => ({ get: () => app })), + ); t.mock.method(AppModel, 'update', async (values, { where }) => { - apps = apps.map((app) => matches(app, where) ? { ...app, ...clone(values) } : app); + apps = apps.map((app) => + matches(app, where) ? { ...app, ...clone(values) } : app, + ); return [1]; }); t.mock.method(AppModel, 'destroy', async ({ where }) => { apps = apps.filter((app) => !matches(app, where)); }); t.mock.method(AppModel, 'create', async (values) => { - const app = { id: Math.max(0, ...apps.map((app) => app.id)) + 1, tokens: [], ...values }; + const app = { + id: Math.max(0, ...apps.map((app) => app.id)) + 1, + tokens: [], + ...values, + }; apps.push(app); return { get: () => clone(app) }; }); - t.mock.method(shareStore, 'updateApps', async (values) => { cached = clone(values); }); + t.mock.method(shareStore, 'updateApps', async (values) => { + cached = clone(values); + }); t.mock.method(shareStore, 'getApps', async () => clone(cached)); - return { service: new OpenService({}), apps: () => clone(apps), cached: () => clone(cached) }; + return { + service: new OpenService({}), + apps: () => clone(apps), + cached: () => clone(cached), + }; } for (const operation of ['acquisition', 'startup refresh']) { @@ -332,8 +437,12 @@ for (const operation of ['acquisition', 'startup refresh']) { const state = appsFixture(t); let resume; let entered; - const paused = new Promise((resolve) => { entered = resolve; }); - const barrier = new Promise((resolve) => { resume = resolve; }); + const paused = new Promise((resolve) => { + entered = resolve; + }); + const barrier = new Promise((resolve) => { + resume = resolve; + }); const findAll = AppModel.findAll; let first = true; AppModel.findAll = async (...args) => { @@ -345,30 +454,48 @@ for (const operation of ['acquisition', 'startup refresh']) { } return snapshot; }; - const publication = operation === 'acquisition' - ? state.service.generateSystemToken() : state.service.refreshApps(); + const publication = + operation === 'acquisition' + ? state.service.generateSystemToken() + : state.service.refreshApps(); await paused; - const issuance = state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' }); + const issuance = state.service.authToken({ + client_id: 'external-client', + client_secret: 'external-secret', + }); await new Promise((resolve) => setTimeout(resolve, 150)); resume(); const [, response] = await Promise.all([publication, issuance]); assert.equal(response.code, 200); - assert.ok(state.apps()[1].tokens.some((token) => token.value === response.data.token)); + assert.ok( + state + .apps()[1] + .tokens.some((token) => token.value === response.data.token), + ); assert.deepEqual(state.cached(), state.apps()); }); } test('concurrent token API calls and scheduled generation preserve every issued token', async (t) => { const state = appsFixture(t); - const credentials = { client_id: 'system-client', client_secret: 'system-secret' }; + const credentials = { + client_id: 'system-client', + client_secret: 'system-secret', + }; const results = await Promise.all([ - state.service.authToken(credentials), state.service.generateSystemToken(true), - state.service.authToken(credentials), state.service.generateSystemToken(true), + state.service.authToken(credentials), + state.service.generateSystemToken(true), + state.service.authToken(credentials), + state.service.generateSystemToken(true), ]); const tokens = state.apps()[0].tokens; assert.equal(tokens.length, 5); for (const response of results) { - assert.ok(tokens.some((token) => token.value === (response.value || response.data.token))); + assert.ok( + tokens.some( + (token) => token.value === (response.value || response.data.token), + ), + ); } assert.deepEqual(state.cached(), state.apps()); }); @@ -376,17 +503,40 @@ test('concurrent token API calls and scheduled generation preserve every issued for (const mutation of ['resetSecret', 'remove', 'update', 'create']) { test(`concurrent cache refresh and ${mutation} retain the latest application state`, async (t) => { const state = appsFixture(t); - await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' }); - const change = () => mutation === 'resetSecret' ? state.service.resetSecret(2) - : mutation === 'remove' ? state.service.remove([2]) - : mutation === 'update' ? state.service.update({ id: 2, name: 'external', scopes: ['dashboard'] }) - : state.service.create({ name: 'created', scopes: ['crons'] }); - await Promise.all([state.service.refreshApps(), change(), state.service.generateSystemToken()]); + await state.service.authToken({ + client_id: 'external-client', + client_secret: 'external-secret', + }); + const change = () => + mutation === 'resetSecret' + ? state.service.resetSecret(2) + : mutation === 'remove' + ? state.service.remove([2]) + : mutation === 'update' + ? state.service.update({ + id: 2, + name: 'external', + scopes: ['dashboard'], + }) + : state.service.create({ name: 'created', scopes: ['crons'] }); + await Promise.all([ + state.service.refreshApps(), + change(), + state.service.generateSystemToken(), + ]); assert.deepEqual(state.cached(), state.apps()); if (mutation === 'resetSecret') { assert.equal(state.cached()[1].tokens.length, 0); assert.notEqual(state.cached()[1].client_secret, 'external-secret'); - assert.equal((await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' })).code, 400); + assert.equal( + ( + await state.service.authToken({ + client_id: 'external-client', + client_secret: 'external-secret', + }) + ).code, + 400, + ); } else if (mutation === 'remove') { assert.equal(state.cached().length, 1); } else if (mutation === 'update') { @@ -416,7 +566,10 @@ test('application mutations cannot change or expose the built-in system app', as test('system initialization preserves active tokens while migrating dashboard scope', async (t) => { const state = appsFixture(t); await AppModel.update({ scopes: ['crons', 'system'] }, { where: { id: 1 } }); - await Promise.all([state.service.initializeSystemApp(), state.service.generateSystemToken(true)]); + await Promise.all([ + state.service.initializeSystemApp(), + state.service.generateSystemToken(true), + ]); assert.deepEqual(state.cached(), state.apps()); assert.deepEqual(state.apps()[0].scopes, ['crons', 'system', 'dashboard']); assert.equal(state.apps()[0].tokens.length, 2); @@ -424,13 +577,19 @@ test('system initialization preserves active tokens while migrating dashboard sc test('failed atomic token-file publication releases the application lock for recovery', async (t) => { const state = appsFixture(t); - const temporary = path.join(config.configPath, `token.json.${process.pid}.tmp`); + const temporary = path.join( + config.configPath, + `token.json.${process.pid}.tmp`, + ); fs.mkdirSync(temporary); await assert.rejects(state.service.generateSystemToken(), /EISDIR/); fs.rmSync(temporary, { recursive: true }); const token = await state.service.generateSystemToken(); assert.equal(token.value, 'system-token'); - assert.equal(fs.existsSync(path.join(config.configPath, '.apps-state.lock')), false); + assert.equal( + fs.existsSync(path.join(config.configPath, '.apps-state.lock')), + false, + ); }); test('real SQLite and authentication cache retain concurrent process updates', async (t) => { @@ -438,10 +597,15 @@ test('real SQLite and authentication cache retain concurrent process updates', a await AppModel.sync({ force: true }); const service = new OpenService({}); await service.initializeSystemApp(); - const external = await service.create({ name: 'sqlite-external', scopes: ['crons'] }); + const external = await service.create({ + name: 'sqlite-external', + scopes: ['crons'], + }); const worker = path.join(environment, 'sqlite-worker.cjs'); const root = path.resolve(__dirname, '../..'); - fs.writeFileSync(worker, ` + fs.writeFileSync( + worker, + ` require(${JSON.stringify(require.resolve('reflect-metadata'))}); const path = require('node:path'); const root = process.cwd(); @@ -458,12 +622,33 @@ test('real SQLite and authentication cache retain concurrent process updates', a console.log(JSON.stringify(result || {})); })().catch(error => { console.error(error); process.exitCode = 1; }) .finally(async () => { await keyvStore.disconnect(); await sequelize.close(); }); - `); - const actions = ['renew', 'acquire', 'auth', 'refresh', 'renew', 'auth', 'auth']; - const outcomes = await Promise.allSettled(actions.map((action) => execute(process.execPath, [ - '-r', require.resolve('ts-node/register/transpile-only'), worker, action, - external.client_id, external.client_secret, - ], { cwd: root, timeout: 20_000, env: process.env }))); + `, + ); + const actions = [ + 'renew', + 'acquire', + 'auth', + 'refresh', + 'renew', + 'auth', + 'auth', + ]; + const outcomes = await Promise.allSettled( + actions.map((action) => + execute( + process.execPath, + [ + '-r', + require.resolve('ts-node/register/transpile-only'), + worker, + action, + external.client_id, + external.client_secret, + ], + { cwd: root, timeout: 20_000, env: process.env }, + ), + ), + ); const results = outcomes.map((outcome) => { assert.equal(outcome.status, 'fulfilled', outcome.reason?.stderr); return outcome.value; @@ -475,14 +660,27 @@ test('real SQLite and authentication cache retain concurrent process updates', a assert.equal(results[index].stderr, ''); const result = JSON.parse(results[index].stdout.trim()); const value = result.value || result.data?.token; - if (value) assert.ok(cached.some((app) => app.tokens?.some((token) => token.value === value))); + if (value) + assert.ok( + cached.some((app) => + app.tokens?.some((token) => token.value === value), + ), + ); } - assert.equal(database.find((app) => app.name === 'sqlite-external').tokens.length, 3); - const file = JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8')); - assert.ok(cached.find((app) => app.name === 'system').tokens.some((token) => token.value === file.value)); + assert.equal( + database.find((app) => app.name === 'sqlite-external').tokens.length, + 3, + ); + const file = JSON.parse( + fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8'), + ); + assert.ok( + cached + .find((app) => app.name === 'system') + .tokens.some((token) => token.value === file.value), + ); }); - test('atomic publication preserves restricted token-file permissions', async (t) => { const state = fixture(t, [{ value: 'current', expiration: START + DAY }]); const file = path.join(config.configPath, 'token.json'); @@ -493,7 +691,6 @@ test('atomic publication preserves restricted token-file permissions', async (t) assert.equal(fs.statSync(file).mode & 0o777, 0o640); }); - test('a SIGKILLed generator leaves a lock that the next acquisition recovers', async (t) => { const state = await processFixture(t); const running = state.run(false, false, true); @@ -505,9 +702,15 @@ test('a SIGKILLed generator leaves a lock that the next acquisition recovers', a } running.child.kill('SIGKILL'); assert.equal((await stopped).signal, 'SIGKILL'); - assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), true); + assert.equal( + fs.existsSync(path.join(state.directory, '.apps-state.lock')), + true, + ); const recovered = await state.run(); assert.equal(recovered.stderr, ''); assert.equal(recovered.stdout.trim(), state.cached().value); - assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), false); + assert.equal( + fs.existsSync(path.join(state.directory, '.apps-state.lock')), + false, + ); }); diff --git a/test/back/task-shell-lifecycle.test.cjs b/test/back/task-shell-lifecycle.test.cjs index dc2c9cf6..330dbbab 100644 --- a/test/back/task-shell-lifecycle.test.cjs +++ b/test/back/task-shell-lifecycle.test.cjs @@ -13,8 +13,17 @@ function extract(file, name) { } const helpers = [ fs.readFileSync('shell/task-timeout.sh', 'utf8'), - ...['handle_task_start', 'handle_task_end', 'run_task_before', 'run_task_after', 'get_env_array', 'clear_env'].map(n => extract('shell/share.sh', n)), - ...['run_shell_script', 'define_program', 'format_params'].map(n => extract('shell/task.sh', n)), + ...[ + 'handle_task_start', + 'handle_task_end', + 'run_task_before', + 'run_task_after', + 'get_env_array', + 'clear_env', + ].map((n) => extract('shell/share.sh', n)), + ...['run_shell_script', 'define_program', 'format_params'].map((n) => + extract('shell/task.sh', n), + ), ].join('\n'); const taskSource = path.resolve('shell/otask.sh'); @@ -23,10 +32,21 @@ function fixture(t) { t.after(() => fs.rmSync(root, { recursive: true, force: true })); const write = (name, body) => fs.writeFileSync(path.join(root, name), body); write('env.sh', 'export QA_PANEL="alpha&beta&gamma"\n'); - write('before.sh', 'export QA_BEFORE=ready\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n'); - write('after.sh', 'printf "AFTER:%s:%s\\n" "$QA_PANEL" "$QA_BEFORE" >> "$QA_ROOT/events"\n'); + write( + 'before.sh', + 'export QA_BEFORE=ready\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n', + ); + write( + 'after.sh', + 'printf "AFTER:%s:%s\\n" "$QA_PANEL" "$QA_BEFORE" >> "$QA_ROOT/events"\n', + ); const run = (args, timeout = '') => { - const r = spawnSync('/bin/bash', ['-c', helpers + ` + const r = spawnSync( + '/bin/bash', + [ + '-c', + helpers + + ` dir_scripts=$QA_ROOT; dir_shell=$QA_ROOT; dir_dep=$QA_ROOT file_env=$QA_ROOT/env.sh; file_task_before=$QA_ROOT/before.sh; file_task_after=$QA_ROOT/after.sh ID=42; log_path=fixture.log; is_macos=0 @@ -41,32 +61,76 @@ function fixture(t) { format_params "$@"; define_program "${'${task_shell_params[@]}'}" . "$QA_TASK_SOURCE" printf 'WRAPPER_FINISHED\\n' >> "$QA_ROOT/events" - `, 'fixture', ...args], { cwd: root, env: { ...process.env, command_timeout_time: timeout, QA_ROOT: root, QA_TASK_SOURCE: taskSource }, encoding: 'utf8', timeout: 10000 }); + `, + 'fixture', + ...args, + ], + { + cwd: root, + env: { + ...process.env, + command_timeout_time: timeout, + QA_ROOT: root, + QA_TASK_SOURCE: taskSource, + }, + encoding: 'utf8', + timeout: 10000, + }, + ); assert.equal(r.status, 0, r.stdout + r.stderr); - return { stdout: r.stdout, events: fs.readFileSync(path.join(root, 'events'), 'utf8').trim().split('\n') }; + return { + stdout: r.stdout, + events: fs + .readFileSync(path.join(root, 'events'), 'utf8') + .trim() + .split('\n'), + }; }; return { write, run }; } -test('managed task propagates the sourced script status through direct output, redirection and tee', t => { +test('managed task propagates the sourced script status through direct output, redirection and tee', (t) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-wrapper-status-')); t.after(() => fs.rmSync(root, { recursive: true, force: true })); const shellDir = path.join(root, 'shell'); fs.mkdirSync(shellDir); // Exercise the real outer wrapper with deterministic paths and a failing payload. - fs.writeFileSync(path.join(shellDir, 'share.sh'), [ - 'is_macos=0; no_delay=true; dir_log=$QL_DIR; log_name=logs', - 'import_config() { :; }', 'make_dir() { mkdir -p "$1"; }', - 'format_timestamp() { echo 1; }', 'format_time() { echo now; }', - ].join('\n')); + fs.writeFileSync( + path.join(shellDir, 'share.sh'), + [ + 'is_macos=0; no_delay=true; dir_log=$QL_DIR; log_name=logs', + 'import_config() { :; }', + 'make_dir() { mkdir -p "$1"; }', + 'format_timestamp() { echo 1; }', + 'format_time() { echo now; }', + ].join('\n'), + ); fs.writeFileSync(path.join(shellDir, 'api.sh'), ''); fs.writeFileSync(path.join(shellDir, 'task-timeout.sh'), ''); - fs.writeFileSync(path.join(shellDir, 'otask.sh'), 'echo payload; return 17\n'); - for (const [direct, noTee] of [[true,false], [false,true], [false,false]]) { - const run = spawnSync('/bin/bash', [path.resolve('shell/task.sh'), 'probe.sh'], { - env: { ...process.env, QL_DIR: root, ID: '42', QL_TRIGGER_ID: 'shell-probe', - real_time: String(direct), no_tee: String(noTee) }, encoding: 'utf8', - }); + fs.writeFileSync( + path.join(shellDir, 'otask.sh'), + 'echo payload; return 17\n', + ); + for (const [direct, noTee] of [ + [true, false], + [false, true], + [false, false], + ]) { + const run = spawnSync( + '/bin/bash', + [path.resolve('shell/task.sh'), 'probe.sh'], + { + env: { + ...process.env, + QL_DIR: root, + ID: '42', + QL_TRIGGER_ID: 'shell-probe', + real_time: String(direct), + no_tee: String(noTee), + }, + encoding: 'utf8', + }, + ); assert.equal(run.status, 17, run.stderr); if (noTee) assert.equal(run.stdout, ''); else assert.match(run.stdout, /payload/); @@ -81,20 +145,33 @@ for (const [label, body, code] of [ ['errexit failure', 'set -e\nfalse\necho SHOULD_NOT_RUN', 1], ['script EXIT trap', `trap 'echo SCRIPT_EXIT_TRAP' EXIT\nexit 4`, 4], ]) { - test(`sourced shell ${label} still runs after hook and reports exactly one completion`, t => { + test(`sourced shell ${label} still runs after hook and reports exactly one completion`, (t) => { const f = fixture(t); - f.write('probe.sh', `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready ]] || exit 99\nqa_function\n${body}\n`); + f.write( + 'probe.sh', + `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready ]] || exit 99\nqa_function\n${body}\n`, + ); const r = f.run(['probe.sh']); assert.match(r.stdout, /HOOK_FUNCTION/); assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/); - if (label === 'script EXIT trap') assert.match(r.stdout, /SCRIPT_EXIT_TRAP/); - assert.deepEqual(r.events, ['STATUS:0:', 'AFTER:alpha&beta&gamma:ready', `STATUS:1:${code}`, `STAT:${code}`, 'WRAPPER_FINISHED']); + if (label === 'script EXIT trap') + assert.match(r.stdout, /SCRIPT_EXIT_TRAP/); + assert.deepEqual(r.events, [ + 'STATUS:0:', + 'AFTER:alpha&beta&gamma:ready', + `STATUS:1:${code}`, + `STAT:${code}`, + 'WRAPPER_FINISHED', + ]); }); } -test('shell arguments and before-hook functions survive isolation while script state stays in the child', t => { +test('shell arguments and before-hook functions survive isolation while script state stays in the child', (t) => { const f = fixture(t); - f.write('probe.sh', '[[ "$1" == "arg with spaces" ]] || exit 99\nqa_function\nexport QA_BEFORE=changed\ncd /\nexit 5\n'); + f.write( + 'probe.sh', + '[[ "$1" == "arg with spaces" ]] || exit 99\nqa_function\nexport QA_BEFORE=changed\ncd /\nexit 5\n', + ); const r = f.run(['probe.sh', '--', 'arg with spaces']); assert.match(r.stdout, /HOOK_FUNCTION/); assert.ok(r.events.includes('AFTER:alpha&beta&gamma:ready')); @@ -105,42 +182,60 @@ for (const [label, args] of [ ['explicit shell interpreter', ['bash', 'probe.sh', 'argument']], ['shell script with positional args', ['probe.sh', 'argument']], ]) { - test(`${label} preserves generated environment and reports failure`, t => { + test(`${label} preserves generated environment and reports failure`, (t) => { const f = fixture(t); - f.write('probe.sh', '[[ "$QA_PANEL" == "alpha&beta&gamma" && "$QA_BEFORE" == ready && "$1" == argument ]] || exit 99\nexit 6\n'); + f.write( + 'probe.sh', + '[[ "$QA_PANEL" == "alpha&beta&gamma" && "$QA_BEFORE" == ready && "$1" == argument ]] || exit 99\nexit 6\n', + ); const r = f.run(args); assert.ok(r.events.includes('STATUS:1:6')); - assert.equal(r.events.filter(x => x.startsWith('STATUS:1:')).length, 1); + assert.equal(r.events.filter((x) => x.startsWith('STATUS:1:')).length, 1); }); } -test('explicit Python interpreter receives panel and before-hook environment', t => { +test('explicit Python interpreter receives panel and before-hook environment', (t) => { const f = fixture(t); - f.write('probe.py', 'import os,sys\nassert os.environ["QA_PANEL"] == "alpha&beta&gamma"\nassert os.environ["QA_BEFORE"] == "ready"\nassert sys.argv[1] == "argument"\nsys.exit(8)\n'); - assert.ok(f.run(['python3', 'probe.py', 'argument']).events.includes('STATUS:1:8')); + f.write( + 'probe.py', + 'import os,sys\nassert os.environ["QA_PANEL"] == "alpha&beta&gamma"\nassert os.environ["QA_BEFORE"] == "ready"\nassert sys.argv[1] == "argument"\nsys.exit(8)\n', + ); + assert.ok( + f.run(['python3', 'probe.py', 'argument']).events.includes('STATUS:1:8'), + ); }); -test('explicit Node interpreter retains generated environment', t => { +test('explicit Node interpreter retains generated environment', (t) => { const f = fixture(t); - f.write('probe.cjs', 'if (process.env.QA_PANEL !== "alpha&beta&gamma" || process.env.QA_BEFORE !== "ready") process.exit(99); process.exit(8);\n'); + f.write( + 'probe.cjs', + 'if (process.env.QA_PANEL !== "alpha&beta&gamma" || process.env.QA_BEFORE !== "ready") process.exit(99); process.exit(8);\n', + ); assert.ok(f.run(['node', 'probe.cjs']).events.includes('STATUS:1:8')); }); -test('plain commands retain generated environment', t => { +test('plain commands retain generated environment', (t) => { const f = fixture(t); assert.match(f.run(['printenv', 'QA_PANEL']).stdout, /alpha&beta&gamma/); }); for (const mode of ['desi', 'conc']) { - test(`shell ${mode} keeps selected account values and completion reporting`, t => { + test(`shell ${mode} keeps selected account values and completion reporting`, (t) => { const f = fixture(t); f.write('probe.sh', 'printf "ACCOUNT=%s\\n" "$QA_PANEL"\nexit 0\n'); const r = f.run(['probe.sh', mode, 'QA_PANEL', '2-3']); - assert.match(r.stdout, mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/); + assert.match( + r.stdout, + mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/, + ); assert.doesNotMatch(r.stdout, /ACCOUNT=alpha/); - assert.ok(r.events.includes(`AFTER:${mode === 'desi' ? 'beta&gamma' : 'gamma'}:ready`)); - assert.equal(r.events.filter(x => x === 'STATUS:1:0').length, 1); - assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1); + assert.ok( + r.events.includes( + `AFTER:${mode === 'desi' ? 'beta&gamma' : 'gamma'}:ready`, + ), + ); + assert.equal(r.events.filter((x) => x === 'STATUS:1:0').length, 1); + assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1); }); } @@ -148,20 +243,36 @@ for (const [label, args] of [ ['sourced shell', ['probe.sh', '--', 'space value']], ['explicit bash', ['bash', 'probe.sh', 'space value']], ]) { - test(`${label} timeout stops descendants and finalizes once with 124`, t => { + test(`${label} timeout stops descendants and finalizes once with 124`, (t) => { const f = fixture(t); - f.write('before.sh', 'export QA_BEFORE=ready\nprivate_value=private\nprivate_array=(one "two words")\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n'); - f.write('probe.sh', `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready && "$1" == 'space value' ]] || exit 91\n${label === 'sourced shell' ? '[[ "$private_value" = private && "${private_array[1]}" = "two words" ]] || exit 92\nqa_function\n' : ''}trap 'echo EXIT_TRAP' EXIT\nsleep 3\necho SHOULD_NOT_RUN\n`); + f.write( + 'before.sh', + 'export QA_BEFORE=ready\nprivate_value=private\nprivate_array=(one "two words")\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n', + ); + f.write( + 'probe.sh', + `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready && "$1" == 'space value' ]] || exit 91\n${ + label === 'sourced shell' + ? '[[ "$private_value" = private && "${private_array[1]}" = "two words" ]] || exit 92\nqa_function\n' + : '' + }trap 'echo EXIT_TRAP' EXIT\nsleep 3\necho SHOULD_NOT_RUN\n`, + ); const before = Date.now(); const r = f.run(args, '0.2s'); assert.ok(Date.now() - before < 2500, r.stdout); assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/); assert.match(r.stdout, /EXIT_TRAP/); - assert.deepEqual(r.events, ['STATUS:0:', 'AFTER:alpha&beta&gamma:ready', 'STATUS:1:124', 'STAT:124', 'WRAPPER_FINISHED']); + assert.deepEqual(r.events, [ + 'STATUS:0:', + 'AFTER:alpha&beta&gamma:ready', + 'STATUS:1:124', + 'STAT:124', + 'WRAPPER_FINISHED', + ]); }); } -test('timeout escalates when a shell and its children ignore TERM', t => { +test('timeout escalates when a shell and its children ignore TERM', (t) => { const f = fixture(t); f.write('probe.sh', 'trap "" TERM\nsleep 3\necho SHOULD_NOT_RUN\n'); const before = Date.now(); @@ -171,7 +282,7 @@ test('timeout escalates when a shell and its children ignore TERM', t => { assert.ok(r.events.includes('STATUS:1:124')); }); -test('completed timed tasks keep their exit code and do not wait for the timer', t => { +test('completed timed tasks keep their exit code and do not wait for the timer', (t) => { const f = fixture(t); f.write('probe.sh', 'exit 7\n'); const before = Date.now(); @@ -180,7 +291,7 @@ test('completed timed tasks keep their exit code and do not wait for the timer', assert.ok(r.events.includes('STATUS:1:7')); }); -test('zero disables the deadline and invalid durations never start the script', t => { +test('zero disables the deadline and invalid durations never start the script', (t) => { const f = fixture(t); f.write('probe.sh', 'echo DID_RUN\n'); assert.match(f.run(['probe.sh'], '0s').stdout, /DID_RUN/); @@ -191,28 +302,42 @@ test('zero disables the deadline and invalid durations never start the script', }); for (const [runtime, filename, body] of [ - ['python3', 'timed.py', 'import time\nprint("STARTED", flush=True)\ntime.sleep(3)\nprint("SHOULD_NOT_RUN", flush=True)\n'], - ['node', 'timed.cjs', 'console.log("STARTED"); setTimeout(() => console.log("SHOULD_NOT_RUN"), 3000);\n'], + [ + 'python3', + 'timed.py', + 'import time\nprint("STARTED", flush=True)\ntime.sleep(3)\nprint("SHOULD_NOT_RUN", flush=True)\n', + ], + [ + 'node', + 'timed.cjs', + 'console.log("STARTED"); setTimeout(() => console.log("SHOULD_NOT_RUN"), 3000);\n', + ], ]) { - test(`${runtime} timeout stops execution and reports 124`, t => { + test(`${runtime} timeout stops execution and reports 124`, (t) => { const f = fixture(t); f.write(filename, body); const r = f.run([runtime, filename], '0.5s'); assert.match(r.stdout, /STARTED/); assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/); assert.ok(r.events.includes('STATUS:1:124')); - assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1); + assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1); }); } for (const mode of ['desi', 'conc']) { - test(`timed shell ${mode} preserves selected accounts and terminates every worker`, t => { + test(`timed shell ${mode} preserves selected accounts and terminates every worker`, (t) => { const f = fixture(t); - f.write('probe.sh', 'echo "ACCOUNT=$QA_PANEL"\nsleep 3\necho SHOULD_NOT_RUN\n'); + f.write( + 'probe.sh', + 'echo "ACCOUNT=$QA_PANEL"\nsleep 3\necho SHOULD_NOT_RUN\n', + ); const r = f.run(['probe.sh', mode, 'QA_PANEL', '2-3'], '0.2s'); - assert.match(r.stdout, mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/); + assert.match( + r.stdout, + mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/, + ); assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/); - assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1); + assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1); // Concurrent mode retains its existing aggregate wait status behavior. assert.ok(r.events.includes(`STATUS:1:${mode === 'desi' ? 124 : 0}`)); }); diff --git a/test/back/task-time.test.cjs b/test/back/task-time.test.cjs index dbe018ff..dc3db31c 100644 --- a/test/back/task-time.test.cjs +++ b/test/back/task-time.test.cjs @@ -115,12 +115,15 @@ handle_task_end ); }); -test('scheduled tasks starting in the same millisecond write different files', t => { - run(t, `log_name=common +test('scheduled tasks starting in the same millisecond write different files', (t) => { + run( + t, + `log_name=common QL_TRIGGER_ID=first; handle_log_path same.py first=$log_path QL_TRIGGER_ID=second; handle_log_path same.py [[ "$first" != "$log_path" ]] QL_TRIGGER_ID=../invalid; handle_log_path same.py -[[ "$log_path" == common/2026-09-12-23-59-59-999.log ]]`); +[[ "$log_path" == common/2026-09-12-23-59-59-999.log ]]`, + ); }); diff --git a/test/back/trigger-lifecycle.test.cjs b/test/back/trigger-lifecycle.test.cjs new file mode 100644 index 00000000..840cb894 --- /dev/null +++ b/test/back/trigger-lifecycle.test.cjs @@ -0,0 +1,187 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { Sequelize, QueryTypes } = require('sequelize'); +const load = require('../helpers/load-security-module.cjs'); +const { installTriggerHistory } = require('../../back/cron/history'); +const { + TriggerLifecycle, +} = require('../../back/cron/execution/triggerLifecycle'); + +async function fixture(t) { + const db = new Sequelize({ + dialect: 'sqlite', + storage: ':memory:', + logging: false, + }); + t.after(() => db.close()); + const tasks = load('back/data/cron.ts', { './index': { sequelize: db } }); + const instances = load('back/data/runningInstance.ts', { + './index': { sequelize: db }, + }); + load('back/data/cronStats.ts', { './index': { sequelize: db } }); + await db.sync(); + await db.transaction((tx) => installTriggerHistory(db, tx)); + await tasks.CrontabModel.create({ id: 1, command: 'true', status: 1 }); + const unexpected = async () => + assert.fail('unexpected exit evidence operation'); + const evidence = { + exitBeforeStop: unexpected, + completeCommandExit: unexpected, + recoverScriptSample: unexpected, + // This fixture has no receipts to replay, but recovery must pass its transaction. + replayPublishedExits: async (tx) => assert.ok(tx && !tx.finished), + }; + const lifecycle = new TriggerLifecycle(db, evidence); + const rows = () => + db.query('SELECT * FROM CronTriggers ORDER BY id', { + type: QueryTypes.SELECT, + }); + return { db, lifecycle, evidence, rows, instances }; +} + +test('lifecycle admission, start and terminal writes roll back with the caller transaction', async (t) => { + const { db, lifecycle, rows } = await fixture(t); + await assert.rejects( + db.transaction(async (tx) => { + assert.equal( + await lifecycle.enqueue('rolled-back', 1, 'manual', null, 100, tx), + true, + ); + assert.equal(await lifecycle.start('rolled-back', 200, false, tx), true); + await lifecycle.finish('rolled-back', 'failed', 'spawn', 1, tx, 300); + throw Error('caller rollback'); + }), + /caller rollback/, + ); + assert.deepEqual(await rows(), []); + + await lifecycle.enqueue('queued', 1, 'manual', null, 100); + await lifecycle.enqueue('claimed', 1, 'manual', null, 100); + await lifecycle.start('claimed', 200); + await assert.rejects( + db.transaction(async (tx) => { + assert.deepEqual(await lifecycle.cancelQueuedInTransaction([1], tx), [ + 'queued', + ]); + await lifecycle.queueInstanceStop(10, 1, 12345, tx); + throw Error('stop snapshot rollback'); + }), + /stop snapshot rollback/, + ); + assert.deepEqual( + (await rows()).map((row) => [row.id, row.state, row.stop_requested]), + [ + ['claimed', 'running', null], + ['queued', 'queued', null], + ], + ); + assert.deepEqual(await lifecycle.pendingStops(), []); +}); + +test('restart recovery requeues only unstarted slots and leaves unknown and terminal results deduplicated', async (t) => { + const { lifecycle, rows } = await fixture(t); + assert.equal(await lifecycle.enqueue('uncertain', 1, 'node', 100, 100), true); + assert.equal( + await lifecycle.enqueue('uncertain', 1, 'node', 100, 100), + false, + ); + assert.equal(await lifecycle.start('uncertain', 200), true); + await lifecycle.enqueue('unstarted', 1, 'node', 100, 100); + await lifecycle.interrupt(process.env.SERVICE_TYPE || 'http'); + assert.deepEqual( + (await rows()).map((row) => [row.id, row.state, row.reason, row.exit_code]), + [ + ['uncertain', 'unknown', 'restart', null], + ['unstarted', 'skipped', 'restart', null], + ], + ); + assert.equal( + await lifecycle.enqueue('uncertain', 1, 'recovery', 100, 300), + false, + ); + assert.equal(await lifecycle.start('uncertain', 300), false); + assert.equal( + await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 300), + true, + ); + assert.equal( + await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 300), + false, + ); + assert.equal(await lifecycle.start('unstarted', 400), true); + await lifecycle.finish('unstarted', 'finished', null, 0, undefined, 500); + assert.equal( + await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 600), + false, + ); + await lifecycle.finish( + 'unstarted', + 'failed', + 'late retry', + 1, + undefined, + 700, + ); + const results = await rows(); + assert.deepEqual( + results.map((row) => [row.id, row.state, row.exit_code]), + [ + ['uncertain', 'unknown', null], + ['unstarted', 'finished', 0], + ], + ); + assert.equal(results[1].finished_at, 500); +}); + +test('failed exit settlement preserves the durable stop snapshot and rolls back state before any signal', async (t) => { + const { db, lifecycle, evidence, rows, instances } = await fixture(t); + await lifecycle.enqueue('run', 1, 'manual', null, 100); + await lifecycle.start('run', 200); + const instance = await instances.RunningInstanceModel.create({ + cron_id: 1, + pid: 12345, + status: 0, + started_at: 1, + }); + await db.query('UPDATE CronTriggers SET instance_id=$instance WHERE id=$id', { + bind: { instance: instance.id, id: 'run' }, + }); + evidence.exitBeforeStop = async () => ({ + canonical: { + version: 1, + code: 0, + signal: null, + time: 300, + file: '/fixture/receipt', + }, + recovered: [], + published: true, + unreadable: false, + }); + let attempts = 0; + evidence.completeCommandExit = async (id, state, reason, code, tx) => { + attempts++; + assert.equal(state, 'unknown'); + assert.ok(tx && !tx.finished); + await lifecycle.finish(id, 'finished', null, 0, tx, 300); + throw Error('ledger unavailable'); + }; + const targets = ['crond:12345:fixture-birth']; + await assert.rejects( + lifecycle.requestInstanceStop( + instance.id, + 12345, + () => assert.fail('must not signal before evidence is settled'), + targets, + ), + /ledger unavailable/, + ); + assert.equal(attempts, 1); + const [row] = await rows(); + assert.equal(row.state, 'running'); + assert.equal(row.exit_code, null); + assert.equal(row.stop_requested, null); + const pending = await lifecycle.pendingStop(instance.id); + assert.equal(pending.signalled, 0); + assert.deepEqual(JSON.parse(pending.targets), targets); +}); diff --git a/test/back/trigger-queries.test.cjs b/test/back/trigger-queries.test.cjs new file mode 100644 index 00000000..17e87479 --- /dev/null +++ b/test/back/trigger-queries.test.cjs @@ -0,0 +1,86 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { Sequelize, QueryTypes } = require('sequelize'); +const load = require('../helpers/load-security-module.cjs'); +const { TriggerQueries } = require('../../back/cron/queries/triggerQueries'); +const { + TriggerHistory, + installTriggerHistory, +} = require('../../back/cron/history'); + +test('history queries work on a read-only database without resolving uncertain exits', async (t) => { + // The in-memory database shares one connection, including audit snapshots, + // so query_only prevents writes throughout the complete read path. + const db = new Sequelize({ + dialect: 'sqlite', + storage: ':memory:', + logging: false, + }); + t.after(() => db.close()); + load('back/data/cron.ts', { './index': { sequelize: db } }); + load('back/data/runningInstance.ts', { './index': { sequelize: db } }); + load('back/data/cronStats.ts', { './index': { sequelize: db } }); + await db.sync(); + await db.transaction((tx) => installTriggerHistory(db, tx)); + await db.query(`INSERT INTO CronTriggers + (id,cron_id,source,state,reason,exit_code,finished_at,exit_pending,observed_at) + VALUES ('a-restart',1,'manual','unknown','restart',0,200,0,100), + ('b-pending',1,'legacy','unknown','restart',0,200,1,100), + ('c-conflict',1,'legacy','unknown','restart',0,200,1,100), + ('d-finished',1,'manual','finished',NULL,0,200,0,100), + ('other-task',2,'manual','finished',NULL,0,200,0,100)`); + await db.query(`INSERT INTO CronExitObservations VALUES + ('c-conflict','0',200), ('c-conflict','1',200)`); + const storedRows = () => + db.query('SELECT * FROM CronTriggers ORDER BY id', { + type: QueryTypes.SELECT, + }); + const before = await storedRows(); + await db.query('PRAGMA query_only=ON'); + await assert.rejects( + db.query("UPDATE CronTriggers SET state='finished'"), + /readonly/i, + ); + + const queries = new TriggerQueries(db); + const compatibility = new TriggerHistory(db); + const ids = before.map((row) => row.id); + const selected = await queries.visibleTriggers(1, ids); + assert.deepEqual( + selected.map((row) => [ + row.id, + row.state, + row.reason, + row.exit_code, + row.finished_at, + ]), + [ + ['a-restart', 'unknown', 'restart', null, null], + ['b-pending', 'unknown', 'exit_pending', null, null], + ['c-conflict', 'unknown', 'exit_conflict', null, null], + ['d-finished', 'finished', null, 0, 200], + ], + ); + assert.deepEqual(await compatibility.visibleTriggers(1, ids), selected); + + const first = await queries.recent(1, 0, 2); + assert.deepEqual( + first.map((row) => row.id), + ['d-finished', 'c-conflict'], + ); + const cursor = { time: first[1].observed_at, id: first[1].id }; + const older = await queries.recent(1, 0, 2, cursor); + assert.deepEqual( + older.map((row) => row.id), + ['b-pending', 'a-restart'], + ); + assert.deepEqual(await queries.recent(1, 2, 2), older); + assert.deepEqual(await compatibility.recent(1, 0, 2, cursor), older); + + const metrics = await queries.metrics(0); + assert.equal(metrics.observed, 5); + assert.equal(metrics.planned, 0); + assert.equal(metrics.waitP95, null); + assert.deepEqual(await compatibility.metrics(0), metrics); + assert.deepEqual(await storedRows(), before); +}); diff --git a/test/back/trigger-settlement.test.cjs b/test/back/trigger-settlement.test.cjs new file mode 100644 index 00000000..3819b48a --- /dev/null +++ b/test/back/trigger-settlement.test.cjs @@ -0,0 +1,275 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { QueryTypes } = require('sequelize'); +const load = require('../helpers/load-security-module.cjs'); +const { installTriggerHistory } = require('../../back/cron/history'); +const { + TriggerLifecycle, +} = require('../../back/cron/execution/triggerLifecycle'); +const { + TriggerSettlement, +} = require('../../back/cron/settlement/triggerSettlement'); +const { + readExit, + writeExit, + receiptPath, +} = require('../../back/cron/settlement/exitReceipt.cjs'); + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-settlement-')); + const db = load('back/data/index.ts', { + '../config/index': { dbPath: root }, + }).sequelize; + const models = load('back/data/cron.ts', { './index': { sequelize: db } }); + const instances = load('back/data/runningInstance.ts', { + './index': { sequelize: db }, + }); + load('back/data/cronStats.ts', { './index': { sequelize: db } }); + for (const key of ['QL_DIR', 'QL_DATA_DIR']) { + const previous = process.env[key]; + process.env[key] = root; + t.after(() => { + if (previous === undefined) delete process.env[key]; + else process.env[key] = previous; + }); + } + t.after(async () => { + await db.close(); + await fs.rm(root, { recursive: true, force: true }); + }); + await db.sync(); + await db.transaction((tx) => installTriggerHistory(db, tx)); + await models.CrontabModel.create({ + id: 1, + command: 'true', + status: 1, + allow_multiple_instances: 1, + }); + // Compose the two modules directly, without a TriggerHistory instance. + function components() { + let lifecycle; + const settlement = new TriggerSettlement(db, { + finish: (...args) => lifecycle.finish(...args), + shouldStop: (...args) => lifecycle.shouldStop(...args), + }); + lifecycle = new TriggerLifecycle(db, settlement); + return { lifecycle, settlement }; + } + const { lifecycle, settlement } = components(); + const start = new Date().setHours(0, 0, 0, 0) - 60_000; + async function seed(id) { + await lifecycle.enqueue(id, 1, 'manual', null, start); + assert.equal(await lifecycle.start(id, start, true), true); + assert.equal( + await lifecycle.bindCommand(id, process.pid, id + '.log'), + true, + ); + } + const rows = () => + db.query('SELECT * FROM CronTriggers ORDER BY id', { + type: QueryTypes.SELECT, + }); + const stats = () => + db.query( + 'SELECT run_count,success_count,fail_count,total_time,max_time FROM CrontabStats', + { type: QueryTypes.SELECT }, + ); + return { + db, + seed, + start, + lifecycle, + settlement, + components, + rows, + stats, + instances, + }; +} + +test('caller rollback preserves exit evidence, state and statistics; a fresh settlement books the replay once', async (t) => { + const { db, seed, start, settlement, components, rows, stats, instances } = + await fixture(t); + await seed('rollback'); + writeExit('rollback', 17, null, start + 1000); + await assert.rejects( + db.transaction(async (tx) => { + await settlement.completeCommandExit('rollback', 'finished', null, 0, tx); + const [row] = await db.query('SELECT counted FROM CronTriggers', { + transaction: tx, + type: QueryTypes.SELECT, + }); + assert.equal(row.counted, 1); + throw Error('caller rollback'); + }), + /caller rollback/, + ); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['running', null, 0]], + ); + assert.deepEqual(await stats(), []); + assert.equal((await instances.RunningInstanceModel.findOne()).status, 0); + assert.equal((await readExit('rollback')).code, 17); + + const restarted = components().settlement; + await db.transaction((tx) => restarted.replayPublishedExits(tx)); + writeExit('rollback', 17, null, start + 1000); + await restarted.retryPendingExits(); + await restarted.complete('rollback', 'finished', null, 0); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['failed', 17, 1]], + ); + assert.deepEqual(await stats(), [ + { + run_count: 1, + success_count: 0, + fail_count: 1, + total_time: 1000, + max_time: 1000, + }, + ]); + assert.equal((await instances.RunningInstanceModel.findOne()).status, 3); + assert.equal(await readExit('rollback'), undefined); +}); + +test('failed COMMIT keeps the receipt despite afterCommit hooks and allows exactly one later booking', async (t) => { + const { db, seed, start, settlement, rows, stats } = await fixture(t); + await seed('commit-failure'); + writeExit('commit-failure', 0, null, start + 2000); + await db.query('CREATE TABLE required_parent(id INTEGER PRIMARY KEY)'); + await db.query( + 'CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)', + ); + await db.query( + 'CREATE TRIGGER fail_settlement_commit AFTER INSERT ON CrontabStats BEGIN INSERT INTO deferred_child VALUES (1); END', + ); + await assert.rejects( + settlement.complete('commit-failure', 'failed', null, 1), + /constraint|foreign key/i, + ); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.counted]), + [['running', 0]], + ); + assert.deepEqual(await stats(), []); + assert.equal((await readExit('commit-failure')).code, 0); + await db.query('DROP TRIGGER fail_settlement_commit'); + await settlement.complete('commit-failure', 'unknown', 'restart', null); + await settlement.complete('commit-failure', 'unknown', 'restart', null); + assert.deepEqual(await stats(), [ + { + run_count: 1, + success_count: 1, + fail_count: 0, + total_time: 2000, + max_time: 2000, + }, + ]); + assert.equal(await readExit('commit-failure'), undefined); +}); + +for (const conflict of ['code', 'time']) { + test(`conflicting bound ${conflict} withdraws only its own booking and remains unknown through replay`, async (t) => { + const { seed, start, lifecycle, settlement, rows, stats, db } = + await fixture(t); + for (const [id, duration] of [ + ['disputed', 3000], + ['sibling', 1000], + ]) { + await seed(id); + writeExit(id, 0, null, start + duration); + await settlement.complete(id, 'finished', null, 0); + } + writeExit( + 'disputed', + conflict === 'code' ? 23 : 0, + null, + start + (conflict === 'time' ? 4000 : 3000), + ); + await settlement.retryPendingExits(); + await settlement.retryPendingExits(); + await settlement.recordShellResult('disputed', 1, 0, 3000, start + 3000); + assert.deepEqual( + (await rows()).map((r) => [r.id, r.state, r.exit_code, r.counted]), + [ + ['disputed', 'unknown', null, 0], + ['sibling', 'finished', 0, 1], + ], + ); + assert.deepEqual(await stats(), [ + { + run_count: 1, + success_count: 1, + fail_count: 0, + total_time: 1000, + max_time: 1000, + }, + ]); + assert.equal( + await lifecycle.enqueue('disputed', 1, 'recovery', null, start + 5000), + false, + ); + const conflicts = await db.query('SELECT * FROM CronBoundExitConflicts', { + type: QueryTypes.SELECT, + }); + assert.equal(conflicts.length, 2); + assert.ok( + await readExit('disputed'), + 'conflicting durable evidence must remain available', + ); + }); +} + +test('a damaged receipt stays unknown and uncounted until verified evidence repairs the result', async (t) => { + const { seed, start, lifecycle, settlement, rows, stats } = await fixture(t); + await seed('damaged'); + const file = receiptPath('damaged'); + await fs.mkdir(path.dirname(file), { recursive: true }); + await fs.writeFile(file, '{"version":1'); + await settlement.complete( + 'damaged', + 'finished', + null, + 0, + start + 1000, + 'legacy', + ); + await settlement.retryPendingExits(); + assert.deepEqual( + (await rows()).map((r) => [ + r.state, + r.exit_code, + r.counted, + r.exit_pending, + ]), + [['unknown', null, 0, 1]], + ); + assert.deepEqual(await stats(), []); + assert.equal( + await lifecycle.enqueue('damaged', 1, 'recovery', null, start + 2000), + false, + ); + assert.equal(await fs.readFile(file, 'utf8'), '{"version":1'); + await fs.unlink(file); + writeExit('damaged', 23, null, start + 1000); + await settlement.retryPendingExits(); + await settlement.retryPendingExits(); + assert.deepEqual( + (await rows()).map((r) => [r.state, r.exit_code, r.counted]), + [['failed', 23, 1]], + ); + assert.deepEqual(await stats(), [ + { + run_count: 1, + success_count: 0, + fail_count: 1, + total_time: 1000, + max_time: 1000, + }, + ]); +}); diff --git a/test/back/update-check.test.cjs b/test/back/update-check.test.cjs index ec03f6e0..813e4e6a 100644 --- a/test/back/update-check.test.cjs +++ b/test/back/update-check.test.cjs @@ -17,7 +17,7 @@ function service(request) { '../data/dependence': {}, '../data/notify': {}, '../data/system': {}, - '../shared/pLimit': {}, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../shared/i18n': { t: (key) => key }, './notify': class {}, diff --git a/test/back/upgrade-download-fallback.test.cjs b/test/back/upgrade-download-fallback.test.cjs index 8b94f328..acc0dff0 100644 --- a/test/back/upgrade-download-fallback.test.cjs +++ b/test/back/upgrade-download-fallback.test.cjs @@ -107,7 +107,10 @@ test('explicit CLI GitHub selection does not switch providers', async (t) => { }); test('checksum validation failure never retries from another mirror', async (t) => { const f = await fixture(t, () => false, 'gitee', true); - await assert.rejects(f.operation, /checksum mismatch|构建文件缺失、损坏或混入旧文件/); + await assert.rejects( + f.operation, + /checksum mismatch|构建文件缺失、损坏或混入旧文件/, + ); assert.equal(f.urls.length, 2); assert.deepEqual(fs.readdirSync(f.tmp), []); }); diff --git a/test/back/upgrade-guards.test.cjs b/test/back/upgrade-guards.test.cjs index 25579cfd..424a2dc7 100644 --- a/test/back/upgrade-guards.test.cjs +++ b/test/back/upgrade-guards.test.cjs @@ -88,7 +88,10 @@ for (const legacy of [true, false]) try { await entered; const contender = await Promise.race(attempts); - assert.match(contender.error?.message || '', /Another upgrade|已有更新或重载/); + assert.match( + contender.error?.message || '', + /Another upgrade|已有更新或重载/, + ); assert.equal(maximum, 1); assert.equal((await original.readdir(lock)).length, 1); } finally { @@ -235,7 +238,10 @@ test( res.once('close', () => clearInterval(timer)); }); const began = Date.now(); - await assert.rejects(waitForHealth({ QlPort: port }, 80), /health check|后端启动检查失败/); + await assert.rejects( + waitForHealth({ QlPort: port }, 80), + /health check|后端启动检查失败/, + ); assert.ok( Date.now() - began < 1000, 'deadline must not depend on socket inactivity', @@ -280,7 +286,10 @@ for (const streaming of [false, true]) test('unhealthy, malformed and oversized health responses fail within the deadline', async (t) => { for (const body of ['{}', '{', ' '.repeat(65537)]) { const port = await healthServer(t, (req, res) => res.end(body)); - await assert.rejects(waitForHealth({ QlPort: port }, 20), /health check|后端启动检查失败/); + await assert.rejects( + waitForHealth({ QlPort: port }, 20), + /health check|后端启动检查失败/, + ); } }); diff --git a/test/back/upgrade-prestart.test.cjs b/test/back/upgrade-prestart.test.cjs index 3b109fcd..4c3cca55 100644 --- a/test/back/upgrade-prestart.test.cjs +++ b/test/back/upgrade-prestart.test.cjs @@ -14,10 +14,17 @@ function checkGroupSignals(t) { const kill = t.mock.method(process, 'kill'); return () => { if (process.platform === 'win32') return; - const groups = kill.mock.calls.filter(call => call.arguments[0] < 0 && call.arguments[1] === 'SIGKILL') - .map(call => call.arguments[0]); + const groups = kill.mock.calls + .filter( + (call) => call.arguments[0] < 0 && call.arguments[1] === 'SIGKILL', + ) + .map((call) => call.arguments[0]); assert.ok(groups.length > 0); - assert.equal(new Set(groups).size, groups.length, 'a retired process group was signalled twice'); + assert.equal( + new Set(groups).size, + groups.length, + 'a retired process group was signalled twice', + ); }; } @@ -34,7 +41,10 @@ for (const [version, exitCode] of [ survivor = path.join(root, 'survivor'); await fs.mkdir(path.join(source, 'node_modules'), { recursive: true }); await fs.mkdir(path.join(statics, 'build/bootstrap'), { recursive: true }); - await fs.writeFile(path.join(source, 'version.yaml'), `version: ${version}`); + await fs.writeFile( + path.join(source, 'version.yaml'), + `version: ${version}`, + ); await fs.writeFile(path.join(statics, 'build/app.js'), 'backend'); await fs.writeFile( path.join(statics, 'build-info.json'), @@ -49,7 +59,9 @@ for (const [version, exitCode] of [ ${JSON.stringify(survivor)}],{stdio:'inherit'}); process.send({type:'upgrade-probe',ok:${ exitCode === 0 - },message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify(version)},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode})); + },message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify( + version, + )},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode})); `, ); const checkSignals = checkGroupSignals(t); @@ -148,7 +160,9 @@ test('cancelled dependency repair kills descendants and retains the original tre if(process.argv[2]==='--version'){console.log('8.3.1');process.exit(0);} require('node:child_process').spawn(process.execPath,['-e', "process.on('SIGTERM',()=>{});require('node:fs').writeFileSync(process.argv[1],'started');setTimeout(()=>require('node:fs').writeFileSync(process.argv[2],'escaped'),1400);", - ${JSON.stringify(started)},${JSON.stringify(survivor)}],{stdio:'inherit'}); + ${JSON.stringify(started)},${JSON.stringify( + survivor, + )}],{stdio:'inherit'}); setInterval(()=>{},1000); `, { mode: 0o755 }, diff --git a/test/back/upgrade-readiness.test.cjs b/test/back/upgrade-readiness.test.cjs index 3850baed..c4049283 100644 --- a/test/back/upgrade-readiness.test.cjs +++ b/test/back/upgrade-readiness.test.cjs @@ -5,27 +5,52 @@ const vm = require('node:vm'); const { EventEmitter } = require('node:events'); const ts = require('typescript'); const load = require('../helpers/load-security-module.cjs'); -const { SchedulerReadiness } = load('back/shared/schedulerReadiness.ts'); +const { SchedulerReadiness } = load( + 'back/cron/scheduling/schedulerReadiness.ts', +); const { outputText } = ts.transpileModule( fs.readFileSync('back/bootstrap/upgradeProbe.ts', 'utf8'), - { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true } }, + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }, ); // Run the real probe entry point, including its lifecycle and IPC reporting. // Only external services and the clock are replaced; no test exports are needed. -async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true }) { +async function runProbe({ + readiness, + arch = 'x64', + armVersion, + supervised = true, +}) { let now = 0; - const events = [], waits = [], messages = []; + const events = [], + waits = [], + messages = []; const build = { sourceCommit: 'a'.repeat(40) }; let finish; - const completed = new Promise((resolve) => { finish = resolve; }); + const completed = new Promise((resolve) => { + finish = resolve; + }); const listener = { address: () => ({ port: 12345 }) }; const server = { - initialize: async () => { events.push('http'); return listener; }, - shutdown: async () => { events.push('http-close'); }, + initialize: async () => { + events.push('http'); + return listener; + }, + shutdown: async () => { + events.push('http-close'); + }, }; const grpc = { - initialize: async () => { events.push('grpc'); return 12346; }, + initialize: async () => { + events.push('grpc'); + return 12346; + }, getServer: () => ({ forceShutdown: () => events.push('grpc-close') }), }; class GrpcServerService {} @@ -34,13 +59,23 @@ async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true 'reflect-metadata': {}, dns: { setDefaultResultOrder: () => {} }, '../config': {}, - '../data': { sequelize: { - transaction: async (action) => action({}), - query: async () => [[{ value: 42 }]], - close: async () => { events.push('db-close'); }, - } }, - '../loaders/db': async () => { events.push('db'); }, - typedi: { Container: { get: (service) => service === GrpcServerService ? grpc : server } }, + '../data': { + sequelize: { + transaction: async (action) => action({}), + query: async () => [[{ value: 42 }]], + close: async () => { + events.push('db-close'); + }, + }, + }, + '../loaders/db': async () => { + events.push('db'); + }, + typedi: { + Container: { + get: (service) => (service === GrpcServerService ? grpc : server), + }, + }, '../services/grpc': { GrpcServerService }, '../services/http': { HttpServerService }, '../loaders/httpApplication': { createHttpApplication: async () => ({}) }, @@ -48,86 +83,154 @@ async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true '../loaders/express': () => {}, '../loaders/app': {}, '../loaders/depInjector': () => {}, - '../schedule/client': { readiness: { - configure: (restore) => readiness.configure(restore), - recover: async () => { - const ready = await readiness.recover(); - if (ready) events.push('ready'); - return ready; + '../schedule/client': { + readiness: { + configure: (restore) => readiness.configure(restore), + recover: async () => { + const ready = await readiness.recover(); + if (ready) events.push('ready'); + return ready; + }, }, - } }, - http: { get: (url, respond) => { - events.push('health'); - const request = new EventEmitter(); - request.setTimeout = () => {}; - queueMicrotask(() => { - const response = new EventEmitter(); - response.statusCode = 200; - respond(response); - response.emit('data', JSON.stringify({ code: 200, data: { status: 'ok', services: { grpc: true, http: true }, build } })); - response.emit('end'); - }); - return request; - } }, + }, + http: { + get: (url, respond) => { + events.push('health'); + const request = new EventEmitter(); + request.setTimeout = () => {}; + queueMicrotask(() => { + const response = new EventEmitter(); + response.statusCode = 200; + respond(response); + response.emit( + 'data', + JSON.stringify({ + code: 200, + data: { + status: 'ok', + services: { grpc: true, http: true }, + build, + }, + }), + ); + response.emit('end'); + }); + return request; + }, + }, }; - vm.runInNewContext(outputText, { - exports: {}, - require: (name) => { - assert.ok(Object.hasOwn(modules, name), `Unexpected probe dependency: ${name}`); - return modules[name]; + vm.runInNewContext( + outputText, + { + exports: {}, + require: (name) => { + assert.ok( + Object.hasOwn(modules, name), + `Unexpected probe dependency: ${name}`, + ); + return modules[name]; + }, + process: { + env: { QL_UPGRADE_PROBE: supervised ? '1' : '0' }, + arch, + config: { variables: { arm_version: armVersion } }, + pid: 123, + once: () => {}, + memoryUsage: () => ({}), + send: (message) => { + messages.push(message); + events.push('report'); + }, + exit: finish, + }, + Date: { now: () => now }, + setTimeout: (callback, ms) => { + assert.ok(ms > 0 && ms <= 250); + waits.push(ms); + now += ms; + queueMicrotask(callback); + }, + console: { error: () => {} }, }, - process: { - env: { QL_UPGRADE_PROBE: supervised ? '1' : '0' }, arch, - config: { variables: { arm_version: armVersion } }, pid: 123, - once: () => {}, memoryUsage: () => ({}), - send: (message) => { messages.push(message); events.push('report'); }, - exit: finish, - }, - Date: { now: () => now }, - setTimeout: (callback, ms) => { - assert.ok(ms > 0 && ms <= 250); - waits.push(ms); - now += ms; - queueMicrotask(callback); - }, - console: { error: () => {} }, - }, { filename: 'upgradeProbe.js' }); + { filename: 'upgradeProbe.js' }, + ); const exitCode = await completed; return { exitCode, events, waits, messages, elapsed: now, build }; } test('upgrade probe survives cold scheduler recovery before checking HTTP and reporting readiness', async () => { - let attempts = 0, restored = false; + let attempts = 0, + restored = false; const readiness = new SchedulerReadiness(async () => { - if (++attempts < 3) throw new Error('Failed to connect before the deadline'); + if (++attempts < 3) + throw new Error('Failed to connect before the deadline'); }); // The probe must configure and finish restoration before reporting readiness. const configure = readiness.configure.bind(readiness); - readiness.configure = (restore) => configure(async () => { await restore(); restored = true; }); + readiness.configure = (restore) => + configure(async () => { + await restore(); + restored = true; + }); const result = await runProbe({ readiness }); assert.equal(result.exitCode, 0); assert.equal(restored, true); assert.equal(await readiness.check(), true); assert.deepEqual(result.waits, [250, 250]); - assert.deepEqual(result.events, ['db', 'grpc', 'ready', 'http', 'health', 'report', 'http-close', 'grpc-close', 'db-close']); + assert.deepEqual(result.events, [ + 'db', + 'grpc', + 'ready', + 'http', + 'health', + 'report', + 'http-close', + 'grpc-close', + 'db-close', + ]); assert.equal(result.messages.length, 1); assert.equal(result.messages[0].ok, true); - assert.equal(result.messages[0].build.sourceCommit, result.build.sourceCommit); + assert.equal( + result.messages[0].build.sourceCommit, + result.build.sourceCommit, + ); }); -for (const [arch, armVersion, timeout] of [['x64', undefined, 10000], ['arm', 7, 10000], ['arm', '6', 60000]]) { +for (const [arch, armVersion, timeout] of [ + ['x64', undefined, 10000], + ['arm', 7, 10000], + ['arm', '6', 60000], +]) { test(`unavailable ${arch}/v${armVersion} scheduler fails at its startup budget and cleans up`, async () => { let attempts = 0; - const result = await runProbe({ arch, armVersion, readiness: { - configure: () => {}, recover: async () => { attempts++; return false; }, - } }); + const result = await runProbe({ + arch, + armVersion, + readiness: { + configure: () => {}, + recover: async () => { + attempts++; + return false; + }, + }, + }); assert.equal(result.exitCode, 1); assert.equal(result.elapsed, timeout); assert.equal(attempts, timeout / 250); - assert.deepEqual(result.events, ['db', 'grpc', 'http-close', 'grpc-close', 'db-close', 'report']); + assert.deepEqual(result.events, [ + 'db', + 'grpc', + 'http-close', + 'grpc-close', + 'db-close', + 'report', + ]); assert.equal(result.messages.length, 1); assert.equal(result.messages[0].ok, false); - assert.match(result.messages[0].message, /Upgrade scheduler readiness failed/); + assert.match( + result.messages[0].message, + /Upgrade scheduler readiness failed/, + ); await new Promise((resolve) => setImmediate(resolve)); assert.equal(attempts, timeout / 250, 'no retries after failure'); }); @@ -135,20 +238,35 @@ for (const [arch, armVersion, timeout] of [['x64', undefined, 10000], ['arm', 7, test('unexpected scheduler recovery errors fail prestart without retries or a success report', async () => { let attempts = 0; - const result = await runProbe({ readiness: { - configure: () => {}, recover: async () => { attempts++; throw new Error('broken scheduler configuration'); }, - } }); + const result = await runProbe({ + readiness: { + configure: () => {}, + recover: async () => { + attempts++; + throw new Error('broken scheduler configuration'); + }, + }, + }); assert.equal(attempts, 1); assert.equal(result.exitCode, 1); assert.deepEqual(result.waits, []); - assert.deepEqual(result.events, ['db', 'grpc', 'http-close', 'grpc-close', 'db-close', 'report']); + assert.deepEqual(result.events, [ + 'db', + 'grpc', + 'http-close', + 'grpc-close', + 'db-close', + 'report', + ]); assert.equal(result.messages.length, 1); assert.equal(result.messages[0].ok, false); assert.match(result.messages[0].message, /broken scheduler configuration/); }); test('an already ready scheduler reaches health without waiting', async () => { - const result = await runProbe({ readiness: { configure: () => {}, recover: async () => true } }); + const result = await runProbe({ + readiness: { configure: () => {}, recover: async () => true }, + }); assert.equal(result.exitCode, 0); assert.deepEqual(result.waits, []); assert.equal(result.messages[0].ok, true); diff --git a/test/back/wpush-grpc.test.cjs b/test/back/wpush-grpc.test.cjs index c40070fa..15832953 100644 --- a/test/back/wpush-grpc.test.cjs +++ b/test/back/wpush-grpc.test.cjs @@ -46,7 +46,12 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura const decorators = { Service: () => (x) => x, Inject: () => () => {} }; const NotificationService = load(back('services/notify.ts'), { typedi: decorators, - './user': {}, + '../data/notificationSettings': { + readNotificationMode: async () => ({ + type: 'wpush', + wpushApiKey: 'saved-key', + }), + }, '../config/util': {}, '../shared/i18n': { t: (x) => x }, '../config/http': { @@ -64,8 +69,12 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura '../config/const': constants, '../config/util': {}, '../data/dependence': {}, - '../data/system': { AuthDataType: { notifyLog: 'notifyLog' }, NotifyStatus: { success: 0, fail: 1 }, SystemModel: { create: async () => {}, findAll: async () => [] } }, - '../shared/pLimit': {}, + '../data/system': { + AuthDataType: { notifyLog: 'notifyLog' }, + NotifyStatus: { success: 0, fail: 1 }, + SystemModel: { create: async () => {}, findAll: async () => [] }, + }, + '../cron/execution/cronLimit': {}, '../schedule/client': {}, '../shared/i18n': { t: (x) => x }, './notify': {}, @@ -73,12 +82,6 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura './sock': {}, }).default; const notification = new NotificationService(); - notification.userService = { - getNotificationMode: async () => ({ - type: 'wpush', - wpushApiKey: 'saved-key', - }), - }; const system = new SystemService({ error() {} }); system.notificationService = notification; diff --git a/test/front/cron-list-polling.test.cjs b/test/front/cron-list-polling.test.cjs index b63695ab..92ae2e16 100644 --- a/test/front/cron-list-polling.test.cjs +++ b/test/front/cron-list-polling.test.cjs @@ -6,38 +6,91 @@ const ts = require('typescript'); // Exercise the real list effect while explicitly releasing each HTTP response. function listEffect() { - const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8'); - const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/index.tsx'), + 'utf8', + ); + const ast = ts.createSourceFile( + 'index.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); const effects = []; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' && - node.arguments[1]?.getText(ast).includes('searchText')) effects.push(node.arguments[0]); + if ( + ts.isCallExpression(node) && + node.expression.getText(ast) === 'useEffect' && + node.arguments[1]?.getText(ast).includes('searchText') + ) + effects.push(node.arguments[0]); ts.forEachChild(node, visit); } visit(ast); assert.equal(effects.length, 1); - const js = ts.transpile('const effect = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2022}); - const requests = [], timers = new Set(), rows = [], totals = [], failures = []; + const js = ts.transpile('const effect = ' + effects[0].getText(ast), { + target: ts.ScriptTarget.ES2022, + }); + const requests = [], + timers = new Set(), + rows = [], + totals = [], + failures = []; const bindings = { - pageConf: { page: 1, size: 20 }, viewConf: null, config: {apiPrefix: '/api/'}, - request: { get(url, options) { - return new Promise((resolve, reject) => requests.push({url, options, resolve, reject})); - } }, setValue: value => rows.push(value), setTotal: value => totals.push(value), - setLoading() {}, setListFailed(failed) { failures.push(failed); }, - setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); }, + pageConf: { page: 1, size: 20 }, + viewConf: null, + config: { apiPrefix: '/api/' }, + request: { + get(url, options) { + return new Promise((resolve, reject) => + requests.push({ url, options, resolve, reject }), + ); + }, + }, + setValue: (value) => rows.push(value), + setTotal: (value) => totals.push(value), + setLoading() {}, + setListFailed(failed) { + failures.push(failed); + }, + setTimeout(fn) { + timers.add(fn); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, + }; + return { + requests, + timers, + rows, + totals, + failures, + start(searchText) { + return Function( + 'searchText', + ...Object.keys(bindings), + js + '\nreturn effect();', + )(searchText, ...Object.values(bindings)); + }, }; - return { requests, timers, rows, totals, failures, start(searchText) { - return Function('searchText', ...Object.keys(bindings), js + '\nreturn effect();')(searchText, ...Object.values(bindings)); - } }; } -const flush = () => new Promise(resolve => setImmediate(resolve)); -const page = (id, sub_id) => ({code: 200, data: {data: [{id, sub_id}], total: 1}}); +const flush = () => new Promise((resolve) => setImmediate(resolve)); +const page = (id, sub_id) => ({ + code: 200, + data: { data: [{ id, sub_id }], total: 1 }, +}); test('switching searches discards stale list and subscription responses and cancels old polling', async () => { for (const delaySubscription of [false, true]) { const view = listEffect(); const closeA = view.start('A'); - if (delaySubscription) { view.requests[0].resolve(page(1, 7)); await flush(); } + if (delaySubscription) { + view.requests[0].resolve(page(1, 7)); + await flush(); + } const stale = view.requests.at(-1); closeA(); assert.ok(stale.options.signal.aborted); @@ -46,9 +99,14 @@ test('switching searches discards stale list and subscription responses and canc assert.equal(fresh.options.params.searchValue, 'B&+'); fresh.resolve(page(2)); await flush(); - stale.resolve(delaySubscription ? {code: 200, data: [{id: 7}]} : page(1, 7)); + stale.resolve( + delaySubscription ? { code: 200, data: [{ id: 7 }] } : page(1, 7), + ); await flush(); - assert.deepEqual(view.rows.map(rows => rows.map(r => r.id)), [[2]]); + assert.deepEqual( + view.rows.map((rows) => rows.map((r) => r.id)), + [[2]], + ); assert.deepEqual(view.totals, [1]); assert.equal(view.requests.length, delaySubscription ? 3 : 2); assert.equal(view.timers.size, 1); @@ -75,18 +133,35 @@ test('list polling recovers on the next tick after a network failure', async () }); test('the next search can be submitted while the table request is in flight', () => { - const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8'); - const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/index.tsx'), + 'utf8', + ); + const ast = ts.createSourceFile( + 'index.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); const controls = []; function visit(node) { - if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(ast) === 'Search') controls.push(node); + if ( + ts.isJsxSelfClosingElement(node) && + node.tagName.getText(ast) === 'Search' + ) + controls.push(node); ts.forEachChild(node, visit); } visit(ast); assert.equal(controls.length, 1); - const attributes = controls[0].attributes.properties.map(p => p.name?.getText(ast)); + const attributes = controls[0].attributes.properties.map((p) => + p.name?.getText(ast), + ); assert.ok(attributes.includes('onSearch')); - assert.ok(!attributes.includes('loading') && !attributes.includes('disabled')); + assert.ok( + !attributes.includes('loading') && !attributes.includes('disabled'), + ); }); test('a failed subscription lookup still displays the current task list', async () => { @@ -96,7 +171,10 @@ test('a failed subscription lookup still displays the current task list', async await flush(); view.requests[1].reject(Error('offline')); await flush(); - assert.deepEqual(view.rows[0].map(row => row.id), [42]); + assert.deepEqual( + view.rows[0].map((row) => row.id), + [42], + ); assert.deepEqual(view.totals, [1]); stop(); }); diff --git a/test/front/cron-log-pagination.test.cjs b/test/front/cron-log-pagination.test.cjs index 9bd5f3b4..2bad4f2d 100644 --- a/test/front/cron-log-pagination.test.cjs +++ b/test/front/cron-log-pagination.test.cjs @@ -40,7 +40,12 @@ function fixture(get) { config: { apiPrefix: '/api/' }, cron: { id: 1 }, session: { current: new AbortController() }, - pinnedTrigger: {}, reading: {current: false}, drained: {}, lastPath: {}, lastCursor: {}, scrollTimer: {}, + pinnedTrigger: {}, + reading: { current: false }, + drained: {}, + lastPath: {}, + lastCursor: {}, + scrollTimer: {}, LOG_CHUNK_BYTES: 256 * 1024, MAX_LOG_VIEW_CHARS: 1024 * 1024, logOffsetRef: { current: undefined }, @@ -54,8 +59,12 @@ function fixture(get) { }, }, intl: { get: (value) => value }, - setLoading(value) { values.loading = value; }, - setReadFailed(value) { values.failed = value; }, + setLoading(value) { + values.loading = value; + }, + setReadFailed(value) { + values.failed = value; + }, autoScroll() {}, handleCancel() {}, setValue(value) { @@ -87,7 +96,9 @@ function fixture(get) { return { values, timers, - retry() { context.getCronLog(context.logOffsetRef.current === undefined); }, + retry() { + context.getCronLog(context.logOffsetRef.current === undefined); + }, start() { context.getCronLog(true); }, @@ -228,12 +239,17 @@ test('first log read failure is recoverable on retry', async () => { test('independent log readers can receive responses in reverse order across close and reopen', async () => { let resolveOld; - const old = fixture(() => new Promise(resolve => { resolveOld = resolve; })); + const old = fixture( + () => + new Promise((resolve) => { + resolveOld = resolve; + }), + ); old.start(); old.close(); - const current = fixture(async () => ({code: 200, data: 'new log'})); + const current = fixture(async () => ({ code: 200, data: 'new log' })); await current.read(); - resolveOld({code: 200, data: 'old log', logStatus: 'running'}); + resolveOld({ code: 200, data: 'old log', logStatus: 'running' }); await old.settle(); assert.equal(current.values.content, 'new log'); assert.equal(old.values.content, ''); @@ -242,7 +258,10 @@ test('independent log readers can receive responses in reverse order across clos test('repeated retries share one in-flight read and closing aborts its transport', async () => { const pending = []; - const view = fixture((url, { signal }) => new Promise(resolve => pending.push({ signal, resolve }))); + const view = fixture( + (url, { signal }) => + new Promise((resolve) => pending.push({ signal, resolve })), + ); view.start(); view.retry(); assert.equal(pending.length, 1); @@ -257,25 +276,43 @@ test('repeated retries share one in-flight read and closing aborts its transport test('polling a missing log displays its status once and retries from the last confirmed byte', async () => { const calls = []; const responses = [ - {data: 'waiting', total: 0, nextOffset: 0}, {data: 'waiting', total: 0, nextOffset: 0}, - {data: 'abc', total: 3, nextOffset: 3, logPath: 'a'}, null, - {data: 'd', total: 4, nextOffset: 4, logPath: 'a'}, - {data: 'new!', total: 4, nextOffset: 4, logPath: 'b', logStatus: 'completed'}, + { data: 'waiting', total: 0, nextOffset: 0 }, + { data: 'waiting', total: 0, nextOffset: 0 }, + { data: 'abc', total: 3, nextOffset: 3, logPath: 'a' }, + null, + { data: 'd', total: 4, nextOffset: 4, logPath: 'a' }, + { + data: 'new!', + total: 4, + nextOffset: 4, + logPath: 'b', + logStatus: 'completed', + }, ]; - const view = fixture(async url => { + const view = fixture(async (url) => { calls.push(new URL(url, 'http://localhost').searchParams); const r = responses.shift(); if (!r) throw Error('offline'); - return {code: 200, logStatus: 'running', ...r}; + return { code: 200, logStatus: 'running', ...r }; }); - await view.read(); await view.tick(); + await view.read(); + await view.tick(); assert.equal(view.values.content, 'waiting'); - await view.tick(); await view.tick(); + await view.tick(); + await view.tick(); assert.equal(view.values.failed, true); assert.equal(view.values.content, 'abc'); - view.retry(); view.retry(); await view.settle(); + view.retry(); + view.retry(); + await view.settle(); assert.equal(view.values.content, 'abcd'); - assert.deepEqual(calls.slice(3).map(p => [p.get('offset'), p.get('previousPath')]), [['3','a'],['3','a']]); + assert.deepEqual( + calls.slice(3).map((p) => [p.get('offset'), p.get('previousPath')]), + [ + ['3', 'a'], + ['3', 'a'], + ], + ); await view.tick(); assert.equal(view.values.content, 'new!'); assert.equal(view.timers.size, 0); @@ -283,21 +320,28 @@ test('polling a missing log displays its status once and retries from the last c test('a shortened file during a retry is reread from its new tail', async () => { const responses = [ - {data: 'previous log', nextOffset: 12, total: 12}, {data: '', nextOffset: 3, total: 3}, - {data: 'new', nextOffset: 3, total: 3}, + { data: 'previous log', nextOffset: 12, total: 12 }, + { data: '', nextOffset: 3, total: 3 }, + { data: 'new', nextOffset: 3, total: 3 }, ]; const calls = []; - const view = fixture(async url => { + const view = fixture(async (url) => { calls.push(url); - return {code: 200, logStatus: responses.length === 3 ? 'running' : 'completed', ...responses.shift()}; + return { + code: 200, + logStatus: responses.length === 3 ? 'running' : 'completed', + ...responses.shift(), + }; }); - await view.read(); await view.tick(); await view.tick(); + await view.read(); + await view.tick(); + await view.tick(); assert.match(calls[2], /tail=true/); assert.equal(view.values.content, 'new'); assert.equal(view.timers.size, 0); }); -test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async t => { +test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async (t) => { const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'ql-log-regrow-')); t.after(() => fsp.rm(dir, { recursive: true, force: true })); const file = path.join(dir, 'run.log'); @@ -305,23 +349,34 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all let running = true; let fail = false; const offsets = []; - const view = fixture(async url => { + const view = fixture(async (url) => { const p = new URL(url, 'http://localhost').searchParams; const offset = p.has('offset') ? Number(p.get('offset')) : undefined; offsets.push(offset); if (fail) throw Error('timeout'); const chunk = await readLogChunk(file, { - offset, follow: p.get('follow') === 'true', cursor: p.get('cursor'), - tail: p.get('tail') === 'true', limit: Number(p.get('limit')), + offset, + follow: p.get('follow') === 'true', + cursor: p.get('cursor'), + tail: p.get('tail') === 'true', + limit: Number(p.get('limit')), }); - return { ...chunk, code: 200, data: chunk.content, logPath: 'run.log', - logStatus: running ? 'running' : 'completed' }; + return { + ...chunk, + code: 200, + data: chunk.content, + logPath: 'run.log', + logStatus: running ? 'running' : 'completed', + }; }); await view.read(); fail = true; await view.tick(); assert.equal(view.values.failed, true); - const current = Array.from({ length: 16000 }, (_, i) => `${i} · 中文日志🚀\n`).join(''); + const current = Array.from( + { length: 16000 }, + (_, i) => `${i} · 中文日志🚀\n`, + ).join(''); await fsp.writeFile(file, current); fail = running = false; view.retry(); @@ -338,42 +393,68 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all test('a fresh list snapshot wakes a drained live viewer only for a new path or active task', () => { const effects = []; function visitEffect(node) { - if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' && - node.arguments[1]?.getText(ast) === '[cron]') effects.push(node.arguments[0]); + if ( + ts.isCallExpression(node) && + node.expression.getText(ast) === 'useEffect' && + node.arguments[1]?.getText(ast) === '[cron]' + ) + effects.push(node.arguments[0]); ts.forEachChild(node, visitEffect); } visitEffect(ast); assert.equal(effects.length, 1); - const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2020}); + const wake = ts.transpile('var wake = ' + effects[0].getText(ast), { + target: ts.ScriptTarget.ES2020, + }); let calls = 0; - const context = { cron: { log_path: 'old', status: 1 }, lastPath: {current: 'old'}, - drained: {current: true}, pinnedTrigger: {}, logUrl: undefined, - CrontabStatus: {running: 0, queued: 3}, getCronLog: () => calls++ }; + const context = { + cron: { log_path: 'old', status: 1 }, + lastPath: { current: 'old' }, + drained: { current: true }, + pinnedTrigger: {}, + logUrl: undefined, + CrontabStatus: { running: 0, queued: 3 }, + getCronLog: () => calls++, + }; const update = () => vm.runInNewContext(wake + '\nwake()', context); - update(); assert.equal(calls, 0); - context.cron = {log_path: 'new', status: 1}; - update(); assert.equal(calls, 1); - context.cron = {log_path: 'old', status: 3}; - update(); assert.equal(calls, 2); + update(); + assert.equal(calls, 0); + context.cron = { log_path: 'new', status: 1 }; + update(); + assert.equal(calls, 1); + context.cron = { log_path: 'old', status: 3 }; + update(); + assert.equal(calls, 2); context.drained.current = false; - update(); assert.equal(calls, 2); + update(); + assert.equal(calls, 2); context.drained.current = true; context.logUrl = '/api/logs/detail?file=old'; - update(); assert.equal(calls, 2); + update(); + assert.equal(calls, 2); }); test('concurrent live log polling and retries stay scoped to the initially selected trigger', async () => { const calls = []; - const view = fixture(async url => { + const view = fixture(async (url) => { const p = new URL(url, 'http://localhost').searchParams; calls.push(p.get('triggerId')); if (calls.length === 2) throw Error('timeout'); const selected = p.get('triggerId') || (calls.length === 1 ? 'a' : 'b'); - return { code: 200, triggerId: selected, logPath: selected + '.log', total: calls.length === 1 ? 1 : 2, - nextOffset: calls.length === 1 ? 1 : 2, logStatus: calls.length < 3 ? 'running' : 'completed', - data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!' }; + return { + code: 200, + triggerId: selected, + logPath: selected + '.log', + total: calls.length === 1 ? 1 : 2, + nextOffset: calls.length === 1 ? 1 : 2, + logStatus: calls.length < 3 ? 'running' : 'completed', + data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!', + }; }); - await view.read(); await view.tick(); view.retry(); await view.settle(); + await view.read(); + await view.tick(); + view.retry(); + await view.settle(); assert.deepEqual(calls, [null, 'a', 'a']); assert.equal(view.values.content, 'A!'); assert.equal(view.timers.size, 0); diff --git a/test/front/dashboard-polling.test.cjs b/test/front/dashboard-polling.test.cjs index 5194355a..218977a7 100644 --- a/test/front/dashboard-polling.test.cjs +++ b/test/front/dashboard-polling.test.cjs @@ -4,51 +4,107 @@ const fs = require('node:fs'); const ts = require('typescript'); function dashboard(anomaly) { - const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8'); - const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + require.resolve('../../src/pages/dashboard/index.tsx'), + 'utf8', + ); + const ast = ts.createSourceFile( + 'dashboard.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let effect; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' && - node.arguments[0].getText(ast).includes('setOverview')) effect = node.arguments[0].getText(ast); + if ( + ts.isCallExpression(node) && + node.expression.getText(ast) === 'useEffect' && + node.arguments[0].getText(ast).includes('setOverview') + ) + effect = node.arguments[0].getText(ast); ts.forEachChild(node, visit); } visit(ast); assert.ok(effect); - const requests = [], results = [], failures = [], timers = new Set(); + const requests = [], + results = [], + failures = [], + timers = new Set(); const noop = () => {}; const bindings = { performance: { now: () => 1000 }, - anomaly, config: { apiPrefix: '/api/' }, REFRESH_INTERVAL: 30000, - setOverview: value => results.push(value), setOverviewFailed: value => failures.push(value), - setLoading: noop, setTrend: noop, setSystem: noop, setTopTime: noop, setTopCount: noop, setLabels: noop, setRuntime: noop, - setInterval(fn) { timers.add(fn); return fn; }, clearInterval(fn) { timers.delete(fn); }, - request: { get(url, options) { - return new Promise((resolve, reject) => requests.push({ url, options, resolve, reject })); - } }, + anomaly, + config: { apiPrefix: '/api/' }, + REFRESH_INTERVAL: 30000, + setOverview: (value) => results.push(value), + setOverviewFailed: (value) => failures.push(value), + setLoading: noop, + setTrend: noop, + setSystem: noop, + setTopTime: noop, + setTopCount: noop, + setLabels: noop, + setRuntime: noop, + setInterval(fn) { + timers.add(fn); + return fn; + }, + clearInterval(fn) { + timers.delete(fn); + }, + request: { + get(url, options) { + return new Promise((resolve, reject) => + requests.push({ url, options, resolve, reject }), + ); + }, + }, }; - const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 }); + const js = ts.transpile('const start = ' + effect, { + target: ts.ScriptTarget.ES2022, + }); return { - start: Function(...Object.keys(bindings), js + '\nreturn start;')(...Object.values(bindings)), - tick() { for (const fn of timers) fn(); }, timers, results, failures, - requests: section => requests.filter(r => r.url === '/api/dashboard/' + section), + start: Function( + ...Object.keys(bindings), + js + '\nreturn start;', + )(...Object.values(bindings)), + tick() { + for (const fn of timers) fn(); + }, + timers, + results, + failures, + requests: (section) => + requests.filter((r) => r.url === '/api/dashboard/' + section), }; } -const flush = () => new Promise(resolve => setImmediate(resolve)); +const flush = () => new Promise((resolve) => setImmediate(resolve)); test('a first anomaly request that never succeeds still expires using the overview deadline', async () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 }; const close = v.start(selection, { page: 1 }); v.tick(10000); assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]); assert.equal(v.requests[0].signal.aborted, true); - v.requests[0].resolve({ code: 200, data: { rows: ['yesterday'], summary: {} } }); + v.requests[0].resolve({ + code: 200, + data: { rows: ['yesterday'], summary: {} }, + }); await flush(); assert.deepEqual(v.received, []); close(); }); test('a first failure and manual retry cannot reset the overview deadline', async () => { - const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, deadline: 10000 }; + const v = anomalies(), + selection = { + source: 'system', + kind: 'unconfirmed', + at: 100, + deadline: 10000, + }; const close = v.start(selection, { page: 1 }); v.requests[0].reject(new Error('offline')); await flush(); @@ -62,7 +118,8 @@ test('a first failure and manual retry cannot reset the overview deadline', asyn }); test('opening an already expired overview does not send an obsolete detail request', () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 }; v.advance(1001); const close = v.start(selection, { page: 1 }); assert.equal(v.requests.length, 0); @@ -71,16 +128,21 @@ test('opening an already expired overview does not send an obsolete detail reque }); test('overview deadlines use server time and request start, independent of the browser wall clock', async () => { - const v = dashboard(), close = v.start(); + const v = dashboard(), + close = v.start(); const serverNow = 1795017590000; - v.requests('overview')[0].resolve({ code: 200, data: { serverNow, expiresAt: serverNow + 10000 } }); + v.requests('overview')[0].resolve({ + code: 200, + data: { serverNow, expiresAt: serverNow + 10000 }, + }); await flush(); assert.equal(v.results[0].anomalyDeadline, 11000); close(); }); test('slow dashboard cards do not block crond counts, overlap a pending refresh or restart polling after unmount', async () => { - const view = dashboard(), leave = view.start(); + const view = dashboard(), + leave = view.start(); view.tick(); assert.equal(view.requests('overview').length, 1); view.requests('overview')[0].resolve({ code: 200, data: { actualSkips: 0 } }); @@ -107,7 +169,11 @@ test('slow dashboard cards do not block crond counts, overlap a pending refresh await flush(); stale.resolve({ code: 200, data: { actualSkips: 0 } }); await flush(); - assert.deepEqual(view.results, [{ actualSkips: 0 }, { actualSkips: 1 }, { actualSkips: 2 }]); + assert.deepEqual(view.results, [ + { actualSkips: 0 }, + { actualSkips: 1 }, + { actualSkips: 2 }, + ]); assert.deepEqual(view.failures, [false, true, false, false]); assert.equal(view.timers.size, 1); closeAgain(); @@ -117,47 +183,114 @@ test('system crond results distinguish missing records, unknown exits and record const intl = require('react-intl-universal'); const messages = require('../../src/locales/zh-CN.json'); await intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': messages } }); - const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8'); - const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + require.resolve('../../src/pages/dashboard/index.tsx'), + 'utf8', + ); + const ast = ts.createSourceFile( + 'dashboard.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let renderer; function visit(node) { - if (ts.isObjectLiteralExpression(node) && node.properties.some(p => - ts.isPropertyAssignment(p) && p.name.getText(ast) === 'title' && - p.initializer.getText(ast) === "intl.get('执行情况')")) { - renderer = node.properties.find(p => p.name.getText(ast) === 'render').initializer; + if ( + ts.isObjectLiteralExpression(node) && + node.properties.some( + (p) => + ts.isPropertyAssignment(p) && + p.name.getText(ast) === 'title' && + p.initializer.getText(ast) === "intl.get('执行情况')", + ) + ) { + renderer = node.properties.find( + (p) => p.name.getText(ast) === 'render', + ).initializer; } ts.forEachChild(node, visit); } visit(ast); assert.ok(renderer); const js = ts.transpileModule('const render = ' + renderer.getText(ast), { - fileName: 'cell.tsx', compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 }, + fileName: 'cell.tsx', + compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 }, }).outputText; - const cell = Function('React', 'intl', js + '\nreturn render;')(require('react'), intl); - const html = row => require('react-dom/server').renderToStaticMarkup(cell(null, row)); + const cell = Function( + 'React', + 'intl', + js + '\nreturn render;', + )(require('react'), intl); + const html = (row) => + require('react-dom/server').renderToStaticMarkup(cell(null, row)); assert.equal(html({ status: 'missing', triggerCount: 0 }), '未收到触发记录'); - assert.equal(html({ status: 'skipped', triggerCount: 1, skipCount: 1 }), '已跳过'); + assert.equal( + html({ status: 'skipped', triggerCount: 1, skipCount: 1 }), + '已跳过', + ); assert.equal(html({ status: 'started' }), '命令已启动'); - assert.equal(html({ status: 'started', triggerCount: 1, startCount: 1, unknownExitCount: 1 }), - '命令已启动 · 结果未知'); - assert.equal(html({ status: 'started', triggerCount: 2, startCount: 1, skipCount: 1, unknownExitCount: 1 }), - '启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知'); + assert.equal( + html({ + status: 'started', + triggerCount: 1, + startCount: 1, + unknownExitCount: 1, + }), + '命令已启动 · 结果未知', + ); + assert.equal( + html({ + status: 'started', + triggerCount: 2, + startCount: 1, + skipCount: 1, + unknownExitCount: 1, + }), + '启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知', + ); }); test('dashboard timing preserves millisecond precision, rounds long waits and distinguishes zero from no samples', async () => { const intl = require('react-intl-universal'); - const locales = { 'zh-CN': require('../../src/locales/zh-CN.json'), 'en-US': require('../../src/locales/en-US.json') }; - const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/timingStatistic.tsx'), 'utf8'); - const { outputText } = ts.transpileModule(source, { compilerOptions: { - jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true, - } }); + const locales = { + 'zh-CN': require('../../src/locales/zh-CN.json'), + 'en-US': require('../../src/locales/en-US.json'), + }; + const source = fs.readFileSync( + require.resolve('../../src/pages/dashboard/timingStatistic.tsx'), + 'utf8', + ); + const { outputText } = ts.transpileModule(source, { + compilerOptions: { + jsx: ts.JsxEmit.ReactJSX, + module: ts.ModuleKind.CommonJS, + esModuleInterop: true, + }, + }); const component = {}; Function('require', 'exports', outputText)(require, component); await intl.init({ currentLocale: 'zh-CN', locales }); - assert.deepEqual([null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(component.formatTiming), - ['—', '0 ms', '136 ms', '1 秒', '5.989 秒', '59.999 秒', '1 分 0 秒', '2 分 0 秒', '28 分 24 秒']); - const render = ms => require('react-dom/server').renderToStaticMarkup( - require('react').createElement(component.default, { title: 'P95', ms })); + assert.deepEqual( + [null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map( + component.formatTiming, + ), + [ + '—', + '0 ms', + '136 ms', + '1 秒', + '5.989 秒', + '59.999 秒', + '1 分 0 秒', + '2 分 0 秒', + '28 分 24 秒', + ], + ); + const render = (ms) => + require('react-dom/server').renderToStaticMarkup( + require('react').createElement(component.default, { title: 'P95', ms }), + ); assert.match(render(1703994), /title="1703994 ms">28 分 24 秒/); assert.match(render(null), /—/); assert.doesNotMatch(render(136), /个样本/); @@ -166,56 +299,127 @@ test('dashboard timing preserves millisecond precision, rounds long waits and di }); function anomalies() { - const filename = require.resolve('../../src/pages/dashboard/scheduleAnomalies.tsx'); + const filename = require.resolve( + '../../src/pages/dashboard/scheduleAnomalies.tsx', + ); const source = fs.readFileSync(filename, 'utf8'); - const ast = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const ast = ts.createSourceFile( + filename, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let effect; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect') + if ( + ts.isCallExpression(node) && + node.expression.getText(ast) === 'useEffect' + ) effect = node.arguments[0].getText(ast); ts.forEachChild(node, visit); } visit(ast); - const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 }); - const requests = [], received = [], failed = [], summaries = [], invalidated = [], timers = new Map(); + const js = ts.transpile('const start = ' + effect, { + target: ts.ScriptTarget.ES2022, + }); + const requests = [], + received = [], + failed = [], + summaries = [], + invalidated = [], + timers = new Map(); let now = 0; const bindings = { expiresAt: { current: undefined }, config: { apiPrefix: '/api/' }, - request: { get(url, options) { - assert.equal(url, '/api/dashboard/schedule-anomalies'); - return new Promise((resolve, reject) => requests.push({ ...options, resolve, reject })); - } }, - setResponse: data => received.push(data.result), setFailed: flag => failed.push(flag), setLoading() {}, + request: { + get(url, options) { + assert.equal(url, '/api/dashboard/schedule-anomalies'); + return new Promise((resolve, reject) => + requests.push({ ...options, resolve, reject }), + ); + }, + }, + setResponse: (data) => received.push(data.result), + setFailed: (flag) => failed.push(flag), + setLoading() {}, onUpdate: (selection, summary) => summaries.push(summary), - onInvalidate: (selection, reason) => invalidated.push({ selection, reason }), + onInvalidate: (selection, reason) => + invalidated.push({ selection, reason }), performance: { now: () => now }, - setTimeout(fn, ms) { timers.set(fn, ms); return fn; }, clearTimeout(fn) { timers.delete(fn); }, + setTimeout(fn, ms) { + timers.set(fn, ms); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, }; return { - start: (selection, query) => Function(...Object.keys(bindings), 'selection', 'query', - js + '\nreturn start();')(...Object.values(bindings), selection, query), - requests, received, failed, summaries, invalidated, timers, - advance(ms) { now += ms; }, - tick(delay = 5000) { for (const [fn, ms] of [...timers]) if (ms === delay) { timers.delete(fn); fn(); } }, + start: (selection, query) => + Function( + ...Object.keys(bindings), + 'selection', + 'query', + js + '\nreturn start();', + )(...Object.values(bindings), selection, query), + requests, + received, + failed, + summaries, + invalidated, + timers, + advance(ms) { + now += ms; + }, + tick(delay = 5000) { + for (const [fn, ms] of [...timers]) + if (ms === delay) { + timers.delete(fn); + fn(); + } + }, }; } test('anomaly pagination pins its plan window, advances revisions after resets and stops old polling across source changes', async () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100 }; const close = v.start(selection, { page: 2, revision: 'old' }); - assert.deepEqual(v.requests[0].params, { ...selection, live: true, page: 2, revision: 'old' }); - const updated = { rows: ['remaining'], page: 1, revision: 'new', total: 26, changed: true, summary: { audit: { missing: 26 } } }; + assert.deepEqual(v.requests[0].params, { + ...selection, + live: true, + page: 2, + revision: 'old', + }); + const updated = { + rows: ['remaining'], + page: 1, + revision: 'new', + total: 26, + changed: true, + summary: { audit: { missing: 26 } }, + }; v.requests[0].resolve({ code: 200, data: updated }); await flush(); assert.deepEqual(v.received, [updated]); assert.deepEqual(v.summaries, [updated.summary]); - v.tick(); v.tick(); + v.tick(); + v.tick(); assert.equal(v.requests.length, 2); - assert.deepEqual(v.requests[1].params, { ...selection, live: true, page: 1, revision: 'new' }); + assert.deepEqual(v.requests[1].params, { + ...selection, + live: true, + page: 1, + revision: 'new', + }); close(); assert.equal(v.requests[1].signal.aborted, true); - const leave = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 }); + const leave = v.start( + { source: 'system', kind: 'unconfirmed', at: 200 }, + { page: 1 }, + ); v.requests[1].resolve({ code: 200, data: { ...updated, total: 99 } }); v.requests[2].reject(new Error('timeout')); await flush(); @@ -223,8 +427,17 @@ test('anomaly pagination pins its plan window, advances revisions after resets a assert.equal(v.received.length, 1); assert.equal(v.timers.size, 0); leave(); - const finish = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 }); - const empty = { rows: [], page: 1, revision: 'empty', total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } }; + const finish = v.start( + { source: 'system', kind: 'unconfirmed', at: 200 }, + { page: 1 }, + ); + const empty = { + rows: [], + page: 1, + revision: 'empty', + total: 0, + summary: { systemAudit: { actualUnconfirmed: 0 } }, + }; v.requests[3].resolve({ code: 200, data: empty }); await flush(); assert.equal(v.failed.at(-1), false); @@ -235,48 +448,90 @@ test('anomaly pagination pins its plan window, advances revisions after resets a }); test('opening anomaly details cancels older overview responses and keeps its counts owned by the detail snapshot', async () => { - const v = dashboard(), close = v.start(); + const v = dashboard(), + close = v.start(); close(); - v.requests('overview')[0].resolve({ code: 200, data: { triggers: { audit: { missing: 55 } } } }); + v.requests('overview')[0].resolve({ + code: 200, + data: { triggers: { audit: { missing: 55 } } }, + }); await flush(); assert.deepEqual(v.results, []); - const opened = dashboard({ source: 'panel' }), leave = opened.start(); + const opened = dashboard({ source: 'panel' }), + leave = opened.start(); opened.tick(); assert.equal(opened.requests('overview').length, 0); assert.equal(opened.requests('runtime').length, 1); leave(); }); -for (const source of ['panel', 'system']) test(source + ' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source', async () => { - const v = anomalies(), selection = { source, kind: 'unconfirmed', at: 100, session: 1 }; - const stop = v.start(selection, { page: 3, revision: 'before-cleanup' }); - const retained = { page: 1, total: 40, revision: 'after-cleanup', changed: true, - rows: [{ trigger: 'retained', hasLog: true }], summary: source === 'panel' - ? { audit: { unconfirmed: 40 } } : { systemAudit: { actualUnconfirmed: 40 } } }; - v.requests[0].resolve({ code: 200, data: retained }); - await flush(); - v.tick(); - assert.equal(v.requests[1].params.page, 1); - assert.equal(v.requests[1].params.revision, 'after-cleanup'); - stop(); - const next = { ...selection, source: source === 'panel' ? 'system' : 'panel', session: 2 }; - const close = v.start(next, { page: 1 }); - const fresh = { ...retained, rows: [{ trigger: 'other-source', hasLog: true }], total: 1, revision: 'fresh', - summary: next.source === 'panel' ? { audit: { unconfirmed: 1 } } : { systemAudit: { actualUnconfirmed: 1 } } }; - v.requests[2].resolve({ code: 200, data: fresh }); - await flush(); - v.requests[1].resolve({ code: 200, data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] } }); - await flush(); - assert.deepEqual(v.received, [retained, fresh]); - assert.deepEqual(v.summaries, [retained.summary, fresh.summary]); - close(); - assert.equal(v.timers.size, 0); -}); +for (const source of ['panel', 'system']) + test( + source + + ' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source', + async () => { + const v = anomalies(), + selection = { source, kind: 'unconfirmed', at: 100, session: 1 }; + const stop = v.start(selection, { page: 3, revision: 'before-cleanup' }); + const retained = { + page: 1, + total: 40, + revision: 'after-cleanup', + changed: true, + rows: [{ trigger: 'retained', hasLog: true }], + summary: + source === 'panel' + ? { audit: { unconfirmed: 40 } } + : { systemAudit: { actualUnconfirmed: 40 } }, + }; + v.requests[0].resolve({ code: 200, data: retained }); + await flush(); + v.tick(); + assert.equal(v.requests[1].params.page, 1); + assert.equal(v.requests[1].params.revision, 'after-cleanup'); + stop(); + const next = { + ...selection, + source: source === 'panel' ? 'system' : 'panel', + session: 2, + }; + const close = v.start(next, { page: 1 }); + const fresh = { + ...retained, + rows: [{ trigger: 'other-source', hasLog: true }], + total: 1, + revision: 'fresh', + summary: + next.source === 'panel' + ? { audit: { unconfirmed: 1 } } + : { systemAudit: { actualUnconfirmed: 1 } }, + }; + v.requests[2].resolve({ code: 200, data: fresh }); + await flush(); + v.requests[1].resolve({ + code: 200, + data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] }, + }); + await flush(); + assert.deepEqual(v.received, [retained, fresh]); + assert.deepEqual(v.summaries, [retained.summary, fresh.summary]); + close(); + assert.equal(v.timers.size, 0); + }, + ); test('midnight cancels a hung anomaly refresh and a late reply cannot publish yesterday counts', async () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100, session: 1 }; const leave = v.start(selection, { page: 1 }); - const data = { page: 1, revision: 'before-midnight', rows: ['old'], summary: { audit: { missing: 1 } }, serverNow: 1000, expiresAt: 11000 }; + const data = { + page: 1, + revision: 'before-midnight', + rows: ['old'], + summary: { audit: { missing: 1 } }, + serverNow: 1000, + expiresAt: 11000, + }; v.requests[0].resolve({ code: 200, data }); await flush(); v.tick(); @@ -292,9 +547,17 @@ test('midnight cancels a hung anomaly refresh and a late reply cannot publish ye }); test('pagination and retry preserve the midnight deadline while their requests remain hung', async () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100, session: 1 }; const leave = v.start(selection, { page: 1 }); - const data = { page: 1, revision: 'old', rows: ['old'], summary: { audit: { missing: 30 } }, serverNow: 1000, expiresAt: 11000 }; + const data = { + page: 1, + revision: 'old', + rows: ['old'], + summary: { audit: { missing: 30 } }, + serverNow: 1000, + expiresAt: 11000, + }; v.requests[0].resolve({ code: 200, data }); await flush(); v.advance(3000); @@ -316,28 +579,56 @@ test('pagination and retry preserve the midnight deadline while their requests r cancelRetry(); }); -for (const status of ['expired', 'unavailable']) test('anomaly ' + status + ' closes the old session without republishing old rows or retrying', async () => { - const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, session: 1 }; - const leave = v.start(selection, { page: 2, revision: 'old' }); - v.requests[0].resolve({ code: 200, data: { status } }); - await flush(); - assert.deepEqual(v.invalidated, [{ selection, reason: status }]); - assert.deepEqual(v.received, []); - assert.deepEqual(v.summaries, []); - assert.equal(v.timers.size, 0); - leave(); - const next = { ...selection, session: 2 }, close = v.start(next, { page: 1 }); - const data = { page: 1, revision: 'new', rows: [], total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } }; - v.requests[1].resolve({ code: 200, data }); - await flush(); - assert.deepEqual(v.received, [data]); - close(); -}); +for (const status of ['expired', 'unavailable']) + test( + 'anomaly ' + + status + + ' closes the old session without republishing old rows or retrying', + async () => { + const v = anomalies(), + selection = { + source: 'system', + kind: 'unconfirmed', + at: 100, + session: 1, + }; + const leave = v.start(selection, { page: 2, revision: 'old' }); + v.requests[0].resolve({ code: 200, data: { status } }); + await flush(); + assert.deepEqual(v.invalidated, [{ selection, reason: status }]); + assert.deepEqual(v.received, []); + assert.deepEqual(v.summaries, []); + assert.equal(v.timers.size, 0); + leave(); + const next = { ...selection, session: 2 }, + close = v.start(next, { page: 1 }); + const data = { + page: 1, + revision: 'new', + rows: [], + total: 0, + summary: { systemAudit: { actualUnconfirmed: 0 } }, + }; + v.requests[1].resolve({ code: 200, data }); + await flush(); + assert.deepEqual(v.received, [data]); + close(); + }, + ); test('an expired response that arrived across midnight cannot be rendered for even one poll', async () => { - const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 }; + const v = anomalies(), + selection = { source: 'panel', kind: 'missing', at: 100 }; const close = v.start(selection, { page: 1 }); - v.requests[0].resolve({ code: 200, data: { serverNow: 1000, expiresAt: 999, summary: { audit: { missing: 7 } }, rows: ['old'] } }); + v.requests[0].resolve({ + code: 200, + data: { + serverNow: 1000, + expiresAt: 999, + summary: { audit: { missing: 7 } }, + rows: ['old'], + }, + }); await flush(); assert.equal(v.invalidated[0].reason, 'expired'); assert.deepEqual(v.received, []); @@ -347,18 +638,37 @@ test('an expired response that arrived across midnight cannot be rendered for ev test('a queued summary update is fenced even when closing and reopening happens before effect cleanup', () => { const file = require.resolve('../../src/pages/dashboard/index.tsx'); - const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync(file, 'utf8'), + ast = ts.createSourceFile( + file, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let callback; function visit(node) { - if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'updateAnomalySummary') + if ( + ts.isVariableDeclaration(node) && + node.name.getText(ast) === 'updateAnomalySummary' + ) callback = node.initializer.arguments[0].getText(ast); ts.forEachChild(node, visit); } visit(ast); assert.ok(callback); - const old = { session: 1 }, next = { session: 2 }, anomalySession = { current: old }, queued = []; - const js = ts.transpile('const update = ' + callback, { target: ts.ScriptTarget.ES2022 }); - const update = Function('anomalySession', 'setOverview', js + '\nreturn update;')(anomalySession, updater => queued.push(updater)); + const old = { session: 1 }, + next = { session: 2 }, + anomalySession = { current: old }, + queued = []; + const js = ts.transpile('const update = ' + callback, { + target: ts.ScriptTarget.ES2022, + }); + const update = Function( + 'anomalySession', + 'setOverview', + js + '\nreturn update;', + )(anomalySession, (updater) => queued.push(updater)); update(old, { audit: { missing: 8 } }); anomalySession.current = next; update(old, { audit: { missing: 9 } }); @@ -369,26 +679,52 @@ test('a queued summary update is fenced even when closing and reopening happens test('an old invalidation cannot close a reopened session or clear its freshly queued summary', () => { const file = require.resolve('../../src/pages/dashboard/index.tsx'); - const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync(file, 'utf8'), + ast = ts.createSourceFile( + file, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let callback; function visit(node) { - if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'invalidateAnomaly') + if ( + ts.isVariableDeclaration(node) && + node.name.getText(ast) === 'invalidateAnomaly' + ) callback = node.initializer.arguments[0].getText(ast); ts.forEachChild(node, visit); } visit(ast); assert.ok(callback); - const old = { session: 1 }, current = { session: 2 }; - const anomalySession = { current }, anomalyVersion = { current: 2 }; - const summaries = [], logs = [], messages = []; + const old = { session: 1 }, + current = { session: 2 }; + const anomalySession = { current }, + anomalyVersion = { current: 2 }; + const summaries = [], + logs = [], + messages = []; let closes = 0; - const bindings = { anomalySession, anomalyVersion, - closeAnomaly() { closes++; anomalySession.current = undefined; }, - setOverview: update => summaries.push(update), setLogCron: update => logs.push(update), - message: { info: text => messages.push(text) }, intl: { get: text => text }, + const bindings = { + anomalySession, + anomalyVersion, + closeAnomaly() { + closes++; + anomalySession.current = undefined; + }, + setOverview: (update) => summaries.push(update), + setLogCron: (update) => logs.push(update), + message: { info: (text) => messages.push(text) }, + intl: { get: (text) => text }, }; - const js = ts.transpile('const invalidate = ' + callback, { target: ts.ScriptTarget.ES2022 }); - const invalidate = Function(...Object.keys(bindings), js + '\nreturn invalidate;')(...Object.values(bindings)); + const js = ts.transpile('const invalidate = ' + callback, { + target: ts.ScriptTarget.ES2022, + }); + const invalidate = Function( + ...Object.keys(bindings), + js + '\nreturn invalidate;', + )(...Object.values(bindings)); invalidate(old, 'unavailable'); assert.equal(closes, 0); assert.equal(summaries.length, 0); @@ -398,7 +734,8 @@ test('an old invalidation cannot close a reopened session or clear its freshly q const next = { session: 3 }; anomalySession.current = next; anomalyVersion.current = 3; - const fresh = { triggers: { audit: { missing: 0 } } }, freshLog = { anomalySession: 3 }; + const fresh = { triggers: { audit: { missing: 0 } } }, + freshLog = { anomalySession: 3 }; assert.strictEqual(summaries[0](fresh), fresh); assert.strictEqual(logs[0](freshLog), freshLog); assert.equal(messages.length, 1); diff --git a/test/front/file-history-races.test.cjs b/test/front/file-history-races.test.cjs index 38cbbaf2..aa5255d0 100644 --- a/test/front/file-history-races.test.cjs +++ b/test/front/file-history-races.test.cjs @@ -46,29 +46,64 @@ const flush = () => new Promise((resolve) => setImmediate(resolve)); const pastCursor = action('components/fileBrowser/index.tsx', 'pastCursor', {}); test('a retry at the top restores the next visible file when the first file was deleted', () => { - const row = (title, top) => ({ title, getBoundingClientRect: () => ({ top, bottom: top + 24 }) }); + const row = (title, top) => ({ + title, + getBoundingClientRect: () => ({ top, bottom: top + 24 }), + }); const element = { - scrollTop: 0, clientHeight: 48, getBoundingClientRect: () => ({ top: 100 }), - querySelectorAll: () => [row('gone', 100), row('survivor', 124), row('below', 148)], - querySelector: selector => selector === 'button[title="survivor"]' ? row('survivor', 364) : null, + scrollTop: 0, + clientHeight: 48, + getBoundingClientRect: () => ({ top: 100 }), + querySelectorAll: () => [ + row('gone', 100), + row('survivor', 124), + row('below', 148), + ], + querySelector: (selector) => + selector === 'button[title="survivor"]' ? row('survivor', 364) : null, }; - const viewport = { current: element }, position = {}; - action('components/fileBrowser/index.tsx', 'rememberPosition', { viewport, position })(); - assert.deepEqual([...position.current.offsets], [['gone', 0], ['survivor', 24]]); + const viewport = { current: element }, + position = {}; + action('components/fileBrowser/index.tsx', 'rememberPosition', { + viewport, + position, + })(); + assert.deepEqual( + [...position.current.offsets], + [ + ['gone', 0], + ['survivor', 24], + ], + ); const emptyListing = { rows: [], next: '', versions: new Map() }; action('components/fileBrowser/index.tsx', 'Entries', { - React: require('react'), emptyListing, Spin: 'i', CSS: { escape: key => key }, - useRef: value => value === null ? viewport : value === undefined ? position : { current: value }, - useState: value => [value, () => {}], useEffect() {}, useLayoutEffect: effect => effect(), + React: require('react'), + emptyListing, + Spin: 'i', + CSS: { escape: (key) => key }, + useRef: (value) => + value === null + ? viewport + : value === undefined + ? position + : { current: value }, + useState: (value) => [value, () => {}], + useEffect() {}, + useLayoutEffect: (effect) => effect(), })({ source: 'logs', path: '', search: '' }); assert.equal(element.scrollTop, 240); assert.equal(position.current, undefined); }); test('a new execution has its own title before its log path arrives', () => { - const readableLogName = action('components/fileBrowser/name.ts', 'readableLogName', {}); + const readableLogName = action( + 'components/fileBrowser/name.ts', + 'readableLogName', + {}, + ); const title = action('pages/crontab/detail.tsx', 'instanceTitle', { - readableLogName, intl: { get: (key, { id }) => key.replace('{id}', id) }, + readableLogName, + intl: { get: (key, { id }) => key.replace('{id}', id) }, }); const next = { id: 34834, status: 0, log_path: null }; const stopped = { id: 34814, status: 2, log_path: 'task/old.log' }; @@ -79,17 +114,34 @@ test('a new execution has its own title before its log path arrives', () => { test('file rows preserve meaningful suffixes, separate the search directory and expose the full path', () => { const React = require('react'); - const names = ['async_components___init__', 'async_components_register.js', '中文任务_同步明细.log']; - const rows = names.map(title => ({ title, parent: 'workers', key: 'workers/' + title, type: 'file' })); + const names = [ + 'async_components___init__', + 'async_components_register.js', + '中文任务_同步明细.log', + ]; + const rows = names.map((title) => ({ + title, + parent: 'workers', + key: 'workers/' + title, + type: 'file', + })); const emptyListing = { rows, next: '', versions: new Map() }; const entries = action('components/fileBrowser/index.tsx', 'Entries', { - React, useRef: current => ({ current }), useState: value => [value, () => {}], useEffect() {}, useLayoutEffect() {}, - emptyListing, FileOutlined: 'i', Spin: 'i', Typography: { Text: 'span' }, readableLogName: value => value, + React, + useRef: (current) => ({ current }), + useState: (value) => [value, () => {}], + useEffect() {}, + useLayoutEffect() {}, + emptyListing, + FileOutlined: 'i', + Spin: 'i', + Typography: { Text: 'span' }, + readableLogName: (value) => value, })({ source: 'logs', path: '', search: 'work' }).props.children[0]; const tails = ['___init__', '_register.js', '_同步明细.log']; for (const [i, button] of entries.entries()) { const [name, parent] = button.props.children[1].props.children; - const parts = name.props.children.map(span => span.props.children); + const parts = name.props.children.map((span) => span.props.children); assert.equal(parts.join(''), names[i]); assert.equal(parts[1], tails[i]); assert.equal(parent.props.children, 'workers'); @@ -101,24 +153,53 @@ test('file rows preserve meaningful suffixes, separate the search directory and for (const remaining of [0, 2, 8]) { test(`manual retry retains the requested depth through churn and a network error with ${remaining} files left`, async () => { const emptyListing = { rows: [], next: '', versions: new Map() }; - const listing = { current: { rows: [0, 1, 2, 3], next: '4', versions: new Map([['a', '1']]) } }; - const states = [], failures = []; - let checks = 0, reads = 0, phase = 'churn'; + const listing = { + current: { + rows: [0, 1, 2, 3], + next: '4', + versions: new Map([['a', '1']]), + }, + }; + const states = [], + failures = []; + let checks = 0, + reads = 0, + phase = 'churn'; const read = action('components/fileBrowser/index.tsx', 'read', { - pastCursor, rememberPosition() {}, - listing, emptyListing, pending: {}, path: 'a', source: 'scripts', search: '', folders: false, - config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v), - setListing: page => states.push(page.rows), + pastCursor, + rememberPosition() {}, + listing, + emptyListing, + pending: {}, + path: 'a', + source: 'scripts', + search: '', + folders: false, + config: { apiPrefix: '/api/' }, + setLoading() {}, + setFailed: (v) => failures.push(v), + setListing: (page) => states.push(page.rows), request: { async get(_url, { params }) { reads++; if (phase === 'offline') throw new Error('network unavailable'); const count = phase === 'churn' ? 8 : remaining; const offset = Number(params.after); - const data = Array.from({ length: Math.min(2, count - offset) }, (_, i) => offset + i); - return { code: 200, data, next: offset + 2 < count ? String(offset + 2) : null, versions: [['a', '1']] }; + const data = Array.from( + { length: Math.min(2, count - offset) }, + (_, i) => offset + i, + ); + return { + code: 200, + data, + next: offset + 2 < count ? String(offset + 2) : null, + versions: [['a', '1']], + }; + }, + async post() { + checks++; + return { code: 200, current: phase === 'stable' }; }, - async post() { checks++; return { code: 200, current: phase === 'stable' }; }, }, }); await read(listing.current); @@ -135,7 +216,10 @@ for (const remaining of [0, 2, 8]) { phase = 'stable'; await Promise.all([read(retry), read(retry)]); const count = Math.min(6, remaining); - assert.deepEqual(listing.current.rows, Array.from({ length: count }, (_, i) => i)); + assert.deepEqual( + listing.current.rows, + Array.from({ length: count }, (_, i) => i), + ); assert.equal(listing.current.next, remaining > count ? String(count) : ''); const completedReads = reads; await read(retry); @@ -149,21 +233,44 @@ for (const [source, search, boundary, cursors] of [ // DFS enters directory "a" before visiting sibling "a-". ['logs', 'needle', 'a-', ['a/1', 'a/2', 'a/3', 'a/x', 'a.', 'z']], ]) { - test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${search || 'directory'})`, async () => { + test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${ + search || 'directory' + })`, async () => { const emptyListing = { rows: [], next: '', versions: new Map() }; - const listing = { current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() } }; + const listing = { + current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() }, + }; const failures = []; let stable = false; const read = action('components/fileBrowser/index.tsx', 'read', { - pastCursor, rememberPosition() {}, listing, emptyListing, pending: {}, source, path: '', search, folders: false, - config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v), setListing() {}, + pastCursor, + rememberPosition() {}, + listing, + emptyListing, + pending: {}, + source, + path: '', + search, + folders: false, + config: { apiPrefix: '/api/' }, + setLoading() {}, + setFailed: (v) => failures.push(v), + setListing() {}, request: { async get(_url, { params }) { - const index = params.after === boundary ? 4 : cursors.indexOf(params.after) + 1; + const index = + params.after === boundary ? 4 : cursors.indexOf(params.after) + 1; assert.ok(index < cursors.length); - return { code: 200, next: cursors[index], data: search && index === 3 ? [] : [cursors[index]], versions: [['', '1']] }; + return { + code: 200, + next: cursors[index], + data: search && index === 3 ? [] : [cursors[index]], + versions: [['', '1']], + }; + }, + async post() { + return { code: 200, current: stable }; }, - async post() { return { code: 200, current: stable }; }, }, }); await read(listing.current); @@ -173,53 +280,119 @@ for (const [source, search, boundary, cursors] of [ await read(listing.current); assert.equal(failures.at(-1), false); assert.equal(listing.current.next, cursors[4]); - assert.deepEqual(listing.current.rows, cursors.slice(0, 5).filter((_, i) => !search || i !== 3)); + assert.deepEqual( + listing.current.rows, + cursors.slice(0, 5).filter((_, i) => !search || i !== 3), + ); }); } test('loading more rebuilds the original depth if a delayed last page missed a move into a previous directory', async () => { const pages = [ { data: ['c/old'], next: null, versions: [['c', '1']] }, - { data: ['a/moved', 'b/kept'], next: 'b/kept', versions: [['a', '2'], ['b', '1']] }, + { + data: ['a/moved', 'b/kept'], + next: 'b/kept', + versions: [ + ['a', '2'], + ['b', '1'], + ], + }, { data: ['c/new'], next: null, versions: [['c', '2']] }, ]; - const cursors = [], checks = [], commits = [], emptyListing = { rows: [], next: '', versions: new Map() }; - const listing = { current: { rows: ['a/deleted', 'b/kept'], next: 'b/kept', versions: new Map([['a', '1'], ['b', '1']]) } }; + const cursors = [], + checks = [], + commits = [], + emptyListing = { rows: [], next: '', versions: new Map() }; + const listing = { + current: { + rows: ['a/deleted', 'b/kept'], + next: 'b/kept', + versions: new Map([ + ['a', '1'], + ['b', '1'], + ]), + }, + }; const read = action('components/fileBrowser/index.tsx', 'read', { - pastCursor, rememberPosition() {}, - pending: {}, listing, emptyListing, source: 'logs', path: '', search: 'match', - folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value.rows), - setLoading() {}, setFailed(value) { assert.equal(value, false); }, + pastCursor, + rememberPosition() {}, + pending: {}, + listing, + emptyListing, + source: 'logs', + path: '', + search: 'match', + folders: false, + config: { apiPrefix: '/api/' }, + setListing: (value) => commits.push(value.rows), + setLoading() {}, + setFailed(value) { + assert.equal(value, false); + }, request: { - async get(_url, { params }) { cursors.push(params.after); return { code: 200, ...pages.shift() }; }, - async post(_url, stamps) { checks.push(Object.fromEntries(stamps)); return { code: 200, current: checks.length > 1 }; }, + async get(_url, { params }) { + cursors.push(params.after); + return { code: 200, ...pages.shift() }; + }, + async post(_url, stamps) { + checks.push(Object.fromEntries(stamps)); + return { code: 200, current: checks.length > 1 }; + }, }, }); const previous = listing.current; await read(previous); await read(previous); // A late second click from the previous render. assert.deepEqual(cursors, ['b/kept', '', 'b/kept']); - assert.deepEqual(checks, [{ a: '1', b: '1', c: '1' }, { a: '2', b: '1', c: '2' }]); + assert.deepEqual(checks, [ + { a: '1', b: '1', c: '1' }, + { a: '2', b: '1', c: '2' }, + ]); assert.deepEqual(commits, [[], ['a/moved', 'b/kept', 'c/new']]); }); for (const retrying of [false, true]) { - test(`abandoning a search discards its delayed validation during ${retrying ? 'manual retry' : 'initial load'}`, async () => { - const pending = {}, commits = []; + test(`abandoning a search discards its delayed validation during ${ + retrying ? 'manual retry' : 'initial load' + }`, async () => { + const pending = {}, + commits = []; const emptyListing = { rows: [], next: '', versions: new Map() }; - const previous = retrying ? { ...emptyListing, retryMinimum: 2 } : emptyListing; - let finish, reads = 0; + const previous = retrying + ? { ...emptyListing, retryMinimum: 2 } + : emptyListing; + let finish, + reads = 0; const read = action('components/fileBrowser/index.tsx', 'read', { - pastCursor, rememberPosition() {}, - pending, listing: { current: previous }, emptyListing, source: 'scripts', path: '', search: 'old', - folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value), - setLoading() {}, setFailed() {}, + pastCursor, + rememberPosition() {}, + pending, + listing: { current: previous }, + emptyListing, + source: 'scripts', + path: '', + search: 'old', + folders: false, + config: { apiPrefix: '/api/' }, + setListing: (value) => commits.push(value), + setLoading() {}, + setFailed() {}, request: { async get() { reads++; - return { code: 200, data: [`old-${reads}.js`], next: reads === 1 ? 'more' : null, versions: [['', '1']] }; + return { + code: 200, + data: [`old-${reads}.js`], + next: reads === 1 ? 'more' : null, + versions: [['', '1']], + }; + }, + post() { + return new Promise((resolve) => { + finish = resolve; + }); }, - post() { return new Promise(resolve => { finish = resolve; }); }, }, }); const loading = read(previous); @@ -237,11 +410,27 @@ test('directory navigation shows the current path separately and returns exactly for (const source of ['scripts', 'logs']) { let directory = 'parent/child'; const render = (input = '') => { - const states = [[directory, next => { directory = next; }], [input, () => {}], [input, () => {}]]; + const states = [ + [ + directory, + (next) => { + directory = next; + }, + ], + [input, () => {}], + [input, () => {}], + ]; return action('components/fileBrowser/index.tsx', 'FileBrowser', { - React, Entries: 'div', Spin: 'span', ArrowUpOutlined: 'i', Button: 'button', - Input: { Search: 'input' }, Typography: { Text: 'span' }, intl: { get: key => key }, - useEffect() {}, useState: () => states.shift(), + React, + Entries: 'div', + Spin: 'span', + ArrowUpOutlined: 'i', + Button: 'button', + Input: { Search: 'input' }, + Typography: { Text: 'span' }, + intl: { get: (key) => key }, + useEffect() {}, + useState: () => states.shift(), })({ source }).props.children[1]; }; assert.ok(!render('query')); @@ -336,7 +525,7 @@ test('expanded history retains its cursor and original head during inserts and r pending, paging, visibleIds, - list: { current: { scrollTo: position => scrolls.push(position) } }, + list: { current: { scrollTo: (position) => scrolls.push(position) } }, pageSize: 2, config: { apiPrefix: '/api/' }, id: 1, @@ -356,13 +545,20 @@ test('expanded history retains its cursor and original head during inserts and r await reading; reading = load('older'); await load('older'); - assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 }); + assert.deepEqual(request.calls.at(-1).config.params, { + paged: true, + limit: 2, + before: 3, + }); assert.equal(request.calls.length, 2); request.calls.at(-1).reject(new Error('older request interrupted')); await reading; assert.equal(failure, 'older'); reading = load('refresh'); - assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 1 }); + assert.deepEqual(request.calls.at(-1).config.params, { + paged: true, + limit: 1, + }); answer([5], null); await flush(); answer([3], null); @@ -370,13 +566,20 @@ test('expanded history retains its cursor and original head during inserts and r assert.equal(state.current.hasNew, true); assert.equal(failure, 'older'); reading = load(failure); - assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 }); + assert.deepEqual(request.calls.at(-1).config.params, { + paged: true, + limit: 2, + before: 3, + }); answer([2, 1], null); await reading; reading = load('refresh'); answer([6], null); await flush(); - assert.deepEqual(request.calls.at(-1).config.params, { paged: true, ids: '3' }); + assert.deepEqual(request.calls.at(-1).config.params, { + paged: true, + ids: '3', + }); answer([3], null); await reading; assert.deepEqual( diff --git a/test/front/http-auth.test.cjs b/test/front/http-auth.test.cjs index ce20c4fb..4f1cad32 100644 --- a/test/front/http-auth.test.cjs +++ b/test/front/http-auth.test.cjs @@ -152,12 +152,27 @@ test('healthy bootstrap continues loading system information', async () => { }); test('retryable panel reads retain their route on gateway failures and still enforce login expiry', async () => { - for (const [status, retryInPlace, expected] of [[502, true, []], [504, true, []], - [502, false, ['/error']], [401, true, ['/login']]]) { - const {request, pushes} = fixture('/crontab'); - await assert.rejects(request.get('/api/crons/1/triggers', {retryInPlace, adapter: async config => { - throw new axios.AxiosError('failed', 'ERR_BAD_RESPONSE', config, null, {status, config, data: {}}); - }})); + for (const [status, retryInPlace, expected] of [ + [502, true, []], + [504, true, []], + [502, false, ['/error']], + [401, true, ['/login']], + ]) { + const { request, pushes } = fixture('/crontab'); + await assert.rejects( + request.get('/api/crons/1/triggers', { + retryInPlace, + adapter: async (config) => { + throw new axios.AxiosError( + 'failed', + 'ERR_BAD_RESPONSE', + config, + null, + { status, config, data: {} }, + ); + }, + }), + ); assert.deepEqual(pushes, expected); } }); diff --git a/test/front/script-history-save.test.cjs b/test/front/script-history-save.test.cjs index 3cddfc23..2e32506c 100644 --- a/test/front/script-history-save.test.cjs +++ b/test/front/script-history-save.test.cjs @@ -6,19 +6,44 @@ const load = require('../helpers/load-security-module.cjs'); test('debugger keeps the selected script when an older read completes after it', async () => { const ts = require('typescript'); const file = path.resolve(__dirname, '../../src/pages/script/editModal.tsx'); - const source = ts.createSourceFile(file, require('fs').readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true); + const source = ts.createSourceFile( + file, + require('fs').readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true, + ); let read; function visit(node) { - if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'getDetail') + if ( + ts.isVariableDeclaration(node) && + node.name.getText(source) === 'getDetail' + ) read = node.initializer.getText(source); ts.forEachChild(node, visit); } visit(source); - const js = ts.transpile('const read = ' + read, { target: ts.ScriptTarget.ES2022 }); - const responses = [], ready = [], contents = []; - const get = Function('request', 'pendingFile', 'setFileReady', 'setValue', 'config', js + '\nreturn read;')( - { get: (_url, { signal }) => new Promise(resolve => responses.push({ resolve, signal })) }, - { current: undefined }, state => ready.push(state), text => contents.push(text), { apiPrefix: '/api/' }, + const js = ts.transpile('const read = ' + read, { + target: ts.ScriptTarget.ES2022, + }); + const responses = [], + ready = [], + contents = []; + const get = Function( + 'request', + 'pendingFile', + 'setFileReady', + 'setValue', + 'config', + js + '\nreturn read;', + )( + { + get: (_url, { signal }) => + new Promise((resolve) => responses.push({ resolve, signal })), + }, + { current: undefined }, + (state) => ready.push(state), + (text) => contents.push(text), + { apiPrefix: '/api/' }, ); get({ title: 'slow.js' }); get({ title: 'current.js' }); diff --git a/test/front/trigger-history-refresh.test.cjs b/test/front/trigger-history-refresh.test.cjs index bb50c826..465d41a8 100644 --- a/test/front/trigger-history-refresh.test.cjs +++ b/test/front/trigger-history-refresh.test.cjs @@ -6,27 +6,59 @@ const ts = require('typescript'); const { createTriggerPoll } = require('../../src/pages/crontab/triggerUpdates'); // Run one tick to settlement for the filtering and single-round tests. -async function refreshExpandedHistory(rows, head, read, active, onHead, onBatch, open = new Set()) { +async function refreshExpandedHistory( + rows, + head, + read, + active, + onHead, + onBatch, + open = new Set(), +) { let failed = false; - createTriggerPoll(head, read, active, onHead, onBatch, value => { failed = value; }, open)(rows); - await new Promise(resolve => setImmediate(resolve)); + createTriggerPoll( + head, + read, + active, + onHead, + onBatch, + (value) => { + failed = value; + }, + open, + )(rows); + await new Promise((resolve) => setImmediate(resolve)); return !failed; } const entry = (id, state = 'finished', reason) => ({ - id: String(id), observed_at: 100, state, reason, + id: String(id), + observed_at: 100, + state, + reason, }); test('expanded terminal history checks for new triggers without fetching stable rows', async () => { for (const [latest, expected] of [ - [[], false], [[entry('a')], false], [[entry('b')], true], + [[], false], + [[entry('a')], false], + [[entry('b')], true], [[{ ...entry('0'), observed_at: 101 }], true], ]) { let notice; - const ok = await refreshExpandedHistory([entry('a')], entry('a'), async params => { - assert.equal(params.toString(), 'limit=1'); - return latest; - }, () => true, newer => { notice = newer; }, assert.fail); + const ok = await refreshExpandedHistory( + [entry('a')], + entry('a'), + async (params) => { + assert.equal(params.toString(), 'limit=1'); + return latest; + }, + () => true, + (newer) => { + notice = newer; + }, + assert.fail, + ); assert.equal(ok, true); assert.equal(notice, expected); } @@ -34,35 +66,67 @@ test('expanded terminal history checks for new triggers without fetching stable test('refreshes recovered receipts and applies successful batches even if another request fails', async () => { const rows = Array.from({ length: 25 }, (_, i) => entry(i, 'running')); - rows.push(entry('replay', 'skipped', 'restart'), entry('late', 'unknown', 'restart'), - entry('wait', 'queued'), entry('done'), entry('skipped', 'skipped', 'changed')); + rows.push( + entry('replay', 'skipped', 'restart'), + entry('late', 'unknown', 'restart'), + entry('wait', 'queued'), + entry('done'), + entry('skipped', 'skipped', 'changed'), + ); for (const failing of [true, false]) { const applied = []; - const ok = await refreshExpandedHistory(rows, rows[0], async params => { - const ids = params.getAll('ids'); - if (failing && (!ids.length || ids.includes('0'))) throw new Error('temporary'); - return ids.filter(id => id !== 'late').map(id => entry(id)); - }, () => true, () => {}, (ids, updated) => applied.push([ids, updated.map(row => row.id)])); + const ok = await refreshExpandedHistory( + rows, + rows[0], + async (params) => { + const ids = params.getAll('ids'); + if (failing && (!ids.length || ids.includes('0'))) + throw new Error('temporary'); + return ids.filter((id) => id !== 'late').map((id) => entry(id)); + }, + () => true, + () => {}, + (ids, updated) => applied.push([ids, updated.map((row) => row.id)]), + ); assert.equal(ok, !failing); assert.equal(applied.length, failing ? 1 : 2); - assert.deepEqual(applied.at(-1), [['replay', 'late', 'wait'], ['replay', 'wait']]); + assert.deepEqual(applied.at(-1), [ + ['replay', 'late', 'wait'], + ['replay', 'wait'], + ]); } }); test('an in-flight response after leaving expanded history cannot update the page', async () => { let active = true; let calls = 0; - await refreshExpandedHistory([entry('r', 'running')], entry('a'), async params => { - calls++; - if (params.has('ids')) active = false; - return [entry('b')]; - }, () => active, () => {}, assert.fail); + await refreshExpandedHistory( + [entry('r', 'running')], + entry('a'), + async (params) => { + calls++; + if (params.has('ids')) active = false; + return [entry('b')]; + }, + () => active, + () => {}, + assert.fail, + ); assert.equal(calls, 2); }); // Run the component's actual action and refresh handlers against controlled requests. -const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/detail.tsx'), 'utf8'); -const ast = ts.createSourceFile('detail.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/detail.tsx'), + 'utf8', +); +const ast = ts.createSourceFile( + 'detail.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, +); function handler(name, bindings) { let body; function visit(node) { @@ -71,22 +135,40 @@ function handler(name, bindings) { ts.forEachChild(node, visit); } visit(ast); - const js = ts.transpileModule('const implementation = ' + body, { fileName: 'handler.tsx', - compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText; - return Function(...Object.keys(bindings), js + '\nreturn implementation;')(...Object.values(bindings)); + const js = ts.transpileModule('const implementation = ' + body, { + fileName: 'handler.tsx', + compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }, + }).outputText; + return Function( + ...Object.keys(bindings), + js + '\nreturn implementation;', + )(...Object.values(bindings)); } test('fresh task status survives an older detail poll without reading all instances', async () => { let task; const pending = []; const refresh = handler('refreshDetails', { - cron: { id: 7 }, config: { apiPrefix: '/api/' }, refreshVersion: { current: 0 }, session: {current: new AbortController()}, setRefreshFailed() {}, - request: { get(url) { return new Promise(resolve => pending.push({ url, resolve })); } }, - setCurrentCron: value => { task = value; }, + cron: { id: 7 }, + config: { apiPrefix: '/api/' }, + refreshVersion: { current: 0 }, + session: { current: new AbortController() }, + setRefreshFailed() {}, + request: { + get(url) { + return new Promise((resolve) => pending.push({ url, resolve })); + }, + }, + setCurrentCron: (value) => { + task = value; + }, }); const old = refresh(); const fresh = refresh(); - assert.deepEqual(pending.map(q => q.url), ['/api/crons/7', '/api/crons/7']); + assert.deepEqual( + pending.map((q) => q.url), + ['/api/crons/7', '/api/crons/7'], + ); pending[1].resolve({ code: 200, data: { status: 3 } }); await fresh; pending[0].resolve({ code: 200, data: { status: 0 } }); @@ -95,9 +177,18 @@ test('fresh task status survives an older detail poll without reading all instan }); test('opening a historical log preserves the filename and lets the log reader issue the first request', () => { - let selected, opened = false; - const open = handler('viewInstanceLog', { cron: {id: 7}, config: { apiPrefix: '/api/' }, URLSearchParams, - setLogUrl(url) { selected = url; }, setIsLogModalVisible(value) { opened = value; }, + let selected, + opened = false; + const open = handler('viewInstanceLog', { + cron: { id: 7 }, + config: { apiPrefix: '/api/' }, + URLSearchParams, + setLogUrl(url) { + selected = url; + }, + setIsLogModalVisible(value) { + opened = value; + }, }); open({ log_path: 'a & b/x#+%&.log' }); assert.equal(opened, true); @@ -111,31 +202,75 @@ test('opening a historical log preserves the filename and lets the log reader is }); test('cancelled page load cannot append, replace the cursor or restart its timer after a task switch', async () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); const effects = []; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' && - node.arguments[1]?.getText(tree).includes('before')) effects.push(node.arguments[0]); + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' && + node.arguments[1]?.getText(tree).includes('before') + ) + effects.push(node.arguments[0]); ts.forEachChild(node, visit); } visit(tree); assert.equal(effects.length, 1); - const compiled = ts.transpile('const effect = ' + effects[0].getText(tree), {target: ts.ScriptTarget.ES2022}); - let rows = [], cursor; - const pending = [], timers = new Set(); + const compiled = ts.transpile('const effect = ' + effects[0].getText(tree), { + target: ts.ScriptTarget.ES2022, + }); + let rows = [], + cursor; + const pending = [], + timers = new Set(); const bindings = { - config: {apiPrefix: '/api/'}, pageSize: 25, pageRequest: {}, paused: false, - request: { get(url, options) { return new Promise(resolve => pending.push({url, options, resolve})); } }, - setRows(fn) { rows = fn(rows); }, setLoading() {}, setFailed() {}, setNextCursor(row) { cursor = row; }, - setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); }, + config: { apiPrefix: '/api/' }, + pageSize: 25, + pageRequest: {}, + paused: false, + request: { + get(url, options) { + return new Promise((resolve) => + pending.push({ url, options, resolve }), + ); + }, + }, + setRows(fn) { + rows = fn(rows); + }, + setLoading() {}, + setFailed() {}, + setNextCursor(row) { + cursor = row; + }, + setTimeout(fn) { + timers.add(fn); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, }; - const start = Function('id', 'before', ...Object.keys(bindings), compiled + '\nreturn effect();'); + const start = Function( + 'id', + 'before', + ...Object.keys(bindings), + compiled + '\nreturn effect();', + ); const begin = (id, before) => start(id, before, ...Object.values(bindings)); - const flush = () => new Promise(resolve => setImmediate(resolve)); - const page = Array.from({length: 26}, (_, i) => entry('A' + i)); + const flush = () => new Promise((resolve) => setImmediate(resolve)); + const page = Array.from({ length: 26 }, (_, i) => entry('A' + i)); const stopFirst = begin(1, null); - pending[0].resolve({data: page}); + pending[0].resolve({ data: page }); await flush(); assert.equal(rows.length, 25); stopFirst(); @@ -143,35 +278,67 @@ test('cancelled page load cannot append, replace the cursor or restart its timer assert.equal(pending[1].options.params.beforeId, 'A24'); stopOlder(); const stopB = begin(2, null); - pending[2].resolve({data: [entry('B')]}); + pending[2].resolve({ data: [entry('B')] }); await flush(); - pending[1].resolve({data: page}); + pending[1].resolve({ data: page }); await flush(); - assert.deepEqual(rows.map(row => row.id), ['B']); + assert.deepEqual( + rows.map((row) => row.id), + ['B'], + ); assert.equal(cursor, null); assert.equal(timers.size, 1); stopB(); }); test('multiple clicks before React commits the loading state admit just one page transition', () => { - const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const ast = ts.createSourceFile('triggerList.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const ast = ts.createSourceFile( + 'triggerList.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let body; function visit(node) { - if (ts.isJsxAttribute(node) && node.name.getText(ast) === 'onClick' && - node.initializer?.getText(ast).includes('setBefore(nextCursor)')) body = node.initializer.expression.getText(ast); + if ( + ts.isJsxAttribute(node) && + node.name.getText(ast) === 'onClick' && + node.initializer?.getText(ast).includes('setBefore(nextCursor)') + ) + body = node.initializer.expression.getText(ast); ts.forEachChild(node, visit); } visit(ast); assert.ok(body); - const compiled = ts.transpile('const click = ' + body, {target: ts.ScriptTarget.ES2022}); + const compiled = ts.transpile('const click = ' + body, { + target: ts.ScriptTarget.ES2022, + }); const controller = new AbortController(); - const cursor = entry('tail'), transitions = []; - const bindings = {loading: false, pageRequest: {current: controller}, expanded: false, - rows: [entry('head')], headRef: {}, failed: false, nextCursor: cursor, - setBefore: value => transitions.push(value), setLoading() {}}; - const click = Function(...Object.keys(bindings), compiled + '\nreturn click;')(...Object.values(bindings)); - click(); click(); click(); + const cursor = entry('tail'), + transitions = []; + const bindings = { + loading: false, + pageRequest: { current: controller }, + expanded: false, + rows: [entry('head')], + headRef: {}, + failed: false, + nextCursor: cursor, + setBefore: (value) => transitions.push(value), + setLoading() {}, + }; + const click = Function( + ...Object.keys(bindings), + compiled + '\nreturn click;', + )(...Object.values(bindings)); + click(); + click(); + click(); assert.deepEqual(transitions, [cursor]); assert.ok(controller.signal.aborted); }); @@ -180,42 +347,59 @@ test('an operation completing after closing the task cannot launch another detai const controller = new AbortController(); const resolveReads = []; const refresh = handler('refreshDetails', { - cron: {id: 1}, config: {apiPrefix: '/api/'}, refreshVersion: {current: 0}, - session: {current: controller}, setRefreshFailed: assert.fail, - setCurrentCron: assert.fail, setRunningInstances: assert.fail, - request: {get(url, {signal}) { - assert.equal(signal, controller.signal); - return new Promise(resolve => resolveReads.push(resolve)); - }}, + cron: { id: 1 }, + config: { apiPrefix: '/api/' }, + refreshVersion: { current: 0 }, + session: { current: controller }, + setRefreshFailed: assert.fail, + setCurrentCron: assert.fail, + setRunningInstances: assert.fail, + request: { + get(url, { signal }) { + assert.equal(signal, controller.signal); + return new Promise((resolve) => resolveReads.push(resolve)); + }, + }, }); const old = refresh(); controller.abort(); await refresh(); assert.equal(resolveReads.length, 1); - resolveReads.forEach(resolve => resolve({code: 200, data: 'old'})); + resolveReads.forEach((resolve) => resolve({ code: 200, data: 'old' })); await old; }); test('failed script read remains unavailable until a retry successfully loads the selected file', async () => { const controller = new AbortController(); - const states = [], values = []; - let response = Promise.resolve({code: 500, data: ''}); + const states = [], + values = []; + let response = Promise.resolve({ code: 500, data: '' }); const get = handler('getScript', { - cron: {command: 'test'}, session: {current: controller}, getCommandScript: () => ['a#b.sh', 'dir'], - config: {apiPrefix: '/api/'}, tabList: [], setValidTabs() {}, setScriptInfo() {}, - setScriptState: state => states.push(state), setValue: value => values.push(value), - request: {get(url, options) { - assert.equal(url, '/api/scripts/detail'); - assert.equal(options.params.file, 'a#b.sh'); - assert.equal(options.signal, controller.signal); - return response; - }}, + cron: { command: 'test' }, + session: { current: controller }, + getCommandScript: () => ['a#b.sh', 'dir'], + config: { apiPrefix: '/api/' }, + tabList: [], + setValidTabs() {}, + setScriptInfo() {}, + setScriptState: (state) => states.push(state), + setValue: (value) => values.push(value), + request: { + get(url, options) { + assert.equal(url, '/api/scripts/detail'); + assert.equal(options.params.file, 'a#b.sh'); + assert.equal(options.signal, controller.signal); + return response; + }, + }, }); - get(); await new Promise(resolve => setImmediate(resolve)); - assert.deepEqual(states, ['loading','failed']); + get(); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(states, ['loading', 'failed']); assert.deepEqual(values, []); - response = Promise.resolve({code: 200, data: 'loaded'}); - get(); await new Promise(resolve => setImmediate(resolve)); + response = Promise.resolve({ code: 200, data: 'loaded' }); + get(); + await new Promise((resolve) => setImmediate(resolve)); assert.equal(states.at(-1), 'ready'); assert.deepEqual(values, ['loaded']); }); @@ -223,7 +407,7 @@ test('failed script read remains unavailable until a retry successfully loads th test('switching to trigger history refreshes the task header without waiting for the next poll', () => { const events = []; const change = handler('onTabChange', { - setActiveTabKey: key => events.push(key), + setActiveTabKey: (key) => events.push(key), refreshDetails: () => events.push('refresh'), }); change('triggers'); @@ -231,14 +415,32 @@ test('switching to trigger history refreshes the task header without waiting for }); test('dashboard live rows open the clicked instance even when the task ID is shared', () => { - const source = fs.readFileSync(path.join(__dirname, '../../src/pages/dashboard/index.tsx'), 'utf8'); - const tree = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/dashboard/index.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'dashboard.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let click, url; function visit(node) { - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onClick' && - node.initializer?.expression?.getText(tree).includes('setLogCron({')) click = node.initializer.expression; - if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(tree) === 'CronLogModal') { - url = node.attributes.properties.find(p => p.name?.getText(tree) === 'logUrl')?.initializer.expression; + if ( + ts.isJsxAttribute(node) && + node.name.getText(tree) === 'onClick' && + node.initializer?.expression?.getText(tree).includes('setLogCron({') + ) + click = node.initializer.expression; + if ( + ts.isJsxSelfClosingElement(node) && + node.tagName.getText(tree) === 'CronLogModal' + ) { + url = node.attributes.properties.find( + (p) => p.name?.getText(tree) === 'logUrl', + )?.initializer.expression; } ts.forEachChild(node, visit); } @@ -246,20 +448,45 @@ test('dashboard live rows open the clicked instance even when the task ID is sha assert.ok(click && url); for (const instanceId of [41, 42]) { let selection; - Function('setLogCron', 'record', 'id', '(' + click.getText(tree) + ')()')( - value => { selection = value; }, { name: 'concurrent', instanceId }, 7); - const endpoint = Function('config', 'logCron', 'return ' + url.getText(tree))({ apiPrefix: '/api/' }, selection); + Function( + 'setLogCron', + 'record', + 'id', + '(' + click.getText(tree) + ')()', + )( + (value) => { + selection = value; + }, + { name: 'concurrent', instanceId }, + 7, + ); + const endpoint = Function( + 'config', + 'logCron', + 'return ' + url.getText(tree), + )({ apiPrefix: '/api/' }, selection); assert.equal(endpoint, '/api/crons/7/log?instanceId=' + instanceId); } }); test('a double click opens a single stop confirmation and natural completion refreshes the selected task', async () => { - const dialogs = [], messages = [], requests = []; + const dialogs = [], + messages = [], + requests = []; const open = handler('stopRunningInstance', { - stopDialogs: { current: new Set() }, Modal: { confirm: opts => dialogs.push(opts) }, - React: require('react'), intl: { get: text => text }, cron: { id: 7 }, config: { apiPrefix: '/api/' }, - request: { post: async url => { requests.push(url); return { code: 200, data: { outcome: 'ended' } }; } }, - message: { info: text => messages.push(text), success: assert.fail }, + stopDialogs: { current: new Set() }, + Modal: { confirm: (opts) => dialogs.push(opts) }, + React: require('react'), + intl: { get: (text) => text }, + cron: { id: 7 }, + config: { apiPrefix: '/api/' }, + request: { + post: async (url) => { + requests.push(url); + return { code: 200, data: { outcome: 'ended' } }; + }, + }, + message: { info: (text) => messages.push(text), success: assert.fail }, refreshAfterChange: () => messages.push('refresh'), }); open({ id: 11, pid: 101 }); @@ -279,14 +506,18 @@ test('retrying the same stop confirmation retains its key and selections, and a const sent = []; const notices = []; const { createStopRequest } = load('src/pages/crontab/stopRequest.ts', { - antd: { message: { error: m => notices.push(m) } }, - 'react-intl-universal': { get: s => s }, + antd: { message: { error: (m) => notices.push(m) } }, + 'react-intl-universal': { get: (s) => s }, '@/utils/config': { apiPrefix: '/api/' }, - '@/utils/http': { request: { put: async (url, ids, options) => { - sent.push([url, [...ids], options.headers['Idempotency-Key']]); - if (sent.length === 1) throw Error('connection lost'); - return { code: 200 }; - } } }, + '@/utils/http': { + request: { + put: async (url, ids, options) => { + sent.push([url, [...ids], options.headers['Idempotency-Key']]); + if (sent.length === 1) throw Error('connection lost'); + return { code: 200 }; + }, + }, + }, }); const ids = [3, 1]; const confirm = createStopRequest(ids); @@ -303,11 +534,21 @@ test('retrying the same stop confirmation retains its key and selections, and a test('expanded history refreshes a pending exit until the repaired result replaces it', async () => { let rows = [entry('older', 'unknown', 'exit_pending'), entry('stable')]; const requested = []; - const refresh = () => refreshExpandedHistory(rows, rows[0], async params => { - if (!params.has('ids')) return [rows[0]]; - requested.push(params.getAll('ids')); - return [entry('older', 'failed')]; - }, () => true, () => {}, (_, updates) => { rows = [updates[0], rows[1]]; }); + const refresh = () => + refreshExpandedHistory( + rows, + rows[0], + async (params) => { + if (!params.has('ids')) return [rows[0]]; + requested.push(params.getAll('ids')); + return [entry('older', 'failed')]; + }, + () => true, + () => {}, + (_, updates) => { + rows = [updates[0], rows[1]]; + }, + ); await refresh(); await refresh(); assert.deepEqual(requested, [['older']]); @@ -315,46 +556,98 @@ test('expanded history refreshes a pending exit until the repaired result replac }); test('expanded history follows a booked legacy exit through dispute and definitive resolution', async () => { - let rows = [{ ...entry('old', 'finished'), legacy_exit_booking: 1 }, entry('sibling', 'finished')]; + let rows = [ + { ...entry('old', 'finished'), legacy_exit_booking: 1 }, + entry('sibling', 'finished'), + ]; const requests = []; - for (const next of [entry('old', 'unknown', 'exit_conflict'), entry('old', 'failed'), null]) { - await refreshExpandedHistory(rows, rows[0], async params => { - if (!params.has('ids')) return [rows[0]]; - requests.push(params.getAll('ids')); - assert.ok(next); - return [next]; - }, () => true, () => {}, (_, updates) => { rows = [updates[0], rows[1]]; }); + for (const next of [ + entry('old', 'unknown', 'exit_conflict'), + entry('old', 'failed'), + null, + ]) { + await refreshExpandedHistory( + rows, + rows[0], + async (params) => { + if (!params.has('ids')) return [rows[0]]; + requests.push(params.getAll('ids')); + assert.ok(next); + return [next]; + }, + () => true, + () => {}, + (_, updates) => { + rows = [updates[0], rows[1]]; + }, + ); } assert.deepEqual(requests, [['old'], ['old']]); - assert.deepEqual(rows.map(row => row.state), ['failed', 'finished']); + assert.deepEqual( + rows.map((row) => row.state), + ['failed', 'finished'], + ); }); test('dashboard never rounds a missed plan up to 100 percent or treats an empty denominator as punctual', () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/dashboard/index.tsx'), 'utf8'); - const tree = ts.createSourceFile('dashboard.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); - const component = tree.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'ScheduleRate'); - const {outputText} = ts.transpileModule(component.getText(tree), {fileName:'rate.tsx', - compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2020}}); - const rate = new Function('React','Statistic',outputText+';return ScheduleRate;')( - {createElement: (_type, props) => props}, 'Statistic'); - for (const [count,total,value] of [[9999,10000,'>99.9%'],[10000,10000,'100.0%'],[0,1,'0.0%'],[0,0,'—']]) { - assert.equal(rate({title:'on time',count,total}).value,value); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/dashboard/index.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'dashboard.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); + const component = tree.statements.find( + (node) => + ts.isFunctionDeclaration(node) && node.name?.text === 'ScheduleRate', + ); + const { outputText } = ts.transpileModule(component.getText(tree), { + fileName: 'rate.tsx', + compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2020 }, + }); + const rate = new Function( + 'React', + 'Statistic', + outputText + ';return ScheduleRate;', + )({ createElement: (_type, props) => props }, 'Statistic'); + for (const [count, total, value] of [ + [9999, 10000, '>99.9%'], + [10000, 10000, '100.0%'], + [0, 1, '0.0%'], + [0, 0, '—'], + ]) { + assert.equal(rate({ title: 'on time', count, total }).value, value); } }); test('opened terminal timelines keep receiving late samples by trigger ID alongside live siblings', async () => { const sameSecond = [entry('old'), entry('sibling'), entry('live', 'queued')]; const open = new Set(['old', 'live']); - const states = new Map(sameSecond.map(row => [row.id, row])); + const states = new Map(sameSecond.map((row) => [row.id, row])); for (const state of ['running', 'finished']) { - await refreshExpandedHistory([...states.values()], sameSecond[0], async params => { - const ids = params.getAll('ids'); - if (!ids.length) return [entry('new')]; - assert.deepEqual(ids, ['old', 'live']); - return [{...entry('live', state), started_at: 22}, {...entry('old'), script_started_at: 17}]; - }, () => true, newer => assert.equal(newer, false), (_, rows) => { - for (const row of rows) states.set(row.id, row); - }, open); + await refreshExpandedHistory( + [...states.values()], + sameSecond[0], + async (params) => { + const ids = params.getAll('ids'); + if (!ids.length) return [entry('new')]; + assert.deepEqual(ids, ['old', 'live']); + return [ + { ...entry('live', state), started_at: 22 }, + { ...entry('old'), script_started_at: 17 }, + ]; + }, + () => true, + (newer) => assert.equal(newer, false), + (_, rows) => { + for (const row of rows) states.set(row.id, row); + }, + open, + ); assert.equal(states.get('old').script_started_at, 17); assert.equal(states.get('live').state, state); assert.equal(states.get('sibling').script_started_at, undefined); @@ -362,168 +655,377 @@ test('opened terminal timelines keep receiving late samples by trigger ID alongs }); test('opening a timeline cancels an in-flight first page and pins its head until the last detail closes', async () => { - const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const source = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let toggle, fetchPage, pageDeps; function visit(node) { - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression; - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' - && node.arguments[1]?.getText(tree).includes('before')) [fetchPage, pageDeps] = node.arguments; + if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') + toggle = node.initializer.expression; + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' && + node.arguments[1]?.getText(tree).includes('before') + ) + [fetchPage, pageDeps] = node.arguments; ts.forEachChild(node, visit); } visit(tree); - const rows = [entry('newer'), entry('subject')], headRef = {}, pageRequest = {}, requests = []; - let opened = new Set(), paused = false, visible = rows, attempt = 0; + const rows = [entry('newer'), entry('subject')], + headRef = {}, + pageRequest = {}, + requests = []; + let opened = new Set(), + paused = false, + visible = rows, + attempt = 0; const context = { - rows, row: rows[1], headRef, pageRequest, statusRequest:{}, before:null, id:7, pageSize:25, config:{apiPrefix:'/api/'}, - expanded:false, get pinned() {return opened.size > 0;}, get paused() {return paused;}, - get attempt() {return attempt;}, setAttempt(fn) {attempt = fn(attempt);}, - setOpenIds(fn) {opened = fn(opened);}, - request:{get:() => new Promise(resolve => requests.push(resolve))}, - setRows(fn) { visible = fn(visible); }, - setRefreshFailed(){},setHasNew(){},setLoading(){},setNextCursor(){},setFailed(){}, - setTimeout(){return 1;},clearTimeout(){}, + rows, + row: rows[1], + headRef, + pageRequest, + statusRequest: {}, + before: null, + id: 7, + pageSize: 25, + config: { apiPrefix: '/api/' }, + expanded: false, + get pinned() { + return opened.size > 0; + }, + get paused() { + return paused; + }, + get attempt() { + return attempt; + }, + setAttempt(fn) { + attempt = fn(attempt); + }, + setOpenIds(fn) { + opened = fn(opened); + }, + request: { get: () => new Promise((resolve) => requests.push(resolve)) }, + setRows(fn) { + visible = fn(visible); + }, + setRefreshFailed() {}, + setHasNew() {}, + setLoading() {}, + setNextCursor() {}, + setFailed() {}, + setTimeout() { + return 1; + }, + clearTimeout() {}, }; - const invoke = body => Function(...Object.keys(context), - ts.transpile('const fn = '+body.getText(tree), {target:ts.ScriptTarget.ES2022})+'\nreturn fn();')(...Object.values(context)); + const invoke = (body) => + Function( + ...Object.keys(context), + ts.transpile('const fn = ' + body.getText(tree), { + target: ts.ScriptTarget.ES2022, + }) + '\nreturn fn();', + )(...Object.values(context)); const stopFirst = invoke(fetchPage); invoke(toggle); assert.ok(pageRequest.current.signal.aborted); - assert.equal(headRef.current.id,'newer'); + assert.equal(headRef.current.id, 'newer'); assert.deepEqual([...opened], ['subject']); - stopFirst();paused = true; + stopFirst(); + paused = true; const leavePinned = invoke(fetchPage); - assert.equal(requests.length,1); - requests[0]({data:[entry('late-first-page')]}); - await new Promise(resolve=>setImmediate(resolve)); + assert.equal(requests.length, 1); + requests[0]({ data: [entry('late-first-page')] }); + await new Promise((resolve) => setImmediate(resolve)); assert.deepEqual(visible, rows); - invoke(toggle);assert.equal(opened.size,0); - leavePinned();paused = false; + invoke(toggle); + assert.equal(opened.size, 0); + leavePinned(); + paused = false; const close = invoke(fetchPage); - requests[1]({data:[entry('current-first-page')]}); - await new Promise(resolve=>setImmediate(resolve)); - assert.equal(visible[0].id,'current-first-page'); + requests[1]({ data: [entry('current-first-page')] }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(visible[0].id, 'current-first-page'); // Two activations in a single commit leave the first page visible. - const dependencies = () => Function(...Object.keys(context), 'return '+pageDeps.getText(tree))(...Object.values(context)); + const dependencies = () => + Function( + ...Object.keys(context), + 'return ' + pageDeps.getText(tree), + )(...Object.values(context)); const prior = dependencies(); - const click = Function(...Object.keys(context), ts.transpile('const fn = '+toggle.getText(tree), - {target:ts.ScriptTarget.ES2022})+'\nreturn fn;')(...Object.values(context)); - click(); click(); - assert.equal(opened.size,0); + const click = Function( + ...Object.keys(context), + ts.transpile('const fn = ' + toggle.getText(tree), { + target: ts.ScriptTarget.ES2022, + }) + '\nreturn fn;', + )(...Object.values(context)); + click(); + click(); + assert.equal(opened.size, 0); assert.ok(pageRequest.current.signal.aborted); - assert.notDeepEqual(dependencies(),prior,'the aborted first-page poll needs a replacement even when the page stays unpinned'); + assert.notDeepEqual( + dependencies(), + prior, + 'the aborted first-page poll needs a replacement even when the page stays unpinned', + ); close(); }); test('reopening a timeline with its sibling still open supersedes stale running and queued responses', async () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let toggle, pollEffect, deps; function visit(node) { - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression; - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' - && node.arguments[1]?.getText(tree).includes('pinned')) [pollEffect, deps] = node.arguments; + if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') + toggle = node.initializer.expression; + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' && + node.arguments[1]?.getText(tree).includes('pinned') + ) + [pollEffect, deps] = node.arguments; ts.forEachChild(node, visit); } visit(tree); - const old = [entry('a','running'), {...entry('b','queued'), queue_wait_ms:1000}]; - const latest = [{...entry('b','finished'), started_at:1200, queued_at:1000, script_started_at:1300}, - {...entry('a','failed'), exit_code:7, script_started_at:1100}]; - const requests = [], timers = new Set(); - let rows = old, opened = new Set(['a','b']); - const headRef = {current:old[0]}, statusRequest = {}, pageRequest = {}; - const context = {id:1, pinned:true, updateStatus:{}, row:old[1], rows:old, headRef, rowsRef:{current:old}, - get openIds() {return opened;}, get firstPageSelection(){return opened;}, expanded:false, statusRequest, pageRequest, - setOpenIds(update){ opened=update(opened); }, - createTriggerPoll, config:{apiPrefix:'/api/'}, setHasNew(){},setRefreshFailed(){}, - setRows(update){rows=update(rows);}, setTimeout(fn){timers.add(fn);return fn;}, clearTimeout(fn){timers.delete(fn);}, - request:{ get(url,{params,signal}) {return params.has('ids') - ? new Promise(resolve=>requests.push({signal,resolve})) : Promise.resolve({data:[old[0]]});} }, + const old = [ + entry('a', 'running'), + { ...entry('b', 'queued'), queue_wait_ms: 1000 }, + ]; + const latest = [ + { + ...entry('b', 'finished'), + started_at: 1200, + queued_at: 1000, + script_started_at: 1300, + }, + { ...entry('a', 'failed'), exit_code: 7, script_started_at: 1100 }, + ]; + const requests = [], + timers = new Set(); + let rows = old, + opened = new Set(['a', 'b']); + const headRef = { current: old[0] }, + statusRequest = {}, + pageRequest = {}; + const context = { + id: 1, + pinned: true, + updateStatus: {}, + row: old[1], + rows: old, + headRef, + rowsRef: { current: old }, + get openIds() { + return opened; + }, + get firstPageSelection() { + return opened; + }, + expanded: false, + statusRequest, + pageRequest, + setOpenIds(update) { + opened = update(opened); + }, + createTriggerPoll, + config: { apiPrefix: '/api/' }, + setHasNew() {}, + setRefreshFailed() {}, + setRows(update) { + rows = update(rows); + }, + setTimeout(fn) { + timers.add(fn); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, + request: { + get(url, { params, signal }) { + return params.has('ids') + ? new Promise((resolve) => requests.push({ signal, resolve })) + : Promise.resolve({ data: [old[0]] }); + }, + }, }; function evaluate(body) { - return Function(...Object.keys(context),ts.transpile('const result = '+body,{target:ts.ScriptTarget.ES2022})+ - '\nreturn result;')(...Object.values(context)); + return Function( + ...Object.keys(context), + ts.transpile('const result = ' + body, { + target: ts.ScriptTarget.ES2022, + }) + '\nreturn result;', + )(...Object.values(context)); } let previousDeps, dispose; - const flush = () => new Promise(resolve=>setImmediate(resolve)); + const flush = () => new Promise((resolve) => setImmediate(resolve)); async function commit() { - const next=evaluate(deps.getText(tree)); - if (!previousDeps || next.some((value,i)=>value!==previousDeps[i])) { + const next = evaluate(deps.getText(tree)); + if (!previousDeps || next.some((value, i) => value !== previousDeps[i])) { dispose?.(); - dispose=evaluate(pollEffect.getText(tree))(); + dispose = evaluate(pollEffect.getText(tree))(); } - previousDeps=next; + previousDeps = next; await flush(); } await commit(); evaluate(toggle.getText(tree))(); - assert.ok(requests[0].signal.aborted, 'close must revoke the old response before effects run'); + assert.ok( + requests[0].signal.aborted, + 'close must revoke the old response before effects run', + ); await commit(); evaluate(toggle.getText(tree))(); await commit(); - assert.equal(requests.length,3); - requests[2].resolve({data:latest}); + assert.equal(requests.length, 3); + requests[2].resolve({ data: latest }); await flush(); - for (const stale of requests.slice(0,2).reverse()) stale.resolve({data:old}); + for (const stale of requests.slice(0, 2).reverse()) + stale.resolve({ data: old }); await flush(); - assert.deepEqual(rows,[latest[1],latest[0]]); - assert.deepEqual([...opened].sort(),['a','b']); - assert.equal(timers.size,1); + assert.deepEqual(rows, [latest[1], latest[0]]); + assert.deepEqual([...opened].sort(), ['a', 'b']); + assert.equal(timers.size, 1); dispose(); - assert.equal(timers.size,0); + assert.equal(timers.size, 0); }); test('opening a detail and loading an older page in the same commit keep the page request and its loading indicator', () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let toggle, load; function visit(node) { - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression; - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onClick' && node.initializer.getText(tree).includes('setBefore(nextCursor)')) load = node.initializer.expression; + if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') + toggle = node.initializer.expression; + if ( + ts.isJsxAttribute(node) && + node.name.getText(tree) === 'onClick' && + node.initializer.getText(tree).includes('setBefore(nextCursor)') + ) + load = node.initializer.expression; ts.forEachChild(node, visit); } visit(tree); - for (const order of [[toggle, load, load], [load, toggle, load]]) { - const rows = [entry('first'), entry('tail')], cursors = []; + for (const order of [ + [toggle, load, load], + [load, toggle, load], + ]) { + const rows = [entry('first'), entry('tail')], + cursors = []; let loading = false; - const bindings = {row:rows[0], rows, pageRequest:{current:new AbortController()}, statusRequest:{}, - pinned:false, loading:false, expanded:false, failed:false, nextCursor:rows[1], headRef:{}, - setBefore:value=>cursors.push(value), setLoading:value=>{loading=value;}, - setOpenIds(){},setHasNew(){},setFailed(){},setRefreshFailed(){},setAttempt(){}}; + const bindings = { + row: rows[0], + rows, + pageRequest: { current: new AbortController() }, + statusRequest: {}, + pinned: false, + loading: false, + expanded: false, + failed: false, + nextCursor: rows[1], + headRef: {}, + setBefore: (value) => cursors.push(value), + setLoading: (value) => { + loading = value; + }, + setOpenIds() {}, + setHasNew() {}, + setFailed() {}, + setRefreshFailed() {}, + setAttempt() {}, + }; for (const action of order) { - const compiled=ts.transpile('const action='+action.getText(tree),{target:ts.ScriptTarget.ES2022}); - Function(...Object.keys(bindings),compiled+'\naction();')(...Object.values(bindings)); + const compiled = ts.transpile('const action=' + action.getText(tree), { + target: ts.ScriptTarget.ES2022, + }); + Function( + ...Object.keys(bindings), + compiled + '\naction();', + )(...Object.values(bindings)); } - assert.deepEqual(cursors,[rows[1]],'a click must request the cursor exactly once'); - assert.equal(loading,true,'pinning details must not clear an accepted page load'); + assert.deepEqual( + cursors, + [rows[1]], + 'a click must request the cursor exactly once', + ); + assert.equal( + loading, + true, + 'pinning details must not clear an accepted page load', + ); } }); test('a stalled head and first status batch do not hold up a later batch with a late entry sample', async () => { - const rows = Array.from({length:51}, (_,i)=>entry(i,'running')); - const batches = [], resolved = []; + const rows = Array.from({ length: 51 }, (_, i) => entry(i, 'running')); + const batches = [], + resolved = []; let head; let failed; - const tick = createTriggerPoll(rows[0],params=>{ - const ids=params.getAll('ids'); - if (!ids.length) return new Promise(resolve=>{head=resolve;}); - return new Promise((resolve,reject)=>batches.push({ids,resolve,reject})); - },()=>true,()=>{},(_,updates)=>resolved.push(...updates),value=>{failed=value;},new Set()); + const tick = createTriggerPoll( + rows[0], + (params) => { + const ids = params.getAll('ids'); + if (!ids.length) + return new Promise((resolve) => { + head = resolve; + }); + return new Promise((resolve, reject) => + batches.push({ ids, resolve, reject }), + ); + }, + () => true, + () => {}, + (_, updates) => resolved.push(...updates), + (value) => { + failed = value; + }, + new Set(), + ); tick(rows); try { - await new Promise(resolve=>setImmediate(resolve)); - assert.deepEqual(batches.map(x=>x.ids.length),[25,25]); - const late={...entry('30','finished'),script_started_at:421}; + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual( + batches.map((x) => x.ids.length), + [25, 25], + ); + const late = { ...entry('30', 'finished'), script_started_at: 421 }; batches[1].resolve([late]); - await new Promise(resolve=>setImmediate(resolve)); - assert.deepEqual(resolved,[late]); - assert.deepEqual(batches[2].ids,['50']); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(resolved, [late]); + assert.deepEqual(batches[2].ids, ['50']); batches[2].resolve([]); batches[0].reject(new Error('timeout')); head([]); - await new Promise(resolve=>setImmediate(resolve)); - assert.equal(failed,true); - assert.deepEqual(resolved,[late]); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(failed, true); + assert.deepEqual(resolved, [late]); } finally { head([]); for (const batch of batches) batch.resolve([]); @@ -531,11 +1033,23 @@ test('a stalled head and first status batch do not hold up a later batch with a }); test('page and status retries can settle in either order before both abandoned reads return', async () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); const effects = {}; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect') { + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' + ) { const dependencies = node.arguments[1]?.getText(tree); if (dependencies?.includes('pinned')) effects.status = node.arguments[0]; if (dependencies?.includes('before')) effects.page = node.arguments[0]; @@ -543,36 +1057,79 @@ test('page and status retries can settle in either order before both abandoned r ts.forEachChild(node, visit); } visit(tree); - const flush = () => new Promise(resolve => setImmediate(resolve)); + const flush = () => new Promise((resolve) => setImmediate(resolve)); for (const pageFirst of [false, true]) { const first = entry('simultaneous-B', 'running'); const tail = entry('simultaneous-A', 'queued'); - const completed = { ...first, state: 'failed', exit_code: 7, script_started_at: 1220 }; - const dispatched = { ...tail, state: 'running', queued_at: 1110, started_at: 1200 }; + const completed = { + ...first, + state: 'failed', + exit_code: 7, + script_started_at: 1220, + }; + const dispatched = { + ...tail, + state: 'running', + queued_at: 1110, + started_at: 1200, + }; const older = entry('earlier'); let rows = [first, tail]; let nextCursor = tail; const calls = { page: [], status: [] }; - const openIds = new Set(rows.map(row => row.id)); + const openIds = new Set(rows.map((row) => row.id)); const timers = new Set(); const bindings = { - rowsRef: { current: rows }, headRef: { current: first }, pageRequest: {}, statusRequest: {}, updateStatus: {}, - before: tail, id: 17, openIds, pinned: true, paused: false, pageSize: 25, createTriggerPoll, + rowsRef: { current: rows }, + headRef: { current: first }, + pageRequest: {}, + statusRequest: {}, + updateStatus: {}, + before: tail, + id: 17, + openIds, + pinned: true, + paused: false, + pageSize: 25, + createTriggerPoll, config: { apiPrefix: '/api/' }, - request: { get(url, { params, signal }) { - if (params instanceof URLSearchParams && !params.has('ids')) return Promise.resolve({ data: [first] }); - const kind = params instanceof URLSearchParams ? 'status' : 'page'; - return new Promise(resolve => calls[kind].push({ params, signal, resolve })); - } }, - setNextCursor(value) { nextCursor = value; }, - setRows(update) { rows = update(rows); }, - setHasNew() {}, setLoading() {}, setRefreshFailed() {}, setFailed() {}, - setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); }, + request: { + get(url, { params, signal }) { + if (params instanceof URLSearchParams && !params.has('ids')) + return Promise.resolve({ data: [first] }); + const kind = params instanceof URLSearchParams ? 'status' : 'page'; + return new Promise((resolve) => + calls[kind].push({ params, signal, resolve }), + ); + }, + }, + setNextCursor(value) { + nextCursor = value; + }, + setRows(update) { + rows = update(rows); + }, + setHasNew() {}, + setLoading() {}, + setRefreshFailed() {}, + setFailed() {}, + setTimeout(fn) { + timers.add(fn); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, }; function start(kind) { - const js = ts.transpile('const effect = ' + effects[kind].getText(tree), { target: ts.ScriptTarget.ES2022 }); - return Function(...Object.keys(bindings), js + '\nreturn effect();')(...Object.values(bindings)); + const js = ts.transpile('const effect = ' + effects[kind].getText(tree), { + target: ts.ScriptTarget.ES2022, + }); + return Function( + ...Object.keys(bindings), + js + '\nreturn effect();', + )(...Object.values(bindings)); } const endOldPage = start('page'); const endOldStatus = start('status'); @@ -581,11 +1138,16 @@ test('page and status retries can settle in either order before both abandoned r const endPage = start('page'); const endStatus = start('status'); try { - assert.deepEqual(calls.page.map(call => call.params.beforeId), [tail.id, tail.id]); + assert.deepEqual( + calls.page.map((call) => call.params.beforeId), + [tail.id, tail.id], + ); assert.deepEqual(calls.status[1].params.getAll('ids'), [...openIds]); const sequence = pageFirst ? ['page', 'status'] : ['status', 'page']; for (const kind of sequence) { - calls[kind][1].resolve({ data: kind === 'page' ? [older] : [dispatched, completed] }); + calls[kind][1].resolve({ + data: kind === 'page' ? [older] : [dispatched, completed], + }); await flush(); } for (const kind of sequence.reverse()) { @@ -607,31 +1169,52 @@ test('page and status retries can settle in either order before both abandoned r test('a held batch cannot delay later polls of other IDs or hide its failure on a sibling success', async () => { const rows = Array.from({ length: 76 }, (_, i) => entry(i)); - const open = new Set(rows.map(row => row.id)); - const requests = [], notices = [], errors = [], updates = []; + const open = new Set(rows.map((row) => row.id)); + const requests = [], + notices = [], + errors = [], + updates = []; let active = true; - const tick = createTriggerPoll(rows[0], params => new Promise((resolve, reject) => { - requests.push({ ids: params.getAll('ids'), resolve, reject }); - }), () => active, value => notices.push(value), (ids, data) => updates.push(...data), - value => errors.push(value), open); - const flush = () => new Promise(resolve => setImmediate(resolve)); - const cycle = () => { tick(rows); }; - const headReads = () => requests.filter(r => !r.ids.length); - const batches = () => requests.filter(r => r.ids.length); + const tick = createTriggerPoll( + rows[0], + (params) => + new Promise((resolve, reject) => { + requests.push({ ids: params.getAll('ids'), resolve, reject }); + }), + () => active, + (value) => notices.push(value), + (ids, data) => updates.push(...data), + (value) => errors.push(value), + open, + ); + const flush = () => new Promise((resolve) => setImmediate(resolve)); + const cycle = () => { + tick(rows); + }; + const headReads = () => requests.filter((r) => !r.ids.length); + const batches = () => requests.filter((r) => r.ids.length); cycle(); const slow = batches()[0]; - const latest = { ...rows[25], script_started_at: 321, state: 'failed', exit_code: 7 }; + const latest = { + ...rows[25], + script_started_at: 321, + state: 'failed', + exit_code: 7, + }; for (let round = 0; round < 3; round++) { for (let offset = 25; offset < rows.length; offset += 25) { const batch = batches().at(-1); - assert.deepEqual(batch.ids, rows.slice(offset, offset + 25).map(r => r.id)); + assert.deepEqual( + batch.ids, + rows.slice(offset, offset + 25).map((r) => r.id), + ); batch.resolve(offset === 25 && round === 2 ? [latest] : []); await flush(); } if (round < 2) cycle(); } assert.ok(updates.includes(latest)); - assert.equal(batches().filter(r => r.ids.includes('0')).length, 1); + assert.equal(batches().filter((r) => r.ids.includes('0')).length, 1); assert.equal(headReads().length, 1); slow.reject(new Error('timeout')); await flush(); @@ -640,47 +1223,95 @@ test('a held batch cannot delay later polls of other IDs or hide its failure on await flush(); assert.equal(errors.at(-1), true); cycle(); - const retry = batches().findLast(r => r.ids.includes('0')); + const retry = batches().findLast((r) => r.ids.includes('0')); assert.notEqual(retry, slow); retry.resolve(rows.slice(0, 25)); await flush(); assert.equal(errors.at(-1), false); active = false; - const prior = { updates: updates.length, notices: notices.length, errors: errors.length }; - requests.forEach(r => r.resolve([entry('stale', 'running')])); + const prior = { + updates: updates.length, + notices: notices.length, + errors: errors.length, + }; + requests.forEach((r) => r.resolve([entry('stale', 'running')])); await flush(); - assert.deepEqual({ updates: updates.length, notices: notices.length, errors: errors.length }, prior); + assert.deepEqual( + { updates: updates.length, notices: notices.length, errors: errors.length }, + prior, + ); }); test('the mounted list keeps its five-second timer while a status batch is pending and cancels it on exit', async () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let effect; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' && - node.arguments[1]?.getText(tree).includes('pinned')) effect = node.arguments[0]; + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' && + node.arguments[1]?.getText(tree).includes('pinned') + ) + effect = node.arguments[0]; ts.forEachChild(node, visit); } visit(tree); const rows = Array.from({ length: 51 }, (_, i) => entry(i, 'running')); - const reads = [], timers = new Map(), changes = []; + const reads = [], + timers = new Map(), + changes = []; const bindings = { - rowsRef: { current: rows }, headRef: { current: rows[0] }, statusRequest: {}, updateStatus: {}, - id: 23, pinned: true, openIds: new Set(rows.map(row => row.id)), createTriggerPoll, - config: { apiPrefix: '/api/' }, setHasNew() {}, setRefreshFailed() {}, - setRows(update) { changes.push(update(rows)); }, - setTimeout(fn, ms) { timers.set(fn, ms); return fn; }, clearTimeout(fn) { timers.delete(fn); }, - request: { get(url, { params, signal }) { - const ids = params.getAll('ids'); - if (!ids.length) return Promise.resolve({ data: [rows[0]] }); - if (ids.includes('25')) return new Promise(resolve => reads.push({ ids, signal, resolve })); - reads.push({ ids, signal }); - return Promise.resolve({ data: rows.filter(row => ids.includes(row.id)) }); - } }, + rowsRef: { current: rows }, + headRef: { current: rows[0] }, + statusRequest: {}, + updateStatus: {}, + id: 23, + pinned: true, + openIds: new Set(rows.map((row) => row.id)), + createTriggerPoll, + config: { apiPrefix: '/api/' }, + setHasNew() {}, + setRefreshFailed() {}, + setRows(update) { + changes.push(update(rows)); + }, + setTimeout(fn, ms) { + timers.set(fn, ms); + return fn; + }, + clearTimeout(fn) { + timers.delete(fn); + }, + request: { + get(url, { params, signal }) { + const ids = params.getAll('ids'); + if (!ids.length) return Promise.resolve({ data: [rows[0]] }); + if (ids.includes('25')) + return new Promise((resolve) => reads.push({ ids, signal, resolve })); + reads.push({ ids, signal }); + return Promise.resolve({ + data: rows.filter((row) => ids.includes(row.id)), + }); + }, + }, }; - const js = ts.transpile('const setup = ' + effect.getText(tree), { target: ts.ScriptTarget.ES2022 }); - const dispose = Function(...Object.keys(bindings), js + '\nreturn setup();')(...Object.values(bindings)); - const flush = () => new Promise(resolve => setImmediate(resolve)); + const js = ts.transpile('const setup = ' + effect.getText(tree), { + target: ts.ScriptTarget.ES2022, + }); + const dispose = Function( + ...Object.keys(bindings), + js + '\nreturn setup();', + )(...Object.values(bindings)); + const flush = () => new Promise((resolve) => setImmediate(resolve)); try { for (let tick = 0; tick < 2; tick++) { await flush(); @@ -691,13 +1322,13 @@ test('the mounted list keeps its five-second timer while a status batch is pendi next(); } await flush(); - assert.equal(reads.filter(read => read.ids.includes('0')).length, 3); - assert.equal(reads.filter(read => read.ids.includes('25')).length, 1); + assert.equal(reads.filter((read) => read.ids.includes('0')).length, 3); + assert.equal(reads.filter((read) => read.ids.includes('25')).length, 1); } finally { dispose(); } const count = changes.length; - const old = reads.find(read => read.resolve); + const old = reads.find((read) => read.resolve); assert.ok(old.signal.aborted); old.resolve({ data: rows }); await flush(); @@ -709,25 +1340,46 @@ test('pending IDs keep their place when pages change between ticks and each ID h const initial = Array.from({ length: 85 }, (_, i) => entry(i, 'running')); let active = true; const calls = []; - const tick = createTriggerPoll(initial[0], params => { - if (!params.has('ids')) return Promise.resolve([]); - return new Promise(resolve => calls.push({ ids: params.getAll('ids'), resolve })); - }, () => active, () => {}, () => {}, () => {}, new Set()); + const tick = createTriggerPoll( + initial[0], + (params) => { + if (!params.has('ids')) return Promise.resolve([]); + return new Promise((resolve) => + calls.push({ ids: params.getAll('ids'), resolve }), + ); + }, + () => active, + () => {}, + () => {}, + () => {}, + new Set(), + ); tick(initial); assert.equal(calls.length, 2); // Drop one queued row, append two newly loaded rows, then reverse display order. - const changed = [...initial.filter(r => r.id !== '60'), entry('85', 'queued'), entry('86', 'queued')]; + const changed = [ + ...initial.filter((r) => r.id !== '60'), + entry('85', 'queued'), + entry('86', 'queued'), + ]; tick(changed.toReversed()); tick(changed); assert.equal(calls.length, 2); calls[1].resolve([]); - await new Promise(resolve => setImmediate(resolve)); - assert.deepEqual(calls[2].ids, changed.slice(50, 75).map(r => r.id)); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual( + calls[2].ids, + changed.slice(50, 75).map((r) => r.id), + ); tick(changed); calls[2].resolve([]); - await new Promise(resolve => setImmediate(resolve)); - assert.deepEqual(calls[3].ids.slice(0, 11), [...initial.slice(76).map(r => r.id), '86', '85']); - assert.ok(!calls[3].ids.some(id => calls[0].ids.includes(id))); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(calls[3].ids.slice(0, 11), [ + ...initial.slice(76).map((r) => r.id), + '86', + '85', + ]); + assert.ok(!calls[3].ids.some((id) => calls[0].ids.includes(id))); active = false; calls[3].resolve([]); calls[0].resolve([]); @@ -735,22 +1387,37 @@ test('pending IDs keep their place when pages change between ticks and each ID h test('consecutive double timeouts give the waiting tail its turn and retries leave healthy reads alone', async () => { const rows = Array.from({ length: 75 }, (_, i) => entry(i, 'running')); - const calls = [], errors = [], updated = []; + const calls = [], + errors = [], + updated = []; let heads = 0; - const poll = createTriggerPoll(rows[0], params => { - if (!params.has('ids')) { - heads++; - return Promise.resolve([]); - } - return new Promise((resolve, reject) => calls.push({ ids: params.getAll('ids'), resolve, reject })); - }, () => true, () => {}, (_, data) => updated.push(...data), value => errors.push(value), new Set()); - const flush = () => new Promise(resolve => setImmediate(resolve)); + const poll = createTriggerPoll( + rows[0], + (params) => { + if (!params.has('ids')) { + heads++; + return Promise.resolve([]); + } + return new Promise((resolve, reject) => + calls.push({ ids: params.getAll('ids'), resolve, reject }), + ); + }, + () => true, + () => {}, + (_, data) => updated.push(...data), + (value) => errors.push(value), + new Set(), + ); + const flush = () => new Promise((resolve) => setImmediate(resolve)); poll(rows); assert.equal(calls.length, 2); calls[0].reject(new Error('timeout')); calls[1].reject(new Error('timeout')); await flush(); - assert.deepEqual(calls[2].ids, rows.slice(50).map(r => r.id)); + assert.deepEqual( + calls[2].ids, + rows.slice(50).map((r) => r.id), + ); poll(rows, 'retry'); poll(rows, 'retry'); assert.equal(calls.length, 4); @@ -759,90 +1426,176 @@ test('consecutive double timeouts give the waiting tail its turn and retries lea calls[2].resolve([late]); await flush(); assert.equal(calls.length, 5); - assert.deepEqual(calls.slice(3).flatMap(c => c.ids), rows.slice(0, 50).map(r => r.id)); + assert.deepEqual( + calls.slice(3).flatMap((c) => c.ids), + rows.slice(0, 50).map((r) => r.id), + ); calls[3].reject(new Error('timeout again')); calls[4].reject(new Error('timeout again')); await flush(); poll(rows); - const newest = { ...rows[60], state: 'finished', script_started_at: 1234, exit_code: 0 }; + const newest = { + ...rows[60], + state: 'finished', + script_started_at: 1234, + exit_code: 0, + }; calls[5].resolve([]); calls[6].resolve([]); await flush(); - assert.deepEqual(calls[7].ids, rows.slice(50).map(r => r.id)); + assert.deepEqual( + calls[7].ids, + rows.slice(50).map((r) => r.id), + ); calls[7].resolve([newest]); await flush(); assert.deepEqual(updated, [late, newest]); assert.equal(errors.at(-1), false); const before = calls.length; poll(rows, 'retry'); - assert.equal(calls.length, before, 'retry with no remaining failure must not query healthy rows'); + assert.equal( + calls.length, + before, + 'retry with no remaining failure must not query healthy rows', + ); }); test('retry button preserves pending responses and bounds the two status reads in the mounted list', async () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let effect, retry; function visit(node) { - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' && - node.arguments[1]?.getText(tree).includes('pinned')) effect = node.arguments[0]; - if (ts.isJsxElement(node) && node.openingElement.tagName.getText(tree) === 'Button' && - node.children.some(child => child.getText(tree).includes("intl.get('重试')"))) { - retry = node.openingElement.attributes.properties.find(a => a.name?.getText(tree) === 'onClick').initializer.expression; + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' && + node.arguments[1]?.getText(tree).includes('pinned') + ) + effect = node.arguments[0]; + if ( + ts.isJsxElement(node) && + node.openingElement.tagName.getText(tree) === 'Button' && + node.children.some((child) => + child.getText(tree).includes("intl.get('重试')"), + ) + ) { + retry = node.openingElement.attributes.properties.find( + (a) => a.name?.getText(tree) === 'onClick', + ).initializer.expression; } ts.forEachChild(node, visit); } visit(tree); const rows = Array.from({ length: 76 }, (_, i) => entry(i, 'running')); - const calls = [], mutations = []; + const calls = [], + mutations = []; const bindings = { - id: 4, pinned: true, openIds: new Set(), createTriggerPoll, - rowsRef: {current:rows}, headRef: {current:rows[0]}, statusRequest:{}, updateStatus: {}, - config: {apiPrefix:'/api/'}, setHasNew(){}, setRefreshFailed(){}, - setRows(update){ mutations.push(update(rows)); }, setTimeout(){}, clearTimeout(){}, - request: { get(url, { signal, timeout, params }) { - if (!params.has('ids')) return Promise.resolve({data:[]}); - return new Promise((resolve,reject)=>calls.push({ids:params.getAll('ids'),signal,timeout,resolve,reject})); - } }, + id: 4, + pinned: true, + openIds: new Set(), + createTriggerPoll, + rowsRef: { current: rows }, + headRef: { current: rows[0] }, + statusRequest: {}, + updateStatus: {}, + config: { apiPrefix: '/api/' }, + setHasNew() {}, + setRefreshFailed() {}, + setRows(update) { + mutations.push(update(rows)); + }, + setTimeout() {}, + clearTimeout() {}, + request: { + get(url, { signal, timeout, params }) { + if (!params.has('ids')) return Promise.resolve({ data: [] }); + return new Promise((resolve, reject) => + calls.push({ + ids: params.getAll('ids'), + signal, + timeout, + resolve, + reject, + }), + ); + }, + }, }; function run(node) { - const js=ts.transpile('const action='+node.getText(tree),{target:ts.ScriptTarget.ES2022}); - return Function(...Object.keys(bindings),js+'\nreturn action();')(...Object.values(bindings)); + const js = ts.transpile('const action=' + node.getText(tree), { + target: ts.ScriptTarget.ES2022, + }); + return Function( + ...Object.keys(bindings), + js + '\nreturn action();', + )(...Object.values(bindings)); } - const dispose=run(effect); - const flush=()=>new Promise(resolve=>setImmediate(resolve)); + const dispose = run(effect); + const flush = () => new Promise((resolve) => setImmediate(resolve)); try { - assert.equal(calls.length,2); - assert.ok(calls.every(call=>call.timeout===10000)); + assert.equal(calls.length, 2); + assert.ok(calls.every((call) => call.timeout === 10000)); calls[0].reject(new Error('timeout')); await flush(); run(retry); run(retry); - assert.equal(calls.length,3); - assert.ok(calls.every(call=>!call.signal.aborted)); - const terminal={...rows[60],state:'failed',exit_code:7,script_started_at:721}; - calls[2].resolve({data:[terminal]}); + assert.equal(calls.length, 3); + assert.ok(calls.every((call) => !call.signal.aborted)); + const terminal = { + ...rows[60], + state: 'failed', + exit_code: 7, + script_started_at: 721, + }; + calls[2].resolve({ data: [terminal] }); await flush(); assert.ok(mutations.at(-1).includes(terminal)); - assert.equal(calls[3].ids[0],'75', 'oldest waiting ID must precede the manual retry'); + assert.equal( + calls[3].ids[0], + '75', + 'oldest waiting ID must precede the manual retry', + ); } finally { dispose(); } - const count=mutations.length; - for (const call of calls) call.resolve({data: rows}); + const count = mutations.length; + for (const call of calls) call.resolve({ data: rows }); await flush(); - assert.equal(mutations.length,count); + assert.equal(mutations.length, count); }); test('selection churn and retries cannot move waiting IDs behind the front pages or cancel an unrelated read', async () => { const rows = Array.from({ length: 100 }, (_, i) => entry(i, 'finished')); - const open = new Set(rows.map(r => r.id)); - const calls = [], updates = []; + const open = new Set(rows.map((r) => r.id)); + const calls = [], + updates = []; let heads = 0; - const poll = createTriggerPoll(rows[0], params => { - if (!params.has('ids')) { heads++; return Promise.resolve([]); } - return new Promise((resolve, reject) => calls.push({ ids: params.getAll('ids'), resolve, reject })); - }, () => true, () => {}, (_, entries) => updates.push(...entries), () => {}, open); - const flush = () => new Promise(resolve => setImmediate(resolve)); + const poll = createTriggerPoll( + rows[0], + (params) => { + if (!params.has('ids')) { + heads++; + return Promise.resolve([]); + } + return new Promise((resolve, reject) => + calls.push({ ids: params.getAll('ids'), resolve, reject }), + ); + }, + () => true, + () => {}, + (_, entries) => updates.push(...entries), + () => {}, + open, + ); + const flush = () => new Promise((resolve) => setImmediate(resolve)); poll(rows); for (const id of ['2', '29', '50', '75']) { const closed = new Set(open); @@ -856,7 +1609,10 @@ test('selection churn and retries cannot move waiting IDs behind the front pages calls[0].reject(new Error('timeout')); calls[1].reject(new Error('timeout')); await flush(); - assert.deepEqual(calls.slice(2).map(c => c.ids), [rows.slice(50,75), rows.slice(75)].map(group => group.map(r => r.id))); + assert.deepEqual( + calls.slice(2).map((c) => c.ids), + [rows.slice(50, 75), rows.slice(75)].map((group) => group.map((r) => r.id)), + ); const closed = new Set(open); closed.delete('0'); poll(rows, closed); @@ -864,22 +1620,33 @@ test('selection churn and retries cannot move waiting IDs behind the front pages calls[2].resolve([]); calls[3].resolve([{ ...rows[78], script_started_at: 1234 }]); await flush(); - assert.ok(updates.some(r => r.id === '78' && r.script_started_at === 1234)); - assert.ok(!calls.slice(4).some(c => c.ids.includes('0'))); + assert.ok(updates.some((r) => r.id === '78' && r.script_started_at === 1234)); + assert.ok(!calls.slice(4).some((c) => c.ids.includes('0'))); for (const call of calls.slice(4)) call.resolve([]); }); test('an opened in-flight row gets one fresh read after its peers, even after several close and reopen events', async () => { const rows = Array.from({ length: 60 }, (_, i) => entry(i)); - const open = new Set(rows.map(r => r.id)); + const open = new Set(rows.map((r) => r.id)); const closed = new Set(open); closed.delete('4'); - const calls = [], applied = []; - const poll = createTriggerPoll(rows[0], params => { - if (!params.has('ids')) return Promise.resolve([]); - return new Promise(resolve => calls.push({ ids: params.getAll('ids'), resolve })); - }, () => true, () => {}, (_, values) => applied.push(...values), () => {}, open); - const flush = () => new Promise(resolve => setImmediate(resolve)); + const calls = [], + applied = []; + const poll = createTriggerPoll( + rows[0], + (params) => { + if (!params.has('ids')) return Promise.resolve([]); + return new Promise((resolve) => + calls.push({ ids: params.getAll('ids'), resolve }), + ); + }, + () => true, + () => {}, + (_, values) => applied.push(...values), + () => {}, + open, + ); + const flush = () => new Promise((resolve) => setImmediate(resolve)); poll(rows); for (let i = 0; i < 5; i++) { poll(rows, closed); @@ -888,7 +1655,7 @@ test('an opened in-flight row gets one fresh read after its peers, even after se assert.equal(calls.length, 2); calls[0].resolve([rows[4]]); await flush(); - assert.deepEqual(calls[2].ids, [...rows.slice(50).map(r => r.id), '4']); + assert.deepEqual(calls[2].ids, [...rows.slice(50).map((r) => r.id), '4']); const sampled = { ...rows[4], script_started_at: 12345, exit_code: 0 }; calls[2].resolve([sampled]); calls[1].resolve([]); @@ -898,15 +1665,34 @@ test('an opened in-flight row gets one fresh read after its peers, even after se }); test('the paginated list keeps its polling session when details change and forwards the new selection', () => { - const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8'); - const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + const file = fs.readFileSync( + path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), + 'utf8', + ); + const tree = ts.createSourceFile( + 'triggerList.tsx', + file, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ); let toggle, dependencies, firstPage, notify; function visit(node) { - if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'firstPageSelection') firstPage = node.initializer; - if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression; - if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect') { - if (node.arguments[0].getText(tree).includes('createTriggerPoll(')) dependencies = node.arguments[1]; - if (node.arguments[1]?.getText(tree) === '[expanded, openIds]') notify = node.arguments[0]; + if ( + ts.isVariableDeclaration(node) && + node.name.getText(tree) === 'firstPageSelection' + ) + firstPage = node.initializer; + if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') + toggle = node.initializer.expression; + if ( + ts.isCallExpression(node) && + node.expression.getText(tree) === 'useEffect' + ) { + if (node.arguments[0].getText(tree).includes('createTriggerPoll(')) + dependencies = node.arguments[1]; + if (node.arguments[1]?.getText(tree) === '[expanded, openIds]') + notify = node.arguments[0]; } ts.forEachChild(node, visit); } @@ -916,17 +1702,32 @@ test('the paginated list keeps its polling session when details change and forwa const requests = []; const controller = new AbortController(); const bindings = { - id: 1, pinned: true, expanded: true, rows, rowsRef: { current: rows }, row: rows[76], - get openIds() { return opened; }, - setOpenIds(change) { opened = change(opened); }, + id: 1, + pinned: true, + expanded: true, + rows, + rowsRef: { current: rows }, + row: rows[76], + get openIds() { + return opened; + }, + setOpenIds(change) { + opened = change(opened); + }, statusRequest: { current: controller }, - updateStatus: { current: (visible, selection) => requests.push({ visible, selection }) }, + updateStatus: { + current: (visible, selection) => requests.push({ visible, selection }), + }, }; function evaluate(expression, extra = {}) { const scope = { ...bindings, ...extra }; - return Function(...Object.keys(scope), 'return (' + expression.getText(tree) + ');')(...Object.values(scope)); + return Function( + ...Object.keys(scope), + 'return (' + expression.getText(tree) + ');', + )(...Object.values(scope)); } - const deps = () => evaluate(dependencies, { firstPageSelection: evaluate(firstPage) }); + const deps = () => + evaluate(dependencies, { firstPageSelection: evaluate(firstPage) }); const before = deps(); for (const index of [76, 32, 76, 2, 76]) { bindings.row = rows[index]; diff --git a/test/front/trigger-timing.test.cjs b/test/front/trigger-timing.test.cjs index 663b5c94..9a7d8684 100644 --- a/test/front/trigger-timing.test.cjs +++ b/test/front/trigger-timing.test.cjs @@ -9,20 +9,37 @@ const zh = require('../../src/locales/zh-CN.json'); const en = require('../../src/locales/en-US.json'); // Render the actual TSX, including disclosure markup and translated field names. -const source = fs.readFileSync(require.resolve('../../src/pages/crontab/triggerTiming.tsx'), 'utf8'); -const { outputText } = ts.transpileModule(source, { compilerOptions: { - jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true, - target: ts.ScriptTarget.ES2022, -}}); +const source = fs.readFileSync( + require.resolve('../../src/pages/crontab/triggerTiming.tsx'), + 'utf8', +); +const { outputText } = ts.transpileModule(source, { + compilerOptions: { + jsx: ts.JsxEmit.ReactJSX, + module: ts.ModuleKind.CommonJS, + esModuleInterop: true, + target: ts.ScriptTarget.ES2022, + }, +}); const output = {}; Function('require', 'exports', outputText)(require, output); const base = new Date(2026, 10, 16, 14, 55).getTime(); -before(() => intl.init({currentLocale: 'zh-CN', locales: {'zh-CN': zh, 'en-US': en}})); +before(() => + intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': zh, 'en-US': en } }), +); function render(fields) { - const html = renderToStaticMarkup(React.createElement(output.default, { row: { - observed_at: base, state: 'running', source: 'node', exit_code: null, ...fields, - }})); + const html = renderToStaticMarkup( + React.createElement(output.default, { + row: { + observed_at: base, + state: 'running', + source: 'node', + exit_code: null, + ...fields, + }, + }), + ); const [summary, details] = html.split(/]*>/); assert.doesNotMatch(html, /]* open/); assert.match(details, /时间明细<\/summary>/); @@ -31,8 +48,12 @@ function render(fields) { } test('summary separates 57 ms in queue from 158 ms to command start and optional script entry', () => { - const fields = { scheduled_at: base, queued_at: base + 10, started_at: base + 67, - command_started_at: base + 158 }; + const fields = { + scheduled_at: base, + queued_at: base + 10, + started_at: base + 67, + command_started_at: base + 158, + }; for (const script_started_at of [null, base + 201]) { const { summary, details } = render({ ...fields, script_started_at }); assert.match(summary, /排队等待 57 ms/); @@ -46,59 +67,103 @@ test('summary separates 57 ms in queue from 158 ms to command start and optional assert.match(details, /计划到脚本开始 201 ms/); } } - const {summary} = render({...fields, state:'finished', finished_at:base+3158}); + const { summary } = render({ + ...fields, + state: 'finished', + finished_at: base + 3158, + }); assert.match(summary, /计划到命令启动 158 ms/); assert.match(summary, /结束时间 14:55:03/); }); test('only a currently queued run accumulates wait; skip or stop freezes the wait', (t) => { t.mock.method(Date, 'now', () => base + 7000); - const fields = { queued_at:base, scheduled_at:base, started_at:null }; - assert.match(render({...fields, state:'queued'}).summary, /已排队 7 s/); - const { summary, details } = render({...fields, state:'skipped', finished_at:base+12}); + const fields = { queued_at: base, scheduled_at: base, started_at: null }; + assert.match(render({ ...fields, state: 'queued' }).summary, /已排队 7 s/); + const { summary, details } = render({ + ...fields, + state: 'skipped', + finished_at: base + 12, + }); assert.doesNotMatch(summary, /已排队|计划到命令启动|排队等待/); assert.match(details, /跳过前等待 12 ms/); - const stopped = render({...fields,state:'stopped',finished_at:base+2100}); - assert.match(stopped.summary,/排队等待 2.1 s/); - const unknown = render({...fields,state:'unknown',finished_at:base+6000}); - assert.doesNotMatch(unknown.summary,/排队等待|结束时间|已排队/); - assert.match(unknown.details,/状态记录时间/); + const stopped = render({ + ...fields, + state: 'stopped', + finished_at: base + 2100, + }); + assert.match(stopped.summary, /排队等待 2.1 s/); + const unknown = render({ + ...fields, + state: 'unknown', + finished_at: base + 6000, + }); + assert.doesNotMatch(unknown.summary, /排队等待|结束时间|已排队/); + assert.match(unknown.details, /状态记录时间/); }); test('manual and legacy rows never synthesize a schedule, queue time, command start or sample', () => { - const manual=render({source:'manual',queued_at:base, started_at:base+30,command_started_at:base+51}); - assert.match(manual.summary,/进入队列/); - assert.match(manual.summary,/命令启动 14:55:00/); - assert.doesNotMatch(manual.summary,/计划到命令启动/); - for (const source of ['system','legacy','client']) { - const {summary,details}=render({source,started_at:base, state:'failed',exit_code:17}); - assert.match(summary,/记录启动/); - assert.match(summary,/退出码 17/); - assert.doesNotMatch(summary,/计划运行|排队等待|计划到命令启动/); - assert.match(details,/记录启动<\/dt>
14:55:00.000/); - assert.match(details,/命令启动<\/dt>
未记录/); + const manual = render({ + source: 'manual', + queued_at: base, + started_at: base + 30, + command_started_at: base + 51, + }); + assert.match(manual.summary, /进入队列/); + assert.match(manual.summary, /命令启动 14:55:00/); + assert.doesNotMatch(manual.summary, /计划到命令启动/); + for (const source of ['system', 'legacy', 'client']) { + const { summary, details } = render({ + source, + started_at: base, + state: 'failed', + exit_code: 17, + }); + assert.match(summary, /记录启动/); + assert.match(summary, /退出码 17/); + assert.doesNotMatch(summary, /计划运行|排队等待|计划到命令启动/); + assert.match(details, /记录启动<\/dt>
14:55:00.000/); + assert.match(details, /命令启动<\/dt>
未记录/); } }); test('retain precision and dates across midnight, accept zero latency, omit reversed timestamps', () => { const scheduled = new Date(2026, 11, 31, 23, 59, 59, 900).getTime(); - const {summary,details}=render({state:'finished',scheduled_at:scheduled,queued_at:scheduled, - started_at:scheduled,command_started_at:scheduled+150,finished_at:scheduled+3100}); - assert.match(summary,/2026-12-31 23:59:59/); - assert.match(summary,/排队等待 0 ms/); - assert.match(summary,/结束时间 2027-01-01 00:00:03/); - assert.match(details,/命令启动<\/dt>
2027-01-01 00:00:00.050/); - assert.doesNotMatch(render({scheduled_at:base, command_started_at:base-1}).summary,/计划到命令启动/); + const { summary, details } = render({ + state: 'finished', + scheduled_at: scheduled, + queued_at: scheduled, + started_at: scheduled, + command_started_at: scheduled + 150, + finished_at: scheduled + 3100, + }); + assert.match(summary, /2026-12-31 23:59:59/); + assert.match(summary, /排队等待 0 ms/); + assert.match(summary, /结束时间 2027-01-01 00:00:03/); + assert.match(details, /命令启动<\/dt>
2027-01-01 00:00:00.050/); + assert.doesNotMatch( + render({ scheduled_at: base, command_started_at: base - 1 }).summary, + /计划到命令启动/, + ); }); test('an entry sample with no schedule names the measured starting point and keeps millisecond precision', () => { const script_started_at = base + 1635; - const manual = render({source:'manual', queued_at:base, started_at:base+10, script_started_at}); - assert.match(manual.details,/入队到脚本开始 1.635 s/); - const client = render({source:'client', started_at:base, script_started_at}); - assert.match(client.details,/启动记录到脚本开始 1.635 s/); - for (const {summary,details} of [manual,client]) { - assert.doesNotMatch(summary + details,/计划到脚本开始|计划到命令启动/); + const manual = render({ + source: 'manual', + queued_at: base, + started_at: base + 10, + script_started_at, + }); + assert.match(manual.details, /入队到脚本开始 1.635 s/); + const client = render({ + source: 'client', + started_at: base, + script_started_at, + }); + assert.match(client.details, /启动记录到脚本开始 1.635 s/); + for (const { summary, details } of [manual, client]) { + assert.doesNotMatch(summary + details, /计划到脚本开始|计划到命令启动/); } }); @@ -106,23 +171,75 @@ test('an expanded queued row uses its server snapshot even when the browser cloc t.mock.method(Date, 'now', () => base + 600000); const queued = { queued_at: base, queue_wait_ms: 375, state: 'queued' }; assert.match(render(queued).summary, /已排队 375 ms/); - assert.match(render({...queued, queue_wait_ms:0}).summary, /已排队 0 ms/); - assert.match(render({...queued, state:'running', started_at:base+812}).summary, /排队等待 812 ms/); + assert.match( + render({ ...queued, queue_wait_ms: 0 }).summary, + /已排队 0 ms/, + ); + assert.match( + render({ ...queued, state: 'running', started_at: base + 812 }).summary, + /排队等待 812 ms/, + ); }); test('expanded wait reasons retain the actual slot holders after the timer freezes', () => { - const queue_context=JSON.stringify({queue:'manual',limit:2,occupied:2,holders:[{id:'instance-101',name:'长任务 A'},{id:'instance-102',name:'长任务 B'}]}); - const {summary,details}=render({state:'finished',queued_at:base,started_at:base+3712,finished_at:base+5000,queue_context}); - assert.match(summary,/排队等待 3.712 s/); - assert.match(details,/手动执行队列/);assert.match(details,/入队时已达并发上限(运行 2,上限 2)/); - assert.match(details,/长任务 A/);assert.match(details,/长任务 B/); - assert.match(render({state:'queued',queued_at:base}).details,/尚无同时运行的任务记录/); + const queue_context = JSON.stringify({ + queue: 'manual', + limit: 2, + occupied: 2, + holders: [ + { id: 'instance-101', name: '长任务 A' }, + { id: 'instance-102', name: '长任务 B' }, + ], + }); + const { summary, details } = render({ + state: 'finished', + queued_at: base, + started_at: base + 3712, + finished_at: base + 5000, + queue_context, + }); + assert.match(summary, /排队等待 3.712 s/); + assert.match(details, /手动执行队列/); + assert.match(details, /入队时已达并发上限(运行 2,上限 2)/); + assert.match(details, /长任务 A/); + assert.match(details, /长任务 B/); + assert.match( + render({ state: 'queued', queued_at: base }).details, + /尚无同时运行的任务记录/, + ); }); -test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation',()=>{ - const admission=JSON.stringify({queue:'manual',occupied:2,limit:2,holders:[{id:'a',name:'holder-A'},{id:'b',name:'holder-B'}]}); - const live=JSON.stringify({queue:'manual',occupied:1,limit:1,holders:[{id:'b',name:'holder-B'}]}); - const row={state:'queued',queued_at:base,queue_context:admission,queue_live_context:live}; - assert.match(render(row).details,/最近一次检查(运行 1,上限 1)/);assert.doesNotMatch(render(row).details,/holder-A/); - assert.match(render({...row,state:'finished',dequeued_at:base+210,started_at:base+810}).summary,/排队等待 210 ms/); +test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation', () => { + const admission = JSON.stringify({ + queue: 'manual', + occupied: 2, + limit: 2, + holders: [ + { id: 'a', name: 'holder-A' }, + { id: 'b', name: 'holder-B' }, + ], + }); + const live = JSON.stringify({ + queue: 'manual', + occupied: 1, + limit: 1, + holders: [{ id: 'b', name: 'holder-B' }], + }); + const row = { + state: 'queued', + queued_at: base, + queue_context: admission, + queue_live_context: live, + }; + assert.match(render(row).details, /最近一次检查(运行 1,上限 1)/); + assert.doesNotMatch(render(row).details, /holder-A/); + assert.match( + render({ + ...row, + state: 'finished', + dequeued_at: base + 210, + started_at: base + 810, + }).summary, + /排队等待 210 ms/, + ); }); diff --git a/test/front/update-progress.test.cjs b/test/front/update-progress.test.cjs index 1c51a71f..f1b0e91d 100644 --- a/test/front/update-progress.test.cjs +++ b/test/front/update-progress.test.cjs @@ -456,7 +456,10 @@ test('sidebar and dialog use the same authoritative status even when old phase f ); f.store.setJob({ status: 'ready', phase: 'downloading', percent: 62 }); notice.render(); - assert.equal(notice.nodes('button')[0].props['aria-label'], '下载完成,等待重启'); + assert.equal( + notice.nodes('button')[0].props['aria-label'], + '下载完成,等待重启', + ); f.store.setJob({ status: 'completed', phase: 'ready' }); assert.equal(notice.render(), null); panel.render(); diff --git a/test/helpers/load-security-module.cjs b/test/helpers/load-security-module.cjs index fd286ab6..f23315bc 100644 --- a/test/helpers/load-security-module.cjs +++ b/test/helpers/load-security-module.cjs @@ -3,22 +3,47 @@ const path = require('node:path'); const { createRequire } = require('node:module'); const ts = require('typescript'); +function moduleFile(file, name) { + const target = path.resolve(path.dirname(file), name); + const resolved = [ + target, + `${target}.ts`, + `${target}.js`, + `${target}.cjs`, + path.join(target, 'index.ts'), + path.join(target, 'index.js'), + ].find( + (candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile(), + ); + return resolved; +} + module.exports = function loadSecurityModule( file, mocks = {}, cache = new Map(), + resolvedMocks, ) { file = path.resolve(file); + // A dependency keeps its mock when a nested module imports it at another depth. + resolvedMocks ??= new Map( + Object.entries(mocks).flatMap(([name, value]) => { + const target = name.startsWith('.') ? moduleFile(file, name) : undefined; + return target ? [[target, value]] : []; + }), + ); if (cache.has(file)) return cache.get(file).exports; const module = { exports: {} }; cache.set(file, module); const localRequire = createRequire(file); const requireModule = (name) => { + const resolved = name.startsWith('.') ? moduleFile(file, name) : undefined; + if (resolvedMocks.has(resolved)) return resolvedMocks.get(resolved); if (Object.hasOwn(mocks, name)) return mocks[name]; if (name.startsWith('.')) { const target = path.resolve(path.dirname(file), name); if (fs.existsSync(`${target}.ts`)) { - return loadSecurityModule(`${target}.ts`, mocks, cache); + return loadSecurityModule(`${target}.ts`, mocks, cache, resolvedMocks); } } return localRequire(name); diff --git a/test/helpers/manual-log-worker.cjs b/test/helpers/manual-log-worker.cjs index f59bc625..e6812554 100644 --- a/test/helpers/manual-log-worker.cjs +++ b/test/helpers/manual-log-worker.cjs @@ -7,7 +7,12 @@ const { LogStreamManager } = require('../../back/shared/logStreamManager'); const [root, command] = process.argv.slice(2); process.env.QL_DATA_DIR = root; const reporter = path.join(root, 'reporter.cjs'); -fs.writeFileSync(reporter, `require('node:fs').writeFileSync(${JSON.stringify(path.join(root, 'receipt.json'))}, process.argv[2]);`); +fs.writeFileSync( + reporter, + `require('node:fs').writeFileSync(${JSON.stringify( + path.join(root, 'receipt.json'), + )}, process.argv[2]);`, +); const Service = load('back/services/cron.ts', { '../config': { logPath: root }, '../data/cron': { @@ -17,22 +22,44 @@ const Service = load('back/services/cron.ts', { '../data/runningInstance': {}, '../config/util': { getUniqPath: async () => "log's $directory" }, '../schedule/client': {}, - '../shared/pLimit': { manualRunWithCronLimit: fn => fn() }, - '../shared/triggerHistory': { TriggerHistory: class { - async bindCommand(_, pid, log) { process.send({ pid, log }); return true; } - async shouldStop() { return false; } - async complete() {} - } }, - '../shared/logStreamManager': { logStreamManager: new LogStreamManager(root) }, - 'cross-spawn': { spawn: (file, args, options) => { - // Record the real supervisor's receipt without starting a panel database. - if (file === 'python3') args[7] = reporter; - return spawn(file, args, options); - } }, + '../cron/execution/cronLimit': { manualRunWithCronLimit: (fn) => fn() }, + '../cron/history': { + TriggerHistory: class { + async bindCommand(_, pid, log) { + process.send({ pid, log }); + return true; + } + async shouldStop() { + return false; + } + async complete() {} + }, + }, + '../shared/logStreamManager': { + logStreamManager: new LogStreamManager(root), + }, + 'cross-spawn': { + spawn: (file, args, options) => { + // Record the real supervisor's receipt without starting a panel database. + if (file === 'python3') args[7] = reporter; + return spawn(file, args, options); + }, + }, }).default; -const service = new Service({ info() {}, error(...args) { console.error(...args); } }); -service.getDb = async () => ({ id: 1, status: 3, command, queued_token: 'test', log_path: '' }); +const service = new Service({ + info() {}, + error(...args) { + console.error(...args); + }, +}); +service.getDb = async () => ({ + id: 1, + status: 3, + command, + queued_token: 'test', + log_path: '', +}); service.makeCommand = () => command; -service.runSingle(1, 'test', 'manual-log-test').then(result => { +service.runSingle(1, 'test', 'manual-log-test').then((result) => { process.send({ result }, () => process.disconnect()); }); diff --git a/test/helpers/receipt-allocation-reuse-ext4.cjs b/test/helpers/receipt-allocation-reuse-ext4.cjs index 014d70ed..b40397a3 100644 --- a/test/helpers/receipt-allocation-reuse-ext4.cjs +++ b/test/helpers/receipt-allocation-reuse-ext4.cjs @@ -8,54 +8,93 @@ const { once } = require('node:events'); const { setTimeout: delay } = require('node:timers/promises'); const { createHash } = require('node:crypto'); const volume = '/ql/data/db'; -const moduleFile = '/ql/static/build/shared/managedExit.cjs'; +const moduleFile = '/ql/static/build/cron/settlement/exitReceipt.cjs'; const { receiptPath, readExit, retiringExits } = require(moduleFile); (async () => { const usage = await fs.statfs(volume); - assert.equal(usage.type,0xef53); - assert.ok(usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192); - await fs.access(path.join(volume,'.qa-isolated-volume')); - const root = await fs.mkdtemp(path.join(volume,'.qa-slot-')); + assert.equal(usage.type, 0xef53); + assert.ok( + usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192, + ); + await fs.access(path.join(volume, '.qa-isolated-volume')); + const root = await fs.mkdtemp(path.join(volume, '.qa-slot-')); const workers = []; try { process.env.QL_DATA_DIR = root; - const id = 'occupied-slot', directory = path.join(path.dirname(receiptPath(id)),'.claim.' + id + '.qaTest'); - await fs.mkdir(directory,{recursive:true}); - const slot = path.join(directory,'receipt'); - const receipt = code => JSON.stringify({code, signal:null, time:1000, version:1, - checksum:createHash('sha256').update(JSON.stringify([id,code,null,1000])).digest('hex')}); - await fs.writeFile(slot,receipt(17),{flag:'wx'}); - for (const role of ['A','B']) { + const id = 'occupied-slot', + directory = path.join( + path.dirname(receiptPath(id)), + '.claim.' + id + '.qaTest', + ); + await fs.mkdir(directory, { recursive: true }); + const slot = path.join(directory, 'receipt'); + const receipt = (code) => + JSON.stringify({ + code, + signal: null, + time: 1000, + version: 1, + checksum: createHash('sha256') + .update(JSON.stringify([id, code, null, 1000])) + .digest('hex'), + }); + await fs.writeFile(slot, receipt(17), { flag: 'wx' }); + for (const role of ['A', 'B']) { const barrier = path.join(root, role); - const child = spawn(process.execPath,[path.join(__dirname,'receipt-claim-reuse-worker.cjs'), - moduleFile, slot, id, '17', '1000', barrier],{stdio:'inherit'}); - workers.push({barrier,child,done:once(child,'exit')}); + const child = spawn( + process.execPath, + [ + path.join(__dirname, 'receipt-claim-reuse-worker.cjs'), + moduleFile, + slot, + id, + '17', + '1000', + barrier, + ], + { stdio: 'inherit' }, + ); + workers.push({ barrier, child, done: once(child, 'exit') }); } const deadline = performance.now() + 10000; - const before = await Promise.all(workers.map(async ({barrier}) => { - while (performance.now() < deadline) { - try { return JSON.parse(await fs.readFile(barrier+'.ready','utf8')); } - catch (error) { if (error.code !== 'ENOENT') throw error; } - await delay(20); - } - throw Error('Both collectors must validate the original slot'); - })); - assert.equal(before[0].fileInode,before[1].fileInode); - assert.equal(before[0].directoryInode,before[1].directoryInode); - await fs.writeFile(slot+'.new',receipt(42),{flag:'wx'}); - await fs.rename(slot+'.new',slot); + const before = await Promise.all( + workers.map(async ({ barrier }) => { + while (performance.now() < deadline) { + try { + return JSON.parse(await fs.readFile(barrier + '.ready', 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + await delay(20); + } + throw Error('Both collectors must validate the original slot'); + }), + ); + assert.equal(before[0].fileInode, before[1].fileInode); + assert.equal(before[0].directoryInode, before[1].directoryInode); + await fs.writeFile(slot + '.new', receipt(42), { flag: 'wx' }); + await fs.rename(slot + '.new', slot); const inode = (await fs.stat(slot)).ino; - assert.notEqual(inode,before[0].fileInode); - for (const {barrier} of workers) await fs.writeFile(barrier+'.go',''); - for (const {done} of workers) assert.deepEqual(await done,[0,null]); + assert.notEqual(inode, before[0].fileInode); + for (const { barrier } of workers) await fs.writeFile(barrier + '.go', ''); + for (const { done } of workers) assert.deepEqual(await done, [0, null]); const captures = await retiringExits(); - assert.equal(captures.length,1); - assert.equal((await fs.stat(captures[0].file)).ino,inode); - assert.equal((await readExit(id,captures[0].file)).code,42); - console.log(JSON.stringify({before,replacementInode:inode,retained:captures[0].file})); + assert.equal(captures.length, 1); + assert.equal((await fs.stat(captures[0].file)).ino, inode); + assert.equal((await readExit(id, captures[0].file)).code, 42); + console.log( + JSON.stringify({ + before, + replacementInode: inode, + retained: captures[0].file, + }), + ); } finally { - for (const {child} of workers) if (child.exitCode === null) child.kill(); - await fs.rm(root,{recursive:true,force:true}); + for (const { child } of workers) if (child.exitCode === null) child.kill(); + await fs.rm(root, { recursive: true, force: true }); } -})().catch(error => { console.error(error); process.exitCode=1; }); +})().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/test/helpers/receipt-boundary-worker.cjs b/test/helpers/receipt-boundary-worker.cjs index a7ce9534..54ac4177 100644 --- a/test/helpers/receipt-boundary-worker.cjs +++ b/test/helpers/receipt-boundary-worker.cjs @@ -5,14 +5,21 @@ const path = require('node:path'); const [operation, stage, side, id] = process.argv.slice(2); const root = process.env.QL_DATA_DIR; const load = require('./load-security-module.cjs'); -const db = load('back/data/index.ts', { '../config/index': { dbPath: root } }).sequelize; -const { TriggerHistory } = require('../../back/shared/triggerHistory'); +const db = load('back/data/index.ts', { + '../config/index': { dbPath: root }, +}).sequelize; +const { TriggerHistory } = require('../../back/cron/history'); const history = new TriggerHistory(db); const stats = load('back/data/cronStats.ts', { '.': { sequelize: db } }); -const running = load('back/data/runningInstance.ts', { '.': { sequelize: db } }); +const running = load('back/data/runningInstance.ts', { + '.': { sequelize: db }, +}); const Retention = load('back/services/retention.ts', { - '../data': { sequelize: db }, '../data/cronStats': stats, '../data/runningInstance': running, - '../data/system': {}, '../config': {}, + '../data': { sequelize: db }, + '../data/cronStats': stats, + '../data/runningInstance': running, + '../data/system': {}, + '../config': {}, }).default; function barrier() { @@ -45,7 +52,8 @@ function intercept(object, method, matches) { return result; }; } -const captured = file => path.basename(file).startsWith('.pending.' + id + '.r-'); +const captured = (file) => + path.basename(file).startsWith('.pending.' + id + '.r-'); if (stage === 'readClaim') { const open = fs.promises.open.bind(fs.promises); fs.promises.open = async (file, ...options) => { @@ -53,16 +61,34 @@ if (stage === 'readClaim') { if (captured(file)) { if (side === 'before') barrier(); const close = handle.close.bind(handle); - handle.close = async () => { await close(); if (side === 'after') barrier(); }; + handle.close = async () => { + await close(); + if (side === 'after') barrier(); + }; } return handle; }; -} else if (stage === 'move') intercept(fs.promises, 'rename', (src) => path.basename(src) === id); +} else if (stage === 'move') + intercept(fs.promises, 'rename', (src) => path.basename(src) === id); else if (stage === 'unlink') intercept(fs.promises, 'unlink', captured); -else intercept(db, 'query', sql => String(sql).replace(/[`"]/g, '').startsWith(statements[stage].replace(/"/g, ''))); +else + intercept(db, 'query', (sql) => + String(sql) + .replace(/[`"]/g, '') + .startsWith(statements[stage].replace(/"/g, '')), + ); (async () => { - if (operation === 'prune') await new Retention().cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 }); + if (operation === 'prune') + await new Retention().cleanup({ + runningInstanceRetentionDays: 1, + cronStatRetentionDays: 1, + }); else await history.complete(id, 'unknown', null, null); throw Error('Expected barrier was never reached: ' + operation + '/' + stage); -})().catch(e => { console.error(e); process.exitCode = 1; }).finally(() => db.close()); +})() + .catch((e) => { + console.error(e); + process.exitCode = 1; + }) + .finally(() => db.close()); diff --git a/test/helpers/receipt-claim-reuse-worker.cjs b/test/helpers/receipt-claim-reuse-worker.cjs index 806f516a..bc77a386 100644 --- a/test/helpers/receipt-claim-reuse-worker.cjs +++ b/test/helpers/receipt-claim-reuse-worker.cjs @@ -1,6 +1,7 @@ const fs = require('node:fs'); const path = require('node:path'); -const [moduleFile, file, id, outcome, time, barrier, recovery, stage] = process.argv.slice(2); +const [moduleFile, file, id, outcome, time, barrier, recovery, stage] = + process.argv.slice(2); const { retireLegacyFile } = require(moduleFile); // Both collectors have read the source and hold its directory lock at this point. const rename = fs.promises.rename.bind(fs.promises); @@ -10,38 +11,69 @@ async function gate(suffix, data, release) { fs.renameSync(barrier + '.tmp', barrier + suffix); const limit = performance.now() + 90000; while (!fs.existsSync(barrier + release)) { - if (performance.now() > limit) throw Error('Timed out waiting for ' + release); - await new Promise(resolve => setTimeout(resolve, 25)); + if (performance.now() > limit) + throw Error('Timed out waiting for ' + release); + await new Promise((resolve) => setTimeout(resolve, 25)); } } fs.promises.rename = async (source, target) => { - if (await fs.promises.realpath(source) !== file) return rename(source, target); - const ready = { pid: process.pid, path:file, target, + if ((await fs.promises.realpath(source)) !== file) + return rename(source, target); + const ready = { + pid: process.pid, + path: file, + target, directoryInode: (await fs.promises.stat(path.dirname(source))).ino, - fileInode: (await fs.promises.stat(source)).ino }; + fileInode: (await fs.promises.stat(source)).ino, + }; await gate('.ready', ready, '.go'); try { await rename(source, target); } catch (error) { if (stage === 'recordMoveError') - fs.writeFileSync(barrier + '.error', JSON.stringify({code:error.code, errno:error.errno, syscall:error.syscall})); + fs.writeFileSync( + barrier + '.error', + JSON.stringify({ + code: error.code, + errno: error.errno, + syscall: error.syscall, + }), + ); throw error; } captured = target; - if (stage === 'holdMoved') await gate('.moved', {target, inode:(await fs.promises.stat(target)).ino}, '.release'); + if (stage === 'holdMoved') + await gate( + '.moved', + { target, inode: (await fs.promises.stat(target)).ino }, + '.release', + ); }; const unlink = fs.promises.unlink.bind(fs.promises); -fs.promises.unlink = async file => { +fs.promises.unlink = async (file) => { if (stage === 'holdUnlink' && captured === file) - await gate('.checked', {target:file, inode:(await fs.promises.stat(file)).ino}, '.release'); + await gate( + '.checked', + { target: file, inode: (await fs.promises.stat(file)).ino }, + '.release', + ); return unlink(file); }; const settlement = recovery - ? require(recovery).triggerHistory().complete(id,'unknown',null,null) - : retireLegacyFile(id, file, {outcome, time:Number(time)}); -settlement.catch(error => { - // Another collector may have already removed the same settled inode. - if (error.code !== 'ENOENT') { console.error(error); process.exitCode = 1; } -}).finally(() => { - if (recovery) return require(path.join(path.dirname(recovery),'../data')).sequelize.close(); -}); + ? require(recovery).triggerHistory().complete(id, 'unknown', null, null) + : retireLegacyFile(id, file, { outcome, time: Number(time) }); +settlement + .catch((error) => { + // Another collector may have already removed the same settled inode. + if (error.code !== 'ENOENT') { + console.error(error); + process.exitCode = 1; + } + }) + .finally(() => { + if (recovery) + return require(path.join( + path.dirname(recovery), + '../data', + )).sequelize.close(); + }); diff --git a/test/helpers/receipt-migration-worker.cjs b/test/helpers/receipt-migration-worker.cjs index 0cb1d9d9..6a6f175c 100644 --- a/test/helpers/receipt-migration-worker.cjs +++ b/test/helpers/receipt-migration-worker.cjs @@ -4,21 +4,37 @@ const fs = require('node:fs'); const path = require('node:path'); const [modules, side, checkpoint] = process.argv.slice(2); const { sequelize } = require(path.join(modules, 'data')); -const { migrateSchema, prunedExitMigrationId } = require(path.join(modules, 'shared/schemaMigrations')); -if (!['before', 'after'].includes(side)) throw new Error('Unknown commit boundary'); +const { migrateSchema, prunedExitMigrationId } = require(path.join( + modules, + 'data/schemaMigrations', +)); +if (!['before', 'after'].includes(side)) + throw new Error('Unknown commit boundary'); const transaction = sequelize.transaction.bind(sequelize); -sequelize.transaction = callback => transaction(async tx => { - await callback(tx); - const [rows] = await sequelize.query(`SELECT +sequelize.transaction = (callback) => + transaction(async (tx) => { + await callback(tx); + const [rows] = await sequelize.query( + `SELECT (SELECT COUNT(*) FROM SchemaMigrations WHERE id=$id) AS marker, - (SELECT COUNT(*) FROM CronUnmatchedBoundExits) AS proofs`, { transaction: tx, bind: { id: prunedExitMigrationId } }); - if (rows[0].marker !== 1 || rows[0].proofs === 0) throw new Error('No verified migration batch'); - const hold = () => { - fs.writeFileSync(checkpoint + '.tmp', JSON.stringify({ side, pid: process.pid, ...rows[0] }), {flag: 'wx'}); - fs.renameSync(checkpoint + '.tmp', checkpoint); - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0); - }; - if (side === 'before') hold(); - else tx.afterCommit(hold); + (SELECT COUNT(*) FROM CronUnmatchedBoundExits) AS proofs`, + { transaction: tx, bind: { id: prunedExitMigrationId } }, + ); + if (rows[0].marker !== 1 || rows[0].proofs === 0) + throw new Error('No verified migration batch'); + const hold = () => { + fs.writeFileSync( + checkpoint + '.tmp', + JSON.stringify({ side, pid: process.pid, ...rows[0] }), + { flag: 'wx' }, + ); + fs.renameSync(checkpoint + '.tmp', checkpoint); + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0); + }; + if (side === 'before') hold(); + else tx.afterCommit(hold); + }); +migrateSchema(sequelize).catch((error) => { + console.error(error); + process.exitCode = 1; }); -migrateSchema(sequelize).catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/test/helpers/receipt-publisher-barrier.cjs b/test/helpers/receipt-publisher-barrier.cjs index a383f372..35a239a8 100644 --- a/test/helpers/receipt-publisher-barrier.cjs +++ b/test/helpers/receipt-publisher-barrier.cjs @@ -1,6 +1,6 @@ const fs = require('node:fs'); const path = require('node:path'); -const { writeExit } = require('../../back/shared/managedExit.cjs'); +const { writeExit } = require('../../back/cron/settlement/exitReceipt.cjs'); const [stage, time] = process.argv.slice(2); const write = fs.writeFileSync; function checkpoint(point) { diff --git a/test/helpers/receipt-reclaim-ext4.cjs b/test/helpers/receipt-reclaim-ext4.cjs index 006052fe..2eca2ae4 100644 --- a/test/helpers/receipt-reclaim-ext4.cjs +++ b/test/helpers/receipt-reclaim-ext4.cjs @@ -4,14 +4,24 @@ const fs = require('node:fs'); const path = require('node:path'); const { exhaust } = require('./receipt-volume-full.cjs'); const { sequelize } = require('/ql/static/build/data'); -const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory'); +const { TriggerHistory } = require('/ql/static/build/cron/history'); const [stage, id] = process.argv.slice(2); const volume = '/ql/data/db'; const canonical = path.join(volume, 'cron-exits', id); const control = '/tmp/journal-qa'; const capacity = () => fs.statfsSync(volume).bavail; -if (fs.statfsSync(volume).type !== 0xef53 || !/^[a-z0-9-]+$/.test(id) || - !['rename-before','rename-after','rename-enospc','unlink-before','unlink-after','unlink-injected'].includes(stage)) { +if ( + fs.statfsSync(volume).type !== 0xef53 || + !/^[a-z0-9-]+$/.test(id) || + ![ + 'rename-before', + 'rename-after', + 'rename-enospc', + 'unlink-before', + 'unlink-after', + 'unlink-injected', + ].includes(stage) +) { throw Error('Expected a supported ext4 collection boundary and execution ID'); } @@ -30,8 +40,9 @@ async function atBoundary(source, destination, operation) { const pin = path.join(volume, '.qa-reclaim-pin'); fs.linkSync(source, pin); exhaust(false); - const event = {stage, id, source, destination, blocksBefore: capacity()}; - if (event.blocksBefore !== 0) throw Error('Expected an exhausted data volume'); + const event = { stage, id, source, destination, blocksBefore: capacity() }; + if (event.blocksBefore !== 0) + throw Error('Expected an exhausted data volume'); if (stage === 'rename-enospc') { // Fill the target directory with entries the same length as the capture name. // Hard links expend directory space without needing another inode. @@ -39,7 +50,16 @@ async function atBoundary(source, destination, operation) { let count = 0; try { for (;;) { - fs.linkSync(pin, path.join(dir, 'q' + count.toString(36).padStart(path.basename(destination).length - 1, '0'))); + fs.linkSync( + pin, + path.join( + dir, + 'q' + + count + .toString(36) + .padStart(path.basename(destination).length - 1, '0'), + ), + ); count++; } } catch (error) { @@ -47,45 +67,86 @@ async function atBoundary(source, destination, operation) { } event.extraDirectoryEntries = count; } - if (stage.endsWith('-before')) hold({...event, called:false}); + if (stage.endsWith('-before')) hold({ ...event, called: false }); if (stage === 'unlink-injected') { // Explicitly synthetic. Keep the file and let the real collector unwind. - throw Object.assign(Error('Injected unlink capacity error'), {code:'ENOSPC', event}); + throw Object.assign(Error('Injected unlink capacity error'), { + code: 'ENOSPC', + event, + }); } try { await operation(); } catch (error) { if (stage !== 'rename-enospc' || error.code !== 'ENOSPC') throw error; - hold({...event, called:true, result:error.code, errno:error.errno, syscall:error.syscall, - sourceExists:fs.existsSync(source), destinationExists:fs.existsSync(destination)}); + hold({ + ...event, + called: true, + result: error.code, + errno: error.errno, + syscall: error.syscall, + sourceExists: fs.existsSync(source), + destinationExists: fs.existsSync(destination), + }); } - if (stage === 'rename-enospc') throw Error('Expected rename to need another directory block'); - hold({...event, called:true, result:'success', blocksAfter:capacity(), - sourceExists:fs.existsSync(source), destinationExists:destination && fs.existsSync(destination)}); + if (stage === 'rename-enospc') + throw Error('Expected rename to need another directory block'); + hold({ + ...event, + called: true, + result: 'success', + blocksAfter: capacity(), + sourceExists: fs.existsSync(source), + destinationExists: destination && fs.existsSync(destination), + }); } const rename = fs.promises.rename.bind(fs.promises); const unlink = fs.promises.unlink.bind(fs.promises); -let reached = false, injected; -fs.promises.rename = (from,to) => { +let reached = false, + injected; +fs.promises.rename = (from, to) => { if (!reached && stage.startsWith('rename-') && from === canonical) { reached = true; - const destination = path.join(fs.realpathSync(path.dirname(to)), path.basename(to)); - return atBoundary(from,destination,() => rename(from,to)); + const destination = path.join( + fs.realpathSync(path.dirname(to)), + path.basename(to), + ); + return atBoundary(from, destination, () => rename(from, to)); } - return rename(from,to); + return rename(from, to); }; -fs.promises.unlink = async file => { - if (!reached && stage.startsWith('unlink-') && path.basename(file).startsWith('.pending.' + id + '.r-')) { +fs.promises.unlink = async (file) => { + if ( + !reached && + stage.startsWith('unlink-') && + path.basename(file).startsWith('.pending.' + id + '.r-') + ) { reached = true; - try {return await atBoundary(fs.realpathSync(file),null,() => unlink(file));} - catch (error) { if (stage === 'unlink-injected') injected = error; throw error; } + try { + return await atBoundary(fs.realpathSync(file), null, () => unlink(file)); + } catch (error) { + if (stage === 'unlink-injected') injected = error; + throw error; + } } return unlink(file); }; -new TriggerHistory(sequelize).complete(id,'unknown',null,null).then(() => { - if (injected?.code === 'ENOSPC') hold({...injected.event, called:false, injected:'ENOSPC', - privateFileRetained:fs.existsSync(injected.event.source)}); - throw Error('Collector did not reach the expected power cut'); -}).catch(error => {console.error(error); process.exitCode = 1;}).finally(() => sequelize.close()); +new TriggerHistory(sequelize) + .complete(id, 'unknown', null, null) + .then(() => { + if (injected?.code === 'ENOSPC') + hold({ + ...injected.event, + called: false, + injected: 'ENOSPC', + privateFileRetained: fs.existsSync(injected.event.source), + }); + throw Error('Collector did not reach the expected power cut'); + }) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }) + .finally(() => sequelize.close()); diff --git a/test/helpers/receipt-volume-full.cjs b/test/helpers/receipt-volume-full.cjs index 71680260..b434e703 100644 --- a/test/helpers/receipt-volume-full.cjs +++ b/test/helpers/receipt-volume-full.cjs @@ -6,15 +6,27 @@ const volume = '/ql/data/db'; const barriers = '/tmp/journal-qa'; const [mode, id] = process.argv.slice(2); const capacity = fs.statfsSync(volume); -const filesystem = fs.readFileSync('/proc/self/mountinfo', 'utf8').split('\n') - .find(line => line.split(' ')[4] === volume)?.split(' - ')[1].split(' ')[0]; +const filesystem = fs + .readFileSync('/proc/self/mountinfo', 'utf8') + .split('\n') + .find((line) => line.split(' ')[4] === volume) + ?.split(' - ')[1] + .split(' ')[0]; const ext4 = filesystem === 'ext4' && capacity.type === 0xef53; -if (!(ext4 || (filesystem === 'tmpfs' && capacity.type === 0x01021994)) || capacity.blocks <= 0 || capacity.blocks * capacity.bsize > 32 * 1024 * 1024 || - capacity.files <= 0 || capacity.files > 8192 || !fs.existsSync(path.join(volume, '.qa-isolated-volume'))) { - throw Error('Requires a dedicated bounded ext4 or tmpfs for receipt acceptance'); +if ( + !(ext4 || (filesystem === 'tmpfs' && capacity.type === 0x01021994)) || + capacity.blocks <= 0 || + capacity.blocks * capacity.bsize > 32 * 1024 * 1024 || + capacity.files <= 0 || + capacity.files > 8192 || + !fs.existsSync(path.join(volume, '.qa-isolated-volume')) +) { + throw Error( + 'Requires a dedicated bounded ext4 or tmpfs for receipt acceptance', + ); } const { sequelize: db } = require('/ql/static/build/data'); -const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory'); +const { TriggerHistory } = require('/ql/static/build/cron/history'); function record(name, data) { fs.writeFileSync(path.join(barriers, name + '.tmp'), JSON.stringify(data)); fs.renameSync(path.join(barriers, name + '.tmp'), path.join(barriers, name)); @@ -34,61 +46,102 @@ function exhaust(inodes) { if (ext4) { if (fd !== undefined) { // A large allocation may fail while individual blocks remain usable. - try { for (;;) fs.writeSync(fd, Buffer.alloc(capacity.bsize)); } - catch (last) { if (last.code !== 'ENOSPC') throw last; } + try { + for (;;) fs.writeSync(fd, Buffer.alloc(capacity.bsize)); + } catch (last) { + if (last.code !== 'ENOSPC') throw last; + } fs.fsyncSync(fd); } for (const entry of [dir, volume]) { const handle = fs.openSync(entry, fs.constants.O_DIRECTORY); - try { fs.fsyncSync(handle); } finally { fs.closeSync(handle); } + try { + fs.fsyncSync(handle); + } finally { + fs.closeSync(handle); + } } } - record(mode + '-capacity', { dir, error: error.code, statfs: fs.statfsSync(volume) }); - } finally { if (fd !== undefined) fs.closeSync(fd); } + record(mode + '-capacity', { + dir, + error: error.code, + statfs: fs.statfsSync(volume), + }); + } finally { + if (fd !== undefined) fs.closeSync(fd); + } } // A short receipt fits one block. Request another block beyond any ext4 // preallocation to obtain kernel ENOSPC while the original prefix is intact. function writePartialReceipt() { const receipt = JSON.parse(process.argv[4]); - const { writeExit } = require('/ql/static/build/shared/managedExit.cjs'); + const { + writeExit, + } = require('/ql/static/build/cron/settlement/exitReceipt.cjs'); const write = fs.writeFileSync; fs.writeFileSync = (file, content, options) => { - if (!content || path.dirname(file) !== path.join(volume, 'cron-exits')) return write(file, content, options); - const fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_SYNC, 0o600); + if (!content || path.dirname(file) !== path.join(volume, 'cron-exits')) + return write(file, content, options); + const fd = fs.openSync( + file, + fs.constants.O_CREAT | + fs.constants.O_EXCL | + fs.constants.O_WRONLY | + fs.constants.O_SYNC, + 0o600, + ); try { const bytes = Buffer.from(content); fs.writeSync(fd, bytes, 0, 12, 0); record('partial-ready', { id, file, bytes: fs.fstatSync(fd).size }); const deadline = performance.now() + 120000; while (!fs.existsSync(path.join(barriers, 'partial-continue'))) { - if (performance.now() > deadline) throw Error('Short-write barrier expired'); + if (performance.now() > deadline) + throw Error('Short-write barrier expired'); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30); } - const offset = ext4 ? (capacity.blocks + 1) * capacity.bsize : capacity.bsize; - try { fs.writeSync(fd, bytes, 12, bytes.length - 12, offset); } - catch (error) { - record('partial-error', { id, file, code: error.code, bytes: fs.fstatSync(fd).size, offset }); + const offset = ext4 + ? (capacity.blocks + 1) * capacity.bsize + : capacity.bsize; + try { + fs.writeSync(fd, bytes, 12, bytes.length - 12, offset); + } catch (error) { + record('partial-error', { + id, + file, + code: error.code, + bytes: fs.fstatSync(fd).size, + offset, + }); // Keep the torn file open across the guest power cut in the ext4 run. - if (ext4) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000); + if (ext4) + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000); throw error; } throw Error('Expected ENOSPC while allocating the next page'); - } finally { fs.closeSync(fd); } + } finally { + fs.closeSync(fd); + } }; writeExit(id, receipt.code, receipt.signal, receipt.time); } async function main() { if (mode === 'partial') return writePartialReceipt(); - if (!['commit','collect'].includes(mode)) throw Error('Unexpected fault mode'); + if (!['commit', 'collect'].includes(mode)) + throw Error('Unexpected fault mode'); await db.query('CREATE TABLE IF NOT EXISTS qa_commit_payload (payload BLOB)'); const original = db.query.bind(db); if (mode === 'commit') { db.query = async (sql, ...args) => { if (!String(sql).startsWith('COMMIT')) return original(sql, ...args); exhaust(false); - try { return await original(sql, ...args); } - catch (error) { - record('commit-error', { code: error.original?.code, sql: String(sql) }); + try { + return await original(sql, ...args); + } catch (error) { + record('commit-error', { + code: error.original?.code, + sql: String(sql), + }); throw error; } }; @@ -102,27 +155,47 @@ async function main() { } try { await rename(...args); - record('collect-moved', { source:args[0], destination:args[1] }); + record('collect-moved', { source: args[0], destination: args[1] }); + } catch (error) { + record('collect-error', { code: error.code, prefix: args[0] }); + throw error; } - catch (error) { record('collect-error', { code: error.code, prefix: args[0] }); throw error; } }; } - await db.transaction(async transaction => { + await db.transaction(async (transaction) => { if (mode === 'commit') { await db.query('PRAGMA cache_spill=OFF', { transaction }); - await db.query('INSERT INTO qa_commit_payload VALUES (zeroblob(524288))', { transaction }); + await db.query( + 'INSERT INTO qa_commit_payload VALUES (zeroblob(524288))', + { transaction }, + ); } record(mode + '-ready', { id }); const deadline = Date.now() + 86400000 * 3; while (!fs.existsSync(path.join(barriers, mode + '-continue'))) { if (Date.now() >= deadline) throw Error('Timed out at database barrier'); - await new Promise(r => setTimeout(r, 30)); + await new Promise((r) => setTimeout(r, 30)); } - await new TriggerHistory(db).completeCommandExit(id, 'unknown', null, null, transaction); + await new TriggerHistory(db).completeCommandExit( + id, + 'unknown', + null, + null, + transaction, + ); }); } module.exports = { exhaust }; -if (require.main === module) main().catch(error => { - if (mode !== 'commit' || error.original?.code !== 'SQLITE_FULL') {console.error(error); process.exitCode = 1;} -}).finally(async () => { await db.close(); record(mode + '-done', { id }); }); +if (require.main === module) + main() + .catch((error) => { + if (mode !== 'commit' || error.original?.code !== 'SQLITE_FULL') { + console.error(error); + process.exitCode = 1; + } + }) + .finally(async () => { + await db.close(); + record(mode + '-done', { id }); + }); diff --git a/test/helpers/runtime-module-graph.cjs b/test/helpers/runtime-module-graph.cjs new file mode 100644 index 00000000..3c300613 --- /dev/null +++ b/test/helpers/runtime-module-graph.cjs @@ -0,0 +1,90 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const ts = require('typescript'); + +// Inspect emitted imports so type-only references do not become false cycles. +// Include literal require() calls inside functions and executable entry points. +function runtimeModuleGraph(root) { + const files = []; + const walk = (directory) => { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const file = path.join(directory, entry.name); + if (entry.isDirectory()) walk(file); + else if (/\.(ts|js|cjs)$/.test(file) && !file.endsWith('.d.ts')) + files.push(file); + } + }; + walk(root); + const graph = new Map(files.map((file) => [file, new Set()])); + for (const file of files) { + const source = fs.readFileSync(file, 'utf8'); + const emitted = file.endsWith('.ts') + ? ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2017, + experimentalDecorators: true, + emitDecoratorMetadata: true, + esModuleInterop: true, + }, + }).outputText + : source; + const parsed = ts.createSourceFile( + file, + emitted, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.JS, + ); + const visit = (node) => { + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'require' && + node.arguments.length === 1 && + ts.isStringLiteral(node.arguments[0]) && + node.arguments[0].text.startsWith('.') + ) { + const base = path.normalize( + path.join(path.dirname(file), node.arguments[0].text), + ); + const target = [ + base, + base + '.ts', + base + '.js', + base + '.cjs', + path.join(base, 'index.ts'), + path.join(base, 'index.js'), + ].find((candidate) => graph.has(candidate)); + if (target) graph.get(file).add(target); + } + ts.forEachChild(node, visit); + }; + visit(parsed); + } + return graph; +} + +function moduleCycles(graph) { + const visited = new Set(), + active = new Set(), + stack = [], + cycles = []; + const visit = (file) => { + if (active.has(file)) { + cycles.push([...stack.slice(stack.indexOf(file)), file]); + return; + } + if (visited.has(file)) return; + visited.add(file); + active.add(file); + stack.push(file); + for (const dependency of graph.get(file) || []) visit(dependency); + stack.pop(); + active.delete(file); + }; + for (const file of graph.keys()) visit(file); + return cycles; +} + +module.exports = { runtimeModuleGraph, moduleCycles }; diff --git a/version.yaml b/version.yaml index f84b1df6..cb58b369 100644 --- a/version.yaml +++ b/version.yaml @@ -1,6 +1,6 @@ version: 2.25.0-rc.3 changeLogLink: https://github.com/whyour/qinglong/blob/develop/docs/releases/2.25.0-rc.3.md -publishTime: "2026-11-21 19:00:16" +publishTime: '2026-11-21 19:00:16' changeLog: | 1. 补齐 OpenAPI 可执行配置、脚本写入、趋势查询和 Perl 环境变量的安全边界。 2. 修复 HTTP 工作进程异常退出后的任务日志保留,完善正常退出与失败任务的日志记录。