Skip to content

Tutorial: what happens next

Chapter 2 ended with Bob’s approval and a Listener that prints one line. In this chapter the App does work after a decision, and after no decision at all. A rejection carries Bob’s note, a Listener saves a notice on the request, and a schedule reminds every request that is still waiting.

When What the App does next
Bob rejects a request with a note Saves the notice Rejected: Team offsite
A request is still pending at 9:00 on a weekday Saves the notice Waiting for a decision

Two Events, two Listeners and one schedule. A real App sends each notice as an email or a chat message. This one saves it on the request, so you can read it back.

You need leave.ts and run.ts from chapter 2, with all five steps done. You run the App the same way in every step:

Terminal window
PYN_ENV=local npx tsx run.ts

It prints:

Leave App is running in Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469
Requested: "Summer holiday" is pending
Approved: "Summer holiday" is approved
Listener: "Summer holiday" is approved
Rejected: "Moving house" is rejected
Canceled: "Summer holiday" is canceled
Listed: "Summer holiday" is canceled
Listed: "Moving house" is rejected
Refused: A rejected leave request cannot be canceled
Listed: "Summer holiday" is canceled
Listed: "Moving house" is rejected
Joined: Alice holds prn::leave:role/employee
Joined: Bob holds prn::leave:role/manager
As Alice: "Long weekend" is pending
As Alice: Refused. Grant assertion failed for the current principal: none of [prn::leave:role/manager] held
As Bob: "Long weekend" is approved
Listener: "Long weekend" is approved

Every step below adds lines after these, and shows only the lines it adds.

An Event says that something happened, and its payload carries the details. In leave.ts, declare a rejected Event with a note, below the approved Listener:

leave.ts
const rejectedEvent = leaveRequest.addEvent('rejected');
rejectedEvent.input.addProperty('note', 'string');

reject takes the note as input. Add an input type below IdInput:

leave.ts
interface RejectInput extends IdInput {
readonly note?: string;
}

Then change reject to take the note and publish the Event. The marked lines are new or changed:

leave.ts
const reject = app.addMutation('reject', async (input: RejectInput, current) => {
const item = await current.templates.leaveRequest.getItem(input.id);
if (item === undefined || item.state?.value !== 'pending') {
throw new Error('Leave request is not pending');
}
const updated = await item.state.transitions.reject.execute({});
await updated.events.rejected.publish({ note: input.note });
return updated;
});
reject.input.addProperty('id', 'id').mandatory();
reject.input.addProperty('note', 'string');
reject.output.item(leaveRequest).mandatory();

publish saves the Event in the same transaction as the rejection.

At the end of run.ts, above the last line, request a day of leave as Alice and reject it as Bob:

run.ts
// Request one day of leave as Alice, then reject it as Bob with a note.
const dentist = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 1, reason: 'Dentist' };
return await leave.mutations.request.handler(input, leave, ctx);
});
const refused = await as(people.bob, async (ctx) => {
const leave = ctx.apps.leave;
const input = { id: dentist.id, note: 'Team offsite' };
return await leave.mutations.reject.handler(input, leave, ctx);
});
console.log(`As Bob: "${refused.properties.reason}" is ${refused.state.value}`);

Run it. You should see one new line:

As Bob: "Dentist" is rejected

The rejection saved an Event. A call made as a person cannot read the Event history, so you read it as the system. At the top of run.ts, add the type of a system write context to the import:

run.ts
import type { SystemWriteRuntimeInstance, WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';

At the end of run.ts, above the last line, read the Events saved for the request:

run.ts
// Read the Events saved for the request.
const history = await workspace.write(async (ctx: SystemWriteRuntimeInstance) => {
const page = await ctx.selectEvents().itemId(dentist.id).execute();
return page.results;
});
for (const event of history) {
console.log(`Event: ${event.eventPrn} ${JSON.stringify(event.payload)}`);
}

Run it:

As Bob: "Dentist" is rejected
Event: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}

The Event is saved with Bob’s note. Its PRN names the rejected Event of the leaveRequest Template. Nothing listens to it yet.

A Listener is your code that runs after an Event. This one saves a notice, so the request needs a Property to hold it. In leave.ts, add notice below the two Properties:

leave.ts
leaveRequest.addProperty('notice', 'string');

The Grant on the Template, just below, covers it, so employees see the notice.

Add a Listener to the rejected Event, below its note:

leave.ts
rejectedEvent.addListener('notify', async (event, item) => {
const note = event.payload.note;
const notice = typeof note === 'string' ? `Rejected: ${note}` : 'Rejected';
await item.updateProperties({ notice });
});

Your Listener gets the Event and the request it was published for. It reads the note from event.payload and saves a notice on the request. A rejection with no note gets the notice Rejected.

In run.ts, above the last line, add a helper that prints the notice Alice sees on a request:

run.ts
// Print the notice Alice sees on a request.
const showNotice = async (id: string) => {
const item = await as(people.alice, async (ctx) => await ctx.getItem(id));
const notice = item?.properties.notice;
const text = notice === undefined ? 'no notice' : `the notice "${notice}"`;
console.log(`As Alice: "${item?.properties.reason}" has ${text}`);
};

Below it, print the notice, finish the work the App has queued, then print the notice again:

run.ts
// Show the notice before and after the queued work runs.
await showNotice(dentist.id);
await harness.tickAll();
await showNotice(dentist.id);

Run it. The notice appears between the two prints:

As Bob: "Dentist" is rejected
Event: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}
As Alice: "Dentist" has no notice
As Alice: "Dentist" has the notice "Rejected: Team offsite"

reject returned before your Listener ran, with the rejection and the Event already saved. The Runtime ran the Listener in a transaction of its own, when run.ts reached harness.tickAll().

A schedule publishes an Event by the clock. In leave.ts, declare a reminderDue Event with a schedule and a Listener, below the notify Listener:

leave.ts
const reminderDue = leaveRequest.addEvent('reminderDue');
reminderDue.addSchedule('weekdays', '0 9 * * 1-5').state(['pending']);
reminderDue.addListener('remind', async (_event, item) => {
await item.updateProperties({ notice: 'Waiting for a decision' });
});

0 9 * * 1-5 is a crontab: 9:00, Monday to Friday. state(['pending']) keeps the schedule to requests that are pending. When the schedule is due, the Runtime publishes reminderDue for each of them, and remind saves the notice.

In run.ts, above the last line, request two days of leave as Alice. Nobody decides this one:

run.ts
// Request two days of leave as Alice. Nobody decides.
const wedding = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 2, reason: 'Wedding' };
return await leave.mutations.request.handler(input, leave, ctx);
});
console.log(`As Alice: "${wedding.properties.reason}" is ${wedding.state.value}`);

Below that, finish the queued work, then print the clock and the notice:

run.ts
// Run the queued work. The clock has not moved.
await harness.tickAll();
console.log(`Clock: ${system.current.toUTCString()}`);
await showNotice(wedding.id);

Run it. The request has no notice:

As Bob: "Dentist" is rejected
Event: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}
As Alice: "Dentist" has no notice
As Alice: "Dentist" has the notice "Rejected: Team offsite"
As Alice: "Wedding" is pending
Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: "Wedding" has no notice

system is the clock you gave the Runtime at the top of run.ts. It starts on 1 January 2020 and moves only when you move it. It has not moved, so the schedule is not due.

tickAll takes a length of time. It moves the clock forward by that much, then finishes the queued work. In run.ts, above the last line, move the clock one day:

run.ts
// Move the clock forward one day, then run the queued work.
await harness.tickAll({ days: 1 });
console.log(`Clock: ${system.current.toUTCString()}`);
await showNotice(wedding.id);
await showNotice(dentist.id);

Run it. The reminder arrives:

As Bob: "Dentist" is rejected
Event: prn::leave:template/leaveRequest/event/rejected {"note":"Team offsite"}
As Alice: "Dentist" has no notice
As Alice: "Dentist" has the notice "Rejected: Team offsite"
As Alice: "Wedding" is pending
Clock: Wed, 01 Jan 2020 00:00:00 GMT
As Alice: "Wedding" has no notice
Clock: Thu, 02 Jan 2020 00:00:00 GMT
As Alice: "Wedding" has the notice "Waiting for a decision"
As Alice: "Dentist" has the notice "Rejected: Team offsite"

The clock passed 9:00 on a weekday, so the schedule was due. The Runtime published reminderDue for “Wedding”, the one request that is pending, and remind saved its notice. “Dentist” is rejected, so the schedule skipped it and its notice is unchanged.

  • An Event with a payload. rejected carries Bob’s note from the Mutation to the Listener.
  • Listeners that write. notify and remind save a notice on the request, after the Event is saved.
  • A schedule. At 9:00 on a weekday, the Runtime publishes reminderDue for every request that is pending.
  • A clock you move. tickAll({ days: 1 }) makes a day pass in your script, so you see the schedule fire.
The whole App
leave.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface RequestInput {
readonly days: number;
readonly reason: string;
}
interface IdInput {
readonly id: string;
}
interface RejectInput extends IdInput {
readonly note?: string;
}
export const leaveApp: AppSpec = (app) => {
app.configure('leave');
const employee = app.addRole('employee', { label: 'Employee' });
const manager = app.addRole('manager', { label: 'Manager' });
manager.extend(employee);
const leaveRequest = app.addTemplate('leaveRequest');
leaveRequest.addProperty('reason', 'string');
leaveRequest.addProperty('days', 'integer');
leaveRequest.addProperty('notice', 'string');
const staff = leaveRequest.addRole('staff', async () => [employee.prn]);
leaveRequest.addGrant(staff, Object.values(leaveRequest.properties));
const pending = leaveRequest.addState('pending').setDefault();
const approved = leaveRequest.addState('approved');
pending.addTransition('approve', approved);
const rejected = leaveRequest.addState('rejected');
pending.addTransition('reject', rejected);
const canceled = leaveRequest.addState('canceled');
pending.addTransition('cancel', canceled);
approved.addTransition('cancel', canceled);
const approvedEvent = leaveRequest.addEvent('approved');
approvedEvent.addListener('announce', async (_event, item) => {
console.log(`Listener: "${item.properties.reason}" is approved`);
});
const rejectedEvent = leaveRequest.addEvent('rejected');
rejectedEvent.input.addProperty('note', 'string');
rejectedEvent.addListener('notify', async (event, item) => {
const note = event.payload.note;
const notice = typeof note === 'string' ? `Rejected: ${note}` : 'Rejected';
await item.updateProperties({ notice });
});
const reminderDue = leaveRequest.addEvent('reminderDue');
reminderDue.addSchedule('weekdays', '0 9 * * 1-5').state(['pending']);
reminderDue.addListener('remind', async (_event, item) => {
await item.updateProperties({ notice: 'Waiting for a decision' });
});
const request = app.addMutation('request', async (input: RequestInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
return await workspace.createChild(current.templates.leaveRequest, {
properties: { days: input.days, reason: input.reason },
});
});
request.input.addProperty('reason', 'string').mandatory();
request.input.addProperty('days', 'integer').mandatory();
request.output.item(leaveRequest).mandatory();
const approve = app.addMutation('approve', async (input: IdInput, current) => {
const item = await current.templates.leaveRequest.getItem(input.id);
if (item === undefined || item.state?.value !== 'pending') {
throw new Error('Leave request is not pending');
}
const updated = await item.state.transitions.approve.execute({});
await updated.events.approved.publish({});
return updated;
});
approve.input.addProperty('id', 'id').mandatory();
approve.output.item(leaveRequest).mandatory();
const reject = app.addMutation('reject', async (input: RejectInput, current) => {
const item = await current.templates.leaveRequest.getItem(input.id);
if (item === undefined || item.state?.value !== 'pending') {
throw new Error('Leave request is not pending');
}
const updated = await item.state.transitions.reject.execute({});
await updated.events.rejected.publish({ note: input.note });
return updated;
});
reject.input.addProperty('id', 'id').mandatory();
reject.input.addProperty('note', 'string');
reject.output.item(leaveRequest).mandatory();
const cancel = app.addMutation('cancel', async (input: IdInput, current) => {
const item = await current.templates.leaveRequest.getItem(input.id);
if (item === undefined) throw new Error('Leave request not found');
const transition = item.state?.transitions.cancel;
if (transition === undefined) {
throw new Error(`A ${item.state?.value} leave request cannot be canceled`);
}
return await transition.execute({});
});
cancel.input.addProperty('id', 'id').mandatory();
cancel.output.item(leaveRequest).mandatory();
const list = app.addQuery('list', async (_input: unknown, current) => {
const requests = current.templates.leaveRequest.selectItems();
const page = await requests.sort(['$createdAt asc']).execute();
return page.results;
});
list.output.item(leaveRequest).array();
request.addGrant(employee);
cancel.addGrant(employee);
list.addGrant(employee);
approve.addGrant(manager);
reject.addGrant(manager);
};
The whole run script
run.ts
import type { SystemWriteRuntimeInstance, WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';
import { createSqliteKnexDatabase } from '@pyn-backend/data-knex-sqlite';
import { createHarnessInstance } from '@pyn-backend/platform-harness-public';
import { createSqliteInstance } from '@pyn-backend/platform-reactor-sqlite';
import { createSqlitePlatformService } from '@pyn-backend/platform-service-sqlite';
import { createTestConfigurationService } from '@pyn-backend/service-configuration-test';
import { createTestCronService } from '@pyn-backend/service-cron-test';
import { createTestSystemService } from '@pyn-backend/service-system-test';
import { createTestDynamicConfigService } from '@pyn-backend/test-services-dynamic-config';
import { createTestLoggerService } from '@pyn-backend/test-services-logger';
import { leaveApp } from './leave';
// A SQLite database, held in memory, with the Alpyne tables.
const knex = await createSqliteKnexDatabase(':memory:');
await knex.current.migrate.latest();
// The services a Runtime depends on.
const system = createTestSystemService();
const services = {
configuration: createTestConfigurationService(),
cron: createTestCronService({ system }),
dynamicConfig: createTestDynamicConfigService(),
knex,
logger: createTestLoggerService(),
system,
};
// The SQLite Runtime with your App loaded, and a Workspace to hold its data.
const platform = createSqlitePlatformService(services);
const reactor = createSqliteInstance({ ...services, platform }, {});
const runtime = { ...services, platform, reactor };
const harness = await createHarnessInstance(runtime, leaveApp);
const workspace = await harness.createWorkspace();
console.log(`Leave App is running in Workspace ${workspace.workspaceId}`);
// Request five days of leave.
const request = await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 5, reason: 'Summer holiday' };
return await leave.mutations.request.handler(input, leave, ctx);
});
console.log(`Requested: "${request.properties.reason}" is ${request.state.value}`);
// Approve the request.
const approved = await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.approve.handler({ id: request.id }, leave, ctx);
});
console.log(`Approved: "${approved.properties.reason}" is ${approved.state.value}`);
// Finish the work the App has queued, then close the database.
await harness.tickAll();
// Request two days of leave and reject the request.
const moving = await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 2, reason: 'Moving house' };
return await leave.mutations.request.handler(input, leave, ctx);
});
const rejected = await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.reject.handler({ id: moving.id }, leave, ctx);
});
console.log(`Rejected: "${rejected.properties.reason}" is ${rejected.state.value}`);
// Cancel the approved request.
const canceled = await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.cancel.handler({ id: request.id }, leave, ctx);
});
console.log(`Canceled: "${canceled.properties.reason}" is ${canceled.state.value}`);
// List the requests with their states.
const listRequests = async () => {
const requests = await workspace.read(async (ctx) => {
const leave = ctx.apps.leave;
return await leave.queries.list.handler({}, leave, ctx);
});
for (const item of requests) {
console.log(`Listed: "${item.properties.reason}" is ${item.state.value}`);
}
};
await listRequests();
// Try to cancel the rejected request.
try {
await workspace.write(async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.cancel.handler({ id: moving.id }, leave, ctx);
});
} catch (error) {
console.log(`Refused: ${error instanceof Error ? error.message : String(error)}`);
}
await listRequests();
// Add two people. Alice is an employee and Bob is a manager.
const people = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const user = ctx.apps.identity.templates.user;
const roles = ctx.apps.leave.roles;
const templatePrn = 'prn::identity:template/user';
const alice = await user.createItem(root, { properties: { displayName: 'Alice' } });
const bob = await user.createItem(root, { properties: { displayName: 'Bob' } });
await roles.employee.assign({ id: alice.id, templatePrn });
await roles.manager.assign({ id: bob.id, templatePrn });
return { alice: alice.id, bob: bob.id };
});
for (const id of [people.alice, people.bob]) {
const item = await workspace.read(async (ctx) => await ctx.getItem(id));
const person = item?.properties;
console.log(`Joined: ${person?.displayName} holds ${person?.rolePrns.join(', ')}`);
}
// Run a write as one person.
const as = async <T>(id: string, fn: (ctx: WriteRuntimeInstance) => Promise<T>) => {
const instance = await platform.createInstance({
identityId: crypto.randomUUID(),
principalId: id,
rolePrns: [],
sessionId: crypto.randomUUID(),
type: 'principal',
workspaceId: workspace.workspaceId,
});
return await instance.execute('readwrite', { payload: {}, traceId: 'tutorial' }, fn);
};
// Request three days of leave as Alice.
const weekend = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 3, reason: 'Long weekend' };
return await leave.mutations.request.handler(input, leave, ctx);
});
console.log(`As Alice: "${weekend.properties.reason}" is ${weekend.state.value}`);
// Try to approve the request as Alice.
try {
await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.approve.handler({ id: weekend.id }, leave, ctx);
});
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
console.log(`As Alice: Refused. ${reason}`);
}
// Approve the request as Bob, then finish the work the App has queued.
const decided = await as(people.bob, async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.approve.handler({ id: weekend.id }, leave, ctx);
});
console.log(`As Bob: "${decided.properties.reason}" is ${decided.state.value}`);
await harness.tickAll();
// Request one day of leave as Alice, then reject it as Bob with a note.
const dentist = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 1, reason: 'Dentist' };
return await leave.mutations.request.handler(input, leave, ctx);
});
const refused = await as(people.bob, async (ctx) => {
const leave = ctx.apps.leave;
const input = { id: dentist.id, note: 'Team offsite' };
return await leave.mutations.reject.handler(input, leave, ctx);
});
console.log(`As Bob: "${refused.properties.reason}" is ${refused.state.value}`);
// Read the Events saved for the request.
const history = await workspace.write(async (ctx: SystemWriteRuntimeInstance) => {
const page = await ctx.selectEvents().itemId(dentist.id).execute();
return page.results;
});
for (const event of history) {
console.log(`Event: ${event.eventPrn} ${JSON.stringify(event.payload)}`);
}
// Print the notice Alice sees on a request.
const showNotice = async (id: string) => {
const item = await as(people.alice, async (ctx) => await ctx.getItem(id));
const notice = item?.properties.notice;
const text = notice === undefined ? 'no notice' : `the notice "${notice}"`;
console.log(`As Alice: "${item?.properties.reason}" has ${text}`);
};
// Show the notice before and after the queued work runs.
await showNotice(dentist.id);
await harness.tickAll();
await showNotice(dentist.id);
// Request two days of leave as Alice. Nobody decides.
const wedding = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 2, reason: 'Wedding' };
return await leave.mutations.request.handler(input, leave, ctx);
});
console.log(`As Alice: "${wedding.properties.reason}" is ${wedding.state.value}`);
// Run the queued work. The clock has not moved.
await harness.tickAll();
console.log(`Clock: ${system.current.toUTCString()}`);
await showNotice(wedding.id);
// Move the clock forward one day, then run the queued work.
await harness.tickAll({ days: 1 });
console.log(`Clock: ${system.current.toUTCString()}`);
await showNotice(wedding.id);
await showNotice(dentist.id);
await knex.destroy();

The leave App now has a lifecycle, access rules and work that follows each decision. The last chapter of the tutorial covers how to compose and measure: importing another App, and Metrics.