Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/34891-status-row-package.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 36 additions & 3 deletions packages/runtime/src/domains/automation-addressed-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<string>();
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: {} })),
Expand All @@ -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<void>((resolve) => { landWrite = resolve; });
let switching!: () => void;
const awaiting = new Promise<void>((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);
Expand Down
55 changes: 37 additions & 18 deletions packages/runtime/src/domains/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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 }) };
}
Expand Down Expand Up @@ -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<IAutomationService, 'getFlowRuntimeStates'>;
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 }) };
Expand Down
20 changes: 8 additions & 12 deletions packages/services/service-automation/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<typeof getFlowRuntimeStates> = {
flows: this.flows,
Expand All @@ -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);
}
Expand Down
32 changes: 20 additions & 12 deletions packages/services/service-automation/src/flow-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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'];
}
Expand Down Expand Up @@ -251,19 +252,21 @@ export function recordFlowRefusal(this: Pick<FlowDefinitionsHost, 'flows' | 'flo
});
}

/** The body of {@link AutomationEngine.getFlowRuntimeStates}, moved unedited; that method's docblock is its contract. */
export function getFlowRuntimeStates(this: Pick<FlowDefinitionsHost, 'flows' | 'resolveTriggerBinding' | 'flowShadowing' | 'describeUnboundReason' | 'isFlowEnabled' | 'boundFlowTriggers' | 'flowSlotName'>): 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<FlowDefinitionsHost, 'flows' | 'resolveTriggerBinding' | 'flowShadowing' | 'describeUnboundReason' | 'isFlowEnabled' | 'boundFlowTriggers' | 'flowSlotName' | 'flowSlotPackage'>): FlowRuntimeStateRow[] {
return [...this.flows.keys()].map((name) => {
const resolved = this.resolveTriggerBinding(name);
// [#11997] Attach the shadowing receipt to the row an admin already
Expand All @@ -275,6 +278,11 @@ export function getFlowRuntimeStates(this: Pick<FlowDefinitionsHost, 'flows' | '
// [#31696] One row per slot, under the flow's own name: two
// packages' flows of one name are two rows of that name.
name: this.flowSlotName(name),
// [ADR-0150 D4] The slot's package, so a reader that means one
// package's flow of a name two packages hold picks its row by
// `(packageId, name)`. Absent, not `undefined`-valued, on a slot
// no package holds, as `reason` is below.
...packageOf(this.flowSlotPackage(name)),
enabled: this.isFlowEnabled(name),
bound: this.boundFlowTriggers.has(name),
status: (this.flows.get(name) as { status?: string } | undefined)?.status,
Expand Down
Loading
Loading