Files
ProcessControl/02-part-ii-processes.qmd
T
2026-09-25 13:33:30 +02:00

362 lines
22 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# [Part II — Cross the process boundary]{.en}[Partie II — Franchir la frontière de processus]{.fr}[Teil II — Die Prozessgrenze überschreiten]{.de} {#sec-part-ii}
<!-- MULTILINGUAL: see the comment at the top of index.qmd. -->
::: {.en}
Steps 11 to 18 take the architecture of part I and split it across five operating-system processes on one computer. The capabilities keep their mailbox names; only the transport underneath changes, from Java objects to files in directories. The first genuinely distributed problem shows up here, and it has nothing to do with ROT13.
:::
::: {.fr}
Les étapes 11 à 18 reprennent l'architecture de la partie I et la répartissent sur cinq processus du système d'exploitation, sur un seul ordinateur. Les capacités gardent leurs noms de boîtes ; seul le transport en dessous change, des objets Java vers des fichiers dans des répertoires. Le premier problème réellement distribué apparaît ici, et il n'a rien à voir avec ROT13.
:::
::: {.de}
Die Schritte 11 bis 18 nehmen die Architektur aus Teil I und verteilen sie auf fünf Betriebssystemprozesse auf einem Rechner. Die Fähigkeiten behalten ihre Postfachnamen; nur der Transport darunter wechselt, von Java-Objekten zu Dateien in Verzeichnissen. Das erste wirklich verteilte Problem tritt hier auf, und es hat nichts mit ROT13 zu tun.
:::
## [Step 11 — Separate the components]{.en}[Étape 11 — Séparer les composants]{.fr}[Schritt 11 — Die Komponenten trennen]{.de} {#sec-step-11}
::: {.en}
Three processes cannot share a `BlockingQueue`: every `java` command starts its own JVM with its own memory, so the `mailboxes` map would exist three times and each copy would see only its own messages. An external transport is needed.
TCP would do, MQTT would do. The tutorial deliberately picks the most primitive option, the **filesystem**, and gives a one-line reason: *because you can see it*. Messages become files you can list with `ls` and read with `cat` while the system runs. Primitive here does not mean inferior; part VIII comes back to what the filesystem is genuinely good and bad at.
:::
::: {.fr}
Trois processus ne peuvent pas partager une `BlockingQueue` : chaque commande `java` démarre sa propre JVM avec sa propre mémoire, la carte `mailboxes` existerait donc en trois exemplaires et chacun ne verrait que ses propres messages. Il faut un transport externe.
TCP conviendrait, MQTT conviendrait. Le tutoriel choisit délibérément l'option la plus primitive, le **système de fichiers**, avec une raison en une ligne : *parce qu'on peut le voir*. Les messages deviennent des fichiers que l'on peut lister avec `ls` et lire avec `cat` pendant que le système tourne. Primitif ne veut pas dire inférieur : la partie VIII revient sur ce que le système de fichiers fait vraiment bien et vraiment mal.
:::
::: {.de}
Drei Prozesse können keine `BlockingQueue` teilen: jeder `java`-Befehl startet seine eigene JVM mit eigenem Speicher, die `mailboxes`-Map existierte also dreimal, und jede Kopie sähe nur ihre eigenen Nachrichten. Ein externer Transport ist nötig.
TCP würde gehen, MQTT würde gehen. Das Tutorial wählt absichtlich die primitivste Möglichkeit, das **Dateisystem**, mit einer einzeiligen Begründung: *weil man es sehen kann*. Nachrichten werden Dateien, die man mit `ls` auflisten und mit `cat` lesen kann, während das System läuft. Primitiv heisst hier nicht schlechter; Teil VIII kommt darauf zurück, was das Dateisystem wirklich gut und wirklich schlecht kann.
:::
## [Steps 12–13 — A directory becomes a mailbox]{.en}[Étapes 12–13 — Un répertoire devient une boîte aux lettres]{.fr}[Schritte 12–13 — Ein Verzeichnis wird zum Postfach]{.de} {#sec-steps-12-13}
::: {.en}
The mapping is one line long:
```text
directory = mailbox file = message
publish = create file receive = watch directory
```
```text
messageBoard/
├── consoleIn/outbox/
├── rot13/inbox/
├── rot13/outbox/
└── consoleOut/inbox/
```
The `Message` record gains an optional timestamp, and the file format stays two lines plus an optional third:
```text
TEXT
Hello World
TIMESTAMP: 2026-09-22T10:42:12.123Z
```
A message written by hand may leave the timestamp out. The `TIMESTAMP: ` marker keeps a payload line that happens to look like a date from being mistaken for metadata; in this tiny format, a final line starting with `TIMESTAMP: ` is reserved.
Jackson could be introduced here and deliberately is not. The point of a ridiculously simple format is that almost nothing hides the architecture — the whole message is readable in any text editor, which is what keeps the attention on who talks to whom.
:::
::: {.fr}
La correspondance tient en une ligne :
```text
directory = mailbox file = message
publish = create file receive = watch directory
```
```text
messageBoard/
├── consoleIn/outbox/
├── rot13/inbox/
├── rot13/outbox/
└── consoleOut/inbox/
```
Le record `Message` gagne un horodatage optionnel, et le format de fichier reste deux lignes plus une troisième facultative :
```text
TEXT
Hello World
TIMESTAMP: 2026-09-22T10:42:12.123Z
```
Un message écrit à la main peut omettre l'horodatage. Le marqueur `TIMESTAMP: ` empêche qu'une ligne de contenu ressemblant à une date soit prise pour une métadonnée ; dans ce format minuscule, une dernière ligne commençant par `TIMESTAMP: ` est réservée.
Jackson pourrait être introduit ici et ne l'est volontairement pas. L'intérêt d'un format ridiculement simple, c'est que presque rien ne cache l'architecture — le message entier est lisible dans n'importe quel éditeur de texte, ce qui maintient l'attention sur qui parle à qui.
:::
::: {.de}
Die Zuordnung ist eine Zeile lang:
```text
directory = mailbox file = message
publish = create file receive = watch directory
```
```text
messageBoard/
├── consoleIn/outbox/
├── rot13/inbox/
├── rot13/outbox/
└── consoleOut/inbox/
```
Der `Message`-Record erhält einen optionalen Zeitstempel, und das Dateiformat bleibt zwei Zeilen plus eine optionale dritte:
```text
TEXT
Hello World
TIMESTAMP: 2026-09-22T10:42:12.123Z
```
Eine handgeschriebene Nachricht darf den Zeitstempel weglassen. Die Marke `TIMESTAMP: ` verhindert, dass eine Inhaltszeile, die zufällig wie ein Datum aussieht, für Metadaten gehalten wird; in diesem winzigen Format ist eine letzte Zeile, die mit `TIMESTAMP: ` beginnt, reserviert.
Jackson könnte hier eingeführt werden und wird es absichtlich nicht. Der Sinn eines lächerlich einfachen Formats ist, dass fast nichts die Architektur verdeckt — die ganze Nachricht ist in jedem Texteditor lesbar, was die Aufmerksamkeit darauf hält, wer mit wem spricht.
:::
## [Step 14 — The first distributed-systems problem: publication]{.en}[Étape 14 — Le premier problème de système distribué : la publication]{.fr}[Schritt 14 — Das erste Problem verteilter Systeme: die Veröffentlichung]{.de} {#sec-step-14}
::: {.en}
A reader watching a directory can discover a file *before the writer has finished writing it*. Hence a publication protocol:
1. create a private temporary file;
2. write the complete message;
3. close it;
4. atomically rename it to its final `.msg` name;
5. consumers react only to final files.
```java
Files.writeString(temporary, content);
Files.move(temporary, published, StandardCopyOption.ATOMIC_MOVE);
```
Both halves are needed. The rename is atomic — a reader sees either no `.msg` file or the complete one — but it protects nothing if readers also pick up `.tmp` files. `.tmp` and `.msg` stay in the same directory so the move cannot cross filesystems, where atomicity would be lost.
> **Writing and publishing are not the same operation.**
:::
::: {.fr}
Un lecteur qui surveille un répertoire peut découvrir un fichier *avant que l'écrivain ait fini de l'écrire*. D'où un protocole de publication :
1. créer un fichier temporaire privé ;
2. écrire le message complet ;
3. le fermer ;
4. le renommer atomiquement vers son nom final `.msg` ;
5. les consommateurs ne réagissent qu'aux fichiers finaux.
```java
Files.writeString(temporary, content);
Files.move(temporary, published, StandardCopyOption.ATOMIC_MOVE);
```
Les deux moitiés sont nécessaires. Le renommage est atomique — un lecteur voit soit aucun fichier `.msg`, soit le fichier complet — mais il ne protège rien si les lecteurs ramassent aussi les `.tmp`. `.tmp` et `.msg` restent dans le même répertoire, pour que le déplacement ne traverse pas de système de fichiers, où l'atomicité serait perdue.
> **Écrire et publier ne sont pas la même opération.**
:::
::: {.de}
Ein Leser, der ein Verzeichnis beobachtet, kann eine Datei entdecken, *bevor der Schreiber sie fertig geschrieben hat*. Daher ein Veröffentlichungsprotokoll:
1. eine private temporäre Datei erzeugen;
2. die vollständige Nachricht schreiben;
3. sie schliessen;
4. sie atomar auf ihren endgültigen `.msg`-Namen umbenennen;
5. Konsumenten reagieren nur auf endgültige Dateien.
```java
Files.writeString(temporary, content);
Files.move(temporary, published, StandardCopyOption.ATOMIC_MOVE);
```
Beide Hälften sind nötig. Das Umbenennen ist atomar — ein Leser sieht entweder keine `.msg`-Datei oder die vollständige —, aber es schützt nichts, wenn Leser auch `.tmp`-Dateien aufgreifen. `.tmp` und `.msg` bleiben im selben Verzeichnis, damit der Verschiebevorgang kein Dateisystem überschreitet, wo die Atomarität verloren ginge.
> **Schreiben und Veröffentlichen sind nicht dieselbe Operation.**
:::
## [Step 15 — Observe a mailbox with `WatchService`]{.en}[Étape 15 — Observer une boîte avec `WatchService`]{.fr}[Schritt 15 — Ein Postfach mit `WatchService` beobachten]{.de} {#sec-step-15}
::: {.en}
Java's own filesystem observer supplies the consumer half: register a directory for `ENTRY_CREATE`, block in `watcher.take()`, and ignore every filename that does not end in `.msg`.
That also gives a low-tech injection tool. With `ActuatorService` running as the consumer:
```bash
printf 'TEXT\nHello from a file' > messageBoard/consoleOut/inbox/manual.tmp
mv messageBoard/consoleOut/inbox/manual.tmp messageBoard/consoleOut/inbox/manual.msg
```
**Observed:** nothing happens when the `.tmp` file appears; the line is printed the moment the rename creates the `.msg` name. Both accepted formats work, with and without the trailing timestamp.
The architectural lesson is the one the tutorial draws as `producer → filesystem → consumer`: the consumer could not tell a human typing `mv` from a real service. It knows its own inbox, not who writes into it. Egoism survived the process boundary.
:::
::: {.fr}
L'observateur de système de fichiers de Java fournit la moitié consommateur : enregistrer un répertoire pour `ENTRY_CREATE`, se bloquer dans `watcher.take()`, et ignorer tout nom de fichier qui ne finit pas par `.msg`.
Cela donne aussi un outil d'injection très rudimentaire. Avec `ActuatorService` lancé comme consommateur :
```bash
printf 'TEXT\nHello from a file' > messageBoard/consoleOut/inbox/manual.tmp
mv messageBoard/consoleOut/inbox/manual.tmp messageBoard/consoleOut/inbox/manual.msg
```
**Observé :** rien ne se passe à l'apparition du fichier `.tmp` ; la ligne est affichée à l'instant où le renommage crée le nom `.msg`. Les deux formats acceptés fonctionnent, avec et sans horodatage final.
La leçon architecturale est celle que le tutoriel formule comme `producer → filesystem → consumer` : le consommateur n'a pas pu distinguer un humain tapant `mv` d'un véritable service. Il connaît sa propre boîte d'entrée, pas qui y écrit. L'égoïsme a survécu à la frontière de processus.
:::
::: {.de}
Javas eigener Dateisystem-Beobachter liefert die Konsumentenhälfte: ein Verzeichnis für `ENTRY_CREATE` registrieren, in `watcher.take()` blockieren und jeden Dateinamen ignorieren, der nicht auf `.msg` endet.
Das ergibt auch ein sehr einfaches Einspeisewerkzeug. Mit `ActuatorService` als laufendem Konsumenten:
```bash
printf 'TEXT\nHello from a file' > messageBoard/consoleOut/inbox/manual.tmp
mv messageBoard/consoleOut/inbox/manual.tmp messageBoard/consoleOut/inbox/manual.msg
```
**Beobachtet:** beim Auftauchen der `.tmp`-Datei geschieht nichts; die Zeile erscheint in dem Moment, in dem das Umbenennen den `.msg`-Namen erzeugt. Beide erlaubten Formate funktionieren, mit und ohne abschliessenden Zeitstempel.
Die architektonische Lehre ist die, die das Tutorial als `producer → filesystem → consumer` zieht: der Konsument konnte einen Menschen, der `mv` tippt, nicht von einem echten Dienst unterscheiden. Er kennt sein eigenes Eingangspostfach, nicht den, der hineinschreibt. Der Egoismus hat die Prozessgrenze überlebt.
:::
## [Steps 16–17 — Services and mediator become processes]{.en}[Étapes 16–17 — Services et médiateur deviennent des processus]{.fr}[Schritte 16–17 — Dienste und Vermittler werden Prozesse]{.de} {#sec-steps-16-17}
::: {.en}
The three capabilities become three programs, and the mediator a fourth kind of program:
| program | plays | reads | writes |
|---|---|---|---|
| `SensorService.java` | ConsoleIn | the keyboard | `consoleIn/outbox` |
| `ProcessorService.java` | ROT13 | `rot13/inbox` | `rot13/outbox` |
| `ActuatorService.java` | ConsoleOut | `consoleOut/inbox` | the console |
| `Mediator.java <from> <to>` | the glue | `<from>` | `<to>` |
The mediator is generic: its route is not compiled in, it arrives as two startup arguments. But the tutorial points at an asymmetry worth keeping in mind: the three capabilities receive their **work** as messages in a mailbox, while the mediator receives its **route** as startup configuration, and it has no name and no control mailbox of its own that anyone could write to.
The practical consequence: arguments are read once, so changing the route of a running mediator means stopping it and starting it again. A configuration file would be no different — it is still read at startup. The tutorial deliberately leaves this unfixed until the cost of the distributed mediators has been felt.
:::
::: {.fr}
Les trois capacités deviennent trois programmes, et le médiateur un quatrième type de programme :
| programme | joue | lit | écrit |
|---|---|---|---|
| `SensorService.java` | ConsoleIn | le clavier | `consoleIn/outbox` |
| `ProcessorService.java` | ROT13 | `rot13/inbox` | `rot13/outbox` |
| `ActuatorService.java` | ConsoleOut | `consoleOut/inbox` | la console |
| `Mediator.java <from> <to>` | la colle | `<from>` | `<to>` |
Le médiateur est générique : sa route n'est pas compilée en dur, elle arrive en deux arguments de démarrage. Mais le tutoriel signale une asymétrie à garder en tête : les trois capacités reçoivent leur **travail** sous forme de messages dans une boîte, tandis que le médiateur reçoit sa **route** comme configuration de démarrage, et il n'a ni nom ni boîte de contrôle propre où quelqu'un pourrait écrire.
Conséquence pratique : les arguments sont lus une seule fois, donc changer la route d'un médiateur en cours d'exécution exige de l'arrêter et de le relancer. Un fichier de configuration ne changerait rien — il est lui aussi lu au démarrage. Le tutoriel laisse volontairement ce point ouvert jusqu'à ce que le coût des médiateurs distribués ait été ressenti.
:::
::: {.de}
Die drei Fähigkeiten werden drei Programme, und der Vermittler eine vierte Art Programm:
| Programm | spielt | liest | schreibt |
|---|---|---|---|
| `SensorService.java` | ConsoleIn | die Tastatur | `consoleIn/outbox` |
| `ProcessorService.java` | ROT13 | `rot13/inbox` | `rot13/outbox` |
| `ActuatorService.java` | ConsoleOut | `consoleOut/inbox` | die Konsole |
| `Mediator.java <from> <to>` | der Klebstoff | `<from>` | `<to>` |
Der Vermittler ist generisch: seine Route ist nicht einkompiliert, sie kommt als zwei Startargumente. Doch das Tutorial weist auf eine Asymmetrie hin, die man im Kopf behalten sollte: die drei Fähigkeiten erhalten ihre **Arbeit** als Nachrichten in einem Postfach, der Vermittler dagegen seine **Route** als Startkonfiguration — und er hat keinen Namen und kein eigenes Steuerpostfach, in das jemand schreiben könnte.
Praktische Folge: Argumente werden einmal gelesen, das Ändern der Route eines laufenden Vermittlers heisst also: anhalten und neu starten. Eine Konfigurationsdatei wäre nicht anders — auch sie wird beim Start gelesen. Das Tutorial lässt diesen Punkt absichtlich offen, bis die Kosten der verteilten Vermittler zu spüren waren.
:::
## [Step 18 — Run the fully external local version]{.en}[Étape 18 — Exécuter la version entièrement externe, en local]{.fr}[Schritt 18 — Die vollständig externe lokale Fassung ausführen]{.de} {#sec-step-18}
::: {.en}
Five terminals, five processes, one local filesystem between them:
```bash
java SensorService.java # terminal 1
java Mediator.java consoleIn/outbox rot13/inbox # terminal 2
java ProcessorService.java # terminal 3
java Mediator.java rot13/outbox consoleOut/inbox # terminal 4
java ActuatorService.java # terminal 5
```
**Observed:** `Hello World` typed in terminal 1 appeared as `Uryyb Jbeyq` in terminal 5. The three middle terminals showed nothing new — each mediator prints one "Mediating: …" line at startup, and `ProcessorService` prints nothing at all. Afterwards each of the four mailbox directories held one `.msg` file: the same line, copied along the chain.
Count it: **five processes** for what step 1 did in one statement. The tutorial's instruction at this point is not to optimise: "We are not done making it painful."
:::
::: {.fr}
Cinq terminaux, cinq processus, un seul système de fichiers local entre eux :
```bash
java SensorService.java # terminal 1
java Mediator.java consoleIn/outbox rot13/inbox # terminal 2
java ProcessorService.java # terminal 3
java Mediator.java rot13/outbox consoleOut/inbox # terminal 4
java ActuatorService.java # terminal 5
```
**Observé :** `Hello World` tapé dans le terminal 1 est apparu comme `Uryyb Jbeyq` dans le terminal 5. Les trois terminaux du milieu n'ont rien affiché de nouveau — chaque médiateur affiche une ligne « Mediating: … » au démarrage, et `ProcessorService` n'affiche rien du tout. Ensuite, chacun des quatre répertoires de boîtes contenait un fichier `.msg` : la même ligne, recopiée le long de la chaîne.
Comptons : **cinq processus** pour ce que l'étape 1 faisait en une instruction. La consigne du tutoriel à ce stade n'est pas d'optimiser : « We are not done making it painful. »
:::
::: {.de}
Fünf Terminals, fünf Prozesse, ein lokales Dateisystem dazwischen:
```bash
java SensorService.java # terminal 1
java Mediator.java consoleIn/outbox rot13/inbox # terminal 2
java ProcessorService.java # terminal 3
java Mediator.java rot13/outbox consoleOut/inbox # terminal 4
java ActuatorService.java # terminal 5
```
**Beobachtet:** `Hello World`, in Terminal 1 getippt, erschien als `Uryyb Jbeyq` in Terminal 5. Die drei mittleren Terminals zeigten nichts Neues — jeder Vermittler gibt beim Start eine Zeile „Mediating: …" aus, und `ProcessorService` gibt überhaupt nichts aus. Danach enthielt jedes der vier Postfachverzeichnisse eine `.msg`-Datei: dieselbe Zeile, entlang der Kette kopiert.
Nachzählen: **fünf Prozesse** für das, was Schritt 1 in einer Anweisung tat. Die Anweisung des Tutorials an dieser Stelle lautet nicht, zu optimieren: „We are not done making it painful."
:::
![[The five processes and the four mailbox directories. In the web version, **Play** follows one line of text from the keyboard to the console.]{.en}[Les cinq processus et les quatre répertoires de boîtes. Dans la version web, **Lancer** suit une ligne de texte du clavier à la console.]{.fr}[Die fünf Prozesse und die vier Postfachverzeichnisse. In der Webfassung folgt **Abspielen** einer Textzeile von der Tastatur zur Konsole.]{.de}](figures/filesystem-processes-@tr{langcode}){#fig-filesystem-processes .flow-figure}
## [What part II moved]{.en}[Ce que la partie II a déplacé]{.fr}[Was Teil II verschoben hat]{.de} {#sec-part-ii-result}
::: {.en}
| stage | where the topology lives | who could rewire it |
|---|---|---|
| step 1 | inside the capability code | whoever edits that code |
| steps 7–8 | in `main()`, as mailbox names | whoever edits `main()` |
| step 18 | in the two `Mediator.java <from> <to>` command lines | whoever starts the processes |
The topology has now left the source code altogether: no `.java` file contains the route. It lives in what the operator typed, which means a person is currently the orchestrator. What the five-process version bought is real — the wiring can change without touching any program — and what it cost is equally real: five processes, four copies of every message, and a program that no longer stops when you press `Ctrl+D`.
:::
::: {.fr}
| étape | où vit la topologie | qui peut recâbler |
|---|---|---|
| étape 1 | dans le code de la capacité | celui qui édite ce code |
| étapes 7–8 | dans `main()`, en noms de boîtes | celui qui édite `main()` |
| étape 18 | dans les deux lignes de commande `Mediator.java <from> <to>` | celui qui lance les processus |
La topologie a maintenant quitté le code source : aucun fichier `.java` ne contient la route. Elle vit dans ce que l'opérateur a tapé, ce qui fait d'une personne l'orchestrateur actuel. Ce que la version à cinq processus apporte est réel — le câblage peut changer sans toucher aucun programme — et ce qu'elle coûte l'est tout autant : cinq processus, quatre copies de chaque message, et un programme qui ne s'arrête plus quand on appuie sur `Ctrl+D`.
:::
::: {.de}
| Stufe | wo die Topologie liegt | wer umverdrahten kann |
|---|---|---|
| Schritt 1 | im Code der Fähigkeit | wer diesen Code ändert |
| Schritte 7–8 | in `main()`, als Postfachnamen | wer `main()` ändert |
| Schritt 18 | in den zwei Befehlszeilen `Mediator.java <from> <to>` | wer die Prozesse startet |
Die Topologie hat den Quellcode nun ganz verlassen: keine `.java`-Datei enthält die Route. Sie steckt in dem, was der Bediener getippt hat — damit ist derzeit ein Mensch der Orchestrator. Was die Fünf-Prozess-Fassung einbringt, ist echt: die Verdrahtung kann sich ändern, ohne ein Programm anzufassen. Was sie kostet, ist ebenso echt: fünf Prozesse, vier Kopien jeder Nachricht und ein Programm, das bei `Ctrl+D` nicht mehr stehen bleibt.
:::