Skip to content

Machine-translated – improvements welcome. Suggest an improvement

Server: folders and patterns

What lives where in the server and which patterns apply everywhere. The map gives the overview, the subject areas are under Subject areas of the server.

Folders

Folder in server/src/ Routes for
anmeldung/ sign-in, two-factor, passkeys, password, setup, emergency access
konten/ users, roles, deputies, API keys; since #1278 the class Konten itself (sign-in, sessions, administration mode, user management) as a chain of partial classes, one file per task
mappentypen/ folder types, their archive, permissions
werkbank/ Workbench overview, designs, region, languages, log, admin mode
ausgang/ export (Workbench and My account); since #1077 the routes to the outside
datenschutz/ data subject requests, deletion concept, retrieval page; since #1078 data protection
pakete/ packages, catalogue, package settings
suche/ search, Ask your archive
wartung/ maintenance mode
sicherung/ backup, restore, emergency sheet, keys; since #1278 Sicherung and Wiederherstellung each as a chain of sub-classes (sicherung-*.ts, wiederherstellung-*.ts), the door stays sicherung.ts and wiederherstellung.ts
system/ operation, system status, connection, sign-in protection, inbox folder, WebDAV, error reports
post/ mailboxes and other inbound channels; since #1077 post
automatisierung/ automations; the engine in motor/ (#1278, chain of partial classes, its own door motor/index.ts because it receives the whole service – automatisierung/index.ts passes its names on)
sichten/ views, folder lists, start page
aufgaben/ tasks; since #1078 the tasks
mappen/ folders, history, recycle bin
dokumente/ documents, versions, contents
textsatz/ set text (#1040): templates of a folder, letter from template as PDF (pdf/brief.ts, tagged, in the worker)
notfallkontakte/ emergency contacts (#812): Workbench → Encryption, info email to trusted people (limits in the short-lived state), “Whom to ask?” on the emergency sheet
paketaktionen/ package actions in the “Folder” menu (#1039): offer per person, run with dialog and result, the package's restricted access, Workbench switches

The folders are named after the service modules of the target structure; their *.dienst.ts files join them when each one moves – first suche/suche.dienst.ts (search, #964). Every subject folder with a *.dienst.ts has an index.ts as its door and a hand-written README.md (20–40 lines); CI checks this in the stil job (.github/werkzeuge/fachordner-pruefen.mjs). Which folders may import what is set by the layers. pakete/ also holds pakete.einstellungen.ts (#961): catalogue sources, package settings, package storage, drafts and conversions in the settings – from outside via pakete/index.ts (imported as ./pakete/index). Package management and package creation (#1278, previously pakete.ts and paketerstellung.ts) sit above the service and each have a door of their own: pakete/verwaltung/index.ts – a chain of partial classes, one file per task (origin, catalogues, uploads, preview, creating, installing, flow, settings, removing; described in verwaltung/basis.ts) – and pakete/erstellung/index.ts.

Alongside, without routes:

Folder in server/src/ Contents
kern/ the core (#961)
zugriff/ checking permissions (#1072)
systemausstattung/ the system setup (#963)
http/ helpers of the HTTP layer – for routes only (checked with npm run lint:abh)
pdf-bearbeiten/ editing PDFs (#1077): pages, shrinking, redacting, stamp templates
pdf/, arbeit/ PDF module, worker pool
laeufer/ package runner; the DMS side (Paketlaeufer) since #1278 as a chain of sub-classes verwaltung-*.ts, door verwaltung.ts

Since #1278 (step 4a) every file lives in a folder; directly in server/src/ there are only the entry points that the build, the Dockerfile and the workflows address by path: index.ts, ablago.ts, dms.ts and pakete-pruefen.ts. Since step 4b ablago.ts calls the sections in start/ and keeps the paths relative to itself (pfad, from src/ as from dist/). The files from there moved into their subject folders (e.g. postfach.ts to post/, sicherung.ts to sicherung/, oidc.ts to anmeldung/, routen.ts and http.ts to http/) or into these folders:

Folder in server/src/ Contents
dienst/ the service (dienst.ts, building blocks per area in bauteile.ts) that assembles the subject folders
grundlagen/ business errors, size limits, transitional exceptions (uebergaenge.ts)
datenbank/ connection, migrations, database connection file, tenant, extensions, lock connection, access measurements
protokoll/ log and evidence journal
sprache/ server texts, language packs, language choice, translation
einstellungen/ settings of the archive, region, operating settings
zwischenspeicher/ counter, read and short-state stores, cache with several processes
geheimnisse/ vault, secrets, lock for secrets
dateien/ file technology: file store, upload, conversion, archival version, unlocking, preview, pages, shrinking, redaction, fallback fonts, fixed folders, disk space
formate/ own writers and readers without a library: ZIP, Excel, XML, document (PDF and Word)
export/ export of several folders, full export (since #1278 split into vollexport-quelle, -formate, -schreiben, -verwaltung; door vollexport.ts), export folder
erkennung/ recognition when assigning (since #1278 a chain of sub-classes erkennung-*.ts, door erkennung.ts), classification, e-invoice
mail/ mailer and lookup of the sending server
prozesse/ several processes, division of work, background work, orderly shutdown
zeitplan/ the schedule building block and spreading
lasttest/ load test mode, storage type, log collection, query statistics, process groups
einrichtung/ setup assistant, setup code, file and mode, and the start page
notfall/ emergency access (RESCUE file, emergency code), emergency sheet
oberflaeche/ fallback rule of the interface, designs, offline help
entdecken/ tours and tips, also from the workbench
webdav/ WebDAV drive
beispiele/ example folder types and example archive of the packages
demo/ demo folders and demo documents, seeded randomness
start/ the sections of start-up from ablago.ts (#1278, step 4b), one function each in the old order; only ablago.ts imports them (start-nur-aus-ablago)

These files have no door yet: OHNE_TUER in .dependency-cruiser.cjs lists them, and the rules treat them like a file directly in server/src/ before (rules).

Patterns

  • Repos twice: every data access interface exists for PostgreSQL (server/src/repo/pg/, pg… functions) and for memory (server/src/repo/speicher/, speicher…); the interface itself is in server/src/repo/index.ts – since #1278 put together from sub-interfaces per subject area in repo/schnittstelle/ (RepoMappen, RepoPakete, RepoDokumente, RepoPapierkorb, RepoVolltext, RepoAufgaben; types and helpers in schnittstelle/typen.ts), imports of …/repo stay the same. Both are split by subject area (#1278: pg/mappen.ts and speicher/mappen.ts, pg/dokumente.ts and speicher/dokumente.ts …): each file has factories (pgMappenLesen(k), speicherMappenLesen(sp)) that receive the shared context (kontext.ts: connection and household, or the in-memory state) and return part of the methods; they are put together only in pg/index.ts and speicher/index.ts. A new method goes into the same subject-area file on both sides. Most tests run quickly in memory; the tests with TEST_DATABASE_URL cover PostgreSQL. New functions need both, and both must behave the same.
  • Routes are kept per subject area in server/src/<fach>/<fach>.routen.ts (#960, e.g. dokumente/dokumente.routen.ts), each with zugang: 'offen' | 'angemeldet' | 'admin'. Each file exports functions …Routen(k) that receive the services and shared helpers via the parameter k (http/routen-kontext.ts; helpers without services in http/routen-hilfen.ts). routen() in server/src/http/routen.ts calls them in a fixed order (BEREICHE) and still holds the types (Route, Anfrage, Antwort), pruefeZugang and the check of package permissions; the test routen-liste.test.ts checks that every route is listed with its zugang in the route table (test/charakter/routen-tabelle.json) and that none is duplicated. Routes without sign-in (zugang: 'offen') are also kept there in a fixed list (OFFEN, each with a reason, #1029): a new open route – or one that changes to offen – goes into this list on purpose and gets a one-sentence justification in the pull request; otherwise the test fails. The helpers in http/routen-hilfen.ts and http/routen-kontext.ts may only be imported by route files (*.routen.ts, routen.ts) (npm run lint:abh, rule routen-hilfen-nur-in-routen). Two features are added: api: true makes a route part of the public API (sign-in also with an API key); konsole: true only allows it via the command dms in the container. The public API for programs is under /api/v1 (http/api-v1/, OpenAPI).
  • Workbench routes (zugang: 'admin', #818/#819) only work in administration mode (state of the session, Konten.modusPruefen) and only with permission for their area. Every new route needs an entry in server/src/werkbank/verwaltungsbereiche.ts (bereicheDerRoute) – otherwise only people with "Full administration" may use it, and the test verwaltungsmodus.test.ts fails. Sensitive actions that require a fresh sign-in are listed there in heikleHandlung. benutzer.rolle is the request's effective role (admin only in the mode); the stored permission is in benutzer.verwaltung (shared/src/verwaltungsrecht.ts). API keys never get admin.
  • Public links without sign-in so far only exist for an access copy's retrieval page (#455, server/src/datenschutz/abruf.ts, web/src/abruf.tsx): key only in the fragment (/abruf#…), in the database only hashes (SHA-256 for the key, scrypt for the code), failed attempts in sign-in protection per IP and on the link, download via a one-time ticket. Further sharing links should follow this pattern. In addition there is the emergency access /notfall (#815, server/src/notfall/notfallcode.ts, web/src/notfall.tsx): emergency code from the emergency sheet only as a scrypt hash (table notfallcode), redeemed in one transaction with the new password, default "home network only" with the real address behind a proxy (istHeimnetz), 30 s lock per address range, accounts only after the right code, notification before every change.
  • Migrations are numbered SQL files in server/migrations/. They run at start-up in one transaction and are never changed afterwards, always supplemented by a new one.
  • Start (#802, server/src/einrichtung/startmodus.ts): right after creating the folders, ablago.ts opens the port (with several processes only the leader at the first start, see Several processes) with the page "Ablago is starting …". It knows no database, only the state in memory (start.schritt('migration', { nr, von, datei }), start.menge(fertig, gesamt)): pages of the interface show step and numbers (reloading via meta refresh, no script), /api/* and /webdav answer 503 with Retry-After and startet: true (the interface counts that as an outage and waits), /api/gesundheit reports 503 with zustand: startet|fehler. It only releases the port immediately before app.listen (and in between for setup mode). An error at start-up lands on the page via uncaughtException – only kind, step, migration file and SQLSTATE, never the message itself (it can contain values); after 5 minutes the process ends, except with the lock against a downgrade. New long preparations get a Startschritt of their own (text in shared/src/sprachen/de/start.json) or run in the background after the start, like the first deadline reconciliation.
  • Pre-start and start errors (#1250, server/src/vorstart.ts, server/src/einrichtung/startfehler.ts): in dms-komplett, deploy/komplett/start.sh first starts the pre-start (dist/vorstart.js, a bundle of its own without database). It shows the same page with the step from DMS_VORSTART_DATEI (one line: pg-anlegen, pg-start, ablago or fehler <reason>), listens with reusePort and reports /api/gesundheit without the state identifier. Ablago gets DMS_VORSTART_PID and DMS_VORSTART_SEIT, also listens with reusePort and only then sends SIGTERM to the pre-start – so the hand-over has no gap. Errors before Ablago (permissions, other major version, initdb, PostgreSQL stopped) are shown by the pre-start for DMS_START_FEHLER_WARTEN_S (default 300), then the container ends. datenbankGrund() interprets "unreachable or blocked" from the error code only (connection refused, lock 55P03/40P01, storage full 53100, too many connections 53300); the page adds the way out. Ablago tries an unreachable database 30 times every 2 s (step datenbank-warten); if another Ablago holds the migration lock, the page shows sperre. The page's language follows Accept-Language (de, otherwise en). Tests: server/test/vorstart.test.ts, in the image deploy/komplett-probe.sh (steps 1 and 5).
  • Uploads as a stream (#746, server/src/dateien/hochladen.ts): routes with strom: true (upload document, new version, also via /api/v1) are in a Fastify scope of their own whose parser writes the body into a temporary file under files/hochladen/ (0600, checksum and header while reading); body is then a Hochgeladen. Via Eingang.aus() the service treats upload or buffer alike; filing happens by renaming (Dateispeicher.uebernimm). WebDAV PUT uses nimmAuf directly. Other uploads (logo, photo stack, packages) still read into memory because they need the whole content anyway.
  • Settings are stored as JSON per key in the table einstellungen. null deletes an entry.
  • Recognising the home network (#595): whether an address is in the home network is decided only by shared/src/heimnetz.ts (imHeimnetz, list HEIMNETZ_ENDUNGEN with .local, .lan, .internal, .home.arpa). Kind ausnahme (strict) allows http:// without TLS – sign-in via a provider, endpoints of mailboxes with an own provider; kind hinweis (wider, e.g. also .fritz.box, 100.64/10) only serves suggestions such as "retrieval link or email", never a security exception. New places use this function instead of a list of their own. "Same computer" (only localhost) is a different question and stays at its places.
  • Help: every ? symbol in the interface points to a place in the manual. The table for this is in shared/src/hilfe.ts, and CI checks that every anchor exists – since #730 in the German and the English manual. The functions take the person's language as an optional last parameter (handbuchOnlineUrl(handbuch, seite, sprache?)); without it, the interface's current language applies (sprache() from shared/src/sprache.ts).
  • Rows written by many and deadlocks (#575): triggers that make many transactions write into the same rows (e.g. counters per word with INSERT … ON CONFLICT DO UPDATE) deadlock under load – every transaction locks its rows in a different order, PostgreSQL cancels one (deadlock). Pattern: the trigger only appends to an inbox without a unique key, a background run takes it over under a lock and in a fixed order (word index: suchwoerter_eingang, dms_woerter_einarbeiten, SucheDienst.woerterEinarbeiten, migration 052). What can still be cancelled and mustn't get lost runs via beiVerklemmungWiederholen (server/src/datenbank/db.ts, repeats on 40P01/40001) – as a transaction of its own or sql.begin (inside a transaction a savepoint). Test: server/test/verklemmung.test.ts.
  • Backup and restore back up all tables except the content of sitzungen and schema_migrationen (OHNE_INHALT in server/src/sicherung/datenbankabzug.ts). A new table is automatically included. Data outside the database needs a thought: where is it, and does it come along?

Without root, tool service

Since #1354 nothing of Ablago runs as root in the container. The start script (deploy/image/einstieg.sh in the dms image, deploy/komplett/start.sh in dms-komplett, shared parts in deploy/image/start-hilfen.sh) runs as root under tini, sets up and then switches user:

Process User Rights
start script root takes over the folders, starts the others
Ablago, pre-start, dms on the console like the owner of the data folder, otherwise ablago (1000:1000); PUID:PGID take precedence. Supplementary group ablago-werkzeug /data, own temp folders, socket of the tool service
tool service (server/dist/werkzeugdienst.js) and the document tools ablago-werkzeug (61000:61000) only one folder per job under /run/ablago-werkzeuge/arbeit and heim (fontconfig); no network
PostgreSQL (only dms-komplett) postgres (70) /data/postgres, socket /run/postgresql (700)
  • Choosing the user (#1466, benutzer_pruefen and daten_kennung in start-hilfen.sh): if PUID and PGID are not set, the script takes owner and group of the data folder – /data if it is mounted itself, otherwise the first mounted one of files, geheim, sicherung, export. "Mounted" means: a mount point in /proc/self/mountinfo; the image's own /data folder (1000:1000) does not count. kennung_tauglich rejects 0 as user or group, likewise 61000 (tools) and the IDs of postgres (its socket uses trust). If no folder fits, 1000:1000 applies with reason root, system or ohne. If PUID or PGID is set, that applies as before (the missing value 1000); PUID=0 only works explicitly, with a warning. The choice goes to Ablago and the pre-start as PUID/PGID, DMS_KENNUNG_HERKUNFT (daten, vorgabe, gesetzt for user and group), DMS_KENNUNG_GRUND and DMS_RECHTE_MERKER, and into the marker (kennung, readable by everyone: ablago-als reads it there because docker exec only knows the compose file's environment). If the script took the folder over for the default itself on the previous start, the origin stays "default" – no back and forth.
  • Taking over folders, as little as possible (ordner_uebernehmen, ordner_angleichen): on the first start of a container (marker under /var/lib/ablago/rechte, i.e. not in the volume) the script, without PUID/PGID, gives Ablago only entries that belong to root (find -user 0 -exec chown -h); entries of other users stay and are mentioned in the log. With PUID/PGID, as before, everything not owned by exactly PUID:PGID. Folders without a volume of their own only live in the container and belong entirely to Ablago afterwards. o-rwx only on one of the four folders that the script created or just took over; folders of the NAS user stay as they are. In geheim, files the group or others could read or write get go-rwx (mandatory, keys live there). Every change on a volume writes aenderung into the marker (aenderungen: time, kind besitzer-root/besitzer/rechte/geheim, folder, count, new owner). Then a write probe as Ablago; if it fails, the script writes the folders it saw into fehler (name, owner, mode, :ro from mountinfo) and a suitable suggestion into vorschlag, the log names the same lines, and the pre-start shows reason daten-rechte. In the inbox folder it only takes over what belongs to root.
  • Display (server/src/einrichtung/dienstbenutzer.ts, sentences in shared/src/dienstbenutzer.ts): reads environment and marker strictly (known kinds, numbers, paths under /data and /eingang only). The start page (startfehler.ts, also in the pre-start) shows the sentence about the choice and the changes of this start – IDs and folder names only, no paths; for daten-rechte the IDs seen and ready-made lines (PUID/PGID, chown, :ro). The system status (/api/werkbank/system, laufzeit.dienstbenutzer) and dms status name user, group, origin and all changes of this container.
  • Why no longer o-rwx on all four folders: it protected the folders from the tool user. But Ablago creates the files in them for itself only anyway (0600, folders 0700: uploads, keys, backups, export work files); the tool user cannot read them even in an open folder. On a NAS, on the other hand, o-rwx on a folder of the NAS user takes access away from other users of the share, and chmod may change ACLs there. Hence only on folders that belong to Ablago just now.
  • Switching user with setpriv (--reuid --regid --groups --no-new-privs): numeric IDs without an entry in /etc/passwd (for PUID/PGID), a supplementary group for the tool service and no_new_privs. su-exec cannot set a supplementary group for a numeric ID nor no_new_privs; the script would have to rewrite /etc/passwd. busybox's setpriv does not know --reuid – CI checks that the util-linux one is in the image. Root in the container may switch users and change owners with the capabilities Docker grants anyway (SETUID, SETGID, CHOWN, DAC_OVERRIDE); the image needs no further rights.
  • Tool service instead of direct calls: A process without root cannot start a program as another user (that would need CAP_SETUID, a setuid program or namespaces – all blocked or ineffective with no-new-privileges). So while it is still root, the start script launches a small service as ablago-werkzeug; for each call Ablago sends command, arguments and standard input over a Unix socket (server/src/prozesse/werkzeugprotokoll.ts) and gets output, error output and the end back. Nothing changes for callers: execFile/spawn from server/src/prozesse/hintergrund.ts behave like node:child_process (ENOENT, killed, maxBuffer, signal); working folders come from werkzeugOrdner(). The service only starts programs from WERKZEUGE (werkzeuggrenzen.ts), with a minimal environment, each in its own process group; when the connection closes it ends the group. If the service ends, the script restarts it after one second.
  • Limits with ulimit in the fixed launcher deploy/image/werkzeug-grenzen.sh (ulimit -v …; ulimit -t …; ulimit -f …; exec "$@", no sh -c, the arguments are passed on unchanged): address space (DMS_WERKZEUG_SPEICHER_MB, default 1024), CPU time (900 s as a backstop behind the callers' own time limits) and file size (2 GB). This needs no rights and no package (busybox, dash and bash), applies only to that program and cannot be raised by it. prlimit would be equivalent but needs util-linux-misc; cgroups would only work with rights on the cgroup tree. poppler reports a failed allocation only with "Out of memory" and exit code 0 – speicherFehlerVon() turns that into an error so that no empty result slips through.
  • Database in dms-komplett: own pg_hba.conf (deploy/komplett/pg_hba.conf, via hba_file, also for existing databases): socket with trust, but the folder is only for postgres (and root); over 127.0.0.1 only scram-sha-256. start.sh sets the password of the dms role on every start (via psql's standard input) and hands it only to Ablago (DMS_DB_KOMPLETT_PASSWORT, inserted in alsUrl, never in datenbank.json). dms is no longer a superuser; start.sh creates pg_trgm and unaccent as postgres in erweiterungen_dms, and dms gets pg_read_all_stats, pg_read_all_settings and pg_stat_statements_reset for the load test.
  • Started without root (docker run --user): the script only starts the command; the tools then run directly, with the same limits. docker exec … dms switches to the Ablago user via ablago-als.
  • Working folders without symlinks: A tool may write to its working folder – a taken-over tool could put a symlink there instead of an output (for example to /data/geheim/…), a hard link or a FIFO. So Ablago only reads and writes there through liesWerkzeugDatei (O_NOFOLLOW, O_NONBLOCK, on the open handle: regular file, one link, size limited), schreibeWerkzeugDatei (remove an existing entry, then only create anew with wx) and werkzeugDateien (only regular files from withFileTypes), all in server/src/prozesse/hintergrund.ts. New code using werkzeugOrdner() only uses these three.
  • Not trusting the service's answers: Ablago checks every frame (at most 4 MB, the end only as an integer or a signal name, start errors only with a code of the form E…, message shortened). Output and error output are data: maxBuffer limits them; callers only derive messages from error output (such as "wrong password" or "font missing"), never rights or paths. What a tool writes only counts as a result after checking (e.g. %PDF- when unlocking, header and size for raster images).
  • Checked in server/test/werkzeugdienst.test.ts, in image-probe (both architectures: process users, .github/werkzeuge/werkzeuge-pruefen.mjs with a huge PDF), in deploy/komplett-probe.sh (step 2d, also: no access to /data, Ablago's environment and the database as ablago-werkzeug; step 2e: bind mounts of 1026:100 without PUID, PUID set, error page with IDs) and in the update test (folders of the old version belong to Ablago afterwards; an installation from 0.299.0 stays unchanged). The choice of user is checked by server/test/dienstbenutzer.test.ts with dash (take-over and write probe only as root), the dms image by the image-probe (step "Benutzer aus dem Datenordner", both architectures).

Known remaining points

  • Network (#1448): The tools can't reach the network. werkzeug-grenzen.sh starts each through ohne-netz (deploy/image/ohne-netz.c, built statically): a seccomp filter that allows socket() only for AF_UNIX (otherwise EACCES) and blocks io_uring_setup (ENOSYS); a call from a foreign architecture or x32 kills the process. This needs no privilege (no_new_privs is set anyway) and works with Docker's seccomp profile. If the filter can't be set, the tool doesn't start (code 126). The tool service itself also runs through ohne-netz (start-hilfen.sh, with the full path to node), because it has the same ID; it only needs its Unix socket, and libuv works without io_uring. The image probe checks that it has one filter more than Ablago (Seccomp_filters). The status job checks with ohne-netz --pruefen whether a tool can open an IP socket; System status shows "no network".
  • Jobs among each other: Each job has its own folder with 128 bits of randomness in its name (werkzeugOrdner()); arbeit is 3730 (the group may create but not list). All tools still run under the same ID: a taken-over tool can see and read the paths and open files of concurrently running jobs via /proc/<pid>/cmdline, /proc/<pid>/cwd and /proc/<pid>/fd, kill other tools and change the shared heim folder (fontconfig). It can't send anything out, but one job can tamper with or abort another. A user of its own per job would close this but needs a pool of IDs; deliberately deferred.
  • Socket: The dienst folder belongs to ablago-werkzeug, the same ID as the tools. A taken-over tool could replace the socket and pose as the service. That is why Ablago treats everything from the service as untrusted (see above), including exit code and error output.
  • Memory limit: 1024 MB per call can be tight for very large scans (A3/A2 at 300 dpi and above). When the limit hits, the message in the workflow and in the workbench names DMS_WERKZEUG_SPEICHER_MB (speicherFehlerVon in werkzeuggrenzen.ts); otherwise poppler reports it only with exit code 0.

dms-komplett: database folder

deploy/komplett/start.sh starts PostgreSQL and Ablago in the dms-komplett image. For the folder /data/postgres (#943):

  • Permissions: the script hands /data/postgres and /data/postgres/daten to the user postgres (70) and sets both to 700. The parent folder matters: without x on it, postgres can't reach daten, even though root can create everything there (NAS folders with 000). chown/chmod don't abort the start, because they often fail on network shares. Afterwards the script creates a probe file in daten as postgres and deletes it again. If that fails, the start ends before initdb with a message including a link to the installation manual. This is checked in deploy/komplett-probe.sh (step 5b).
  • Not mounted: datenbankOhneVolume() (server/src/datenbank/anbindung.ts) uses aufVolume (like the key file, backup and exports) to check whether /data/postgres is a mount point of its own. If not: an error in the log on start, a red message in the overview (anbindung.ohneVolume, can't be accepted) and under Database connection.
  • Deliberately no VOLUME /data/postgres in the image – why is explained under decisions.
  • Stopping: the template deploy/komplett/docker-compose.yml sets stop_grace_period: 60s so that Ablago and PostgreSQL shut down cleanly. The two-container templates don't need it: the postgres image stops with SIGINT ("fast shutdown") within the usual 10 seconds.

Worker pool

The server answers all requests in one thread. Heavy computing work therefore runs in a small pool of worker threads (node:worker_threads, #542), without a new dependency:

server/src/arbeit/index.ts        arbeite(vorgang, ...args), setting (DMS_ARBEITER), state for system health
server/src/arbeit/pool.ts         worker pool: queue, time limit, memory limit, crash, idle
server/src/arbeit/vorgaenge.ts    what a worker can do: all operations of the PDF place, tables of large exports, demo documents
server/src/arbeit/arbeitsfaden.ts the worker's entry point (built as dist/arbeitsfaden.mjs)
server/src/arbeit/nachricht.ts    messages, Buffers and errors across the boundary
  • Calling: the PDF place passes its operations to the pool itself (pdf/index.ts); for everything else await arbeite('exportTabellen', …). The types of parameters and results come from VORGAENGE.
  • New operation: enter a function with simple data as parameters and result (bytes, numbers, texts, lists, simple objects, Map – no classes, no functions, no repo, no database) in vorgaenge.ts. A Buffer arrives in the worker as a Uint8Array and alsBuffer turns it back into a Buffer – also in lists and simple objects. Fachfehler arrive at the caller with status and details. The worker writes nothing into the log; notices are in the result.
  • What doesn't belong in it: small requests (the handover itself costs something: data is copied, with 20,000 table rows about 0.1–0.3 s) and everything that needs database or files – the main thread fetches the data beforehand.
  • Setting: DMS_ARBEITER (0–16; 0 = off, everything in the main thread), default half of the cores from the cgroup's cpu.max or availableParallelism(), 1 to 4. Time limit 10 minutes, queue at most 50 (above that 503), heap per worker 1.5 GB, idle 2 minutes. Without calling richteArbeiterEin() (tests, command dms) the pool is created with the first job.
  • Tests: server/test/arbeiter.test.ts checks the pool (result, error, time limit, full queue, crash), the setting, the warning on high waiting time and that the Library loads quickly during a large PDF export (values without and with pool are in the output). In tests the worker runs with tsx (load arguments from ladeArgumente).
  • The package runner (laeufer/) is a process of its own with a permission model and stays separate from this.

Warning on high waiting time: Auslastung (messung.ts) remembers the p99 of the event loop delay per minute window. If it is above 100 ms in 5 consecutive windows (SCHLEIFE_GRENZE_MS, SCHLEIFE_MINUTEN in shared/src/systemlast.ts), it writes a warning into the log, and Systemlast.warnung() reports schleife to system health, overview and the Workbench's bar.

External services (#565): One measuring point for everything Ablago waits for at other services: extern in server/src/system/externmessung.ts (one instance per process like the log; start-up sets store and settings, start/betrieb.ts). The connectors only report there: extern.messe({ dienst, funktion }, f) times a call (measuring point with erste(), bytes(), token(), ergebnis()), extern.erfasse(aufruf) takes one already measured – OIDC in Oidc.abruf, SMTP in the transport of betrieb.ts (gemessen), IMAP per session via imapGemessen (when Postfaecher is built), packages in the runner (netzMesser in laeufer/prozess.ts, total as messung in the result, recorded in Paketlaeufer.rufe; AI service is istKiPaket). Only ExternAufruf (shared/src/extern.ts) is stored, with person and estimated cost: raw data in extern_aufrufe (35 days, ROH_TAGE), then condensed into extern_monate (24 months, MONATE; migration 100). Per request the calls go into Kontext.extern and from there into the header Server-Timing (extern, extern-1 …, externTiming); streamed responses ("Ask your library") carry them in the last line (externDerAnfrage). Prices and budget are in the setting extern_kosten; extern.pruefePause(paket) throws 429 "AI features paused until …" before an AI call, extern.pausiertBis(paket) holds back the delivery of events. New connectors only call extern.messe – never content, addresses or URLs in funktion. Test: server/test/extern.test.ts (also: no content in tables, evaluation, log, Server-Timing).

State between requests (#744)

Build rule "keep several servers possible later": whatever applies between two requests lives in PostgreSQL – not in a Map inside one process. Otherwise an attacker with two processes would get twice as many attempts, and the second sign-in step would end up at the wrong process.

  • Building block: Kurzzustand (server/src/zwischenspeicher/kurzzustand.ts, table kurzzustand, migration 078): per entry a kind, key, counter, value and expiry. pgKurzzustand(sql, haushalt) in operation, speicherKurzzustand() in tests and building blocks without a database (same rules, one process). Not in the backup, like the sessions.
  • Counting atomically: zaehle is an INSERT … ON CONFLICT … DO UPDATE … RETURNING with a fixed or sliding window – never read-then-write.
  • Exactly once: nimm (DELETE … RETURNING) for tickets and identifiers; belege/belegeAlle for markers "only once in quick succession" and for claims with a deadline ("at most one check at a time" – if a process ends halfway through, the deadline releases it).
  • Secrets: if the key itself is secret (ticket, state, identifier, session), only its hash is stored (hashe). Secret values (TOTP draft, PKCE verifier, device code, new emergency sheet) are encrypted by the caller with the vault.
  • Schedules: exklusiv(name, f) takes pg_try_advisory_lock(744, hashtext(haushalt:name)) on a connection of its own; if another process holds it, the run doesn't happen here (there is never any waiting). In ablago.ts as nurEiner(…) for the Bin, absences, deadlines (day of the last run also in the short-term state), technical tasks, test restore, RESCUE file, storage transitions and cleaning up the short-term state (every 10 minutes). Daily runs with laufeFaellige (backup, summary, automations) were already safe via the marker in the settings.
  • Sign of life: lebenszeichen(sperren, haushalt) holds a shared lock per process – since #745 only the leader (the process for background work). Only a process that is alone at start-up resets "running" text recognition to interrupted.
  • Lock connection (#1198, server/src/datenbank/sperrverbindung.ts): all session locks of a process – exklusiv of the schedules, package lock 4711405, permanent locks for the intake folder 4711195 and mailboxes 4711196 (sperren.dauerhaft(…).halte()), sign of life – run over one connection of their own outside the pool (eigeneSperrquelle(url): a client with max: 1, without max_lifetime/idle_timeout). Never sql.reserve() for a lock while work runs again: the work itself needs connections from the pool, and with a full pool it deadlocked (#1198: 3 permanent locks + 7 schedules = 10). Queries on it run one after another with a time limit (SPERRABFRAGE_MS); it rejects duplicate locks in the same process itself (PostgreSQL would count them in the same session). On loss: all locks lost, warning in the log, running work carries on, permanent locks take theirs again on the next halte(), the sign of life by itself. Without locks it closes the connection. pgKurzzustand(sql, h) without a lock connection takes one from the pool (tests). Schedules start staggered (wiederkehrend(name, ms, f), server/src/zeitplan/streuung.ts).
  • Compare and swap instead of overwriting where two processes change the same value: last TOTP step and used recovery codes (zweifaktor.ts), passkey counters (passkeys.ts), renewed token of the mailbox sign-in (postfach-oauth.ts), toggling maintenance mode (wartung.ts, now reads the state from the database at every check).
What Kind(s) in the short-term state
Sign-in protection: failed attempts per account and IP, per IP, IP blocks, collective and immediate notification anmeldung-konto, anmeldung-ip, anmeldung-ip-sperre, anmeldung-meldung, anmeldung-sammelmeldung, anmeldung-sofortmeldung
Second sign-in step, setting up two-factor zweiter-schritt, zweifaktor-entwurf
Passkeys (#811): challenge when adding and when signing in, counter per address passkey-neu, passkey-anmeldung, passkey-anmeldung-offen, passkey-optionen-adresse
Retrieval page: tickets, failed attempts per scope, one check per link abruf-ticket, abruf-fehler, abruf-pruefung
OIDC, mailbox OAuth (callback, device code) oidc-anmeldung, postfach-oauth-code, postfach-oauth-geraet
WebDAV: counting windows, pending files webdav-fenster, webdav-schwebend
Protected PDFs: failed attempts, confirmation for document passwords pdf-passwort-fehler, dokumentpasswort-bestaetigt, dokumentpasswort-fehler
Emergency access: block and claim per scope, notification, new sheet notfall-sperre, notfall-pruefung, notfall-fehlversuche, notfall-gemeldet, notfall-blatt, notfall-blatt-erzeugen
Trail in administration mode, personal export, deadline run modusspur, eigener-export-laeuft, eigener-export-fehler, fristen-tag
Workbench jobs (#745): claim with deadline, progress, cancelling; own changes to the counters (#742, #745) auftrag (lauf, stand, abbruch:<id>), eigene-aenderung

May stay per process (at most makes things slower, never wrong): caches for page images and PDF display, stamped WebDAV versions (#722: at most 64 MB or 2000 entries; since #874 several processes share the bytes, zwischenspeicher.ts), protection type per PDF, the provider's discovery and keys (OIDC), settings read with a short lifetime (sign-in protection 10 s, WebDAV 5 s, OIDC 30 s), requests to packages "already requested", limits on concurrent work that protect this process's computing time (scrypt on the retrieval page, uploads per user, questions), metrics and load. What #744 left open for several processes is solved by #745 (Several processes).

Several processes (#745)

DMS_PROZESSE (auto = 2 processes from 4 cores and 8 GB, otherwise 1 – PROZESSE_EMPFOHLEN_MAX, ZWEI_PROZESSE_KERNE_AB, ZWEI_PROZESSE_SPEICHER_AB –, and no more than DMS_DB_VERBINDUNGEN carries; cores and memory from the container's cgroup limits, at most the computer (nutzbar); without the variable like auto (autoVorgabe; with DMS_VARIANTE=komplett since #1259, in the image dms since #1309); prozesseAus/empfohleneProzesse in server/src/prozesse/prozesse.ts, #874). With 1, everything runs in one process as before.

  • Entry point: server/src/index.ts is now only the switch. With more than one process it becomes the lean main process (leite, doesn't load Ablago) and uses node:cluster to start the processes, which begin in index.ts again and load ablago.ts (the former index.ts). In the build, dist/ablago.js is a separate file; the import in index.ts therefore has no fixed path.
  • Roles: process 1 is the leader. It starts first – verbund.erster: start page (#802), migrations, one-off work at start-up – and reports "ready"; only then does the main process start the others (without start page and migrations). If the leader doesn't come up before its first "ready", the main process ends with its code (as before: Docker restarts; the downgrade lock stays in place). After that the main process restarts crashed processes (neustartWarten: 1 s, doubled up to 60 s, back to 1 s after 5 minutes of running), the leader too (then without start page). The main process's log only contains number, code and signal.
  • Group (Verbund in prozesse.ts): rufe (call to the leader with result, parts and domain errors including status), melde (to the leader, to all, to the others), frageAlle (e.g. prozess.stand), bereit, beendeAlle (restart after a restore, changed database connection, end of the load test). The main process only passes things on (IPC with serialization: 'advanced', so buffers and Float32Array too). With one process, einzeln() does everything in its own.
  • What the leader does for the others (server/src/prozesse/aufteilung.ts): triggers for text recognition, thumbnails and the event dispatcher go to it as a message – the others process none of that themselves (a dispatcher without the automations' consumers would have marked events as dispatched). Starting backup, checksum, test and restore, fetching the mailbox, checking intake folders and catching up on thumbnails are calls to the leader; it mirrors running backups and restores to all every second (laeuft() and aktuellerLauf() without waiting, up to one second old). Whatever a route shows as status and only the leader updates, the others ask the leader for (#1341): the progress of backup, checksum, test and restore (laufStand()), the status of the intake folder and of text recognition; rescheduling the intake folder after saving happens only in the leader (no timer in the others), and "restart needed" for the database connection comes from the file – otherwise the workbench showed progress or "no run" depending on the process.
  • Package runner exactly once, in the leader – it holds the packages' API keys. The others use Fernlaeufer (server/src/laeufer/fern.ts): actions, vectors, "Ask your library" (parts of the answer come as parts of the call), "Fill in from document", overview. What they need without waiting (which package offers what, the packages' service accounts) the leader sends as a snapshot on every change.
  • Workbench jobs (Auftraege.teile): the job runs in the process that accepted it. "Only one at a time" is a claim in the short-term state with a 60 s deadline that the running process extends every second; it also writes the progress, and stand() reads it everywhere. Cancelling from another process sets a marker. Routes with 202 wait with angemeldet() until the progress is visible to all. If the process dies, the progress shows "Interrupted".
  • Uploaded packages are kept until installation (30 minutes) under files/hochladen/pakete/ (archive and details, 0600, name from the hash of the identifier) and are read again by the other process with the same checks.
  • Own changes to the counters (#742): after the household version is incremented, the new version per person is briefly kept in the short-term state (eigene-aenderung); another process only asks for it if the minimum validity would otherwise apply.
  • Settings in memory (encryption key, email sending, OIDC, timing threshold): every process reads the household version lesen every 2 seconds; if it changes, Tresor.nachladen, Betrieb.nachladen, Oidc.vergiss and Messung.start reload. If key file and fingerprint don't match at that moment (a change in another process), the next tick tries again.
  • Per process: overload protection, workers (default divided by the number of processes). Shared (#874): connections – DMS_DB_VERBINDUNGEN applies to all together (default verbindungenVorgabe: 10 + 4 per further process), verbindungsaufteilung first gives the leader 4 connections in advance – since #1198 one for the lock connection (poolGroesse: its pool is smaller by it), the rest for its background work (before, it held 3 of them permanently for session locks), all share the rest equally (each further one at least 2, the leader at least 6 in total), together at most max_connections − 10; caches – teileZwischenspeicher(anzahl) gives each process 1/anzahl of the limits of PDF display, WebDAV stamps and page images. Heap: the main process starts every process with --max-old-space-size (haldeJeProzess: the further ones with 60 % of their share of the memory, 1024–1536 MB; haldeLeiter, #891: the leader with 512 MB more, because it also does the work in the background) unless it is already set or only one process runs; the main process itself stays without a limit. The start-up log names both values (haldeLeiterMb, haldeMb). Restarts are counted by the main process (Verbund.neustarts(): number and the last ten with number, code, signal) and sent to all with the list of processes. The dms command uses a shared key from the main process; the leader writes the file. At start-up, a process only deletes temporary uploads next to others if they are older than 6 hours.
  • System health: frageAlle('prozess.stand') returns RSS, CPU time, event loop delay and running requests per process; plus Pss from /proc. For the load test, /api/werkbank/last asks prozess.last: the same plus the waiting time for connections (Poolmessung, #874), which this switches on; plus the restarts. /api/werkbank/last reports the memory of all processes together (including the main process) and the delay of the slowest, per process under engpass.speicher. Since #920 the load test limit (1.5 GB) applies per process; it compares the sum with the limit × processes.
  • Load test mode: if the leader is measuring, the others also only listen on the internal port (listen(0) shares the same port under cluster).
  • Tests: prozesse.test.ts (setting, group with a real cluster via test/hilfen-prozesse.ts, triggers, remote runner, uploads, counters, jobs, keys), prozesse-e2e.test.ts (all of Ablago with two processes: start page, migration once, system health, console, job, crash with restart without signing out, shutdown, downgrade).