Skip to content

Tutorial: compose and measure

Chapter 3 ended with an App that acts after every decision. It still works alone, and nothing adds up what it has done. In this chapter the leave App imports a second App that holds people, each request points at the person who asked for it, and a Metric counts the approvals.

You add What it gives you
A people App, imported by the leave App person Items that a leave request can point at
A requester Relation The person who asked, one step from the request
An approvals Metric with a requester Dimension The number of approvals, in total and for each person

One imported App, one Relation and one Metric with a Dimension.

You need leave.ts and run.ts from chapter 3, with all five steps done. This chapter uses one package the Quickstart did not install. Install it:

Terminal window
npm install @pyn-backend/platform-projector-sqlite

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
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"

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

An App can import another App and use what it declares. Next to leave.ts, create people.ts. It is a second App, with one Template:

people.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
export const peopleApp: AppSpec = (app) => {
app.configure('people');
const person = app.addTemplate('person');
person.addProperty('name', 'string');
};

In leave.ts, import the file below the first line:

leave.ts
import { peopleApp } from './people';

Then import the App, below app.configure('leave');:

leave.ts
const people = app.addDependency('people', peopleApp);
const person = people.templates.person;

addDependency adds the people App to yours and returns a handle on it. people.templates.person is its person Template. You use it in leave.ts like a Template of your own.

At the end of run.ts, above the last line, add Alice and Bob to the people App:

run.ts
// Add Alice and Bob to the people App.
const persons = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const person = ctx.apps.people.templates.person;
const alice = await person.createItem(root, { properties: { name: 'Alice' } });
const bob = await person.createItem(root, { properties: { name: 'Bob' } });
return { alice: alice.id, bob: bob.id };
});
for (const id of [persons.alice, persons.bob]) {
const item = await workspace.read(async (ctx) => await ctx.getItem(id));
console.log(`Person: ${item?.properties.name} is an Item of ${item?.templatePrn}`);
}

Your script reaches the imported App by its name, ctx.apps.people, the same way it reaches ctx.apps.leave.

Run it. You should see two new lines:

Person: Alice is an Item of prn::people:template/person
Person: Bob is an Item of prn::people:template/person

Each PRN names the person Template of the people App.

Alice is now two Items. The user from chapter 2 makes calls and holds a Role. The person is what the people App knows about her. Nothing links the two, so run.ts keeps both Identifiers: people.alice is the user and persons.alice is the person.

A Relation links one Item to another. In leave.ts, declare one from the leave request to the person, below the three Properties:

leave.ts
leaveRequest.addRelation('requester', 'many-to-one', person, { toKey: 'leave' });

many-to-one says many requests point at one person. A request calls the Relation requester, and a person calls it leave.

Alice makes the request, so your handler loads the person as Alice. She needs a Grant to see it, and the people App grants its person to nobody. Add the Grant below the one on the leave request:

leave.ts
const colleagues = person.addRole('colleagues', async () => [employee.prn]);
person.addGrant(colleagues, Object.values(person.properties));

This is the Grant from chapter 2, on a Template your App imported. Every employee sees a person and its name.

A request now says who asked. Add requester to RequestInput:

leave.ts
readonly requester?: string;

Then change request to set the Relation. The marked lines are new or changed:

leave.ts
const request = app.addMutation('request', async (input: RequestInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
const item = await workspace.createChild(current.templates.leaveRequest, {
properties: { days: input.days, reason: input.reason },
});
if (input.requester !== undefined) {
const requester = await ctx.apps.people.templates.person.getItem(input.requester);
if (requester === undefined) throw new Error('Person not found');
const relation = item.relations.requester;
if (relation.type === 'one') await relation.set(requester);
}
return item;
});
request.input.addProperty('reason', 'string').mandatory();
request.input.addProperty('days', 'integer').mandatory();
request.input.addProperty('requester', 'id');
request.output.item(leaveRequest).mandatory();

Your handler loads the person from the people App and points the new request at it. A request sent without a requester is saved as before, so the earlier calls in run.ts still work.

At the end of run.ts, above the last line, request two days of leave as Alice and send her person with it:

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

Below that, follow the Relation from the request to the person:

run.ts
// Follow the Relation from the request to the person.
const requester = await as(people.alice, async (ctx) => {
const item = await ctx.getItem(conference.id);
const relation = item?.relations.requester;
return relation?.type === 'one' ? await relation.get() : undefined;
});
console.log(`As Alice: "Conference" was requested by ${requester?.properties.name}`);

Run it:

Person: Alice is an Item of prn::people:template/person
Person: Bob is an Item of prn::people:template/person
As Alice: "Conference" is pending
As Alice: "Conference" was requested by Alice

get() returns the person the request points at. Alice reads the name of an Item that belongs to another App.

A Metric counts Events, and a Dimension says who each count belongs to. In leave.ts, declare both below the remind Listener:

leave.ts
const approvals = app.addMetric('approvals');
approvals.addEvent(approvedEvent);
const byRequester = app.addMetricDimension('requester', [person]);
approvals.addDimension(byRequester, 1, async (event, _dimension, ctx) => {
const item = await ctx.getItem(event.itemId);
const relation = item?.relations.requester;
return relation?.type === 'one' ? await relation.get() : undefined;
});

Each approved Event adds 1 to approvals. For each Event, your handler loads the request, follows requester and returns the person, so the Metric keeps a count for each person. For a request with no requester it returns undefined, and the approval counts in the total only.

Run it. The output does not change, because nothing reads the Metric yet.

A query does not count leave requests. It reads the counts that a projector builds from the saved Events, and your script has no projector. At the top of run.ts, import one below the harness import:

run.ts
import { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';

Register it below the line that creates the harness:

run.ts
await harness.ticker.register(createSqliteProjector(runtime, { spec: leaveApp }));

From now on, harness.tickAll() runs the projector with the rest of the queued work.

At the end of run.ts, above the last line, add a helper that reads the Metric, and call it:

run.ts
// Read the approvals Metric: the total, and the count for Alice.
const showApprovals = async () => {
const report = await workspace.read(async (ctx) => {
const metric = ctx.apps.leave.metrics.approvals;
const byRequester = metric.dimensions.requester;
const from = ctx.now.minus({ days: 7 }).toJSDate();
const to = ctx.now.toJSDate();
return await metric
.query('count')
.focalDimension(byRequester)
.dimensions([byRequester])
.interval(from, to)
.period('day')
.execute();
});
const total = report.value ?? 0;
const alice = report.entries.day.entries[persons.alice]?.value ?? 0;
console.log(`Metric: ${total} approvals, ${alice} for Alice`);
};
await showApprovals();

A query needs a focal Dimension, an interval and a period. Every query names a focal Dimension, and dimensions lists the Dimensions that break the result down. Here both are requester.

The interval is the last seven days on the script’s clock. The period is a label: with 'day', the count for each person sits under report.entries.day. report.value is the total, and null while nothing is counted. The entry under Alice’s Identifier holds her count.

Run it:

Person: Alice is an Item of prn::people:template/person
Person: Bob is an Item of prn::people:template/person
As Alice: "Conference" is pending
As Alice: "Conference" was requested by Alice
Metric: 2 approvals, 0 for Alice

The Metric holds two approvals already: “Summer holiday” from the Quickstart and “Long weekend” from chapter 2. The projector counted them in the harness.tickAll() calls earlier in the script. “Summer holiday” was canceled later and still counts, because a Metric counts Events, not the state of an Item. Neither request points at a person, so Alice has none.

Approve Alice’s request as Bob, and read the Metric twice: before the queued work runs, and after. At the end of run.ts, above the last line:

run.ts
// Approve the request as Bob. Show the Metric before and after the queued work runs.
const counted = await as(people.bob, async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.approve.handler({ id: conference.id }, leave, ctx);
});
console.log(`As Bob: "${counted.properties.reason}" is ${counted.state.value}`);
await showApprovals();
await harness.tickAll();
await showApprovals();

Run it:

Person: Alice is an Item of prn::people:template/person
Person: Bob is an Item of prn::people:template/person
As Alice: "Conference" is pending
As Alice: "Conference" was requested by Alice
Metric: 2 approvals, 0 for Alice
As Bob: "Conference" is approved
Metric: 2 approvals, 0 for Alice
Listener: "Conference" is approved
Metric: 3 approvals, 1 for Alice

approve returned with the request approved and the Event saved, and the Metric still read 2. The projector counted the Event when run.ts reached harness.tickAll(). The total is now 3, and 1 of them is Alice’s.

  • An imported App. people holds the person Items. Your App reaches it through addDependency in leave.ts and through ctx.apps.people when it runs.
  • A Relation across Apps. Each new request points at the person who asked for it, and employees see that person.
  • A Metric with a Dimension. approvals counts every approved Event, in total and for each person.
  • A projector in your script. harness.tickAll() runs it, so the count moves when the queued work runs.
The whole App
leave.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
import { peopleApp } from './people';
interface RequestInput {
readonly days: number;
readonly reason: string;
readonly requester?: string;
}
interface IdInput {
readonly id: string;
}
interface RejectInput extends IdInput {
readonly note?: string;
}
export const leaveApp: AppSpec = (app) => {
app.configure('leave');
const people = app.addDependency('people', peopleApp);
const person = people.templates.person;
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');
leaveRequest.addRelation('requester', 'many-to-one', person, { toKey: 'leave' });
const staff = leaveRequest.addRole('staff', async () => [employee.prn]);
leaveRequest.addGrant(staff, Object.values(leaveRequest.properties));
const colleagues = person.addRole('colleagues', async () => [employee.prn]);
person.addGrant(colleagues, Object.values(person.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 approvals = app.addMetric('approvals');
approvals.addEvent(approvedEvent);
const byRequester = app.addMetricDimension('requester', [person]);
approvals.addDimension(byRequester, 1, async (event, _dimension, ctx) => {
const item = await ctx.getItem(event.itemId);
const relation = item?.relations.requester;
return relation?.type === 'one' ? await relation.get() : undefined;
});
const request = app.addMutation('request', async (input: RequestInput, current, ctx) => {
const workspace = await ctx.getWorkspaceItem();
const item = await workspace.createChild(current.templates.leaveRequest, {
properties: { days: input.days, reason: input.reason },
});
if (input.requester !== undefined) {
const requester = await ctx.apps.people.templates.person.getItem(input.requester);
if (requester === undefined) throw new Error('Person not found');
const relation = item.relations.requester;
if (relation.type === 'one') await relation.set(requester);
}
return item;
});
request.input.addProperty('reason', 'string').mandatory();
request.input.addProperty('days', 'integer').mandatory();
request.input.addProperty('requester', 'id');
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 people App
people.ts
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
export const peopleApp: AppSpec = (app) => {
app.configure('people');
const person = app.addTemplate('person');
person.addProperty('name', 'string');
};
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 { createSqliteProjector } from '@pyn-backend/platform-projector-sqlite';
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);
await harness.ticker.register(createSqliteProjector(runtime, { spec: 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);
// Add Alice and Bob to the people App.
const persons = await workspace.write(async (ctx) => {
const root = await ctx.getWorkspaceItem();
const person = ctx.apps.people.templates.person;
const alice = await person.createItem(root, { properties: { name: 'Alice' } });
const bob = await person.createItem(root, { properties: { name: 'Bob' } });
return { alice: alice.id, bob: bob.id };
});
for (const id of [persons.alice, persons.bob]) {
const item = await workspace.read(async (ctx) => await ctx.getItem(id));
console.log(`Person: ${item?.properties.name} is an Item of ${item?.templatePrn}`);
}
// Request two days of leave as Alice, for the person Alice.
const conference = await as(people.alice, async (ctx) => {
const leave = ctx.apps.leave;
const input = { days: 2, reason: 'Conference', requester: persons.alice };
return await leave.mutations.request.handler(input, leave, ctx);
});
console.log(`As Alice: "${conference.properties.reason}" is ${conference.state.value}`);
// Follow the Relation from the request to the person.
const requester = await as(people.alice, async (ctx) => {
const item = await ctx.getItem(conference.id);
const relation = item?.relations.requester;
return relation?.type === 'one' ? await relation.get() : undefined;
});
console.log(`As Alice: "Conference" was requested by ${requester?.properties.name}`);
// Read the approvals Metric: the total, and the count for Alice.
const showApprovals = async () => {
const report = await workspace.read(async (ctx) => {
const metric = ctx.apps.leave.metrics.approvals;
const byRequester = metric.dimensions.requester;
const from = ctx.now.minus({ days: 7 }).toJSDate();
const to = ctx.now.toJSDate();
return await metric
.query('count')
.focalDimension(byRequester)
.dimensions([byRequester])
.interval(from, to)
.period('day')
.execute();
});
const total = report.value ?? 0;
const alice = report.entries.day.entries[persons.alice]?.value ?? 0;
console.log(`Metric: ${total} approvals, ${alice} for Alice`);
};
await showApprovals();
// Approve the request as Bob. Show the Metric before and after the queued work runs.
const counted = await as(people.bob, async (ctx) => {
const leave = ctx.apps.leave;
return await leave.mutations.approve.handler({ id: conference.id }, leave, ctx);
});
console.log(`As Bob: "${counted.properties.reason}" is ${counted.state.value}`);
await showApprovals();
await harness.tickAll();
await showApprovals();
await knex.destroy();

This is the last chapter. You started with the Quickstart’s leave request, which was pending or approved. Now it is a small App:

  • A lifecycle. Four states, and a refusal for a move you did not declare. Chapter 1.
  • Access rules. Two Roles, a Grant on every operation, and calls made as Alice and as Bob. Chapter 2.
  • Work after a decision. Events with payloads, Listeners, and a schedule on a clock you move. Chapter 3.
  • Composition and measurement. An imported App, a Relation to its people, and a Metric. This chapter.

All of it is two Apps and one script: leave.ts, people.ts and run.ts.

Each guide takes one part of the App further.