Skip to content

Handle events

Publish an Event when something happened that other code reacts to, such as a task being completed, and register Listeners for the reaction.

  • A Template declared with addTemplate. Define data covers Templates and Properties.
  • A Mutation that publishes the Event. Publishing needs a write execution.
  • The harness from Run and test it and Test an app to run the Verify section.
  1. Declare the Event and its input. On the Template, call addEvent(key). Declare payload Properties on event.input; the Runtime parses every published payload against them. An Event declared on a Template is published against one Item. An Event declared on the App with app.addEvent is published against the Workspace Item. Every Template also has events.created: reading it declares an Event that the Runtime publishes whenever an Item of the Template is created (Created Event).

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };
  2. Register a Listener. Call addListener(key, handler) on the Event. The handler receives the Event, the Item it was published against, the current App and a write context. It runs in its own write execution after the Event is processed. Read the payload through event.payload.

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };
  3. Bubble to the parent and declare child Events. Call addParentListener(key, childEvent, handler) on a parent Template to react to an Event published on a child Item. The handler receives the Event, the parent, the child, the current App and the write context, and the reactor walks the hierarchy up to the Workspace Item. Declare an Event that a Listener publishes with addChildEvent. The Builder rejects a circular declaration, and the Runtime bounds an Event chain at 20 Events deep (Limits and errors).

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };
  4. Schedule an Event. Call addSchedule(key, crontab) on the Event with a five-part crontab expression. When the schedule is due, the Runtime publishes the Event once for every Item of the Template that is not archived. Chain .state(['open']) to restrict it to Items in the listed states. A schedule on an App Event publishes once against the Workspace Item. Timing is best effort: a due time passed over several times fires once.

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };
  5. Choose publish or immediate. publish(payload) appends the Event to the Workspace’s Event history inside the write execution. The reactor claims it after the commit and runs the Listeners. Awaiting publish awaits the append, not the Listeners, and an array publishes one Event per payload. immediate(payload) appends the Event and runs its Listeners inline, so their writes are visible before the call returns. The reactor never processes an immediate Event. A Listener error during immediate propagates to the caller: let it propagate to fail the execution, or catch it to continue. Unit of Work defines what a rollback does to the Event and the Listeners’ writes.

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };
  6. Seed a Workspace with an App Hook. Call app.onCreate(fn) to run code for every new Workspace, or app.onSeed(fn) for a source Workspace. The hook receives prev, the current App and a system write context. Hooks form a chain: awaiting prev() runs the hooks registered earlier and the hooks of imported Apps; a hook that returns without calling prev() stops the chain there.

    examples/events/onboarding-app.ts
    import type { AppSpec } from '@alpynehq/alpyne-types/builder';
    interface CompleteInput {
    readonly id: string;
    readonly note: string;
    }
    export const onboardingSpec: AppSpec = (app) => {
    app.configure('onboarding');
    const plan = app.addTemplate('plan');
    plan.addProperty('completedTasks', 'integer');
    plan.addProperty('reminderCount', 'integer');
    const task = app.addTemplate('task');
    task.addProperty('title', 'string');
    task.addProperty('lastNote', 'string');
    const completed = task.addEvent('completed');
    completed.input.addProperty('note', 'string');
    completed.addListener('recordNote', async (event, item) => {
    const note = event.payload.note;
    if (typeof note === 'string') await item.updateProperties({ lastNote: note });
    });
    const progressed = plan.addEvent('progressed');
    completed.addChildEvent(progressed);
    plan.addParentListener('countCompleted', completed, async (_event, parent) => {
    const count = typeof parent.properties.completedTasks === 'number' ? parent.properties.completedTasks : 0;
    const updated = await parent.updateProperties({ completedTasks: count + 1 });
    await updated.events.progressed.publish({});
    });
    const reminderDue = plan.addEvent('reminderDue');
    reminderDue.addSchedule('daily', '0 9 * * *');
    reminderDue.addListener('remind', async (_event, item) => {
    const count = typeof item.properties.reminderCount === 'number' ? item.properties.reminderCount : 0;
    await item.updateProperties({ reminderCount: count + 1 });
    });
    const complete = app.addMutation('complete', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.publish({ note: input.note });
    });
    complete.input.addProperty('id', 'id').mandatory();
    complete.input.addProperty('note', 'string').mandatory();
    complete.output.void();
    const completeNow = app.addMutation('completeNow', async (input: CompleteInput, current) => {
    const item = await current.templates.task.getItem(input.id);
    if (item === undefined) throw new Error('Task not found');
    await item.events.completed.immediate({ note: input.note });
    const updated = await current.templates.task.getItem(input.id);
    const note = updated?.properties.lastNote;
    return typeof note === 'string' ? note : undefined;
    });
    completeNow.input.addProperty('id', 'id').mandatory();
    completeNow.input.addProperty('note', 'string').mandatory();
    completeNow.output.value('string');
    app.onCreate(async (prev, current, ctx) => {
    await prev();
    const workspace = await ctx.getWorkspaceItem();
    await workspace.createChild(current.templates.plan, {
    key: 'starter',
    properties: { completedTasks: 0, reminderCount: 0 },
    });
    });
    };

The test publishes completed both ways, moves the clock across a schedule boundary and relies on the starter plan that the onCreate hook created.

examples/events/onboarding-app.test.ts
import type { SystemWriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
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 { onboardingSpec } from './onboarding-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 }, onboardingSpec);
const workspace = await harness.createWorkspace();
const ids = await workspace.write(async (ctx) => {
const plan = await ctx.getItemByKeyPath('starter');
if (plan === undefined) throw new Error('The onCreate hook did not create the starter plan');
const task = await plan.createChild(ctx.apps.onboarding.templates.task, { properties: { title: 'Sign the contract' } });
return { planId: plan.id, taskId: task.id };
});
return { ...ids, harness, workspace };
};
describe('onboarding events', () => {
it('runs Listeners and parent Listeners after the reactor processes a published Event', async () => {
const { harness, planId, taskId, workspace } = await setup();
await workspace.write(async (ctx) => {
const current = ctx.apps.onboarding;
await current.mutations.complete.handler({ id: taskId, note: 'Signed' }, current, ctx);
});
await workspace.read(async (ctx) => {
expect((await ctx.getItem(taskId))?.properties.lastNote).toBeUndefined();
expect((await ctx.getItem(planId))?.properties.completedTasks).toBe(0);
});
await harness.tickAll();
await workspace.read(async (ctx) => {
expect((await ctx.getItem(taskId))?.properties.lastNote).toBe('Signed');
expect((await ctx.getItem(planId))?.properties.completedTasks).toBe(1);
});
await workspace.write<void, SystemWriteRuntimeInstance>(async (ctx) => {
const events = await ctx.selectEvents().itemId(planId).execute();
const plan = await ctx.getItem(planId);
if (plan === undefined) throw new Error('Plan not found');
expect(events.results.some((event) => event.eventPrn === plan.events.progressed.prn)).toBe(true);
});
expect.assertions(5);
});
it('runs Listeners inline when an Event is published with immediate', async () => {
const { taskId, workspace } = await setup();
const note = await workspace.write(async (ctx) => {
const current = ctx.apps.onboarding;
return await current.mutations.completeNow.handler({ id: taskId, note: 'Signed today' }, current, ctx);
});
expect(note).toBe('Signed today');
});
it('publishes a scheduled Event for every Item when the schedule is due', async () => {
const { harness, planId, workspace } = await setup();
await harness.tickAll({ millisecond: 1 });
await harness.tickAll({ days: 1 });
await workspace.read(async (ctx) => {
expect((await ctx.getItem(planId))?.properties.reminderCount).toBe(1);
});
expect.assertions(1);
});
});

From the repository root, run:

Terminal window
pnpm run cli test alpynehq/alpyne/website/examples/events/

You should see:

Test Files 1 passed (1)
Tests 3 passed (3)

After the complete Mutation resolves, lastNote is absent and completedTasks is 0. After harness.tickAll(), the Listener and the parent Listener have run and the progressed Event is in the Event history. completeNow returns the note from the same write execution because immediate ran the Listener inline. The first tickAll({ millisecond: 1 }) primes the schedule clock; tickAll({ days: 1 }) passes 09:00 and publishes reminderDue for the plan.