Skip to content

Commit 888c3e1

Browse files
fix(service-automation)!: the inbound hook door refuses the address of a flow slot whose package is disabled, before anything is enqueued (ADR-0150 D5) (#34278)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbCpddLFmKzR39wJWZpkRMCi)_ Fixes #33906 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: follow-up owed — skills/objectstack-automation/SKILL.md:383-395 > **BREAKING** for a sender that posts to the inbound hook of a flow whose package is disabled while the automation engine still holds that flow's slot (the disable's re-sync failed or did not run, or the disable came with no announce). The door answered `202 Accepted`, queued the post, and the queued run was then skipped: the event was lost while the sender was told it was accepted. It now answers the door's one refusal, `401 INVALID_SIGNATURE`, the bytes the same address gets once the re-sync has withdrawn the slot. Senders that retry on a non-2xx keep the event and can redeliver after a re-enable. Remedy: enable the package; the address answers `202` again with no re-arm. Nothing durable moves, so nothing is migrated (ADR-0087: `not-required (no-migration-prescription)`). ## 维护者速读 - 改了什么:入站 hook 的地址指向"包已停用、但引擎仍挂着其流程槽位"的流程时,入口不再回 202 受理,而是回入口唯一的 401 拒绝(读完整个请求体之后),不入队;两种托管形态(自托管挂载与托管分发)都一样。原因只写服务器日志(`cause: 'disabled-holder'`),不告诉发送方。 - 为什么改:之前入口回 202,随后排队的运行被跳过,发送方以为已处理,事件静默丢失。按座席裁决 6898449441(方案 A,沿用裁决 6884403301 第 2、3、8 条):停用包的槽位不接受任何地址,与重同步撤回槽位后的回答逐字节相同。 - 风险与回滚:破坏性收窄(标题带 `!`),只影响"包已停用但重同步没撤掉槽位"的流程的 hook 地址;会在非 2xx 时重试的发送方可在重新启用后补投,不重试的发送方这段时间的事件会被拒收(之前是被假受理后丢弃)。共享名的裸 hook、在服务的同名包、无包流程、用槽位开关关掉的流程,回答都不变。回滚即还原本 PR。 - 先看:`packages/services/service-automation/src/engine.ts` 的 `inboundHookSlot`(两处新判断:单一持有者分支、地址选定槽位之后)与新增的 `disabledHolderHookRefused`;测试 `packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/dogfood exec vitest run --project isolated --maxWorkers=2 test/inbound-hook-disabled-holder-33906.test.ts`(需先构建依赖),预期 6 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes `AutomationEngine.inboundHookSlot` (both faces of the inbound hook door ask it before the signature is read) now asks `isDisabledHolderSlot`, the predicate the trigger's fire-time skip already asks (PR #33890, extended to a name one package holds by PR #34048): - **A name two packages hold**: once the qualified address has picked its slot (the namespace's package), a slot whose package is disabled answers `unadmitted`. The slot is judged after the pick, so no other holder is served in its place (amendment 8: admission is judged on the slot that would execute). - **A name one package holds** (the door previously answered `undefined` and judged it as before): a disabled sole holder answers `unadmitted` for every address, the bare one included. `unadmitted` is the door's existing answer: the self-hosted mount (`ApiTriggerPlugin`) and the hosted face (`handleInboundHookRequest` in the runtime, and the `trigger-api` member for the bare hook) read the body in full and answer `inboundHookRefusal()`, `401 INVALID_SIGNATURE`. No door file changes. The engine logs the real cause at `info`, once per refused post, with `{ cause: 'disabled-holder', flow, package, slot }`; the door's own line still logs `unadmitted-address` (qualified) or `unknown-flow` (bare). Nothing is enqueued. The question is asked at post time, so the enable serves the address again with no re-arm. Not moved: the bare hook of a name two packages hold stays the `shared-name` refusal (PR #33646 "Not moved"); the served co-holder beside a disabled one, a flow no package ships, and a flow switched off with `toggleFlowSlot` (its address still routes to its slot: `flow-triggers-per-slot.test.ts:198-210`, untouched) answer as before. ## Tests New file `packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts` (6 tests). The rig: the real `AutomationEngine` built by the real `AutomationServicePlugin.init()` (so its flow-name resolver is the plugin's own) over a real `SchemaRegistry`; the real `ApiTriggerPlugin` mounting the self-hosted routes and registering the `trigger-api` member; the real runtime `HttpDispatcher` as the hosted face over a kernel with no `http.server`; a queue that hands each message to the trigger's consumer at once, so a run is observed. Each post is signed with the hook's correct secret, so the disable is the only reason for a refusal. - red line: the disabled co-holder's qualified address answers the one refusal on both faces, byte-identical (status, headers, body) to `inboundHookRefusalResponse()` and to the same address after `withdrawFlowSlot` (the re-sync); nothing enqueued, nothing run; the cause is in the log only (the body names no package, namespace or `disabled`). - red line: both holders disabled: neither qualified address is served. - red line: a disabled sole holder: its qualified and bare addresses answer the same refusal on both faces, byte-identical to after the re-sync; nothing enqueued. - the enable: each address answers `202` and runs again; the active trigger bindings and the queue subscriptions are unchanged (no re-arm). - CONTROL: nothing disabled: every address answers `202` on both faces and runs. - CONTROL: the served co-holder beside the disabled one answers `202` on both faces and runs its own flow. The file is new rather than a describe in `flow-hook-per-slot.dogfood.test.ts` because the order names it; that file's rig mounts only the self-hosted face. ## Acceptance notes - Skills follow-up owed: `skills/objectstack-automation/SKILL.md:383-395` (the area files that card). - The door's own log line for this refusal names a generic cause (`unadmitted-address` qualified, `unknown-flow` bare); the engine's `disabled-holder` line beside it is the true cause. Giving the door a cause of its own would add a member to `UnverifiedPostCause` in `trigger-api` and the runtime's door text, outside this claim. - The full PATCH-disable stack through a booted app was not measured (as in the measurement 6897225218); the armed-but-disabled state is reached in the rig with `registry.disablePackage` and no re-sync. ## Verification All readings are on head `84e37cab` (the branch with `origin/main` merged in, #34048 included) unless a line says otherwise. - **Pins:** `pnpm --filter @objectstack/dogfood exec vitest run --project isolated --maxWorkers=2 test/inbound-hook-disabled-holder-33906.test.ts`: Test Files 1 passed, Tests 6 passed. - **Dogfood battery** (title has `!`): the dependency closure built (`--filter '@objectstack/dogfood^...' build`, exit 0), then `pnpm --filter @objectstack/dogfood test` under the verify lock: exit 0, Test Files 470 passed, 3 skipped (473); Tests 3980 passed, 42 skipped (4022); 2007 s. - **`@objectstack/service-automation`:** `pnpm test`: Test Files 284 passed, Tests 4040 passed (`flow-triggers-per-slot.test.ts`, the toggled-off slot pin at L198-210, untouched and green). `pnpm typecheck`: exit 0, test layer compiles. - **Derived gates** (`dispatch-gates --commands`, 76 families): 75 exit 0. `check:dual-build-cjs-loads` exit 3, PREREQUISITE NOT MET (it reads every package's `dist/` and this tree built only the dogfood closure): NOT MEASURED here; CI runs it. `--ran` reconciliation: 76 derived, 76 run, 0 unrun. `check:engine-double-contract` was red on an earlier head (the rig's credential store pinned write verbs the ledger does not record); the store is now read-only, so no ledger row is owed, and the gate is green. - **Declaration self-check:** `check-changeset-no-major`, `check-adr-0087-registration` (`[BREAKING+bang+clause-②-narrowing] not-required (no-migration-prescription)`), `check-closing-keyword-parity`, `check-partof-closing-keyword` on this body: all exit 0. `dispatch-gates --tier`: no path-derived model mandate. - **eslint** on the two touched source files: exit 0. Repo-wide `pnpm lint` is left to CI. <details><summary>Ablation: each leave-out put back, the pins go red (rebuilt, marker proved in dist/, restored)</summary> Each leg went through `scripts/ablation-replace.mjs` (anchor hit 1 to 0, blob checked), then `pnpm --filter @objectstack/service-automation build`, then `ablation-dist-preflight.mjs` (marker present in `dist/index.js` and `dist/index.cjs`), then the pin file. Taken on `aa16cc6e`, before the merges, with the same engine hunk. 1. The shared-name leave-out made inert (`if (globalThis.__ABLATED_33906_SHARED__ === true && ...)`): 3 failed, 3 passed. The red lines for the disabled co-holder, for both holders disabled, and for the enable go red, for example `AssertionError: self-hosted: expected { status: 202, …(2) } to deeply equal { status: 401, …(2) }`. 2. The sole-holder leave-out made inert: 2 failed, 4 passed. The sole-holder red line and the enable go red: `AssertionError: self-hosted {"ns":"alpha","flowName":"zz_disabled_alone"}: expected { status: 202, …(2) } to deeply equal { status: 401, …(2) }`. Restore: each blob equal to HEAD, `git diff HEAD` empty. A rebuild, then `ablation-dist-preflight --absent` for both markers: absent from all 6 built files, tree clean. The pin file: 6 passed. </details> Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent bb17350 commit 888c3e1

3 files changed

Lines changed: 410 additions & 2 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
fix(service-automation)!: the inbound hook door refuses the address of a flow slot whose package is disabled, before anything is enqueued (ADR-0150 D5)
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. The moved answer is the anonymous inbound hook's answer to a post under a reversible package state: no stored row, slot key, run key, trigger binding, hook secret or dispatch key changes, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** for a sender that posts to the inbound hook of a flow whose package is disabled while the automation engine still holds that flow's slot (the re-sync that follows a disable failed or did not run, or the disable came with no announce). The door answered `202 Accepted` and queued the post, and the queued run was then skipped, so the event was lost while the sender was told it was accepted. It now answers the door's one refusal, `401 INVALID_SIGNATURE`.
13+
14+
What moves, while the package is disabled:
15+
16+
- `POST /api/v1/automation/hooks/NAMESPACE/NAME/HOOK` for a name two packages each ship, where NAMESPACE names the disabled package: the self-hosted mount and the hosted face both answer the one refusal, once the body has been read in full. Nothing is enqueued, and the other package's flow of the name is not reached in its place.
17+
- For a name only the disabled package ships, both its qualified address and the bare `POST /api/v1/automation/hooks/NAME/HOOK` answer the same refusal.
18+
19+
The answer is byte for byte the one the same address gets once the disable's re-sync has withdrawn the slot, and the one every unverified post gets, so it says nothing about which packages are installed or disabled. The cause is written to the server log only, at `info`, once per refused post (`cause: 'disabled-holder'`, with the flow, the package and the slot).
20+
21+
Senders that retry on a non-2xx keep the event and can redeliver after a re-enable. When the package is enabled again the address answers `202` and runs the flow again, with no re-arm.
22+
23+
The served package's qualified hook beside a disabled one, a flow no package ships, and a flow switched off with its slot toggle answer as before. The bare hook of a name two packages ship answers the one refusal as before.
Lines changed: 345 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,345 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0150 D5, #33906; seat ruling 6884403301, amendments 2, 3 and 8] END
5+
* TO END: the inbound hook of a flow slot whose package is disabled while the
6+
* slot is still armed (the disable's re-sync has not withdrawn it: its
7+
* announce or protocol read failed, or the disable came with no announce).
8+
*
9+
* The real `AutomationEngine`, built by the real `AutomationServicePlugin`
10+
* `init()` (so its flow-name resolver is the plugin's own, over the real
11+
* `SchemaRegistry`), the real `ApiTriggerPlugin` mounting the self-hosted
12+
* door and registering the `trigger-api` member, the real `ApiTrigger`
13+
* verifying and enqueueing, and the real runtime `HttpDispatcher` forwarding
14+
* the hosted face to that member. A queue delivers each message to the
15+
* trigger's consumer at once, so a run is observed.
16+
*
17+
* - The qualified address of a disabled co-holder's slot answers the door's
18+
* one refusal on both faces, once the body is read: the bytes the address
19+
* gets after the disable's re-sync. Nothing is enqueued and nothing runs;
20+
* the cause is in the server log only.
21+
* - A disabled sole holder's flow: the same, on its qualified and its bare
22+
* address.
23+
* - The enable serves the address again (202), with no re-arm.
24+
* - CONTROL: the served co-holder answers 202 and runs; with nothing
25+
* disabled every address answers as before.
26+
*
27+
* Every value is a probe sentinel, not a credential.
28+
*/
29+
30+
import { createHmac } from 'node:crypto';
31+
import { beforeEach, describe, expect, it } from 'vitest';
32+
import { inboundHookJsonResponse, inboundHookRefusalResponse } from '@objectstack/core';
33+
import { SchemaRegistry } from '@objectstack/objectql';
34+
import { HttpDispatcher } from '@objectstack/runtime';
35+
import { AutomationEngine, AutomationServicePlugin, FlowCredentialChannel } from '@objectstack/service-automation';
36+
import { ApiTriggerPlugin, HOOKS_ADDRESSED_PATH, HOOKS_PATH } from '@objectstack/trigger-api';
37+
38+
const P1 = 'com.acme.alpha';
39+
const P2 = 'com.acme.beta';
40+
const SHARED = 'zz_disabled_hook';
41+
const ALONE = 'zz_disabled_alone';
42+
const S1 = 'pin-disabled-hook-alpha-71c4';
43+
const S2 = 'pin-disabled-hook-beta-e09a';
44+
const S_ALONE = 'pin-disabled-hook-alone-3f58';
45+
46+
type Line = { level: string; message: string; fields?: any };
47+
const lines: Line[] = [];
48+
const logger: any = {};
49+
for (const level of ['debug', 'info', 'warn', 'error']) {
50+
logger[level] = (message: string, fields?: unknown) => { lines.push({ level, message, fields }); };
51+
}
52+
logger.child = () => logger;
53+
54+
const sign = (secret: string, body: string) => {
55+
const t = Math.floor(Date.now() / 1000);
56+
return `t=${t},v1=` + createHmac('sha256', secret).update(`${t}.${body}`, 'utf8').digest('hex');
57+
};
58+
59+
/** start (api hook `h1`, its secret in the channel) → mark(tag) → end. */
60+
function hooked(name: string, tag: string) {
61+
return {
62+
name,
63+
label: name,
64+
type: 'api',
65+
nodes: [
66+
{ id: 'start', type: 'start', label: 'Start', config: { hookId: 'h1' } },
67+
{ id: 'mark', type: 'mark', label: 'Mark', config: { tag } },
68+
{ id: 'end', type: 'end', label: 'End' },
69+
],
70+
edges: [
71+
{ id: 'e1', source: 'start', target: 'mark' },
72+
{ id: 'e2', source: 'mark', target: 'end' },
73+
],
74+
};
75+
}
76+
77+
/** One active hook-secret row per (flow, package), as the channel stores them: read-only, the hook door writes nothing. */
78+
function credentialStore(rows: Array<{ flow: string; packageId: string; value: string }>) {
79+
const stored = rows.map((r, i) => ({
80+
id: `cred_${i}`, flow_name: r.flow, flow_package: r.packageId, node_id: 'start', credential_key: 'secret', state: 'active', value: r.value,
81+
}));
82+
return {
83+
async find(_object: string, query?: { where?: Record<string, unknown>; limit?: number }) {
84+
const where = query?.where ?? {};
85+
const rows = stored.filter((row) => Object.entries(where).every(([k, v]) => (row as Record<string, unknown>)[k] === v));
86+
const page = typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows;
87+
return page.map(({ value: _value, ...row }) => row);
88+
},
89+
async resolveSecretField(_object: string, id: string) {
90+
return stored.find((row) => row.id === id)?.value ?? null;
91+
},
92+
};
93+
}
94+
95+
/** An answer as its bytes: status, headers and body. */
96+
type Snapshot = { status: number; headers: Array<[string, string]>; body: string };
97+
async function snapshot(res: Response): Promise<Snapshot> {
98+
return { status: res.status, headers: [...res.headers.entries()], body: await res.text() };
99+
}
100+
101+
let registry: SchemaRegistry;
102+
let engine: AutomationEngine;
103+
let routes: Map<string, (c: any, next: () => Promise<void>) => Promise<unknown>>;
104+
let dispatcher: HttpDispatcher;
105+
let enqueued: string[];
106+
let ran: string[];
107+
let subscribed: string[];
108+
109+
/** The hook's address: `ns` absent is the bare hook. */
110+
type Address = { ns?: string; flowName: string };
111+
112+
/** POST through the self-hosted mount, as Hono hands a handler its decoded parameters and renders `c.json`. */
113+
async function postSelfHosted(address: Address, secret: string): Promise<Snapshot> {
114+
const body = JSON.stringify({ probe: address });
115+
const headers: Record<string, string> = { 'x-objectstack-signature': sign(secret, body) };
116+
const params: Record<string, string> = { flowName: address.flowName, hookId: 'h1', ...(address.ns ? { ns: address.ns } : {}) };
117+
const c = {
118+
req: { param: (n: string) => params[n], text: async () => body, header: (n: string) => headers[n.toLowerCase()] },
119+
json: (b: unknown, status: number) => inboundHookJsonResponse(b, status),
120+
};
121+
const route = routes.get(address.ns ? HOOKS_ADDRESSED_PATH : HOOKS_PATH)!;
122+
return snapshot((await route(c, async () => {})) as Response);
123+
}
124+
125+
/** POST through the runtime dispatcher (the hosted face: a kernel with no http.server). */
126+
async function postHosted(address: Address, secret: string): Promise<Snapshot> {
127+
const body = JSON.stringify({ probe: address });
128+
const path = address.ns
129+
? `/automation/hooks/${address.ns}/${address.flowName}/h1`
130+
: `/automation/hooks/${address.flowName}/h1`;
131+
const request = new Request(`http://tenant.example/api/v1${path}`, {
132+
method: 'POST',
133+
headers: { 'Content-Type': 'application/json', 'x-objectstack-signature': sign(secret, body) },
134+
body,
135+
});
136+
const result = await dispatcher.dispatch('POST', path, {}, {}, { request } as never);
137+
expect(result.response, path).toBeUndefined();
138+
return snapshot(result.result as Response);
139+
}
140+
141+
const FACES = [['self-hosted', postSelfHosted], ['hosted', postHosted]] as const;
142+
143+
/** The engine's own line for a post it refused because its slot's package is disabled. */
144+
const disabledCauses = () => lines.filter((l) => l.fields?.cause === 'disabled-holder');
145+
146+
beforeEach(async () => {
147+
routes = new Map();
148+
lines.length = 0;
149+
enqueued = [];
150+
ran = [];
151+
subscribed = [];
152+
registry = new SchemaRegistry();
153+
registry.logLevel = 'silent';
154+
for (const [id, namespace] of [[P1, 'alpha'], [P2, 'beta']]) {
155+
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace } as never, 'code');
156+
}
157+
const loaderSets: Record<string, string[]> = {};
158+
159+
// The queue delivers each message to the trigger's consumer at once.
160+
const consumers = new Map<string, (message: { data: unknown }) => Promise<void> | void>();
161+
const queue = {
162+
async publish(name: string, data: unknown) {
163+
enqueued.push(name);
164+
await consumers.get(name)?.({ data });
165+
return `msg_${enqueued.length}`;
166+
},
167+
async subscribe(name: string, handler: (message: { data: unknown }) => Promise<void> | void) {
168+
subscribed.push(name);
169+
consumers.set(name, handler);
170+
},
171+
async unsubscribe(name: string) { consumers.delete(name); },
172+
};
173+
const app = { post: (path: string, handler: any) => { routes.set(path, handler); } };
174+
const services: Record<string, unknown> = {
175+
queue,
176+
'http.server': { getRawApp: () => app },
177+
objectql: { registry },
178+
};
179+
const ctx = {
180+
logger,
181+
hook: (event: string, fn: () => Promise<void>) => { if (event === 'kernel:ready') ready.push(fn); },
182+
getService: (name: string) => {
183+
if (name in services) return services[name];
184+
throw new Error(`no ${name}`);
185+
},
186+
registerService: (name: string, service: unknown) => { services[name] = service; },
187+
};
188+
const ready: Array<() => Promise<void>> = [];
189+
190+
// The engine the automation plugin builds, its flow-name resolver the plugin's own.
191+
await new AutomationServicePlugin({ suspendedRunStore: 'memory' }).init(ctx as never);
192+
engine = services.automation as AutomationEngine;
193+
engine.registerNodeExecutor({
194+
type: 'mark',
195+
async execute(node: { config?: { tag?: string } }) {
196+
ran.push(String(node.config?.tag));
197+
return { success: true };
198+
},
199+
} as never);
200+
engine.setPackagedFlowSource((name, packageId) => {
201+
const holders = loaderSets[name] ?? [];
202+
if (packageId !== undefined) return holders.includes(packageId) ? packageId : undefined;
203+
return holders.length === 1 ? holders[0] : undefined;
204+
});
205+
const channel = new FlowCredentialChannel(() => credentialStore([
206+
{ flow: SHARED, packageId: P1, value: S1 },
207+
{ flow: SHARED, packageId: P2, value: S2 },
208+
{ flow: ALONE, packageId: P1, value: S_ALONE },
209+
]) as never);
210+
await channel.loadIndex();
211+
engine.setFlowCredentialSource(channel);
212+
213+
await new ApiTriggerPlugin().start(ctx as never);
214+
for (const fn of ready) await fn();
215+
expect(services['trigger-api']).toBeDefined();
216+
217+
// The hosted face: the runtime dispatcher over a kernel with no http.server.
218+
const { 'http.server': _socket, ...hosted } = services;
219+
const kernel: any = {
220+
getState: () => 'running',
221+
getService: (n: string) => hosted[n] ?? null,
222+
getServiceAsync: async (n: string) => hosted[n] ?? null,
223+
context: { getService: (n: string) => hosted[n] ?? null },
224+
};
225+
dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false });
226+
(dispatcher as any).domainDeps.logger = logger;
227+
228+
const ship = (packageId: string, body: { name: string }) => {
229+
registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId);
230+
loaderSets[body.name] = [...new Set([...(loaderSets[body.name] ?? []), packageId])];
231+
engine.registerFlow(body.name, body, { source: 'package', packageId, holder: packageId });
232+
};
233+
ship(P1, hooked(SHARED, 'p1'));
234+
ship(P2, hooked(SHARED, 'p2'));
235+
ship(P1, hooked(ALONE, 'alone'));
236+
// The consumer runs the flow after the publish resolves its subscription.
237+
await new Promise((r) => setTimeout(r, 0));
238+
});
239+
240+
describe('#33906 the inbound hook of a disabled holder\'s armed slot, both faces', () => {
241+
it('CONTROL: with nothing disabled, each qualified hook and the sole holder\'s bare hook answer 202 and run', async () => {
242+
for (const [face, post] of FACES) {
243+
ran = [];
244+
expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(202);
245+
expect((await post({ ns: 'beta', flowName: SHARED }, S2)).status, face).toBe(202);
246+
expect((await post({ ns: 'alpha', flowName: ALONE }, S_ALONE)).status, face).toBe(202);
247+
expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(202);
248+
expect(ran, face).toEqual(['p1', 'p2', 'alone', 'alone']);
249+
}
250+
expect(disabledCauses()).toEqual([]);
251+
});
252+
253+
it('red line: the disabled co-holder\'s qualified address answers the one refusal, the bytes it gets after the re-sync; nothing is enqueued; the cause is logged only', async () => {
254+
registry.disablePackage(P1);
255+
const reference = await snapshot(inboundHookRefusalResponse());
256+
const armed: Record<string, Snapshot> = {};
257+
for (const [face, post] of FACES) {
258+
armed[face] = await post({ ns: 'alpha', flowName: SHARED }, S1);
259+
expect(armed[face], face).toEqual(reference);
260+
for (const leak of [P1, 'alpha', 'disabled']) expect(armed[face].body, face).not.toContain(leak);
261+
}
262+
expect(enqueued).toEqual([]);
263+
expect(ran).toEqual([]);
264+
const causes = disabledCauses();
265+
expect(causes).toHaveLength(2);
266+
expect(causes[0].fields).toEqual({ cause: 'disabled-holder', flow: SHARED, package: P1, slot: `${P1}/${SHARED}` });
267+
268+
// The disable's re-sync withdraws the slot: the same address, the same bytes.
269+
engine.withdrawFlowSlot(P1, SHARED);
270+
for (const [face, post] of FACES) expect(await post({ ns: 'alpha', flowName: SHARED }, S1), face).toEqual(armed[face]);
271+
expect(enqueued).toEqual([]);
272+
expect(ran).toEqual([]);
273+
});
274+
275+
it('CONTROL: the served co-holder beside the disabled one answers 202 on both faces and runs its own flow', async () => {
276+
registry.disablePackage(P1);
277+
for (const [face, post] of FACES) expect((await post({ ns: 'beta', flowName: SHARED }, S2)).status, face).toBe(202);
278+
expect(enqueued).toEqual([`flow-api:${P2}/${SHARED}`, `flow-api:${P2}/${SHARED}`]);
279+
expect(ran).toEqual(['p2', 'p2']);
280+
expect(disabledCauses()).toEqual([]);
281+
});
282+
283+
it('red line: both holders disabled, neither qualified address is served', async () => {
284+
registry.disablePackage(P1);
285+
registry.disablePackage(P2);
286+
const reference = await snapshot(inboundHookRefusalResponse());
287+
for (const [face, post] of FACES) {
288+
expect(await post({ ns: 'alpha', flowName: SHARED }, S1), face).toEqual(reference);
289+
expect(await post({ ns: 'beta', flowName: SHARED }, S2), face).toEqual(reference);
290+
}
291+
expect(enqueued).toEqual([]);
292+
expect(ran).toEqual([]);
293+
expect(disabledCauses().map((l) => l.fields.package)).toEqual([P1, P2, P1, P2]);
294+
});
295+
296+
it('red line: a disabled sole holder\'s flow answers the one refusal on its qualified and its bare address, the bytes they get after the re-sync; nothing is enqueued', async () => {
297+
registry.disablePackage(P1);
298+
const reference = await snapshot(inboundHookRefusalResponse());
299+
const addresses: Address[] = [{ ns: 'alpha', flowName: ALONE }, { flowName: ALONE }];
300+
const armed = new Map<string, Snapshot>();
301+
for (const [face, post] of FACES) {
302+
for (const address of addresses) {
303+
const answer = await post(address, S_ALONE);
304+
expect(answer, `${face} ${JSON.stringify(address)}`).toEqual(reference);
305+
for (const leak of [P1, 'alpha', 'disabled']) expect(answer.body).not.toContain(leak);
306+
armed.set(`${face} ${JSON.stringify(address)}`, answer);
307+
}
308+
}
309+
expect(enqueued).toEqual([]);
310+
expect(ran).toEqual([]);
311+
expect(disabledCauses()).toHaveLength(4);
312+
expect(disabledCauses()[0].fields).toEqual({ cause: 'disabled-holder', flow: ALONE, package: P1, slot: ALONE });
313+
314+
engine.withdrawFlowSlot(P1, ALONE);
315+
for (const [face, post] of FACES) {
316+
for (const address of addresses) {
317+
const key = `${face} ${JSON.stringify(address)}`;
318+
expect(await post(address, S_ALONE), key).toEqual(armed.get(key));
319+
}
320+
}
321+
expect(enqueued).toEqual([]);
322+
expect(ran).toEqual([]);
323+
});
324+
325+
it('the enable serves each address again, 202 and a run, with no re-arm', async () => {
326+
const bindings = engine.getActiveTriggerBindings().map((b) => b.flowName).sort();
327+
const subscriptions = [...subscribed];
328+
registry.disablePackage(P1);
329+
for (const [face, post] of FACES) {
330+
expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(401);
331+
expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(401);
332+
}
333+
expect(ran).toEqual([]);
334+
335+
registry.enablePackage(P1);
336+
for (const [face, post] of FACES) {
337+
expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(202);
338+
expect((await post({ ns: 'alpha', flowName: ALONE }, S_ALONE)).status, face).toBe(202);
339+
expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(202);
340+
}
341+
expect(ran).toEqual(['p1', 'alone', 'alone', 'p1', 'alone', 'alone']);
342+
expect(engine.getActiveTriggerBindings().map((b) => b.flowName).sort()).toEqual(bindings);
343+
expect(subscribed).toEqual(subscriptions);
344+
});
345+
});

0 commit comments

Comments
 (0)