Files
ProcessControl/05-part-v-subscriptions.qmd

163 lines
11 KiB
Plaintext

# [Part V — Replay the dynamic idea across processes]{.en}[Partie V — Rejouer l'idée dynamique entre processus]{.fr}[Teil V — Die dynamische Idee über Prozesse hinweg wiederholen]{.de} {#sec-part-v}
<!-- MULTILINGUAL: see the comment at the top of index.qmd. -->
::: {.en}
Steps 35 to 38 take the subscription idea out of the single JVM. The services become separate programs again, but instead of mediators copying files, each service watches the mailbox it was *told* to watch. One assumption of the first filesystem helper does not survive the move, and fixing it is what this part is really about.
:::
::: {.fr}
Les étapes 35 à 38 sortent l'idée d'abonnement de la JVM unique. Les services redeviennent des programmes séparés, mais au lieu de médiateurs qui copient des fichiers, chaque service observe la boîte qu'on lui a *indiquée*. Une hypothèse du premier utilitaire de fichiers ne survit pas au déplacement, et c'est bien de la corriger qu'il s'agit ici.
:::
::: {.de}
Die Schritte 35 bis 38 holen die Abonnement-Idee aus der einzelnen JVM heraus. Die Dienste werden wieder getrennte Programme, aber anstelle von Vermittlern, die Dateien kopieren, beobachtet jeder Dienst das Postfach, das ihm *gesagt* wurde. Eine Annahme des ersten Dateisystem-Helfers übersteht den Umzug nicht, und genau deren Korrektur ist das Thema dieses Teils.
:::
## [One blocking watch is not enough]{.en}[Une observation bloquante ne suffit pas]{.fr}[Ein blockierendes watch genügt nicht]{.de} {#sec-watch-limit}
::: {.en}
`FileMessageBoard.watch(topic, receiver)` registers **one** directory and blocks forever. That was enough while every process watched one fixed mailbox. A dynamically wired service needs more:
```text
always watch its own control inbox
AND
add a watched directory at runtime
AND
possibly remove it later
```
The old signature cannot express that, and the consequence was already visible earlier: the configurable mediator accepted exactly one `ROUTE`, because the moment it began watching its source it went deaf to its own control inbox. The limitation was never *whose* directory — it was *one, fixed, forever*.
:::
::: {.fr}
`FileMessageBoard.watch(topic, receiver)` enregistre **un** répertoire et se bloque indéfiniment. Cela suffisait tant que chaque processus observait une boîte fixe. Un service câblé dynamiquement demande davantage :
```text
observer en permanence sa propre boîte de contrôle
ET
ajouter un répertoire observé à l'exécution
ET
éventuellement le retirer ensuite
```
L'ancienne signature ne peut pas exprimer cela, et la conséquence était déjà visible : le médiateur configurable n'acceptait qu'une seule `ROUTE`, car dès qu'il observait sa source il devenait sourd à sa propre boîte de contrôle. La limite n'a jamais été *de qui* est le répertoire, mais *un seul, fixe, pour toujours*.
:::
::: {.de}
`FileMessageBoard.watch(topic, receiver)` registriert **ein** Verzeichnis und blockiert für immer. Das genügte, solange jeder Prozess ein festes Postfach beobachtete. Ein dynamisch verdrahteter Dienst braucht mehr:
```text
dauerhaft das eigene Steuerpostfach beobachten
UND
zur Laufzeit ein beobachtetes Verzeichnis hinzufügen
UND
es möglicherweise später entfernen
```
Die alte Signatur kann das nicht ausdrücken, und die Folge war schon vorher sichtbar: der konfigurierbare Vermittler nahm genau eine `ROUTE` an, denn sobald er seine Quelle beobachtete, wurde er für sein eigenes Steuerpostfach taub. Die Grenze war nie, *wessen* Verzeichnis es ist — sondern *eines, festes, für immer*.
:::
## [The helper: `FileSubscriptions`]{.en}[L'utilitaire : `FileSubscriptions`]{.fr}[Der Helfer: `FileSubscriptions`]{.de} {#sec-filesubscriptions}
::: {.en}
One `WatchService` can serve many directories. `register(...)` returns a `WatchKey` identifying one of them, `watcher.take()` returns whichever key has events, and `key.cancel()` deregisters it. The helper keeps both directions, `name → key` and `key → name`, so an event can be traced back to the mailbox it came from.
Events do not reach a callback directly. They go onto a queue, read with `take()`, carrying
```java
record IncomingMessage(String mailbox, Message message) {}
```
Two reasons, and order of arrival is only the third. First, the observing thread must stay responsive for *every* subscribed directory: a callback that transformed, published or blocked would stall the observation of all the others. Second, the mailbox name travels with the message, so **one** loop in the service can decide what a message means — control inbox, so this is Intent to act on; subscribed source, so this is data to transform — and that same loop is free to add or remove subscriptions, because it is not sitting inside a callback.
:::
::: {.fr}
Un seul `WatchService` peut servir plusieurs répertoires. `register(...)` retourne un `WatchKey` qui en identifie un, `watcher.take()` retourne la clé qui a des événements, et `key.cancel()` la désenregistre. L'utilitaire garde les deux sens, `nom → clé` et `clé → nom`, pour qu'un événement puisse être rattaché à la boîte dont il vient.
Les événements n'arrivent pas directement dans un callback. Ils passent par une file, lue avec `take()`, et portent
```java
record IncomingMessage(String mailbox, Message message) {}
```
Deux raisons, l'ordre d'arrivée n'étant que la troisième. D'abord, le thread observateur doit rester réactif pour *tous* les répertoires abonnés : un callback qui transforme, publie ou bloque arrêterait l'observation de tous les autres. Ensuite, le nom de la boîte voyage avec le message, de sorte qu'**une seule** boucle du service peut décider de son sens — boîte de contrôle, donc un Intent à appliquer ; source abonnée, donc des données à transformer — et cette même boucle peut ajouter ou retirer des abonnements, puisqu'elle n'est pas prisonnière d'un callback.
:::
::: {.de}
Ein `WatchService` kann viele Verzeichnisse bedienen. `register(...)` gibt einen `WatchKey` zurück, der eines davon bezeichnet, `watcher.take()` liefert den Schlüssel mit Ereignissen, und `key.cancel()` meldet ihn ab. Der Helfer hält beide Richtungen, `Name → Schlüssel` und `Schlüssel → Name`, damit ein Ereignis auf das Postfach zurückgeführt werden kann, aus dem es kam.
Ereignisse erreichen keinen Callback direkt. Sie gehen in eine Warteschlange, gelesen mit `take()`, und tragen
```java
record IncomingMessage(String mailbox, Message message) {}
```
Dafür zwei Gründe; die Ankunftsreihenfolge ist nur der dritte. Erstens muss der beobachtende Thread für *jedes* abonnierte Verzeichnis ansprechbar bleiben: ein Callback, der transformiert, veröffentlicht oder blockiert, hielte die Beobachtung aller anderen auf. Zweitens reist der Postfachname mit der Nachricht, sodass **eine** Schleife im Dienst deren Bedeutung bestimmen kann — Steuerpostfach, also ein anzuwendender Intent; abonnierte Quelle, also zu transformierende Daten — und dieselbe Schleife darf Abonnements hinzufügen oder entfernen, weil sie nicht in einem Callback feststeckt.
:::
## [Two publications instead of four]{.en}[Deux publications au lieu de quatre]{.fr}[Zwei Veröffentlichungen statt vier]{.de} {#sec-two-publications}
::: {.en}
Run `SensorService`, `DynamicProcessorService` and `DynamicActuatorService` — and no mediators — then let `Configure.java` publish the two `TOPIC` messages. A line typed afterwards leaves exactly two application publications in the board:
| mailbox | content | what it is |
|---|---|---|
| `consoleIn/outbox` | `TEXT hello` | the input |
| `rot13/outbox` | `TEXT uryyb` | the result |
| `rot13/inbox` | `TOPIC consoleIn/outbox` | Intent, published once |
| `consoleOut/inbox` | `TOPIC rot13/outbox` | Intent, published once |
`consoleOut/inbox` holds **no payload at all**: ConsoleOut takes straight from `rot13/outbox`. Its inbox changed job, from carrying messages to carrying wiring.
A line typed *before* `Configure.java` ran stays in `consoleIn/outbox` forever. A subscription that does not exist yet misses what came before it — exactly what the restarted mediator showed when it delivered nothing.
| version | application publications | processes in the data path |
|---|---|---|
| mediated (step 18) | 4 | 5 |
| configurable mediator (step 27) | 4 | 5 |
| dynamic (step 38) | **2** | **3** |
:::
::: {.fr}
Lancez `SensorService`, `DynamicProcessorService` et `DynamicActuatorService` — sans médiateurs — puis laissez `Configure.java` publier les deux messages `TOPIC`. Une ligne tapée ensuite laisse exactement deux publications applicatives dans le tableau :
| boîte | contenu | nature |
|---|---|---|
| `consoleIn/outbox` | `TEXT hello` | l'entrée |
| `rot13/outbox` | `TEXT uryyb` | le résultat |
| `rot13/inbox` | `TOPIC consoleIn/outbox` | Intent, publié une fois |
| `consoleOut/inbox` | `TOPIC rot13/outbox` | Intent, publié une fois |
`consoleOut/inbox` ne contient **aucune charge utile** : ConsoleOut retire directement de `rot13/outbox`. Sa boîte a changé de métier, des messages vers le câblage.
Une ligne tapée *avant* l'exécution de `Configure.java` reste dans `consoleIn/outbox` pour toujours. Un abonnement qui n'existe pas encore manque ce qui l'a précédé — le même constat que le médiateur redémarré qui n'a rien livré.
| version | publications applicatives | processus dans le chemin des données |
|---|---|---|
| médiée (étape 18) | 4 | 5 |
| médiateur configurable (étape 27) | 4 | 5 |
| dynamique (étape 38) | **2** | **3** |
:::
::: {.de}
Starten Sie `SensorService`, `DynamicProcessorService` und `DynamicActuatorService` — ohne Vermittler — und lassen Sie dann `Configure.java` die zwei `TOPIC`-Nachrichten veröffentlichen. Eine danach getippte Zeile hinterlässt genau zwei Anwendungsveröffentlichungen im Brett:
| Postfach | Inhalt | was es ist |
|---|---|---|
| `consoleIn/outbox` | `TEXT hello` | die Eingabe |
| `rot13/outbox` | `TEXT uryyb` | das Ergebnis |
| `rot13/inbox` | `TOPIC consoleIn/outbox` | Intent, einmal veröffentlicht |
| `consoleOut/inbox` | `TOPIC rot13/outbox` | Intent, einmal veröffentlicht |
`consoleOut/inbox` enthält **keine Nutzlast**: ConsoleOut nimmt direkt aus `rot13/outbox`. Sein Postfach wechselte die Aufgabe, von Nachrichten zu Verdrahtung.
Eine Zeile, die *vor* dem Lauf von `Configure.java` getippt wurde, bleibt für immer in `consoleIn/outbox`. Ein Abonnement, das noch nicht existiert, verpasst, was ihm vorausging — dieselbe Lehre wie beim neu gestarteten Vermittler, der nichts auslieferte.
| Fassung | Anwendungsveröffentlichungen | Prozesse im Datenpfad |
|---|---|---|
| vermittelt (Schritt 18) | 4 | 5 |
| konfigurierbarer Vermittler (Schritt 27) | 4 | 5 |
| dynamisch (Schritt 38) | **2** | **3** |
:::