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 inserver/src/repo/index.ts– since #1278 put together from sub-interfaces per subject area inrepo/schnittstelle/(RepoMappen,RepoPakete,RepoDokumente,RepoPapierkorb,RepoVolltext,RepoAufgaben; types and helpers inschnittstelle/typen.ts), imports of…/repostay the same. Both are split by subject area (#1278:pg/mappen.tsandspeicher/mappen.ts,pg/dokumente.tsandspeicher/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 inpg/index.tsandspeicher/index.ts. A new method goes into the same subject-area file on both sides. Most tests run quickly in memory; the tests withTEST_DATABASE_URLcover 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 withzugang: 'offen' | 'angemeldet' | 'admin'. Each file exports functions…Routen(k)that receive the services and shared helpers via the parameterk(http/routen-kontext.ts; helpers without services inhttp/routen-hilfen.ts).routen()inserver/src/http/routen.tscalls them in a fixed order (BEREICHE) and still holds the types (Route,Anfrage,Antwort),pruefeZugangand the check of package permissions; the testrouten-liste.test.tschecks that every route is listed with itszugangin 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 tooffen– goes into this list on purpose and gets a one-sentence justification in the pull request; otherwise the test fails. The helpers inhttp/routen-hilfen.tsandhttp/routen-kontext.tsmay only be imported by route files (*.routen.ts,routen.ts) (npm run lint:abh, rulerouten-hilfen-nur-in-routen). Two features are added:api: truemakes a route part of the public API (sign-in also with an API key);konsole: trueonly allows it via the commanddmsin 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 inserver/src/werkbank/verwaltungsbereiche.ts(bereicheDerRoute) – otherwise only people with "Full administration" may use it, and the testverwaltungsmodus.test.tsfails. Sensitive actions that require a fresh sign-in are listed there inheikleHandlung.benutzer.rolleis the request's effective role (adminonly in the mode); the stored permission is inbenutzer.verwaltung(shared/src/verwaltungsrecht.ts). API keys never getadmin. - 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 (tablenotfallcode), 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.tsopens 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 viameta refresh, no script),/api/*and/webdavanswer503withRetry-Afterandstartet: true(the interface counts that as an outage and waits),/api/gesundheitreports503withzustand: startet|fehler. It only releases the port immediately beforeapp.listen(and in between for setup mode). An error at start-up lands on the page viauncaughtException– 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 aStartschrittof their own (text inshared/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.shfirst starts the pre-start (dist/vorstart.js, a bundle of its own without database). It shows the same page with the step fromDMS_VORSTART_DATEI(one line:pg-anlegen,pg-start,ablagoorfehler <reason>), listens withreusePortand reports/api/gesundheitwithout the state identifier. Ablago getsDMS_VORSTART_PIDandDMS_VORSTART_SEIT, also listens withreusePortand only then sendsSIGTERMto 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 forDMS_START_FEHLER_WARTEN_S(default 300), then the container ends.datenbankGrund()interprets "unreachable or blocked" from the error code only (connection refused, lock55P03/40P01, storage full53100, too many connections53300); the page adds the way out. Ablago tries an unreachable database 30 times every 2 s (stepdatenbank-warten); if another Ablago holds the migration lock, the page showssperre. The page's language followsAccept-Language(de, otherwise en). Tests:server/test/vorstart.test.ts, in the imagedeploy/komplett-probe.sh(steps 1 and 5). - Uploads as a stream (#746,
server/src/dateien/hochladen.ts): routes withstrom: 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 underfiles/hochladen/(0600, checksum and header while reading);bodyis then aHochgeladen. ViaEingang.aus()the service treats upload or buffer alike; filing happens by renaming (Dateispeicher.uebernimm). WebDAV PUT usesnimmAufdirectly. 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.nulldeletes an entry. - Recognising the home network (#595): whether an address is in the home network is decided only by
shared/src/heimnetz.ts(imHeimnetz, listHEIMNETZ_ENDUNGENwith.local,.lan,.internal,.home.arpa). Kindausnahme(strict) allowshttp://without TLS – sign-in via a provider, endpoints of mailboxes with an own provider; kindhinweis(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" (onlylocalhost) 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()fromshared/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 viabeiVerklemmungWiederholen(server/src/datenbank/db.ts, repeats on 40P01/40001) – as a transaction of its own orsql.begin(inside a transaction a savepoint). Test:server/test/verklemmung.test.ts. - Backup and restore back up all tables except the content of
sitzungenandschema_migrationen(OHNE_INHALTinserver/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_pruefenanddaten_kennunginstart-hilfen.sh): ifPUIDandPGIDare not set, the script takes owner and group of the data folder –/dataif it is mounted itself, otherwise the first mounted one offiles,geheim,sicherung,export. "Mounted" means: a mount point in/proc/self/mountinfo; the image's own/datafolder (1000:1000) does not count.kennung_tauglichrejects 0 as user or group, likewise 61000 (tools) and the IDs ofpostgres(its socket usestrust). If no folder fits, 1000:1000 applies with reasonroot,systemorohne. IfPUIDorPGIDis set, that applies as before (the missing value 1000);PUID=0only works explicitly, with a warning. The choice goes to Ablago and the pre-start asPUID/PGID,DMS_KENNUNG_HERKUNFT(daten,vorgabe,gesetztfor user and group),DMS_KENNUNG_GRUNDandDMS_RECHTE_MERKER, and into the marker (kennung, readable by everyone:ablago-alsreads it there becausedocker execonly 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, withoutPUID/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. WithPUID/PGID, as before, everything not owned by exactlyPUID:PGID. Folders without a volume of their own only live in the container and belong entirely to Ablago afterwards.o-rwxonly on one of the four folders that the script created or just took over; folders of the NAS user stay as they are. Ingeheim, files the group or others could read or write getgo-rwx(mandatory, keys live there). Every change on a volume writesaenderunginto the marker (aenderungen: time, kindbesitzer-root/besitzer/rechte/geheim, folder, count, new owner). Then a write probe as Ablago; if it fails, the script writes the folders it saw intofehler(name, owner, mode,:rofrommountinfo) and a suitable suggestion intovorschlag, the log names the same lines, and the pre-start shows reasondaten-rechte. In the inbox folder it only takes over what belongs to root. - Display (
server/src/einrichtung/dienstbenutzer.ts, sentences inshared/src/dienstbenutzer.ts): reads environment and marker strictly (known kinds, numbers, paths under/dataand/eingangonly). 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; fordaten-rechtethe IDs seen and ready-made lines (PUID/PGID,chown,:ro). The system status (/api/werkbank/system,laufzeit.dienstbenutzer) anddms statusname user, group, origin and all changes of this container. - Why no longer
o-rwxon all four folders: it protected the folders from the tool user. But Ablago creates the files in them for itself only anyway (0600, folders0700: 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-rwxon a folder of the NAS user takes access away from other users of the share, andchmodmay 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(forPUID/PGID), a supplementary group for the tool service andno_new_privs.su-execcannot set a supplementary group for a numeric ID norno_new_privs; the script would have to rewrite/etc/passwd. busybox'ssetprivdoes 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 withno-new-privileges). So while it is still root, the start script launches a small service asablago-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/spawnfromserver/src/prozesse/hintergrund.tsbehave likenode:child_process(ENOENT,killed,maxBuffer,signal); working folders come fromwerkzeugOrdner(). The service only starts programs fromWERKZEUGE(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
ulimitin the fixed launcherdeploy/image/werkzeug-grenzen.sh(ulimit -v …; ulimit -t …; ulimit -f …; exec "$@", nosh -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.prlimitwould be equivalent but needsutil-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: ownpg_hba.conf(deploy/komplett/pg_hba.conf, viahba_file, also for existing databases): socket withtrust, but the folder is only forpostgres(and root); over127.0.0.1onlyscram-sha-256.start.shsets the password of thedmsrole on every start (viapsql's standard input) and hands it only to Ablago (DMS_DB_KOMPLETT_PASSWORT, inserted inalsUrl, never indatenbank.json).dmsis no longer a superuser;start.shcreatespg_trgmandunaccentaspostgresinerweiterungen_dms, anddmsgetspg_read_all_stats,pg_read_all_settingsandpg_stat_statements_resetfor 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 … dmsswitches to the Ablago user viaablago-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 throughliesWerkzeugDatei(O_NOFOLLOW,O_NONBLOCK, on the open handle: regular file, one link, size limited),schreibeWerkzeugDatei(remove an existing entry, then only create anew withwx) andwerkzeugDateien(only regular files fromwithFileTypes), all inserver/src/prozesse/hintergrund.ts. New code usingwerkzeugOrdner()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:maxBufferlimits 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, inimage-probe(both architectures: process users,.github/werkzeuge/werkzeuge-pruefen.mjswith a huge PDF), indeploy/komplett-probe.sh(step 2d, also: no access to/data, Ablago's environment and the database asablago-werkzeug; step 2e: bind mounts of 1026:100 withoutPUID,PUIDset, 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 byserver/test/dienstbenutzer.test.tswith dash (take-over and write probe only as root), thedmsimage 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.shstarts each throughohne-netz(deploy/image/ohne-netz.c, built statically): a seccomp filter that allowssocket()only forAF_UNIX(otherwiseEACCES) and blocksio_uring_setup(ENOSYS); a call from a foreign architecture or x32 kills the process. This needs no privilege (no_new_privsis 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 throughohne-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 withohne-netz --pruefenwhether 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());arbeitis3730(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>/cwdand/proc/<pid>/fd, kill other tools and change the sharedheimfolder (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
dienstfolder belongs toablago-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(speicherFehlerVoninwerkzeuggrenzen.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/postgresand/data/postgres/datento the userpostgres(70) and sets both to700. The parent folder matters: withoutxon it,postgrescan't reachdaten, even though root can create everything there (NAS folders with000).chown/chmoddon't abort the start, because they often fail on network shares. Afterwards the script creates a probe file indatenaspostgresand deletes it again. If that fails, the start ends beforeinitdbwith a message including a link to the installation manual. This is checked indeploy/komplett-probe.sh(step 5b). - Not mounted:
datenbankOhneVolume()(server/src/datenbank/anbindung.ts) usesaufVolume(like the key file, backup and exports) to check whether/data/postgresis 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/postgresin the image – why is explained under decisions. - Stopping: the template
deploy/komplett/docker-compose.ymlsetsstop_grace_period: 60sso that Ablago and PostgreSQL shut down cleanly. The two-container templates don't need it: thepostgresimage stops withSIGINT("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 elseawait arbeite('exportTabellen', …). The types of parameters and results come fromVORGAENGE. - 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) invorgaenge.ts. ABufferarrives in the worker as aUint8ArrayandalsBufferturns it back into aBuffer– also in lists and simple objects.Fachfehlerarrive 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'scpu.maxoravailableParallelism(), 1 to 4. Time limit 10 minutes, queue at most 50 (above that 503), heap per worker 1.5 GB, idle 2 minutes. Without callingrichteArbeiterEin()(tests, commanddms) the pool is created with the first job. - Tests:
server/test/arbeiter.test.tschecks 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 withtsx(load arguments fromladeArgumente). - 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, tablekurzzustand, 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:
zaehleis anINSERT … ON CONFLICT … DO UPDATE … RETURNINGwith a fixed or sliding window – never read-then-write. - Exactly once:
nimm(DELETE … RETURNING) for tickets and identifiers;belege/belegeAllefor 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)takespg_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). Inablago.tsasnurEiner(…)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 withlaufeFaellige(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 –exklusivof the schedules, package lock4711405, permanent locks for the intake folder4711195and mailboxes4711196(sperren.dauerhaft(…).halte()), sign of life – run over one connection of their own outside the pool (eigeneSperrquelle(url): a client withmax: 1, withoutmax_lifetime/idle_timeout). Neversql.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 nexthalte(), 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.tsis now only the switch. With more than one process it becomes the lean main process (leite, doesn't load Ablago) and usesnode:clusterto start the processes, which begin inindex.tsagain and loadablago.ts(the formerindex.ts). In the build,dist/ablago.jsis a separate file; the import inindex.tstherefore 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 (
Verbundinprozesse.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 withserialization: 'advanced', so buffers andFloat32Arraytoo). 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()andaktuellerLauf()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, andstand()reads it everywhere. Cancelling from another process sets a marker. Routes with 202 wait withangemeldet()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
lesenevery 2 seconds; if it changes,Tresor.nachladen,Betrieb.nachladen,Oidc.vergissandMessung.startreload. 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_VERBINDUNGENapplies to all together (defaultverbindungenVorgabe: 10 + 4 per further process),verbindungsaufteilungfirst 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 mostmax_connections− 10; caches –teileZwischenspeicher(anzahl)gives each process1/anzahlof 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. Thedmscommand 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/lastasksprozess.last: the same plus the waiting time for connections (Poolmessung, #874), which this switches on; plus the restarts./api/werkbank/lastreports the memory of all processes together (including the main process) and the delay of the slowest, per process underengpass.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 undercluster). - Tests:
prozesse.test.ts(setting, group with a realclusterviatest/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).