465 lines
41 KiB
Plaintext
465 lines
41 KiB
Plaintext
# [Part IX — MQTT]{.en}[Partie IX — MQTT]{.fr}[Teil IX — MQTT]{.de} {#sec-part-ix}
|
|
|
|
<!-- MULTILINGUAL: see the comment at the top of index.qmd.
|
|
Part VIII (step 53) is one step and opens this chapter rather than
|
|
standing alone. -->
|
|
|
|
## [What the filesystem taught, and what it is not for]{.en}[Ce que le système de fichiers a enseigné, et ce pour quoi il n'est pas fait]{.fr}[Was das Dateisystem gelehrt hat und wofür es nicht taugt]{.de} {#sec-filesystem-verdict}
|
|
|
|
::: {.en}
|
|
The filesystem taught publication boundaries, directories as addresses, observation, independent processes, independent languages, synchronisation latency, runtime wiring, State, Intent, Events, mediator costs, service ownership and transformer services. It was a good teacher and it is not an elegant message broker: by the end the architecture was clean and the transport was a pile of `.tmp` files, atomic moves, rescanning, shared paths and replication delay.
|
|
|
|
The conclusion is **not** "files bad, MQTT good". The filesystem has an advantage MQTT cannot match — it routinely stores gigabytes or terabytes, while brokers and clients are built for small messages, and chunking a huge payload over MQTT means inventing a file-transfer protocol inside a message protocol. So:
|
|
|
|
> Use messages for coordination and events. Use an appropriate file or object store for large data. A message can carry the **location, identity and metadata** of that data instead of the terabytes themselves.
|
|
|
|
A replicated filesystem also gives every machine a local copy, which is a genuine strength — though replication is not a backup: deletion and corruption replicate too, unless versioning preserves older copies.
|
|
:::
|
|
|
|
::: {.fr}
|
|
Le système de fichiers a enseigné les frontières de publication, les répertoires comme adresses, l'observation, des processus indépendants, des langages indépendants, la latence de synchronisation, le câblage à l'exécution, le State, l'Intent, les Events, le coût des médiateurs, la propriété des services et les services transformateurs. Ce fut un bon professeur, et ce n'est pas un courtier de messages élégant : à la fin, l'architecture était propre et le transport était un amas de fichiers `.tmp`, de déplacements atomiques, de rescans, de chemins partagés et de délais de réplication.
|
|
|
|
La conclusion n'est **pas** « fichiers mauvais, MQTT bon ». Le système de fichiers a un avantage que MQTT ne peut égaler — il stocke couramment des gigaoctets ou des téraoctets, alors que courtiers et clients sont conçus pour de petits messages, et découper une charge énorme sur MQTT revient à inventer un protocole de transfert de fichiers dans un protocole de messages. Donc :
|
|
|
|
> Utilisez les messages pour la coordination et les événements. Utilisez un stockage de fichiers ou d'objets adapté pour les grandes données. Un message peut porter l'**emplacement, l'identité et les métadonnées** de ces données au lieu des téraoctets eux-mêmes.
|
|
|
|
Un système de fichiers répliqué donne aussi à chaque machine une copie locale, ce qui est une vraie force — mais la réplication n'est pas une sauvegarde : suppressions et corruptions se répliquent aussi, à moins qu'un versionnement conserve les copies antérieures.
|
|
:::
|
|
|
|
::: {.de}
|
|
Das Dateisystem lehrte Veröffentlichungsgrenzen, Verzeichnisse als Adressen, Beobachtung, unabhängige Prozesse, unabhängige Sprachen, Synchronisationslatenz, Verdrahtung zur Laufzeit, State, Intent, Events, Vermittlerkosten, Dienstbesitz und Transformatordienste. Es war ein guter Lehrer und ist kein eleganter Nachrichten-Broker: am Ende war die Architektur sauber und der Transport ein Haufen `.tmp`-Dateien, atomarer Verschiebungen, erneuter Scans, geteilter Pfade und Replikationsverzögerung.
|
|
|
|
Die Schlussfolgerung ist **nicht** „Dateien schlecht, MQTT gut". Das Dateisystem hat einen Vorteil, den MQTT nicht erreicht — es speichert routinemässig Gigabytes bis Terabytes, während Broker und Clients für kleine Nachrichten gebaut sind, und das Stückeln einer riesigen Nutzlast über MQTT heisst, ein Dateitransferprotokoll in einem Nachrichtenprotokoll zu erfinden. Also:
|
|
|
|
> Nachrichten für Koordination und Ereignisse. Für grosse Daten ein passender Datei- oder Objektspeicher. Eine Nachricht kann **Ort, Identität und Metadaten** dieser Daten tragen statt der Terabytes selbst.
|
|
|
|
Ein repliziertes Dateisystem gibt zudem jeder Maschine eine lokale Kopie, eine echte Stärke — doch Replikation ist kein Backup: Löschungen und Beschädigungen replizieren mit, sofern nicht eine Versionierung ältere Kopien bewahrt.
|
|
:::
|
|
|
|
## [MQTT should look familiar]{.en}[MQTT devrait sembler familier]{.fr}[MQTT sollte vertraut wirken]{.de} {#sec-mqtt-mapping}
|
|
|
|
::: {.en}
|
|
| filesystem / Syncthing | MQTT |
|
|
|---|---|
|
|
| synchronised message-board root | broker / namespace |
|
|
| directory path | topic |
|
|
| `.msg` file | publication |
|
|
| file contents | payload |
|
|
| `WatchService` | subscription |
|
|
| dynamic directory | topic / filter |
|
|
| control directory | `I` |
|
|
| state directory | `S/…` |
|
|
| event directory | `E/…` |
|
|
|
|
The reaction the material is after: *"Oh. We already know this architecture."* MQTT is a transport change, not an architectural claim.
|
|
|
|
Two things a directory could not do, both visible in a minute at the command line. A publication made **before** a subscriber exists never reaches it — the stranded-message problem for the third time, now with an answer the filesystem never had. And a filter like `test/#` matches `test/a` and `test/a/b/c` but not `testing/x`, because `#` works on **levels**, not string prefixes; `test/+` would match only one level down.
|
|
|
|
The deeper correction: **a topic is not a container.** There is no object called `test/a` on the broker. A topic is a routing key carried by each publication and matched against the filters of whoever is subscribed at that instant. Directories *hold* messages; topics *match* them. One subscription therefore covers topics that do not exist yet — where a message board needed a new directory and a new registration.
|
|
:::
|
|
|
|
::: {.fr}
|
|
| système de fichiers / Syncthing | MQTT |
|
|
|---|---|
|
|
| racine du tableau de messages synchronisé | courtier / espace de noms |
|
|
| chemin de répertoire | sujet (*topic*) |
|
|
| fichier `.msg` | publication |
|
|
| contenu du fichier | charge utile |
|
|
| `WatchService` | abonnement |
|
|
| répertoire dynamique | sujet / filtre |
|
|
| répertoire de contrôle | `I` |
|
|
| répertoire d'état | `S/…` |
|
|
| répertoire d'événements | `E/…` |
|
|
|
|
La réaction visée par le matériel : « Ah. Nous connaissons déjà cette architecture. » MQTT est un changement de transport, pas une affirmation architecturale.
|
|
|
|
Deux choses qu'un répertoire ne pouvait pas faire, visibles en une minute en ligne de commande. Une publication faite **avant** l'existence d'un abonné ne lui parvient jamais — le constat des messages bloqués, pour la troisième fois, mais avec une réponse que le système de fichiers n'avait pas. Et un filtre comme `test/#` correspond à `test/a` et `test/a/b/c` mais pas à `testing/x`, car `#` travaille par **niveaux** et non par préfixes de chaîne ; `test/+` ne correspondrait qu'à un seul niveau.
|
|
|
|
La correction plus profonde : **un sujet n'est pas un conteneur.** Il n'existe aucun objet nommé `test/a` sur le courtier. Un sujet est une clé de routage portée par chaque publication et confrontée aux filtres de qui est abonné à cet instant. Les répertoires *contiennent* les messages ; les sujets les *filtrent*. Un seul abonnement couvre donc des sujets qui n'existent pas encore — là où un tableau de messages exigeait un nouveau répertoire et un nouvel enregistrement.
|
|
:::
|
|
|
|
::: {.de}
|
|
| Dateisystem / Syncthing | MQTT |
|
|
|---|---|
|
|
| Wurzel des synchronisierten Nachrichtenbretts | Broker / Namensraum |
|
|
| Verzeichnispfad | Topic |
|
|
| `.msg`-Datei | Veröffentlichung |
|
|
| Dateiinhalt | Nutzlast |
|
|
| `WatchService` | Abonnement |
|
|
| dynamisches Verzeichnis | Topic / Filter |
|
|
| Steuerverzeichnis | `I` |
|
|
| Zustandsverzeichnis | `S/…` |
|
|
| Ereignisverzeichnis | `E/…` |
|
|
|
|
Die gewünschte Reaktion des Materials: „Ach. Diese Architektur kennen wir schon." MQTT ist ein Transportwechsel, keine architektonische Aussage.
|
|
|
|
Zwei Dinge, die ein Verzeichnis nicht konnte, in einer Minute auf der Kommandozeile sichtbar. Eine Veröffentlichung **vor** der Existenz eines Abonnenten erreicht ihn nie — die Lehre der liegengebliebenen Nachrichten zum dritten Mal, nun mit einer Antwort, die das Dateisystem nie hatte. Und ein Filter wie `test/#` passt auf `test/a` und `test/a/b/c`, nicht aber auf `testing/x`, weil `#` auf **Ebenen** arbeitet, nicht auf Zeichenpräfixen; `test/+` passte nur eine Ebene tief.
|
|
|
|
Die tiefere Korrektur: **ein Topic ist kein Behälter.** Es gibt kein Objekt namens `test/a` auf dem Broker. Ein Topic ist ein Routing-Schlüssel, den jede Veröffentlichung trägt und der gegen die Filter derjenigen geprüft wird, die in diesem Moment abonniert haben. Verzeichnisse *halten* Nachrichten; Topics *vergleichen* sie. Ein Abonnement deckt daher Topics ab, die noch nicht existieren — wo ein Nachrichtenbrett ein neues Verzeichnis und eine neue Registrierung brauchte.
|
|
:::
|
|
|
|
## [The library, the client id and the broker address]{.en}[La bibliothèque, l'identifiant client et l'adresse du courtier]{.fr}[Die Bibliothek, die Client-ID und die Broker-Adresse]{.de} {#sec-paho}
|
|
|
|
::: {.en}
|
|
Java has no MQTT client in its standard library, so Paho arrives now — after the need, like the mediator in step 7 and Jackson in step 64. Four things are needed from it: connect, publish, subscribe, callback. Connecting is deliberately anticlimactic: *"Nothing architectural happened here. We merely attached our process to the transport."*
|
|
|
|
Two details of connecting carry weight:
|
|
|
|
- **the client id** is not merely a uniqueness token. The broker recognises a returning client by it and keeps session state for it: subscriptions, messages queued at QoS > 0, and the association with its Last Will. A directory never knew who was watching, which is exactly why a restarted watcher's backlog was never replayed.
|
|
- **the broker address** is deployment configuration: every runnable reads `System.getProperty("mqtt.broker", "tcp://localhost:1883")`. It is also the one piece of configuration that cannot arrive as Intent, because Intent travels *through* the broker. Topology can be published; the address of the thing that publishes it cannot.
|
|
|
|
Subscribing costs one packet, and **the broker keeps the subscription list**. There is no standard way to ask it what another client subscribed to — which is why `S/subscriptions` exists: a component's own declaration of its wiring, published so the architecture can know what the transport keeps private. Only its owner may publish it, by the one-writer rule, because only its owner knows what it accepted.
|
|
:::
|
|
|
|
::: {.fr}
|
|
Java n'a pas de client MQTT dans sa bibliothèque standard ; Paho arrive donc maintenant — après le besoin, comme le médiateur à l'étape 7 et Jackson à l'étape 64. Quatre choses suffisent : se connecter, publier, s'abonner, rappeler. La connexion est volontairement anticlimatique : « Rien d'architectural ne s'est produit ici. Nous avons simplement attaché notre processus au transport. »
|
|
|
|
Deux détails de la connexion comptent :
|
|
|
|
- **l'identifiant client** n'est pas qu'un jeton d'unicité. Le courtier reconnaît par lui un client qui revient et conserve son état de session : abonnements, messages en file en QoS > 0, et l'association à sa dernière volonté. Un répertoire ne savait jamais qui l'observait, et c'est précisément pour cela qu'un observateur redémarré ne rejouait rien.
|
|
- **l'adresse du courtier** est de la configuration de déploiement : chaque programme lit `System.getProperty("mqtt.broker", "tcp://localhost:1883")`. C'est aussi la seule configuration qui ne peut pas arriver par Intent, puisque l'Intent passe *par* le courtier. La topologie se publie ; l'adresse de ce qui la publie, non.
|
|
|
|
S'abonner coûte un paquet, et **le courtier détient la liste des abonnements**. Il n'existe aucun moyen standard de lui demander à quoi un autre client s'est abonné — d'où `S/subscriptions` : la déclaration par un composant de son propre câblage, publiée pour que l'architecture sache ce que le transport garde privé. Seul son propriétaire peut la publier, par la règle de l'écrivain unique, car seul lui sait ce qu'il a accepté.
|
|
:::
|
|
|
|
::: {.de}
|
|
Java hat keinen MQTT-Client in der Standardbibliothek, also kommt Paho jetzt — nach dem Bedarf, wie der Vermittler in Schritt 7 und Jackson in Schritt 64. Vier Dinge braucht man: verbinden, veröffentlichen, abonnieren, Rückruf. Das Verbinden ist absichtlich unspektakulär: „Hier ist architektonisch nichts geschehen. Wir haben unseren Prozess nur an den Transport angeschlossen."
|
|
|
|
Zwei Details des Verbindens haben Gewicht:
|
|
|
|
- **die Client-ID** ist nicht bloss ein Eindeutigkeitsmerkmal. Der Broker erkennt daran einen zurückkehrenden Client und hält Sitzungszustand für ihn: Abonnements, bei QoS > 0 eingereihte Nachrichten und die Verknüpfung mit seinem Last Will. Ein Verzeichnis wusste nie, wer es beobachtete — genau deshalb spielte ein neu gestarteter Beobachter nichts nach.
|
|
- **die Broker-Adresse** ist Deployment-Konfiguration: jedes Programm liest `System.getProperty("mqtt.broker", "tcp://localhost:1883")`. Sie ist auch die einzige Konfiguration, die nicht als Intent kommen kann, denn Intent reist *durch* den Broker. Topologie lässt sich veröffentlichen; die Adresse des Veröffentlichenden nicht.
|
|
|
|
Abonnieren kostet ein Paket, und **der Broker führt die Abonnementliste**. Es gibt keinen Standardweg, ihn zu fragen, was ein anderer Client abonniert hat — daher `S/subscriptions`: die eigene Erklärung einer Komponente über ihre Verdrahtung, veröffentlicht, damit die Architektur weiss, was der Transport privat hält. Nur ihr Eigentümer darf sie veröffentlichen, nach der Ein-Schreiber-Regel, denn nur er weiss, was er angenommen hat.
|
|
:::
|
|
|
|
## [Structured Intent, and two object mappers]{.en}[Intent structuré, et deux mappeurs]{.fr}[Strukturierter Intent und zwei Mapper]{.de} {#sec-structured-intent}
|
|
|
|
::: {.en}
|
|
`TOPIC some/path` has one field and one meaning. It cannot say which *kind* of Intent this is, carry a second parameter, nest, or be extended; and there is nothing for a receiver to validate against. Richer Intent wants structure:
|
|
|
|
```yaml
|
|
subscribe:
|
|
topic: Tutorial/ConsoleIn/U/alice/E/text
|
|
```
|
|
|
|
Only then does a serialisation library have a clear job. `JsonTools` keeps **two** mappers, and the asymmetry is deliberate:
|
|
|
|
- reading uses a **YAML** factory with `FAIL_ON_UNKNOWN_PROPERTIES` off — JSON is a subset of YAML, so hand-typed Intent is accepted, and a newer configurator can send fields an older service ignores;
|
|
- writing uses plain **JSON** with `INDENT_OUTPUT` on, so published payloads are strict and readable.
|
|
|
|
Tolerant in, strict out. A single shared mapper would have to give up one of those.
|
|
:::
|
|
|
|
::: {.fr}
|
|
`TOPIC some/path` a un champ et un sens. Il ne peut pas dire de quel *type* d'Intent il s'agit, porter un second paramètre, s'imbriquer ou s'étendre ; et un récepteur n'a rien contre quoi valider. Un Intent plus riche demande une structure :
|
|
|
|
```yaml
|
|
subscribe:
|
|
topic: Tutorial/ConsoleIn/U/alice/E/text
|
|
```
|
|
|
|
C'est seulement là qu'une bibliothèque de sérialisation a une tâche claire. `JsonTools` garde **deux** mappeurs, et l'asymétrie est voulue :
|
|
|
|
- en entrée, une fabrique **YAML** avec `FAIL_ON_UNKNOWN_PROPERTIES` désactivé — JSON étant un sous-ensemble de YAML, un Intent tapé à la main est accepté, et un configurateur plus récent peut envoyer des champs qu'un service plus ancien ignore ;
|
|
- l'écriture utilise du **JSON** strict avec `INDENT_OUTPUT` activé, donc les charges publiées sont strictes et lisibles.
|
|
|
|
Tolérant en entrée, strict en sortie. Un mappeur unique devrait renoncer à l'un des deux.
|
|
:::
|
|
|
|
::: {.de}
|
|
`TOPIC some/path` hat ein Feld und eine Bedeutung. Es kann nicht sagen, welche *Art* Intent vorliegt, keinen zweiten Parameter tragen, nicht verschachteln, nicht erweitert werden; und ein Empfänger hat nichts, wogegen er prüfen könnte. Reicherer Intent braucht Struktur:
|
|
|
|
```yaml
|
|
subscribe:
|
|
topic: Tutorial/ConsoleIn/U/alice/E/text
|
|
```
|
|
|
|
Erst dann hat eine Serialisierungsbibliothek eine klare Aufgabe. `JsonTools` hält **zwei** Mapper, und die Asymmetrie ist Absicht:
|
|
|
|
- das Lesen nutzt eine **YAML**-Factory mit abgeschaltetem `FAIL_ON_UNKNOWN_PROPERTIES` — JSON ist eine Teilmenge von YAML, handgetippter Intent wird akzeptiert, und ein neuerer Konfigurator darf Felder senden, die ein älterer Dienst ignoriert;
|
|
- das Schreiben nutzt strenges **JSON** mit `INDENT_OUTPUT`, die veröffentlichten Nutzlasten sind also streng und lesbar.
|
|
|
|
Tolerant hinein, streng hinaus. Ein einziger Mapper müsste auf eines davon verzichten.
|
|
:::
|
|
|
|
## [DUISE, and rewiring a running system]{.en}[DUISE, et recâbler un système en marche]{.fr}[DUISE und das Umverdrahten im Betrieb]{.de} {#sec-duise}
|
|
|
|
::: {.en}
|
|
The naming scheme finally gets its name: **D**escription (what contracts this service understands and publishes), **U**nit (which instance), **I**ntent (requested behaviour), **S**tatus (what is true now), **E**vent (what happened).
|
|
|
|
```text
|
|
Tutorial/ROT13/U/alice/{I, S/online, S/subscriptions/text, E/crypted}
|
|
```
|
|
|
|
`U/<unit>` is what the filesystem never needed: each machine had its own replica of the same relative path, so instance identity was implicit. MQTT has one shared namespace, so a topic must say *which* copy. Hard-coding `U/alice` in a capability is therefore worse than hard-coding `consoleIn.outbox` ever was: it binds the build to one deployment. Configured by Intent, **one build serves everyone** — which is why `MqttConfigure` takes three unit names as arguments. The unit names *are* the topology.
|
|
|
|
Rewiring, observed on a running system: publish a new Intent naming a different source topic, and the service unsubscribes from the old one, subscribes to the new one, and republishes `S/subscriptions` to match. No restart, no edit. Send an invalid filter instead — `Tutorial/#/E/text`, where `#` is not the last level — and `MqttTools.isValidFilter` rejects it; the old subscription stands and the Status still tells the truth.
|
|
|
|
That rejection exposes a real gap, worth naming rather than hiding: it is logged locally only. The configurator cannot tell whether its Intent was applied or refused, and a monitor cannot distinguish "refused" from "not yet processed". In this design a sender learns the outcome by reading Status and comparing it with what it asked for. Publishing refusals as an Event, or a last-error Status, would close that gap; neither is in the material, so it is a design decision to justify.
|
|
:::
|
|
|
|
::: {.fr}
|
|
Le schéma de nommage reçoit enfin son nom : **D**escription (quels contrats ce service comprend et publie), **U**nit (quelle instance), **I**ntent (comportement demandé), **S**tatus (ce qui est vrai maintenant), **E**vent (ce qui est arrivé).
|
|
|
|
```text
|
|
Tutorial/ROT13/U/alice/{I, S/online, S/subscriptions/text, E/crypted}
|
|
```
|
|
|
|
`U/<unit>` est ce dont le système de fichiers n'avait pas besoin : chaque machine avait sa réplique du même chemin relatif, l'identité d'instance était implicite. MQTT a un espace de noms partagé : un sujet doit donc dire *quelle* copie. Coder en dur `U/alice` dans une capacité est donc pire que de coder en dur `consoleIn.outbox` : cela lie la compilation à un déploiement. Configuré par Intent, **une seule compilation sert tout le monde** — d'où les trois noms d'unité en arguments de `MqttConfigure`. Les noms d'unité *sont* la topologie.
|
|
|
|
Recâblage observé sur un système en marche : publiez un nouvel Intent nommant une autre source, et le service se désabonne de l'ancienne, s'abonne à la nouvelle et republie `S/subscriptions` en conséquence. Sans redémarrage, sans édition. Envoyez au contraire un filtre invalide — `Tutorial/#/E/text`, où `#` n'est pas le dernier niveau — et `MqttTools.isValidFilter` le rejette ; l'ancien abonnement demeure et le Status continue de dire vrai.
|
|
|
|
Ce rejet révèle une vraie lacune, à nommer plutôt qu'à cacher : il n'est journalisé que localement. Le configurateur ne peut savoir si son Intent a été appliqué ou refusé, et un moniteur ne peut distinguer « refusé » de « pas encore traité ». Dans cette conception, l'émetteur apprend le résultat en lisant le Status et en le comparant à sa demande. Publier les refus comme Event, ou un Status de dernière erreur, combleraient la lacune ; ni l'un ni l'autre n'est dans le matériel : c'est une décision de conception à justifier.
|
|
:::
|
|
|
|
::: {.de}
|
|
Das Namensschema erhält endlich seinen Namen: **D**escription (welche Verträge dieser Dienst versteht und veröffentlicht), **U**nit (welche Instanz), **I**ntent (gewünschtes Verhalten), **S**tatus (was jetzt gilt), **E**vent (was geschehen ist).
|
|
|
|
```text
|
|
Tutorial/ROT13/U/alice/{I, S/online, S/subscriptions/text, E/crypted}
|
|
```
|
|
|
|
`U/<unit>` brauchte das Dateisystem nie: jede Maschine hatte ihr eigenes Replikat desselben relativen Pfades, Instanzidentität war implizit. MQTT hat einen gemeinsamen Namensraum, ein Topic muss also sagen, *welche* Kopie. `U/alice` in einer Fähigkeit festzuschreiben ist daher schlimmer, als `consoleIn.outbox` es je war: es bindet das Build an ein Deployment. Per Intent konfiguriert, **dient ein Build allen** — daher die drei Unit-Namen als Argumente von `MqttConfigure`. Die Unit-Namen *sind* die Topologie.
|
|
|
|
Umverdrahten, am laufenden System beobachtet: einen neuen Intent mit anderer Quelle veröffentlichen, und der Dienst kündigt die alte, abonniert die neue und veröffentlicht `S/subscriptions` passend neu. Kein Neustart, keine Änderung. Schickt man stattdessen einen ungültigen Filter — `Tutorial/#/E/text`, wo `#` nicht die letzte Ebene ist — weist `MqttTools.isValidFilter` ihn ab; das alte Abonnement bleibt, und der Status sagt weiter die Wahrheit.
|
|
|
|
Diese Abweisung legt eine echte Lücke offen, die man benennen und nicht verstecken sollte: sie wird nur lokal protokolliert. Der Konfigurator erfährt nicht, ob sein Intent angewandt oder abgelehnt wurde, und ein Monitor kann „abgelehnt" nicht von „noch nicht verarbeitet" unterscheiden. In diesem Entwurf erfährt ein Sender das Ergebnis, indem er den Status liest und mit seiner Anfrage vergleicht. Abweisungen als Event zu veröffentlichen oder ein Letzter-Fehler-Status würden die Lücke schliessen; beides steht nicht im Material — es ist eine zu begründende Entwurfsentscheidung.
|
|
:::
|
|
|
|
## [What a new subscriber learns, and what a dead one admits]{.en}[Ce qu'un nouvel abonné apprend, et ce qu'un mort avoue]{.fr}[Was ein neuer Abonnent erfährt und was ein Toter zugibt]{.de} {#sec-retained-and-will}
|
|
|
|
::: {.en}
|
|
Subscribing to `Tutorial/#` for three seconds, with nothing being published, returns this:
|
|
|
|
```text
|
|
Tutorial/ROT13/U/nitro5/S/online {"value":true}
|
|
Tutorial/ROT13/U/nitro5/S/subscriptions/text "Tutorial/ConsoleIn/U/nitro5/E/text"
|
|
Tutorial/ConsoleOut/U/nitro5/S/online {"value":true}
|
|
Tutorial/ConsoleOut/U/nitro5/S/subscriptions/text "Tutorial/ROT13/U/nitro5/E/crypted"
|
|
```
|
|
|
|
A late arrival learns the entire current wiring of the system, instantly, without asking anyone and without any component knowing a monitor exists. That is retained **Status**. No Events arrive, because Events are published non-retained — "retained State, non-retained Events". It is also the proper answer to the instinct of *asking* a service what it is doing: nobody asks; the service states it, once, and the broker keeps it for whoever turns up.
|
|
|
|
Retained Status alone would lie, though. Kill a service with `Ctrl+C` and its `S/online = true` stays on the broker forever. Hence the **Last Will**, registered at connect time:
|
|
|
|
```java
|
|
var will = new MqttMessage("{\"value\":false}".getBytes(UTF_8), 1, true, new MqttProperties());
|
|
options.setWill(lastWillTopic, will);
|
|
```
|
|
|
|
The will is **retained**, so when the broker publishes it on the client's behalf it replaces the stale `true`. The component that fails is not the component that reports the failure — which is the only arrangement that can work. One caveat: a clean DISCONNECT does **not** trigger a will, so a well-behaved service publishes `online=false` itself on the way out, and the will covers the ugly deaths.
|
|
:::
|
|
|
|
::: {.fr}
|
|
S'abonner à `Tutorial/#` pendant trois secondes, sans que rien ne soit publié, renvoie ceci :
|
|
|
|
```text
|
|
Tutorial/ROT13/U/nitro5/S/online {"value":true}
|
|
Tutorial/ROT13/U/nitro5/S/subscriptions/text "Tutorial/ConsoleIn/U/nitro5/E/text"
|
|
Tutorial/ConsoleOut/U/nitro5/S/online {"value":true}
|
|
Tutorial/ConsoleOut/U/nitro5/S/subscriptions/text "Tutorial/ROT13/U/nitro5/E/crypted"
|
|
```
|
|
|
|
Un arrivant tardif apprend instantanément tout le câblage actuel du système, sans rien demander et sans qu'aucun composant sache qu'un moniteur existe. C'est le **Status** retenu. Aucun Event n'arrive, car les Events sont publiés non retenus — « State retenu, Events non retenus ». C'est aussi la bonne réponse à l'instinct de *demander* à un service ce qu'il fait : personne ne demande ; le service le déclare, une fois, et le courtier le garde pour quiconque se présente.
|
|
|
|
Le Status retenu seul mentirait pourtant. Tuez un service par `Ctrl+C` et son `S/online = true` reste sur le courtier à jamais. D'où la **dernière volonté**, enregistrée au moment de la connexion :
|
|
|
|
```java
|
|
var will = new MqttMessage("{\"value\":false}".getBytes(UTF_8), 1, true, new MqttProperties());
|
|
options.setWill(lastWillTopic, will);
|
|
```
|
|
|
|
Elle est **retenue** : quand le courtier la publie au nom du client, elle remplace le `true` périmé. Le composant qui échoue n'est pas celui qui signale l'échec — seul arrangement qui puisse fonctionner. Une réserve : une déconnexion propre ne déclenche **pas** la dernière volonté ; un service bien élevé publie donc `online=false` lui-même en partant, la volonté couvrant les morts brutales.
|
|
:::
|
|
|
|
::: {.de}
|
|
Drei Sekunden `Tutorial/#` abonnieren, ohne dass etwas veröffentlicht wird, ergibt dies:
|
|
|
|
```text
|
|
Tutorial/ROT13/U/nitro5/S/online {"value":true}
|
|
Tutorial/ROT13/U/nitro5/S/subscriptions/text "Tutorial/ConsoleIn/U/nitro5/E/text"
|
|
Tutorial/ConsoleOut/U/nitro5/S/online {"value":true}
|
|
Tutorial/ConsoleOut/U/nitro5/S/subscriptions/text "Tutorial/ROT13/U/nitro5/E/crypted"
|
|
```
|
|
|
|
Ein Spätankömmling erfährt augenblicklich die gesamte aktuelle Verdrahtung des Systems, ohne jemanden zu fragen und ohne dass eine Komponente von einem Monitor weiss. Das ist retained **Status**. Keine Events kommen an, denn Events werden nicht retained veröffentlicht — „retained State, nicht retained Events". Es ist auch die richtige Antwort auf den Reflex, einen Dienst zu *fragen*, was er tut: niemand fragt; der Dienst erklärt es einmal, und der Broker bewahrt es für jeden, der kommt.
|
|
|
|
Retained Status allein würde allerdings lügen. Beendet man einen Dienst mit `Ctrl+C`, bleibt sein `S/online = true` für immer beim Broker. Daher der **Last Will**, bei der Verbindung registriert:
|
|
|
|
```java
|
|
var will = new MqttMessage("{\"value\":false}".getBytes(UTF_8), 1, true, new MqttProperties());
|
|
options.setWill(lastWillTopic, will);
|
|
```
|
|
|
|
Der Will ist **retained**, ersetzt also beim Veröffentlichen durch den Broker das veraltete `true`. Die Komponente, die ausfällt, ist nicht die, die den Ausfall meldet — die einzige Anordnung, die funktionieren kann. Ein Vorbehalt: ein sauberes DISCONNECT löst **keinen** Will aus; ein gut erzogener Dienst veröffentlicht daher beim Beenden selbst `online=false`, und der Will deckt die hässlichen Tode.
|
|
:::
|
|
|
|
## [What survived the transport, and what coupling remains]{.en}[Ce qui a survécu au transport, et le couplage restant]{.fr}[Was den Transport überlebte und welche Kopplung bleibt]{.de} {#sec-coupling-remains}
|
|
|
|
::: {.en}
|
|
The lower half of the filesystem→MQTT table is the point: `I`, `S`, `E`, egoistic services, runtime topology and "transformer if needed" are **unchanged**. The architecture survived the transport replacement, and that is the strongest available evidence that the architecture was never about the transport.
|
|
|
|
Loose coupling does not mean nothing knows anything. What remains, necessarily, is agreement on: message syntax, message semantics, topic contracts, Intent, ownership, the meaning of State and the meaning of Events. The goal is not to eliminate coupling but to **eliminate unnecessary knowledge**. Concretely, in this system each service must understand exactly one foreign Event contract — ROT13 understands ConsoleIn's `E/text`, ConsoleOut understands ROT13's `E/crypted` — plus the Intent schema it accepts on its own `I`. That list is the irreducible minimum.
|
|
|
|
Separately, the broker is a shared infrastructure dependency: everyone needs its address and nothing works without it. Real, but a different kind of thing from one component knowing another.
|
|
|
|
The step-78 checklist is the tool to keep. Twelve questions, of which these six carry the argument for this system:
|
|
|
|
| question | answer here |
|
|
|---|---|
|
|
| does a capability contain a hard-coded producer identity? | no — it arrives as Intent |
|
|
| which foreign contracts must it understand? | one Event contract each, plus its own Intent schema |
|
|
| where is topology defined? | in the configurator, outside the data path |
|
|
| can topology change without recompiling? | yes — demonstrated on a running system |
|
|
| could the transport be replaced? | yes — demonstrated, filesystem then MQTT |
|
|
| does every mediator do something that needs mediation? | yes, vacuously: `TEXT → TEXT` needs none, and none exists |
|
|
|
|
The material's own caution applies: the answers need not all be "no". They need to be **intentional**.
|
|
:::
|
|
|
|
::: {.fr}
|
|
La moitié inférieure du tableau système de fichiers→MQTT est l'essentiel : `I`, `S`, `E`, les services égoïstes, la topologie à l'exécution et « transformateur si nécessaire » sont **inchangés**. L'architecture a survécu au remplacement du transport, et c'est la meilleure preuve disponible qu'elle n'a jamais dépendu du transport.
|
|
|
|
Un couplage faible ne signifie pas que rien ne sait rien. Ce qui reste, nécessairement, est l'accord sur : la syntaxe des messages, leur sémantique, les contrats de sujets, l'Intent, la propriété, le sens du State et celui des Events. Le but n'est pas d'éliminer le couplage mais d'**éliminer la connaissance inutile**. Concrètement, chaque service ici doit comprendre exactement un contrat d'Event étranger — ROT13 comprend `E/text` de ConsoleIn, ConsoleOut comprend `E/crypted` de ROT13 — plus le schéma d'Intent qu'il accepte sur son propre `I`. Cette liste est le minimum irréductible.
|
|
|
|
Par ailleurs, le courtier est une dépendance d'infrastructure partagée : tout le monde a besoin de son adresse et rien ne marche sans lui. Réel, mais d'une autre nature que la connaissance d'un composant par un autre.
|
|
|
|
La liste de l'étape 78 est l'outil à garder. Douze questions, dont ces six portent l'argument de ce système :
|
|
|
|
| question | réponse ici |
|
|
|---|---|
|
|
| une capacité contient-elle l'identité d'un producteur en dur ? | non — elle arrive par Intent |
|
|
| quels contrats étrangers doit-elle comprendre ? | un contrat d'Event chacun, plus son propre schéma d'Intent |
|
|
| où la topologie est-elle définie ? | dans le configurateur, hors du chemin des données |
|
|
| la topologie peut-elle changer sans recompiler ? | oui — démontré sur un système en marche |
|
|
| le transport pourrait-il être remplacé ? | oui — démontré : système de fichiers puis MQTT |
|
|
| chaque médiateur fait-il quelque chose qui exige une médiation ? | oui, trivialement : `TEXT → TEXT` n'en exige aucune, et il n'y en a aucun |
|
|
|
|
La prudence du matériel s'applique : les réponses n'ont pas à être toutes « non ». Elles doivent être **intentionnelles**.
|
|
:::
|
|
|
|
::: {.de}
|
|
Die untere Hälfte der Tabelle Dateisystem→MQTT ist der Punkt: `I`, `S`, `E`, egoistische Dienste, Topologie zur Laufzeit und „Transformator wenn nötig" sind **unverändert**. Die Architektur überlebte den Transportwechsel, und das ist der stärkste verfügbare Beleg, dass sie nie am Transport hing.
|
|
|
|
Lose Kopplung heisst nicht, dass nichts etwas weiss. Notwendig bleibt die Einigkeit über: Nachrichtensyntax, Nachrichtensemantik, Topic-Verträge, Intent, Besitz, Bedeutung von State und Bedeutung von Events. Ziel ist nicht, Kopplung zu beseitigen, sondern **unnötiges Wissen** zu beseitigen. Konkret muss hier jeder Dienst genau einen fremden Event-Vertrag verstehen — ROT13 den `E/text` von ConsoleIn, ConsoleOut den `E/crypted` von ROT13 — plus das Intent-Schema, das er auf seinem eigenen `I` annimmt. Diese Liste ist das unverzichtbare Minimum.
|
|
|
|
Davon getrennt: der Broker ist eine geteilte Infrastrukturabhängigkeit; alle brauchen seine Adresse, und ohne ihn läuft nichts. Real, aber anderer Art als das Wissen einer Komponente über eine andere.
|
|
|
|
Die Prüfliste aus Schritt 78 ist das Werkzeug, das bleibt. Zwölf Fragen, von denen diese sechs das Argument dieses Systems tragen:
|
|
|
|
| Frage | Antwort hier |
|
|
|---|---|
|
|
| enthält eine Fähigkeit eine festgeschriebene Produzentenidentität? | nein — sie kommt als Intent |
|
|
| welche fremden Verträge muss sie verstehen? | je einen Event-Vertrag, plus ihr eigenes Intent-Schema |
|
|
| wo ist die Topologie definiert? | im Konfigurator, ausserhalb des Datenpfads |
|
|
| kann sich die Topologie ohne Neukompilieren ändern? | ja — am laufenden System gezeigt |
|
|
| könnte der Transport ersetzt werden? | ja — gezeigt: Dateisystem, dann MQTT |
|
|
| leistet jeder Vermittler etwas, das Vermittlung braucht? | ja, trivial: `TEXT → TEXT` braucht keine, und es gibt keinen |
|
|
|
|
Die Mahnung des Materials gilt: die Antworten müssen nicht alle „nein" lauten. Sie müssen **absichtlich** sein.
|
|
:::
|
|
|
|
## [The whole journey]{.en}[Le parcours complet]{.fr}[Der ganze Weg]{.de} {#sec-whole-journey}
|
|
|
|
::: {.en}
|
|
The program never changed: a line goes in, the same line comes out rotated by 13 letters. What changed, eleven times, is how the parts are joined and who holds the knowledge of how they are joined.
|
|
|
|
| stage | how the parts are joined | where the topology lives | in the data path besides the capabilities |
|
|
|---|---|---|---|
|
|
| 1 procedural | direct calls | inside the capability code | — |
|
|
| 2 egoistic services | not joined at all | nowhere — that is the problem | — |
|
|
| 3 static mediation, one JVM | mailboxes, copied by mediators | the mediators, started in `main()` | two mediators |
|
|
| 4 static mediation, filesystem | directories, copied by mediator processes | the operator's command lines | two mediator processes |
|
|
| 5 static mediation, Syncthing | replicated directories | the operator's command lines | two mediator processes, plus replication delay |
|
|
| 6 named, configurable mediators | `ROUTE` Intent from an orchestrator | the orchestrator, outside the path | the mediators, still |
|
|
| 7 dynamic, one JVM | services listen, told by `TOPIC` Intent | the configurator | nothing |
|
|
| 8 dynamic, filesystem | the same, over directories | the configurator | nothing |
|
|
| 9 dynamic, Syncthing | the same, over replicated directories | the configurator | nothing — transport hops only |
|
|
| 10 contracts | compatible: direct; incompatible: a transformer | the configurator | a transformer, only where contracts differ |
|
|
| 11 MQTT | topics on a broker | the configurator | nothing — the broker is transport |
|
|
|
|
Read the third column from top to bottom: the topology moves outward, one stage at a time, until no capability holds any of it. Read the last one: the price of that move falls to zero at stage 7 and stays there while the transport changes underneath three times. Same architecture, better transport.
|
|
:::
|
|
|
|
::: {.fr}
|
|
Le programme n'a jamais changé : une ligne entre, la même ressort décalée de 13 lettres. Ce qui a changé, onze fois, c'est la manière dont les parties sont reliées et qui détient la connaissance de ce câblage.
|
|
|
|
| étape | comment les parties sont reliées | où vit la topologie | dans le chemin des données, outre les capacités |
|
|
|---|---|---|---|
|
|
| 1 procédural | appels directs | dans le code de la capacité | — |
|
|
| 2 services égoïstes | pas reliées du tout | nulle part — c'est le problème | — |
|
|
| 3 médiation statique, une JVM | boîtes, copiées par des médiateurs | les médiateurs, démarrés dans `main()` | deux médiateurs |
|
|
| 4 médiation statique, système de fichiers | répertoires, copiés par des processus médiateurs | les lignes de commande de l'opérateur | deux processus médiateurs |
|
|
| 5 médiation statique, Syncthing | répertoires répliqués | les lignes de commande de l'opérateur | deux processus médiateurs, plus le délai de réplication |
|
|
| 6 médiateurs nommés et configurables | Intent `ROUTE` d'un orchestrateur | l'orchestrateur, hors du chemin | les médiateurs, encore |
|
|
| 7 dynamique, une JVM | les services écoutent, guidés par un Intent `TOPIC` | le configurateur | rien |
|
|
| 8 dynamique, système de fichiers | idem, sur des répertoires | le configurateur | rien |
|
|
| 9 dynamique, Syncthing | idem, sur des répertoires répliqués | le configurateur | rien — seulement des sauts de transport |
|
|
| 10 contrats | compatibles : direct ; incompatibles : un transformateur | le configurateur | un transformateur, seulement là où les contrats diffèrent |
|
|
| 11 MQTT | des sujets sur un courtier | le configurateur | rien — le courtier est du transport |
|
|
|
|
Lisez la troisième colonne de haut en bas : la topologie s'éloigne, une étape après l'autre, jusqu'à ce qu'aucune capacité n'en détienne plus rien. Lisez la dernière : le prix de ce déplacement tombe à zéro à l'étape 7 et y reste pendant que le transport change trois fois en dessous. Même architecture, meilleur transport.
|
|
:::
|
|
|
|
::: {.de}
|
|
Das Programm hat sich nie geändert: eine Zeile geht hinein, dieselbe kommt um 13 Buchstaben verschoben heraus. Geändert hat sich, elfmal, wie die Teile verbunden sind und wer das Wissen über diese Verbindung hält.
|
|
|
|
| Stufe | wie die Teile verbunden sind | wo die Topologie liegt | im Datenpfad ausser den Fähigkeiten |
|
|
|---|---|---|---|
|
|
| 1 prozedural | direkte Aufrufe | im Code der Fähigkeit | — |
|
|
| 2 egoistische Dienste | gar nicht verbunden | nirgends — das ist das Problem | — |
|
|
| 3 statische Vermittlung, eine JVM | Postfächer, von Vermittlern kopiert | die Vermittler, gestartet in `main()` | zwei Vermittler |
|
|
| 4 statische Vermittlung, Dateisystem | Verzeichnisse, von Vermittlerprozessen kopiert | die Befehlszeilen des Bedieners | zwei Vermittlerprozesse |
|
|
| 5 statische Vermittlung, Syncthing | replizierte Verzeichnisse | die Befehlszeilen des Bedieners | zwei Vermittlerprozesse, dazu Replikationsverzögerung |
|
|
| 6 benannte, konfigurierbare Vermittler | `ROUTE`-Intent von einem Orchestrator | der Orchestrator, ausserhalb des Pfads | weiterhin die Vermittler |
|
|
| 7 dynamisch, eine JVM | die Dienste hören selbst, gesteuert durch `TOPIC`-Intent | der Konfigurator | nichts |
|
|
| 8 dynamisch, Dateisystem | dasselbe, über Verzeichnisse | der Konfigurator | nichts |
|
|
| 9 dynamisch, Syncthing | dasselbe, über replizierte Verzeichnisse | der Konfigurator | nichts — nur Transportsprünge |
|
|
| 10 Verträge | kompatibel: direkt; inkompatibel: ein Transformator | der Konfigurator | ein Transformator, nur wo Verträge sich unterscheiden |
|
|
| 11 MQTT | Topics auf einem Broker | der Konfigurator | nichts — der Broker ist Transport |
|
|
|
|
Die dritte Spalte von oben nach unten gelesen: die Topologie wandert nach aussen, Stufe um Stufe, bis keine Fähigkeit mehr etwas davon hält. Die letzte gelesen: der Preis dieser Wanderung fällt in Stufe 7 auf null und bleibt dort, während darunter dreimal der Transport wechselt. Dieselbe Architektur, besserer Transport.
|
|
:::
|
|
|
|
## [The sentences to remember]{.en}[Les phrases à retenir]{.fr}[Die Sätze, die man behalten sollte]{.de} {#sec-sentences}
|
|
|
|
::: {.en}
|
|
- **Event-driven describes how information and control flow.**
|
|
- **Loose coupling describes how much participants need to know about one another.**
|
|
- **Publish what happened.**
|
|
- **Declare what you want.**
|
|
- **Publish your own State.**
|
|
- **Keep capabilities egoistic.**
|
|
- **Keep topology out of capabilities.**
|
|
- **Do not pay for a mediator unless it actually mediates something.**
|
|
|
|
And whenever an architecture becomes confusing, go back to the first question of this book: **who knows whom?**
|
|
:::
|
|
|
|
::: {.fr}
|
|
- **« Event-driven » décrit comment circulent l'information et le contrôle.**
|
|
- **Le couplage faible décrit ce que les participants doivent savoir les uns des autres.**
|
|
- **Publiez ce qui est arrivé.**
|
|
- **Déclarez ce que vous voulez.**
|
|
- **Publiez votre propre état.**
|
|
- **Gardez les capacités égoïstes.**
|
|
- **Gardez la topologie hors des capacités.**
|
|
- **Ne payez pas un médiateur qui ne fait pas réellement de médiation.**
|
|
|
|
Et chaque fois qu'une architecture devient confuse, revenez à la première question de ce livre : **qui connaît qui ?**
|
|
:::
|
|
|
|
::: {.de}
|
|
- **„Event-driven" beschreibt, wie Information und Steuerung fliessen.**
|
|
- **Lose Kopplung beschreibt, wie viel die Beteiligten voneinander wissen müssen.**
|
|
- **Veröffentliche, was geschehen ist.**
|
|
- **Erkläre, was du willst.**
|
|
- **Veröffentliche deinen eigenen Zustand.**
|
|
- **Halte Fähigkeiten egoistisch.**
|
|
- **Halte die Topologie aus den Fähigkeiten heraus.**
|
|
- **Bezahle keinen Vermittler, der nicht wirklich vermittelt.**
|
|
|
|
Und wann immer eine Architektur verwirrend wird, zurück zur ersten Frage dieses Buches: **wer kennt wen?**
|
|
:::
|