Skip to content

A Workspace per customer

Run it as a server left you with one server that answers for one Workspace. Here the same server answers for two customers, acme and globex. Each has a Workspace of its own in the one leave.db, and neither customer’s requests appear in the other’s list.

You change What it gives you
The script creates a Workspace for each customer Two customers in the one leave.db
The first part of the path names the customer One server that answers at /acme/... and /globex/...
Each call opens the Workspace its path names A list that holds one customer’s requests and no other’s

The App does not change. Every change is in server.ts.

You need leave.ts, people.ts and server.ts as Run it as a server left them. There is nothing to install: server.ts imports the same packages as before.

If that server is still running, stop it with Ctrl-C. Then start with a new file, so your lists match the ones here:

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

Change server.ts so it reads like this. Every line that is not marked is already in your script. The marked lines are new:

server.ts
import { randomUUID } from 'node:crypto';
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 { createRestExpress } from '@pyn-backend/platform-transport-rest-express';
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 { createLocalTicker } from '@tsvcs/ticker/local';
import express from 'express';
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 };
await createHarnessInstance(runtime, leaveApp);
// Each customer's name, and the Identifier of that customer's Workspace.
const customers = new Map([
['acme', 'ebb23f3a-270a-42c3-98d8-22b79094e2c0'],
['globex', 'd2959d87-54a2-47c4-abbe-9bc0559f7cff'],
]);
// Create each Workspace on the first run. Every run after that finds it in the file.
for (const [customer, workspaceId] of customers) {
const found = await platform.checkWorkspaceExists(workspaceId);
if (found) continue;
await platform.createWorkspace({
canonicalAppId: 'leave',
sourceWorkspaceId: workspaceId,
traceId: randomUUID(),
vendorId: workspaceId,
workspaceId,
});
console.log(`Created a Workspace for ${customer}`);
}
// Run the queued work in a loop, with a pause of 100 milliseconds between passes.
const ticker = createLocalTicker({ delayMilliseconds: 100 });
await ticker.register(reactor);
await ticker.register(platform);
// Answer HTTP calls. The first part of the path names the customer.
const app = express();
app.use(express.json());
app.use((request, _response, next) => {
Object.assign(request, { traceId: randomUUID() });
next();
});
app.all('/:customer/*', async (request, response, next) => {
try {
const workspaceId = customers.get(request.params.customer);
if (workspaceId === undefined) {
response.sendStatus(404);
return;
}
const auth = { tag: 'server', type: 'system', workspaceId } as const;
const instance = await platform.createInstance(auth);
await createRestExpress(instance)(request, response, next);
} catch (error) {
next(error);
}
});
const port = Number(process.env.PORT ?? 3000);
const server = app.listen(port, () => console.log(`Listening on port ${port}`));
// Ctrl-C ends the loop. Then close the port and the database.
ticker.onDestroy(async () => {
server.close();
await knex.destroy();
return true;
});
await ticker.start();

They take the place of the lines that created one Workspace and opened it for every call. The new lines do three jobs:

  • Name the customers. customers holds each customer’s name and the Identifier of that customer’s Workspace. An Identifier is a UUID, and these two are made up for the example. Alpyne knows a Workspace by its Identifier. The names are the script’s own.
  • Create each Workspace once. platform.createWorkspace creates a Workspace for the App that canonicalAppId names: leave, the name leave.ts sets with app.configure. The script calls it only for a Workspace the file does not hold.
  • Open the Workspace the path names. createRestExpress skips the first part of the path. It was api, and now it is the customer’s name: /acme/leave/mutation/request is the request Mutation, run for acme. The script looks the name up in customers and opens that Workspace for the call. A name that is not in customers gets a 404.

createWorkspace takes the Workspace’s Identifier three times. workspaceId is the Workspace to create. sourceWorkspaceId names its Source Workspace: a new Workspace starts as a copy of the Items in its Source Workspace. Each of these Workspaces names itself, so it starts with no requests. vendorId is stored with the Workspace, and the script gives the same Identifier there.

createHarnessInstance still loads your App. The script does not keep the harness it returns, because platform.createWorkspace now creates the Workspaces.

Every call still runs as the system, and the path alone names the customer. Anyone who can reach the port can call as any customer.

Start the server:

Terminal window
PYN_ENV=local npx tsx server.ts

You should see:

Created a Workspace for acme
Created a Workspace for globex
Listening on port 3000

The script created both Workspaces in leave.db, then started to listen.

Leave the server running and open a second terminal. Request five days of leave as acme:

Terminal window
curl -X POST localhost:3000/acme/leave/mutation/request \
-H 'content-type: application/json' \
-d '{"days":5,"reason":"Summer holiday"}'

curl prints the response on one line. Here it is on several lines:

{
"createdAt": "2020-01-01T00:00:00.000Z",
"id": "59e3f3bf-cddb-4e1d-aaa8-f2aabfc54ac3",
"isArchived": false,
"parentId": "ebb23f3a-270a-42c3-98d8-22b79094e2c0",
"properties": {
"reason": "Summer holiday",
"days": 5
},
"relations": {},
"rolePrns": [
"prn::leave:template/leaveRequest/role/staff"
],
"state": "pending",
"templatePrn": "prn::leave:template/leaveRequest"
}

Your id differs. parentId is the Identifier of acme’s Workspace, the one in customers: the request belongs to that Workspace.

The other responses on this page are trimmed to three of these fields: id, properties and state.

List acme’s requests:

Terminal window
curl localhost:3000/acme/leave/query/list
[
{
"id": "59e3f3bf-cddb-4e1d-aaa8-f2aabfc54ac3",
"properties": {
"reason": "Summer holiday",
"days": 5
},
"state": "pending"
}
]

List globex’s requests:

Terminal window
curl localhost:3000/globex/leave/query/list
[]

The list is empty. That call opened globex’s Workspace, and acme’s request is not in it.

Request two days of leave as globex:

Terminal window
curl -X POST localhost:3000/globex/leave/mutation/request \
-H 'content-type: application/json' \
-d '{"days":2,"reason":"Conference"}'
{
"id": "cea598ad-59c4-4a79-98a4-07fd857a1912",
"properties": {
"reason": "Conference",
"days": 2
},
"state": "pending"
}

Approve it. Put the id from your own response in place of this one:

Terminal window
curl -X POST localhost:3000/globex/leave/mutation/approve \
-H 'content-type: application/json' \
-d '{"id":"cea598ad-59c4-4a79-98a4-07fd857a1912"}'
{
"id": "cea598ad-59c4-4a79-98a4-07fd857a1912",
"properties": {
"reason": "Conference",
"days": 2
},
"state": "approved"
}

Look at the server’s terminal:

Created a Workspace for acme
Created a Workspace for globex
Listening on port 3000
Listener: "Conference" is approved

The last line is the Listener in leave.ts, run for globex’s approval. One loop runs the queued work of both customers.

List acme’s requests again:

Terminal window
curl localhost:3000/acme/leave/query/list
[
{
"id": "59e3f3bf-cddb-4e1d-aaa8-f2aabfc54ac3",
"properties": {
"reason": "Summer holiday",
"days": 5
},
"state": "pending"
}
]

The list is as it was: one request, still pending. List globex’s requests:

Terminal window
curl localhost:3000/globex/leave/query/list
[
{
"id": "cea598ad-59c4-4a79-98a4-07fd857a1912",
"properties": {
"reason": "Conference",
"days": 2
},
"state": "approved"
}
]

This list holds globex’s own request, approved, and nothing of acme’s.

A call as globex that names acme’s request fails, because that request is not in globex’s Workspace.

4. Call a customer the script does not name

Section titled “4. Call a customer the script does not name”

List the requests of initech, which is not in customers:

Terminal window
curl localhost:3000/initech/leave/query/list
Not Found

The response is a 404. The script sends it before it opens a Workspace, so the call reaches no customer’s requests.

In the server’s terminal, press Ctrl-C. The process ends, and leave.db holds both Workspaces.

Start the server again:

Terminal window
PYN_ENV=local npx tsx server.ts

It prints one line:

Listening on port 3000

No Created line comes before it. The script found both Workspaces in the file and created neither. From the second terminal, list acme’s requests:

Terminal window
curl localhost:3000/acme/leave/query/list
[
{
"id": "59e3f3bf-cddb-4e1d-aaa8-f2aabfc54ac3",
"properties": {
"reason": "Summer holiday",
"days": 5
},
"state": "pending"
}
]

Then globex’s:

Terminal window
curl localhost:3000/globex/leave/query/list
[
{
"id": "cea598ad-59c4-4a79-98a4-07fd857a1912",
"properties": {
"reason": "Conference",
"days": 2
},
"state": "approved"
}
]

Both requests are still there, each in its own customer’s list.

  • A Workspace for each customer. The script creates it on the first run and finds it in leave.db on every run after that.
  • The customer in the path. /acme/leave/... runs in acme’s Workspace and /globex/leave/... in globex’s. Any other name gets a 404.
  • Requests that stay apart. A customer’s list holds that customer’s requests and no other’s, before a restart and after it.
  • One server for both. One process, one port, one leave.db and one loop for the queued work.