/tutorials/ticket-desk/
Build a ticket desk with vola and memento
This tutorial builds a small help desk from an empty folder: a kanban board of tickets, a page for each ticket with its files, and a feed that shows everything that happens as it happens. You write the program; the files and the history are two services you run next to it.
vola and memento
Section titled “vola and memento”vola is a self-hosted file service. It keeps the bytes and their hierarchy: uploads, thumbnails, folders, versions and share links, each file under an instance of your application such as tickets/<id>.
memento is a self-hosted activity ledger. Your application pushes events (TICKET_COMMENTED, by ana, on tickets/<id>). memento keeps them as an immutable trail, renders each one into a sentence in the reader’s language, and streams new ones over a WebSocket.
They go together because a file in a real application has an owner and a history. vola knows what the bytes are and where they sit. It does not know why they are there, and it should not. memento knows who did what, and it holds no bytes. In this program each service does its own half, and step 7 joins them with two environment variables and no code.
What you build
Section titled “What you build”The Ticket desk, in seven steps. Each step is one commit in the history of the finished program, and the chapters below use the same order and the same names.
| step | what it adds | what you can do after it |
|---|---|---|
| 1 | the stack | GET /health answers, with vola and memento running |
| 2 | the keys | the desk has a tenant and API keys in both services |
| 3 | the backend | create, assign and move tickets with curl |
| 4 | the events | every action is an event, with a sentence in English and Serbian |
| 5 | the UI | the board, the files and the feed in a browser |
| 6 | live | a change by anybody shows up without a reload |
| 7 | the audit, without code | vola’s own events appear in the same feed |
The tickets are one jsudc collection, because jsudc gives a kanban board out of the box. The board is not what this tutorial is about, so it takes one component.
What you need
Section titled “What you need”- Docker with Compose v2. The whole stack runs in containers.
- Node 24. The backend runs its TypeScript directly, with no build step.
- pnpm 11. If you do not have it,
corepack enablegets the versionpackage.jsonasks for.
Port 8080 must be free. If it is not, set DESK_PORT in .env in step 1 and use your port in every curl below.
How to read the code
Section titled “How to read the code”Every file of every step is on this page. A file a step adds is shown whole, under its path. Copy it to that path.
A file a step changes is shown as a diff: + lines are new, - lines go away, the rest is there to show you where. Edit the file by hand, or run patch -p1 in the program’s folder, paste the block and press Ctrl-D.
Tests and long stylesheets are folded, under a “Show” line. They belong to the program as much as the rest, and the checks below run them.
pnpm-lock.yaml is not shown: pnpm install writes it. README.md is not shown either, because it only points back here.
Step 1: the stack
Section titled “Step 1: the stack”Start with everything the program runs on, and a backend that only says it is alive. Make the program’s folder and work in it from now on:
mkdir ticket-desk && cd ticket-desk
@vol-a/* and @memento/* are not on npm yet, so the client packages come as five tarballs from this site. The services themselves are Docker images, so these five files are all you take from outside:
mkdir -p vendorfor tarball in vol-a-core-1.0.1 vol-a-client-1.0.1 vol-a-react-1.0.1 memento-core-1.0.0 memento-react-1.0.0; do curl -fsSL -o "vendor/$tarball.tgz" \ "https://vol-a.com/tutorials/ticket-desk/vendor/$tarball.tgz"donels vendormemento-core-1.0.0.tgzmemento-react-1.0.0.tgzvol-a-client-1.0.1.tgzvol-a-core-1.0.1.tgzvol-a-react-1.0.1.tgzThe project
Section titled “The project”package.json has no dependency on either service yet, only Fastify. pnpm-workspace.yaml makes this folder its own project and points the package names at vendor/. It costs nothing until step 4 asks for one of them.
{ "name": "ticket-desk", "version": "1.0.0", "private": true, "description": "A small help desk on vola (the files) and memento (who did what, when): the program the vola + memento tutorial is written from.", "license": "MIT", "type": "module", "packageManager": "pnpm@11.21.0", "engines": { "node": ">=24" }, "scripts": { "dev": "node --watch --env-file-if-exists=.env src/server/main.ts", "start": "node src/server/main.ts", "typecheck": "tsc --noEmit", "lint": "biome check .", "format": "biome format --write ." }, "dependencies": { "fastify": "^5.12.7" }, "devDependencies": { "@biomejs/biome": "^2.6.4", "@types/node": "^24", "typescript": "^5.9.3" }}# This folder is its own project, not a member of any repository around it. A file here also# stops pnpm from walking up to a parent workspace.packages: - "."
# Not on npm yet: see vendor/README.md.overrides: "@vol-a/core": "file:vendor/vol-a-core-1.0.1.tgz" "@vol-a/client": "file:vendor/vol-a-client-1.0.1.tgz" "@vol-a/react": "file:vendor/vol-a-react-1.0.1.tgz" "@memento/core": "file:vendor/memento-core-1.0.0.tgz" "@memento/react": "file:vendor/memento-react-1.0.0.tgz"
allowBuilds: esbuild: true{ "compilerOptions": { "target": "ES2023", "lib": ["ES2023"], "module": "NodeNext", "moduleResolution": "NodeNext", "types": ["node"], "strict": true, "noUncheckedIndexedAccess": true, "verbatimModuleSyntax": true, "erasableSyntaxOnly": true, "allowImportingTsExtensions": true, "resolveJsonModule": true, "skipLibCheck": true, "noEmit": true }, "include": ["src/server"]}node_modules/dist/.env# `make setup` writes the keys below. Only DESK_PORT is yours to change.DESK_PORT=8080Show biome.json (lint and format rules)
{ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, "files": { "includes": ["**", "!**/dist", "!**/*.md"] }, "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 }, "linter": { "enabled": true, "rules": { "preset": "recommended" } }, "javascript": { "formatter": { "quoteStyle": "double", "semicolons": "always", "trailingCommas": "all" } }}The backend
Section titled “The backend”One route for now. Later steps replace this file, one piece at a time.
import Fastify from "fastify";
const app = Fastify({ logger: true });
app.get("/health", async () => ({ ok: true }));
await app.listen({ host: "0.0.0.0", port: Number(process.env.PORT ?? 8080) });The containers
Section titled “The containers”The image installs from the lockfile and runs the TypeScript as it is.
FROM docker.io/library/node:24-slimWORKDIR /appRUN corepack enableCOPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./COPY vendor ./vendorRUN pnpm install --frozen-lockfileCOPY . .USER node# Node 24 runs TypeScript as it is: there is no build step for the server.CMD ["node", "src/server/main.ts"]node_modulesdist.env.gitOne PostgreSQL holds one database per program, so nothing mixes. The image makes the desk’s own database, because POSTGRES_USER names it, so this script makes the other two:
-- One PostgreSQL, one database per program. The desk's own is not here: the image makes it,-- because it is named after POSTGRES_USER, and making it again would stop this script with an error.CREATE DATABASE vola;CREATE DATABASE memento;The compose file is most of this step. vola and vola-worker are the same image: the worker makes the thumbnails from the same /data. Only desk publishes a port. The browser will reach vola and memento through it, on one origin.
# The whole stack: vola, its worker, memento, PostgreSQL, Redis and the desk.# docker compose up -d --build# Only the desk has a port: the browser reaches vola and memento through it (same origin).name: ticket-desk
services: vola: image: ghcr.io/digital-cube/jsvola:latest restart: unless-stopped depends_on: postgres: { condition: service_healthy } redis: { condition: service_healthy } environment: &vola-env VOLA_DATABASE_URL: postgresql://desk:desk@postgres:5432/vola VOLA_REDIS_URL: redis://redis:6379/0 VOLA_PORT: 8300 VOLA_PREFIX: /vola VOLA_STORAGE_PATH: /data/storage VOLA_OCR_ENABLED: "0" # Share links are built on this origin, the one the browser knows. VOLA_PUBLIC_URL: http://localhost:${DESK_PORT:-8080} volumes: - vola-data:/data healthcheck: test: ["CMD", "vola-healthcheck"] interval: 5s timeout: 5s start_period: 20s retries: 10
# The same image: makes the thumbnails, on the same /data. vola-worker: image: ghcr.io/digital-cube/jsvola:latest command: ["node", "dist/worker.js"] restart: unless-stopped depends_on: vola: { condition: service_healthy } environment: *vola-env volumes: - vola-data:/data healthcheck: disable: true
memento: image: ghcr.io/digital-cube/jsmemento:latest restart: unless-stopped depends_on: postgres: { condition: service_healthy } redis: { condition: service_healthy } environment: DATABASE_URL: postgresql://desk:desk@postgres:5432/memento REDIS_URL: redis://redis:6379/1 PORT: 3000 MEMENTO_DEFAULT_LOCALE: en volumes: - memento-data:/data healthcheck: test: ["CMD", "memento-healthcheck"] interval: 5s timeout: 5s start_period: 20s retries: 10
postgres: image: docker.io/library/postgres:16 restart: unless-stopped environment: POSTGRES_USER: desk POSTGRES_PASSWORD: desk volumes: - postgres-data:/var/lib/postgresql/data - ./docker/init-databases.sql:/docker-entrypoint-initdb.d/init-databases.sql:ro healthcheck: test: ["CMD-SHELL", "pg_isready -U desk -d desk"] interval: 3s timeout: 5s retries: 20
redis: image: docker.io/library/redis:7-alpine restart: unless-stopped healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 3s timeout: 5s retries: 20
# The program this tutorial writes. desk: build: . restart: unless-stopped depends_on: vola: { condition: service_healthy } memento: { condition: service_healthy } environment: PORT: 8080 ports: - "${DESK_PORT:-8080}:8080"
volumes: vola-data: memento-data: postgres-data:.PHONY: up down clean
up: docker compose up -d --build
down: docker compose down
# Everything, the data too.clean: docker compose down -vCheck it
Section titled “Check it”pnpm install writes the lockfile the image needs. The first up pulls the images and takes a few minutes.
pnpm installcp .env.example .envdocker compose up -d --buildcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echodocker compose ps --format '{{.Service}}: {{.State}}'{"ok":true}desk: runningmemento: runningpostgres: runningredis: runningvola: runningvola-worker: runningYou should see {"ok":true} and all six services running. Neither service knows about the desk yet. That is the next step.
Step 2: the keys
Section titled “Step 2: the keys”vola and memento are both multi-tenant, and neither lets you in without a key. This step makes a tenant called desk in each, through the command lines inside their images, plus four keys:
in .env |
who holds it | scopes |
|---|---|---|
MEMENTO_SERVER_KEY |
the backend | write: it pushes the events |
VOLA_SERVER_KEY |
the backend | files:read: it reads the name of an attached file |
MEMENTO_BROWSER_KEY |
the browser | read: the feed |
VOLA_BROWSER_KEY |
the browser | files:*, folders:*, shares:write: uploads go straight to vola |
The script is safe to run again, because a key .env already has is kept. The later steps rely on that: each one that needs something new from the services adds a few lines here and you run make setup again.
#!/bin/sh# Makes a tenant called `desk` in vola and in memento, and the API keys the desk needs, and writes# them to .env. Safe to run again: a key .env already has is kept.set -eucd "$(dirname "$0")/.."[ -f .env ] || cp .env.example .env
memento() { docker compose exec -T memento memento --json "$@"; }vola() { docker compose exec -T vola vola --json "$@"; }
# save_key NAME: reads a CLI answer from stdin and writes its "key" to .env as NAME=…save_key() { key=$(sed -n 's/.*"key":"\([^"]*\)".*/\1/p') [ -n "$key" ] || { echo "setup: no key came back for $1" >&2; exit 1; } echo "$1=$key" >> .env echo " $1"}missing() { ! grep -q "^$1=." .env; }
echo "Starting the stack (the first time this builds the desk)…"docker compose up -d --build
echo "Tenants…"memento list-tenants | grep -q '"slug":"desk"' \ || memento create-tenant desk --name "Ticket desk" > /dev/nullvola create-tenant --slug desk --name "Ticket desk" > /dev/null 2>&1 || true # already there
echo "Keys…"# The backend writes events and reads a file's name.missing MEMENTO_SERVER_KEY \ && memento create-key --tenant desk --name desk-server --scopes write | save_key MEMENTO_SERVER_KEYmissing VOLA_SERVER_KEY \ && vola create-key --tenant desk --name desk-server --scopes files:read | save_key VOLA_SERVER_KEY# The browser reads the feed, and works with files directly on vola.missing MEMENTO_BROWSER_KEY \ && memento create-key --tenant desk --name desk-browser --scopes read | save_key MEMENTO_BROWSER_KEYmissing VOLA_BROWSER_KEY \ && vola create-key --tenant desk --name desk-browser \ --scopes files:read,files:write,folders:read,folders:write,shares:write \ | save_key VOLA_BROWSER_KEY
echo "Restarting with the keys…"docker compose up -d
port=$(sed -n 's/^DESK_PORT=//p' .env)echo "Ready: http://localhost:${port:-8080}"The backend gets the keys from the environment, and the Makefile gets a target:
--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -94,6 +94,11 @@ services: memento: { condition: service_healthy } environment: PORT: 8080+ # `make setup` writes these to .env.+ MEMENTO_SERVER_KEY: ${MEMENTO_SERVER_KEY:-}+ MEMENTO_BROWSER_KEY: ${MEMENTO_BROWSER_KEY:-}+ VOLA_SERVER_KEY: ${VOLA_SERVER_KEY:-}+ VOLA_BROWSER_KEY: ${VOLA_BROWSER_KEY:-} ports: - "${DESK_PORT:-8080}:8080"--- a/Makefile+++ b/Makefile@@ -1,11 +1,16 @@-.PHONY: up down clean+.PHONY: up setup down clean
up: docker compose up -d --build
+# Tenants and keys in vola and memento, written to .env.+setup:+ sh scripts/setup.sh+ down: docker compose down
-# Everything, the data too.+# Everything, the data and the keys too. clean: docker compose down -v+ rm -f .envCheck it
Section titled “Check it”make setupTenants…Keys… MEMENTO_SERVER_KEY VOLA_SERVER_KEY MEMENTO_BROWSER_KEY VOLA_BROWSER_KEYRestarting with the keys…Ready: http://localhost:8080cut -d= -f1 .env | grep KEYdocker compose exec -T memento memento --json list-tenants | grep -o '"slug":"desk"'docker compose exec -T vola vola --json list-keys --tenant desk | grep -o '"name":"[^"]*"'MEMENTO_SERVER_KEYVOLA_SERVER_KEYMEMENTO_BROWSER_KEYVOLA_BROWSER_KEY"slug":"desk""name":"desk-browser""name":"desk-server"You should see the four key names, and the tenant in both services. There is no login in this program, so step 5 hands the browser its two keys. A real application gives them to signed-in users only.
make clean drops all the data and .env with it, if you ever want to start over.
Step 3: the backend
Section titled “Step 3: the backend”Now the program has something to keep: tickets, in the desk’s own database. Neither service is involved in this step.
The tickets, as a collection
Section titled “The tickets, as a collection”A ticket is one row of a jsudc collection. schema.json says what a ticket is, and view.yaml says how the board shows it: kanban_options is the whole configuration of the board. A column of the board is a row of buckets, and a card sits in the column its status names.
{ "version": "v1", "core_fields": [], "fields": { "board_id": { "type": "relation", "ref": "boards", "label_field": "name", "required": true }, "status": { "type": "enum", "values": ["new", "in_progress", "done"], "required": true, "index": true }, "order": { "type": "integer", "index": true }, "title": { "type": "string", "length": 200, "required": true, "index": true }, "body": { "type": "text" }, "assignees": { "type": "string_array" } }}# The tickets, as a kanban board. Everything the board does is read from `kanban_options`:# the columns are the rows of `buckets`, a card is in the column its `status` names, and a drag# writes `status` and `order` through UDC's `mutate`.default_renderer: kanbanavailable_renderers: [kanban]pagination: infinitepage_size_default: 100
kanban_options: bucket_collection: buckets bucket_filter_field: board_id bucket_order_field: order bucket_label_field: name bucket_color_field: color ticket_board_field: board_id ticket_bucket_field: status ticket_order_field: order card: title_field: title body_field: body assignees_field: assignees buckets: show_add_ticket_button: false min_width_px: 240 board: extendable_with_buckets: false buckets_sortable: false
columns: - { field: title } - { field: status } - { field: assignees }
search: fields: [title, body] placeholder: Search tickets case_insensitive: trueThe columns and the one board are small collections kept in memory, filled from their seed files:
{ "version": "v1", "core_fields": [], "fields": { "board_id": { "type": "relation", "ref": "boards", "label_field": "name", "required": true }, "name": { "type": "string", "required": true }, "color": { "type": "string" }, "order": { "type": "integer" } }}[ { "__meta": { "id": "new" }, "board_id": "desk", "name": "New", "color": "info", "order": 100 }, { "__meta": { "id": "in_progress" }, "board_id": "desk", "name": "In progress", "color": "warning", "order": 200 }, { "__meta": { "id": "done" }, "board_id": "desk", "name": "Done", "color": "success", "order": 300 }]kind: memory# The columns of the board. A column's id is a value of the tickets' `status`.default_renderer: tableavailable_renderers: [table]columns: - { field: name } - { field: order }{ "version": "v1", "core_fields": [], "fields": { "name": { "type": "string", "required": true } }}[{ "__meta": { "id": "desk" }, "name": "Ticket desk" }]kind: memory# The kanban renderer asks for a board. The desk has one.default_renderer: tableavailable_renderers: [table]columns: - { field: name }The routes
Section titled “The routes”desk.ts is what the backend and the frontend share. The list of users is the whole login of this program.
/** Who can "sign in": a pick from this list is the whole login of this program. */export const USERS = ["igor", "ana", "marko"] as const;
/** A ticket's status. Each one is a column of the board (collections/buckets/seed.json). */export const STATUSES = ["new", "in_progress", "done"] as const;export type Status = (typeof STATUSES)[number];
export const BOARD_ID = "desk";
export interface Ticket { id: string; title: string; body: string; status: Status; assignee: string | null;}| route | what it does |
|---|---|
POST /tickets |
a new ticket at the top of the first column |
GET /tickets/:id |
one ticket |
PATCH /tickets/:id/status |
moves it to another column |
POST /tickets/:id/assign |
gives it to somebody |
Every write needs X-User-Id, naming one of the users.
import type { Row } from "@jsudc/core";import type { Source } from "@jsudc/server";import type { FastifyInstance, FastifyRequest } from "fastify";import { z } from "zod";import { BOARD_ID, STATUSES, type Status, type Ticket, USERS } from "../shared/desk.ts";
const IdParams = z.object({ id: z.uuid() });const NewTicket = z.object({ title: z.string().trim().min(1).max(200), body: z.string().trim().max(5000).default(""),});const NewStatus = z.object({ status: z.enum(STATUSES) });const Assignment = z.object({ assignee: z.enum(USERS) });
/** What goes wrong is an HTTP status: Fastify answers with the error's `statusCode`. */function httpError(statusCode: number, message: string): Error { return Object.assign(new Error(message), { statusCode });}
/** `X-User-Id` is the signed-in user of this program: one of USERS, or the request is refused. */export function actorOf(request: FastifyRequest): string { const actor = request.headers["x-user-id"]; if (typeof actor === "string" && (USERS as readonly string[]).includes(actor)) return actor; throw httpError(401, "X-User-Id must name one of the desk's users");}
/** A row of the `tickets` collection as the API shows it. */export function toTicket(row: Row): Ticket { return { id: row.__meta.id, title: String(row.title), body: String(row.body ?? ""), status: row.status as Status, assignee: (row.assignees as string[] | undefined)?.[0] ?? null, };}
/** The first free place at the top of a column: 100 above the card that is there now. */async function topOrder(tickets: Source, status: Status): Promise<number> { const { rows } = await tickets.list({ filter: { field: "status", op: "eq", value: status }, sort: [{ field: "order" }], page: { limit: 1 }, }); return Number(rows[0]?.order ?? 0) - 100;}
export async function ticketRoutes(app: FastifyInstance, opts: { tickets: Source }) { const { tickets } = opts;
app.setErrorHandler((error: Error & { statusCode?: number; code?: string }, _request, reply) => { if (error instanceof z.ZodError) return reply.code(422).send({ error: z.prettifyError(error) }); if (error.code === "not_found") return reply.code(404).send({ error: "no such ticket" }); return reply.code(error.statusCode ?? 500).send({ error: error.message }); });
app.post("/tickets", async (request, reply) => { actorOf(request); const { title, body } = NewTicket.parse(request.body); const row = await tickets.mutate({ op: "insert", row: { board_id: BOARD_ID, status: "new", order: await topOrder(tickets, "new"), title, body, assignees: [], }, }); return reply.code(201).send(toTicket(row)); });
app.get("/tickets/:id", async (request) => { const { id } = IdParams.parse(request.params); return toTicket(await tickets.read(id)); });
app.patch("/tickets/:id/status", async (request) => { actorOf(request); const { id } = IdParams.parse(request.params); const { status } = NewStatus.parse(request.body); const row = await tickets.mutate({ op: "update", id, row: { status, order: await topOrder(tickets, status) }, }); return toTicket(row); });
app.post("/tickets/:id/assign", async (request) => { actorOf(request); const { id } = IdParams.parse(request.params); const { assignee } = Assignment.parse(request.body); return toTicket(await tickets.mutate({ op: "update", id, row: { assignees: [assignee] } })); });}buildApp takes everything the backend talks to as an argument, so the tests can replace it. udcPlugin serves the collections at POST /udc/*, which is what the board will read. main.ts is what connects the real things: it makes the table, loads the collections and starts the server.
import { type CollectionRegistry, createDispatcher, udcPlugin } from "@jsudc/server";import Fastify, { type FastifyServerOptions } from "fastify";import { ticketRoutes } from "./tickets.ts";
export interface AppOptions { registry: CollectionRegistry; logger?: FastifyServerOptions["logger"];}
/** The whole backend, with everything it talks to passed in: that is what the tests replace. */export async function buildApp({ registry, logger = false }: AppOptions) { const app = Fastify({ logger });
app.get("/health", async () => ({ ok: true }));
// POST /udc/*: the protocol the board reads the `tickets` collection through. await app.register(udcPlugin, { dispatcher: createDispatcher(registry, { log: app.log }), swagger: false, }); await app.register(ticketRoutes, { tickets: registry.get("tickets").source });
return app;}--- a/src/server/main.ts+++ b/src/server/main.ts@@ -1,7 +1,29 @@-import Fastify from "fastify";+import {+ connect,+ createCollectionTableSql,+ ensureUdcSchema,+ loadRegistry,+ makeSource,+ readCollectionAssets,+ seedCollection,+} from "@jsudc/server";+import { sql } from "drizzle-orm";+import { buildApp } from "./app.ts";
-const app = Fastify({ logger: true });+const COLLECTIONS = new URL("../../collections", import.meta.url).pathname;
-app.get("/health", async () => ({ ok: true }));+const { db } = connect(process.env.DATABASE_URL ?? "postgresql://desk:desk@localhost/desk");
+// The one table of this program: the tickets, every field in a jsonb column.+await ensureUdcSchema(db);+await db.execute(sql.raw(createCollectionTableSql("tickets")));+const asset = readCollectionAssets(COLLECTIONS).find(({ name }) => name === "tickets");+if (!asset) throw new Error("collections/tickets is missing");+await seedCollection(db, { table: "tickets", schema: asset.schemaJson, rows: [] });++const registry = loadRegistry(COLLECTIONS, (collection, reg) =>+ makeSource(collection, { db, registry: reg }),+);++const app = await buildApp({ registry, logger: true }); await app.listen({ host: "0.0.0.0", port: Number(process.env.PORT ?? 8080) });The rest is wiring: the database for the desk, the new dependencies, and the tests in the type check.
--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -90,10 +90,12 @@ services: build: . restart: unless-stopped depends_on:+ postgres: { condition: service_healthy } vola: { condition: service_healthy } memento: { condition: service_healthy } environment: PORT: 8080+ DATABASE_URL: postgresql://desk:desk@postgres:5432/desk # `make setup` writes these to .env. MEMENTO_SERVER_KEY: ${MEMENTO_SERVER_KEY:-} MEMENTO_BROWSER_KEY: ${MEMENTO_BROWSER_KEY:-}--- a/package.json+++ b/package.json@@ -14,14 +14,22 @@ "start": "node src/server/main.ts", "typecheck": "tsc --noEmit", "lint": "biome check .",- "format": "biome format --write ."+ "format": "biome format --write .",+ "test": "vitest run" }, "dependencies": {- "fastify": "^5.12.7"+ "@jsudc/core": "^0.2.0",+ "@jsudc/server": "^0.2.1",+ "drizzle-orm": "^0.45.4",+ "fastify": "^5.12.7",+ "pg": "^8.23.1",+ "zod": "^4.6.7" }, "devDependencies": { "@biomejs/biome": "^2.6.4", "@types/node": "^24",- "typescript": "^5.9.3"+ "@types/pg": "^8.23.1",+ "typescript": "^5.9.3",+ "vitest": "^5.0.5" } }--- a/tsconfig.json+++ b/tsconfig.json@@ -14,5 +14,5 @@ "skipLibCheck": true, "noEmit": true },- "include": ["src/server"]+ "include": ["src/server", "src/shared", "test", "vitest.config.ts"] }import { defineConfig } from "vitest/config";
export default defineConfig({ test: { include: ["test/**/*.test.ts"] },});The tests run the routes on tickets kept in memory, so nothing has to be up for them.
Show the tests (test/helpers.ts, test/tickets.test.ts)
import { loadRegistry, MemorySource, makeSource } from "@jsudc/server";import { buildApp } from "../src/server/app.ts";
const COLLECTIONS = new URL("../collections", import.meta.url).pathname;
/** The backend with the tickets in memory: no database, nothing to start. */export async function testApp() { const registry = loadRegistry(COLLECTIONS, (asset, reg) => asset.name === "tickets" ? new MemorySource({ schema: asset.schema }) : makeSource(asset, { registry: reg }), ); return buildApp({ registry });}
export const AS_IGOR = { "x-user-id": "igor" };import { describe, expect, it } from "vitest";import { AS_IGOR, testApp } from "./helpers.ts";
async function newTicket(app: Awaited<ReturnType<typeof testApp>>, title = "Printer on fire") { const res = await app.inject({ method: "POST", url: "/tickets", headers: AS_IGOR, payload: { title }, }); expect(res.statusCode).toBe(201); return res.json();}
describe("POST /tickets", () => { it("creates a ticket in the first column", async () => { const app = await testApp(); expect(await newTicket(app)).toMatchObject({ title: "Printer on fire", status: "new", assignee: null, }); });
it("puts a newer ticket above an older one", async () => { const app = await testApp(); const older = await newTicket(app, "older"); const newer = await newTicket(app, "newer"); const { payload } = ( await app.inject({ method: "POST", url: "/udc/list", payload: { collection: "tickets", sort: [{ field: "order" }] }, }) ).json(); expect(payload.rows.map((row: { __meta: { id: string } }) => row.__meta.id)).toEqual([ newer.id, older.id, ]); });
it("refuses a request from nobody", async () => { const app = await testApp(); const res = await app.inject({ method: "POST", url: "/tickets", payload: { title: "x" } }); expect(res.statusCode).toBe(401); });
it("refuses a user the desk does not know", async () => { const app = await testApp(); const res = await app.inject({ method: "POST", url: "/tickets", headers: { "x-user-id": "mallory" }, payload: { title: "x" }, }); expect(res.statusCode).toBe(401); });
it("refuses an empty title", async () => { const app = await testApp(); const res = await app.inject({ method: "POST", url: "/tickets", headers: AS_IGOR, payload: { title: " " }, }); expect(res.statusCode).toBe(422); });});
describe("GET /tickets/:id", () => { it("answers with the ticket", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "GET", url: `/tickets/${ticket.id}` }); expect(res.json()).toEqual(ticket); });
it("answers 404 for a ticket that is not there", async () => { const app = await testApp(); const res = await app.inject({ method: "GET", url: "/tickets/0192f7a0-0000-7000-8000-000000000000", }); expect(res.statusCode).toBe(404); });});
describe("PATCH /tickets/:id/status", () => { it("moves the ticket", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "PATCH", url: `/tickets/${ticket.id}/status`, headers: AS_IGOR, payload: { status: "in_progress" }, }); expect(res.json().status).toBe("in_progress"); });
it("refuses a status that is not a column", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "PATCH", url: `/tickets/${ticket.id}/status`, headers: AS_IGOR, payload: { status: "lost" }, }); expect(res.statusCode).toBe(422); });});
describe("POST /tickets/:id/assign", () => { it("sets the assignee", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/assign`, headers: AS_IGOR, payload: { assignee: "ana" }, }); expect(res.json().assignee).toBe("ana"); });
it("refuses somebody who is not on the desk", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/assign`, headers: AS_IGOR, payload: { assignee: "mallory" }, }); expect(res.statusCode).toBe(422); });});Check it
Section titled “Check it”pnpm installpnpm test Test Files 1 passed (1) Tests 11 passed (11)docker compose up -d --buildcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echocurl -s -X POST localhost:8080/tickets \ -H 'x-user-id: igor' -H 'content-type: application/json' \ -d '{"title":"Printer on fire"}' | tee /tmp/ticket.json; echoID=$(sed -n 's/.*"id":"\([^"]*\)".*/\1/p' /tmp/ticket.json)
curl -s -X POST "localhost:8080/tickets/$ID/assign" \ -H 'x-user-id: igor' -H 'content-type: application/json' \ -d '{"assignee":"ana"}'; echocurl -s -X PATCH "localhost:8080/tickets/$ID/status" \ -H 'x-user-id: ana' -H 'content-type: application/json' \ -d '{"status":"in_progress"}'; echo{"id":"0b9a7643-5d64-40ef-95aa-848811def427","title":"Printer on fire","body":"","status":"new","assignee":null}{"id":"0b9a7643-5d64-40ef-95aa-848811def427","title":"Printer on fire","body":"","status":"new","assignee":"ana"}{"id":"0b9a7643-5d64-40ef-95aa-848811def427","title":"Printer on fire","body":"","status":"in_progress","assignee":"ana"}You should get the ticket back three times, with assignee and then status changed. Without a user the backend refuses:
curl -s -X POST localhost:8080/tickets \ -H 'content-type: application/json' -d '{"title":"Who am I?"}'; echo{"error":"X-User-Id must name one of the desk's users"}Step 4: the events
Section titled “Step 4: the events”This is where memento comes in. Everything that happens to a ticket becomes one event, on the instance tickets/<id>, with the user as the actor.
| action | event_type |
payload |
|---|---|---|
POST /tickets |
TICKET_CREATED |
title |
POST /tickets/:id/comments |
TICKET_COMMENTED |
text |
PATCH /tickets/:id/status, or a card dragged on the board |
TICKET_STATUS_CHANGED |
status, previous |
POST /tickets/:id/assign |
TICKET_ASSIGNED |
assignee |
POST /tickets/:id/files |
TICKET_FILE_ATTACHED |
file_id, filename, size, mime_type |
Which event, and how it gets there
Section titled “Which event, and how it gets there”events.ts says which event an action is, and does nothing else, so it is easy to test.
import type { Status, Ticket } from "../shared/desk.ts";
/** One memento event: what happened (`event_type`), to what (`instance_*`), and who did it. */export interface DeskEvent { event_type: string; instance_type: "tickets"; instance_id: string; actor_id: string; payload: Record<string, unknown>;}
const onTicket = ( event_type: string, ticketId: string, actor: string, payload: Record<string, unknown>,): DeskEvent => ({ event_type, instance_type: "tickets", instance_id: ticketId, actor_id: actor, payload,});
export const ticketCreated = (ticket: Ticket, actor: string) => onTicket("TICKET_CREATED", ticket.id, actor, { title: ticket.title });
export const ticketCommented = (ticket: Ticket, actor: string, text: string) => onTicket("TICKET_COMMENTED", ticket.id, actor, { text });
export const ticketStatusChanged = (ticket: Ticket, actor: string, previous: Status) => onTicket("TICKET_STATUS_CHANGED", ticket.id, actor, { status: ticket.status, previous });
export const ticketAssigned = (ticket: Ticket, actor: string) => onTicket("TICKET_ASSIGNED", ticket.id, actor, { assignee: ticket.assignee });
export const ticketFileAttached = ( ticket: Ticket, actor: string, file: { id: string; filename: string; size: number; mime_type: string },) => onTicket("TICKET_FILE_ATTACHED", ticket.id, actor, { file_id: file.id, filename: file.filename, size: file.size, mime_type: file.mime_type, });memento.ts sends one with POST /memento/events. The change is already saved by then, so a memento that is down costs a log line and not the user’s request.
import type { DeskEvent } from "./events.ts";
export type Emit = (event: DeskEvent) => Promise<void>;
interface Log { warn(obj: unknown, msg: string): void;}
/** * `POST /memento/events`. The change is already saved when the event goes out, so a memento that * is down costs a log line, never the user's request. */export function mementoEmitter(url: string, key: string, log: Log): Emit { return async (event) => { try { const response = await fetch(`${url}/events`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json" }, body: JSON.stringify(event), signal: AbortSignal.timeout(2000), }); if (!response.ok) throw new Error(`memento answered ${response.status}`); } catch (error) { log.warn({ err: error, event_type: event.event_type }, "event not delivered"); } };}The routes tell
Section titled “The routes tell”Two new routes arrive with it. A comment has no table of its own: the event is the comment, and memento is where comments live. POST /tickets/:id/files is how the backend will hear about a file: the browser uploads straight to vola, then says so here. The backend asks vola for that file, so the event carries vola’s facts, and a file that is not on this ticket is refused.
--- a/src/server/tickets.ts+++ b/src/server/tickets.ts@@ -3,6 +3,14 @@ import type { Source } from "@jsudc/server"; import type { FastifyInstance, FastifyRequest } from "fastify"; import { z } from "zod"; import { BOARD_ID, STATUSES, type Status, type Ticket, USERS } from "../shared/desk.ts";+import {+ ticketAssigned,+ ticketCommented,+ ticketCreated,+ ticketFileAttached,+ ticketStatusChanged,+} from "./events.ts";+import type { Emit } from "./memento.ts";
const IdParams = z.object({ id: z.uuid() }); const NewTicket = z.object({@@ -11,6 +19,20 @@ const NewTicket = z.object({ }); const NewStatus = z.object({ status: z.enum(STATUSES) }); const Assignment = z.object({ assignee: z.enum(USERS) });+const NewComment = z.object({ text: z.string().trim().min(1).max(5000) });+const AttachedFile = z.object({ file_id: z.string().min(1) });++/** The facts of a file in vola, or a rejection when it is not on this ticket. */+export type FileLookup = (+ ticketId: string,+ fileId: string,+) => Promise<{ id: string; filename: string; size: number; mime_type: string }>;++export interface TicketRoutesOptions {+ tickets: Source;+ emit: Emit;+ lookupFile: FileLookup;+}
/** What goes wrong is an HTTP status: Fastify answers with the error's `statusCode`. */ function httpError(statusCode: number, message: string): Error {@@ -45,8 +67,8 @@ async function topOrder(tickets: Source, status: Status): Promise<number> { return Number(rows[0]?.order ?? 0) - 100; }
-export async function ticketRoutes(app: FastifyInstance, opts: { tickets: Source }) {- const { tickets } = opts;+export async function ticketRoutes(app: FastifyInstance, opts: TicketRoutesOptions) {+ const { tickets, emit, lookupFile } = opts;
app.setErrorHandler((error: Error & { statusCode?: number; code?: string }, _request, reply) => { if (error instanceof z.ZodError) return reply.code(422).send({ error: z.prettifyError(error) });@@ -55,7 +77,7 @@ export async function ticketRoutes(app: FastifyInstance, opts: { tickets: Source });
app.post("/tickets", async (request, reply) => {- actorOf(request);+ const actor = actorOf(request); const { title, body } = NewTicket.parse(request.body); const row = await tickets.mutate({ op: "insert",@@ -68,7 +90,9 @@ export async function ticketRoutes(app: FastifyInstance, opts: { tickets: Source assignees: [], }, });- return reply.code(201).send(toTicket(row));+ const ticket = toTicket(row);+ await emit(ticketCreated(ticket, actor));+ return reply.code(201).send(ticket); });
app.get("/tickets/:id", async (request) => {@@ -77,21 +101,53 @@ export async function ticketRoutes(app: FastifyInstance, opts: { tickets: Source });
app.patch("/tickets/:id/status", async (request) => {- actorOf(request);+ const actor = actorOf(request); const { id } = IdParams.parse(request.params); const { status } = NewStatus.parse(request.body);- const row = await tickets.mutate({- op: "update",- id,- row: { status, order: await topOrder(tickets, status) },- });- return toTicket(row);+ const before = toTicket(await tickets.read(id));+ if (before.status === status) return before;+ const ticket = toTicket(+ await tickets.mutate({+ op: "update",+ id,+ row: { status, order: await topOrder(tickets, status) },+ }),+ );+ await emit(ticketStatusChanged(ticket, actor, before.status));+ return ticket; });
app.post("/tickets/:id/assign", async (request) => {- actorOf(request);+ const actor = actorOf(request); const { id } = IdParams.parse(request.params); const { assignee } = Assignment.parse(request.body);- return toTicket(await tickets.mutate({ op: "update", id, row: { assignees: [assignee] } }));+ const ticket = toTicket(+ await tickets.mutate({ op: "update", id, row: { assignees: [assignee] } }),+ );+ await emit(ticketAssigned(ticket, actor));+ return ticket;+ });++ // A comment is nothing but its event: memento is where the comments live.+ app.post("/tickets/:id/comments", async (request, reply) => {+ const actor = actorOf(request);+ const { id } = IdParams.parse(request.params);+ const { text } = NewComment.parse(request.body);+ await emit(ticketCommented(toTicket(await tickets.read(id)), actor, text));+ return reply.code(201).send({ ok: true });+ });++ // The browser uploads straight to vola and then says so here. We ask vola for the file, so the+ // event carries vola's facts and a file that is not on this ticket is refused.+ app.post("/tickets/:id/files", async (request, reply) => {+ const actor = actorOf(request);+ const { id } = IdParams.parse(request.params);+ const { file_id } = AttachedFile.parse(request.body);+ const ticket = toTicket(await tickets.read(id));+ const file = await lookupFile(id, file_id).catch(() => {+ throw httpError(422, "that file is not on this ticket");+ });+ await emit(ticketFileAttached(ticket, actor, file));+ return reply.code(201).send({ ok: true }); }); }The board does not use these routes. It writes through UDC’s POST /udc/mutate, so two Fastify hooks stand around that route, and a dragged card gives the same event as the status route.
import type { Source } from "@jsudc/server";import type { FastifyInstance, FastifyRequest } from "fastify";import { z } from "zod";import { STATUSES, type Status } from "../shared/desk.ts";import { ticketStatusChanged } from "./events.ts";import type { Emit } from "./memento.ts";import { actorOf, toTicket } from "./tickets.ts";
/** A card dropped in another column. A drop inside its own column carries no `status`. */const CardMove = z.looseObject({ collection: z.literal("tickets"), op: z.literal("update"), id: z.uuid(), row: z.looseObject({ status: z.enum(STATUSES) }),});
/** * The board writes through UDC's `POST /udc/mutate`, not through our routes. These two hooks stand * around that route, so a dragged card gives the same TICKET_STATUS_CHANGED as the status route. */export function emitOnDrag(app: FastifyInstance, tickets: Source, emit: Emit) { const moves = new WeakMap<FastifyRequest, { actor: string; previous: Status }>();
app.addHook("preHandler", async (request) => { if (request.url !== "/udc/mutate") return; const move = CardMove.safeParse(request.body); if (!move.success) return; const actor = actorOf(request); const row = await tickets.read(move.data.id).catch(() => null); // mutate will answer not_found if (row) moves.set(request, { actor, previous: toTicket(row).status }); });
app.addHook("onSend", async (request, _reply, payload) => { const move = moves.get(request); if (!move) return payload; const answer = JSON.parse(String(payload)); if (answer.kind === "udc.mutate.ok") { const ticket = toTicket(answer.payload.row); if (ticket.status !== move.previous) { await emit(ticketStatusChanged(ticket, move.actor, move.previous)); } } return payload; });}--- a/src/server/app.ts+++ b/src/server/app.ts@@ -1,24 +1,34 @@ import { type CollectionRegistry, createDispatcher, udcPlugin } from "@jsudc/server"; import Fastify, { type FastifyServerOptions } from "fastify";-import { ticketRoutes } from "./tickets.ts";+import { emitOnDrag } from "./drag.ts";+import type { Emit } from "./memento.ts";+import { type FileLookup, ticketRoutes } from "./tickets.ts";
export interface AppOptions { registry: CollectionRegistry;+ /** Sends one event to memento. */+ emit: Emit;+ /** Asks vola about one file. */+ lookupFile: FileLookup; logger?: FastifyServerOptions["logger"]; }
/** The whole backend, with everything it talks to passed in: that is what the tests replace. */-export async function buildApp({ registry, logger = false }: AppOptions) {+export async function buildApp({ registry, emit, lookupFile, logger = false }: AppOptions) { const app = Fastify({ logger });+ const tickets = registry.get("tickets").source;
app.get("/health", async () => ({ ok: true }));
+ // Before the plugin below: its routes inherit these hooks.+ emitOnDrag(app, tickets, emit);+ // POST /udc/*: the protocol the board reads the `tickets` collection through. await app.register(udcPlugin, { dispatcher: createDispatcher(registry, { log: app.log }), swagger: false, });- await app.register(ticketRoutes, { tickets: registry.get("tickets").source });+ await app.register(ticketRoutes, { tickets, emit, lookupFile });
return app; }main.ts passes in the real memento and the real vola. This is the first use of @vol-a/client:
--- a/src/server/main.ts+++ b/src/server/main.ts@@ -7,8 +7,10 @@ import { readCollectionAssets, seedCollection, } from "@jsudc/server";+import { VolaClient } from "@vol-a/client"; import { sql } from "drizzle-orm"; import { buildApp } from "./app.ts";+import { mementoEmitter } from "./memento.ts";
const COLLECTIONS = new URL("../../collections", import.meta.url).pathname;
@@ -25,5 +27,19 @@ const registry = loadRegistry(COLLECTIONS, (collection, reg) => makeSource(collection, { db, registry: reg }), );
-const app = await buildApp({ registry, logger: true });+const vola = new VolaClient({+ baseUrl: process.env.VOLA_URL ?? "http://localhost:8300/vola",+ apiKey: process.env.VOLA_SERVER_KEY ?? "",+});++const app = await buildApp({+ registry,+ logger: true,+ emit: mementoEmitter(+ process.env.MEMENTO_URL ?? "http://localhost:3000/memento",+ process.env.MEMENTO_SERVER_KEY ?? "",+ console,+ ),+ lookupFile: (ticketId, fileId) => vola.files.info("tickets", ticketId, fileId),+}); await app.listen({ host: "0.0.0.0", port: Number(process.env.PORT ?? 8080) });--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -96,6 +96,8 @@ services: environment: PORT: 8080 DATABASE_URL: postgresql://desk:desk@postgres:5432/desk+ MEMENTO_URL: http://memento:3000/memento+ VOLA_URL: http://vola:8300/vola # `make setup` writes these to .env. MEMENTO_SERVER_KEY: ${MEMENTO_SERVER_KEY:-} MEMENTO_BROWSER_KEY: ${MEMENTO_BROWSER_KEY:-}--- a/package.json+++ b/package.json@@ -20,6 +20,7 @@ "dependencies": { "@jsudc/core": "^0.2.0", "@jsudc/server": "^0.2.1",+ "@vol-a/client": "file:vendor/vol-a-client-1.0.1.tgz", "drizzle-orm": "^0.45.4", "fastify": "^5.12.7", "pg": "^8.23.1",The sentences
Section titled “The sentences”Raw JSON is no use in a feed. A template gives memento the sentence for an event type in one language, and the reader’s locale picks which one to render. There is one file per event type and language, so TICKET_ASSIGNED.sr.hbs is the Serbian sentence for TICKET_ASSIGNED:
{{actor_id}} opened the ticket "{{payload.title}}"{{actor_id}} otvara tiket „{{payload.title}}"{{actor_id}} commented: "{{truncate payload.text 120}}"{{actor_id}} komentariše: „{{truncate payload.text 120}}"{{actor_id}} moved the ticket: {{payload.previous}} → {{payload.status}}{{actor_id}} menja status tiketa: {{payload.previous}} → {{payload.status}}{{actor_id}} assigned the ticket to {{payload.assignee}}{{actor_id}} dodeljuje tiket: {{payload.assignee}}{{actor_id}} attached {{payload.filename}}{{actor_id}} kači fajl {{payload.filename}}The Serbian sentences are in the present tense on purpose. The past tense needs the actor’s gender, and an event only has actor_id.
make setup hands them to memento:
--- a/scripts/setup.sh+++ b/scripts/setup.sh@@ -1,6 +1,7 @@ #!/bin/sh # Makes a tenant called `desk` in vola and in memento, and the API keys the desk needs, and writes-# them to .env. Safe to run again: a key .env already has is kept.+# them to .env; then gives memento the sentences of the desk's events. Safe to run again: a key+# .env already has is kept. set -eu cd "$(dirname "$0")/.." [ -f .env ] || cp .env.example .env@@ -39,6 +40,14 @@ missing VOLA_BROWSER_KEY \ --scopes files:read,files:write,folders:read,folders:write,shares:write \ | save_key VOLA_BROWSER_KEY
+echo "Templates…"+# templates/<EVENT_TYPE>.<locale>.hbs: the sentence memento renders for an event, in that language.+for file in templates/*.hbs; do+ name=$(basename "$file" .hbs)+ memento create-template --tenant desk --event-type "${name%.*}" --locale "${name##*.}" \+ --body "$(cat "$file")" --replace > /dev/null+done+ echo "Restarting with the keys…" docker compose up -dShow the tests (test/helpers.ts, test/events.test.ts)
--- a/test/helpers.ts+++ b/test/helpers.ts@@ -1,16 +1,35 @@ import { loadRegistry, MemorySource, makeSource } from "@jsudc/server"; import { buildApp } from "../src/server/app.ts";+import type { DeskEvent } from "../src/server/events.ts";
const COLLECTIONS = new URL("../collections", import.meta.url).pathname;
-/** The backend with the tickets in memory: no database, nothing to start. */+export const FILE = {+ id: "file-1",+ filename: "report.pdf",+ size: 1024,+ mime_type: "application/pdf",+};++/** The backend with the tickets in memory and a list for memento: nothing to start. */ export async function testApp() {+ const events: DeskEvent[] = []; const registry = loadRegistry(COLLECTIONS, (asset, reg) => asset.name === "tickets" ? new MemorySource({ schema: asset.schema }) : makeSource(asset, { registry: reg }), );- return buildApp({ registry });+ const app = await buildApp({+ registry,+ emit: async (event) => {+ events.push(event);+ },+ lookupFile: async (_ticketId, fileId) => {+ if (fileId !== FILE.id) throw new Error("not on this ticket");+ return FILE;+ },+ });+ return Object.assign(app, { events }); }
export const AS_IGOR = { "x-user-id": "igor" };import { describe, expect, it } from "vitest";import { AS_IGOR, FILE, testApp } from "./helpers.ts";
type App = Awaited<ReturnType<typeof testApp>>;
async function newTicket(app: App) { const res = await app.inject({ method: "POST", url: "/tickets", headers: AS_IGOR, payload: { title: "Printer on fire" }, }); return res.json();}
const lastEvent = (app: App) => app.events.at(-1);
describe("every action is one memento event", () => { it("POST /tickets: TICKET_CREATED", async () => { const app = await testApp(); const ticket = await newTicket(app); expect(app.events).toEqual([ { event_type: "TICKET_CREATED", instance_type: "tickets", instance_id: ticket.id, actor_id: "igor", payload: { title: "Printer on fire" }, }, ]); });
it("POST /tickets/:id/comments: TICKET_COMMENTED", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/comments`, headers: { "x-user-id": "ana" }, payload: { text: "On my way" }, }); expect(res.statusCode).toBe(201); expect(lastEvent(app)).toMatchObject({ event_type: "TICKET_COMMENTED", actor_id: "ana", payload: { text: "On my way" }, }); });
it("PATCH /tickets/:id/status: TICKET_STATUS_CHANGED, with the previous status", async () => { const app = await testApp(); const ticket = await newTicket(app); await app.inject({ method: "PATCH", url: `/tickets/${ticket.id}/status`, headers: AS_IGOR, payload: { status: "done" }, }); expect(lastEvent(app)).toMatchObject({ event_type: "TICKET_STATUS_CHANGED", payload: { status: "done", previous: "new" }, }); });
it("PATCH to the status it already has changes nothing and says nothing", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "PATCH", url: `/tickets/${ticket.id}/status`, headers: AS_IGOR, payload: { status: "new" }, }); expect(res.statusCode).toBe(200); expect(app.events).toHaveLength(1); });
it("POST /tickets/:id/assign: TICKET_ASSIGNED", async () => { const app = await testApp(); const ticket = await newTicket(app); await app.inject({ method: "POST", url: `/tickets/${ticket.id}/assign`, headers: AS_IGOR, payload: { assignee: "marko" }, }); expect(lastEvent(app)).toMatchObject({ event_type: "TICKET_ASSIGNED", payload: { assignee: "marko" }, }); });
it("POST /tickets/:id/files: TICKET_FILE_ATTACHED, with vola's facts", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/files`, headers: AS_IGOR, payload: { file_id: FILE.id, filename: "a lie the browser told.exe" }, }); expect(res.statusCode).toBe(201); expect(lastEvent(app)).toMatchObject({ event_type: "TICKET_FILE_ATTACHED", payload: { file_id: FILE.id, filename: "report.pdf", size: 1024, mime_type: "application/pdf", }, }); });
it("refuses a file that is not on the ticket, and says nothing", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/files`, headers: AS_IGOR, payload: { file_id: "someone-elses" }, }); expect(res.statusCode).toBe(422); expect(app.events).toHaveLength(1); });
it("refuses an empty comment, and a comment on a ticket that is not there", async () => { const app = await testApp(); const ticket = await newTicket(app); const empty = await app.inject({ method: "POST", url: `/tickets/${ticket.id}/comments`, headers: AS_IGOR, payload: { text: " " }, }); const missing = await app.inject({ method: "POST", url: "/tickets/0192f7a0-0000-7000-8000-000000000000/comments", headers: AS_IGOR, payload: { text: "hello?" }, }); expect([empty.statusCode, missing.statusCode]).toEqual([422, 404]); expect(app.events).toHaveLength(1); });});
describe("a card dragged on the board (POST /udc/mutate)", () => { const drag = (app: App, id: string, row: Record<string, unknown>, user: string | null = "ana") => app.inject({ method: "POST", url: "/udc/mutate", headers: user ? { "x-user-id": user } : {}, payload: { collection: "tickets", op: "update", id, row }, });
it("to another column: the same event as the status route", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await drag(app, ticket.id, { status: "in_progress", order: 50 }); expect(res.json().kind).toBe("udc.mutate.ok"); expect(lastEvent(app)).toMatchObject({ event_type: "TICKET_STATUS_CHANGED", instance_id: ticket.id, actor_id: "ana", payload: { status: "in_progress", previous: "new" }, }); });
it("inside its column: no event, it is only an order", async () => { const app = await testApp(); const ticket = await newTicket(app); await drag(app, ticket.id, { order: 50 }); expect(app.events).toHaveLength(1); });
it("by nobody: refused and not saved", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await drag(app, ticket.id, { status: "done", order: 50 }, null); expect(res.json().kind).toBe("udc.mutate.err"); const stored = await app.inject({ method: "GET", url: `/tickets/${ticket.id}` }); expect(stored.json().status).toBe("new"); expect(app.events).toHaveLength(1); });
it("a write that fails: no event", async () => { const app = await testApp(); const ticket = await newTicket(app); const res = await drag(app, ticket.id, { status: "lost", order: 50 }); expect(res.json().kind).toBe("udc.mutate.err"); expect(app.events).toHaveLength(1); });});Check it
Section titled “Check it”pnpm installpnpm test Test Files 2 passed (2) Tests 23 passed (23)make setupcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echoTemplates…Restarting with the keys…Ready: http://localhost:8080{"ok":true}Open a ticket, comment on it as ana, and move it:
curl -s -X POST localhost:8080/tickets \ -H 'x-user-id: igor' -H 'content-type: application/json' \ -d '{"title":"Printer on fire"}' > /tmp/ticket.jsonID=$(sed -n 's/.*"id":"\([^"]*\)".*/\1/p' /tmp/ticket.json)
curl -s -X POST "localhost:8080/tickets/$ID/comments" \ -H 'x-user-id: ana' -H 'content-type: application/json' \ -d '{"text":"On my way"}'; echocurl -s -X PATCH "localhost:8080/tickets/$ID/status" \ -H 'x-user-id: ana' -H 'content-type: application/json' \ -d '{"status":"in_progress"}' > /dev/null{"ok":true}Now read the ticket’s history back from memento, in both languages. memento has no port of its own yet, so the request is made from inside its container; step 5 opens the way for the browser.
. ./.envfor locale in en sr; do docker compose exec -T memento node -e " fetch('http://localhost:3000/memento/entities/tickets/$ID/events?locale=$locale', { headers: { authorization: 'Bearer $MEMENTO_BROWSER_KEY' }, }) .then((answer) => answer.json()) .then(({ data }) => data.forEach((event) => console.log(event.rendered)));"doneana moved the ticket: new → in_progressana commented: "On my way"igor opened the ticket "Printer on fire"ana menja status tiketa: new → in_progressana komentariše: „On my way"igor otvara tiket „Printer on fire"You should see the same three events twice, newest first, once in each language. Nothing in the desk’s database records a comment, yet it is there.
Step 5: the UI
Section titled “Step 5: the UI”Three pieces do the work in the browser, and all three are components from the libraries:
| component | talks to | |
|---|---|---|
| the board | <UdcDataView collection="tickets"> with @jsudc/react/kanban: search, columns, drag and drop |
the backend’s /udc/* |
| the files | <VolaFileBrowser> and <VolaUploadButton> from @vol-a/react, on the instance tickets/<id> |
vola, directly, with X-User-Id |
| the feed | useMementoEvents from @memento/react |
memento, directly |
One origin
Section titled “One origin”The backend now passes /vola and /memento to the two services, HTTP and WebSocket, so the browser sees a single origin and neither service needs a port. GET /config gives the page its two keys, and the backend serves the built frontend.
import { connect } from "node:net";import httpProxy from "@fastify/http-proxy";import type { FastifyInstance } from "fastify";
/** Where a path goes: `/vola/…` to vola, `/memento/…` to memento. */export type Upstreams = Record<string, string>;
/** * The browser sees one origin: memento sends no CORS headers, and this way neither service needs * a port of its own. HTTP goes through @fastify/http-proxy; a WebSocket is replayed byte for byte, * because both services read the API key from the subprotocol list the browser offered. */export async function proxyServices(app: FastifyInstance, upstreams: Upstreams) { for (const [prefix, upstream] of Object.entries(upstreams)) { await app.register(httpProxy, { upstream, prefix, rewritePrefix: prefix }); }
app.server.on("upgrade", (request, socket, head) => { const prefix = Object.keys(upstreams).find((p) => request.url?.startsWith(`${p}/`)); if (!prefix) return socket.destroy(); const { hostname, port } = new URL(String(upstreams[prefix])); const upstream = connect(Number(port), hostname, () => { const headers = request.rawHeaders .flatMap((value, i, all) => (i % 2 ? [] : [`${value}: ${all[i + 1]}`])) .join("\r\n"); upstream.write(`GET ${request.url} HTTP/1.1\r\n${headers}\r\n\r\n`); upstream.write(head); socket.pipe(upstream).pipe(socket); }); upstream.on("error", () => socket.destroy()); socket.on("error", () => upstream.destroy()); });}--- a/src/server/app.ts+++ b/src/server/app.ts@@ -1,7 +1,11 @@+import { existsSync } from "node:fs";+import fastifyStatic from "@fastify/static"; import { type CollectionRegistry, createDispatcher, udcPlugin } from "@jsudc/server"; import Fastify, { type FastifyServerOptions } from "fastify";+import { USERS } from "../shared/desk.ts"; import { emitOnDrag } from "./drag.ts"; import type { Emit } from "./memento.ts";+import { proxyServices, type Upstreams } from "./proxy.ts"; import { type FileLookup, ticketRoutes } from "./tickets.ts";
export interface AppOptions {@@ -10,11 +14,18 @@ export interface AppOptions { emit: Emit; /** Asks vola about one file. */ lookupFile: FileLookup;+ /** The keys the browser works with. There is no login: anybody who opens the page gets them. */+ browserKeys: { memento: string; vola: string };+ /** vola and memento, for the browser. */+ upstreams?: Upstreams;+ /** The built frontend, served when it is there. */+ webRoot?: string; logger?: FastifyServerOptions["logger"]; }
/** The whole backend, with everything it talks to passed in: that is what the tests replace. */-export async function buildApp({ registry, emit, lookupFile, logger = false }: AppOptions) {+export async function buildApp(options: AppOptions) {+ const { registry, emit, lookupFile, browserKeys, upstreams, webRoot, logger = false } = options; const app = Fastify({ logger }); const tickets = registry.get("tickets").source;
@@ -30,5 +41,21 @@ export async function buildApp({ registry, emit, lookupFile, logger = false }: A }); await app.register(ticketRoutes, { tickets, emit, lookupFile });
+ // What the page needs to know to start.+ app.get("/config", async (_request, reply) => {+ if (!browserKeys.memento || !browserKeys.vola) {+ return reply.code(503).send({ error: "no keys yet: run `make setup`" });+ }+ return { users: USERS, memento_key: browserKeys.memento, vola_key: browserKeys.vola };+ });++ if (upstreams) await proxyServices(app, upstreams);++ if (webRoot && existsSync(webRoot)) {+ await app.register(fastifyStatic, { root: webRoot });+ // A page of the frontend (/t/<id>) is index.html: the router in the browser takes it from there.+ app.setNotFoundHandler((_request, reply) => reply.sendFile("index.html"));+ }+ return app; }--- a/src/server/main.ts+++ b/src/server/main.ts@@ -27,19 +27,21 @@ const registry = loadRegistry(COLLECTIONS, (collection, reg) => makeSource(collection, { db, registry: reg }), );
-const vola = new VolaClient({- baseUrl: process.env.VOLA_URL ?? "http://localhost:8300/vola",- apiKey: process.env.VOLA_SERVER_KEY ?? "",-});+const VOLA_URL = process.env.VOLA_URL ?? "http://localhost:8300/vola";+const MEMENTO_URL = process.env.MEMENTO_URL ?? "http://localhost:3000/memento";++const vola = new VolaClient({ baseUrl: VOLA_URL, apiKey: process.env.VOLA_SERVER_KEY ?? "" });
const app = await buildApp({ registry, logger: true,- emit: mementoEmitter(- process.env.MEMENTO_URL ?? "http://localhost:3000/memento",- process.env.MEMENTO_SERVER_KEY ?? "",- console,- ),+ emit: mementoEmitter(MEMENTO_URL, process.env.MEMENTO_SERVER_KEY ?? "", console), lookupFile: (ticketId, fileId) => vola.files.info("tickets", ticketId, fileId),+ browserKeys: {+ memento: process.env.MEMENTO_BROWSER_KEY ?? "",+ vola: process.env.VOLA_BROWSER_KEY ?? "",+ },+ upstreams: { "/vola": new URL(VOLA_URL).origin, "/memento": new URL(MEMENTO_URL).origin },+ webRoot: new URL("../../dist", import.meta.url).pathname, }); await app.listen({ host: "0.0.0.0", port: Number(process.env.PORT ?? 8080) });The image now builds the frontend too, and the project gets its dependencies and the Vite setup:
--- a/Dockerfile+++ b/Dockerfile@@ -5,6 +5,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY vendor ./vendor RUN pnpm install --frozen-lockfile COPY . .+RUN pnpm build USER node # Node 24 runs TypeScript as it is: there is no build step for the server. CMD ["node", "src/server/main.ts"]--- a/package.json+++ b/package.json@@ -12,25 +12,46 @@ "scripts": { "dev": "node --watch --env-file-if-exists=.env src/server/main.ts", "start": "node src/server/main.ts",- "typecheck": "tsc --noEmit",+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json", "lint": "biome check .", "format": "biome format --write .",- "test": "vitest run"+ "test": "vitest run",+ "dev:web": "vite",+ "build": "vite build" }, "dependencies": {+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2",+ "@fastify/http-proxy": "^11.6.6",+ "@fastify/static": "^10.1.8", "@jsudc/core": "^0.2.0",+ "@jsudc/react": "^0.2.1", "@jsudc/server": "^0.2.1",+ "@memento/react": "file:vendor/memento-react-1.0.0.tgz",+ "@tanstack/react-query": "^5.105.1",+ "@tanstack/react-table": "^8.21.3", "@vol-a/client": "file:vendor/vol-a-client-1.0.1.tgz",+ "@vol-a/react": "file:vendor/vol-a-react-1.0.1.tgz", "drizzle-orm": "^0.45.4", "fastify": "^5.12.7",+ "lucide-react": "^1.66.0", "pg": "^8.23.1",+ "radix-ui": "^1.8.1",+ "react": "^19.3.1",+ "react-dom": "^19.3.1",+ "react-router": "^7.18.5", "zod": "^4.6.7" }, "devDependencies": { "@biomejs/biome": "^2.6.4", "@types/node": "^24", "@types/pg": "^8.23.1",+ "@types/react": "^19.3.0",+ "@types/react-dom": "^19.3.0",+ "@vitejs/plugin-react": "^6.2.1", "typescript": "^5.9.3",+ "vite": "^8.3.5", "vitest": "^5.0.5" } }<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Ticket desk</title> </head> <body> <div id="root"></div> <script type="module" src="/src/web/main.tsx"></script> </body></html>import react from "@vitejs/plugin-react";import { defineConfig } from "vite";
// `pnpm dev:web`: the backend is on :8080, with vola and memento behind it.const backend = process.env.DESK_BACKEND ?? "http://localhost:8080";const toBackend = { target: backend, ws: true };
export default defineConfig({ plugins: [react()], server: { proxy: { "/config": toBackend, "/tickets": toBackend, "/udc": toBackend, "/vola": toBackend, "/memento": toBackend, }, },});{ "compilerOptions": { "target": "ES2023", "lib": ["ES2023", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "Bundler", "jsx": "react-jsx", "types": ["vite/client"], "strict": true, "noUncheckedIndexedAccess": true, "verbatimModuleSyntax": true, "allowImportingTsExtensions": true, "skipLibCheck": true, "noEmit": true }, "include": ["src/web", "src/shared", "vite.config.ts"]}The page around them
Section titled “The page around them”api.ts is the backend’s routes as functions. session.ts holds who is signed in. App.tsx loads /config, sets up MementoProvider and draws the header with its two picks: who you are, and which language the feed speaks.
import "@jsudc/react/styles.css";import "@memento/react/styles.css";import "@vol-a/react/styles.css";import "./desk.css";import { createRoot } from "react-dom/client";import { App } from "./App.tsx";
createRoot(document.getElementById("root") as HTMLElement).render(<App />);import type { Ticket } from "../shared/desk.ts";
export interface Config { users: string[]; memento_key: string; vola_key: string;}
/** The backend's routes. Every write says who is doing it in `X-User-Id`. */async function request<T>(method: string, path: string, user: string, body?: unknown): Promise<T> { const response = await fetch(path, { method, headers: { "x-user-id": user, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); const answer = await response.json(); if (!response.ok) throw new Error(answer.error ?? `${method} ${path}: ${response.status}`); return answer;}
export const getConfig = () => request<Config>("GET", "/config", "");
export const getTicket = (id: string, user: string) => request<Ticket>("GET", `/tickets/${id}`, user);
export const createTicket = (user: string, title: string, body: string) => request<Ticket>("POST", "/tickets", user, { title, body });
export const setStatus = (id: string, user: string, status: string) => request<Ticket>("PATCH", `/tickets/${id}/status`, user, { status });
export const assign = (id: string, user: string, assignee: string) => request<Ticket>("POST", `/tickets/${id}/assign`, user, { assignee });
export const comment = (id: string, user: string, text: string) => request("POST", `/tickets/${id}/comments`, user, { text });
export const fileAttached = (id: string, user: string, fileId: string) => request("POST", `/tickets/${id}/files`, user, { file_id: fileId });import { createContext, useContext } from "react";import type { Config } from "./api.ts";
export interface Session extends Config { /** Who is "signed in": the pick in the header. Everything they do carries this as X-User-Id. */ user: string; locale: "en" | "sr";}
export const SessionContext = createContext<Session | null>(null);
export function useSession(): Session { const session = useContext(SessionContext); if (!session) throw new Error("useSession outside of <SessionContext>"); return session;}import { MementoProvider } from "@memento/react";import { useEffect, useState } from "react";import { BrowserRouter, Link, Route, Routes } from "react-router";import { type Config, getConfig } from "./api.ts";import { BoardPage } from "./BoardPage.tsx";import { type Session, SessionContext } from "./session.ts";import { TicketPage } from "./TicketPage.tsx";
export function App() { const [config, setConfig] = useState<Config | null>(null); const [error, setError] = useState<string | null>(null); const [user, setUser] = useState("igor"); const [locale, setLocale] = useState<Session["locale"]>("en");
useEffect(() => { getConfig().then(setConfig, (reason) => setError(String(reason.message))); }, []);
if (error) return <p className="notice">{error}</p>; if (!config) return null;
return ( <SessionContext.Provider value={{ ...config, user, locale }}> <MementoProvider baseUrl="/memento" apiKey={config.memento_key} locale={locale}> <BrowserRouter> <header className="topbar"> <Link to="/" className="brand"> Ticket desk </Link> <label> Signed in as{" "} <select value={user} onChange={(e) => setUser(e.target.value)}> {config.users.map((name) => ( <option key={name}>{name}</option> ))} </select> </label> <label> Language{" "} <select value={locale} onChange={(e) => setLocale(e.target.value as Session["locale"])} > <option value="en">English</option> <option value="sr">Srpski</option> </select> </label> </header> <Routes> <Route path="/" element={<BoardPage />} /> <Route path="/t/:id" element={<TicketPage />} /> </Routes> </BrowserRouter> </MementoProvider> </SessionContext.Provider> );}The board
Section titled “The board”The whole board is one component: it asks the backend what the tickets collection is, and draws it. A drag writes through udc/mutate with X-User-Id, and step 4’s hooks turn it into an event.
import { UdcClient } from "@jsudc/core/client";import { createRendererRegistry, createUdcQueryClient, UdcDataView, UdcI18nProvider, UdcProvider,} from "@jsudc/react";import { kanbanRenderer } from "@jsudc/react/kanban";import { Toaster, TooltipProvider } from "@jsudc/react/ui";import { QueryClientProvider } from "@tanstack/react-query";import { type MouseEvent, useMemo } from "react";import { useNavigate } from "react-router";import { useSession } from "./session.ts";
const renderers = createRendererRegistry(kanbanRenderer);const queryClient = createUdcQueryClient();
/** Lists read again after a new ticket, so it shows up without a reload. */export const refreshBoard = () => queryClient.invalidateQueries();
/** * The whole board is this one component of `@jsudc/react`: it asks the backend what the `tickets` * collection is (`collections/tickets/view.yaml`) and draws it. A drag writes through `udc/mutate`, * with `X-User-Id`, and the backend turns it into an event (src/server/drag.ts). */export function Board() { const { user, locale } = useSession(); const navigate = useNavigate(); const client = useMemo( () => new UdcClient({ httpUrl: "", headers: { "X-User-Id": user } }), [user], );
// A click on a card opens the ticket's page instead of the board's read-only dialog. const openCard = (event: MouseEvent) => { const card = (event.target as Element).closest("[data-card-id]"); if (!card) return; event.stopPropagation(); navigate(`/t/${card.getAttribute("data-card-id")}`); };
return ( <UdcProvider client={client} renderers={renderers}> <QueryClientProvider client={queryClient}> <UdcI18nProvider locale={locale}> <TooltipProvider> <Toaster> <div className="board" onClickCapture={openCard}> <UdcDataView collection="tickets" /> </div> </Toaster> </TooltipProvider> </UdcI18nProvider> </QueryClientProvider> </UdcProvider> );}import { type FormEvent, useState } from "react";import { createTicket } from "./api.ts";import { Board, refreshBoard } from "./Board.tsx";import { useSession } from "./session.ts";
export function BoardPage() { const { user } = useSession(); const [title, setTitle] = useState("");
const submit = async (event: FormEvent) => { event.preventDefault(); await createTicket(user, title, ""); setTitle(""); await refreshBoard(); };
return ( <main className="board-page"> <form className="row" onSubmit={submit}> <input aria-label="Title of the new ticket" placeholder="What is wrong?" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit" disabled={!title.trim()}> New ticket </button> </form> <Board /> </main> );}The files
Section titled “The files”The browser talks to vola itself, on the instance tickets/<id>, with the signed-in user in userId. Thumbnails, folders, download, delete and Share in a file’s menu all come with VolaFileBrowser. The upload goes through VolaUploadButton because its onUploaded is how the backend hears about the file, and that is what records TICKET_FILE_ATTACHED.
import { VolaClient } from "@vol-a/client";import { VolaFileBrowser, VolaProvider, VolaUploadButton } from "@vol-a/react";import { useMemo } from "react";import { fileAttached } from "./api.ts";import { useSession } from "./session.ts";
/** * The files of one ticket: the instance `tickets/<id>` in vola. The browser talks to vola itself, * with `X-User-Id`. After an upload it tells the backend, which records TICKET_FILE_ATTACHED. * Sharing a file with somebody outside is the browser's Share action (`VolaShareDialog`). */export function Files({ ticketId, onAttached }: { ticketId: string; onAttached: () => void }) { const { user, vola_key, locale } = useSession(); const client = useMemo( () => new VolaClient({ baseUrl: "/vola", apiKey: vola_key, userId: user }), [vola_key, user], );
return ( // `key`: another user is another principal, so everything below starts over. <VolaProvider key={user} client={client} locale={locale} lockAfterMs={0}> <VolaUploadButton instanceType="tickets" instanceId={ticketId} onUploaded={({ fileId }) => { fileAttached(ticketId, user, fileId).then(onAttached); }} /> <VolaFileBrowser instanceType="tickets" instanceId={ticketId} upload={false} keyringStatus={false} columns={["thumb_url", "filename", "size", "created_at"]} actions={["download", "share", "delete"]} /> </VolaProvider> );}The feed
Section titled “The feed”For now the feed is read once, and read again after each of your own actions.
import type { MementoEvent } from "@memento/react";import { formatTime } from "@memento/react";import type { ReactNode } from "react";
/** The feed: memento's sentence for each event, newest first. */export function Activity({ events, status }: { events: MementoEvent[]; status?: ReactNode }) { return ( <section className="activity" aria-label="Activity"> <h2>Activity {status}</h2> <ol> {events.map((event) => ( <li key={event.id}> <time dateTime={event.occurred_at}>{formatTime(event.occurred_at)}</time> <span data-event-type={event.event_type}>{event.rendered}</span> </li> ))} </ol> </section> );}import { useMementoEvents } from "@memento/react";import { type FormEvent, useEffect, useState } from "react";import { useParams } from "react-router";import { STATUSES, type Ticket } from "../shared/desk.ts";import { Activity } from "./Activity.tsx";import { assign, comment, getTicket, setStatus } from "./api.ts";import { Files } from "./Files.tsx";import { useSession } from "./session.ts";
export function TicketPage() { const id = String(useParams().id); const { user, users } = useSession(); const [ticket, setTicket] = useState<Ticket | null>(null); const [text, setText] = useState(""); const feed = useMementoEvents({ instance_type: "tickets", instance_id: id }, { live: false });
useEffect(() => { getTicket(id, user).then(setTicket); }, [id, user]);
const submitComment = async (event: FormEvent) => { event.preventDefault(); await comment(id, user, text); setText(""); feed.reload(); };
if (!ticket) return null;
return ( <main className="ticket-page"> <div className="ticket-main"> <h1>{ticket.title}</h1> <div className="row"> <label> Status{" "} <select value={ticket.status} onChange={async (e) => { setTicket(await setStatus(id, user, e.target.value)); feed.reload(); }} > {STATUSES.map((status) => ( <option key={status}>{status}</option> ))} </select> </label> <label> Assignee{" "} <select value={ticket.assignee ?? ""} onChange={async (e) => { setTicket(await assign(id, user, e.target.value)); feed.reload(); }} > <option value="" disabled> nobody </option> {users.map((name) => ( <option key={name}>{name}</option> ))} </select> </label> </div> <form className="row" onSubmit={submitComment}> <input aria-label="Comment" placeholder="Write a comment" value={text} onChange={(e) => setText(e.target.value)} /> <button type="submit" disabled={!text.trim()}> Comment </button> </form> <Files ticketId={id} onAttached={feed.reload} /> </div> <Activity events={feed.events} /> </main> );}Show src/web/desk.css
/* The look comes from @jsudc/react's tokens; this is only the layout around its components. */html,body,#root { height: 100%; margin: 0;}
#root { display: flex; flex-direction: column; font-family: "Inter Variable", system-ui, sans-serif; font-size: 14px; color: var(--foreground); background: var(--background);}
.topbar { display: flex; align-items: center; gap: 20px; padding: 10px 20px; border-bottom: 1px solid var(--border);}
.brand { margin-right: auto; font-size: 16px; font-weight: 600; color: inherit; text-decoration: none;}
.notice { padding: 40px; text-align: center;}
.row { display: flex; align-items: center; gap: 12px;}
.topbar select,.row input,.row select,.row button { font: inherit; padding: 6px 10px; color: inherit; background: var(--background); border: 1px solid var(--border); border-radius: 6px;}
.row input { flex: 1; min-width: 0;}
.row button { cursor: pointer;}
.row button:disabled { cursor: default; opacity: 0.5;}
.board-page { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); gap: 12px 20px; padding: 16px 20px;}
.board { grid-column: 1; min-height: 0; display: flex; flex-direction: column;}
.board-page > .row { grid-column: 1;}
.board [data-card-id] { cursor: pointer;}
.ticket-page { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 20px; padding: 16px 20px;}
.ticket-main { min-height: 0; display: flex; flex-direction: column; gap: 12px; overflow: auto;}
.ticket-main h1 { margin: 0; font-size: 20px; font-weight: 600;}
.activity { min-height: 0; overflow: auto; padding: 12px 16px; border: 1px solid var(--border); border-radius: 8px;}
.activity h2 { display: flex; justify-content: space-between; align-items: center; margin: 0 0 8px; font-size: 14px; font-weight: 600;}
.activity ol { margin: 0; padding: 0; list-style: none;}
.activity li { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 10px; padding: 7px 0; border-top: 1px solid var(--border);}
.activity time { color: var(--muted-foreground); font-variant-numeric: tabular-nums;}Show the changes to the tests
--- a/test/helpers.ts+++ b/test/helpers.ts@@ -12,7 +12,7 @@ export const FILE = { };
/** The backend with the tickets in memory and a list for memento: nothing to start. */-export async function testApp() {+export async function testApp(browserKeys = { memento: "mk_browser", vola: "vola_browser" }) { const events: DeskEvent[] = []; const registry = loadRegistry(COLLECTIONS, (asset, reg) => asset.name === "tickets"@@ -28,6 +28,7 @@ export async function testApp() { if (fileId !== FILE.id) throw new Error("not on this ticket"); return FILE; },+ browserKeys, }); return Object.assign(app, { events }); }--- a/test/tickets.test.ts+++ b/test/tickets.test.ts@@ -137,3 +137,22 @@ describe("POST /tickets/:id/assign", () => { expect(res.statusCode).toBe(422); }); });++describe("GET /config", () => {+ it("gives the page its users and its two keys", async () => {+ const app = await testApp();+ const res = await app.inject({ method: "GET", url: "/config" });+ expect(res.json()).toEqual({+ users: ["igor", "ana", "marko"],+ memento_key: "mk_browser",+ vola_key: "vola_browser",+ });+ });++ it("says what to do before `make setup`", async () => {+ const app = await testApp({ memento: "", vola: "" });+ const res = await app.inject({ method: "GET", url: "/config" });+ expect(res.statusCode).toBe(503);+ expect(res.json().error).toContain("make setup");+ });+});Check it
Section titled “Check it”pnpm installpnpm test Test Files 2 passed (2) Tests 25 passed (25)docker compose up -d --buildcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echocurl -s localhost:8080/ | grep -o '<title>.*</title>'curl -s -o /dev/null -w '/config %{http_code}\n' localhost:8080/config<title>Ticket desk</title>/config 200Open http://localhost:8080. You see the board with its three columns, and on it the tickets you made with curl in the earlier steps. On a clean stack (make clean, then make setup) it is empty:

Type a title and press New ticket, then click the card. On the ticket’s page, change its status, leave a comment, and upload a file with the button above the file list. Each action appears in the feed on the right, as a sentence. The Language pick in the header turns the same events into Serbian.
For development with reloads, pnpm dev and pnpm dev:web run the two halves outside Docker.
Step 6: live
Section titled “Step 6: live”Nothing on the page moves yet unless you moved it. This step fixes that without adding a server of any kind, because memento already streams every event over its WebSocket, /memento/ws.
useMementoEvents loads the newest events and then gets each new one as it is stored. The feed’s onEvent tells the board and the ticket page to read again, so memento’s stream becomes the one signal the whole page follows, and everything added for reloading in step 5 goes away.
--- a/src/web/Activity.tsx+++ b/src/web/Activity.tsx@@ -1,15 +1,36 @@-import type { MementoEvent } from "@memento/react";-import { formatTime } from "@memento/react";-import type { ReactNode } from "react";+import { formatTime, type MementoEvent, StatusIndicator, useMementoEvents } from "@memento/react";+import { useEffect } from "react";+import { ticketEvents } from "./feed.ts";++/**+ * The feed: memento's sentence for each event, newest first, and every new event as it is stored.+ * One subscription to the whole desk: with `ticketId` it shows that ticket's part of it. A write+ * by anybody, in any tab, arrives here, so nothing has to reload after an action any more.+ */+export function Activity({+ ticketId,+ onEvent,+}: {+ ticketId?: string;+ /** Called with each newest event: what else on the page has to catch up. */+ onEvent?: (event: MementoEvent) => void;+}) {+ const { events, status, liveIds } = useMementoEvents({}, { limit: 200 });+ const shown = ticketId ? ticketEvents(events, ticketId) : events;+ const newest = events[0];++ useEffect(() => {+ if (newest) onEvent?.(newest);+ }, [newest, onEvent]);
-/** The feed: memento's sentence for each event, newest first. */-export function Activity({ events, status }: { events: MementoEvent[]; status?: ReactNode }) { return (- <section className="activity" aria-label="Activity">- <h2>Activity {status}</h2>+ <section className="activity memento" aria-label="Activity">+ <h2>+ Activity <StatusIndicator status={status} />+ </h2> <ol>- {events.map((event) => (- <li key={event.id}>+ {shown.map((event) => (+ <li key={event.id} className={liveIds.has(event.id) ? "fresh" : undefined}> <time dateTime={event.occurred_at}>{formatTime(event.occurred_at)}</time> <span data-event-type={event.event_type}>{event.rendered}</span> </li>--- a/src/web/BoardPage.tsx+++ b/src/web/BoardPage.tsx@@ -1,4 +1,5 @@ import { type FormEvent, useState } from "react";+import { Activity } from "./Activity.tsx"; import { createTicket } from "./api.ts"; import { Board, refreshBoard } from "./Board.tsx"; import { useSession } from "./session.ts";@@ -11,7 +12,6 @@ export function BoardPage() { event.preventDefault(); await createTicket(user, title, ""); setTitle("");- await refreshBoard(); };
return (@@ -28,6 +28,7 @@ export function BoardPage() { </button> </form> <Board />+ <Activity onEvent={refreshBoard} /> </main> ); }--- a/src/web/Board.tsx+++ b/src/web/Board.tsx@@ -16,7 +16,7 @@ import { useSession } from "./session.ts"; const renderers = createRendererRegistry(kanbanRenderer); const queryClient = createUdcQueryClient();
-/** Lists read again after a new ticket, so it shows up without a reload. */+/** The feed calls this for every new event: whoever changed a ticket, the board catches up. */ export const refreshBoard = () => queryClient.invalidateQueries();
/**--- a/src/web/Files.tsx+++ b/src/web/Files.tsx@@ -9,7 +9,7 @@ import { useSession } from "./session.ts"; * with `X-User-Id`. After an upload it tells the backend, which records TICKET_FILE_ATTACHED. * Sharing a file with somebody outside is the browser's Share action (`VolaShareDialog`). */-export function Files({ ticketId, onAttached }: { ticketId: string; onAttached: () => void }) {+export function Files({ ticketId }: { ticketId: string }) { const { user, vola_key, locale } = useSession(); const client = useMemo( () => new VolaClient({ baseUrl: "/vola", apiKey: vola_key, userId: user }),@@ -23,7 +23,7 @@ export function Files({ ticketId, onAttached }: { ticketId: string; onAttached: instanceType="tickets" instanceId={ticketId} onUploaded={({ fileId }) => {- fileAttached(ticketId, user, fileId).then(onAttached);+ fileAttached(ticketId, user, fileId); }} /> <VolaFileBrowser--- a/src/web/TicketPage.tsx+++ b/src/web/TicketPage.tsx@@ -1,5 +1,4 @@-import { useMementoEvents } from "@memento/react";-import { type FormEvent, useEffect, useState } from "react";+import { type FormEvent, useCallback, useEffect, useState } from "react"; import { useParams } from "react-router"; import { STATUSES, type Ticket } from "../shared/desk.ts"; import { Activity } from "./Activity.tsx";@@ -12,17 +11,17 @@ export function TicketPage() { const { user, users } = useSession(); const [ticket, setTicket] = useState<Ticket | null>(null); const [text, setText] = useState("");- const feed = useMementoEvents({ instance_type: "tickets", instance_id: id }, { live: false });
- useEffect(() => {+ // Read at the start, and again on every new event: somebody else may have just moved it.+ const reload = useCallback(() => { getTicket(id, user).then(setTicket); }, [id, user]);+ useEffect(reload, [reload]);
const submitComment = async (event: FormEvent) => { event.preventDefault(); await comment(id, user, text); setText("");- feed.reload(); };
if (!ticket) return null;@@ -34,13 +33,7 @@ export function TicketPage() { <div className="row"> <label> Status{" "}- <select- value={ticket.status}- onChange={async (e) => {- setTicket(await setStatus(id, user, e.target.value));- feed.reload();- }}- >+ <select value={ticket.status} onChange={(e) => setStatus(id, user, e.target.value)}> {STATUSES.map((status) => ( <option key={status}>{status}</option> ))}@@ -50,10 +43,7 @@ export function TicketPage() { Assignee{" "} <select value={ticket.assignee ?? ""}- onChange={async (e) => {- setTicket(await assign(id, user, e.target.value));- feed.reload();- }}+ onChange={(e) => assign(id, user, e.target.value)} > <option value="" disabled> nobody@@ -75,9 +65,9 @@ export function TicketPage() { Comment </button> </form>- <Files ticketId={id} onAttached={feed.reload} />+ <Files ticketId={id} /> </div>- <Activity events={feed.events} />+ <Activity ticketId={id} onEvent={reload} /> </main> ); }There is one subscription to the whole desk, and feed.ts picks a ticket’s part of it. A filter on tickets/<id> alone would be shorter, and step 7 shows why it would miss things.
interface FeedEvent { event_type: string; instance_type: string; instance_id: string; payload: Record<string, unknown>;}
/** * The events of one ticket, out of the events of the whole desk. * * Our own events are on the instance `tickets/<id>`. vola's are not: it knows nothing about * tickets, so a deleted file is on `vola_file/<file id>` and a new share on `vola_share/<share * id>`. They still lead back to the ticket: a file's event says which instance the file is in, and * a share's says which file it is for, and TICKET_FILE_ATTACHED says which ticket has that file. */export function ticketEvents<E extends FeedEvent>(events: E[], ticketId: string): E[] { const files = new Set( events .filter((e) => e.event_type === "TICKET_FILE_ATTACHED" && e.instance_id === ticketId) .map((e) => e.payload.file_id), ); return events.filter((e) => { if (e.instance_type === "tickets") return e.instance_id === ticketId; if (e.payload.instance_type === "tickets") return e.payload.instance_id === ticketId; return files.has(e.payload.file_id); });}Show the stylesheet changes and the test
--- a/src/web/desk.css+++ b/src/web/desk.css@@ -72,7 +72,7 @@ body, flex: 1; min-height: 0; display: grid;- grid-template-columns: minmax(0, 1fr);+ grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: auto minmax(0, 1fr); gap: 12px 20px; padding: 16px 20px;@@ -120,10 +120,16 @@ body, min-height: 0; overflow: auto; padding: 12px 16px;+ background: transparent; border: 1px solid var(--border); border-radius: 8px; }
+.board-page .activity {+ grid-column: 2;+ grid-row: 1 / span 2;+}+ .activity h2 { display: flex; justify-content: space-between;@@ -151,3 +157,19 @@ body, color: var(--muted-foreground); font-variant-numeric: tabular-nums; }++.activity li.fresh {+ animation: fresh 1.5s ease-out;+}++@keyframes fresh {+ from {+ background: var(--sem-warning-bg);+ }+}++@media (prefers-reduced-motion: reduce) {+ .activity li.fresh {+ animation: none;+ }+}import { describe, expect, it } from "vitest";import { ticketEvents } from "../src/web/feed.ts";
const created = { event_type: "TICKET_CREATED", instance_type: "tickets", instance_id: "t-1", payload: { title: "Printer on fire" },};const attached = { event_type: "TICKET_FILE_ATTACHED", instance_type: "tickets", instance_id: "t-1", payload: { file_id: "f-1", filename: "report.pdf" },};const otherTicket = { ...created, instance_id: "t-2" };const otherAttached = { ...attached, instance_id: "t-2", payload: { file_id: "f-2" } };
describe("ticketEvents", () => { it("keeps the ticket's own events and leaves another ticket's out", () => { expect(ticketEvents([created, otherTicket], "t-1")).toEqual([created]); });
it("keeps vola's event about a file in the ticket's instance", () => { const deleted = { event_type: "VOLA_FILE_DELETED", instance_type: "vola_file", instance_id: "f-1", payload: { file_id: "f-1", instance_type: "tickets", instance_id: "t-1" }, }; const elsewhere = { ...deleted, payload: { file_id: "f-2", instance_type: "tickets", instance_id: "t-2" }, }; expect(ticketEvents([deleted, elsewhere], "t-1")).toEqual([deleted]); });
it("keeps vola's event about a share of a file attached to the ticket", () => { const shared = { event_type: "VOLA_SHARE_CREATED", instance_type: "vola_share", instance_id: "s-1", payload: { share_id: "s-1", file_id: "f-1" }, }; const sharedElsewhere = { ...shared, payload: { share_id: "s-2", file_id: "f-2" } }; const events = [shared, sharedElsewhere, attached, otherAttached]; expect(ticketEvents(events, "t-1")).toEqual([shared, attached]); });
it("leaves out what has nothing to do with any ticket", () => { const key = { event_type: "VOLA_KEY_CREATED", instance_type: "vola_key", instance_id: "k-1", payload: { key_id: "k-1" }, }; expect(ticketEvents([key], "t-1")).toEqual([]); });});The files need no change here. VolaFileBrowser has been live since step 5: it opens its own WebSocket to vola’s /udc/subscribe, so a file another tab uploads or deletes appears in the list by itself. So the page now follows two streams, each from the service that owns the data.
Check it
Section titled “Check it”pnpm test Test Files 3 passed (3) Tests 29 passed (29)docker compose up -d --buildcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echoOpen a ticket and put its page in your browser:
curl -s -X POST localhost:8080/tickets \ -H 'x-user-id: igor' -H 'content-type: application/json' \ -d '{"title":"Printer on fire"}' > /tmp/ticket.jsonID=$(sed -n 's/.*"id":"\([^"]*\)".*/\1/p' /tmp/ticket.json)echo "http://localhost:8080/t/$ID"http://localhost:8080/t/64b1e676-c53c-4393-9677-c4d61dd9200bWith that page open, comment from the terminal, as somebody else. Do not touch the page.
curl -s -X POST "localhost:8080/tickets/$ID/comments" \ -H 'x-user-id: ana' -H 'content-type: application/json' \ -d '{"text":"On my way"}'; echo{"ok":true}The sentence appears at the top of the feed by itself. Live next to the heading says memento’s stream is connected, and the Live above the files is vola’s:

The same works between two tabs: sign in as somebody else in one, and act in the other.
Step 7: the audit, without code
Section titled “Step 7: the audit, without code”So far the feed shows what the program says. A file deleted through vola is not in it, because the program never hears of it. vola can report that itself. Its destructive and security-relevant operations can go straight to memento, and switching that on takes two environment variables and one more key.
--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -5,7 +5,7 @@ name: ticket-desk
services: vola:- image: ghcr.io/digital-cube/jsvola:latest+ image: ${VOLA_IMAGE:-ghcr.io/digital-cube/jsvola:latest} restart: unless-stopped depends_on: postgres: { condition: service_healthy }@@ -19,6 +19,11 @@ services: VOLA_OCR_ENABLED: "0" # Share links are built on this origin, the one the browser knows. VOLA_PUBLIC_URL: http://localhost:${DESK_PORT:-8080}+ # The whole integration with memento: vola pushes its own events, and no code of ours runs.+ # Both or neither, so there is no URL until `make setup` has made the key. With Redis the+ # worker does the pushing: it reads this same block.+ VOLA_MEMENTO_URL: ${MEMENTO_AUDIT_KEY:+http://memento:3000/memento}+ VOLA_MEMENTO_API_KEY: ${MEMENTO_AUDIT_KEY:-} volumes: - vola-data:/data healthcheck:@@ -30,7 +35,7 @@ services:
# The same image: makes the thumbnails, on the same /data. vola-worker:- image: ghcr.io/digital-cube/jsvola:latest+ image: ${VOLA_IMAGE:-ghcr.io/digital-cube/jsvola:latest} command: ["node", "dist/worker.js"] restart: unless-stopped depends_on:@@ -42,7 +47,7 @@ services: disable: true
memento:- image: ghcr.io/digital-cube/jsmemento:latest+ image: ${MEMENTO_IMAGE:-ghcr.io/digital-cube/jsmemento:latest} restart: unless-stopped depends_on: postgres: { condition: service_healthy }--- a/scripts/setup.sh+++ b/scripts/setup.sh@@ -32,6 +32,9 @@ missing MEMENTO_SERVER_KEY \ && memento create-key --tenant desk --name desk-server --scopes write | save_key MEMENTO_SERVER_KEY missing VOLA_SERVER_KEY \ && vola create-key --tenant desk --name desk-server --scopes files:read | save_key VOLA_SERVER_KEY+# vola pushes its own events to memento with this one: see VOLA_MEMENTO_* in docker-compose.yaml.+missing MEMENTO_AUDIT_KEY \+ && memento create-key --tenant desk --name vola-audit --scopes write | save_key MEMENTO_AUDIT_KEY # The browser reads the feed, and works with files directly on vola. missing MEMENTO_BROWSER_KEY \ && memento create-key --tenant desk --name desk-browser --scopes read | save_key MEMENTO_BROWSER_KEY--- a/.env.example+++ b/.env.example@@ -1,2 +1,5 @@ # `make setup` writes the keys below. Only DESK_PORT is yours to change. DESK_PORT=8080+# The two services' images, when you want other ones than the latest release:+# VOLA_IMAGE=ghcr.io/digital-cube/jsvola:edge+# MEMENTO_IMAGE=ghcr.io/digital-cube/jsmemento:latestNo line of the program changes. The new events only need sentences, so they get templates like the others:
{{actor_id}} made a share link{{#if payload.has_password}} with a password{{/if}}{{actor_id}} pravi link za deljenje{{#if payload.has_password}} sa lozinkom{{/if}}{{actor_id}} revoked a share link, after {{payload.download_count}} download(s){{actor_id}} povlači link za deljenje, preuzimanja: {{payload.download_count}}{{actor_id}} deleted {{payload.filename}}{{actor_id}} briše fajl {{payload.filename}}This is what feed.ts from step 6 was for. vola puts these events on its own instances, vola_file/<id> and vola_share/<id>, because it knows nothing about tickets. The payload is what leads them back to the ticket: a file’s event says which instance the file is in, and a share’s event names the file.
The whole flow as a test
Section titled “The whole flow as a test”The rest of this step is one test that walks the main flow against the running stack, through the desk’s own port, as the browser’s requests do.
--- a/Makefile+++ b/Makefile@@ -1,4 +1,4 @@-.PHONY: up setup down clean+.PHONY: up setup e2e down clean
up: docker compose up -d --build@@ -7,6 +7,11 @@ up: setup: sh scripts/setup.sh
+# The main flow, against the stack that is up.+e2e:+ pnpm install --frozen-lockfile+ set -a; . ./.env; set +a; pnpm test:e2e+ down: docker compose down--- a/package.json+++ b/package.json@@ -17,7 +17,8 @@ "format": "biome format --write .", "test": "vitest run", "dev:web": "vite",- "build": "vite build"+ "build": "vite build",+ "test:e2e": "vitest run --config vitest.e2e.config.ts" }, "dependencies": { "@dnd-kit/core": "^6.3.1",--- a/tsconfig.json+++ b/tsconfig.json@@ -14,5 +14,13 @@ "skipLibCheck": true, "noEmit": true },- "include": ["src/server", "src/shared", "test", "vitest.config.ts"]+ "include": [+ "src/server",+ "src/shared",+ "src/web/feed.ts",+ "test",+ "e2e",+ "vitest.config.ts",+ "vitest.e2e.config.ts"+ ] }import { defineConfig } from "vitest/config";
export default defineConfig({ test: { include: ["e2e/**/*.test.ts"] },});Show e2e/smoke.test.ts
/** * The main flow against the running stack: `docker compose up -d --build`, `make setup`, then * `pnpm test:e2e`. Everything goes through the desk's own port, as the browser's requests do. */import { VolaClient } from "@vol-a/client";import { beforeAll, describe, expect, it } from "vitest";import { ticketEvents } from "../src/web/feed.ts";
const DESK = process.env.DESK_URL ?? `http://localhost:${process.env.DESK_PORT ?? 8080}`;
interface MementoEvent { id: string; event_type: string; instance_type: string; instance_id: string; actor_id: string; rendered: string; payload: Record<string, unknown>;}
interface Config { memento_key: string; vola_key: string;}
interface Ticket { id: string;}
interface RowList { payload: { rows: { __meta: { id: string } }[] };}
let mementoKey: string;let vola: VolaClient;
async function call<T>(method: string, path: string, user: string | null, body?: unknown) { const response = await fetch(`${DESK}${path}`, { method, headers: { ...(user ? { "x-user-id": user } : {}), ...(body === undefined ? {} : { "content-type": "application/json" }), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); expect(response.status, `${method} ${path}`).toBeLessThan(300); return response.json() as Promise<T>;}
async function desksEvents(locale: string): Promise<MementoEvent[]> { const response = await fetch(`${DESK}/memento/events?limit=200&locale=${locale}`, { headers: { authorization: `Bearer ${mementoKey}` }, }); return ((await response.json()) as { data: MementoEvent[] }).data;}
/** vola's events arrive through its worker, so the last ones take a moment. */async function eventually<T>(read: () => Promise<T>, done: (value: T) => boolean): Promise<T> { for (let tries = 0; ; tries++) { const value = await read(); if (done(value) || tries === 40) return value; await new Promise((resolve) => setTimeout(resolve, 250)); }}
beforeAll(async () => { const config = await call<Config>("GET", "/config", null); mementoKey = config.memento_key; vola = new VolaClient({ baseUrl: `${DESK}/vola`, apiKey: config.vola_key, userId: "ana" });});
describe("the main flow", () => { it("every action, ours and vola's, lands in one feed as a sentence", async () => { const { id } = await call<Ticket>("POST", "/tickets", "igor", { title: "Printer on fire" });
// The stream is open before anything happens, through the desk's WebSocket passage. const heard: MementoEvent[] = []; const stream = new WebSocket( `${DESK.replace(/^http/, "ws")}/memento/ws?instance_type=tickets&instance_id=${id}`, ["memento.v1", `bearer.${mementoKey}`], ); stream.onmessage = (message) => { const { kind, payload } = JSON.parse(String(message.data)); if (kind === "memento.event.new") heard.push(payload); }; await new Promise((resolve, reject) => { stream.onopen = resolve; stream.onerror = reject; });
await call("POST", `/tickets/${id}/comments`, "ana", { text: "On my way" }); await call("POST", `/tickets/${id}/assign`, "igor", { assignee: "ana" }); await call("PATCH", `/tickets/${id}/status`, "ana", { status: "in_progress" }); await new Promise((resolve) => setTimeout(resolve, 1100)); // occurred_at orders the feed
// A card dragged on the board. const dragged = await call<{ kind: string }>("POST", "/udc/mutate", "marko", { collection: "tickets", op: "update", id, row: { status: "done", order: 1 }, }); expect(dragged.kind).toBe("udc.mutate.ok");
// A file, straight to vola, then announced to the backend. const file = await vola.files.upload("tickets", id, Buffer.from("smoke\n"), { filename: "report.txt", contentType: "text/plain", }); await call("POST", `/tickets/${id}/files`, "ana", { file_id: file.id });
// The audit: nothing in this program sends these two. const share = await vola.shares.create({ file_id: file.id, max_downloads: 5 }); const shared = await fetch(new URL(new URL(share.url).pathname, DESK)); expect(shared.status).toBe(200); await vola.files.delete("tickets", id, file.id);
const all = await eventually( () => desksEvents("sr"), (events) => ticketEvents(events, id).some(({ event_type }) => event_type === "VOLA_FILE_DELETED"), ); const feed = ticketEvents(all, id);
expect(feed.map(({ event_type }) => event_type).sort()).toEqual( [ "TICKET_CREATED", "TICKET_COMMENTED", "TICKET_ASSIGNED", "TICKET_STATUS_CHANGED", "TICKET_STATUS_CHANGED", "TICKET_FILE_ATTACHED", "VOLA_SHARE_CREATED", "VOLA_FILE_DELETED", ].sort(), );
const sentence = (type: string) => feed.find((event) => event.event_type === type)?.rendered; expect(sentence("TICKET_COMMENTED")).toBe('ana komentariše: „On my way"'); expect(sentence("TICKET_ASSIGNED")).toBe("igor dodeljuje tiket: ana"); expect(sentence("TICKET_FILE_ATTACHED")).toBe("ana kači fajl report.txt"); expect(sentence("VOLA_SHARE_CREATED")).toBe("ana pravi link za deljenje"); expect(sentence("VOLA_FILE_DELETED")).toBe("ana briše fajl report.txt");
// The dragged card has its user, and the previous column. expect(feed.find(({ actor_id }) => actor_id === "marko")?.payload).toMatchObject({ previous: "in_progress", status: "done", });
// English from the same events. const english = ticketEvents(await desksEvents("en"), id); expect(english.find(({ event_type }) => event_type === "VOLA_FILE_DELETED")?.rendered).toBe( "ana deleted report.txt", );
// And the stream carried the program's events as they happened. const types = heard.map(({ event_type }) => event_type); stream.close(); expect(types).toContain("TICKET_COMMENTED"); expect(types).toContain("TICKET_FILE_ATTACHED"); }, 30_000);
it("the board sees the move", async () => { const ticket = await call<Ticket>("POST", "/tickets", "igor", { title: "On the board" }); await call("PATCH", `/tickets/${ticket.id}/status`, "igor", { status: "done" }); const { payload } = await call<RowList>("POST", "/udc/list", null, { collection: "tickets", filter: { field: "status", op: "eq", value: "done" }, }); expect(payload.rows.map((row) => row.__meta.id)).toContain(ticket.id); });});Check it
Section titled “Check it”make setupcurl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echoTenants…Keys… MEMENTO_AUDIT_KEYTemplates…Restarting with the keys…Ready: http://localhost:8080{"ok":true}make e2e Test Files 1 passed (1) Tests 2 passed (2)docker compose logs vola-worker | grep -c 'memento answered 422'0The test passes, and the worker has nothing refused to report. Now see it yourself. Open a ticket, upload a file, and open that file’s menu: Share then Create link makes VOLA_SHARE_CREATED, and Delete, once you confirm it, makes VOLA_FILE_DELETED. Both appear in the feed next to the program’s own events, with the signed-in user as the actor, because the browser sent X-User-Id to vola.

Finish with everything the program has:
pnpm testpnpm typecheck && pnpm lint Test Files 3 passed (3) Tests 29 passed (29)$ tsc --noEmit && tsc --noEmit -p tsconfig.web.json$ biome check .Checked 44 filesWhat next
Section titled “What next”The program leaves a lot out on purpose. It has no real login: anybody who opens the page gets the browser’s keys, and X-User-Id is taken at its word. If memento is down, an event is lost with a log line, because the change itself is already saved. The feed reads the desk’s newest 200 events and picks a ticket’s part of them, which is plenty here; a large desk would keep a table from file to ticket and query per ticket.
From here:
- Encryption. Files sealed at rest, per file: how it works and the live example.
- A keyring and a PIN. Keys only the user can unlock, with
VolaPinGatefrom@vol-a/react: the encryption reference. - Sharing. Passwords, expiry and download limits on a share link: the live example.
- The Filter DSL. Query memento’s events by field instead of reading the newest ones, with
POST /memento/events/query: memento’s API. - A second tenant. Run
create-tenantandcreate-keyagain, with another slug, in both services. A key sees its own tenant and nothing else. One memento key takes the audit of a whole vola installation, with the vola tenant’s slug inpayload.tenant.
The references:
| vola | memento | |
|---|---|---|
| HTTP API | API | API.md |
| Live | Real-time | STREAMING.md |
| Command line | CLI | CLI.md |
| React | Packages, Get started with React | REACT.md |
| Sentences | TEMPLATES.md |
v1.1.1released built 519e3dc