Tutorial: who can do what
Chapter 1 gave the leave request its lifecycle, and your script made every call as the system. Real calls come from people: an employee asks for leave and a manager decides. In this chapter you say who can do what, add two people and make calls as each of them.
What you build
Section titled “What you build”| Operation | employee |
manager |
|---|---|---|
request, cancel, list |
Yes | Yes |
approve, reject |
No | Yes |
Two Roles and two people. Alice is an employee. Bob is a manager.
Before you start
Section titled “Before you start”You need leave.ts and run.ts from chapter 1, with all four steps done. You run the App the same way in every step:
PYN_ENV=local npx tsx run.tsIt prints:
Leave App is running in Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Requested: "Summer holiday" is pendingApproved: "Summer holiday" is approvedListener: "Summer holiday" is approvedRejected: "Moving house" is rejectedCanceled: "Summer holiday" is canceledListed: "Summer holiday" is canceledListed: "Moving house" is rejectedRefused: A rejected leave request cannot be canceledListed: "Summer holiday" is canceledListed: "Moving house" is rejectedEvery step below adds lines after these, and shows only the lines it adds.
1. Add two people
Section titled “1. Add two people”A Role names who may do something. In leave.ts, declare two Roles below app.configure('leave');:
const employee = app.addRole('employee', { label: 'Employee' }); const manager = app.addRole('manager', { label: 'Manager' }); manager.extend(employee);extend gives a manager everything an employee has.
Your script has nobody to make a call as. At the end of run.ts, above the last line, add two people and give each a Role:
// 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(', ')}`);}Alpyne adds an App named identity to every App you run. A person is an Item of its user Template. assign gives a person a Role: you pass the person’s Identifier and the PRN of the user Template, which is its full name.
Run it. You should see two new lines:
Joined: Alice holds prn::leave:role/employeeJoined: Bob holds prn::leave:role/managerA Role has a PRN too. prn::leave:role/employee is the employee Role of the leave App.
2. Say what each Role can do
Section titled “2. Say what each Role can do”A Grant links a Role to what it may do. In leave.ts, grant each operation to a Role at the end of the App, above the closing };:
request.addGrant(employee); cancel.addGrant(employee); list.addGrant(employee); approve.addGrant(manager); reject.addGrant(manager);Employees request, cancel and list. Managers approve and reject. An operation with no Grant refuses every person.
A person needs a second kind of Grant to see a leave request. Add it below the two Properties:
const staff = leaveRequest.addRole('staff', async () => [employee.prn]); leaveRequest.addGrant(staff, Object.values(leaveRequest.properties));staff is a Role on the Template. Its callback says who holds it for one leave request: here, every employee. The Grant lets staff see a leave request and all its Properties.
Run it. The output does not change. Your script still makes every call as the system, and the system passes every Grant check.
3. Request leave as Alice
Section titled “3. Request leave as Alice”To make a call as a person, you ask the Runtime for an instance that acts as that person. At the top of run.ts, import the type of a write context:
import type { WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';At the end of run.ts, above the last line, add a helper:
// 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);};as runs a write the way workspace.write does, as the person you name. That person is the principalId: Alpyne calls them the principal. identityId and sessionId name a sign-in, and nobody signs in here, so the script makes them up. rolePrns is empty because the Runtime looks up the Roles the person holds.
Below the helper, request three days of leave as Alice:
// 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}`);Run it. Alice gets her request back:
Joined: Alice holds prn::leave:role/employeeJoined: Bob holds prn::leave:role/managerAs Alice: "Long weekend" is pendingBoth Grants are at work. The Grant on request lets Alice call it. The Grant on the Template lets her see the leave request it returns. Without the second Grant, request still creates the leave request and returns nothing to her.
4. Try to approve it as Alice
Section titled “4. Try to approve it as Alice”Alice is not a manager. Below her request, try to approve it as her:
// 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}`);}Run it. The Runtime refuses the call:
Joined: Alice holds prn::leave:role/employeeJoined: Bob holds prn::leave:role/managerAs Alice: "Long weekend" is pendingAs Alice: Refused. Grant assertion failed for the current principal: none of [prn::leave:role/manager] heldThe Runtime checks the Grant on approve before your handler runs. approve is granted to manager, and Alice holds employee. The handler never starts, and the request stays pending.
5. Approve it as Bob
Section titled “5. Approve it as Bob”Bob is a manager. Below the refused call, approve the request as him, then finish the work the App has queued:
// 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();Run it. The call goes through, and the Listener runs:
Joined: Alice holds prn::leave:role/employeeJoined: Bob holds prn::leave:role/managerAs Alice: "Long weekend" is pendingAs Alice: Refused. Grant assertion failed for the current principal: none of [prn::leave:role/manager] heldAs Bob: "Long weekend" is approvedListener: "Long weekend" is approvedBob holds manager, so the Runtime lets the call through. He also holds employee, through extend, so the handler finds the request he approves.
What you have now
Section titled “What you have now”- Two Roles.
employeeandmanager. A manager is an employee too. - A Grant on every operation. Employees request, cancel and list. Managers approve and reject.
- A Grant on the Template. Employees see every leave request, with its reason and its days.
- Calls made as a person.
asruns a write as Alice or as Bob, and the Runtime checks the Roles each one holds.
The whole App
import type { AppSpec } from '@alpynehq/alpyne-types/builder';
interface RequestInput { readonly days: number; readonly reason: string;}
interface IdInput { readonly id: 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');
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 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: 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'); } return await item.state.transitions.reject.execute({}); }); reject.input.addProperty('id', 'id').mandatory(); 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
import type { 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();
await knex.destroy();Next steps
Section titled “Next steps”Bob’s approval ran a Listener. The next chapter of the tutorial covers what happens next: Events, Listeners and schedules.

