Skip to content

Add states and transitions

Give a Template a state machine when its Items move through named stages and only some moves are valid, such as a leave request that is approved or declined from pending.

  • A Template declared with addTemplate. Define data covers Templates and Properties.
  • A Mutation that executes the transition. A transition runs in a write execution.
  • The harness from Test an app to run the Verify section.
  1. Declare the states. On the Template, call addState once per state. Mark one state with setDefault: a new Item starts there when createChild receives no state. Mark other valid starting states with setInitial: createChild(template, { state: 'approved' }) accepts a default or initial state and rejects every other state. An Item exposes its state as item.state.value; state is never null on a Template that declares states, and is null on a Template without states.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };
  2. Declare the transitions. On the source state, call addTransition(key, target). Both states belong to the same Template. A transition is directional, a state may have several, and a transition back to the source state is permitted.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };
  3. Grant the transition. A transition accepts Grants for a Template Role. Declare the Role on the Template with addRole and pass it to addGrant on the transition. The Role callback returns the access identifiers that may execute it: principal Identifiers or App Role PRNs.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };
  4. Execute the transition from a Mutation. Read the Item through current.templates.leaveRequest.getItem, check item.state.value, and call item.state.transitions.approve.execute({}). The call returns the updated Item; continue with that Item, because earlier references keep the old state. The transitions available on item.state.transitions are those declared on the Item’s current state.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };
  5. Publish the matching Event. A transition changes the state and nothing else. Declare an Event on the Template and publish it on the updated Item so Listeners and Metrics react after the write commits. The payload passed to execute does not publish anything; the Event is always explicit.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };
  6. Let the Runtime resolve a conflict. A transition is atomic against its source state. When another execution has already moved the Item, execute rejects with StateTransitionConflictError. The Runtime classifies the conflict as transient and starts a fresh attempt of the whole write execution, once by default (maximumTransientRetries on ReadWriteExecuteOptions). Keep the state check at the top of the handler and do not catch the conflict there: the new attempt reads the committed state, and the check decides what happens.

    examples/state-transitions/leave-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface DecideInput {
    readonly id: string;
    }
    export const leaveApp: AppSpec = (app) => {
    app.configure('leave');
    const approver = app.addRole('approver', { label: 'Approver' });
    const leaveRequest = app.addTemplate('leaveRequest');
    leaveRequest.addProperty('reason', 'string');
    leaveRequest.addProperty('decisionNoted', 'boolean');
    const pending = leaveRequest.addState('pending').setDefault();
    const approved = leaveRequest.addState('approved').setInitial();
    const declined = leaveRequest.addState('declined');
    const approve = pending.addTransition('approve', approved);
    pending.addTransition('decline', declined);
    const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);
    approve.addGrant(reviewer);
    const approvedEvent = leaveRequest.addEvent('approved');
    approvedEvent.addListener('noteDecision', async (_event, item) => {
    await item.updateProperties({ decisionNoted: true });
    });
    const approveRequest = app.addMutation('approve', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    const updated = await item.state.transitions.approve.execute({});
    await updated.events.approved.publish({});
    });
    approveRequest.input.addProperty('id', 'id').mandatory();
    approveRequest.output.void();
    const declineRequest = app.addMutation('decline', async (input: DecideInput, current) => {
    const item = await current.templates.leaveRequest.getItem(input.id);
    if (item === undefined) throw new Error('Leave request not found');
    if (item.state.value !== 'pending') return;
    await item.state.transitions.decline.execute({});
    });
    declineRequest.input.addProperty('id', 'id').mandatory();
    declineRequest.output.void();
    };

The test creates leave requests, approves and declines them through the Mutations, and forces a conflict by holding one write execution open while a second one commits a competing transition.

examples/state-transitions/leave-app.test.ts
import { createHarnessInstance } from '@pyn-backend/platform-harness-public';
import { createTestPlatformService } from '@pyn-backend/platform-service-test';
import { createTestCronService } from '@pyn-backend/service-cron-test';
import { createTestSystemService } from '@pyn-backend/service-system-test';
import { createTestLoggerService } from '@pyn-backend/test-services-logger';
import { describe, expect, it } from 'vitest';
import { leaveApp } from './leave-app';
const setup = async () => {
const system = createTestSystemService();
const logger = createTestLoggerService();
const cron = createTestCronService({ system });
const platform = createTestPlatformService({ cron, logger, system });
const harness = await createHarnessInstance({ cron, logger, platform, system }, leaveApp);
const workspace = await harness.createWorkspace();
const createRequest = async (state?: string) =>
await workspace.write(async (ctx) => {
const parent = await ctx.getWorkspaceItem();
const item = await parent.createChild(ctx.apps.leave.templates.leaveRequest, { properties: { reason: 'Holiday' }, state });
return item.id;
});
const readState = async (id: string) => await workspace.read(async (ctx) => (await ctx.getItem(id))?.state?.value);
return { createRequest, harness, readState, workspace };
};
describe('leave request state machine', () => {
it('starts in the default state and accepts a declared initial state', async () => {
const { createRequest, readState } = await setup();
const pendingId = await createRequest();
const approvedId = await createRequest('approved');
expect(await readState(pendingId)).toBe('pending');
expect(await readState(approvedId)).toBe('approved');
await expect(createRequest('declined')).rejects.toThrow();
});
it('approves a pending request and publishes the matching Event', async () => {
const { createRequest, harness, readState, workspace } = await setup();
const id = await createRequest();
await workspace.write(async (ctx) => {
const current = ctx.apps.leave;
await current.mutations.approve.handler({ id }, current, ctx);
});
expect(await readState(id)).toBe('approved');
await workspace.read(async (ctx) => {
expect((await ctx.getItem(id))?.properties.decisionNoted).toBeUndefined();
});
await harness.tickAll();
await workspace.read(async (ctx) => {
expect((await ctx.getItem(id))?.properties.decisionNoted).toBe(true);
});
});
it('leaves a decided request unchanged when a second decision arrives', async () => {
const { createRequest, readState, workspace } = await setup();
const id = await createRequest();
await workspace.write(async (ctx) => {
const current = ctx.apps.leave;
await current.mutations.approve.handler({ id }, current, ctx);
});
await workspace.write(async (ctx) => {
const current = ctx.apps.leave;
await current.mutations.decline.handler({ id }, current, ctx);
});
expect(await readState(id)).toBe('approved');
});
it('retries a write execution whose transition conflicted with a committed one', async () => {
const { createRequest, readState, workspace } = await setup();
const id = await createRequest();
let attempts = 0;
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const first = workspace.write(async (ctx) => {
attempts += 1;
const current = ctx.apps.leave;
if (attempts === 1) await gate;
await current.mutations.approve.handler({ id }, current, ctx);
});
await workspace.write(async (ctx) => {
const current = ctx.apps.leave;
await current.mutations.decline.handler({ id }, current, ctx);
});
release();
await first;
expect(attempts).toBe(2);
expect(await readState(id)).toBe('declined');
});
});

From the repository root, run:

Terminal window
pnpm run cli test alpynehq/alpyne/website/examples/state-transitions/

You should see:

Test Files 1 passed (1)
Tests 4 passed (4)

A new Item starts in pending, state: 'approved' is accepted because approved is an initial state, and state: 'declined' is rejected. The approve Mutation moves the Item and the noteDecision Listener runs after tickAll. A second decision on a decided Item returns without changing it. The conflicting write execution runs twice: the first attempt rejects with the conflict, the second attempt sees declined and returns.