Keep your data
The tutorial runs the leave App on SQLite in memory, so every request is gone when the script ends. Here the same App runs on a SQLite file. A second run finds what the first run saved, and finishes the work it left queued.
What you build
Section titled “What you build”| You change | What it gives you |
|---|---|
The database is the file leave.db |
Requests that are still there on the next run |
| The script opens the Workspace the file holds | A second run that works, and a third |
| The queued work runs at the start of a run | Work that one run leaves behind, done by the next |
The App does not change. Every step is a change to the script that runs it.
Before you start
Section titled “Before you start”You need leave.ts and people.ts from chapter 4 of the tutorial. Both stay as they are.
You write a new, short run.ts. It uses only the packages the Quickstart installed. Move the tutorial’s script out of the way:
mv run.ts tutorial.tsYou run the App the same way in every step:
PYN_ENV=local npx tsx run.ts1. Point the database at a file
Section titled “1. Point the database at a file”Create run.ts. Most of it is the Quickstart’s script. The marked lines are new:
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 in the file leave.db, with the Alpyne tables.const knex = await createSqliteKnexDatabase('leave.db');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.const platform = createSqlitePlatformService(services);const reactor = createSqliteInstance({ ...services, platform }, {});const runtime = { ...services, platform, reactor };const harness = await createHarnessInstance(runtime, leaveApp);
// A Workspace to hold the App's data.const workspace = await harness.createWorkspace();console.log(`Leave App is running in Workspace ${workspace.workspaceId}`);
// List the requests the file holds.const saved = await workspace.read(async (ctx) => { const leave = ctx.apps.leave; return await leave.queries.list.handler({}, leave, ctx);});for (const item of saved) { console.log(`Saved: "${item.properties.reason}" is ${item.state.value}`);}
// Request one day of leave. The reason counts the requests the file holds.const request = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; const input = { days: 1, reason: `Trip ${saved.length + 1}` }; 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();await knex.destroy();Three things differ from the Quickstart:
- The database is a file.
createSqliteKnexDatabase('leave.db')opensleave.dbin the folder you run the script from, and creates it when it is missing. - The script lists what is saved. It prints every request the file holds, before it adds one.
- Each run adds one request. The reason counts the requests: “Trip 1” on the first run, “Trip 2” on the second.
Run it. You should see:
Leave App is running in Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Requested: "Trip 1" is pendingApproved: "Trip 1" is approvedListener: "Trip 1" is approvedNothing was saved before this run, so it prints no Saved: line. The request is in leave.db now.
Run it again. This run should print Saved: "Trip 1" is approved. It stops before that, with an AlpyneError and a stack trace. The message ends:
[error-001-workspace-exists] Attempting to create a workspace with id:56eef1d9-c851-5e2f-87c7-8759dcf17469, but that workspace already exists.The Workspace is already in the file. harness.createWorkspace() gives your App’s Workspace the same Identifier on every run, and the file holds one Workspace for each Identifier.
2. Create the Workspace once, then open it
Section titled “2. Create the Workspace once, then open it”A run has to tell a new file from one that holds the Workspace. In run.ts, replace the three lines that create the Workspace, from // A Workspace to hold the App's data. down, with these:
// Create the Workspace on the first run. Every run after that finds it in the file.const workspaceId = '56eef1d9-c851-5e2f-87c7-8759dcf17469';const found = await platform.checkWorkspaceExists(workspaceId);if (!found) await harness.createWorkspace();console.log(`${found ? 'Opened' : 'Created'} Workspace ${workspaceId}`);
// Open the Workspace by its Identifier, to read from it or to write to it.const auth = { tag: 'run', type: 'system', workspaceId } as const;const workspace = { read: async <T>(fn: (ctx: ReadRuntimeInstance) => Promise<T>) => { const instance = await platform.createInstance(auth); return await instance.execute('read', async (_root, ctx) => await fn(ctx)); }, write: async <T>(fn: (ctx: WriteRuntimeInstance) => Promise<T>) => { const instance = await platform.createInstance(auth); return await instance.execute('readwrite', { payload: {}, traceId: 'run' }, fn); },};The two types come from @alpynehq/alpyne-types. Import them in the first line of run.ts:
import type { ReadRuntimeInstance, WriteRuntimeInstance } from '@alpynehq/alpyne-types/runtime';The new lines do two jobs:
- Create, or find.
checkWorkspaceExistslooks in the file for the Workspace. The Identifier is the one your first run printed. It is made from the App’s name,leave, so it is the same on your machine.harness.createWorkspace()runs only when the file does not hold the Workspace. - Open.
platform.createInstance(auth)opens the Workspace thatauthnames, as the system.readandwriterun your function in it, the way the harness’sworkspace.readandworkspace.writedo. The rest of the script calls them by the same names, so it does not change.
createHarnessInstance still runs on every run. It loads your App from leave.ts, because the file holds the App’s data and not the App.
3. Run it three times
Section titled “3. Run it three times”Run it:
Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Saved: "Trip 1" is approvedRequested: "Trip 2" is pendingApproved: "Trip 2" is approvedListener: "Trip 2" is approvedThe script opened the Workspace, and “Trip 1” from step 1 is still there, approved. This run added “Trip 2”.
Run it again:
Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Saved: "Trip 1" is approvedSaved: "Trip 2" is approvedRequested: "Trip 3" is pendingApproved: "Trip 3" is approvedListener: "Trip 3" is approvedAnd once more:
Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Saved: "Trip 1" is approvedSaved: "Trip 2" is approvedSaved: "Trip 3" is approvedRequested: "Trip 4" is pendingApproved: "Trip 4" is approvedListener: "Trip 4" is approvedEach run lists what the runs before it saved, oldest first, then adds one request of its own.
4. Leave work for the next run
Section titled “4. Leave work for the next run”approve saves an Event with the approval, and the Listener runs when the script reaches harness.tickAll(). The Event is in the file too. A run that ends before harness.tickAll() leaves it there, and the next run finds it.
To see it, move harness.tickAll() from the end of the script to the start. Replace the last three lines of run.ts with these two:
// Close the database. The work the approval queued stays in the file.await knex.destroy();Then add these lines above the block that lists the requests:
// Finish the work an earlier run left queued.await harness.tickAll();Run it:
Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Saved: "Trip 1" is approvedSaved: "Trip 2" is approvedSaved: "Trip 3" is approvedSaved: "Trip 4" is approvedRequested: "Trip 5" is pendingApproved: "Trip 5" is approved“Trip 5” is approved, and no Listener: line follows. The script ended with the Event saved and its Listener still to run.
Run it again:
Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Listener: "Trip 5" is approvedSaved: "Trip 1" is approvedSaved: "Trip 2" is approvedSaved: "Trip 3" is approvedSaved: "Trip 4" is approvedSaved: "Trip 5" is approvedRequested: "Trip 6" is pendingApproved: "Trip 6" is approvedThe second line is the Listener for “Trip 5”. The run before committed the approval and its Event together. This run’s harness.tickAll() found the Event in the file and ran the Listener. The approval of “Trip 6” now waits in the file the same way.
5. Start over
Section titled “5. Start over”Everything the App saved is in leave.db. To start over, delete it:
rm -f leave.db leave.db-wal leave.db-shmA run that ends well leaves one file, leave.db. A run that stops on an error, like the second run in step 1, leaves two more beside it: leave.db-wal and leave.db-shm. The command deletes all three.
Run the script again:
Created Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469Requested: "Trip 1" is pendingApproved: "Trip 1" is approvedThe script found no Workspace, so it created one in a new leave.db. The count starts again at “Trip 1”.
What you have now
Section titled “What you have now”- Data that stays.
leave.dbholds every request, and each run finds what the runs before it saved. - A Workspace you create once. The script creates it on the first run and opens it by its Identifier on every run after that.
- Work that waits. An Event one run saves is still there for the next run, which runs its Listener.
- A clean start. Delete
leave.dband the two files beside it, and the next run begins with nothing.
The whole run script
import type { ReadRuntimeInstance, 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 in the file leave.db, with the Alpyne tables.const knex = await createSqliteKnexDatabase('leave.db');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.const platform = createSqlitePlatformService(services);const reactor = createSqliteInstance({ ...services, platform }, {});const runtime = { ...services, platform, reactor };const harness = await createHarnessInstance(runtime, leaveApp);
// Create the Workspace on the first run. Every run after that finds it in the file.const workspaceId = '56eef1d9-c851-5e2f-87c7-8759dcf17469';const found = await platform.checkWorkspaceExists(workspaceId);if (!found) await harness.createWorkspace();console.log(`${found ? 'Opened' : 'Created'} Workspace ${workspaceId}`);
// Open the Workspace by its Identifier, to read from it or to write to it.const auth = { tag: 'run', type: 'system', workspaceId } as const;const workspace = { read: async <T>(fn: (ctx: ReadRuntimeInstance) => Promise<T>) => { const instance = await platform.createInstance(auth); return await instance.execute('read', async (_root, ctx) => await fn(ctx)); }, write: async <T>(fn: (ctx: WriteRuntimeInstance) => Promise<T>) => { const instance = await platform.createInstance(auth); return await instance.execute('readwrite', { payload: {}, traceId: 'run' }, fn); },};
// Finish the work an earlier run left queued.await harness.tickAll();
// List the requests the file holds.const saved = await workspace.read(async (ctx) => { const leave = ctx.apps.leave; return await leave.queries.list.handler({}, leave, ctx);});for (const item of saved) { console.log(`Saved: "${item.properties.reason}" is ${item.state.value}`);}
// Request one day of leave. The reason counts the requests the file holds.const request = await workspace.write(async (ctx) => { const leave = ctx.apps.leave; const input = { days: 1, reason: `Trip ${saved.length + 1}` }; 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}`);
// Close the database. The work the approval queued stays in the file.await knex.destroy();
