Skip to content

Commit b6e6545

Browse files
feat(runtime): package jobs honour the host's per-kernel scheduledWorkPolicy (#31423)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XUJTu64tU69Q3BhNU1nAuhF)_ Fixes #31382 Clause-②: yes — an optional `scheduledWorkPolicy` member on `AppPlugin` / `AppArtifactJobSchedulingOptions` (both exported from runtime's `.` entry, measured: `packages/runtime/src/index.ts` exports `AppPlugin` and the type `AppArtifactJobSchedulingOptions`) and two names newly exported by `@objectstack/types` (`ScheduledWorkPolicySource`, `readScheduledWorkPolicy`) widen published surfaces; nothing narrows Metadata-protocol: none ## 维护者速读 - 改了什么:`AppPlugin` 和包 job 排程器 `scheduleAppArtifactJobs` 现在接受宿主按内核给的 `scheduledWorkPolicy`(值或解析函数),和引擎、两个时间触发器用的是同一个类型。策略关掉时,这个内核不排程包里的 `jobs`,之前排过的取消,日志写宿主自己的原因。 - 为什么改:宿主(云端托管运行时)按内核关掉定时工作后,`schedule` 流程不武装,但同一个包的 `jobs` 还在跑。云端实测 Free 环境 2.5 秒写了 5 行(cloud#3733 等这个缝)。 - 风险与回滚:不传策略时逐字节照旧,只读部署开关 `OS_AUTOMATION_SCHEDULED_WORK_ENABLED`(新增 CONTROL 钉住)。`ScheduledWorkPolicySource` / `readScheduledWorkPolicy` 从 `@objectstack/trigger-schedule` 挪到 `@objectstack/types`,trigger-schedule 原名再导出,导入方不用改。回滚即还原本 PR。 - 先看:`packages/runtime/src/app-artifact-handlers.ts` 的 `scheduleAppArtifactJobs` 开关段(`hostPolicy` 一读两用);`packages/types/src/env.ts` 新增的两个名字;`packages/runtime/src/app-plugin.ts` 构造参数。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/app-plugin.scheduled-work-policy.test.ts`,预期 9 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes - `AppArtifactJobSchedulingOptions` gains an optional `scheduledWorkPolicy?: ScheduledWorkPolicySource` (a `ScheduledWorkPolicy` value or a resolver). When it is present, `scheduleAppArtifactJobs` reads it **once** per call and uses that one reading in place of both zero-argument reads: `enabled` for the gate (instead of `resolveScheduledWorkEnabled()`), and `requiresActingOrganization` / `runOwnership` for the per-job organization rule (instead of `resolveScheduledWorkPolicy()`). - Off: nothing is scheduled, `withheld: 'scheduled-work-disabled'`, the app's previously scheduled jobs are cancelled through `retireAppJobs` as today, and the one `info` line carries `scheduledWorkDisabledReason(policy)`, so a host's `hostDisabledReason` (#21110) is printed instead of the deployment sentence. - A host resolver that throws fails closed, like the deployment posture read: nothing scheduled, prior jobs cancelled, `withheld: 'scheduled-work-policy-unreadable'`, one `error` line. - `AppPlugin`'s third constructor argument gains the same optional `scheduledWorkPolicy` and hands it to the binder on `kernel:ready`. - Absent policy: the code path is the old one, read for read (`resolveScheduledWorkEnabled()` before the job-service probe, `resolveScheduledWorkPolicy()` after it). - One spelling of the source type: `@objectstack/runtime` does not depend on `@objectstack/trigger-schedule` (and should not), so `ScheduledWorkPolicySource` and `readScheduledWorkPolicy` move into `@objectstack/types` `env.ts` beside `ScheduledWorkPolicy`. `schedule-trigger.ts` imports them from there and re-exports both under the same names, so `@objectstack/trigger-schedule`'s entry still exports `ScheduledWorkPolicySource` and the triggers' behaviour is unchanged. The seat widened the claim's file face for this before any edit (claim 6718074628). - Changeset `31382-package-jobs-host-scheduled-work-policy.md`: `@objectstack/runtime` patch, `@objectstack/types` patch, `@objectstack/trigger-schedule` patch (ruling A, #25105: a widening of TypeScript exports is not a metadata-protocol change). ## Tests New `packages/runtime/src/app-plugin.scheduled-work-policy.test.ts` (9 cells), the deployment switch ON as the hosted runtime sets it: - Two kernels in one process, each with the real `CronJobAdapter`: the `AppPlugin` handed `enabled: false` holds no job and never runs it; the sibling handed `enabled: true` holds the same job and runs it on trigger. - A resolver policy is read at `kernel:ready`; a third kernel in the same process with no policy stays on the deployment switch. - Cancel: a kernel rebuilt with an off policy on the same job service cancels the job the earlier boot scheduled. - Host reason: one `info` line containing `hostDisabledReason`, and not naming `OS_AUTOMATION_SCHEDULED_WORK_ENABLED`. - Binder: off ⇒ `withheld`, prior jobs in `cancelled`; an `isolated` policy (`requiresActingOrganization: true`) puts an org-less job in `missingOrganization` while the deployment posture is `single`; a throwing resolver ⇒ `scheduled-work-policy-unreadable`, prior job cancelled, one `error`. - Absent policy (CONTROL): switch off ⇒ the `info` line is exactly `[Test] declarative jobs NOT scheduled — ` plus `SCHEDULED_WORK_DISABLED_REASON`; switch off but host hands `enabled: true` ⇒ scheduled. The existing suites `app-plugin.jobs.test.ts`, `app-artifact-handlers.jobs.test.ts`, `app-artifact-handlers.job-pull.test.ts` (zero-argument path, deployment sentence, posture rules) are unchanged and green. <details><summary>Red first and ablations</summary> Red first on `77a675db` (`main`), the new file in place and no fix: `Tests 8 failed | 1 passed (9)`. The one green was the absent-policy deployment-sentence CONTROL. The two-kernels cell read `AssertionError: the off kernel holds no job: expected [ 'hourly_sweep' ] to deeply equal []`; the posture cell read `expected [] to deeply equal [ 'orgless_job' ]`. Ablations via `node scripts/ablation-replace.mjs` on the committed fix (`260d1c1d`); each printed `ok mutation landed: anchor 1 -> 0` and then `ok restored: blob == HEAD (f980f08) and git diff HEAD is empty`: 1. Gate back to the deployment switch only (`if (!resolveScheduledWorkEnabled())`): `Tests 6 failed | 3 passed (9)` (two-kernels, resolver, cancel, host reason, binder off, throwing-resolver cells). 2. Reason back to the deployment constant: `Tests 1 failed | 8 passed (9)`, the host-reason cell. 3. Posture half back to `resolveScheduledWorkPolicy()`: `Tests 1 failed | 8 passed (9)`, the `requiresActingOrganization` cell. </details> ## Acceptance notes - Out of scope, recorded: `AutomationEngineOptions.scheduledWorkPolicy` in `packages/services/service-automation/src/engine.ts` still spells the union inline (`ScheduledWorkPolicy | (() => ScheduledWorkPolicy)`) and keeps its own private `readScheduledWorkPolicy()`. It is structurally the same type, so a host passes one value to all three; pointing it at `@objectstack/types`' `ScheduledWorkPolicySource` is a follow-up for the seat. - `@objectstack/trigger-schedule` keeps exporting `ScheduledWorkPolicySource` from its entry; `readScheduledWorkPolicy` was and stays off its entry (only `schedule-trigger.ts` re-exports it, for `time-relative-trigger.ts`). ## Verification All local runs on head `85ab0691` (branch merged with `origin/main` at `00a88375`); the second commit only adds a module-top `import '@objectstack/metadata'` to the new test, after which `check:test-source-alias`, the new suite and runtime `typecheck` were re-run green. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 69 derived families. `--ran` with exit codes recorded: `69 derived, 68 run, 1 NOT-MEASURED, 0 UNRUN`. - NOT MEASURED: `pnpm check:dual-build-cjs-loads` (exit 3, `PREREQUISITE NOT MET`: reads every package's `dist/`, and only the runtime / trigger-schedule closures were built here). CI builds the full tree and runs it. - First pass reds, fixed and re-run green: `check:test-source-alias` (the new test reached `@objectstack/metadata` through `AppPlugin`'s dynamic import; fixed with the convention's module-top import), `check-plugin-teardown-shape --self-test` (exit 3, shallow clone; `git fetch --depth=1` of the pinned fixture commit, then exit 0), `@objectstack/trigger-schedule` test/typecheck (its devDependency `@objectstack/service-automation` was not built; after building `@objectstack/trigger-schedule^...`, exit 0). - Package suites: `@objectstack/runtime` test `Test Files 556 passed (556)`, `Tests 8966 passed | 19 skipped (8985)`; `@objectstack/types` test `Test Files 37 passed (37)`, `Tests 870 passed (870)`; `@objectstack/trigger-schedule` test and typecheck exit 0; runtime and types typecheck exit 0. - `pnpm exec eslint` on the five touched source files: exit 0. - Full record: `pm-orders/server/31382-gates-ran.txt` (command :: exit code). --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oC5iX95o2LveAatWo)_ <!-- signed: domain:server#5 · os-project-manager · session_01FEkQ5o8PE7ZtVjcor51wBZ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3d73c1d commit b6e6545

6 files changed

Lines changed: 376 additions & 32 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/types': patch
4+
'@objectstack/trigger-schedule': patch
5+
---
6+
7+
feat(runtime): package jobs honour the host's per-kernel `scheduledWorkPolicy`
8+
9+
Clause-②: yes — an optional `scheduledWorkPolicy` member on `AppPlugin`'s options and on `AppArtifactJobSchedulingOptions` (both exported from the `@objectstack/runtime` entry), and `ScheduledWorkPolicySource` / `readScheduledWorkPolicy` newly exported by `@objectstack/types`, widen published surfaces; nothing narrows.
10+
Metadata-protocol: none
11+
12+
A host that runs many kernels in one process can turn package-authored scheduled work off for one kernel by handing it a `scheduledWorkPolicy`. The automation engine and both schedule triggers have taken it since the per-kernel policy landed, but a package's `jobs` did not: `scheduleAppArtifactJobs` read only the deployment switch `OS_AUTOMATION_SCHEDULED_WORK_ENABLED`, so on a kernel whose host turned scheduled work off, the `schedule` flows stayed unarmed while the same package's jobs kept running.
13+
14+
- `AppPlugin` takes an optional `scheduledWorkPolicy` in its third constructor argument and hands it to the jobs binder on `kernel:ready`.
15+
- `AppArtifactJobSchedulingOptions` takes the same optional `scheduledWorkPolicy`, a value or a resolver. When it is present, `scheduleAppArtifactJobs` reads it once per call in place of both deployment reads: `enabled` gates the call, and `requiresActingOrganization` / `runOwnership` decide whether each job must declare its `organization`.
16+
- When that policy is off, nothing is scheduled, the result is `withheld: 'scheduled-work-disabled'`, the jobs the app scheduled before are cancelled, and the info line carries the host's own `hostDisabledReason` when it gave one, instead of the sentence that tells the reader to set the environment variable.
17+
- A resolver that throws fails closed: nothing is scheduled, the app's earlier jobs are cancelled, the result is `withheld: 'scheduled-work-policy-unreadable'`, and the reason is logged at `error`.
18+
- When no policy is handed, the deployment switch decides, exactly as before.
19+
20+
Give the kernel's engine, its schedule triggers and its `AppPlugin` the same policy.
21+
22+
`ScheduledWorkPolicySource` and `readScheduledWorkPolicy` now live in `@objectstack/types` beside `ScheduledWorkPolicy`, so every binder spells the source type once. `@objectstack/trigger-schedule` re-exports `ScheduledWorkPolicySource` under the same name, so existing imports keep working.

‎packages/runtime/src/app-artifact-handlers.ts‎

Lines changed: 49 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,13 @@ import type {
138138
import { JobSchema } from '@objectstack/spec/system';
139139
import { ScheduleOrganizationSchema } from '@objectstack/spec/automation';
140140
import {
141+
readScheduledWorkPolicy,
141142
resolveScheduledWorkEnabled,
142143
resolveScheduledWorkPolicy,
143144
SCHEDULED_WORK_DISABLED_REASON,
145+
scheduledWorkDisabledReason,
144146
type ScheduledWorkPolicy,
147+
type ScheduledWorkPolicySource,
145148
} from '@objectstack/types';
146149
import { SEMCONV } from '@objectstack/observability';
147150
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
@@ -629,16 +632,34 @@ export interface AppArtifactJobSchedulingOptions {
629632
ql: IObjectQLEngine | undefined;
630633
/** Who is scheduling, for the log lines — `'AppPlugin'`, `'MarketplaceInstallLocal'`. */
631634
source?: string;
635+
/**
636+
* [#31382] THIS kernel's scheduled-work policy, as its host decided it — the
637+
* jobs half of #19834, the same source the automation engine and both
638+
* schedule triggers take. Present, it is read ONCE per call in place of
639+
* both zero-argument deployment reads: `enabled` gates the call, and
640+
* `requiresActingOrganization` / `runOwnership` are the per-job
641+
* organization rule. Off, nothing is scheduled, the app's previously
642+
* scheduled jobs are cancelled, and the info line carries
643+
* `scheduledWorkDisabledReason(policy)` — the host's own reason when it
644+
* gave one (#21110).
645+
*
646+
* Absent (the default), `resolveScheduledWorkEnabled()` and
647+
* `resolveScheduledWorkPolicy()` are read exactly as before:
648+
* `OS_AUTOMATION_SCHEDULED_WORK_ENABLED` keeps its meaning. Hand the
649+
* engine and the triggers of the same kernel the same policy.
650+
*/
651+
scheduledWorkPolicy?: ScheduledWorkPolicySource;
632652
}
633653

634654
/** What one {@link scheduleAppArtifactJobs} call scheduled. */
635655
export interface AppArtifactJobScheduling {
636656
/**
637657
* Set when nothing was scheduled for a reason that holds for every job:
638-
* the deployment does not run package-authored scheduled work (#17396), no
639-
* job service is registered, or (#20281 stage ③) the deployment's
640-
* scheduled-work policy could not be read — an unrecognized tenancy
641-
* posture, so whether a job must declare its organization is unknown.
658+
* the deployment does not run package-authored scheduled work (#17396) —
659+
* or (#31382) the host's per-kernel policy turned it off — no job service
660+
* is registered, or (#20281 stage ③) the scheduled-work policy could not
661+
* be read — an unrecognized tenancy posture, or a host resolver that
662+
* threw, so whether a job must declare its organization is unknown.
642663
*/
643664
withheld?: 'scheduled-work-disabled' | 'no-job-service' | 'scheduled-work-policy-unreadable';
644665
/** Jobs scheduled to run their sandboxed `body`. */
@@ -764,8 +785,29 @@ export async function scheduleAppArtifactJobs(
764785
// normal-but-broken. Said once per app with the job count, rather than once
765786
// per job — the remedy is one variable, and repeating it N times is how a
766787
// line stops being read.
767-
if (!resolveScheduledWorkEnabled()) {
768-
logger.info(`${tag} declarative jobs NOT scheduled — ${SCHEDULED_WORK_DISABLED_REASON}`, {
788+
//
789+
// [#31382] A host-handed policy is read here, ONCE, and answers both the
790+
// gate and the posture half below — a resolver that moves between two
791+
// reads must not pair one reading's verdict with another's rule. A
792+
// resolver that throws fails CLOSED, as the deployment read below does.
793+
let hostPolicy: ScheduledWorkPolicy | undefined;
794+
if (options.scheduledWorkPolicy !== undefined) {
795+
try {
796+
hostPolicy = readScheduledWorkPolicy(options.scheduledWorkPolicy);
797+
} catch (err: any) {
798+
logger.error(
799+
`${tag} declarative jobs NOT scheduled — the scheduled-work policy this kernel's host handed could not be `
800+
+ 'read, so whether scheduled work runs here, and whether each job must declare its `organization`, is unknown.',
801+
err as Error,
802+
{ appId, jobCount: jobs.length },
803+
);
804+
if (svc) out.cancelled = await retireAppJobs(svc, appId, new Set(), logger, tag);
805+
return { ...out, withheld: 'scheduled-work-policy-unreadable' };
806+
}
807+
}
808+
if (hostPolicy ? !hostPolicy.enabled : !resolveScheduledWorkEnabled()) {
809+
const reason = hostPolicy ? scheduledWorkDisabledReason(hostPolicy) : SCHEDULED_WORK_DISABLED_REASON;
810+
logger.info(`${tag} declarative jobs NOT scheduled — ${reason}`, {
769811
appId,
770812
jobCount: jobs.length,
771813
});
@@ -786,7 +828,7 @@ export async function scheduleAppArtifactJobs(
786828
// scheduled, and the reason is said at `error`.
787829
let policy: ScheduledWorkPolicy;
788830
try {
789-
policy = resolveScheduledWorkPolicy();
831+
policy = hostPolicy ?? resolveScheduledWorkPolicy();
790832
} catch (err: any) {
791833
logger.error(
792834
`${tag} declarative jobs NOT scheduled — the deployment's scheduled-work policy could not be read, so whether `
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #31382 — a package's `jobs` honour the HOST's per-kernel scheduled-work
5+
* policy, the jobs half of #19834.
6+
*
7+
* A host that runs many kernels in one process (cloud's hosted runtime) turns
8+
* package-authored scheduled work off per kernel by handing each one a
9+
* `scheduledWorkPolicy`. The engine and both schedule triggers took it since
10+
* #19834; `AppPlugin` / `scheduleAppArtifactJobs` read only the zero-argument
11+
* deployment switch, so the same kernel's `jobs` still ran. Pinned here:
12+
*
13+
* - two kernels in one process, the deployment switch ON as the hosted
14+
* runtime sets it: the one handed `enabled: false` schedules none of its
15+
* package's jobs, the sibling handed `enabled: true` runs the same job;
16+
* - a kernel whose policy turns off cancels the jobs its app had scheduled;
17+
* - the off line carries the host's own reason (#21110), not the deployment
18+
* sentence;
19+
* - the policy replaces the posture half too (`requiresActingOrganization`);
20+
* - a resolver that throws fails CLOSED;
21+
* - absent a policy, the deployment resolvers are read exactly as before.
22+
*/
23+
24+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
25+
import type { PluginContext } from '@objectstack/core';
26+
import { defineJob } from '@objectstack/spec/system';
27+
import { CronJobAdapter } from '@objectstack/service-job';
28+
import {
29+
SCHEDULED_WORK_DISABLED_REASON,
30+
SCHEDULED_WORK_ENV,
31+
type ScheduledWorkPolicy,
32+
} from '@objectstack/types';
33+
import { AppPlugin } from './app-plugin.js';
34+
import { scheduleAppArtifactJobs } from './app-artifact-handlers.js';
35+
import { withScheduledWorkOn } from './scheduled-work.test-support.js';
36+
// Paid at collection, not inside a case's clock: `AppPlugin` reaches it through a dynamic import.
37+
import '@objectstack/metadata';
38+
39+
// The deployment switch is ON, as the hosted runtime sets it: what turns a
40+
// kernel's jobs off below is the host's per-kernel policy, nothing else.
41+
withScheduledWorkOn();
42+
43+
const OFF: ScheduledWorkPolicy = {
44+
enabled: false,
45+
posture: 'single',
46+
requiresActingOrganization: false,
47+
runOwnership: 'unscoped',
48+
};
49+
const ON: ScheduledWorkPolicy = { ...OFF, enabled: true };
50+
const HOST_REASON = 'scheduled work is not part of the Free plan — upgrade this environment to Team to run it.';
51+
52+
const APP_ID = 'com.test.hosted';
53+
const JOB = 'hourly_sweep';
54+
55+
/** One kernel: its own job service (the real cron adapter), logger and `kernel:ready` hooks. */
56+
function kernel(adapter: CronJobAdapter = new CronJobAdapter()) {
57+
const readyHooks: Array<() => Promise<void>> = [];
58+
const logger = { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() };
59+
const ctx = {
60+
logger,
61+
registerService: vi.fn(),
62+
getService: vi.fn((name: string) => {
63+
if (name === 'job') return adapter;
64+
if (name === 'objectql') return {};
65+
return undefined;
66+
}),
67+
getServices: vi.fn(() => []),
68+
hook: vi.fn((event: string, cb: () => Promise<void>) => {
69+
if (event === 'kernel:ready') readyHooks.push(cb);
70+
}),
71+
trigger: vi.fn(),
72+
} as unknown as PluginContext;
73+
return {
74+
adapter,
75+
ctx,
76+
logger,
77+
ready: async () => { for (const cb of readyHooks) await cb(); },
78+
infos: () => logger.info.mock.calls.map((c) => String(c[0])),
79+
};
80+
}
81+
82+
/** The same package every kernel below boots: one cron job running a `functions` entry. */
83+
function bundle(sweep: () => Promise<void>) {
84+
return {
85+
id: APP_ID,
86+
jobs: [defineJob({ name: JOB, schedule: { type: 'cron', expression: '0 * * * *' }, handler: 'sweep' })],
87+
functions: { sweep },
88+
};
89+
}
90+
91+
describe('#31382: AppPlugin — two kernels in one process, each under its host-handed policy', () => {
92+
const adapters: CronJobAdapter[] = [];
93+
afterEach(async () => {
94+
for (const a of adapters.splice(0)) await a.destroy();
95+
});
96+
const boot = async (policy: ScheduledWorkPolicy | (() => ScheduledWorkPolicy) | undefined, adapter?: CronJobAdapter) => {
97+
const k = kernel(adapter);
98+
if (!adapter) adapters.push(k.adapter);
99+
const sweep = vi.fn(async () => { /* the job's work */ });
100+
const plugin = new AppPlugin(bundle(sweep), undefined, policy === undefined ? {} : { scheduledWorkPolicy: policy });
101+
await plugin.start!(k.ctx);
102+
await k.ready();
103+
return { ...k, sweep };
104+
};
105+
106+
it('the kernel handed `enabled: false` schedules NONE of its jobs; its sibling handed `enabled: true` runs the same job', async () => {
107+
const free = await boot(OFF);
108+
const team = await boot(ON);
109+
110+
expect(await free.adapter.listJobs(), 'the off kernel holds no job').toEqual([]);
111+
expect(await team.adapter.listJobs(), 'the on kernel holds it').toEqual([JOB]);
112+
113+
await team.adapter.trigger(JOB);
114+
expect(team.sweep).toHaveBeenCalledTimes(1);
115+
expect(free.sweep).not.toHaveBeenCalled();
116+
});
117+
118+
it('a resolver is read at kernel:ready, and the same process keeps a kernel with NO policy on the deployment switch', async () => {
119+
const free = await boot(() => OFF);
120+
const plain = await boot(undefined);
121+
122+
expect(await free.adapter.listJobs()).toEqual([]);
123+
expect(await plain.adapter.listJobs(), 'no policy ⇒ the deployment switch (ON here) decides').toEqual([JOB]);
124+
});
125+
126+
it('a kernel whose policy turned off CANCELS the job its app had scheduled before', async () => {
127+
const adapter = new CronJobAdapter();
128+
adapters.push(adapter);
129+
await boot(ON, adapter);
130+
expect(await adapter.listJobs()).toEqual([JOB]);
131+
132+
// The host rebuilds this environment's kernel on a plan that is off.
133+
const rebuilt = await boot(OFF, adapter);
134+
135+
expect(await adapter.listJobs(), 'the job the earlier boot scheduled is gone').toEqual([]);
136+
expect(rebuilt.sweep).not.toHaveBeenCalled();
137+
});
138+
139+
it("says so once at `info`, with the HOST's reason — not the deployment sentence", async () => {
140+
const free = await boot({ ...OFF, hostDisabledReason: HOST_REASON });
141+
142+
const said = free.infos().filter((m) => m.includes('declarative jobs NOT scheduled'));
143+
expect(said).toHaveLength(1);
144+
expect(said[0]).toContain(HOST_REASON);
145+
expect(said[0], 'the variable is set on this deployment — naming it as the remedy is wrong here')
146+
.not.toContain(SCHEDULED_WORK_ENV);
147+
});
148+
});
149+
150+
describe('#31382: scheduleAppArtifactJobs — `scheduledWorkPolicy` in place of the zero-argument reads', () => {
151+
/** `IJobService` as state, `schedule` replacing by name and `cancel` removing. */
152+
function jobs() {
153+
const scheduled = new Set<string>();
154+
const svc = {
155+
schedule: async (name: string) => { scheduled.add(name); },
156+
cancel: async (name: string) => { scheduled.delete(name); },
157+
trigger: async () => undefined,
158+
};
159+
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
160+
const ctx = {
161+
logger,
162+
getService: (name: string) => {
163+
if (name === 'job') return svc;
164+
throw new Error(`no ${name}`);
165+
},
166+
} as unknown as PluginContext;
167+
const run = (
168+
jobList: unknown[],
169+
scheduledWorkPolicy?: ScheduledWorkPolicy | (() => ScheduledWorkPolicy),
170+
) => scheduleAppArtifactJobs(
171+
ctx,
172+
{ id: APP_ID, jobs: jobList, functions: { sweep: async () => undefined } },
173+
{ appId: APP_ID, ql: undefined, source: 'Test', ...(scheduledWorkPolicy ? { scheduledWorkPolicy } : {}) },
174+
);
175+
return { scheduled, logger, run };
176+
}
177+
const job = (name: string, extra: Record<string, unknown> = {}) =>
178+
({ name, schedule: { type: 'interval', intervalMs: 60_000 }, handler: 'sweep', ...extra });
179+
180+
it('off ⇒ `withheld: scheduled-work-disabled`, nothing scheduled, the prior jobs cancelled', async () => {
181+
const h = jobs();
182+
await h.run([job('a_job'), job('b_job')], ON);
183+
expect([...h.scheduled].sort()).toEqual(['a_job', 'b_job']);
184+
185+
const out = await h.run([job('a_job'), job('b_job')], OFF);
186+
187+
expect(out.withheld).toBe('scheduled-work-disabled');
188+
expect(out.handlers).toEqual([]);
189+
expect(out.cancelled.sort()).toEqual(['a_job', 'b_job']);
190+
expect(h.scheduled.size).toBe(0);
191+
});
192+
193+
it("the policy's posture half replaces the deployment's: `requiresActingOrganization` refuses an org-less job", async () => {
194+
const h = jobs();
195+
const isolated: ScheduledWorkPolicy = {
196+
enabled: true, posture: 'isolated', requiresActingOrganization: true, runOwnership: 'declared',
197+
};
198+
199+
const out = await h.run([job('orgless_job'), job('declared_job', { organization: 'org_1' })], isolated);
200+
201+
expect(out.missingOrganization).toEqual(['orgless_job']);
202+
expect(out.handlers).toEqual(['declared_job']);
203+
});
204+
205+
it('a resolver that throws fails CLOSED: nothing scheduled, `scheduled-work-policy-unreadable`, said at error', async () => {
206+
const h = jobs();
207+
await h.run([job('a_job')], ON);
208+
209+
const out = await h.run([job('a_job')], () => { throw new Error('plan lookup failed'); });
210+
211+
expect(out.withheld).toBe('scheduled-work-policy-unreadable');
212+
expect(out.cancelled).toEqual(['a_job']);
213+
expect(h.scheduled.size).toBe(0);
214+
expect(h.logger.error).toHaveBeenCalledTimes(1);
215+
});
216+
217+
describe('absent ⇒ the deployment resolvers, exactly as before', () => {
218+
let prior: string | undefined;
219+
beforeEach(() => { prior = process.env[SCHEDULED_WORK_ENV]; delete process.env[SCHEDULED_WORK_ENV]; });
220+
afterEach(() => {
221+
if (prior === undefined) delete process.env[SCHEDULED_WORK_ENV];
222+
else process.env[SCHEDULED_WORK_ENV] = prior;
223+
});
224+
225+
it('switch OFF and no policy: withheld with the deployment sentence, verbatim', async () => {
226+
const h = jobs();
227+
const out = await h.run([job('a_job')]);
228+
229+
expect(out.withheld).toBe('scheduled-work-disabled');
230+
expect(h.scheduled.size).toBe(0);
231+
expect(String(h.logger.info.mock.calls[0][0])).toBe(
232+
`[Test] declarative jobs NOT scheduled — ${SCHEDULED_WORK_DISABLED_REASON}`,
233+
);
234+
});
235+
236+
it('switch OFF but the host hands `enabled: true`: the policy, not the switch, decides', async () => {
237+
const h = jobs();
238+
const out = await h.run([job('a_job')], ON);
239+
240+
expect(out.withheld).toBeUndefined();
241+
expect(out.handlers).toEqual(['a_job']);
242+
});
243+
});
244+
});

0 commit comments

Comments
 (0)