diff --git a/.changeset/34891-status-row-package.md b/.changeset/34891-status-row-package.md new file mode 100644 index 00000000000..aa00dec82f5 --- /dev/null +++ b/.changeset/34891-status-row-package.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +'@objectstack/runtime': patch +--- + +fix(automation): status rows of a flow name two packages hold carry their package, so the toggle answers the switched flow's stored state + +Clause-②: yes (widening) +Metadata-protocol: none + +`FlowRuntimeState` (`@objectstack/spec/contracts`) gains an optional `packageId`: the package of the engine slot the row reads (ADR-0150 D4, one slot per package and name), absent for a flow no package holds. `getFlowRuntimeStates()`, and so `GET /automation/_status`, now stamps it on every row of a package-held flow, so the two rows of a name two packages hold are told apart by `(packageId, name)`. + +`POST /automation/NAME/toggle` (and its namespaced address) on such a name now answers the stored state of the slot it switched, read back from that slot's own row. It used to echo the request whenever the name had two rows, so a flow republished `obsolete` while the switch awaited its durable write was answered `enabled: true` though it does not run. The request is still echoed by a service that does not implement `getFlowRuntimeStates`, by one whose reading holds no row of the switched flow, or, on a door serving no package's slot, when two or more rows carry the name; the composed runtime never reaches that last case, because the bare `toggleFlow` refuses a name two packages hold. + +A reader that means one package's flow of a shared name picks its row by both `packageId` and `name`; a row picked by `name` alone may be the other holder's. diff --git a/packages/runtime/src/domains/automation-addressed-route.test.ts b/packages/runtime/src/domains/automation-addressed-route.test.ts index bb858a5edcd..b697d7798e2 100644 --- a/packages/runtime/src/domains/automation-addressed-route.test.ts +++ b/packages/runtime/src/domains/automation-addressed-route.test.ts @@ -729,10 +729,16 @@ describe('[#33905] a flow whose only holder\'s package is disabled: the bare doo * name there is the FIRST holder's, so each case switches the holder * registered SECOND, with the first one's row reading the opposite state. * + * Each row carries its slot's `packageId`, so the door reads back the row of + * the slot it switched: the answer is that slot's STORED state, and where the + * stored state is not the request (the slot republished `obsolete` while the + * switch awaits its durable write) the answer is the stored state, never the + * request echoed. + * * Driven through the real dispatcher over a real `SchemaRegistry`, and an * engine double that keeps each slot's state, switches it in `toggleFlowSlot` * and reads it back the engine's way (`getFlowRuntimeStates`: one row per - * slot, under the bare name). + * slot, under the bare name, carrying the slot's package). */ describe('[ADR-0126 §7.2] the toggle door answers the switched slot, on a name two packages hold', () => { const NAME = 'convert'; @@ -751,13 +757,16 @@ describe('[ADR-0126 §7.2] the toggle door answers the switched slot, on a name /** `slots`: each holder's slot of `NAME` and its state, in registration order. */ function dispatcherOver(registry: SchemaRegistry, slots: Array<[string, boolean]>) { const state = new Map(slots); + /** Slots whose definition's `status` keeps them off (`obsolete`), whatever the switch reads. */ + const statusOff = new Set(); + const enabledOf = (pkg: string) => state.get(pkg) === true && !statusOff.has(pkg); const keyed = (pkg: string | null) => (pkg !== null && state.has(pkg) ? (state.size > 1 ? `${pkg}/${NAME}` : NAME) : undefined); const shared = () => Object.assign(new Error(`Flow '${NAME}' is held by several packages`), { code: 'RESOURCE_CONFLICT', status: 409 }); const automation = { handlerReady: true, getFlow: vi.fn(async (name: string) => { if (name === NAME) throw shared(); return null; }), toggleFlow: vi.fn(async (name: string) => { if (name === NAME) throw shared(); }), - getFlowRuntimeStates: vi.fn(() => [...state].map(([, enabled]) => ({ name: NAME, enabled, bound: enabled }))), + getFlowRuntimeStates: vi.fn(() => [...state.keys()].map((pkg) => ({ name: NAME, packageId: pkg, enabled: enabledOf(pkg), bound: enabledOf(pkg) }))), flowSlotKey: vi.fn((pkg: string | null, name: string) => (name === NAME ? keyed(pkg) : undefined)), getFlowSlot: vi.fn((pkg: string | null, name: string) => (name === NAME && keyed(pkg) ? { name, label: `${pkg} flow` } : null)), executeSlot: vi.fn(async () => ({ success: true, output: {} })), @@ -771,9 +780,33 @@ describe('[ADR-0126 §7.2] the toggle door answers the switched slot, on a name const answered = await dispatcher.handleAutomation(path, 'POST', { enabled }, { request: {}, executionContext: ADMIN } as any, {}); return { status: answered.response?.status ?? 200, body: answered.response?.body as any }; }; - return { toggle, automation, stateOf: (pkg: string) => state.get(pkg) }; + return { toggle, automation, stateOf: enabledOf, republishObsolete: (pkg: string) => statusOff.add(pkg) }; } + it('red line: the switched slot republished `obsolete` while the switch awaits its durable write: 200 { enabled: false } (FROM: { enabled: true } over a flow that is off)', async () => { + const { toggle, automation, stateOf, republishObsolete } = dispatcherOver(registryOf([CRM, HR]), [[CRM, true], [HR, false]]); + const flip = automation.toggleFlowSlot.getMockImplementation()!; + let landWrite!: () => void; + const written = new Promise((resolve) => { landWrite = resolve; }); + let switching!: () => void; + const awaiting = new Promise((resolve) => { switching = resolve; }); + // The engine's order: the durable write is awaited first, the in-process bit moves after it. + automation.toggleFlowSlot.mockImplementation(async (pkg: string, name: string, enabled: boolean) => { + switching(); + await written; + await flip(pkg, name, enabled); + }); + const pending = toggle(`/hr/${NAME}/toggle`, true); + await awaiting; + // The republish lands while the switch awaits: the slot's status is now `obsolete`. + republishObsolete(HR); + landWrite(); + const on = await pending; + expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: false }]); + expect(on.body?.data?.enabled).toBe(stateOf(HR)); + expect(stateOf(CRM)).toBe(true); + }); + it('switched ON at the second holder\'s address, the first holder off: 200 { enabled: true }, that slot\'s state (FROM: the first holder\'s false)', async () => { const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, false], [HR, false]]); const on = await toggle(`/hr/${NAME}/toggle`, true); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 97e3fe7aa20..78fbc1a27ce 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -3890,10 +3890,16 @@ async function respondToRecordUpdateStarts( * disables it → 409 `RESOURCE_CONFLICT` naming the * status; nothing changes. 200 answers * `{ name, enabled }` with `enabled` read back from - * `getFlowRuntimeStates` while the name has one - * row there (echoed by a service that does not - * implement that read, and for a name two packages - * hold, which reads one row per holder) + * the switched flow's `getFlowRuntimeStates` row: + * where the door serves one package's slot (a + * name two packages hold, ADR-0150 D4), the row + * of `(packageId, name)`; elsewhere the name's + * one row. Echoed only by a service that does not + * implement that read, or by a reading that holds + * no row of the switched flow, or (on a door + * serving no slot) two or more rows of the name, + * which the composed runtime never reaches: the + * bare `toggleFlow` refuses a shared name * ⚑ authoring write — `manage_metadata` (commit 266436a7f): * enablement is environment-wide, so an * unentitled toggle reached every organization @@ -4178,6 +4184,9 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // is served from that holder's slot, as its address is (seat ruling // 6884403301). `item` is the address's item, else the bare door's own. let connectorPackage: string | undefined; + // [ADR-0150 D4] The package whose slot a by-name door serves, when it + // serves one (`flowSlotView`): the toggle reads back that slot's row. + let flowSlotPackage: string | undefined; { const door = bareByNameItem(parts, m); const item = address.qualifier ? address.item : door; @@ -4192,6 +4201,7 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str : undefined; if (slotted) { automationService = slotted; + flowSlotPackage = admission.packageId; } else if (address.qualifier || door?.type !== 'flow') { return { handled: true, response: automationAddressRefusalResponse(deps, { status: 409, refusal: admission.refusal }) }; } @@ -4547,22 +4557,31 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // not move, so "the write landed" and "the flow is on" are two // facts. Read through `getFlowRuntimeStates`, the one reading // `GET /_status` serves, so the two doors cannot disagree. - // That reading names the switched flow only while the name - // has ONE row. A name two packages hold reaches here too: by - // its address, or bare with one served holder left, through - // `flowSlotView`, whose `toggleFlow` switches one slot while - // the engine still reads one row per slot under the bare - // name ([ADR-0150 D4], `getFlowRuntimeStates`). A row picked - // by name there may be the other holder's, so two or more - // rows read back nothing. Then, as for a service that does - // not implement the read or holds no row of the name, the - // request is echoed, the legacy answer; for the engine's own - // service (the only one with slots) that echo is true by - // construction, since every toggle entry refuses switching - // on a flow its status keeps off. + // + // [ADR-0150 D4] The row read is the SWITCHED flow's. A name + // two packages hold reaches here too: by its address, or bare + // with one served holder left, through `flowSlotView`, whose + // `toggleFlow` switches one slot while the engine reads one + // row per slot under the bare name. Each row carries its + // slot's `packageId`, so a door serving a slot reads the row + // of `(flowSlotPackage, name)`, ⛔ never a row picked by name + // alone (it may be the other holder's). That is also what + // keeps the answer true when the slot is republished + // `obsolete` while the switch awaits its durable write: the + // row then reads off, and so does the answer. A bare door + // reads the name's one row. + // + // The request is echoed, the legacy answer, only where the + // reading cannot name the switched flow: a service that does + // not implement the read, a read that holds no row of it, or, + // on a door serving no slot, two or more rows of the name. The + // composed runtime never reaches that last case: the bare + // `toggleFlow` refuses a name two packages hold, and such a + // name reaches this door through a slot. const svc = automationService as Pick; const rows = typeof svc.getFlowRuntimeStates === 'function' - ? svc.getFlowRuntimeStates().filter((s) => s.name === name) + ? svc.getFlowRuntimeStates().filter((s) => s.name === name + && (flowSlotPackage === undefined || s.packageId === flowSlotPackage)) : []; const state = rows.length === 1 ? rows[0] : undefined; return { handled: true, response: deps.success({ name, enabled: state ? state.enabled : enabled }) }; diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 32d6bba6bdc..a178e793a41 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -215,6 +215,7 @@ import { withdrawFlow, hydrateFlowActivations, toggleFlow, + type FlowRuntimeStateRow, } from './flow-definitions.js'; // [#25222] The subflow guards' bodies: finding and describing disabled or // packaged subflows and their callers, and refusing what would reach a disabled @@ -5978,19 +5979,13 @@ export class AutomationEngine implements IAutomationService { * is `GET /automation/_status`, which passes these rows through verbatim and * has no access to {@link getTriggerBindingAudit}. Same sentence, same * eligibility, one computation — see {@link describeUnboundReason}. + * + * [ADR-0150 D4] One row per slot, under the flow's own name, carrying the + * slot's `packageId` (absent for a slot no package holds): a name two + * packages hold reads as two rows of that name, told apart by it, so the + * toggle door reads back the slot it switched. */ - getFlowRuntimeStates(): Array<{ - name: string; - enabled: boolean; - bound: boolean; - status?: string; - triggerType?: string; - object?: string; - reason?: string; - unboundCause?: FlowUnboundCause; - armedFrom?: FlowContender; - shadowed?: FlowContender[]; - }> { + getFlowRuntimeStates(): FlowRuntimeStateRow[] { // The body lives in ./flow-definitions.ts (#25222). const host: ThisParameterType = { flows: this.flows, @@ -6000,6 +5995,7 @@ export class AutomationEngine implements IAutomationService { isFlowEnabled: (...a) => this.isFlowEnabled(...a), boundFlowTriggers: this.boundFlowTriggers, flowSlotName: (...a) => this.flowSlotName(...a), + flowSlotPackage: (...a) => this.flowSlotPackage(...a), }; return getFlowRuntimeStates.call(host); } diff --git a/packages/services/service-automation/src/flow-definitions.ts b/packages/services/service-automation/src/flow-definitions.ts index 8515f70b491..bef8c73ad1a 100644 --- a/packages/services/service-automation/src/flow-definitions.ts +++ b/packages/services/service-automation/src/flow-definitions.ts @@ -17,7 +17,7 @@ */ import type { ConnectorProviderFactory } from '@objectstack/spec/integration'; -import type { AutomationContext, FlowUnboundCause } from '@objectstack/spec/contracts'; +import type { AutomationContext, FlowRuntimeState, FlowUnboundCause } from '@objectstack/spec/contracts'; import type { MetadataActivationWriteOptions } from '@objectstack/core'; import type { ConversionNotice, ConversionTodoNotice } from '@objectstack/spec'; import { applyConversionsToFlow } from '@objectstack/spec'; @@ -92,6 +92,7 @@ export interface FlowDefinitionsHost { readonly parkedRunsOf: AutomationEngine['parkedRunsOf']; readonly activateFlowTrigger: AutomationEngine['activateFlowTrigger']; readonly flowSlotName: AutomationEngine['flowSlotName']; + readonly flowSlotPackage: AutomationEngine['flowSlotPackage']; readonly flowSlotKeysOf: AutomationEngine['flowSlotKeysOf']; readonly isSharedFlowKey: AutomationEngine['isSharedFlowKey']; } @@ -251,19 +252,21 @@ export function recordFlowRefusal(this: Pick): Array<{ - name: string; - enabled: boolean; - bound: boolean; - status?: string; - triggerType?: string; - object?: string; - reason?: string; - unboundCause?: FlowUnboundCause; +/** + * One row of {@link AutomationEngine.getFlowRuntimeStates}: the contract's + * `FlowRuntimeState`, plus the shadowing receipt the engine attaches (#11997). + */ +export type FlowRuntimeStateRow = FlowRuntimeState & { armedFrom?: FlowContender; shadowed?: FlowContender[]; -}> { +}; + +function packageOf(packageId: string | undefined): { packageId?: string } { + return packageId === undefined ? {} : { packageId }; +} + +/** The body of {@link AutomationEngine.getFlowRuntimeStates}; that method's docblock is its contract. */ +export function getFlowRuntimeStates(this: Pick): FlowRuntimeStateRow[] { return [...this.flows.keys()].map((name) => { const resolved = this.resolveTriggerBinding(name); // [#11997] Attach the shadowing receipt to the row an admin already @@ -275,6 +278,11 @@ export function getFlowRuntimeStates(this: Pick { + it('a name two packages hold: two rows of the name, each carrying its own package and its own state', async () => { + ship(P1, leaf('f', 'p1')); + ship(P2, leaf('f', 'p2')); + await engine.toggleFlowSlot(P2, 'f', false); + const rows = engine.getFlowRuntimeStates().filter((row) => row.name === 'f'); + expect(rows.map((row) => [row.packageId, row.name, row.enabled])).toEqual([[P1, 'f', true], [P2, 'f', false]]); + }); + + it('a name one package holds carries its package; a flow no package holds carries no package key at all', () => { + ship(P1, leaf('solo', 'p1')); + engine.registerFlow('own', leaf('own', 'env')); + const rows = new Map(engine.getFlowRuntimeStates().map((row) => [row.name, row])); + expect(rows.get('solo')?.packageId).toBe(P1); + expect(Object.keys(rows.get('own') ?? {})).not.toContain('packageId'); + }); + + it('measured: a slot republished `obsolete` while its switch awaits the durable write — the switch resolves, and the slot\'s own row reads it off', async () => { + const store = new InMemoryFlowActivationStore(); + engine.setFlowActivationStore(store); + ship(P1, leaf('f', 'p1')); + ship(P2, leaf('f', 'p2')); + await engine.toggleFlowSlot(P2, 'f', false); + + // The durable write is held open, as a database write is. + const write = store.setActive.bind(store); + let landWrite!: () => void; + const held = new Promise((resolve) => { landWrite = resolve; }); + let awaiting!: () => void; + const reached = new Promise((resolve) => { awaiting = resolve; }); + store.setActive = (async (...args: Parameters) => { + awaiting(); + await held; + return write(...args); + }) as typeof store.setActive; + + const switching = engine.toggleFlowSlot(P2, 'f', true); + await reached; + // The republish lands while the switch awaits: P2's flow is now `obsolete`. + engine.registerFlow('f', { ...leaf('f', 'p2'), status: 'obsolete' }, { source: 'package', packageId: P2, holder: P2 }); + landWrite(); + await expect(switching).resolves.toBeUndefined(); + + const rows = engine.getFlowRuntimeStates().filter((row) => row.name === 'f'); + // Two rows of the name: an answer picked by name alone cannot be read back. + expect(rows).toHaveLength(2); + // The switched slot's own row reads it off, though the switch was asked to turn it on. + expect(rows.find((row) => row.packageId === P2)).toMatchObject({ enabled: false, status: 'obsolete' }); + expect(rows.find((row) => row.packageId === P1)).toMatchObject({ enabled: true }); + expect(await engine.executeSlot(P2, 'f')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + }); +}); diff --git a/packages/spec/src/contracts/automation-service.test.ts b/packages/spec/src/contracts/automation-service.test.ts index 65c769647fd..72bbef566c7 100644 --- a/packages/spec/src/contracts/automation-service.test.ts +++ b/packages/spec/src/contracts/automation-service.test.ts @@ -61,6 +61,13 @@ export type FlowRuntimeStateReasonIsOptional = Assert< export type FlowRuntimeStateUnboundCauseIsTheClosedTuple = Assert< Eq >; +/** + * [ADR-0150 D4] The row's slot package: optional (a flow no package holds + * carries none, and the minimal row above still satisfies the contract) and + * spelled as the slot spells it. The identity fails if the key is dropped, + * renamed or narrowed — the toggle door picks a co-held name's row by it. + */ +export type FlowRuntimeStateCarriesAnOptionalPackageId = Assert>; export type FlowUnboundCauseIsTheTupleUnion = Assert< Eq >; diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index f8c365be903..da0290acf87 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1000,6 +1000,18 @@ export interface RecordUpdateStartsInput { export interface FlowRuntimeState { /** Flow name (snake_case) — the key {@link IAutomationService.execute} takes. */ name: string; + /** + * [ADR-0150 D4] The package whose flow this row reads: the package of the + * engine slot `(packageId, name)` the row is one of, absent for a flow no + * package holds. The engine holds one slot per package and name, and a + * name two packages hold reads as two rows of that `name`, so this is the + * member that tells them apart: `(packageId, name)` names exactly one row. + * A reader that means one package's flow of such a name picks its row by + * both, ⛔ never by `name` alone (that row may be the other holder's). + * The spelling is the slot's own (`FlowSlot.packageId`, the activation + * ledger row's `packageId`). + */ + packageId?: string; /** Whether the flow is enabled; a disabled flow stays registered and never runs. */ enabled: boolean; /**