Skip to content

/tutorials/ticket-desk-sr/

Napravite ticket desk sa volom i mementom

This tutorial in English

Ovaj tutorijal od praznog foldera pravi mali help-desk: kanban tablu sa tiketima, stranicu svakog tiketa sa njegovim fajlovima i feed koji prikazuje sve što se dešava, u trenutku kad se dešava. Program pišete vi; fajlovi i istorija su dva servisa koja pokrećete pored njega.

vola je servis za fajlove koji sami hostujete. Čuva bajtove i njihovu hijerarhiju: otpremanja, sličice, foldere, verzije i linkove za deljenje, a svaki fajl stoji pod nekom instancom vaše aplikacije, recimo tickets/<id>.

memento je dnevnik aktivnosti koji sami hostujete. Aplikacija mu šalje događaje (TICKET_COMMENTED, uradila ana, na tickets/<id>). Memento ih čuva kao trag koji se ne menja, svaki pretvara u rečenicu na jeziku čitaoca, a nove šalje preko WebSocket-a.

Idu zajedno zato što fajl u pravoj aplikaciji ima vlasnika i istoriju. Vola zna šta su bajtovi i gde stoje. Ne zna zašto su tu, i ne treba da zna. Memento zna ko je šta uradio, a ne drži nijedan bajt. U ovom programu svaki servis radi svoju polovinu, a korak 7 ih spaja sa dve promenljive okruženja, bez koda.

Ticket desk, u sedam koraka. Svaki korak je jedan commit u istoriji gotovog programa, a poglavlja ispod prate isti redosled i iste nazive.

korak šta dodaje šta možete posle njega
1 stack GET /health odgovara, a vola i memento rade
2 ključevi desk ima tenanta i API ključeve u oba servisa
3 backend pravljenje, dodela i pomeranje tiketa preko curl-a
4 događaji svaka akcija je događaj, sa rečenicom na engleskom i srpskom
5 UI tabla, fajlovi i feed u browseru
6 live izmena bilo koga se pojavljuje bez ponovnog učitavanja
7 audit, bez koda vola sopstvene događaje šalje u isti feed

Tiketi su jedna jsudc kolekcija, jer jsudc daje kanban tablu bez dodatnog rada. Tutorijal nije o tabli, pa ona zauzima jednu komponentu.

  • Docker sa Compose v2. Ceo stack radi u kontejnerima.
  • Node 24. Backend pokreće TypeScript direktno, bez build koraka.
  • pnpm 11. Ako ga nemate, corepack enable daje verziju koju traži package.json.

Port 8080 mora da bude slobodan. Ako nije, u koraku 1 postavite DESK_PORT u .env i svuda ispod koristite taj port u curl komandama.

Svaki fajl svakog koraka je na ovoj stranici. Fajl koji korak dodaje prikazan je ceo, pod svojom putanjom. Iskopirajte ga na tu putanju.

Fajl koji korak menja prikazan je kao diff: linije sa + su nove, linije sa - odlaze, a ostale pokazuju gde je izmena. Izmenite fajl ručno, ili u folderu programa pokrenite patch -p1, nalepite blok i pritisnite Ctrl-D.

Testovi i dugački stilovi su sklopljeni, pod linijom „Prikaži”. Deo su programa kao i sve ostalo, i provere ispod ih pokreću.

pnpm-lock.yaml nije prikazan: njega piše pnpm install. Nije ni README.md, jer on samo upućuje ovamo.

Počnite od svega na čemu program radi, uz backend koji samo javlja da je živ. Napravite folder programa i od sada radite u njemu:

mkdir ticket-desk && cd ticket-desk

@vol-a/* i @memento/* još nisu na npm-u, pa klijentski paketi stižu kao pet tarball fajlova sa ovog sajta. Sami servisi su Docker slike, tako da je ovih pet fajlova sve što uzimate spolja:

mkdir -p vendor
for 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"
done
ls vendor
Šta je ispisano
memento-core-1.0.0.tgz
memento-react-1.0.0.tgz
vol-a-client-1.0.1.tgz
vol-a-core-1.0.1.tgz
vol-a-react-1.0.1.tgz

package.json još ne zavisi ni od jednog servisa, samo od Fastify-ja. pnpm-workspace.yaml čini ovaj folder zasebnim projektom i upućuje nazive paketa na vendor/. To ništa ne košta dok korak 4 ne zatraži jedan od njih.

package.json
{
"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"
}
}
pnpm-workspace.yaml
# 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
tsconfig.json
{
"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"]
}
.gitignore
node_modules/
dist/
.env
.env.example
# `make setup` writes the keys below. Only DESK_PORT is yours to change.
DESK_PORT=8080
Prikaži biome.json (pravila za lint i format)
biome.json
{
"$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"
}
}
}

Za sada jedna ruta. Kasniji koraci menjaju ovaj fajl, deo po deo.

src/server/main.ts
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) });

Slika instalira zavisnosti iz lockfile-a i pokreće TypeScript takav kakav je.

Dockerfile
FROM docker.io/library/node:24-slim
WORKDIR /app
RUN corepack enable
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY vendor ./vendor
RUN pnpm install --frozen-lockfile
COPY . .
USER node
# Node 24 runs TypeScript as it is: there is no build step for the server.
CMD ["node", "src/server/main.ts"]
.dockerignore
node_modules
dist
.env
.git

Jedan PostgreSQL drži po jednu bazu za svaki program, da se ništa ne meša. Bazu programa pravi sama slika, jer je POSTGRES_USER imenuje, pa ova skripta pravi preostale dve:

docker/init-databases.sql
-- 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;

Compose fajl je najveći deo ovog koraka. vola i vola-worker su ista slika: worker pravi sličice iz istog /data. Samo desk objavljuje port. Browser će do vole i mementa stizati preko njega, na jednom origin-u.

docker-compose.yaml
# 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:
Makefile
.PHONY: up down clean
up:
docker compose up -d --build
down:
docker compose down
# Everything, the data too.
clean:
docker compose down -v

pnpm install piše lockfile koji slici treba. Prvi up preuzima slike i traje nekoliko minuta.

pnpm install
cp .env.example .env
docker compose up -d --build
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo
docker compose ps --format '{{.Service}}: {{.State}}'
Šta je ispisano
{"ok":true}
desk: running
memento: running
postgres: running
redis: running
vola: running
vola-worker: running

Treba da vidite {"ok":true} i svih šest servisa u stanju running. Nijedan servis još ne zna za desk. To je sledeći korak.

I vola i memento imaju više tenanata, i nijedan vas ne pušta bez ključa. Ovaj korak u svakom pravi tenanta desk, preko komandne linije koja je u njihovim slikama, i još četiri ključa:

u .env ko ga drži dozvole
MEMENTO_SERVER_KEY backend write: šalje događaje
VOLA_SERVER_KEY backend files:read: čita ime priloženog fajla
MEMENTO_BROWSER_KEY browser read: feed
VOLA_BROWSER_KEY browser files:*, folders:*, shares:write: otpremanje ide direktno na volu

Skriptu možete bezbedno da pokrenete ponovo, jer se ključ koji već postoji u .env zadržava. Kasniji koraci se na to oslanjaju: svaki koji od servisa traži nešto novo dodaje ovde par linija, a vi ponovo pokrenete make setup.

scripts/setup.sh
#!/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 -eu
cd "$(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/null
vola 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_KEY
missing 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_KEY
missing 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}"

Backend dobija ključeve iz okruženja, a Makefile novu metu:

docker-compose.yaml
--- 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"
Makefile
--- 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 .env
make setup
Šta je ispisano
Tenants…
Keys…
MEMENTO_SERVER_KEY
VOLA_SERVER_KEY
MEMENTO_BROWSER_KEY
VOLA_BROWSER_KEY
Restarting with the keys…
Ready: http://localhost:8080
cut -d= -f1 .env | grep KEY
docker 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":"[^"]*"'
Šta je ispisano
MEMENTO_SERVER_KEY
VOLA_SERVER_KEY
MEMENTO_BROWSER_KEY
VOLA_BROWSER_KEY
"slug":"desk"
"name":"desk-browser"
"name":"desk-server"

Treba da vidite četiri imena ključeva i tenanta u oba servisa. Ovaj program nema prijavu, pa korak 5 browseru daje njegova dva ključa. Prava aplikacija ih daje samo prijavljenim korisnicima.

Ako ikad poželite da počnete iznova, make clean briše sve podatke, a s njima i .env.

Sada program ima šta da čuva: tikete, u sopstvenoj bazi. Nijedan servis ne učestvuje u ovom koraku.

Tiket je jedan red jsudc kolekcije. schema.json kaže šta je tiket, a view.yaml kako ga tabla prikazuje: kanban_options je cela konfiguracija table. Kolona table je jedan red kolekcije buckets, a kartica stoji u koloni koju imenuje njen status.

collections/tickets/schema.json
{
"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" }
}
}
collections/tickets/view.yaml
# 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: kanban
available_renderers: [kanban]
pagination: infinite
page_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: true

Kolone i jedina tabla su male kolekcije u memoriji, popunjene iz seed fajlova:

collections/buckets/schema.json
{
"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" }
}
}
collections/buckets/seed.json
[
{ "__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
}
]
collections/buckets/source.yaml
kind: memory
collections/buckets/view.yaml
# The columns of the board. A column's id is a value of the tickets' `status`.
default_renderer: table
available_renderers: [table]
columns:
- { field: name }
- { field: order }
collections/boards/schema.json
{
"version": "v1",
"core_fields": [],
"fields": {
"name": { "type": "string", "required": true }
}
}
collections/boards/seed.json
[{ "__meta": { "id": "desk" }, "name": "Ticket desk" }]
collections/boards/source.yaml
kind: memory
collections/boards/view.yaml
# The kanban renderer asks for a board. The desk has one.
default_renderer: table
available_renderers: [table]
columns:
- { field: name }

desk.ts je ono što dele backend i frontend. Spisak korisnika je cela prijava u ovom programu.

src/shared/desk.ts
/** 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;
}
ruta šta radi
POST /tickets novi tiket na vrhu prve kolone
GET /tickets/:id jedan tiket
PATCH /tickets/:id/status pomera ga u drugu kolonu
POST /tickets/:id/assign dodeljuje ga nekome

Svako pisanje traži X-User-Id, koji imenuje jednog od korisnika.

src/server/tickets.ts
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 kao argument prima sve sa čim backend razgovara, da bi testovi mogli to da zamene. udcPlugin servira kolekcije na POST /udc/*, a to će tabla čitati. main.ts povezuje prave stvari: pravi tabelu, učitava kolekcije i pokreće server.

src/server/app.ts
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;
}
src/server/main.ts
--- 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) });

Ostalo je povezivanje: baza za desk, nove zavisnosti i testovi u proveri tipova.

docker-compose.yaml
--- 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:-}
package.json
--- 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"
}
}
tsconfig.json
--- 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"]
}
vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: { include: ["test/**/*.test.ts"] },
});

Testovi pokreću rute nad tiketima u memoriji, pa za njih ništa ne mora da bude podignuto.

Prikaži testove (test/helpers.ts, test/tickets.test.ts)
test/helpers.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" };
test/tickets.test.ts
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);
});
});
pnpm install
pnpm test
Šta je ispisano
Test Files 1 passed (1)
Tests 11 passed (11)
docker compose up -d --build
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo
curl -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; echo
ID=$(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"}'; echo
curl -s -X PATCH "localhost:8080/tickets/$ID/status" \
-H 'x-user-id: ana' -H 'content-type: application/json' \
-d '{"status":"in_progress"}'; echo
Šta je ispisano
{"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"}

Tiket treba da dobijete tri puta, s tim što su se assignee, pa status promenili. Bez korisnika backend odbija:

curl -s -X POST localhost:8080/tickets \
-H 'content-type: application/json' -d '{"title":"Who am I?"}'; echo
Šta je ispisano
{"error":"X-User-Id must name one of the desk's users"}

Ovde stupa memento. Sve što se desi tiketu postaje jedan događaj, na instanci tickets/<id>, sa korisnikom kao akterom.

akcija event_type payload
POST /tickets TICKET_CREATED title
POST /tickets/:id/comments TICKET_COMMENTED text
PATCH /tickets/:id/status, ili kartica prevučena na tabli 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

events.ts kaže koji događaj odgovara akciji i ništa drugo ne radi, pa ga je lako testirati.

src/server/events.ts
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 ga šalje preko POST /memento/events. Izmena je do tada već sačuvana, pa memento koji ne radi košta jedan red u logu, a ne zahtev korisnika.

src/server/memento.ts
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");
}
};
}

Uz to stižu dve nove rute. Komentar nema svoju tabelu: događaj jeste komentar, a komentari žive u mementu. Preko POST /tickets/:id/files backend saznaje za fajl: browser otprema direktno na volu, pa to ovde javi. Backend od vole traži taj fajl, pa događaj nosi činjenice iz vole, a fajl koji nije na ovom tiketu biva odbijen.

src/server/tickets.ts
--- 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 });
});
}

Tabla ne koristi ove rute. Ona piše preko UDC rute POST /udc/mutate, pa oko te rute stoje dve Fastify kuke, i prevučena kartica daje isti događaj kao ruta za status.

src/server/drag.ts
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;
});
}
src/server/app.ts
--- 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 prosleđuje pravi memento i pravu volu. Ovo je prva upotreba paketa @vol-a/client:

src/server/main.ts
--- 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) });
docker-compose.yaml
--- 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:-}
package.json
--- 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",

Sirov JSON ne vredi u feedu. Šablon mementu daje rečenicu za tip događaja na jednom jeziku, a locale čitaoca bira koja će se prikazati. Po jedan fajl ide na tip događaja i jezik, pa je TICKET_ASSIGNED.sr.hbs srpska rečenica za TICKET_ASSIGNED:

templates/TICKET_CREATED.en.hbs
{{actor_id}} opened the ticket "{{payload.title}}"
templates/TICKET_CREATED.sr.hbs
{{actor_id}} otvara tiket „{{payload.title}}"
templates/TICKET_COMMENTED.en.hbs
{{actor_id}} commented: "{{truncate payload.text 120}}"
templates/TICKET_COMMENTED.sr.hbs
{{actor_id}} komentariše: „{{truncate payload.text 120}}"
templates/TICKET_STATUS_CHANGED.en.hbs
{{actor_id}} moved the ticket: {{payload.previous}} → {{payload.status}}
templates/TICKET_STATUS_CHANGED.sr.hbs
{{actor_id}} menja status tiketa: {{payload.previous}} → {{payload.status}}
templates/TICKET_ASSIGNED.en.hbs
{{actor_id}} assigned the ticket to {{payload.assignee}}
templates/TICKET_ASSIGNED.sr.hbs
{{actor_id}} dodeljuje tiket: {{payload.assignee}}
templates/TICKET_FILE_ATTACHED.en.hbs
{{actor_id}} attached {{payload.filename}}
templates/TICKET_FILE_ATTACHED.sr.hbs
{{actor_id}} kači fajl {{payload.filename}}

Srpske rečenice su namerno u sadašnjem vremenu. Prošlo vreme traži rod aktera, a događaj ima samo actor_id.

make setup ih predaje mementu:

scripts/setup.sh
--- 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 -d
Prikaži testove (test/helpers.ts, test/events.test.ts)
test/helpers.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" };
test/events.test.ts
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);
});
});
pnpm install
pnpm test
Šta je ispisano
Test Files 2 passed (2)
Tests 23 passed (23)
make setup
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo
Šta je ispisano
Templates…
Restarting with the keys…
Ready: http://localhost:8080
{"ok":true}

Otvorite tiket, komentarišite ga kao ana i pomerite ga:

curl -s -X POST localhost:8080/tickets \
-H 'x-user-id: igor' -H 'content-type: application/json' \
-d '{"title":"Printer on fire"}' > /tmp/ticket.json
ID=$(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"}'; echo
curl -s -X PATCH "localhost:8080/tickets/$ID/status" \
-H 'x-user-id: ana' -H 'content-type: application/json' \
-d '{"status":"in_progress"}' > /dev/null
Šta je ispisano
{"ok":true}

Sada iz mementa pročitajte istoriju tiketa, na oba jezika. Memento još nema svoj port, pa zahtev ide iz njegovog kontejnera; korak 5 otvara put browseru.

. ./.env
for 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)));"
done
Šta je ispisano
ana moved the ticket: new → in_progress
ana commented: "On my way"
igor opened the ticket "Printer on fire"
ana menja status tiketa: new → in_progress
ana komentariše: „On my way"
igor otvara tiket „Printer on fire"

Treba da vidite ista tri događaja dvaput, najnoviji prvi, po jednom na svakom jeziku. Ništa u bazi programa ne beleži komentar, a on je tu.

U browseru posao rade tri dela, i sva tri su komponente iz biblioteka:

komponenta razgovara sa
tabla <UdcDataView collection="tickets"> sa @jsudc/react/kanban: pretraga, kolone, prevlačenje /udc/* na backendu
fajlovi <VolaFileBrowser> i <VolaUploadButton> iz @vol-a/react, na instanci tickets/<id> volom, direktno, sa X-User-Id
feed useMementoEvents iz @memento/react mementom, direktno

Backend sada prosleđuje /vola i /memento ka dva servisa, HTTP i WebSocket, pa browser vidi jedan origin i nijednom servisu ne treba port. GET /config stranici daje njena dva ključa, a backend servira izgrađeni frontend.

src/server/proxy.ts
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());
});
}
src/server/app.ts
--- 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;
}
src/server/main.ts
--- 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) });

Slika sada gradi i frontend, a projekat dobija zavisnosti i Vite podešavanje:

Dockerfile
--- 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"]
package.json
--- 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"
}
}
index.html
<!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>
vite.config.ts
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,
},
},
});
tsconfig.web.json
{
"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"]
}

api.ts su rute backenda kao funkcije. session.ts čuva ko je prijavljen. App.tsx učitava /config, podešava MementoProvider i crta zaglavlje sa dva izbora: ko ste i na kom jeziku feed govori.

src/web/main.tsx
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 />);
src/web/api.ts
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 });
src/web/session.ts
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;
}
src/web/App.tsx
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>
);
}

Cela tabla je jedna komponenta: pita backend šta je kolekcija tickets i nacrta je. Prevlačenje piše preko udc/mutate sa X-User-Id, a kuke iz koraka 4 od toga prave događaj.

src/web/Board.tsx
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>
);
}
src/web/BoardPage.tsx
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>
);
}

Browser sam razgovara sa volom, na instanci tickets/<id>, sa prijavljenim korisnikom u userId. Sličice, folderi, preuzimanje, brisanje i Share u meniju fajla dolaze uz VolaFileBrowser. Otpremanje ide kroz VolaUploadButton jer preko njegovog onUploaded backend saznaje za fajl, a to beleži TICKET_FILE_ATTACHED.

src/web/Files.tsx
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>
);
}

Za sada se feed čita jednom, pa ponovo posle svake vaše akcije.

src/web/Activity.tsx
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>
);
}
src/web/TicketPage.tsx
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>
);
}
Prikaži src/web/desk.css
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;
}
Prikaži izmene testova
test/helpers.ts
--- 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 });
}
test/tickets.test.ts
--- 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");
+ });
+});
pnpm install
pnpm test
Šta je ispisano
Test Files 2 passed (2)
Tests 25 passed (25)
docker compose up -d --build
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo
curl -s localhost:8080/ | grep -o '<title>.*</title>'
curl -s -o /dev/null -w '/config %{http_code}\n' localhost:8080/config
Šta je ispisano
<title>Ticket desk</title>
/config 200

Otvorite http://localhost:8080. Videćete tablu sa tri kolone, a na njoj tikete koje ste u ranijim koracima napravili curl-om. Na čistom stack-u (make clean, pa make setup) tabla je prazna:

Prazna tabla posle koraka 5: kolone New, In progress i Done, bez kartica

Upišite naslov, pritisnite New ticket i kliknite na karticu. Na stranici tiketa promenite status, ostavite komentar i otpremite fajl dugmetom iznad liste fajlova. Svaka akcija se pojavljuje u feedu desno, kao rečenica. Izbor Language u zaglavlju prebacuje iste događaje na srpski.

Za razvoj sa ponovnim učitavanjem, pnpm dev i pnpm dev:web pokreću obe polovine van Docker-a.

Na stranici se još ništa ne pomera ako vi to niste pomerili. Ovaj korak to popravlja bez ikakvog novog servera, jer memento već šalje svaki događaj preko svog WebSocket-a, /memento/ws.

useMementoEvents učitava najnovije događaje, a zatim dobija svaki novi čim se sačuva. onEvent iz feeda javlja tabli i stranici tiketa da ponovo pročitaju podatke, pa tok iz mementa postaje jedini signal koji cela stranica prati, a sve što je u koraku 5 dodato zbog ponovnog čitanja odlazi.

src/web/Activity.tsx
--- 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>
src/web/BoardPage.tsx
--- 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>
);
}
src/web/Board.tsx
--- 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();
/**
src/web/Files.tsx
--- 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
src/web/TicketPage.tsx
--- 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>
);
}

Postoji jedna pretplata na ceo desk, a feed.ts iz nje bira deo jednog tiketa. Filter samo na tickets/<id> bio bi kraći, a korak 7 pokazuje zašto bi nešto propustio.

src/web/feed.ts
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);
});
}
Prikaži izmene stilova i test
src/web/desk.css
--- 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;
+ }
+}
test/feed.test.ts
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([]);
});
});

Fajlovima ovde ne treba nikakva izmena. VolaFileBrowser je živ još od koraka 5: sam otvara WebSocket ka volinom /udc/subscribe, pa se fajl koji drugi tab otpremi ili obriše sam pojavi u listi, odnosno nestane iz nje. Stranica sada prati dva toka, svaki iz servisa koji poseduje te podatke.

pnpm test
Šta je ispisano
Test Files 3 passed (3)
Tests 29 passed (29)
docker compose up -d --build
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo

Otvorite tiket i stranicu tiketa u browseru:

curl -s -X POST localhost:8080/tickets \
-H 'x-user-id: igor' -H 'content-type: application/json' \
-d '{"title":"Printer on fire"}' > /tmp/ticket.json
ID=$(sed -n 's/.*"id":"\([^"]*\)".*/\1/p' /tmp/ticket.json)
echo "http://localhost:8080/t/$ID"
Šta je ispisano
http://localhost:8080/t/64b1e676-c53c-4393-9677-c4d61dd9200b

Dok je ta stranica otvorena, komentarišite iz terminala, kao neko drugi. Ne dirajte stranicu.

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
Šta je ispisano
{"ok":true}

Rečenica se sama pojavljuje na vrhu feeda. Live pored naslova kaže da je tok iz mementa povezan, a Live iznad fajlova je tok iz vole:

Stranica tiketa posle koraka 6: komentar poslat iz terminala pojavio se u feedu bez ponovnog učitavanja

Isto radi između dva taba: u jednom se prijavite kao neko drugi, a radite u drugom.

Do sada feed prikazuje ono što program kaže. Fajl obrisan preko vole nije u njemu, jer program za to nikad ne čuje. Vola to može sama da javi. Njene destruktivne i bezbednosno važne operacije mogu direktno u memento, a za uključivanje su dovoljne dve promenljive okruženja i još jedan ključ.

docker-compose.yaml
--- 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 }
scripts/setup.sh
--- 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
.env.example
--- 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:latest

Nijedna linija programa se ne menja. Novim događajima trebaju samo rečenice, pa dobijaju šablone kao i ostali:

templates/VOLA_SHARE_CREATED.en.hbs
{{actor_id}} made a share link{{#if payload.has_password}} with a password{{/if}}
templates/VOLA_SHARE_CREATED.sr.hbs
{{actor_id}} pravi link za deljenje{{#if payload.has_password}} sa lozinkom{{/if}}
templates/VOLA_SHARE_REVOKED.en.hbs
{{actor_id}} revoked a share link, after {{payload.download_count}} download(s)
templates/VOLA_SHARE_REVOKED.sr.hbs
{{actor_id}} povlači link za deljenje, preuzimanja: {{payload.download_count}}
templates/VOLA_FILE_DELETED.en.hbs
{{actor_id}} deleted {{payload.filename}}
templates/VOLA_FILE_DELETED.sr.hbs
{{actor_id}} briše fajl {{payload.filename}}

Zbog ovoga postoji feed.ts iz koraka 6. Vola ove događaje stavlja na sopstvene instance, vola_file/<id> i vola_share/<id>, jer ne zna ništa o tiketima. Do tiketa vodi payload: događaj fajla kaže u kojoj je instanci fajl, a događaj deljenja imenuje fajl.

Ostatak koraka je jedan test koji prolazi glavni tok na podignutom stack-u, kroz port programa, kao i zahtevi iz browsera.

Makefile
--- 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
package.json
--- 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",
tsconfig.json
--- 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"
+ ]
}
vitest.e2e.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: { include: ["e2e/**/*.test.ts"] },
});
Prikaži e2e/smoke.test.ts
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);
});
});
make setup
curl -s --retry 20 --retry-all-errors --retry-delay 1 localhost:8080/health; echo
Šta je ispisano
Tenants…
Keys…
MEMENTO_AUDIT_KEY
Templates…
Restarting with the keys…
Ready: http://localhost:8080
{"ok":true}
make e2e
Šta je ispisano
Test Files 1 passed (1)
Tests 2 passed (2)
docker compose logs vola-worker | grep -c 'memento answered 422'
Šta je ispisano
0

Test prolazi, a worker nema nijedno odbijanje da prijavi. Sada to pogledajte sami. Otvorite tiket, otpremite fajl i otvorite meni tog fajla: Share pa Create link pravi VOLA_SHARE_CREATED, a Delete sa potvrdom pravi VOLA_FILE_DELETED. Oba se pojavljuju u feedu pored događaja programa, sa prijavljenim korisnikom kao akterom, jer je browser voli poslao X-User-Id.

Stranica tiketa posle koraka 7: deljenje i brisanje iz volinog audita, u istom feedu sa događajima programa

Završite svime što program ima:

pnpm test
pnpm typecheck && pnpm lint
Šta je ispisano
Test Files 3 passed (3)
Tests 29 passed (29)
$ tsc --noEmit && tsc --noEmit -p tsconfig.web.json
$ biome check .
Checked 44 files

Program namerno mnogo toga izostavlja. Nema pravu prijavu: ko god otvori stranicu dobija ključeve za browser, a X-User-Id se prima na reč. Ako memento ne radi, događaj se gubi uz jedan red u logu, jer je sama izmena već sačuvana. Feed čita najnovijih 200 događaja i iz njih bira deo za tiket, što je ovde sasvim dovoljno; veliki desk bi držao tabelu fajl → tiket i pitao po tiketu.

Odavde možete dalje:

  • Enkripcija. Fajlovi zapečaćeni na disku, svaki posebno: kako radi i živi primer.
  • Keyring i PIN. Ključevi koje samo korisnik može da otključa, sa VolaPinGate iz @vol-a/react: referenca za enkripciju.
  • Deljenje. Lozinke, rok i ograničenje preuzimanja na linku za deljenje: živi primer.
  • Filter DSL. Upiti nad događajima u mementu po polju, umesto čitanja najnovijih, preko POST /memento/events/query: API mementa.
  • Drugi tenant. Pokrenite create-tenant i create-key ponovo, sa drugim imenom, u oba servisa. Ključ vidi svog tenanta i ništa drugo. Jedan memento ključ prima audit cele vola instalacije, sa imenom vola tenanta u payload.tenant.

Reference:

vola memento
HTTP API API API.md
Uživo Real-time STREAMING.md
Komandna linija CLI CLI.md
React Packages, Get started with React REACT.md
Rečenice TEMPLATES.md

v1.1.1released built 519e3dc