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
26 changes: 26 additions & 0 deletions .changeset/34655-toggle-status-disarmed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@objectstack/service-automation': patch
'@objectstack/runtime': patch
---

fix(automation)!: switching on a packaged flow that its own status disarms is refused, and the toggle door answers the engine's state

Clause-②: no (narrowing)
Metadata-protocol: none
Skills-docs: none — skills/objectstack-automation/SKILL.md teaches the toggle only as the off switch for an installed package's flow; nothing it says changes

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value, metadata type or stored row shape is added, removed, renamed or rewritten: what moves is the answer of one REST door (POST /automation/:name/toggle, and the IAutomationService.toggleFlow it calls) to one request, switching on a packaged flow whose own status already keeps it off. A flow definition that was valid stays valid and is armed exactly as before; nothing exists for objectstack migrate meta to rewrite. The one-line fix for a caller is in the body: publish the flow with status active, then switch it on. -->

**BREAKING** for a caller that switches on a packaged flow whose definition's `status` is `obsolete` or `invalid`. The switch moves only the activation-ledger bit, and a status is the author's, so that request never made the flow run. It now says so instead of reporting success.

**What changes.**

- `POST /api/v1/automation/:name/toggle` with `{ enabled: true }` (and `IAutomationService.toggleFlow(name, true)` on the engine's service) on such a flow used to answer `200 { name, enabled: true }`. It wrote `active: true` to `sys_metadata_activation`, replacing any `active: false` row an administrator had left there, while `GET /automation/_status` read `enabled: false`. It now answers `409 RESOURCE_CONFLICT`, names the status, and writes nothing.
- An `active: false` row already standing for the flow stays as it is.
- The refusal names the step that arms the flow: publish it with status `active`, or for a read-only package, install a package version that ships it active.
- A second case changes. An administrator switches such a flow on while it is still `obsolete`, and the flow is later published or shipped `active`. If the ledger held an `active: false` row for it, the flow used to run as soon as it arrived `active`, because the earlier switch-on had replaced that row. Now the row is still there, so the flow stays off after it arrives `active` until it is switched on again.
- The door's `200` answer reads `enabled` back from `getFlowRuntimeStates`, the same reading `GET /automation/_status` serves, and no longer echoes the request. A service that does not implement `getFlowRuntimeStates` keeps the old answer, the request echoed. So does a flow name two packages hold, switched at one package's address (`/automation/:ns/:name/toggle`) or at the bare name while only one holder's package is enabled: that reading has one row per holder under the same name, so it cannot tell which row was switched, and the engine's echo is true because it refuses the one switch-on that would leave the flow off.

**Who moves, in one line.** Publish the flow with status `active` first, then switch it on. A flow already published `active` that still reads `enabled: false` needs one more switch-on.

**Unchanged.** Switching such a flow off is still accepted: it writes `active: false`, which keeps the flow off after a later definition ships it active. Every flow whose status is `active` or `draft` switches on and off as before. A customer-authored flow is still refused by the earlier provenance check.
100 changes: 100 additions & 0 deletions packages/runtime/src/domains/automation-addressed-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,3 +719,103 @@ describe('[#33905] a flow whose only holder\'s package is disabled: the bare doo
}
});
});

/**
* [ADR-0126 §7.2, ADR-0150 D4] The toggle door's `200` answers the switched
* flow's own state, on a name two packages hold too. The door reaches such a
* name through `flowSlotView` (an address, or the bare name with one served
* holder left), whose `toggleFlow` switches one slot, while the engine reads
* one row per slot under the bare name, in registration order. A row picked by
* 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.
*
* 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).
*/
describe('[ADR-0126 §7.2] the toggle door answers the switched slot, on a name two packages hold', () => {
const NAME = 'convert';

function registryOf(order: readonly string[], disabled: readonly string[] = []) {
const registry = new SchemaRegistry();
registry.logLevel = 'silent';
for (const [id, namespace] of [[CRM, 'crm'], [HR, 'hr']]) {
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace } as never, 'code');
}
for (const holder of order) registry.registerItem('flow', { name: NAME, _packageId: holder }, 'name' as never, holder);
for (const id of disabled) registry.disablePackage(id);
return registry;
}

/** `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);
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 }))),
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: {} })),
toggleFlowSlot: vi.fn(async (pkg: string, _name: string, enabled: boolean) => { state.set(pkg, enabled); }),
};
const services: Record<string, unknown> = { automation, objectql: { registry } };
const resolve = (name: string) => services[name];
const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
const dispatcher = new HttpDispatcher(kernel);
const toggle = async (path: string, enabled: boolean) => {
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) };
}

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);
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[HR, true]]);
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
expect(on.body?.data?.enabled).toBe(stateOf(HR));
expect(stateOf(CRM)).toBe(false);
});

it('switched OFF at the second holder\'s address, the first holder on: 200 { enabled: false } (FROM: the first holder\'s true)', async () => {
const { toggle, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, true], [HR, true]]);
const off = await toggle(`/hr/${NAME}/toggle`, false);
expect([off.status, off.body?.data], JSON.stringify(off.body)).toEqual([200, { name: NAME, enabled: false }]);
expect(off.body?.data?.enabled).toBe(stateOf(HR));
expect(stateOf(CRM)).toBe(true);
});

it('the bare name whose one served holder is the second registered (the first disabled, its slot off): 200 { enabled: true } (FROM: the disabled holder\'s false)', async () => {
const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR], [CRM]), [[CRM, false], [HR, false]]);
const on = await toggle(`/${NAME}/toggle`, true);
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[HR, true]]);
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
expect(on.body?.data?.enabled).toBe(stateOf(HR));
expect(automation.toggleFlow).not.toHaveBeenCalled();
});

it('CONTROL — the first holder\'s address, the second holder reading the opposite: the answer is the first holder\'s own state', async () => {
const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, false], [HR, true]]);
const on = await toggle(`/crm/${NAME}/toggle`, true);
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[CRM, true]]);
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
expect(on.body?.data?.enabled).toBe(stateOf(CRM));
});

it('CONTROL — a name one package holds still answers its one row read back, not the request', async () => {
const { toggle, automation } = dispatcherOver(registryOf([HR]), [[HR, false]]);
// The row reads off whatever was asked: the door answers the row.
automation.toggleFlowSlot.mockImplementation(async () => {});
automation.toggleFlow.mockImplementation(async () => {});
automation.getFlow.mockImplementation(async (name: string) => (name === NAME ? { name } : null) as never);
const on = await toggle(`/${NAME}/toggle`, true);
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: false }]);
expect(automation.getFlowRuntimeStates).toHaveBeenCalled();
});
});
74 changes: 74 additions & 0 deletions packages/runtime/src/domains/automation-toggle-caller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import { describe, it, expect, vi } from 'vitest';

import { HttpDispatcher } from '../http-dispatcher.js';
// Paid at collection, not inside a clocked case: the dispatcher's package domain
// reaches it through a dynamic import (check:test-source-alias).
import '@objectstack/metadata';

function makeDispatcher() {
const toggleFlow = vi.fn(async (_name: string, _on: boolean, _caller?: { userId?: string }) => undefined);
Expand Down Expand Up @@ -62,3 +65,74 @@ describe('#26474 — the flow toggle door passes its caller to toggleFlow', () =
expect(caller).toEqual({ userId: 'u_admin' });
});
});

/**
* [ADR-0126 §7.2] The 200 answer is the engine's state read back through
* `getFlowRuntimeStates` (the reading `GET /_status` serves), never the
* request echoed: the switch moves only the ledger bit, so a flow its own
* status keeps off read `{enabled: true}` here and `enabled: false` there.
* The stand-in's state is set apart from what toggleFlow was asked, so an echo
* and a read-back answer differently.
*/
describe('[ADR-0126 §7.2] the toggle door answers the engine state, not the request', () => {
function dispatcherWithState(stateEnabled: boolean | undefined, readsState = true) {
const toggleFlow = vi.fn(async () => undefined);
const getFlowRuntimeStates = vi.fn(() =>
stateEnabled === undefined ? [] : [{ name: 'welcome_flow', enabled: stateEnabled, bound: stateEnabled }],
);
const services: Record<string, unknown> = {
automation: {
getFlow: async (name: string) => (name === 'welcome_flow' ? { name, trigger: { type: 'manual' } } : null),
toggleFlow,
...(readsState ? { getFlowRuntimeStates } : {}),
},
};
const resolve = (name: string) => services[name];
const kernel: any = {
getService: resolve,
getServiceAsync: async (name: string) => resolve(name),
context: { getService: resolve },
};
return { dispatcher: new HttpDispatcher(kernel), toggleFlow, getFlowRuntimeStates };
}

it('enable requested, the engine reads the flow off: 200 { enabled: false }, as GET /_status reads it', async () => {
const { dispatcher, toggleFlow } = dispatcherWithState(false);
const ctx = ctxOf({ userId: 'u_admin' });

const on = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: true }, ctx);
const status = await dispatcher.handleAutomation('/_status', 'GET', undefined, ctx);

expect(toggleFlow).toHaveBeenLastCalledWith('welcome_flow', true, { userId: 'u_admin' });
expect(on.response?.status).toBe(200);
expect(on.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: false });
expect(status.response?.body?.data?.flows?.[0]?.enabled).toBe(on.response?.body?.data?.enabled);
});

it('disable requested, the engine reads the flow on: 200 { enabled: true }', async () => {
const { dispatcher } = dispatcherWithState(true);

const off = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: false }, ctxOf({ userId: 'u_admin' }));

expect(off.response?.status).toBe(200);
expect(off.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: true });
});

it('CONTROL — engine state agrees with the request: the answer is that state', async () => {
const { dispatcher, getFlowRuntimeStates } = dispatcherWithState(true);

const on = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: true }, ctxOf({ userId: 'u_admin' }));

expect(on.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: true });
expect(getFlowRuntimeStates).toHaveBeenCalled();
});

it('a service that does not implement the read keeps the legacy answer, the request echoed', async () => {
const { dispatcher } = dispatcherWithState(undefined, false);

const off = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: false }, ctxOf({ userId: 'u_admin' }));

expect(off.response?.status).toBe(200);
expect(off.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: false });
});
});
36 changes: 34 additions & 2 deletions packages/runtime/src/domains/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3781,7 +3781,15 @@ export async function classifyResumeResult(
* activation ledger. A flow no package ships → 409
* `RESOURCE_CONFLICT` naming that flow's own switch,
* its `status` ('obsolete' / 'active') published
* through `PUT /:name`; nothing changes (#20726)
* through `PUT /:name`; nothing changes (#20726).
* Switching ON a packaged flow whose own `status`
* 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)
* ⚑ authoring write — `manage_metadata` (commit 266436a7f):
* enablement is environment-wide, so an
* unentitled toggle reached every organization
Expand Down Expand Up @@ -4422,7 +4430,31 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
// [#26474] Who asked, so the ledger row and its audit row name
// them. The id only: this door has already judged the caller.
await automationService.toggleFlow(name, enabled, activationCaller(context));
return { handled: true, response: deps.success({ name, enabled }) };
// [ADR-0126 §7.2] The answer is the engine's state read back,
// never the request echoed: the switch moves only the ledger
// bit, and the flow's `status` is a second dimension it does
// 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.
const svc = automationService as Pick<IAutomationService, 'getFlowRuntimeStates'>;
const rows = typeof svc.getFlowRuntimeStates === 'function'
? svc.getFlowRuntimeStates().filter((s) => s.name === name)
: [];
const state = rows.length === 1 ? rows[0] : undefined;
return { handled: true, response: deps.success({ name, enabled: state ? state.enabled : enabled }) };
}
}

Expand Down
Loading
Loading