Skip to content

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.

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.

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:

Terminal window
mv run.ts tutorial.ts

You run the App the same way in every step:

Terminal window
PYN_ENV=local npx tsx run.ts

Create run.ts. Most of it is the Quickstart’s script. The marked lines are new:

run.ts
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') opens leave.db in 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-8759dcf17469
Requested: "Trip 1" is pending
Approved: "Trip 1" is approved
Listener: "Trip 1" is approved

Nothing 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:

run.ts
// 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:

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

The new lines do two jobs:

  • Create, or find. checkWorkspaceExists looks 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 that auth names, as the system. read and write run your function in it, the way the harness’s workspace.read and workspace.write do. 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.

Run it:

Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469
Saved: "Trip 1" is approved
Requested: "Trip 2" is pending
Approved: "Trip 2" is approved
Listener: "Trip 2" is approved

The 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-8759dcf17469
Saved: "Trip 1" is approved
Saved: "Trip 2" is approved
Requested: "Trip 3" is pending
Approved: "Trip 3" is approved
Listener: "Trip 3" is approved

And once more:

Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469
Saved: "Trip 1" is approved
Saved: "Trip 2" is approved
Saved: "Trip 3" is approved
Requested: "Trip 4" is pending
Approved: "Trip 4" is approved
Listener: "Trip 4" is approved

Each run lists what the runs before it saved, oldest first, then adds one request of its own.

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:

run.ts
// 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:

run.ts
// Finish the work an earlier run left queued.
await harness.tickAll();

Run it:

Opened Workspace 56eef1d9-c851-5e2f-87c7-8759dcf17469
Saved: "Trip 1" is approved
Saved: "Trip 2" is approved
Saved: "Trip 3" is approved
Saved: "Trip 4" is approved
Requested: "Trip 5" is pending
Approved: "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-8759dcf17469
Listener: "Trip 5" is approved
Saved: "Trip 1" is approved
Saved: "Trip 2" is approved
Saved: "Trip 3" is approved
Saved: "Trip 4" is approved
Saved: "Trip 5" is approved
Requested: "Trip 6" is pending
Approved: "Trip 6" is approved

The 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.

Everything the App saved is in leave.db. To start over, delete it:

Terminal window
rm -f leave.db leave.db-wal leave.db-shm

A 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-8759dcf17469
Requested: "Trip 1" is pending
Approved: "Trip 1" is approved

The script found no Workspace, so it created one in a new leave.db. The count starts again at “Trip 1”.

  • Data that stays. leave.db holds 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.db and the two files beside it, and the next run begins with nothing.
The whole run script
run.ts
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();