Compare commits

..
Author SHA1 Message Date
jschoubben fc6cebd69b S5 hub-binds-a-process-durable: the process hub binds the durable of the process's own name, and Start's comment says its nil is started, never heard
Builds: design 47 H2b §836 5. (H-A-876), §836 1. (H-A-877)
2026-11-27 03:55:17 +01:00
jschoubben 6df5d82783 H2b-review-3 journal-lines-asserted: the hub rows assert the journal lines through logf, and a process reader row adopts an event after the hub's Start
Builds: design 47 H2b §836 4. (review round 1, part 1, item 3)
2026-11-27 03:53:04 +01:00
jschoubben e49fe6da5c H2b-review-2 wake-before-first-bind-row: a row where durables-composed is said from inside Start's failing bind and the stream is bound
Builds: design 47 H2b §836 2. (review round 1, part 1, item 2)
2026-11-27 03:52:27 +01:00
jschoubben c2972eb338 H2b-review-4 events-unheard-names-each: the finding events-unheard names every pattern not heard, no bound
Builds: design 47 H2b §836 4. (review round 1, part 1, item 4)
2026-11-27 03:52:01 +01:00
jschoubben df029926d0 H2b-review-1 hub-row-no-sleep: the late-live row reads Start's synchronous pass with default, no 300 ms wait
Builds: design 47 H2b §836 1. (review round 1, part 1, item 1)
2026-11-27 03:51:50 +01:00
jschoubben eaf16ed5dc H2b-review-8 hub-rows-name-n1: the hub rows name the node n1, no real node
Builds: design 47 H2b §836 (review round 1, part 1, item 8)
2026-11-27 03:51:40 +01:00
jschoubben 9392930a68 S3 hub-real-bus-rows: on a real bus the hub's Start binds a kept seat event's stream and a late durable is bound on durables-composed
Rows of TestTheHubBindsALateConsumerAndSaysItIsLive, no new top-level test.

Builds: design 47 H2b §836 (How it is checked); H-A-855
2026-11-27 03:00:57 +01:00
jschoubben dda65f1cf2 S2 events-unheard: the hub says each pattern it does not hear, and the process reader raises the finding
OnUnheard is told the patterns not heard with stream and why (no stream carries it, not composed,
refused, registered after Start), the journal says each; the process reader raises events-unheard
(id module.node) from it and clears it on an empty list. A reader with no findings writer says
them in the journal alone. A late first adopt is among the unheard patterns.

Builds: design 47 H2b §836 4.; H-A-834, H-A-840, H-A-854
2026-11-27 03:00:35 +01:00
jschoubben eca41b2b57 S4 decoder-sets-aside: an unknown word of a long-form invokes, requires or consumes entry is set aside and named
A consumes entry is a name or {event, ...}, read as its event, every other key set aside.

Builds: design 47 H2b §871; H-A-850
2026-11-27 02:57:21 +01:00
jschoubben 6a097cd036 S1 hub-binds-every-pattern: a handler registered after Start is refused, naming its pattern
Builds: design 47 H2b §836 3.
2026-11-27 02:57:06 +01:00
jschoubben 9d0478d12e S1 hub-binds-every-pattern: the subject of durables-composed names the grants part through buscompose.GrantsModule
mesh-sdk takes no new seat-specific name (ADR 0613 §5): the hub's wake subject is built from the one
literal it keeps for the grants part. API unchanged.

Builds: design 47 H2b §836 2.; H-A-835 as amended by H-A-864
2026-11-27 02:56:43 +01:00
jschoubben 2e192b4ebf S1 hub-binds-every-pattern: Start binds every kept stream a pattern needs, OnAllHeard, wake on durables-composed
StartKept is folded into Start and StartUntilBound goes with its timer; a durable not bound is
bound on the grants part's durables-composed and at the bus connection's reconnect; OnBound is
told at each durable's bind.

Builds: design 47 H2b §836 1., 2.; H-A-834, H-A-835
2026-11-27 02:55:06 +01:00
mesh-tools c42ada4525 Merge pull request 'Design 47 H2's corrections: ledger forms, ask once, the event hub by key, the away answers (issue 1984)' (#215) from feat/47-H2-corrections into main 2026-11-25 20:11:44 +00:00
jschoubben 6dd3141c5e hearHeld paces its pull at the kept-call pace and says each kind of error once
Builds: design 47 H2 §775, H-A-695 (2), H-A-733
2026-11-25 18:50:23 +01:00
jschoubben 0766acdd69 AnswerSeat answers away as the result in AwayAnswer's form
Builds: design 47 H2 H-A-708 (2), H-A-717 DQ-58, §776
2026-11-25 18:50:23 +01:00
jschoubben 8c35c72a9d stdio: the comment names the kind away, no stopping is left
Builds: design 47 H2 H-A-570 (3), §776
2026-11-25 18:50:23 +01:00
jschoubben c9d5f43cd6 seatlist.HolderNodesIn: each holder of a seat with its module and its node
Builds: design 47 H2 H-A-742
2026-11-25 17:41:55 +01:00
jschoubben 1d7c996ac9 S6 event-hub-by-key: Handle keeps its earlier form; HandleByKey holds by key
Builds: design 47 H2 H-A-683 (1), H-A-737 (1)
2026-11-25 17:25:17 +01:00
jschoubben eea766ae3c S1 needs-leave-the-sdk: ManifestNeeds, ModuleNeeds, the baseline reads and ReadDirectoryContentsOwner leave mesh-sdk
Builds: design 47 H2 H-A-568, H-A-622, H-A-605 (1), H-A-639, H-A-669, H-A-671
2026-11-25 17:21:12 +01:00
jschoubben 7ff8e07d2a S6 event-hub-by-key: the pull takes one message at a time and only while the hub has room
Builds: design 47 H2 H-A-695 (2), H-A-733
2026-11-25 17:19:38 +01:00
jschoubben 065e73e1dd S7 event-overrun: the hub times each handling, the finding event-overrun, ViewKinds names both
Builds: design 47 H2 H-A-683 (3), H-A-697 (1) (2) (3)
2026-11-25 17:16:27 +01:00
jschoubben fd01ec91a2 S9 kept-call-hook: process.KeptAsk gains the hook and keptOf hands it on
Builds: design 47 H2 H-A-708 (4), H-A-731
2026-11-25 17:14:46 +01:00
jschoubben 4f2c6cbdc8 S6 event-hub-by-key: the hub hands events by key, holds each and says it in progress
Builds: design 47 H2 H-A-683 (1), H-A-695 (1) to (5)
2026-11-25 17:13:22 +01:00
jschoubben f0bc6a3ceb S8 unread-away: Unread of a state and a view, the away answers, the start's phase
Builds: design 47 H2 H-A-708 (1) (2), H-A-717 (DQ-54, DQ-58)
2026-11-25 17:09:15 +01:00
jschoubben b4f9429115 S9 kept-call-hook: a kept call's hook at five minutes waited and at its answer
Builds: design 47 H2 H-A-708 (4)
2026-11-25 17:06:52 +01:00
jschoubben e6da0aeb5f S5 ledger-watch: stdio.WatchLedger and the bundle's mesh/ledger answer
Builds: design 47 H2 H-A-706 (DMC-13), H-A-717 (DQ-50)
2026-11-25 17:06:06 +01:00
jschoubben a123ebd643 S3 ask-once-ts: the TypeScript stdio asks once; the kind stopping goes
Builds: design 47 H2 H-A-570 (2) (3) (4)
2026-11-25 17:05:11 +01:00
jschoubben e5b66a77ba S2 ask-once-go: Ask calls once; the kind stopping goes
Builds: design 47 H2 H-A-570 (2) (3) (4), H-A-624 (3)
2026-11-25 17:04:29 +01:00
jschoubben cedfa71169 S4 ledger-forms: ends-with, ended-days, expires, a reindex naming an instance
Builds: design 47 H2 H-A-634 (3) (4), H-A-685 (1), H-A-690 (1)
2026-11-25 17:02:53 +01:00
mesh-tools bb11615b1a Merge pull request 'Test copies of node-uplink, node-resolver and node-display-session byte for byte (design 08 sign-in-page)' (#214) from feat/sign-in-page into main 2026-11-25 00:20:04 +00:00
jochen 40ac107900 Copy node-resolver byte for byte from mesh-connectivity-contracts
node-resolver.json is copied byte for byte from mesh-networking
modules/mesh-connectivity-contracts/seats/node-resolver/seat.json (11a1195, after its fix giving
routes' answer outside_writes as systemd-resolved does). node_resolver_test.go's decision text now
matches the real definition ("novox/hq ADR 0247, ADR 0687"); its verb list already matched.

This completes C-3 for mesh-sdk: all three test copies are now byte-for-byte copies of their
contracts modules' definitions.

Builds: design 08 sign-in-page §1, §2, §3; lead answer C-3
2026-11-24 21:50:43 +01:00
jochen 7c3e439e32 Copy node-uplink and node-display-session byte for byte from their contracts modules
Code review round 1 found the test copies were not copies: a reconstruction from the holders'
code drifted in a few fields and added ADR 0613 to the decision, which the real definitions do
not carry. node-uplink.json is copied byte for byte from mesh-networking
modules/mesh-connectivity-contracts/seats/node-uplink/seat.json (8d993ea), and
node-display-session.json from mesh-contracts seats/node-display-session/seat.json (3260a68a).
graphical_session_test.go's decision text now matches the real definition
("novox/hq ADR 0208, ADR 0687"). node-resolver.json and node_resolver_test.go wait for
mesh-networking's fix for outside_writes.

Builds: design 08 sign-in-page §1, §3; lead answer C-3
2026-11-24 21:48:49 +01:00
jochen 18c68fda5a Refresh the test copies of node-uplink, node-resolver and node-display-session to their whole definitions
mesh-sdk joins the sign-in-page milestone only to replace its seatlisttest copies with the three
seats' whole definitions, and to update the two tests that assert today's verbs; the seat-name
constants and the package's own code stay untouched (ADR 0613 §5: nothing seat-specific is added
to mesh-sdk).

Builds: design 08 sign-in-page §1, §2, §3, §4
2026-11-24 21:13:21 +01:00
mesh-tools 0cc22bd7a4 Merge pull request 'A module of its own account needs a node-engine that gives a directory's contents (design 47 H2, H-A-554, H-A-556)' (#213) from fix/gitea-runs-as into main 2026-11-23 11:31:53 +00:00
jschoubben 2ef966ca17 A manifest of its own account needs an engine that gives directory contents
A module moved to runs-as reads what it wrote before only once its node-engine
gives a directory's contents the directory's new owner. ManifestNeeds now names
the reader capability directory-contents-owner for every manifest declaring
runs-as, so the module graph orders such a module's move after that engine runs
on its node; the node-engine states it itself.

Builds: design 47 H2 H-A-554 (1), H-A-556
2026-11-23 12:23:58 +01:00
mesh-tools 31a1c5abb0 Merge pull request 'A stopping tool runner's fault is asked again by every caller (design 47 H2, H-A-542, H-A-544, H-A-549)' (#212) from fix/runner-stopping into main 2026-11-23 11:10:48 +00:00
jschoubben b3509e7d31 process: a reply's error-kind is read from its bytes, and tested so (H-A-549 (1))
Review round 2: the row for a stopping tool runner built its fault itself, so
requestAsk's reading of error-kind went untested. The reading of a reply (result,
error, error-kind, held) is now readReply, and the kept-call table reads the
runner's raw reply {"error": ..., "error-kind": "stopping"} through it.

Builds: design 47 H2 H-A-549 (1)
2026-11-23 12:09:05 +01:00
jschoubben 07bfc71c33 stdio (TypeScript): the ask's bound is the setting ask-bound; the pause has a seam (H-A-549)
Review round 1: the bound of asking again while the tool runner is stopping is the
setting ask-bound (default 60 s), and the pause and the clock are askPacing, which
the test replaces as the Go test does pause and askNow, so nothing sleeps. Rows
added: past the bound the fault is the caller's, a bare timeout stays a failure.

Builds: design 47 H2 H-A-542, H-A-544, H-A-549
2026-11-23 12:05:15 +01:00
jschoubben fdb85e8bd5 process, stdio: a kept call paces on a stopping tool runner; the ask's bound is a setting (H-A-549)
Review round 1: the process caller read only a reply's error, so a kept call
(CallKept, e.g. seat:git.trees) ended at once on stopping instead of pacing until
the new runner answers. requestAsk now reads error-kind stopping as
busretry.Stopping, which busretry.Fault counts as a transport fault, as away. The
Go stdio Ask's 60 s bound becomes the setting ask-bound (default 60 s), read by
the settings reader.

Builds: design 47 H2 H-A-542, H-A-549
2026-11-23 12:05:15 +01:00
jschoubben 6459dee6aa stdio (TypeScript): a stopping tool runner's fault reaches the bundle as such and is asked again (H-A-544)
As in the Go stdio: the runtime's answer names its typed fault in the error's data
error-kind, kept on the error as errorKind (isStopping); a broker request (mesh/ask)
met by stopping is asked again after a pause at the kept-call pace (the settings
kept-call-pace-first and -max, 1 s doubling to 30 s by default) until the new
runner answers or 60 s end, then the fault is the caller's. A plain refusal is
never asked again; a TypeScript bundle (the forge, the registries' holder) meets a
restarting runner as a Go one does.

Builds: design 47 H2 H-A-542, H-A-544
2026-11-23 11:51:56 +01:00
jschoubben 78a0c4d154 stdio: a stopping tool runner's fault reaches the bundle as such and is asked again (H-A-542)
A call a stopping tool runner did not take reached a bundle as a bare words error,
or, before the runner said so, as a "timeout", so a build step's publish failed
when the runner restarted (main.440). The runtime's answer now names its typed
fault (the error's data error-kind); stdio keeps it (ErrStopping, ErrorKind), and
Ask asks again after a pause at the kept-call pace until the new runner answers or
Ask's own bound ends, then hands the caller ErrStopping. A plain refusal and a bare
timeout are never asked again.

Builds: design 47 H2 H-A-542
2026-11-23 11:45:40 +01:00
mesh-tools 2992d7187f Merge pull request 'The TypeScript sdk's build refuses an undeclared bare import (design 47 H2 H-A-491)' (#211) from fix/ts-declares-blakejs into main 2026-11-23 01:08:40 +00:00
jschoubben a614536509 H-A-491: the build refuses built files that import an undeclared package
The forge's bundle met "Could not resolve blakejs" in the SDK's seal code. blakejs and tweetnacl are declared
dependencies already. The build now runs a check after tsc: every bare import in dist/**/*.js must be a Node built-in,
the package itself, or a declared dependency or peerDependency. The builder runs npm run build before npm pack, so a
package that breaks this is never published. The check lives under src because the builder's workspace holds only
the artifact's paths.

Builds: design 47 H2 H-A-491
2026-11-23 02:04:27 +01:00
mesh-tools 1fa56e1a0e Merge pull request 'A heard entry of the membership carries its consumer's spec (H-A-472, seventh and eighth addenda)' (#210) from fix/heard-issued-spec into main 2026-11-22 19:01:42 +00:00
jschoubben ed9e5bd700 membership: a heard entry carries its consumer's whole spec
A part that creates a hearing consumer itself (the tool runner, for a module's
_tools twin) reads the filters, ack wait, max deliver, max ack pending and
deliver policy from the membership instead of computing them, so the grants
part stays the one composer of filters. The fields are omitted when unset: an
older grants part's membership still reads, and an older reader ignores them.
HasSpec says which an entry is, so a reader binds an older entry by name and
creates a newer one from its spec.

Builds: design 47 H2 H-A-472 (seventh addendum, eighth addendum)
2026-11-22 19:12:50 +01:00
mesh-tools a6d22f10fb Merge pull request 'Design 47 H2: the kept call paced, take once, page by cursor, settings, class and caps, check-needs' (#209) from feat/47-H2 into main 2026-11-22 03:50:58 +00:00
jschoubben 087e41497e The tests' seat list takes again node-engine, whose have's pipeline description moved
seatlisttest takes again node-engine from mesh-contracts feat/47-H2 ba5a2538,
where only the have's pipeline description changed (a want's run is compared
with the have's run only when the want's branch is the same), no form change.
It is a bootstrapped seat, so the bootstrap copy and its captured contracts
copy are replaced too (ADR 0635 §3), and CAPTURED names the commit. Every
other seat and both parts still equal the group's heads (mesh-contracts
feat/47-H2 ba5a2538, mesh-delivery feat/47-H2 abfe37e6, mesh-networking
feat/47-H2 18e564c0).

Builds: design 47 H2, H-A-452, ADR 0635 §3
2026-11-22 03:15:14 +01:00
jschoubben 78fd003263 The tests' seat list takes again five definitions the group's heads moved, two of them bootstrapped
seatlisttest takes again mesh-builds (its verb publish-queue), mesh-delivery,
mesh-wants (keep-now), node-engine (form 4: the have's run keeps its pipeline,
the composition answer gains drift) and node-packet-filter from the group's
current heads (mesh-contracts feat/47-H2 8f2bed18, mesh-delivery feat/47-H2
abfe37e6, mesh-networking feat/47-H2 18e564c0), so a test judges a manifest
against the seats the running validator judges it against; every other seat
and both parts already equal those heads. The two bootstrapped seats among
them (mesh-delivery, node-engine) are replaced in the bootstrap and its
captured contracts copy too (ADR 0635 §3), and CAPTURED names the commits.

Builds: design 47 H2, H-A-452
2026-11-22 02:58:54 +01:00
jschoubben a323a3fd54 The tests' seat list holds the group's definitions: mesh-recovery and four more seats, eleven taken again
seatlisttest gains mesh-builds, mesh-delivery-view, mesh-grants,
mesh-pipeline-runner and mesh-recovery, which the live list (revision 473)
holds, and takes again the eleven definitions and two parts the group's heads
change (mesh-contracts feat/47-H2 e6ed560e, mesh-delivery feat/47-H2 80ff1afa,
mesh-catalog's form 5 from feat/47-H2-i 5e943280), so a test judges a manifest
against the seats the running validator judges it against. The three
bootstrapped seats among them (mesh-catalog, mesh-delivery, node-engine) are
replaced in the bootstrap and its captured contracts copy too (ADR 0635 §3,
ADR 0636 §7); the service manager's tests take its kernel-log verb, and the
grants module's name, now also a seat's, joins the kept names.

Builds: design 47 H2, H-A-452
2026-11-22 02:29:29 +01:00
jschoubben f90189353c Fold H2's new tests into existing ones: go/ at 327 unit tests (from 331), TypeScript at 48 (from 49)
The eight Go test functions H2 added become subtests of existing tests
(catalogue's state test, the bundle's state test, the views test, the process
state test, the testbus bus test, the seal byte-for-byte test), and four more
are folded beside them (two seal, two process watch); the two TypeScript seal
tests become one, and two more TypeScript tests are folded into their
neighbours. No assertion is lost.

Builds: design 47 H2 §819
2026-11-22 02:25:44 +01:00
jschoubben 7d7a89411c M1 check-needs: a manifest names at its top level the seats a package outside every artifact's from needs
A package no artifact's from holds (the forge module's seatgit whole test) has no artifact to carry its
check-needs, so the module says it once at its level, in the artifact's form (H-A-453 (2)).

Builds: design 47 H2 §800, H-A-453 (2)
2026-11-22 02:24:49 +01:00
jschoubben 4e338436da Kept-call pace read once and atomically: no data race with the kept calls reading it
ReadPace wrote the pace at every Connect and Serve while kept calls on other
goroutines read it. The pace is now held atomically and read once at the
start: a later read of the same pace changes nothing, one of another pace is
refused naming both. KeptPace becomes a function.

Builds: design 47 H2 §782, §775
2026-11-22 02:21:53 +01:00
jschoubben 03e2aca59f S4 page by cursor: a page hands a kept delete as an entry marked deleted with no value
A reader following pages removes the key, so a deleted key never comes back
alive from a bucket with history.

Builds: design 47 H2 §779, H-A-451 (1)
2026-11-22 02:19:27 +01:00
jschoubben ed281663fd S16 addendum: a waiting ask says when it waits again after a nak
Builds: design 47 H2 §777, H-A-410 and its addendum
2026-11-22 01:00:24 +01:00
jschoubben d6cdf3b8f5 S15 TypeScript seals: seal, open and sealAnonymous beside go/seal
The forge module's minting processes are TypeScript and the vault's two steps need ADR 0206's
sealed box and the NaCl anonymous box its intake opens; both now live once in mesh-sdk, proven
byte for byte against the Go package's bytes (tweetnacl 1.0.3 and blakejs 1.2.1 pinned).

Builds: design 47 H2 §808, §822, H-A-407 and its addendum
2026-11-22 00:59:54 +01:00
jschoubben 3ad8ccbc06 S16 QueueWaiting: a holder reads its own seat queue's waiting asks through the runtime
A holder's asks tool answers what waits on its seat's queue; the queue is its own store, so
the read is the owner's, one shared form asked of the tool runner as mesh/queue.waiting.

Builds: design 47 H2 §777, H-A-410
2026-11-22 00:56:35 +01:00
jschoubben 3f8f35a87a S14 kept chunked call: CallChunksKept and CallFileKept pace the ask and carry its id on every chunk
The assigner's compose-candidate ask is chunked, and the one-shot CallFile ended at the
first no responders; the kept call's form now makes the chunked call too.

Builds: design 47 H2 §775, H-A-405 (1), H-A-351
2026-11-22 00:55:25 +01:00
jschoubben c99295c21d The starved setup's line lives in the root package
stdio.SetupStarved holds "mesh: setup starved:" so the delivery SDK reads
it without importing testbus; testbus.SetupStarved names it.

Builds: design 47 H2 §800; H-A-368, H-A-399
2026-11-22 00:52:02 +01:00
jschoubben 5dd0d66acb S10 check-needs names the seats a package's tests need the node to hold
check-needs is a list of seat names (node-build-node), as the marker
file named them, not the value node-modules.

Builds: design 47 H2 §800; H-A-350 DMC-6, H-A-399 (3)
2026-11-22 00:44:18 +01:00
jschoubben e54151336e S13 bootstrap copy of git: take the git seat as D5 defines it
The bootstrapped definition, its test copy and the captured contract file
are replaced by mesh-delivery's seats/git/seat.json at D5 (tags name their
commits, a holder says away), byte for byte.

Builds: design 47 H2 §796, §776; H-A-350 DMC-3
2026-11-22 00:22:57 +01:00
jschoubben 98ed28c1d1 S12 class: a manifest says whether its module is core or a leaf
The gate reads a mover's class from its catalog entry; a module that
names none is a leaf.

Builds: design 47 H2 §810, §814; H-A-394 (1)
2026-11-22 00:21:38 +01:00
jschoubben 7e538e3eae S12 caps in the catalog: a manifest says each kept store that names no cap
The manifest validator refuses a delivery module's state, log or objects
entry with no cap; the catalog reads them from the old sections and the
requires entries alike, so the validator judges one list.

Builds: design 47 H2 §814, §812
2026-11-22 00:20:57 +01:00
jschoubben 134b111e3f Raise the declaration's Version to 2 for drain-bound; manifests state the Version read and written
Version is the declaration's form: drain-bound raises it by one, and a
node-engine refuses only a higher one, so it still takes what a composer
of version 1 writes. A manifest says declaration-reads (the node-engine's)
and declaration-writes (the composer's), so the delivery plan can order
the writer of a Version after every engine that reads it.

Builds: design 47 H2 §813 (12), H-A-388 (2), H-A-358
2026-11-22 00:19:52 +01:00
jschoubben 484e2bba3c S11 prune helper and tools: a kept store is pruned toward its cap at its own writes
A process judges a running sum of what its writes put against the figures
read at the bind and after each prune; a bundle judges the fill the
runtime's put answer carries. Past prune-mark (70 %) the oldest keys by
revision go down to prune-target (50 %), in one journal line; a key kept
under _keep/<key> stays, and no reader counts the keep. The generic tools
<module>_state_prune_now and <module>_state_keep act through the hand-act log.

Builds: design 47 H2 §812, H-A-380, H-A-386
2026-11-22 00:17:36 +01:00
jschoubben fe052c135e Read a state's max-mib in the manifest-reads baseline
Every running node-engine reads a state's max-mib (it writes every
module's bucket cap from it), so the baseline a node-engine that states
nothing is read as stating carries it.

Builds: design 47 H2 §812, §820; H-A-383
2026-11-22 00:06:15 +01:00
jschoubben 450ea7eddc S10 check-needs: a Go artifact declares what its tests need in its manifest
catalogue.Artifact gains check-needs (node-modules), the field that
replaces the marker file in a package's directory; its readers read it
from the manifest.

Builds: design 47 H2 §800; H-A-350 DMC-6
2026-11-22 00:04:53 +01:00
jschoubben eee02a20a9 S7 safe for concurrent use: hold the bus wrappers to it under the race detector
Many goroutines' gets, puts, pages, keys and watches through one bundle's
runtime channel, one process connection's state and one process reader's
pictures run under the race detector; no unguarded call was found, so the
tests hold the wrappers to it.

Builds: design 47 H2 §782; H-A-349 DQ-3
2026-11-22 00:03:19 +01:00
jschoubben e9481928f5 KeptPace from settings: a module's declared pace paces its kept calls
busretry.ReadPace sets the kept-call pace from kept-call-pace-first and
kept-call-pace-max through the one settings reader; process.Connect and a
bundle's Serve read it at their start and refuse a value that is no
duration.

Builds: design 47 H2 §775, §781; H-A-370
2026-11-21 23:59:04 +01:00
jschoubben 139626daab S9 setup bound: a starved setup on the bus says so in one line
A test's setup waits on the bus for half of its level's bound
(MESH_TEST_LEVEL_BOUND), 30 s when unset, and fails with the line
"mesh: setup starved:" a build module reads to run the level again.

Builds: design 47 H2 §800; H-A-368
2026-11-21 23:57:12 +01:00
jschoubben 92cb6a8d6d S4 page by cursor: a state page continues from an opaque cursor in sequence order
The runtime's mesh/state.page takes the cursor the page before answered as
next, so a state is read once however many pages it takes; a key written
again since an earlier page comes marked seen-again.

Builds: design 47 H2 §779
2026-11-21 23:56:07 +01:00
jschoubben 6d290eb46b S6 settings: read a setting by its key in a process and a bundle
The node-engine composes each config value as MESH_CONFIG_<KEY>, in a
process's environment and the module's tool-runner slice alike;
stdio.Setting and SettingDuration read it, the one reader both sides use.

Builds: design 47 H2 §781; H-A-350 DMC-13, H-A-370
2026-11-21 23:23:15 +01:00
jschoubben ab05031e9a Purge a deleted object's leftovers through the runtime's delete
The runtime's objects delete already purges an object's chunks, and purges
them again when asked again: Purge and purgeObject ask it, and no act of
their own is added.

Builds: design 47 H2 §812; H-A-366 (correction)
2026-11-21 23:22:38 +01:00
jschoubben 75287d8ce5 Let a bundle purge a deleted object's leftovers through the runtime
The runtime's objects act purge removes a deleted object's chunks:
busstate.Objects.Purge and TypeScript purgeObject, so the registry's
program opens no connection of its own for it.

Builds: design 47 H2 §812; H-A-366
2026-11-21 23:20:52 +01:00
jschoubben 0c27544582 Let a holder take asks once over a store bound on its own link
process.StateOver gives a State over a key-value store the caller bound
itself, so the node-engine, which serves its seat over its own link, keeps
the asks it took in its own taken state.

Builds: design 47 H2 §775; H-A-364
2026-11-21 23:19:11 +01:00
jschoubben 6852228000 Derive a seat's work queue and its worker from the seat definition
An accepted kind names its work queue's settings (max-age,
duplicates-window, ack-wait, in-progress, max-msgs, max-ack-pending,
max-deliveries); buscompose.SeatQueue derives the seat's work-queue stream
and its one shared worker from them, once, for the grants part to take.

Builds: design 47 H2 §777; H-A-350 DMC-1, H-A-362, H-A-340 (1)
2026-11-21 23:18:34 +01:00
jschoubben 1f2b1cd46b Carry a seat definition's form and a part's form
A definition and a part gain form, raised at every field their messages
add or remove; absent reads 1 and below 1 is refused, so the generator can
hold a changed definition to a raised form.

Builds: design 47 H2 §780; H-A-352 (1)
2026-11-21 23:14:28 +01:00
jschoubben 25b3030a93 S2 take once in a bundle too, Go and TypeScript
A bundle holder takes an ask once through the runtime's create with the
ask's bound as the key's time to live: stdio.KeptState.TakeOnce and
TypeScript takeOnce; stdio.TakenState and TakenKey are the one name, which
process refers to.

Builds: design 47 H2 §775, §820; H-A-359
2026-11-21 23:12:58 +01:00
jschoubben 423de0e8a2 S3 away: read a holder's answer of the kind away as a transport fault
A holder answers error-kind away, with part and words, when a part it
depends on is away; the kept call reads it from the answer and calls again
at the pace. Go: busretry.ErrorKindAway, AwayAnswer, AwayIn, Away;
TypeScript: ERROR_KIND_AWAY, awayAnswer, awayIn.

Builds: design 47 H2 §776, §775; H-A-349 DQ-15, H-A-350 DMC-2, H-A-354
2026-11-21 23:10:27 +01:00
jschoubben d40fa0b3a0 Carry a process's drain bound in the declaration
A process that stays up may name drain-bound (seconds): the node-engine
writes its unit's stop from it, so the tool runner finishes its calls in
flight before it exits. Absent is none; a step or a scheduled run is
refused one.

Builds: design 47 H2 §813 (12); H-A-358, H-A-353
2026-11-21 23:08:38 +01:00
jschoubben f5dc3b6bd1 S2 take once: keep the ids a holder took in its state taken
A holder of a kept call takes an ask once by its id: TakeOnce creates
<seat>.<ask> in the state taken with the ask's bound as its time to live,
and a second ask of the same id within it answers false.

Builds: design 47 H2 §775, §820; H-A-338 (6), H-A-339 (4)
2026-11-21 23:08:38 +01:00
jschoubben 14c2532b0c S1 kept call paced: carry the ask id, pace at the settings' defaults with jitter, stop at the caller's bound
The kept call is made again on a transport fault after kept-call-pace-first
(1 s) doubling to kept-call-pace-max (30 s), each wait within 20 %, until
the caller's bound; past it the answer names every call's time and words.
One journal line per seat at the first fault, then at most once a minute.
The ask id travels in the header x-ask; a holder reads it with
process.AskOf, a bundle with stdio.AskIDOf (TypeScript askIdOf) from the
call's _meta mesh/ask.

Builds: design 47 H2 §775; H-A-351
2026-11-21 23:06:24 +01:00
mesh-tools bdc5cff0d6 Merge pull request 'Design 47 H1: the event hub pulls small batches and keeps slow handlers alive (H-A-281)' (#208) from fix/47-H1-sdk-hub-small-pulls into main 2026-11-21 15:51:39 +00:00
jschoubben fedf9d2e7b Pull small batches in the event hub and keep slow handlers alive (H-A-281)
The hub pulled the bus client's default 500 messages per pull and handled
them one by one, so buffered messages outlived the 30 s ack wait and were
given again and handled twice (met live on the builder: 37 of 38
outstanding redelivered). HearEvents, the one pull of the hub and of
HearStream, now pulls at most twenty messages per pull and says in
progress for a message whose handler runs past a third of the consumer's
ack wait, read once from the bound consumer's information.

Builds: design 47 H H-A-281
2026-11-21 16:48:05 +01:00
mesh-tools dfcf2147bc Merge pull request 'Design 47 H1, proof 2: one comment in the SDK, delivered with its importer in one merge call' (#206) from proof/47-H1-sdk into main 2026-11-21 11:27:05 +00:00
mesh-tools 49b7db386a Merge pull request 'Design 47 H1: a held findings writer seeds only the kinds it owns; retired kinds clear once (H-A-242)' (#207) from fix/47-H1-sdk-held-writer-owned into main 2026-11-21 10:50:20 +00:00
jschoubben 78807e5ef3 Design 47 H1: a held writer always starts; a retired entry may name its scope
Start returned at the first early write, early clear or retired clear that
failed, before the writer started, so one refused kind stopped the writer
whole. A refused kind is now skipped (refuse said it once) and any other
failure is said in the journal and left to the next start; the writer always
starts. A RetiredKind may name its Scope, so an entry clears only keys of it.

Builds: design 47 H H-A-242 (3), H-A-249, G §580
2026-11-21 11:47:20 +01:00
jschoubben d06835bf93 Design 47 H1: a retired kind may name the ids its writer once wrote
Where another writer of the same state owns a retired kind now, clearing every
key of it would clear that writer's findings. A RetiredKind entry names its
kind and, optionally, the exact ids and id prefixes this writer wrote under
it; Start clears only those keys, every key of the kind when none are named.

Builds: design 47 H H-A-247 (3), H-A-249, G §580
2026-11-21 11:42:45 +01:00
jschoubben 220d511f95 Design 47 H1: a held writer clears its retired kinds once at start and reads only its own keys
A kind no code raises any more stood in the state with its condition open and
nobody to clear it. A writer's Retired kinds are cleared once at Start, said
as finding-cleared so the keeper clears their conditions, and never seeded;
Start reads (Get) only its own and its retired keys, checking ownership first.

Builds: design 47 H H-A-242, H-A-247 (3), G §580
2026-11-21 11:39:08 +01:00
jschoubben af2abcf121 Design 47 H1: a held writer seeds only the kinds it owns; an unowned kind is said once
The tool runner's held writer seeded every key of the module's shared state
`findings`, the daemon's kinds included, and then refused them once a minute,
so no finding of the indexer was stated. Start now seeds only keys of the
writer's own kinds (G §580: another bundle states its own), and a kind the
writer does not own is refused with "finding kind X not declared", said in
the journal once per kind and left out of a statement, never retried.

Builds: design 47 H H-A-240, H-A-242 (1) (3), G §580
2026-11-21 11:28:04 +01:00
jschoubben 3bc7da52e4 Design 47 H1, proof 2: mark the SDK side of the two-module change
The process package's doc names the proof, so the SDK publishes a new version that node-tools, its importer, is built against in the same merge call.

Builds: design 47 H §5 step 7, G §370
2026-11-21 01:46:34 +01:00
mesh-tools bc138366af Merge pull request 'Design 47 H1: the views reader's test waits for the acknowledged floor, not the pending count (H-A-196, H-A-197)' (#205) from fix/47-H1-sdk-views-one-durable into main 2026-11-21 00:27:19 +00:00
jschoubben 4a5eb26f4e views: read the durable's ack floor up to a mark, not its pending count, after the handlers spoke
The views test read NumAckPending as soon as the picture and the adopted handler had said the last event, but the
reader acknowledges after both, and the bus takes acks on its own; on the loaded build node (pipeline main.54) one
ack was still pending. The reader binds the module's durable once (the hub's one pull); the guard of H-A-196 is not
involved. The test now publishes a mark the hub hands after every event before it, acknowledged with the bus's
answer, and reads that the ack floor reached the mark; an event the owner says after it may still wait.

Builds: design 47 H §774, H-A-196, H-A-197
2026-11-21 01:20:35 +01:00
mesh-tools 173a8c120d Merge pull request 'Design 47 H1: a process pulls a durable consumer once; ConsumeOnce claims, pulls and releases (H-A-196)' (#204) from fix/47-H1-durable-pulled-once into main 2026-11-20 23:53:09 +00:00
jschoubben becaf8096a H-A-196: one SDK function claims, pulls and wraps a durable's loop
The tool runner would otherwise copy the claim's wrapper (review round 1, P7):
ConsumeOnce claims the durable, pulls it and answers the loop, and HearEvents
uses it; Conn.Consume claims through the same guard. A drain keeps its claim
until the loop ended, and the loop's Closed is closed only once the claim is
released, so a bind during a drain is refused and one after it is never.

Builds: design 47 H H-A-196, H-A-197
2026-11-20 22:18:43 +01:00
jschoubben c1c369f50c H-A-196: a process pulls a durable consumer once
A second pull loop on a durable the same process already pulls takes every other
event from the first, and nothing said so: the tool runner's two loops on the
indexer bundle's durable left the catalog seat's revision verb stale twice today.
The SDK now refuses it at bind time, naming the durable and both binders:
PullOnce claims a durable (by stream, name and the time the bus made it), and
HearEvents and Conn.Consume claim through it, releasing on stop, drain or the
bus ending the loop.

Builds: design 47 H H-A-196
2026-11-20 22:05:14 +01:00
mesh-tools c15460faf5 Merge pull request 'Design 47 H1: a view reader hears an event on its bare subject; an unhandled event is the module's finding (H-A-166, H-A-169)' (#203) from fix/47-H1-sdk-bare-subject into main 2026-11-20 16:55:39 +00:00
jschoubben a5225dfac3 views: wire the unhandled-event count once, and prove it on the bus
The hub's hook, the path the live fault took, had no test that failed
without it, and each Start appended it again, so a second Start counted
every event twice. Start now wires it once per hub and keeps the time of
the first start; the shared-durable integration test holds the reader's
finding of the one event nobody takes, counted once across two starts.

Builds: design 47 H H-A-169
2026-11-20 17:52:48 +01:00
jschoubben e568e6dc63 views: count the events no handler takes as the module's finding
An event a module consumes that no handler takes was said in the journal
alone, so a part that never acted on it (the runner's placing at 17:34) was
seen only by reading the log. The event hub now tells a hook of each such
subject; the process reader, where it holds a findings writer, counts them
in one finding event-unhandled per module (the count since the start and
the last subject) and clears it at its start, since a new build may handle
the event. Without a findings writer the journal line stands alone.

Builds: design 47 H H-A-166, H-A-169
2026-11-20 17:45:27 +01:00
mesh-tools 723c747cea Merge pull request 'Design 47 H1: proof 2, a two-module change along a dependency edge delivered by its pipeline (H §5 step 7)' (#202) from proof/47-H1-two-modules into main 2026-11-20 16:44:50 +00:00
jschoubben 7aae152760 views: hear a seat's event on its bare subject as on its further parts
A seat's contract says an event on its bare subject (the seat mesh-catalog's
registration-changed), while both view readers adopted it on `<subject>.>`
alone, so the event hub acknowledged it unhandled and the part never acted.
The process reader now registers one handler on both forms of the hub (the
two patterns do not overlap, so a message reaches it once), and the stdio
reader subscribes both forms with the one handler.

Builds: design 47 H H-A-166
2026-11-20 17:43:14 +01:00
jschoubben 3667ec96a0 Design 47 H1: proof 2, a two-module change along a dependency edge delivered by its pipeline (H §5 step 7) 2026-11-20 17:06:03 +01:00
mesh-tools 1fff67f017 Merge pull request 'Design 47 H1: seat definitions and generated packages (checker gone, callers API gone, Composed removed)' (#201) from feat/47-H1-seats into main 2026-11-20 07:13:06 +00:00
jschoubben 237e5fcc91 catalogue: no mention of the seat mesh-delivery-checker is left (CheckerSeat, its baseline word and the exclusion)
Builds: design 47 H §764 (The checker), H-A-57
2026-11-20 04:55:49 +01:00
jschoubben 034b67110b sdk-seat-copies-h1: the copy of mesh-catalog equals mesh-delivery's file at 9a55e6e8 (through C1d)
Builds: design 47 H §745, H-A-42
2026-11-20 04:16:17 +01:00
jschoubben 229e7ea755 sdk-seat-copies-h1: the copy of mesh-delivery equals mesh-delivery's file at c94e8564 (through C3c)
Builds: design 47 H §737, H-A-95
2026-11-20 03:49:40 +01:00
jschoubben 4b7889e0d6 sdk-seat-copies-h1: the copies of git, mesh-delivery and mesh-catalog equal mesh-delivery's files at be741a7a (through C1c)
Builds: design 47 H §737, §745, H-A-42
2026-11-20 03:46:23 +01:00
jschoubben f1b828c6e5 process: Account.NamedEventConsumer binds the durable <node>_<module>_<suffix> beside EventConsumer's
Builds: design 47 H §743, H-A-90
2026-11-20 03:31:31 +01:00
jschoubben 7f3b712a1f motion: a want carries no composed digest, so a have at the wanted fingerprint is applied; the test copy of mesh-wants at C-W
Builds: design 47 H §750, H-A-37, H-A-78
2026-11-20 03:11:33 +01:00
jschoubben 177847e24f sdk-seat-copies-h1: the copy of git equals mesh-delivery's file at d24d6a08; the test build seats take their acts without a bound
Builds: design 47 H §734, §736, H-A-42, H-A-71
2026-11-20 02:53:20 +01:00
jschoubben 67369c99aa sdk-seat-copies-h1: the copy of mesh-delivery equals mesh-delivery's file at C3 (6e027de5)
Builds: design 47 H §737, §752, H-A-42
2026-11-20 02:50:53 +01:00
jschoubben 809fe9aa66 sdk-seat-copies-h1: the copy of git equals mesh-delivery's file at C2 (f8bbde96); the timeout comment names the 30 seconds bound
Builds: design 47 H §734, §736, H-A-42, H-A-65
2026-11-20 02:46:24 +01:00
jschoubben 77a7b187f4 sdk-seat-copies-h1: the copy of mesh-catalog equals mesh-delivery's file at C1 (f006ab50); git and mesh-delivery equal theirs
Builds: design 47 H §745, §752, H-A-42
2026-11-20 02:43:42 +01:00
jschoubben c74f332eba sdk-holder-callers-gone: the gate knows a first-view tool by its name; ViewCallersPrefix and views.CallersEnv go
Builds: design 47 H §752, H-A-66, H-A-69
2026-11-20 02:37:45 +01:00
jschoubben b54a05a687 sdk-holder-callers-gone: no holder keeps a callers list; every seat-list tool and first-view tool answers every caller
go/callers.go goes (stdio.Callers, VerbCallers, ParseCallers, ParseVerbCallers, ConfiguredVerbCallers, HoldVerbCallers, AnyPerson, CallerSeatPrefix; ModuleOf stays in caller.go). seatlist.NewPart(prefix), Tools(r, read, again); ToolsWith, Refusal, RefusalWith and Part.Holders go. views.FirstViewTool loses its callers argument; views.ParseCallers and views.Refusal go. approval.ViewCallersPrefix and views.CallersEnv stay until the question of how the gate tells a first-view tool is answered.

Builds: design 47 H §752, §764, H-A-41, H-A-66
2026-11-20 02:37:10 +01:00
jschoubben 98e3209d70 sdk-seat-copies-h1: the copy of node-engine takes the step placing
Builds: design 47 H §771, H-A-67
2026-11-20 02:36:05 +01:00
jschoubben bc6c7a7710 sdk-callers-refused: seatdef refuses callers and drops the checker's copies
A definition naming callers is refused (a field the format does not know); Callers, DefaultCallers, EffectiveCallers, CallerEntryProblem and the Caller constants go. The test seat list's seats lose their callers. The seat mesh-delivery-checker's bootstrap, test and captured copies go.

The copies of git, mesh-delivery and mesh-catalog (bootstrap, test, captured) have only their callers lines taken out by hand so this commit's tests are green: they are replaced by mesh-delivery's contracts files in sdk-seat-copies-h1's remainder.

Builds: design 47 H §752, §764 (The checker, Every seat contract), H-A-41, H-A-42, H-A-57
2026-11-20 02:34:34 +01:00
jschoubben f60ccc2cfa sdk-seat-copies-h1: the copies of node-engine and operator-channel equal mesh-contracts' files at feat/47-H1-seats
The copies of git, mesh-delivery and mesh-catalog follow with mesh-delivery's contracts commit.

Builds: design 47 H §751, §764, §771, §772, H-A-42
2026-11-20 02:32:16 +01:00
jschoubben bd2db73c3b approval: the gate reads no held-back ask (the operator channel offers every ask)
Builds: design 47 H §764 (The operator channel's limit), H-A-57
2026-11-20 02:31:54 +01:00
jschoubben 59a73e72c0 seatdef-verb-timeout: a verb's definition names a timeout of whole seconds, 1 to 600, others refused
Builds: design 47 H §760, H-A-43
2026-11-20 02:30:41 +01:00
jschoubben be306f4a04 seat list: the captured mesh-catalog and mesh-config definitions lose config-candidates and kept (issue 1982; ADR 0681 §7)
The bootstrapped, test and beside copies are the seats' files as the contracts hold them after the removal of the pull
request path (design 47 G); the views test names a
state the indexer still has.

Builds: ADR 0681 §7 (mesh-sdk's seat list definitions of mesh-config's `kept` and the mesh-catalog seat's `config-candidates` go).

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-19 22:51:27 +01:00
mesh-tools bee9aa6e1c Merge pull request 'approval: test table as gofmt writes it (unblocks the sdk's lint step)' (#199) from fix/gofmt-approval-test into main 2026-11-19 12:23:24 +00:00
jschoubben e5d5b2d267 approval: the test table as gofmt writes it, so the sdk's lint step passes and #198's version can be published
Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-19 12:06:12 +01:00
mesh-tools 61548a07b5 Merge pull request 'A-481: catalogue Resolve keeps a templated module's archive digest' (#198) from fix/a481-composition-templates into main 2026-11-18 00:54:46 +00:00
jschoubben 3bb2c4e7f4 catalogue: Resolve keeps the digest of a templated module's archive as TemplatesDigest (A-481, A-481a)
Builds: design 47 G A-481, A-481a
2026-11-17 23:43:08 +01:00
mesh-tools 57f03e9f65 Merge pull request 'approval: the first views run before any seat list is read' (#197) from fix/approval-first-view into main 2026-11-16 17:03:27 +00:00
jschoubben 2559c205bb approval: the first views run before any seat list is read (novox 2026-11-16 deadlock)
Cause: startRead looked only in the definitions the runner holds. The seat list is itself read through the seat
mesh-catalog, so before the catalog half is ready the runner holds none, and every first view it waits on (its own
and another runner's, from any account) was refused with "marks not read yet" for ever.

Quick fix: let the one account that stalled through (calledByModule). Thorough fix (chosen): the foundation's bootstrapped
definitions answer for the seats they name wherever the held list lacks them, so a first view runs whoever asks; an act
of the same seat and a seat no definition names stay held.

Test: TestTheFirstViewsRunBeforeAnySeatListIsRead (fails without run.go change).

Builds: design 47 G A-387, A-388, A-433
2026-11-16 18:00:04 +01:00
mesh-tools 08c6e3a21e Merge pull request 'Design 47 G start: SDK fixes placed by hand' (#196) from fix/47-G-start-3 into main 2026-11-16 14:15:08 +00:00
jschoubben 9b77f82c8b process: the integration test of the seat's callers follows A-434 (an unproven caller of a read definition is admitted)
Builds: design 47 G A-434
2026-11-16 09:40:47 +01:00
jschoubben 88c385a7d2 process: an unread seat definition holds a verb that may need approval for a caller that is no module's account
A-435: the mesh MCP server's account, a person and an unproven caller are held as before while the definition is unread;
a module's account runs it (A-433).

Builds: design 47 G A-433, A-435
2026-11-16 09:40:21 +01:00
jschoubben 1182cadc9d approval: before the catalog half is read, a module account's call runs unmarked, seat verb or tool, and a module's own call in its runtime of its own (design 47 G A-433) 2026-11-16 02:34:22 +01:00
jschoubben 45ee5a2a88 views: a picture whose answer names no make time is judged by its revision alone
The assigner's first view of the indexer's modules stayed behind from 2026-11-14 15:04 UTC: events said the state was
made 2026-10-29, the answer named no make time, and zero is always before it, so it asked 378 times and took in no
event; every want kept its build of that day (the indexer's own new build was never wanted, so mesh-delivery #219
was never taken in).
2026-11-15 23:38:39 +01:00
jschoubben 58c396e3dc process: a seat verb answered by a process admits every caller
The operator, 2026-11-15 23:25 CET: every module, agent and operator may call anything. A marked verb still goes
through the holder's gate.
2026-11-15 23:27:12 +01:00
jschoubben 8eb20000c9 Findings writer: a Write or Clear never holds its caller on the bus past SayWithin, and never holds its lock while waiting on it
The writer's lock was held through the event's resend (up to PublishRetryFor, one minute), so one unacknowledged event
blocked every other Write and Clear behind it.

Builds: design 47 G §383 (the next statement covers an event not acknowledged; the state alone holds the finding)
2026-11-15 01:38:17 +01:00
jschoubben 958b327432 EventHub.StartKept: a program binds its durable on each kept seat event's stream it handles (A-397: the tool runner reads its own twin) 2026-11-14 18:58:20 +01:00
jschoubben 9ec8a88cb0 A call nobody answered names the subjects it was asked on and how long it waited, so its caller's log says where it went unanswered (operator, 2026-11-14: add logging) 2026-11-14 16:17:14 +01:00
jschoubben 7fab6ecde2 Let another module's call of a module tool run unmarked before the catalog half is read
The take-in's call of the forge bridge's tool was refused while the runner's catalog half was
unread: a module tool names no class, and its marks live only in the half the take-in makes.
A module tool whose proven caller is another module's account now runs unmarked then, logged
once per tool with its caller; the console's account (the runner's own), a person, the
controller and an unproven caller still wait and are judged as before.

Builds: design 47 G lead answers A-389

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-14 02:40:37 +01:00
jschoubben 98d275661f Let the gate's start path through every verb the held definition classes read
Before its catalog half is read, a tool runner's gate admitted a hand-kept
list of seat verbs; the first take-in then failed on git.pull and the
runner's own mesh-catalog.seat-definitions. The gate now reads the seat
definition the runner holds (its catalog's Definitions, the seat list):
a verb classed read explicitly and not marked needs-approval runs; a
verb naming no class, an act, or a marked read is judged as before.

Builds: design 47 G lead answers A-387, A-388

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-14 02:26:17 +01:00
jschoubben f11ef2f5dd Bootstrap the git seat and take the reads the catalog and broker seats now class
The first take-in reaches the seat git before a tool runner's seat list is
read, so its definition is bootstrapped, a copy of its contracts file with
its row in the bootstrap test; the catalog and broker copies follow their
contracts, which class their reads.

Builds: design 47 G lead answers A-387, A-388

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-14 02:24:25 +01:00
jschoubben c01a3de0b2 Let the approval gate's start path through a module's own first-view tools (A-377)
The tool is told by the callers list its bundle's environment carries (views.CallersEnv); the list still limits who.

Builds: design 47 G A-377 (widens A-359 toward A-353)

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-13 23:14:06 +01:00
jschoubben 6903ed97cd Let the approval gate's start path through mesh-broker.list (A-375)
Builds: design 47 G A-375 (extends A-359)

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-13 22:47:21 +01:00
jschoubben d11e2423ff Merge pull request 'G start: the runner admits first-view seat verbs before the catalog half is read; the SDK declares the verbs it calls' (#195) from fix/47-G-start into main
Reviewed-on: #195
2026-11-13 19:07:59 +00:00
jschoubben ab355879f0 Bootstrap the seat mesh-delivery so a runner admits its source before the seat list is read (A-362)
mesh/delivery merged: source.main moved to novox/mesh-sdk@d11e2423ff04
mesh/delivery-group group fix/47-G-start merged: every member is merged
The catalog half is read through mesh-delivery's source as well as mesh-catalog's verbs, and a runner with an unread
seat list admitted only the latter. The bootstrapped copy is mesh-delivery main 21eaa55b's contract file, byte for
byte; the tests' seat list and the captured beside copy take the same file.

Builds: design 47 G lead answers A-362, A-353

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-13 17:45:44 +01:00
jschoubben affde04396 Declare the seat verbs the Go package calls on a module's behalf (A-357)
Every module built against the SDK reads its catalog half through mesh-catalog's registrations, revision and entry and
mesh-delivery's source; naming them in the Go package's calls lets the indexer order such a module after the running
versions that serve its start.

Builds: design 47 G lead answer A-357 (the SDK half), §47 kind 6

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-13 17:30:03 +01:00
jschoubben d6ca425737 Let a tool runner's catalog-half reads through its gate while that half is unread (A-353)
A runner serving the indexer's tools refused every call until its own catalog half was read, and that read is a call of
the same seat verbs through the same gate: G could not start. The four seat verbs the catalog half is read by now run
unmarked while it is unread; every other call waits and is refused as before.

Builds: design 47 G lead answers A-353, A-359

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
2026-11-13 17:28:58 +01:00
mesh-tools cf6bc7612f Merge pull request 'Milestone 47 G: mesh-sdk's part of the one release' (#194) from feat/47-G-join12 into main 2026-11-13 13:08:12 +00:00
183 changed files with 24096 additions and 7479 deletions
+2
View File
@@ -30,6 +30,8 @@ type Call struct {
Description string
// Own says it is one of the runner's own tools served under the module's name (its ledger repairs), not its bundle's.
Own bool
// Env is the environment the bundle is composed with, as the runner reads the fingerprint from it.
Env map[string]string
}
// MostArguments is the most a marked call's arguments may hold: more is refused, asking nothing (§9).
+144
View File
@@ -2,10 +2,15 @@ package approval
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/operatorask"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"git.novox.be/novox/mesh-sdk/go/seatlist"
)
// call is a fixture call of the marked tool wipe.
@@ -78,3 +83,142 @@ func TestTheActAndItsAsk(t *testing.T) {
t.Errorf("headline %q", got)
}
}
// unread is a catalog half whose first view is not read yet, beside the seat definitions the runner holds.
type unread struct{ defs map[string]seatdef.Definition }
func (unread) Ready() error { return errors.New("the registrations are not answered") }
func (unread) Revision() string { return "" }
func (unread) Served(string) (Entry, bool, string) { return Entry{}, false, "not read" }
func (unread) Newest(string) (Entry, bool) { return Entry{}, false }
func (u unread) Definitions() map[string]seatdef.Definition { return u.defs }
func (unread) Entries() []Entry { return nil }
// Design 47 G lead answers A-387, A-388, A-389 (and A-377): while its catalog half is unread, the gate lets through every
// seat verb the definition the runner holds (here the bootstrapped list) classes `read` explicitly and does not mark
// needs-approval, a module's own first-view tools, and a module tool another module's account calls, logged once per tool;
// it holds every other call as before.
func TestAnUnreadCatalogHalfLetsItsOwnReadsThrough(t *testing.T) {
defs := map[string]seatdef.Definition{}
for _, d := range seatlist.Bootstrapped() {
defs[d.Seat] = d
}
defs["marked"] = seatdef.Definition{Seat: "marked", Verbs: []seatdef.Verb{{Name: "look", Class: seatdef.ClassRead, NeedsApproval: true}}}
waited := 0
var logged []string
g := New(Deps{Node: "n1", Runner: "node-tools", Catalog: unread{defs: defs}, Wait: func(time.Duration) error {
waited++
return errors.New("still unread")
}, Logf: func(f string, a ...any) { logged = append(logged, fmt.Sprintf(f, a...)) }})
for _, tc := range []struct {
seat, name string
runs bool
env map[string]string
caller string
own bool
}{
{"mesh-catalog", "registrations", true, nil, "", false},
{"mesh-catalog", "revision", true, nil, "", false},
{"mesh-catalog", "entry", true, nil, "", false},
{"mesh-delivery", "source", true, nil, "", false},
{"mesh-broker", "list", true, nil, "", false},
{"mesh-catalog", "seat-definitions", true, nil, "", false},
{"mesh-catalog", "modules", true, nil, "", false},
{"git", "pull", true, nil, "", false},
{"git", "merge-pull", false, nil, "", false}, // an act
{"mesh-broker", "create", false, nil, "", false}, // an act
{"mesh-delivery-checker", "try", false, nil, "", false}, // names no class, so no read (A-388)
{"operator-channel", "tell", false, nil, "", false}, // names no class
{"marked", "look", false, nil, "", false}, // a read marked needs-approval
{"unheld", "list", false, nil, "", false}, // a seat the runner holds no definition of
{"mesh-broker", "events", false, nil, "", false},
// A-377: a module's own first-view tool runs unread, an ordinary tool of the same module stays held.
{"", "mesh-delivery-indexer_first_views", true, nil, "", false},
{"", "mesh-delivery-indexer_first_view_again", true, nil, "", false},
{"", "first_views", false, nil, "", false},
{"", "read_modules", false, map[string]string{"MESH_VIEW_CALLERS_MODULES": "grants"}, "", false},
{"mesh-catalog", "register", false, nil, "", false},
{"mesh-delivery", "registrations", false, nil, "", false},
{"", "registrations", false, nil, "", false}, // a module's tool of that name is no seat verb
{"", "revision", false, nil, "", false},
// A-389: a module tool another module's account calls runs unmarked; called otherwise it is held.
{"", "bridge_merged_message", true, nil, "n2.mesh-delivery-forge-bridge", false},
{"", "bridge_merged_message", true, nil, "n1.mesh-delivery-forge-bridge", false}, // logged once
{"", "read_modules", true, nil, "n1.mesh-delivery-runner", false},
{"", "bridge_merged_message", false, nil, "n1.node-tools", false}, // the console's and its sessions' account
{"", "bridge_merged_message", false, nil, "n2.node-tools", false}, // another machine's console
{"", "bridge_merged_message", false, nil, "person.operator", false}, // a person
{"", "bridge_merged_message", false, nil, "controller", false},
{"", "bridge_merged_message", false, nil, "unproven", false},
{"", "bridge_merged_message", true, nil, "n1.mesh-delivery-indexer", false}, // the tool's own module's account (A-433)
{"", "ledger_repair", false, nil, "n1.mesh-delivery-runner", true}, // the runner's own tool
{"git", "merge-pull", true, nil, "n1.mesh-delivery-runner", false}, // a module's account, a seat verb too (A-433)
{"git", "merge-pull", false, nil, "n1.node-tools", false}, // the console's account stays held
} {
ran := false
address := tc.seat + "." + tc.name
if tc.seat == "" {
address = "mesh-delivery-indexer." + tc.name
}
caller := tc.caller
if caller == "" {
caller = "node-tools"
}
_, err := g.Run(Call{Address: address, Module: "mesh-delivery-indexer", Seat: tc.seat, Name: tc.name, Fingerprint: "fp1",
Caller: caller, Env: tc.env, Own: tc.own}, func() (any, error) { ran = true; return "ok", nil })
if ran != tc.runs || (err == nil) != tc.runs {
t.Errorf("%s: ran %v (%v), want ran %v", address, ran, err, tc.runs)
}
if !tc.runs && (err == nil || !strings.Contains(err.Error(), "are not read yet")) {
t.Errorf("%s: refused with %v, want the marks not read yet", address, err)
}
}
if waited != 20 {
t.Errorf("the other calls waited for the catalog half %d times, want 20 (the start reads wait for nothing)", waited)
}
want := []string{
"[approval] mesh-delivery-indexer.bridge_merged_message called by n2.mesh-delivery-forge-bridge: run unmarked before the catalog half is read",
"[approval] mesh-delivery-indexer.read_modules called by n1.mesh-delivery-runner: run unmarked before the catalog half is read",
"[approval] git.merge-pull called by n1.mesh-delivery-runner: run unmarked before the catalog half is read",
}
if strings.Join(logged, "\n") != strings.Join(want, "\n") {
t.Errorf("logged %q, want each module tool run unmarked once with its caller %q", logged, want)
}
// A-433: a module's runtime of its own (its runner the module itself) runs its own account's seat call while unread, as the
// indexer's runtime asks its own mesh-catalog.revision for the first view it waits on; a seat the definition does not class
// read, so no start read.
own := New(Deps{Node: "n1", Runner: "mesh-delivery-indexer", Catalog: unread{defs: map[string]seatdef.Definition{}},
Wait: func(time.Duration) error { return errors.New("still unread") }, Logf: func(string, ...any) {}})
ran := false
if _, err := own.Run(Call{Address: "mesh-catalog.revision", Module: "mesh-delivery-indexer", Seat: "mesh-catalog", Name: "revision",
Fingerprint: "fp1", Caller: "n1.mesh-delivery-indexer"}, func() (any, error) { ran = true; return "ok", nil }); err != nil || !ran {
t.Errorf("the module's own seat call in its own runtime: ran %v (%v), want it run", ran, err)
}
}
// The deadlock of novox 2026-11-16: the seat list is read through the seat mesh-catalog, so while the catalog half is unread
// the runner holds no definitions, and the first views it waits on (its own and another runner's) were refused for ever. The
// foundation's bootstrapped definitions answer for them, from whichever account asks.
func TestTheFirstViewsRunBeforeAnySeatListIsRead(t *testing.T) {
g := New(Deps{Node: "n1", Runner: "node-tools", Catalog: unread{defs: map[string]seatdef.Definition{}},
Wait: func(time.Duration) error { return errors.New("still unread") }, Logf: func(string, ...any) {}})
for _, tc := range []struct {
seat, name, caller string
runs bool
}{
{"mesh-catalog", "revision", "n1.node-tools", true},
{"mesh-catalog", "revision", "n2.node-tools", true},
{"mesh-catalog", "registrations", "person.operator", true},
{"mesh-catalog", "entry", "n1.node-tools", true},
{"mesh-catalog", "seat-definitions", "n1.node-tools", true},
{"git", "merge-pull", "n1.node-tools", false},
{"unheld", "list", "n1.node-tools", false},
} {
ran := false
_, err := g.Run(Call{Address: tc.seat + "." + tc.name, Module: "mesh-delivery-indexer", Seat: tc.seat, Name: tc.name,
Fingerprint: "fp1", Caller: tc.caller}, func() (any, error) { ran = true; return "ok", nil })
if ran != tc.runs || (err == nil) != tc.runs {
t.Errorf("%s.%s by %s: ran %v (%v), want %v", tc.seat, tc.name, tc.caller, ran, err, tc.runs)
}
}
}
+2
View File
@@ -78,6 +78,8 @@ type Gate struct {
unserved map[string][]string
// unmarkedAt is each caller's address it last called unmarked, so a mark added since is named (§12).
unmarkedAt map[string]bool
// unmarkedLogged is each module tool already logged as run unmarked before the catalog half is read (A-389).
unmarkedLogged map[string]bool
// inFlight is each ask whose recording runs now.
inFlight map[string]bool
// failingSince is when the state approvals began to fail; zero while it is read.
+2 -2
View File
@@ -217,7 +217,7 @@ func (g *Gate) openAsk(module, id string) (bool, time.Time, error) {
return err == nil && k != nil && k.Ended == "", time.Time{}, nil // raised and not yet taken by the router
}
switch rec.State {
case "open", "held-back":
case "open":
return true, time.Time{}, nil
case "chosen":
if w := rec.Warrant; w != nil && w.Option == OptionDecline {
@@ -335,7 +335,7 @@ func (g *Gate) Decided(id string) {
g.d.Logf("[approval] the router's record of ask %s cannot be read (%v): read again at the next start", id, err)
return
}
if rec == nil || rec.State == "open" || rec.State == "held-back" {
if rec == nil || rec.State == "open" {
return
}
calls, err := g.waiting(func(w WaitingCall) bool { return w.Ask == id })
+11
View File
@@ -352,6 +352,17 @@ func TestAHolderHoldsAMarkedCall(t *testing.T) {
t.Fatalf("again: %+v, %v", answer, err)
}
})
t.Run("an ask in the old state held-back is no open ask: the call asks again (ADR 0682 section 14)", func(t *testing.T) {
w := setup()
_, h, _ := hold(t, w, call("n1.a", `{}`), true)
w.router.mu.Lock()
w.router.records[h.Asked] = &Record{State: "held-back"}
w.router.mu.Unlock()
_, h2, err := hold(t, w, call("n1.a", `{}`), false)
if err == nil || h2 != nil || strings.Contains(err.Error(), "still waiting") || len(w.router.asks) != 2 {
t.Errorf("the call: %v, %d asks, want it asked again", err, len(w.router.asks))
}
})
t.Run("a restart between the ask and the Approve runs the waiting call once", func(t *testing.T) {
w := setup()
_, h, _ := hold(t, w, call("n1.a", `{}`), true)
+83 -3
View File
@@ -3,9 +3,13 @@ package approval
import (
"encoding/json"
"fmt"
"slices"
"strings"
"sync"
"git.novox.be/novox/mesh-sdk/go/operatorask"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"git.novox.be/novox/mesh-sdk/go/seatlist"
)
// Run is a call through the gate (§20): an unmarked call runs; a marked one runs only on the operator's approval of that
@@ -67,13 +71,72 @@ func (g *Gate) Run(c Call, run func() (any, error)) (any, error) {
// Binding is a Store that says whether the runner's membership binds the state now (§13).
type Binding interface{ Bound() bool }
// marksOf is the module's marks as the catalog half has them now; before its first view, the call waits for it within
// RecordWithin and is then judged, refused naming mesh_first_views when it is still unread (§19).
// startRead says the call runs while the catalog half is unread (design 47 G lead answers A-387, A-388): a seat verb the
// seat definition the runner holds classes `read` explicitly and does not mark needs-approval, so the runner that serves
// them answers the reads its own catalog half and the first take-in wait on; and a module's own first-view tools (A-377),
// known by their names `<module>_first_views` and `<module>_first_view_again` (design 47 H H-A-69).
func (g *Gate) startRead(c Call) bool {
if c.Seat == "" {
for _, form := range []string{"_first_views", "_first_view_again"} {
if m, ok := strings.CutSuffix(c.Name, form); ok && m != "" {
return true
}
}
return false
}
def, ok := g.d.Catalog.Definitions()[c.Seat]
if !ok {
// The seat list is itself read through the seat mesh-catalog, so before its first view the held definitions are
// none: the foundation's bootstrapped definitions answer for the seats they name (the first view of the catalog half
// must run before the catalog half is ready: novox 2026-11-16, the indexer's mesh-catalog.revision refused for 20 minutes).
def, ok = bootstrapped(c.Seat)
if !ok {
return false
}
}
i := slices.IndexFunc(def.Verbs, func(v seatdef.Verb) bool { return v.Name == c.Name })
return i >= 0 && def.Verbs[i].Class == seatdef.ClassRead && !def.Verbs[i].NeedsApproval
}
// calledByModule says a call runs unmarked while the catalog half is unread (design 47 G lead answers A-389, A-433): one
// whose proven caller is a module's account, `<node>.<module>`, a seat verb or a module tool alike, and the module itself
// in a runtime of its own; never the runner's own account where the runner serves other modules (the console's, which the
// sessions and agents call as), a person's, the controller's or an unproven caller. Approval marks are for agent calls; a
// module's account may do everything (principle 6), and a runtime of its own asks its own seat for the very first view it
// waits on (novox 2026-11-16: the indexer's runtime refused its own mesh-catalog.revision for ever). The runner's own tools
// are none. Each such call is logged once, with its caller.
func (g *Gate) calledByModule(c Call) bool {
if c.Own || strings.HasPrefix(c.Caller, "person.") {
return false
}
node, module, ok := strings.Cut(c.Caller, ".")
if !ok || node == "" || module == "" || strings.Contains(module, ".") || (module == g.d.Runner && g.d.Runner != c.Module) {
return false
}
g.mu.Lock()
if g.unmarkedLogged == nil {
g.unmarkedLogged = map[string]bool{}
}
first := !g.unmarkedLogged[c.Address]
g.unmarkedLogged[c.Address] = true
g.mu.Unlock()
if first {
g.d.Logf("[approval] %s called by %s: run unmarked before the catalog half is read", c.Address, c.Caller)
}
return true
}
// marksOf is the module's marks as the catalog half has them now; before its first view, a start read runs unmarked
// (A-387), and so does a module tool another module calls (A-389); any other waits for it within RecordWithin and is then judged, refused naming
// mesh_first_views when it is still unread (§19).
func (g *Gate) marksOf(c Call) (Marks, error) {
if g.d.Catalog == nil {
return Marks{}, g.refused(c, "", "the tool runner reads no catalog half, so its marks are not read")
}
if err := g.d.Catalog.Ready(); err != nil {
if g.startRead(c) || g.calledByModule(c) {
return Marks{Module: c.Module}, nil
}
if g.d.Wait != nil {
err = g.d.Wait(RecordWithin)
}
@@ -127,7 +190,7 @@ func (g *Gate) judge(c Call, act operatorask.Act, digest, id, since string, run
return nil, fmt.Errorf("The ask %s %s; asked again. %w", id, why, err)
}
switch rec.State {
case "open", "held-back":
case "open":
return nil, fmt.Errorf("Not run: still waiting for the operator's answer to ask %s (fingerprint %s); it expires at %s",
id, Fingerprint(digest), rec.Expires)
case "refused":
@@ -174,3 +237,20 @@ func errText(err error) string {
}
return err.Error()
}
var (
bootOnce sync.Once
boot map[string]seatdef.Definition
)
// bootstrapped is the foundation's definition of a seat, which every runner knows before any seat list is read.
func bootstrapped(seat string) (seatdef.Definition, bool) {
bootOnce.Do(func() {
boot = map[string]seatdef.Definition{}
for _, d := range seatlist.Bootstrapped() {
boot[d.Seat] = d
}
})
d, ok := boot[seat]
return d, ok
}
+2 -2
View File
@@ -96,7 +96,7 @@ func (g *Gate) Waited(ctx context.Context, c Call, w Wait, hear func(within time
switch {
case err != nil:
return nil, g.holdRefused(ctx, deadline, g.refused(c, digest, "the router's record of its ask "+id+" cannot be read: "+err.Error()).Error())
case rec == nil, rec.State == "open", rec.State == "held-back":
case rec == nil, rec.State == "open":
return nil, g.holdAsk(ctx, deadline, c.Module, id, digest, false)
case rec.State == "refused":
return nil, g.holdRefused(ctx, deadline, g.refused(c, digest, "the router refused its ask "+id+": "+orNone(rec.Answer)).Error())
@@ -251,7 +251,7 @@ func (g *Gate) waitWords(rec *Record, id, digest string, first bool) error {
return fmt.Errorf("Not run: this wait needs the operator's approval. Asked on %s at %s (ask %s, fingerprint %s); make this wait "+
"again within 30 minutes of the approval; the ask expires at %s", orNone(strings.Join(rec.OfferedOn, ", ")), rec.Opened,
id, Fingerprint(digest), rec.Expires)
case rec.State == "open", rec.State == "held-back":
case rec.State == "open":
return fmt.Errorf("Not run: still waiting for the operator's answer to ask %s (fingerprint %s); it expires at %s",
id, Fingerprint(digest), rec.Expires)
}
+8
View File
@@ -333,6 +333,9 @@ type InstanceState struct {
Instance string `json:"instance"`
State json.RawMessage `json:"state"`
Sequence uint64 `json:"sequence"`
// Expires is when the instance's state key goes, its end plus the ledger's ended-days; absent while the instance has
// not ended (design 47 H2 H-A-634 (4)).
Expires *time.Time `json:"expires,omitempty"`
}
// HistoryRequest reads an instance's operations from a sequence on, at most Limit of them.
@@ -377,6 +380,8 @@ type InstanceChange struct {
State json.RawMessage `json:"state"`
Sequence uint64 `json:"sequence"`
Current bool `json:"current"`
// Expires is as InstanceState's (design 47 H2 H-A-634 (4)).
Expires *time.Time `json:"expires,omitempty"`
}
// QueryRequest reads a declared index of a ledger: the entries whose key Key names (a key, with `*` for one name and
@@ -449,6 +454,9 @@ type RebuildRequest struct {
type ReindexRequest struct {
Ledger string `json:"ledger"`
Index string `json:"index"`
// Instance, when set, builds only that instance's entries again and deletes the ones the index holds for it that it no
// longer should (design 47 H2 H-A-690 (1)).
Instance string `json:"instance,omitempty"`
}
// LedgerRequest names a ledger: lag, fill.
+33
View File
@@ -3,6 +3,7 @@ package buscalls
import (
"encoding/json"
"testing"
"time"
)
// A-42: stream.publish is a method of its own, beside read and fill, and its request and answer keep their field names.
@@ -19,3 +20,35 @@ func TestStreamPublishIsAMethodWithItsShapes(t *testing.T) {
t.Errorf("answer %s", a)
}
}
// Design 47 H2 H-A-634 (4), H-A-690 (1): an instance's state and a change carry `expires` while it has ended, none
// while it has not; a reindex names an instance only when asked to.
func TestAnInstancesExpiresAndAReindexInstanceKeepTheirNames(t *testing.T) {
at := time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC)
for _, c := range []struct {
name string
v any
want string
}{
{"state ended", InstanceState{Instance: "record/a", State: json.RawMessage(`{}`), Sequence: 3, Expires: &at},
`{"instance":"record/a","state":{},"sequence":3,"expires":"2026-12-01T10:00:00Z"}`},
{"state open", InstanceState{Instance: "record/a", State: json.RawMessage(`{}`), Sequence: 3},
`{"instance":"record/a","state":{},"sequence":3}`},
{"change ended", InstanceChange{Watch: "w", Instance: "i", State: json.RawMessage(`{}`), Expires: &at},
`{"watch":"w","instance":"i","state":{},"sequence":0,"current":false,"expires":"2026-12-01T10:00:00Z"}`},
{"change open", InstanceChange{Watch: "w", Instance: "i", State: json.RawMessage(`{}`)},
`{"watch":"w","instance":"i","state":{},"sequence":0,"current":false}`},
{"reindex one", ReindexRequest{Ledger: "records", Index: "movers", Instance: "mover/x"},
`{"ledger":"records","index":"movers","instance":"mover/x"}`},
{"reindex whole", ReindexRequest{Ledger: "records", Index: "movers"}, `{"ledger":"records","index":"movers"}`},
} {
b, err := json.Marshal(c.v)
if err != nil || string(b) != c.want {
t.Errorf("%s: %s (%v), want %s", c.name, b, err, c.want)
}
}
var back InstanceState
if err := json.Unmarshal([]byte(`{"instance":"i","state":null,"sequence":1,"expires":"2026-12-01T10:00:00Z"}`), &back); err != nil || back.Expires == nil || !back.Expires.Equal(at) {
t.Errorf("expires read back as %+v (%v)", back.Expires, err)
}
}
+4
View File
@@ -38,6 +38,10 @@ type Consumer struct {
// and a merge that came back rebuilt what it had just built, five times over on 2026-09-30.
// With one outstanding, the server holds the rest, and the heartbeat is keeping the message.
MaxAckPending int
// InProgressSeconds is how often a holder working a delivery says it is still in progress, so its ack wait does
// not pass while it works (design 47 H2 §777; H-A-340 (1)): the holder's to keep, never sent to the server. Zero
// says nothing.
InProgressSeconds int
// FromNow makes a consumer that does not exist yet start at the stream's end rather than its
// beginning (novox/hq issue 248). For a consumer that reacts to announcements — a merge, a build's
// outcome — on a stream that keeps a week of them: the server's default, everything the stream
+19
View File
@@ -49,4 +49,23 @@ func TestTheBusNamesAgree(t *testing.T) {
t.Errorf("the shared events stream keeps %d s, a seat's definition says %d days", st.MaxAge, seatdef.SharedEventsMaxAgeDays)
}
}
// Design 47 H2 §777, H-A-362: a seat's work queue and its one worker are derived from its accepted kind's settings;
// absent settings take the defaults, two kinds naming one setting differently are refused, no accept is no queue.
st, w, ok, err := SeatQueue("mesh-builds", []seatdef.Message{{Name: "step", MaxAge: "24h", DuplicatesWindow: "2m",
AckWait: "60s", InProgress: "20s", MaxMsgs: 10000, MaxAckPending: 64, MaxDeliveries: 3}})
if err != nil || !ok || st.Name != "SEAT_MESH_BUILDS" || st.Retention != RetentionWorkQueue || st.MaxAge != 86400 ||
st.MaxMsgs != 10000 || st.DuplicatesSeconds != 120 || st.Subjects[0] != "mesh.seat.mesh-builds.accept.>" ||
w.Name != "SEAT_MESH_BUILDS_worker" || w.Stream != st.Name || w.AckWaitSeconds != 60 || w.MaxDeliver != 3 ||
w.MaxAckPending != 64 || w.InProgressSeconds != 20 {
t.Errorf("derived %+v and %+v, %v", st, w, err)
}
if st, w, _, _ := SeatQueue("mesh-wants", []seatdef.Message{{Name: "step"}}); st.MaxAge != 7*86400 || w.AckWaitSeconds != 60 || w.MaxDeliver != 5 {
t.Errorf("the defaults: %+v, %+v", st, w)
}
if _, _, _, err := SeatQueue("s", []seatdef.Message{{Name: "a", AckWait: "60s"}, {Name: "b", AckWait: "2m"}}); err == nil {
t.Error("two ack waits for one worker were derived")
}
if _, _, ok, _ := SeatQueue("s", nil); ok {
t.Error("a seat that accepts nothing has a queue")
}
}
+97
View File
@@ -0,0 +1,97 @@
package buscompose
import (
"fmt"
"strings"
"time"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// The work queue's settings where a seat's accepted kinds name none: a week of asks, a delivery given up after five
// handings, a minute before an unacknowledged one is handed again.
const (
SeatQueueDefaultMaxAge = 7 * 24 * time.Hour
SeatQueueDefaultAckWait = time.Minute
SeatQueueDefaultDelivers = 5
)
// SeatQueueStreamName is the stream holding a seat's inbound work, named after the seat, never its holder.
func SeatQueueStreamName(seat string) string { return "SEAT_" + seatUpper(seat) }
// SeatQueueWorkerName is the one worker a seat's holders share on its work queue.
func SeatQueueWorkerName(seat string) string { return "SEAT_" + seatUpper(seat) + "_worker" }
func seatUpper(seat string) string {
return strings.ToUpper(strings.NewReplacer("-", "_", ".", "_").Replace(seat))
}
// SeatQueue derives a seat's work-queue stream and its one shared worker from its accepted kinds' work-queue settings
// (design 47 H2 §777; H-A-350 DMC-1, H-A-362), the one derivation every part takes: max-age, max-msgs and
// duplicates-window bound the stream; ack-wait, max-deliveries, max-ack-pending and in-progress the worker. A setting
// named by two accepted kinds with two values is refused: one stream and one worker carry one value. A seat that
// accepts nothing has no queue (ok false).
func SeatQueue(seat string, accepts []seatdef.Message) (stream Stream, worker Consumer, ok bool, err error) {
if len(accepts) == 0 {
return Stream{}, Consumer{}, false, nil
}
durations := map[string]string{}
counts := map[string]int{}
for _, a := range accepts {
if ps := a.QueueProblems("accepts " + a.Name); len(ps) > 0 {
return Stream{}, Consumer{}, false, fmt.Errorf("the seat %s's work queue: %w", seat, ps)
}
for name, v := range map[string]string{"max-age": a.MaxAge, "duplicates-window": a.DuplicatesWindow,
"ack-wait": a.AckWait, "in-progress": a.InProgress} {
if v == "" {
continue
}
if was, seen := durations[name]; seen && was != v {
return Stream{}, Consumer{}, false, fmt.Errorf("the seat %s's work queue: %s is %s and %s in two accepted kinds", seat, name, was, v)
}
durations[name] = v
}
for name, v := range map[string]int{"max-msgs": a.MaxMsgs, "max-ack-pending": a.MaxAckPending, "max-deliveries": a.MaxDeliveries} {
if v == 0 {
continue
}
if was, seen := counts[name]; seen && was != v {
return Stream{}, Consumer{}, false, fmt.Errorf("the seat %s's work queue: %s is %d and %d in two accepted kinds", seat, name, was, v)
}
counts[name] = v
}
}
seconds := func(name string, def time.Duration) int {
if v, set := durations[name]; set {
d, _ := time.ParseDuration(v) // QueueProblems read it
return int(d / time.Second)
}
return int(def / time.Second)
}
delivers := SeatQueueDefaultDelivers
if v, set := counts["max-deliveries"]; set {
delivers = v
}
subject := "mesh.seat." + seat + ".accept.>"
stream = Stream{
Name: SeatQueueStreamName(seat),
Subjects: []string{subject},
Retention: RetentionWorkQueue,
MaxAge: seconds("max-age", SeatQueueDefaultMaxAge),
MaxMsgs: counts["max-msgs"],
DuplicatesSeconds: seconds("duplicates-window", 0),
Why: fmt.Sprintf("work submitted to the %s seat; one holder consumes it, and it queues while nobody does", seat),
}
worker = Consumer{
Name: SeatQueueWorkerName(seat),
Stream: stream.Name,
Filters: []string{subject},
AckWaitSeconds: seconds("ack-wait", SeatQueueDefaultAckWait),
MaxDeliver: delivers,
MaxAckPending: counts["max-ack-pending"],
InProgressSeconds: seconds("in-progress", 0),
Why: fmt.Sprintf("every holder of %s pulls its asks from this one worker and acknowledges after the work is "+
"done, so a crash mid-work redelivers rather than loses", seat),
}
return stream, worker, true, nil
}
+2
View File
@@ -32,6 +32,8 @@ type Stream struct {
// another's events out of a shared stream. Verified: with a cap of 3, ten messages on one
// subject and one on another leave four in the stream, not three.
MaxMsgsPerSubject int
// MaxMsgs caps the stream's messages, zero for unbounded: a seat's work queue's max-msgs (design 47 H2 §777).
MaxMsgs int
// Why is carried into the assertion so an operator reading the server's own state finds the
// reason there, rather than only in a repository they may not have.
Why string
+303 -1
View File
@@ -15,10 +15,15 @@ package busretry
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand/v2"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats.go"
@@ -36,10 +41,307 @@ var (
// in a process shares, so a test sets them only through it, as t.Cleanup(busretry.Waits(...)): a test that set them
// and left them set shortened the next test's bound to milliseconds, and a loaded check machine overran it (the check
// of release sdk1, 2026-11-02). A bound a test waits on to succeed is seconds: no slow machine reaches it.
// It sets the kept-call pace (KeptPace) to first and most too, so a test of a kept call waits milliseconds.
func Waits(bound, first, most time.Duration) (restore func()) {
was := [3]time.Duration{Bound, FirstWait, MostWait}
wasPace := keptPace.Swap(&Pace{First: first, Max: most})
Bound, FirstWait, MostWait = bound, first, most
return func() { Bound, FirstWait, MostWait = was[0], was[1], was[2] }
return func() { Bound, FirstWait, MostWait = was[0], was[1], was[2]; keptPace.Store(wasPace) }
}
// Pace is the kept-call form's pace (design 47 H2 §775): on a transport fault the call is made again after First,
// the wait doubling to at most Max, each wait drawn within 20 % of its value so many callers do not call in step.
type Pace struct{ First, Max time.Duration }
// The settings every module using the kept-call form declares, with DefaultPace's values as their defaults (§775).
const (
PaceFirstSetting = "kept-call-pace-first"
PaceMaxSetting = "kept-call-pace-max"
)
// DefaultPace is the pace a module's settings name when they name none (§775): 1 s doubling to 30 s, so a holder
// between two lives (a restart takes 20 to 50 s) is met within one minute without a call a second.
var DefaultPace = Pace{First: time.Second, Max: 30 * time.Second}
// keptPace is the pace ReadPace read, nil until it read one. It is set once and read by every kept call at once, so it
// is held atomically: a kept call on one goroutine never races a Connect or a Serve on another (§782).
var keptPace atomic.Pointer[Pace]
// KeptPace is the pace of every kept call this process makes: DefaultPace until the process reads its settings
// (ReadPace, at process.Connect and at a bundle's stdio.Serve). Safe for concurrent use.
func KeptPace() Pace {
if p := keptPace.Load(); p != nil {
return *p
}
return DefaultPace
}
// ReadPace sets KeptPace from the module's settings PaceFirstSetting and PaceMaxSetting, read through read (the one
// settings reader, stdio.SettingDuration, which answers its default for a setting not composed), so a module's
// declared pace paces its kept calls (§775). A setting that is no duration, or a most below the first, is an error
// naming it, and KeptPace stays. The pace is read once, at the process's start: a later call reading the same pace
// changes nothing, and one reading another pace is refused, naming both, and KeptPace stays (§782). Safe for
// concurrent use.
func ReadPace(read func(key string, def time.Duration) (time.Duration, error)) error {
held := KeptPace()
first, err := read(PaceFirstSetting, held.First)
if err != nil {
return err
}
most, err := read(PaceMaxSetting, held.Max)
if err != nil {
return err
}
if most < first {
return fmt.Errorf("the setting %s (%s) is below %s (%s)", PaceMaxSetting, most, PaceFirstSetting, first)
}
got := Pace{First: first, Max: most}
if keptPace.CompareAndSwap(nil, &got) {
return nil
}
if held = KeptPace(); got != held {
return fmt.Errorf("the kept-call pace is read once, at the start: it is %s to %s, and the settings now say %s to %s",
held.First, held.Max, got.First, got.Max)
}
return nil
}
// The clock and the sleep the paced form waits on; a test of this package replaces both, so nothing sleeps.
var (
now = time.Now
sleep = time.Sleep
)
// jittered is w drawn within 20 % of its value.
func jittered(w time.Duration) time.Duration {
return time.Duration(float64(w) * (0.8 + 0.4*rand.Float64()))
}
// Kept names one kept call of the paced form (design 47 H2 §775): the seat and the verb it asks (named in the journal
// line), the ask's id (named among the asks waiting), the caller's bound (zero is Bound) and the pace (zero is
// KeptPace). Open, when given, makes it asked again only while its key is open (DoKept). Logf is the journal; nil
// writes to standard error. Hook, when given, is called when the call has waited WaitSaid, with its last fault and since
// when it waited, and once more when it is answered (design 47 H2 H-A-708 (4)).
type Kept struct {
Seat, Verb, Ask string
Bound time.Duration
Pace Pace
Open *Open
Logf func(format string, args ...any)
Hook func(Waited)
}
// WaitSaid is how long a kept call waits before its hook says so (design 47 H2 H-A-708 (4)).
const WaitSaid = 5 * time.Minute
// Waited is what a kept call's hook is told: the call's seat, verb and ask, since when it waited, its last fault's words,
// and whether it is answered (the call ended, by an answer of any kind that is no transport fault).
type Waited struct {
Seat, Verb, Ask string
Since time.Time
Last string
Answered bool
}
// Try is one call of a kept call that met a transport fault: when it was made and the words it met.
type Try struct {
At time.Time
Words string
}
// Unanswered is a kept call's end past its caller's bound (§775): every call's time and words, so the caller's
// could-not-run or could-not-be-performed names them. It wraps the last fault, so Undelivered and TimedOut read it.
type Unanswered struct {
Seat, Verb, Ask string
Bound time.Duration
Tries []Try
Last error
}
func (u *Unanswered) Error() string {
var b strings.Builder
fmt.Fprintf(&b, "%s.%s", u.Seat, u.Verb)
if u.Ask != "" {
fmt.Fprintf(&b, " (ask %s)", u.Ask)
}
fmt.Fprintf(&b, " unanswered within its bound of %s, called %d times:", u.Bound, len(u.Tries))
for i, t := range u.Tries {
if i > 0 {
b.WriteString(";")
}
fmt.Fprintf(&b, " %s %s", t.At.UTC().Format("15:04:05.000"), t.Words)
}
return b.String()
}
func (u *Unanswered) Unwrap() error { return u.Last }
// Fault says err is a transport fault of a kept call (§775): a request that reached no one, a call's own deadline
// passing, or a holder's answer of the kind away (§776); a callee's refusal never is.
func Fault(err error) bool {
var away *Away
return TimedOut(err) || Undelivered(err) || errors.As(err, &away)
}
// ErrorKindAway is the seat error kind a holder answers when a part it depends on is away (design 47 H2 §776): its
// answer's `error-kind`, beside `part` (what did not answer) and `words`. A caller reads it as a transport fault.
const ErrorKindAway = "away"
// Away is a holder's answer of the kind away, read as an error: the part that did not answer and the holder's words.
type Away struct {
Part, Words string
}
func (a *Away) Error() string {
return fmt.Sprintf("away: %s does not answer: %s", a.Part, a.Words)
}
// AwayAnswer is the seat error answer of the kind away a holder gives (§776): `error` and `error-kind` as each seat's
// error answer has them, with `part` and `words`.
func AwayAnswer(part, words string) map[string]string {
return map[string]string{"error": (&Away{Part: part, Words: words}).Error(), "error-kind": ErrorKindAway,
"part": part, "words": words}
}
// AwayIn is the *Away a verb's answer says when its `error-kind` is away, else nil: an answer that is no object, or
// of another kind, is the caller's to read.
func AwayIn(answer json.RawMessage) *Away {
var a struct {
Error string `json:"error"`
Kind string `json:"error-kind"`
Part string `json:"part"`
Words string `json:"words"`
}
if json.Unmarshal(answer, &a) != nil || a.Kind != ErrorKindAway {
return nil
}
if a.Words == "" {
a.Words = a.Error
}
return &Away{Part: a.Part, Words: a.Words}
}
// DoPaced makes a kept call through try (design 47 H2 §775): on a transport fault (Fault) it calls again at k's pace,
// each wait jittered, until the caller's bound, writing one journal line per seat at the first fault and then at most
// once a minute (the seat, the verb, the asks waiting and the count of calls). Past the bound it returns the last
// answer with an *Unanswered naming every call; a refusal of what was asked returns at once.
func DoPaced[T any](k Kept, try func() (T, error)) (T, error) {
bound, pace := k.Bound, k.Pace
if bound <= 0 {
bound = Bound
}
if pace.First <= 0 || pace.Max <= 0 {
held := KeptPace()
if pace.First <= 0 {
pace.First = held.First
}
if pace.Max <= 0 {
pace.Max = held.Max
}
}
logf := k.Logf
if logf == nil {
logf = func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-sdk] "+f+"\n", a...) }
}
start, wait := now(), pace.First
var tries []Try
waiting, said := false, false
defer func() {
if waiting {
journal.done(k.Seat, k.Ask)
}
}()
for {
at := now()
v, err := try()
if !Fault(err) || (k.Open != nil && !k.Open.stillOpen()) {
if said {
k.Hook(Waited{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Since: start, Last: tries[len(tries)-1].Words, Answered: true})
}
return v, err
}
tries = append(tries, Try{At: at, Words: err.Error()})
if !said && k.Hook != nil && now().Sub(start) >= WaitSaid {
said = true
k.Hook(Waited{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Since: start, Last: err.Error()})
}
if !waiting {
journal.wait(k.Seat, k.Ask)
waiting = true
}
journal.fault(k.Seat, k.Verb, logf)
left := bound - now().Sub(start)
if left <= 0 {
return v, &Unanswered{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Bound: bound, Tries: tries, Last: err}
}
sleep(min(jittered(wait), left))
wait = min(wait*2, pace.Max)
}
}
// journal holds, per seat, the asks of this process waiting on it through a fault, the calls made since its last
// line and when that line was written: one line per seat at the first fault, then at most once a minute (§775).
var journal = &faults{seats: map[string]*seatFaults{}}
type faults struct {
mu sync.Mutex
seats map[string]*seatFaults
}
type seatFaults struct {
asks map[string]int
calls int
last time.Time
}
func (f *faults) of(seat string) *seatFaults {
s := f.seats[seat]
if s == nil {
s = &seatFaults{asks: map[string]int{}}
f.seats[seat] = s
}
return s
}
func (f *faults) wait(seat, ask string) {
f.mu.Lock()
defer f.mu.Unlock()
f.of(seat).asks[ask]++
}
func (f *faults) done(seat, ask string) {
f.mu.Lock()
defer f.mu.Unlock()
s := f.of(seat)
if s.asks[ask]--; s.asks[ask] <= 0 {
delete(s.asks, ask)
}
}
func (f *faults) fault(seat, verb string, logf func(string, ...any)) {
f.mu.Lock()
s := f.of(seat)
s.calls++
t := now()
if !s.last.IsZero() && t.Sub(s.last) < time.Minute {
f.mu.Unlock()
return
}
s.last = t
var asks []string
n := 0
for a, c := range s.asks {
n += c
if a != "" {
asks = append(asks, a)
}
}
sort.Strings(asks)
calls := s.calls
s.calls = 0
f.mu.Unlock()
logf("kept call: the seat %s does not answer (%s): %d asks waiting %v, %d calls since the last line; called "+
"again at the kept-call pace until each caller's bound", seat, verb, n, asks, calls)
}
// Undelivered says err means the request reached no one: no responders, JetStream not enabled (for the account), or
+178
View File
@@ -2,9 +2,11 @@ package busretry
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
@@ -110,8 +112,184 @@ func subAKeptCallIsAskedAgainOnlyWhileItsKeyIsOpen(t *testing.T) {
}
}
// fakeClock replaces the paced form's clock and sleep for one test: a sleep moves the clock, nothing sleeps.
func fakeClock(t *testing.T) (slept *[]time.Duration) {
at := time.Date(2026, 11, 21, 22, 0, 0, 0, time.UTC)
waits := []time.Duration{}
wasNow, wasSleep, wasJournal := now, sleep, journal
now = func() time.Time { return at }
sleep = func(d time.Duration) { waits = append(waits, d); at = at.Add(d) }
journal = &faults{seats: map[string]*seatFaults{}}
t.Cleanup(func() { now, sleep, journal = wasNow, wasSleep, wasJournal })
return &waits
}
// Design 47 H2 §775: the kept call is paced from 1 s doubling to 30 s, each wait within 20 %; met by no responders twice
// and then answered it returns the answer and writes one journal line; past its caller's bound it returns every try;
// a refusal returns at once; the journal says a seat at most once a minute.
func subAKeptCallIsPaced(t *testing.T) {
t.Run("no responders twice, then answered: the answer and one line", func(t *testing.T) {
slept := fakeClock(t)
tries, logs := 0, []string{}
v, err := DoPaced(Kept{Seat: "mesh-builds", Verb: "build", Ask: "a1", Bound: time.Minute,
Logf: func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) }}, func() (int, error) {
if tries++; tries <= 2 {
return 0, nats.ErrNoResponders
}
return 7, nil
})
if v != 7 || err != nil || tries != 3 || len(logs) != 1 || !strings.Contains(logs[0], "mesh-builds") ||
!strings.Contains(logs[0], "build") || !strings.Contains(logs[0], "[a1]") {
t.Fatalf("%d, %v after %d tries, logs %q", v, err, tries, logs)
}
for i, base := range []time.Duration{time.Second, 2 * time.Second} {
if w := (*slept)[i]; w < base*8/10 || w > base*12/10 {
t.Errorf("wait %d is %s, not within 20 %% of %s", i, w, base)
}
}
})
t.Run("past its bound: every try", func(t *testing.T) {
slept := fakeClock(t)
tries := 0
_, err := DoPaced(Kept{Seat: "mesh-wants", Verb: "compose-candidate", Ask: "a2", Bound: 3 * time.Minute,
Logf: func(string, ...any) {}}, func() (int, error) { tries++; return 0, context.DeadlineExceeded })
var u *Unanswered
if !errors.As(err, &u) || len(u.Tries) != tries || tries < 5 || !TimedOut(err) ||
!strings.Contains(err.Error(), "context deadline exceeded") {
t.Fatalf("%d tries: %v", tries, err)
}
for _, w := range *slept {
if w > 30*time.Second*12/10 {
t.Errorf("a wait of %s passes the pace's most", w)
}
}
})
t.Run("the hook is told at five minutes waited, once, and at the answer", func(t *testing.T) {
fakeClock(t)
tries, told := 0, []Waited{}
v, err := DoPaced(Kept{Seat: "mesh-builds", Verb: "build", Ask: "a9", Bound: time.Hour, Logf: func(string, ...any) {},
Hook: func(w Waited) { told = append(told, w) }}, func() (int, error) {
if tries++; tries <= 40 {
return 0, nats.ErrNoResponders
}
return 3, nil
})
if v != 3 || err != nil || len(told) != 2 || told[0].Answered || !told[1].Answered || told[0].Seat != "mesh-builds" ||
told[0].Verb != "build" || told[0].Last == "" || !told[0].Since.Equal(told[1].Since) {
t.Fatalf("%d, %v, told %+v", v, err, told)
}
// Answered within the five minutes: the hook is never told.
tries, told = 0, nil
_, _ = DoPaced(Kept{Seat: "s", Verb: "v", Logf: func(string, ...any) {}, Hook: func(w Waited) { told = append(told, w) }},
func() (int, error) { tries++; return 1, map[bool]error{true: nats.ErrNoResponders}[tries < 3] })
if len(told) != 0 {
t.Fatalf("told %+v for a call answered in time", told)
}
})
t.Run("a refusal returns at once", func(t *testing.T) {
slept := fakeClock(t)
tries := 0
_, err := DoPaced(Kept{Seat: "git", Verb: "merge"}, func() (int, error) { tries++; return 0, &Answered{Words: "refused"} })
if tries != 1 || len(*slept) != 0 || err == nil {
t.Fatalf("%d tries, %v", tries, err)
}
})
t.Run("away is a transport fault; its answer reads back", func(t *testing.T) {
raw, _ := json.Marshal(AwayAnswer("the forge's store", "401 and the version read failed"))
a := AwayIn(raw)
if a == nil || a.Part != "the forge's store" || a.Words != "401 and the version read failed" || !Fault(a) ||
!strings.Contains(string(raw), `"error-kind":"away"`) {
t.Fatalf("%s read as %+v", raw, a)
}
// Design 47 H2 H-A-570 (3): no responders is the transport fault, wrapped or not; a reply naming the withdrawn kind
// stopping is the callee's answer, no fault.
if !Fault(nats.ErrNoResponders) || !Fault(fmt.Errorf("asked: %w", nats.ErrNoResponders)) || Fault(&Answered{Words: "the tool runner is stopping"}) {
t.Fatal("no responders is no transport fault, or a reply of the kind stopping is one")
}
if AwayIn([]byte(`{"error":"no","error-kind":"refused"}`)) != nil || AwayIn([]byte(`[1]`)) != nil || Fault(&Answered{Words: "away"}) {
t.Fatal("a refusal reads as away")
}
if a := AwayIn([]byte(`{"error":"the store is down","error-kind":"away"}`)); a == nil || a.Words != "the store is down" {
t.Fatalf("an away answer with no words reads %+v", a)
}
})
t.Run("the pace is the module's settings", func(t *testing.T) {
was := keptPace.Load()
t.Cleanup(func() { keptPace.Store(was) })
reader := func(set map[string]time.Duration) func(string, time.Duration) (time.Duration, error) {
return func(key string, def time.Duration) (time.Duration, error) {
if d, ok := set[key]; ok {
if d < 0 {
return 0, fmt.Errorf("the setting %s is no duration", key)
}
return d, nil
}
return def, nil
}
}
two := map[string]time.Duration{PaceFirstSetting: 2 * time.Second, PaceMaxSetting: time.Minute}
for _, c := range []struct {
name string
held *Pace // the pace read before, nil none
set map[string]time.Duration
bad string
want Pace
}{
{name: "none set", want: DefaultPace},
{name: "both set", set: two, want: Pace{First: 2 * time.Second, Max: time.Minute}},
{name: "most below first", set: map[string]time.Duration{PaceFirstSetting: time.Minute, PaceMaxSetting: time.Second}, bad: "is below", want: DefaultPace},
{name: "no duration", set: map[string]time.Duration{PaceFirstSetting: -1}, bad: "no duration", want: DefaultPace},
// Design 47 H2 §782: the pace is read once; a later read of the same pace changes nothing, of another is refused.
{name: "read again, the same", held: &Pace{First: 2 * time.Second, Max: time.Minute}, set: two, want: Pace{First: 2 * time.Second, Max: time.Minute}},
{name: "read again, none set", held: &Pace{First: 2 * time.Second, Max: time.Minute}, want: Pace{First: 2 * time.Second, Max: time.Minute}},
{name: "read again, another", held: &DefaultPace, set: two, bad: "read once", want: DefaultPace},
} {
keptPace.Store(c.held)
err := ReadPace(reader(c.set))
if (err != nil) != (c.bad != "") || (err != nil && !strings.Contains(err.Error(), c.bad)) || KeptPace() != c.want {
t.Errorf("%s: pace %+v, %v", c.name, KeptPace(), err)
}
}
// Design 47 H2 §782, under -race: a Connect or a Serve reading the pace while kept calls read it is no data race.
keptPace.Store(nil)
var wg sync.WaitGroup
for i := range 8 {
wg.Add(2)
go func() { defer wg.Done(); _ = ReadPace(reader(two)) }()
go func() {
defer wg.Done()
if _, err := DoPaced(Kept{Seat: "s", Verb: fmt.Sprint(i), Logf: func(string, ...any) {}}, func() (int, error) { return 1, nil }); err != nil {
t.Error(err)
}
_ = KeptPace()
}()
}
wg.Wait()
if KeptPace() != (Pace{First: 2 * time.Second, Max: time.Minute}) {
t.Errorf("after concurrent reads the pace is %+v", KeptPace())
}
})
t.Run("one line per seat a minute", func(t *testing.T) {
fakeClock(t)
logs := 0
k := Kept{Seat: "mesh-builds", Verb: "build", Bound: 10 * time.Second, Logf: func(string, ...any) { logs++ }}
fail := func() (int, error) { return 0, nats.ErrNoResponders }
_, _ = DoPaced(k, fail)
_, _ = DoPaced(k, fail)
if logs != 1 {
t.Fatalf("%d lines within a minute", logs)
}
k.Bound = 2 * time.Minute
_, _ = DoPaced(k, fail)
if logs < 2 {
t.Fatalf("%d lines past a minute", logs)
}
})
}
// TestABusThatAnswersNothingIsWaitedOut runs the tests of this package that were merged to keep the module within its test budget (design 47 G §419), each as a subtest.
func TestABusThatAnswersNothingIsWaitedOut(t *testing.T) {
t.Run("ABusThatAnswersNothingIsWaitedOut", subABusThatAnswersNothingIsWaitedOut)
t.Run("AKeptCallIsAskedAgainOnlyWhileItsKeyIsOpen", subAKeptCallIsAskedAgainOnlyWhileItsKeyIsOpen)
t.Run("AKeptCallIsPaced", subAKeptCallIsPaced)
}
+35
View File
@@ -2,7 +2,9 @@ package stdio
import (
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"strings"
"time"
)
@@ -29,3 +31,36 @@ func BusState(method string, params any) (json.RawMessage, error) {
}
return c.ask(method, params, 60*time.Second)
}
// WatchLedger hands handle every current state of the instances of this bundle's own ledger that instances names (an
// instance, with `*` for one name and `>` for the rest; empty is every instance), and then every change, in the order it
// came, and returns once the current states have all been handled. The watch lasts as long as the process. handle runs
// beside the runtime (follower.go): its time never counts against the runtime's bound on the current states, and an error
// it returns is said on standard error. A watch the runtime refuses is given up, said, and a change the runtime still hands
// to it is refused saying so. A change names the instance's expiry while it has ended (design 47 H2 H-A-706 on DMC-13,
// H-A-717 DQ-50).
func WatchLedger(ledger, instances string, handle func(buscalls.InstanceChange) error) error {
if handle == nil {
return errors.New("a watch needs a handler")
}
c, err := live()
if err != nil {
return err
}
id := c.newID()
f := newFollower("the watch "+id+" of the ledger "+ledger, handle, func(ch buscalls.InstanceChange) string { return ch.Instance })
c.mu.Lock()
c.ledgerWatches[id] = f
c.mu.Unlock()
if _, err := c.askAs(id, buscalls.LedgerWatch, buscalls.LedgerWatchRequest{Ledger: ledger, Instances: instances, Watch: id}, 60*time.Second); err != nil {
c.mu.Lock()
delete(c.ledgerWatches, id)
c.gaveUp(id, fmt.Sprintf("the ledger %s at %s: %v", ledger, time.Now().Format(time.RFC3339), err))
c.mu.Unlock()
sayf("the watch %s of the ledger %s is given up: %v", id, ledger, err)
return err
}
// The runtime hands every current state over before it answers the watch: each is in the follower by now.
<-f.handled()
return nil
}
+7
View File
@@ -78,6 +78,13 @@ func (o Objects) Delete(name string) error {
return err
}
// Purge removes what the deleted object name left behind in the store, its chunks, through the runtime's delete, which
// purges them again when asked again (H-A-366): a bundle never opens a connection of its own for it.
func (o Objects) Purge(name string) error {
_, err := call[buscalls.Done](buscalls.ObjectsDelete, buscalls.ObjectsNameRequest{Objects: o.local, Name: name})
return err
}
// Fill is how much the store holds against its cap.
func (o Objects) Fill() (buscalls.Fill, error) {
return call[buscalls.Fill](buscalls.ObjectsInfo, buscalls.ObjectsRequest{Objects: o.local})
+6 -2
View File
@@ -35,6 +35,7 @@ func subABundleKeepsObjectsThroughTheRuntime(t *testing.T) {
list, err := in.List()
results <- result{"list", err, len(list)}
results <- result{"delete", in.Delete("t1.part0"), nil}
results <- result{"purge", in.Purge("t1.part0"), nil} // H-A-366
fill, err := in.Fill()
results <- result{"fill", err, fill.MaxBytes}
_, err = stdio.BusState("mesh/state.get", nil)
@@ -81,8 +82,8 @@ func subABundleKeepsObjectsThroughTheRuntime(t *testing.T) {
asked[method] = p
send(map[string]any{"jsonrpc": "2.0", "id": m["id"], "result": answers[method]})
}
want := map[string]any{"put": "SHA-256=x", "get": "hello", "list": 1, "delete": nil, "fill": uint64(20 << 30)}
for range 5 {
want := map[string]any{"put": "SHA-256=x", "get": "hello", "list": 1, "delete": nil, "purge": nil, "fill": uint64(20 << 30)}
for range 6 {
r := <-results
if r.err != nil || r.got != want[r.what] {
t.Errorf("%s answered %v, %v; want %v", r.what, r.got, r.err, want[r.what])
@@ -96,6 +97,9 @@ func subABundleKeepsObjectsThroughTheRuntime(t *testing.T) {
t.Errorf("%s named the store %v, not its local name", method, p["objects"])
}
}
if p := asked[buscalls.ObjectsDelete]; p["name"] != "t1.part0" {
t.Errorf("delete and purge asked %v", p)
}
if p := asked[buscalls.ObjectsPut]; p["name"] != "t1.part0" || p["data"] != "aGVsbG8=" || p["description"] != "a part" {
t.Errorf("put asked %v", p)
}
+41 -3
View File
@@ -3,6 +3,7 @@ package stdio
import (
"reflect"
"regexp"
"strings"
"sync"
"unsafe"
)
@@ -27,11 +28,19 @@ var busUser = regexp.MustCompile(`^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$`)
// buscalls.MetaCall, written here too so this package imports nothing of buscalls.
const MetaCall = "mesh/call"
// AskHeader is the bus header a kept call carries its ask's id in (design 47 H2 §775; H-A-351): a holder in a process
// reads it with process.AskOf, and the tool runner copies it into a `tools/call`'s `_meta` under MetaAsk, read with
// AskIDOf.
const AskHeader = "x-ask"
// MetaAsk is where in a `tools/call`'s `_meta` the runtime names the ask id the call carried in AskHeader (H-A-351).
const MetaAsk = "mesh/ask"
// callID is the shape of a call's id: one subject-safe token, as the runtime makes it. Anything else reads as none.
var callID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
// inFlight is what the runtime said of one call while its tool runs.
type inFlight struct{ caller, call string }
type inFlight struct{ caller, call, ask string }
// calls holds the caller and the id of every call while its tool runs, by the arguments map that call was handed.
var calls sync.Map // unsafe.Pointer → inFlight
@@ -74,6 +83,27 @@ func callIn(meta map[string]any) string {
return ""
}
// AskIDOf is the ask id the call that was handed args carried (design 47 H2 §775; H-A-351): what the kept call set in
// AskHeader and the runtime named under MetaAsk, by which a holder takes the ask once. Empty when the call
// carried none. Valid while the tool runs.
func AskIDOf(args map[string]any) string {
if args == nil {
return ""
}
if c, ok := calls.Load(argsKey(args)); ok {
return c.(inFlight).ask
}
return ""
}
// askIn is the ask id a `tools/call`'s `_meta` names, or empty: one subject-safe token, as a call's id is.
func askIn(meta map[string]any) string {
if s, ok := meta[MetaAsk].(string); ok && callID.MatchString(s) {
return s
}
return ""
}
// callerIn is the caller a `tools/call`'s `_meta` names, or Unproven.
func callerIn(meta map[string]any) string {
if s, ok := meta[MetaCaller].(string); ok && busUser.MatchString(s) {
@@ -83,9 +113,17 @@ func callerIn(meta map[string]any) string {
}
// runAs runs a tool with the caller and the call's id held for its arguments for as long as it runs.
func runAs(t Tool, caller, call string, args map[string]any) (any, error) {
func runAs(t Tool, f inFlight, args map[string]any) (any, error) {
key := argsKey(args)
calls.Store(key, inFlight{caller, call})
calls.Store(key, f)
defer calls.Delete(key)
return t.Run(args)
}
// ModuleOf is the module of a proved module caller, which the runtime names <machine>.<module>.
func ModuleOf(proved string) string {
if _, module, ok := strings.Cut(proved, "."); ok {
return module
}
return proved
}
+43 -111
View File
@@ -3,8 +3,8 @@ package stdio
import (
"bufio"
"encoding/json"
"errors"
"io"
"strings"
"testing"
"time"
@@ -14,26 +14,26 @@ import (
// callWith serves one tool that answers the caller CallerOf reads from its arguments, sends it one tools/call
// with the params given, and returns the caller it answered.
func callWith(t *testing.T, params map[string]any) string {
caller, _ := callAnswering(t, params)
caller, _, _ := callAnswering(t, params)
return caller
}
// callAnswering is callWith answering the call's id CallIDOf read too.
func callAnswering(t *testing.T, params map[string]any) (string, string) {
func callAnswering(t *testing.T, params map[string]any) (string, string, string) {
servesAlone(t)
t.Helper()
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("tracker", []Tool{{Name: "who", Run: func(args map[string]any) (any, error) {
return map[string]any{"caller": CallerOf(args), "call": CallIDOf(args)}, nil
return map[string]any{"caller": CallerOf(args), "call": CallIDOf(args), "ask": AskIDOf(args)}, nil
}}}, inR, outW)
}()
defer inW.Close()
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params})
_, _ = inW.Write(append(b, '\n'))
lines := bufio.NewScanner(outR)
done := make(chan [2]string, 1)
done := make(chan [3]string, 1)
go func() {
if lines.Scan() {
var m struct {
@@ -47,19 +47,20 @@ func callAnswering(t *testing.T, params map[string]any) (string, string) {
var answer struct {
Caller string `json:"caller"`
Call string `json:"call"`
Ask string `json:"ask"`
}
if len(m.Result.Content) > 0 {
_ = json.Unmarshal([]byte(m.Result.Content[0].Text), &answer)
}
done <- [2]string{answer.Caller, answer.Call}
done <- [3]string{answer.Caller, answer.Call, answer.Ask}
}
}()
select {
case got := <-done:
return got[0], got[1]
return got[0], got[1], got[2]
case <-time.After(3 * time.Second):
t.Fatal("the bundle did not answer the call")
return "", ""
return "", "", ""
}
}
@@ -84,13 +85,46 @@ func TestAToolReadsTheCallerTheRuntimeNamed(t *testing.T) {
{map[string]any{}, map[string]any{MetaCall: "a b"}, ""},
{map[string]any{}, map[string]any{MetaCall: 7}, ""},
} {
if _, call := callAnswering(t, map[string]any{"name": "who", "arguments": c.args, "_meta": c.meta}); call != c.want {
if _, call, _ := callAnswering(t, map[string]any{"name": "who", "arguments": c.args, "_meta": c.meta}); call != c.want {
t.Errorf("args %v, meta %v: the tool read call %q, want %q", c.args, c.meta, call, c.want)
}
}
// Design 47 H2 §775, H-A-351: the ask id a kept call carried is the runtime's to name under mesh/ask, never the
// arguments'.
for _, c := range []struct {
args, meta map[string]any
want string
}{
{map[string]any{}, map[string]any{MetaAsk: "build-7Hq2"}, "build-7Hq2"},
{map[string]any{MetaAsk: "forged"}, map[string]any{}, ""},
{map[string]any{}, map[string]any{MetaAsk: "a.b"}, ""},
} {
if _, _, ask := callAnswering(t, map[string]any{"name": "who", "arguments": c.args, "_meta": c.meta}); ask != c.want {
t.Errorf("args %v, meta %v: the tool read ask %q, want %q", c.args, c.meta, ask, c.want)
}
}
if CallIDOf(map[string]any{"x": 1}) != "" || CallIDOf(nil) != "" {
t.Error("arguments no call was handed have a call id")
}
// Design 47 H2 §781, H-A-370: a process and a bundle read a setting by its key from the word the node-engine composes.
t.Setenv("MESH_CONFIG_ASK_UNANSWERED_BOUND", "10m")
t.Setenv("MESH_CONFIG_KEPT_CALL_PACE_FIRST", "soon")
if v, ok := Setting("ask-unanswered-bound"); !ok || v != "10m" {
t.Errorf("the setting read %q, %v", v, ok)
}
if d, err := SettingDuration("ask-unanswered-bound", time.Minute); err != nil || d != 10*time.Minute {
t.Errorf("the duration read %s, %v", d, err)
}
if d, err := SettingDuration("compose-ask-bound", 10*time.Second); err != nil || d != 10*time.Second {
t.Errorf("an absent setting read %s, %v, not its default", d, err)
}
if _, err := SettingDuration("kept-call-pace-first", time.Second); err == nil || !strings.Contains(err.Error(), "kept-call-pace-first") {
t.Errorf("a value that is no duration read as %v", err)
}
// §775: a bundle reads its kept-call pace from the same settings at its start, and refuses one that is no duration.
if err := ServeOn("b", nil, strings.NewReader(""), io.Discard); err == nil || !strings.Contains(err.Error(), "kept-call-pace-first") {
t.Errorf("a bundle served with a pace that is no duration: %v", err)
}
if MetaCall != buscalls.MetaCall {
t.Errorf("the call id's place is %q here and %q in buscalls", MetaCall, buscalls.MetaCall)
}
@@ -108,67 +142,6 @@ func TestACallerInTheArgumentsIsNeverTheCaller(t *testing.T) {
if got != "shanks.node-tools" {
t.Fatalf("with a caller in the arguments the tool read %q, want the runtime's", got)
}
// A module's trusted list of callers (issue 774, ADR 0563 §8) grants the callers it names as the runtime proved them:
// a module on any machine, <machine>.<module> exactly, person.<name> exactly; no wildcard, never one unproven.
callers, err := ParseCallers([]byte(`{"callers":["node-tools","ace.claude-code","person.jo","*"]}`))
if err != nil {
t.Fatal(err)
}
for caller, want := range map[string]bool{"shanks.node-tools": true, "ace.claude-code": true, "g14.claude-code": false,
"person.jo": true, "person.node-tools": false, Unproven: false, "": false, "novox.mesh-vault": false} {
if callers.Allows(caller) != want {
t.Errorf("%q allowed: %v, want %v", caller, !want, want)
}
}
if _, err := ParseCallers([]byte(`{"callers":["x"],"more":1}`)); err == nil {
t.Error("a list with a field it does not know was read")
}
// A holder's list per verb (ADR 0627 §2): each verb's entries as above, plus every proved caller (AnyCaller) or
// every operator's session (AnyPerson); an unproven caller never, a verb the holder does not serve refused.
verbs, err := ParseVerbCallers(`{"publish":["mesh-build-go"],"versions":["*"],"release":["operator","sweep"]}`,
[]string{"publish", "versions", "release", "remove"}, nil)
if err != nil {
t.Fatal(err)
}
for _, c := range []struct {
verb, caller string
want bool
}{{"publish", "ace.mesh-build-go", true}, {"publish", "ace.mesh-build-node", false}, {"versions", "g14.anything", true},
{"versions", Unproven, false}, {"release", "person.jo", true}, {"release", "ace.operator", false},
{"release", "novox.sweep", true}, {"remove", "novox.sweep", false}} {
if got := verbs.Allowed(c.verb, c.caller) == nil; got != c.want {
t.Errorf("%s by %q allowed: %v, want %v", c.verb, c.caller, got, c.want)
}
}
// A-295: an entry `seat:<seat>` allows the modules the part's holder function answers for the seat, and
// nobody without holders.
seats := VerbCallers{"again": {AnyPerson, "seat:node-tool-runner", "seat:mesh-healers"}}
holders := func(seat string) []string {
return map[string][]string{"node-tool-runner": {"node-tools"}, "mesh-healers": {"mesh-delivery-watchman"}}[seat]
}
for _, c := range []struct {
caller string
holders func(string) []string
want bool
}{{"ace.node-tools", holders, true}, {"g14.mesh-delivery-watchman", holders, true}, {"ace.mesh-build-go", holders, false},
{"person.jo", holders, true}, {"ace.node-tools", nil, false}} {
if got := seats.AllowedWith("again", c.caller, c.holders) == nil; got != c.want {
t.Errorf("again by %q (holders %v) allowed: %v, want %v", c.caller, c.holders != nil, got, c.want)
}
}
if _, err := ParseVerbCallers(`{"mirror":["x"]}`, []string{"publish"}, nil); err == nil {
t.Error("a list naming a verb the holder does not serve was read")
}
if d, _ := ParseVerbCallers(" ", nil, VerbCallers{"publish": {"x"}}); len(d["publish"]) != 1 {
t.Error("an empty value is not the holder's defaults")
}
// As mesh-config resolves the value: the object itself, or written as a string; null is the defaults.
for _, raw := range []string{`{"publish":["a"]}`, `"{\"publish\":[\"a\"]}"`, `null`} {
c, err := parseConfiguredVerbCallers(json.RawMessage(raw), []string{"publish"}, VerbCallers{"publish": {"a"}})
if err != nil || c.Allowed("publish", "ace.a") != nil {
t.Errorf("the config value %s read as %v, %v", raw, c, err)
}
}
if ModuleOf("ace.mesh-build-go") != "mesh-build-go" {
t.Error("ModuleOf does not read the module of a proved caller")
}
@@ -200,44 +173,3 @@ func TestArgumentsOfNoCallHaveNoCaller(t *testing.T) {
t.Fatalf("CallerOf(nil) answered %q", got)
}
}
// A holder's caller list is held (issue 1966): the runtime is asked once, by a watch; a later call never asks again, so
// an ask that timed out refuses no verb, and a change that cannot be read keeps the list last read.
func TestAHeldCallerListIsAskedOnceAndSurvivesAnUnreadableChange(t *testing.T) {
verbs, defaults := []string{"publish"}, VerbCallers{"publish": {"a"}}
var asks int
var push func(ProvisionChange) error
fail := true
read := holdVerbCallers(func(key string, h func(ProvisionChange) error) error {
asks++
if fail {
return errors.New("nats: timeout")
}
push = h
return h(ProvisionChange{Kind: "config", Key: key, Value: json.RawMessage(`{"publish":["b"]}`)})
}, "callers", verbs, defaults)
if _, err := read(); err == nil {
t.Fatal("a list never read was answered")
}
fail = false
c, err := read()
if err != nil || c.Allowed("publish", "ace.b") != nil || asks != 2 {
t.Fatalf("after the ask answered: %v, %v, asked %d times", c, err, asks)
}
for i := 0; i < 3; i++ {
if _, err := read(); err != nil {
t.Fatal(err)
}
}
if asks != 2 {
t.Errorf("a held list was asked again: %d asks", asks)
}
_ = push(ProvisionChange{Kind: "config", Key: "callers", Value: json.RawMessage(`{"nothing":["x"]}`)})
if c, err := read(); err != nil || c.Allowed("publish", "ace.b") != nil {
t.Errorf("an unreadable change dropped the list last read: %v, %v", c, err)
}
_ = push(ProvisionChange{Kind: "config", Key: "callers", Value: json.RawMessage(`{"publish":["c"]}`)})
if c, _ := read(); c.Allowed("publish", "ace.c") != nil || c.Allowed("publish", "ace.b") == nil {
t.Errorf("a change was not held: %v", c)
}
}
-207
View File
@@ -1,207 +0,0 @@
package stdio
import (
"bytes"
"encoding/json"
"fmt"
"slices"
"strings"
"sync"
)
// Callers is a module's trusted list of who may call a verb of its (novox/hq ADR 0459 §2, ADR 0563 §8), as the mesh
// writes a list setting into a file the module reads: `{"callers": [...]}`. An entry is a module's name (that module on
// any machine), exactly <machine>.<module>, or exactly person.<name>. Each caller is the runtime's proof (CallerOf), never
// an argument; nobody beyond the list is granted, a wildcard is no entry, and an unproven caller never matches.
type Callers []string
// ParseCallers reads a callers file: the list under `callers`, and nothing else.
func ParseCallers(raw []byte) (Callers, error) {
var f struct {
Callers Callers `json:"callers"`
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&f); err != nil {
return nil, fmt.Errorf("the callers setting is not a list of callers: %v", err)
}
return f.Callers, nil
}
// Allows says whether caller, as the runtime proved it, is one the list names.
func (c Callers) Allows(caller string) bool {
if caller == "" || caller == Unproven {
return false
}
for _, entry := range c {
if entry == "" || strings.ContainsAny(entry, "*> ") {
continue
}
if entry == caller {
return true
}
if !strings.Contains(entry, ".") {
if _, module, ok := strings.Cut(caller, "."); ok && module == entry && !strings.HasPrefix(caller, "person.") {
return true
}
}
}
return false
}
// VerbCallers is a holder's trusted list per verb (novox/hq ADR 0627 §2, design 51 *Who may call which verb*): for each
// verb of the seats it holds, the callers that may call it, each entry read as Callers reads it. Two entries more stand
// for a whole class: AnyCaller lets every proved caller call the verb (a read the mesh keeps open), AnyPerson every
// operator's session the runtime proved as person.<name>. It names no seat and no verb: the holder gives its verbs and
// its defaults, and keeps any rule of its own seat (who may never be on a list) beside it.
type VerbCallers map[string][]string
// The entries of a VerbCallers list that stand for a class of callers.
const (
AnyCaller = "*"
AnyPerson = "operator"
)
// ParseVerbCallers reads a holder's config value of verb to callers; an empty value is defaults. A verb not among verbs
// is refused, so a list that names a verb the holder does not serve is said at once.
func ParseVerbCallers(raw string, verbs []string, defaults VerbCallers) (VerbCallers, error) {
if strings.TrimSpace(raw) == "" {
return defaults, nil
}
var c VerbCallers
if err := json.Unmarshal([]byte(raw), &c); err != nil {
return nil, fmt.Errorf("callers is not a JSON object of verb to callers: %w", err)
}
for verb := range c {
if !slices.Contains(verbs, verb) {
return nil, fmt.Errorf("callers names the verb %q, which the holder does not serve", verb)
}
}
return c, nil
}
// CallerSeatPrefix opens an entry naming a seat, `seat:<seat>`: every module holding it, so a list names no module (design 47
// G A-210, A-295).
const CallerSeatPrefix = "seat:"
// Allowed answers nil when caller, as the runtime proved it, may call verb; else the refusal naming both. An unproven
// caller is never allowed, not even by AnyCaller. An entry `seat:<seat>` allows no one here (AllowedWith).
func (c VerbCallers) Allowed(verb, caller string) error { return c.AllowedWith(verb, caller, nil) }
// AllowedWith is Allowed whose entries `seat:<seat>` allow a module caller whose module holders answers for that seat:
// the part's holder function, which answers from what it last heard of the assigner's seat-holders view (design 47 G A-295),
// so no call is made per check. A nil holders, or a seat it answers none for, allows no one by that entry.
func (c VerbCallers) AllowedWith(verb, caller string, holders func(seat string) []string) error {
if caller == "" || caller == Unproven {
return fmt.Errorf("%s: refused: the request carries no caller the tool runner proved", verb)
}
person := strings.HasPrefix(caller, "person.")
for _, entry := range c[verb] {
if seat, ok := strings.CutPrefix(entry, CallerSeatPrefix); ok {
if !person && holders != nil && slices.Contains(holders(seat), ModuleOf(caller)) {
return nil
}
continue
}
switch entry {
case AnyCaller:
return nil
case AnyPerson:
if person {
return nil
}
default:
if (Callers{entry}).Allows(caller) {
return nil
}
}
}
return fmt.Errorf("%s: refused for %s: not on the holder's caller list for %s", verb, caller, verb)
}
// ModuleOf is the module of a proved module caller, which the runtime names <machine>.<module>.
func ModuleOf(proved string) string {
if _, module, ok := strings.Cut(proved, "."); ok {
return module
}
return proved
}
// ConfiguredVerbCallers is the holder's list as mesh-config resolved its config value key for this machine (Config):
// a JSON object of verb to callers, or that object written as a string; an unset or empty value is defaults. A value
// that cannot be read is an error, never the defaults, so a broken list is said, not widened.
func ConfiguredVerbCallers(key string, verbs []string, defaults VerbCallers) (VerbCallers, error) {
raw, err := Config(key)
if err != nil {
return nil, fmt.Errorf("the config value %s cannot be read: %w", key, err)
}
return parseConfiguredVerbCallers(raw, verbs, defaults)
}
// HoldVerbCallers is ConfiguredVerbCallers held: the returned reader asks the runtime once, by a watch of the config
// value key (WatchConfig), and from then on answers the list it holds, which each change of the value replaces. A call
// never asks the runtime again, so a runtime that is slow or away for a moment (a timed-out ask) refuses no verb; a
// change that cannot be read keeps the list last read and is said on the bundle's standard error, so a broken list is
// said and never widened. Only a reader that has not yet read any value answers an error, and its next call asks again.
func HoldVerbCallers(key string, verbs []string, defaults VerbCallers) func() (VerbCallers, error) {
return holdVerbCallers(WatchConfig, key, verbs, defaults)
}
func holdVerbCallers(watch func(string, func(ProvisionChange) error) error, key string, verbs []string, defaults VerbCallers) func() (VerbCallers, error) {
var start, mu sync.Mutex
var held VerbCallers
var bad error
handle := func(c ProvisionChange) error {
mu.Lock()
defer mu.Unlock()
if c.Refused != "" {
bad = fmt.Errorf("the config value %s is not answered: %s", key, c.Refused)
} else if l, err := parseConfiguredVerbCallers(c.Value, verbs, defaults); err != nil {
bad = fmt.Errorf("the config value %s cannot be read: %w", key, err)
} else {
held, bad = l, nil
return nil
}
if held != nil {
sayf("%v: the list last read stays", bad)
}
return nil
}
read := func() (VerbCallers, error) {
mu.Lock()
defer mu.Unlock()
if held != nil {
return held, nil
}
if bad != nil {
return nil, bad
}
return nil, nil
}
return func() (VerbCallers, error) {
if l, err := read(); l != nil || err != nil {
return l, err
}
start.Lock()
defer start.Unlock()
if l, err := read(); l != nil || err != nil {
return l, err
}
if err := watch(key, handle); err != nil {
return nil, fmt.Errorf("the config value %s cannot be read: %w", key, err)
}
l, err := read()
if l == nil && err == nil {
err = fmt.Errorf("the config value %s cannot be read: the runtime handed over no value", key)
}
return l, err
}
}
func parseConfiguredVerbCallers(raw json.RawMessage, verbs []string, defaults VerbCallers) (VerbCallers, error) {
var text string
if err := json.Unmarshal(raw, &text); err == nil || len(bytes.TrimSpace(raw)) == 0 || string(bytes.TrimSpace(raw)) == "null" {
return ParseVerbCallers(text, verbs, defaults)
}
return ParseVerbCallers(string(raw), verbs, defaults)
}
+3
View File
@@ -64,6 +64,7 @@ func (m Manifest) Resolve(built []Built) (Manifest, error) {
// **Each template's text, as the build read it back from its templates archive** (novox/hq ADR 0349 §2): into
// the file's content, so what the mesh holds and composes is what the same text inline would be.
var handed *Handed
templatesDigest := ""
if m.Templated() {
name := TemplatesArtifact(m)
texts := by[name].Texts
@@ -90,12 +91,14 @@ func (m Manifest) Resolve(built []Built) (Manifest, error) {
// And, for a moved module, where its templates are and which one each file and item is filled from
// (handed.go): read while its resources and items still name their templates.
handed = handedBy(m, by[name])
templatesDigest = by[name].Digest
m.Resources = filled
m.Items = items
}
out := m
out.Handed = handed
out.TemplatesDigest = templatesDigest
out.Build = nil
// Read with the build, like Build: the manifest the mesh holds carries each file's text (issue 731).
out.Templates = ""
+16
View File
@@ -120,3 +120,19 @@ func TestAResourceNamingAPackageIsRefused(t *testing.T) {
t.Fatal("a resource backed by a package was accepted; a package is not a resource")
}
}
// A templated module's resolved manifest keeps the digest of the archive its files were rendered from, handed or not
// (design 47 G A-481, A-481a); a module with no templates keeps none.
func TestResolveKeepsTheDigestOfTheTemplatesArchive(t *testing.T) {
m := Manifest{Module: "tidy", Build: &Build{Artifacts: []Artifact{{Name: "files", Kind: ArtifactArchive, From: "files"}}}, Resources: []map[string]any{
{"id": "tidy:conf", "type": "file", "path": "/etc/tidy.conf", TemplateField: "files/tidy.conf"}}}
digest := "sha256:" + strings.Repeat("c", 64)
got, err := m.Resolve([]Built{{Name: "files", Kind: ArtifactArchive, Digest: digest,
Reference: ArtifactStoreScheme + "tidy/files/blobs/" + digest, Texts: map[string]string{"tidy.conf": "x"}}})
if err != nil || got.TemplatesDigest != digest {
t.Fatalf("templates digest %q, %v; want %s", got.TemplatesDigest, err, digest)
}
if plain, err := buildable().Resolve(wasBuilt()); err != nil || plain.TemplatesDigest != "" {
t.Fatalf("a module with no templates keeps no templates digest: %q, %v", plain.TemplatesDigest, err)
}
}
+8
View File
@@ -61,6 +61,10 @@ const (
OptionDuplicates = "duplicates"
)
// ConfigEndedDays is the configuration name of a ledger that gives its ended instances a lifetime: a whole number of
// days, 1 to 3650, after an instance's end until its state key, snapshot and index keys go (design 47 H2 H-A-634 (3)).
const ConfigEndedDays = "ended-days"
// ConfigWhenFull is what a configuration of its own says a bare stream does when full: WhenFullRefuse or
// WhenFullDropOldest. In a template it is fixed, never an option (ADR 0595 §3).
const (
@@ -92,6 +96,10 @@ type LedgerType struct {
Operations []LedgerOperation `json:"operations"`
// Indexes are its declared indexes, each a second key-value bucket kept by a watcher (ADR 0597 §4).
Indexes []LedgerIndex `json:"indexes,omitempty"`
// EndsWith names the field of the type's schema whose value ends an instance: an instance has ended while its state
// holds a value there (absent, null, an empty object and an empty text are no value). Absent: its instances never end
// (design 47 H2 H-A-634 (1), (3)).
EndsWith string `json:"ends-with,omitempty"`
}
// LedgerField is one field of a ledger type's schema.
+58
View File
@@ -0,0 +1,58 @@
package catalogue
import (
"encoding/json"
"strconv"
)
// Every kept store of a delivery module names its cap (design 47 H2 §812, §814): the manifest validator refuses a
// delivery module's state, log or objects entry with no cap. This is what it reads of a manifest; which module is a
// delivery module (one claiming a seat of the delivery system) and the foundation parts' old sections are its own to
// judge.
// Uncapped is one state, log or objects entry of a manifest that names no cap.
type Uncapped struct {
// Name is the entry's local name.
Name string `json:"name"`
// Kind is state, log or objects (the template's, or the old section's).
Kind string `json:"kind"`
// OldSection says the entry is in the old section of its kind (`state`, `logs`, `objects`), not an entry of
// `requires`.
OldSection bool `json:"old-section,omitempty"`
}
// UncappedStores is every state, log and objects entry of m that names no cap, the old sections' (max-mib) and the
// bus-state entries' (the option max-mib) alike, in the manifest's order. A log's default cap is not one it names.
func (m Manifest) UncappedStores() []Uncapped {
var out []Uncapped
for _, s := range m.State {
if s.MaxMiB == 0 {
out = append(out, Uncapped{Name: s.Name, Kind: TemplateState, OldSection: true})
}
}
for _, l := range m.Logs {
if l.MaxMiB == 0 {
out = append(out, Uncapped{Name: l.Name, Kind: TemplateLog, OldSection: true})
}
}
for _, o := range m.Objects {
if o.MaxMiB == 0 {
out = append(out, Uncapped{Name: o.Name, Kind: TemplateObjects, OldSection: true})
}
}
for _, e := range m.BusState {
switch e.Template {
case TemplateState, TemplateLog, TemplateObjects:
if !namesCap(e.Options[OptionCapMiB]) {
out = append(out, Uncapped{Name: e.Name, Kind: e.Template})
}
}
}
return out
}
// namesCap is whether an option's value is a cap above zero.
func namesCap(raw json.RawMessage) bool {
n, err := strconv.ParseFloat(string(raw), 64)
return err == nil && n > 0
}
-6
View File
@@ -1,6 +0,0 @@
package catalogue
// CheckerSeat is the seat mesh-delivery-checker holds.
//
// Deprecated: a whole seat's name is mesh-contracts' (seats.MeshDeliveryChecker); kept for its importers until their
// next change takes it from there (testdata/seat-names.txt).
+10 -4
View File
@@ -3,6 +3,7 @@ package catalogue
import (
"bytes"
"encoding/json"
"slices"
"strings"
"testing"
)
@@ -135,10 +136,10 @@ func TestAConfigManifestIsWrittenBackInItsOwnForm(t *testing.T) {
// The registry milestone's words round-trip the same (design 32): a config value's old name, an artifact's series
// and contracts marker, the series a module accepts of a package; absent, a series is 0.1.
declared := []byte(`{"module":"c","version":"1","config":{"font":{"type":"string","renamed-from":"font-name"}},
declared := []byte(`{"module":"c","version":"1","check-needs":["node-build-node"],"config":{"font":{"type":"string","renamed-from":"font-name"}},
"packages":{"mesh-sdk":"0.2"},
"build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"],"series":"0.2",
"generated-from":"seats"},{"name":"lib","kind":"package","language":"typescript"}]}}`)
"generated-from":"seats","check-needs":["node-build-node"]},{"name":"lib","kind":"package","language":"typescript"}]}}`)
m, err = decodeForTest(declared)
if err != nil {
t.Fatal(err)
@@ -146,16 +147,21 @@ func TestAConfigManifestIsWrittenBackInItsOwnForm(t *testing.T) {
if m.Settings["font"].RenamedFrom != "font-name" || m.AcceptedSeries("mesh-sdk") != "0.2" ||
m.AcceptedSeries("mesh-contracts") != DefaultSeries || m.Build.Artifacts[0].SeriesOf() != "0.2" ||
m.AcceptedSeries("mesh-sdk", "0.1") != "0.2" || m.AcceptedSeries("mesh-contracts", "0.10", "x", "0.3", "1.0") != "0.3" ||
m.Build.Artifacts[0].GeneratedFrom != "seats" || m.Build.Artifacts[1].SeriesOf() != "0.1" {
m.Build.Artifacts[0].GeneratedFrom != "seats" || m.Build.Artifacts[1].SeriesOf() != "0.1" ||
!slices.Equal(m.Build.Artifacts[0].CheckNeeds, []string{"node-build-node"}) || m.Build.Artifacts[1].CheckNeeds != nil ||
!slices.Equal(m.CheckNeeds, []string{"node-build-node"}) {
t.Fatalf("read %+v", m)
}
raw, _ = json.Marshal(m)
for _, said := range []string{`"renamed-from":"font-name"`, `"packages":{"mesh-sdk":"0.2"}`, `"series":"0.2"`,
`"generated-from":"seats"`} {
`"generated-from":"seats"`, `"check-needs":["node-build-node"]`} {
if !strings.Contains(string(raw), said) {
t.Errorf("written back without %s: %s", said, raw)
}
}
if strings.Count(string(raw), `"check-needs":["node-build-node"]`) != 2 { // H-A-453 (2): the module's own and the artifact's
t.Errorf("the module's check-needs is not written back: %s", raw)
}
if strings.Count(string(raw), `"series"`) != 1 {
t.Errorf("a series nobody said is written: %s", raw)
}
+17 -9
View File
@@ -5,17 +5,25 @@ import (
"testing"
)
// 1279/AC4 (ADR 0443 §4): no module is given a way to ask where its consumer starts. A consumes entry is an event's
// name; one that carries a key asking for the stream's history is refused by name, so the safe start is the only one.
func TestAConsumesEntryAskingWhereItStartsIsRefused(t *testing.T) { // 1279/AC4
// 1279/AC4 (ADR 0443 §4), design 47 H2b §871 (H-A-850): no module is given a way to ask where its consumer starts. A consumes entry is an
// event's name or {event, …}; a key beside the event (from, start, deliver) is set aside and named with its path, the entry read as
// its event alone, so a registration still refuses the manifest by that unknown word; an object with no event is refused by name.
func TestAConsumesEntryAskingWhereItStartsIsRefused(t *testing.T) { // 1279/AC4, 1984/AC-871
for _, key := range []string{"from", "start", "deliver"} {
raw := `{"module":"audit","version":"1","consumes":[{"event":"shop.order.placed","` + key + `":"beginning"}]}`
_, err := decodeForTest([]byte(raw))
if err == nil {
t.Fatalf("a consumes entry with %q was accepted", key)
raw := `{"module":"audit","version":"1","consumes":["a.b",{"event":"shop.order.placed","` + key + `":"beginning"}]}`
m, err := decodeForTest([]byte(raw))
if err != nil {
t.Fatalf("a consumes entry with %q was refused: %v", key, err)
}
if !strings.Contains(err.Error(), `"`+key+`"`) || !strings.Contains(err.Error(), "consumes") {
t.Errorf("the refusal for %q does not name the key and the field: %v", key, err)
if strings.Join(m.Consumes, " ") != "a.b shop.order.placed" || !strings.Contains(m.SetAside(), "consumes[1]."+key) {
t.Errorf("%q: consumes %v, set aside %q", key, m.Consumes, m.SetAside())
}
if !strings.Contains(m.UnknownField(), `"`+key+`"`) {
t.Errorf("%q is not named unknown, which is what a registration refuses by: %q", key, m.UnknownField())
}
_, err = decodeForTest([]byte(`{"module":"audit","version":"1","consumes":[{"` + key + `":"beginning"}]}`))
if err == nil || !strings.Contains(err.Error(), `"`+key+`"`) || !strings.Contains(err.Error(), "consumes") {
t.Errorf("the refusal of an entry with %q and no event does not name the key and the field: %v", key, err)
}
}
if _, err := decodeForTest([]byte(`{"module":"audit","version":"1","consumes":["shop.order.placed"]}`)); err != nil {
+11 -4
View File
@@ -8,12 +8,14 @@ import (
// Defends novox/hq ADR 0208: the graphical session is one module per piece, on the mesh's seats.
// §2: the eleven roles are the mesh's own node seats, each with the verbs it starts with.
// §2: the eleven roles are the mesh's own node seats, each with the verbs it starts with. Defends design 08
// sign-in-page §3 (novox/hq ADR 0687 §4): the display session gains the required verb `open`, and its decision
// gains ADR 0687.
func TestTheGraphicalSessionsSeatsAreTheMeshsOwnWithTheirVerbs(t *testing.T) {
want := map[string][]string{
LoginManagerSeat: {"sessions"},
DisplayServerSeat: {"displays", "layout"},
DisplaySessionSeat: {"reload", "workspaces", "windows"},
DisplaySessionSeat: {"reload", "workspaces", "windows", "open"},
TerminalEmulatorSeat: {"open"},
LauncherSeat: {"menu", "secret"},
NotifierSeat: {"send", "history"},
@@ -23,14 +25,19 @@ func TestTheGraphicalSessionsSeatsAreTheMeshsOwnWithTheirVerbs(t *testing.T) {
CompositorSeat: nil,
SecretServiceSeat: nil,
}
decisions := map[string]string{DisplaySessionSeat: "novox/hq ADR 0208, ADR 0687"}
for name, verbs := range want {
s, ok := SeatNamed(name)
if !ok {
t.Errorf("%s is not in the mesh's set", name)
continue
}
if s.Scope != ScopeNode || s.Decision != "novox/hq ADR 0208" {
t.Errorf("%s is %s-scoped under %q", name, s.Scope, s.Decision)
wantDecision := decisions[name]
if wantDecision == "" {
wantDecision = "novox/hq ADR 0208"
}
if s.Scope != ScopeNode || s.Decision != wantDecision {
t.Errorf("%s is %s-scoped under %q, want %q", name, s.Scope, s.Decision, wantDecision)
}
var got []string
for _, v := range s.Serves {
+96 -30
View File
@@ -452,6 +452,15 @@ func (m Manifest) AnsweredByHelperFor(provision string) bool {
return false
}
// The classes a module is (Manifest.Class; design 47 H2 §810, H-A-394).
const (
ClassCore = "core"
ClassLeaf = "leaf"
)
// Leaf is whether m is a leaf: its class says so, or it names none.
func (m Manifest) Leaf() bool { return m.Class == "" || m.Class == ClassLeaf }
// Manifest is everything a module says about itself.
type Manifest struct {
Module string `json:"module"`
@@ -737,6 +746,11 @@ type Manifest struct {
// wrong the moment anybody edits anything.
Build *Build `json:"build,omitempty"`
// CheckNeeds are the seats the integration tests of a package outside every artifact's `from` need the node to hold, by
// name, in an artifact's form (Artifact.CheckNeeds): the Go build module reads them for the packages no artifact's
// `from` holds (design 47 H2 H-A-453 (2)). Empty needs nothing.
CheckNeeds []string `json:"check-needs,omitempty"`
// Templates is the module's directory its template files are kept in, and its build packs into its templates
// archive: files/ when it says none (DefaultTemplatesDir; novox/hq ADR 0349 §2, issue 731). A module whose files/
// is already an archive unpacked onto the machine names another, so its templates neither land beside what it
@@ -749,6 +763,9 @@ type Manifest struct {
// Handed is what its build kept for that (handed.go): written by Resolve, never in a repository.
Moved bool `json:"moved,omitempty"`
Handed *Handed `json:"handed,omitempty"`
// TemplatesDigest is the digest of the archive a templated module's files were rendered from, "sha256:<hex>": written
// by Resolve, never in a repository; the composition names it (design 47 G A-481, A-481a).
TemplatesDigest string `json:"templates-digest,omitempty"`
// Binds is where this module wants to be told about something it requires, per requirement.
//
@@ -820,6 +837,18 @@ type Manifest struct {
// no module): the bus and the provisioner and its client say it.
CoreCredentials bool `json:"core-credentials,omitempty"`
// DeclarationReads is the declaration Version (declaration.Version) the node-engine this module is reads, and
// DeclarationWrites the one the composer this module is writes (design 47 H2 §813 (12), H-A-388): the edge the delivery
// plan derives orders the writer of a Version after every node's engine that reads it. Said by the module; zero for
// one that is neither.
DeclarationReads int `json:"declaration-reads,omitempty"`
DeclarationWrites int `json:"declaration-writes,omitempty"`
// Class is ClassCore for a module whose delivery carries a contract of the mesh (one that claims a seat) and
// ClassLeaf for one that claims none (design 47 H2 §810, H-A-394): the gate reads it from the module's catalog
// entry. Absent is a leaf (Leaf); which manifest must name it is the manifest check's.
Class string `json:"class,omitempty"`
// SecretsOwner is who the files holding this module's secrets belong to on the machine —
// `uid:gid`, or a name — when its process is not root.
//
@@ -1260,6 +1289,11 @@ type Artifact struct {
// module carrying it holds contracts only and claims no seat, which the judge refuses naming the seat; the build
// modules' test step regenerates the package and fails on a file out of step.
GeneratedFrom string `json:"generated-from,omitempty"`
// CheckNeeds are the seats a Go artifact's integration tests need the node to hold, by name (`node-build-node`), as the
// marker file check-needs in a package's directory named them, which this field replaces (design 47 H2 §800; H-A-350
// DMC-6, H-A-399 (3)); the Go build module's digest and the delivery SDK's step run read it here. Empty needs nothing.
CheckNeeds []string `json:"check-needs,omitempty"`
}
// AcceptedSeries is the series of the package of that name this module accepts: the one Packages names, or else the
@@ -1578,10 +1612,11 @@ func (m *Manifest) UnmarshalJSON(raw []byte) error {
// Beside `settings` it is refused by name (MixedFormProblems), never merged into it.
delete(keys, ConfigField)
}
if err := consumesEntryProblem(keys["consumes"]); err != nil {
consumesAside, err := readConsumes(keys)
if err != nil {
return err
}
invokeFields, err := readInvokes(keys)
invokeFields, invokesAside, err := readInvokes(keys)
if err != nil {
return err
}
@@ -1671,6 +1706,8 @@ func (m *Manifest) UnmarshalJSON(raw []byte) error {
requireShares = read.shares
busState, busStateAside = read.busState, read.aside
}
busStateAside = append(busStateAside, consumesAside...)
busStateAside = append(busStateAside, invokesAside...)
// The stored form's shares (RequireSharesKey).
if stored, ok := keys[RequireSharesKey]; ok {
if string(stored) != "null" {
@@ -1767,35 +1804,37 @@ type invokeLongForm struct {
// readInvokes reads `invokes` whose entries are verbs or, in their long form, {verb, fields}: it puts the verbs back in
// keys as plain names and answers the fields each long-form entry names.
func readInvokes(keys map[string]json.RawMessage) (map[string][]string, error) {
// An unknown key of a long-form entry is set aside and said as the path `invokes[i].key` (design 47 H2b §871).
func readInvokes(keys map[string]json.RawMessage) (map[string][]string, []string, error) {
raw, ok := keys["invokes"]
if !ok || string(raw) == "null" {
return nil, nil
return nil, nil, nil
}
var entries []json.RawMessage
if err := json.Unmarshal(raw, &entries); err != nil {
return nil, nil // not a list: the field's own decoder says so
return nil, nil, nil // not a list: the field's own decoder says so
}
var verbs []string
var verbs, aside []string
var fields map[string][]string
for i, e := range entries {
trimmed := bytes.TrimSpace(e)
if len(trimmed) == 0 || trimmed[0] != '{' {
var verb string
if err := json.Unmarshal(trimmed, &verb); err != nil {
return nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
return nil, nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
}
verbs = append(verbs, verb)
continue
}
var long invokeLongForm
dec := json.NewDecoder(bytes.NewReader(trimmed))
dec.DisallowUnknownFields()
if err := dec.Decode(&long); err != nil {
return nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
long, unknown, err := readAside[invokeLongForm](trimmed)
if err != nil {
return nil, nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
}
for _, path := range unknown {
aside = append(aside, fmt.Sprintf("invokes[%d]%s", i, path))
}
if long.Verb == "" {
return nil, fmt.Errorf("invokes[%d]: a long-form entry names its verb", i)
return nil, nil, fmt.Errorf("invokes[%d]: a long-form entry names its verb", i)
}
verbs = append(verbs, long.Verb)
if len(long.Fields) > 0 {
@@ -1807,10 +1846,10 @@ func readInvokes(keys map[string]json.RawMessage) (map[string][]string, error) {
}
plain, err := json.Marshal(verbs)
if err != nil {
return nil, err
return nil, nil, err
}
keys["invokes"] = plain
return fields, nil
return fields, aside, nil
}
// checkSharesNotContributed refuses a module whose own `contributes` to s3-bucket names `shares` (ADR 0468 §8).
@@ -1825,30 +1864,57 @@ func (m Manifest) checkSharesNotContributed() error {
return nil
}
// consumesEntryProblem refuses a consumes entry that is more than an event's name. **No manifest word asks where a
// consumer starts** (novox/hq ADR 0443 §4): the controller makes every module's consumer from now, and the first module
// that needs a stream's history brings a decision that adds the word. An entry carrying a key such as from, start or
// deliver would otherwise be read as a bare "cannot unmarshal object", which says nothing of why.
func consumesEntryProblem(raw json.RawMessage) error {
// consumesLongForm is an entry of `consumes` in its long form: the event it consumes (design 47 H2b §871, H-A-850).
type consumesLongForm struct {
Event string `json:"event"`
}
// readConsumes reads `consumes` whose entries are an event's name or, in the long form, {event, …}: it puts the names back in keys
// as plain names, and answers the paths of the words it set aside in a long-form entry (`consumes[i].key`). **No manifest word asks
// where a consumer starts** (novox/hq ADR 0443 §4): the controller makes every module's consumer from now, so an object with no
// `event` (a key such as from, start or deliver alone) is refused, with the reason, never read as a bare "cannot unmarshal object".
func readConsumes(keys map[string]json.RawMessage) ([]string, error) {
raw := keys["consumes"]
var entries []json.RawMessage
if len(raw) == 0 || json.Unmarshal(raw, &entries) != nil {
return nil // not an array: the ordinary decoding says so
return nil, nil // not an array: the ordinary decoding says so
}
var aside []string
plain := make([]any, 0, len(entries))
long := false
for i, e := range entries {
var obj map[string]json.RawMessage
if json.Unmarshal(e, &obj) != nil {
var v any
_ = json.Unmarshal(e, &v)
plain = append(plain, v)
continue
}
keys := make([]string, 0, len(obj))
for k := range obj {
keys = append(keys, strconv.Quote(k))
read, unknown, err := readAside[consumesLongForm](e)
if err != nil || read.Event == "" {
names := make([]string, 0, len(obj))
for k := range obj {
names = append(names, strconv.Quote(k))
}
sort.Strings(names)
return nil, fmt.Errorf("consumes entry %d is the long form {event, …} or an event's name, and carries the key %s with no event: "+
"no word asks where a consumer starts, because the controller makes every module's consumer from now (novox/hq ADR 0443 §4)",
i, strings.Join(names, ", "))
}
sort.Strings(keys)
return fmt.Errorf("consumes entry %d carries the key %s: an entry is an event's name alone, and no word asks where a "+
"consumer starts, because the controller makes every module's consumer from now (novox/hq ADR 0443 §4)",
i, strings.Join(keys, ", "))
for _, path := range unknown {
aside = append(aside, fmt.Sprintf("consumes[%d]%s", i, path))
}
plain = append(plain, read.Event)
long = true
}
return nil
if long {
b, err := json.Marshal(plain)
if err != nil {
return nil, err
}
keys["consumes"] = b
}
return aside, nil
}
// MarshalJSON writes `secrets` and `contributes` back in the shape they were read: single values,
@@ -2270,7 +2336,7 @@ const WhileStopped = "while-stopped"
// one reader of the field for a part that holds no Manifest. An entry of neither form is an error, never none.
func InvokedVerbs(raw json.RawMessage) ([]string, error) {
keys := map[string]json.RawMessage{"invokes": raw}
if _, err := readInvokes(keys); err != nil {
if _, _, err := readInvokes(keys); err != nil {
return nil, err
}
var verbs []string
+3 -266
View File
@@ -1,12 +1,8 @@
package catalogue
import (
"bytes"
_ "embed"
"encoding/json"
"reflect"
"regexp"
"slices"
"sort"
"strings"
)
@@ -23,9 +19,8 @@ import (
// - `seat:<name>`, a seat of the contract's seat table, as a manifest names one in a claim, a use, an invoke or a
// bucket's share.
//
// ManifestReads is what this contract reads; ManifestNeeds what one manifest's own words, forms and seat names need;
// BaselineManifestReads what a node-engine that states none is read as stating. What a module's build reads once it
// runs is never asked.
// ManifestReads is what this contract reads; what one manifest needs of it is the indexer's judge's to say (design 47 H2
// H-A-622, H-A-639). What a module's build reads once it runs is never asked.
const (
ReadWord = "word:"
ReadForm = "form:"
@@ -41,10 +36,6 @@ var referenceForms = []string{"access", "backup", "bound", "collected", "config"
// ifConfigWord is the reader capability for a resource's `if-config` (IfConfigField).
const ifConfigWord = ReadWord + "resources." + IfConfigField
// configJSONToken is the reference form `${config-json}` whole: it holds no colon, so textNeeds's search for `${<form>:`
// does not find it (design 42 zfs-owns-zfs, answer A-25).
const configJSONToken = "${config-json}"
// ReferenceFormSeat names the reference form a registry seat answers for a build's artifact,
// `<seat>/<module>/<artifact>@sha256:<digest>` (novox/hq ADR 0605 §9; the registry clients' reference forms), as the reader capability
// `form:seat-reference` a node-engine built with this contract states (ADR 0618 §1, ADR 0624 §1): the builder writes it
@@ -60,32 +51,9 @@ var artifactReferenceForms = []string{ReferenceFormSeat}
// opens to the mesh, the store's three seats among them, never from a module serving the retired provision
// artifact-store. An engine before it filled the store's reach only from that provision, so a manifest naming a seat's
// reach, and the store holder's own manifest, need it and are held from a node whose engine does not state it
// (ManifestNeeds).
// (the indexer's judge reads it).
const ReferenceFormSeatReach = "seat-reach"
// storeHolderSeat is the seat whose holder's own manifest needs form:seat-reach (novox/hq ADR 0632 §2): the one seat
// name this contract reads a rule by, and the one seat name of the package-list test's exceptions (S-8).
const storeHolderSeat = "container-image-registry"
// claimsAtMesh says whether a manifest claims seat at the mesh's scope (a claim with no scope is the seat's own). The
// store holder's own manifest, a claim of storeHolderSeat, needs form:seat-reach this way (ADR 0632 §2): read
// on every node, it leaves an engine before the reading without the old way to find the store, so it is held from every
// node whose engine does not state it.
func claimsAtMesh(top map[string]any, seat string) bool {
for _, c := range asList(top["claims"]) {
obj, _ := c.(map[string]any)
name, _ := obj["name"].(string)
scope, _ := obj["scope"].(string)
if hs, ok := SeatNamed(name); ok && hs.Name == seat && (scope == "" || scope == ScopeMesh) {
return true
}
}
return false
}
// ofSeatReach is a manifest's value naming a seat's reach, `${seat:<seat>:reach}`.
var ofSeatReach = regexp.MustCompile(`\$\{seat:[a-z0-9][a-z0-9-]*:reach\}`)
// manifestTopWords are the top-level keys Manifest.UnmarshalJSON reads apart from the fields of manifestFields: each
// read whole, its inside a map of the module's own names (requirements, local names) and values, no words of the
// contract's beneath it. `requires` and `config` are read as their fields are (manifestNeeds).
@@ -120,158 +88,6 @@ func ManifestReads() []string {
return sortedSet(set)
}
// baselineManifestReads is the baseline, generated once from mesh-sdk f02f142 (the contract every node-engine ran
// before any stated what it reads) by ManifestReads as this file computes it: one reader capability a line.
//
//go:embed manifest_reads_baseline.txt
var baselineManifestReads string
// BaselineManifestReads is what a node-engine that states no reader capability is read as stating (novox/hq ADR 0614
// §4): the words, forms and seat names of the shared contract as it stood before any node-engine stated them.
func BaselineManifestReads() []string {
var out []string
for _, line := range strings.Split(baselineManifestReads, "\n") {
if line = strings.TrimSpace(line); line != "" {
out = append(out, line)
}
}
return out
}
// StatedManifestReads is what a node-engine's statement is read as: stated itself, or the baseline when it states none
// (an engine built before the statement existed).
func StatedManifestReads(stated []string) []string {
if len(stated) == 0 {
return BaselineManifestReads()
}
return stated
}
// MissingManifestReads is each of needs that stated, read as StatedManifestReads reads it, lacks: sorted, nil when it
// lacks none.
func MissingManifestReads(needs, stated []string) []string {
have := map[string]bool{}
for _, s := range StatedManifestReads(stated) {
have[s] = true
}
var missing []string
for _, n := range needs {
if !have[n] {
missing = append(missing, n)
}
}
sort.Strings(missing)
return slices.Compact(missing)
}
// ManifestNeeds is every reader capability a manifest's own words, forms and seat names need, sorted, read as the
// lenient decoder walks the manifest: only what this contract knows is named, since what it does not know is set aside
// (Manifest.SetAside). An error is only bytes that are no JSON object.
func ManifestNeeds(raw []byte) ([]string, error) {
var top map[string]any
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&top); err != nil {
return nil, err
}
used := map[string]bool{}
textNeeds(raw, used)
if claimsAtMesh(top, storeHolderSeat) {
used[ReadForm+ReferenceFormSeatReach] = true
}
for _, r := range asList(top["resources"]) {
if obj, ok := r.(map[string]any); ok {
if _, has := obj[IfConfigField]; has {
used[ifConfigWord] = true
}
}
}
if _, has := top[ConfigField]; has || takesConfigKey.Match(raw) {
used[ReadForm+"config"] = true
}
words := map[string]bool{}
fields := structFields(reflect.TypeOf(manifestFields{}))
for _, k := range sortedAnyKeys(top) {
v := top[k]
switch {
case k == ConfigField:
// The config form is the settings form's words under another key (config.go).
words[SettingsField] = true
walkValue(v, fields[SettingsField].Type, SettingsField, words)
case k == "requires":
words[k] = true
for _, e := range asList(v) {
obj, isObj := e.(map[string]any)
if !isObj {
continue
}
if _, bus := obj["storage"]; bus {
// A bus-state entry of `requires` (BusStateEntry): the stored form's `bus-state`.
words[BusStateField] = true
walkValue(obj, reflect.TypeOf(BusStateEntry{}), BusStateField, words)
continue
}
walkValue(obj, reflect.TypeOf(requirementForm{}), k, words)
}
case slices.Contains(manifestTopWords, k):
words[k] = true
default:
if f, known := fields[k]; known {
words[k] = true
walkValue(v, f.Type, k, words)
}
}
}
for w := range words {
used[ReadWord+w] = true
}
for _, s := range seatNamesUsed(top) {
used[ReadSeat+s] = true
}
return sortedSet(used), nil
}
// seatNamesUsed is each seat of the contract's table the manifest names: in a claim, a use, an invoke of a seat's verb,
// and a bucket's share with a seat.
func seatNamesUsed(top map[string]any) []string {
known := map[string]bool{}
for _, s := range Seats() {
known[s.Name] = true
}
set := map[string]bool{}
add := func(name string) {
if known[name] {
set[name] = true
}
}
for _, c := range asList(top["claims"]) {
if obj, ok := c.(map[string]any); ok {
name, _ := obj["name"].(string)
add(name)
}
}
for _, u := range asList(top["uses"]) {
name, _ := u.(string)
add(name)
}
for _, i := range asList(top["invokes"]) {
text, _ := i.(string)
if seat, _, ok := SeatInvoke(text); ok {
add(seat)
}
}
for _, r := range asList(top["requires"]) {
obj, _ := r.(map[string]any)
for _, share := range asList(obj["shares"]) {
text, _ := share.(string)
if seat, ok := strings.CutPrefix(text, "seat:"); ok {
add(seat)
}
}
}
return sortedSet(set)
}
// contractWords is every word of this contract, by path (ReadWord): the fields of manifestFields, the keys the
// manifest's own decoder reads beside them, and the long form of a requirement.
func contractWords() []string {
@@ -315,49 +131,6 @@ func walkType(t reflect.Type, path string, set map[string]bool, onPath map[refle
}
}
// walkValue adds to used every word of t that v, a value decoded from JSON, has at path.
func walkValue(v any, t reflect.Type, path string, used map[string]bool) {
t = deref(t)
if keys, custom := wireKeys[t]; custom {
obj, _ := v.(map[string]any)
for _, k := range keys {
if _, has := obj[k]; has {
used[joinWord(path, k)] = true
}
}
return
}
switch t.Kind() {
case reflect.Struct:
obj, isObj := v.(map[string]any)
if !isObj {
return // a short form (a name for an offer): no words inside it
}
fields := structFields(t)
for _, k := range sortedAnyKeys(obj) {
f, known := fields[k]
if !known {
continue // set aside by the decoder, so no word of this contract
}
word := joinWord(path, k)
used[word] = true
walkValue(obj[k], f.Type, word, used)
}
case reflect.Slice, reflect.Array:
if t.Elem().Kind() == reflect.Uint8 {
return
}
for _, item := range asList(v) {
walkValue(item, t.Elem(), path, used)
}
case reflect.Map:
obj, _ := v.(map[string]any)
for _, k := range sortedAnyKeys(obj) {
walkValue(obj[k], t.Elem(), path, used)
}
}
}
// structFields are a struct's fields by the key the JSON decoder reads each by: its tag's name, else its own name; an
// untagged embedded struct's fields as the struct's own; never one tagged "-" or unexported.
func structFields(t reflect.Type) map[string]reflect.StructField {
@@ -444,42 +217,6 @@ func asList(v any) []any {
return list
}
// textNeeds adds the reference forms a manifest's or a template's text writes to used: a form the engine fills in a
// file's text is read there whether the text is inline or in a template file.
func textNeeds(text []byte, used map[string]bool) {
for _, f := range referenceForms {
if bytes.Contains(text, []byte("${"+f+":")) {
used[ReadForm+f] = true
}
}
if bytes.Contains(text, []byte(configJSONToken)) {
used[ReadForm+"config-json"] = true
}
if ofSeatReach.Match(text) {
used[ReadForm+ReferenceFormSeatReach] = true
}
}
// ModuleNeeds is ManifestNeeds of a module whose files take their text from templates (template.go): what the manifest
// needs and what each template's text writes, by template path (TemplatePaths), sorted. A module's needs are both: an
// engine renders the template's text as it renders inline content, so a template naming ${seat:x:reach} needs the
// reading as the same content inline does, though the manifest itself is unchanged (novox/hq ADR 0632 §2). A template
// named and not given is no need; the reader of the files says it could not read one.
func ModuleNeeds(raw []byte, templates map[string]string) ([]string, error) {
needs, err := ManifestNeeds(raw)
if err != nil || len(templates) == 0 {
return needs, err
}
used := map[string]bool{}
for _, n := range needs {
used[n] = true
}
for _, text := range templates {
textNeeds([]byte(text), used)
}
return sortedSet(used), nil
}
func sortedSet(set map[string]bool) []string {
out := make([]string, 0, len(set))
for k := range set {
-334
View File
@@ -1,334 +0,0 @@
form:access
form:backup
form:bound
form:collected
form:config
form:consumer
form:consumers
form:contribution
form:dir
form:machine
form:port
form:seat
form:secret
form:setting
seat:git
seat:mesh-artifact-store
seat:mesh-artifact-sweep
seat:mesh-broker
seat:mesh-catalog
seat:mesh-conditions
seat:mesh-config
seat:mesh-delivery
seat:mesh-delivery-checker
seat:mesh-dns-resolver
seat:mesh-enrolment
seat:mesh-hand-acts
seat:mesh-healers
seat:mesh-placement
seat:mesh-provisioner
seat:mesh-self-check
seat:mesh-store
seat:mesh-vault
seat:mesh-wants
seat:mesh-watchdogs
seat:node-backup
seat:node-bar
seat:node-build-go
seat:node-build-image
seat:node-build-node
seat:node-clipboard
seat:node-compositor
seat:node-container-runtime
seat:node-display-server
seat:node-display-session
seat:node-engine
seat:node-environment
seat:node-files
seat:node-hostname
seat:node-hotkeys
seat:node-intrusion-prevention
seat:node-launcher
seat:node-lock-screen
seat:node-login-manager
seat:node-login-shell
seat:node-message-bus
seat:node-mounts
seat:node-nfs-server
seat:node-notifier
seat:node-package-manager
seat:node-packet-filter
seat:node-power
seat:node-provisioner
seat:node-reads
seat:node-resolver
seat:node-secret-service
seat:node-service-manager
seat:node-terminal-emulator
seat:node-uplink
seat:npm-package-registry
seat:the-private-network
word:accesses
word:accesses.id
word:accesses.mode
word:accesses.path
word:binds
word:build
word:build.artifacts
word:build.artifacts.binary
word:build.artifacts.bus
word:build.artifacts.bus.asks
word:build.artifacts.bus.emits
word:build.artifacts.bus.invokes
word:build.artifacts.bus.queues
word:build.artifacts.bus.removes
word:build.artifacts.bus.state
word:build.artifacts.compiles
word:build.artifacts.context
word:build.artifacts.context.ref
word:build.artifacts.context.repository
word:build.artifacts.context.seat
word:build.artifacts.entrypoints
word:build.artifacts.env
word:build.artifacts.external
word:build.artifacts.file
word:build.artifacts.from
word:build.artifacts.kind
word:build.artifacts.language
word:build.artifacts.loads
word:build.artifacts.name
word:build.artifacts.names-on-purpose
word:build.artifacts.paths
word:build.artifacts.sha256
word:build.artifacts.system
word:build.artifacts.target
word:build.artifacts.url
word:build.artifacts.version
word:build.artifacts.within
word:build.on
word:build.on.arg
word:build.on.artifact
word:build.on.image
word:build.on.module
word:bundles
word:bundles.binary
word:bundles.bus
word:bundles.bus.asks
word:bundles.bus.emits
word:bundles.bus.invokes
word:bundles.bus.queues
word:bundles.bus.removes
word:bundles.bus.state
word:bundles.digest
word:bundles.entrypoints
word:bundles.env
word:bundles.language
word:bundles.launchers
word:bundles.loads
word:bundles.name
word:bundles.source
word:bus-users
word:capabilities
word:certificate
word:certificate.authority
word:certificate.into
word:claims
word:claims.capabilities
word:claims.kind
word:claims.name
word:claims.renders
word:claims.scope
word:claims.serves
word:collections
word:collections.comment
word:collections.name
word:computed
word:consumes
word:contributes
word:contributions
word:contributions.content
word:contributions.data
word:contributions.if-capability
word:contributions.kind
word:contributions.seat
word:data
word:data.consumers
word:data.consumers.class
word:data.consumers.in
word:data.consumers.why
word:data.kept-by
word:data.kept-by.class
word:data.kept-by.why
word:data.own
word:data.own.active
word:data.own.backup
word:data.own.backup.dump
word:data.own.backup.into
word:data.own.class
word:data.own.id
word:data.own.measure
word:data.own.path
word:data.own.redundancy
word:data.own.why
word:data.own.within
word:emits
word:environment
word:environment.path
word:environment.path.at
word:environment.path.entry
word:environment.variables
word:facts
word:facts.home
word:facts.path
word:facts.shared
word:facts.template
word:filtering
word:filtering.into
word:grants
word:guards
word:handed
word:handed.digest
word:handed.items
word:handed.source
word:handed.templates
word:instances
word:invokes
word:items
word:items.attributes
word:items.collection
word:items.content
word:items.if-capability
word:items.name
word:items.template
word:jailing
word:jailing.filter-into
word:jailing.into
word:jails
word:jails.failregex
word:jails.jail
word:jails.name
word:keeps
word:listens
word:listens.fixed
word:listens.from
word:listens.name
word:listens.port
word:listens.protocol
word:listens.why
word:logs
word:logs.max-age-days
word:logs.max-mib
word:logs.name
word:module
word:moved
word:objects
word:objects.grant
word:objects.grant.config
word:objects.max-mib
word:objects.name
word:optional-requires
word:own-secrets
word:own-secrets.issued-by
word:own-secrets.owner
word:own-secrets.path
word:own-secrets.prompt
word:own-secrets.taken
word:prepares
word:provides
word:provides.answered-by
word:provides.credential
word:provides.credential.form
word:provides.credential.issued-by
word:provides.credential.own
word:provides.credential.tool
word:provides.identity
word:provides.identity.in
word:provides.identity.max
word:provides.keeps-consumer-data
word:provides.name
word:provides.reach
word:provides.scope
word:reads
word:receives
word:replaces
word:requires
word:requires-shares
word:requires.name
word:requires.optional
word:requires.shares
word:requires.shares.methods
word:requires.shares.to
word:resources
word:runs-as
word:runtime-health
word:seats
word:seats.accepts
word:seats.by-caller
word:seats.emits
word:seats.kinded
word:seats.name
word:seats.needs
word:seats.paths
word:seats.proofs
word:seats.records
word:seats.retain-seconds
word:seats.scope
word:seats.serves
word:seats.serves.description
word:seats.serves.input
word:seats.serves.name
word:seats.serves.output
word:seats.serves.replaces
word:secrets
word:secrets-owner
word:serves
word:settings
word:settings.default
word:settings.description
word:settings.enum
word:settings.kind
word:settings.maximum
word:settings.minimum
word:settings.pattern
word:settings.predefined
word:settings.required
word:settings.runtime
word:settings.trusted
word:settings.type
word:settings.why
word:shell
word:shell.code
word:shell.for
word:shell.slot
word:slug
word:state
word:state.history
word:state.key-ttl
word:state.name
word:state.per-machine
word:state.ttl-seconds
word:streams
word:streams.duplicates
word:streams.events
word:streams.grant
word:streams.grant.config
word:streams.grant.events
word:streams.max-age-days
word:streams.max-deliveries
word:streams.max-mib
word:streams.name
word:streams.retention
word:templates
word:tools
word:unhealthy
word:unhealthy.severity
word:unhealthy.why
word:upgrade
word:upgrade.policy
word:upgrade.why
word:uses
word:version
word:waits
word:zone
word:zone.listen
word:zone.name
+14 -8
View File
@@ -7,16 +7,19 @@ import (
// Defends novox/hq ADR 0247: a machine's own resolver is a node seat, held only where something requires
// `split-dns`; where it is held it writes the resolver file and the uplink's holder steps back from it.
// Defends design 08 sign-in-page §2 (novox/hq ADR 0687 §2): the seat gains the required verb
// `uplink-names`, which replaces nothing of a shell command.
// The seat: node-scoped, decided by ADR 0247, and its three verbs required of every holder — a holder
// exists only once the module serving them does, so nothing has to be optional while it catches up.
// The seat: node-scoped, decided by ADR 0247 (gaining ADR 0687), and its four verbs required of every
// holder — a holder exists only once the module serving them does, so nothing has to be optional while it
// catches up.
func TestTheMachinesOwnResolverIsANodeSeatWithItsVerbs(t *testing.T) {
s, ok := SeatNamed(ResolverSeat)
if !ok {
t.Fatalf("%s is not in the mesh's set", ResolverSeat)
}
if s.Scope != ScopeNode || s.Decision != "novox/hq ADR 0247" || s.Delivers != "" || s.Replicated {
t.Errorf("%s is %+v; a node seat under ADR 0247 that delivers nothing", ResolverSeat, s)
if s.Scope != ScopeNode || s.Decision != "novox/hq ADR 0247, ADR 0687" || s.Delivers != "" || s.Replicated {
t.Errorf("%s is %+v; a node seat under ADR 0247, ADR 0687 that delivers nothing", ResolverSeat, s)
}
var got []string
for _, v := range s.Serves {
@@ -24,12 +27,15 @@ func TestTheMachinesOwnResolverIsANodeSeatWithItsVerbs(t *testing.T) {
if v.Optional {
t.Errorf("%s.%s is optional; its first holder serves it", ResolverSeat, v.Name)
}
if v.Description == "" || v.Input["type"] != "object" || len(v.Replaces) == 0 {
t.Errorf("%s.%s has no description, no object schema or says it replaces nothing", ResolverSeat, v.Name)
if v.Description == "" || v.Input["type"] != "object" {
t.Errorf("%s.%s has no description or no object schema", ResolverSeat, v.Name)
}
if v.Name != "uplink-names" && len(v.Replaces) == 0 {
t.Errorf("%s.%s says it replaces nothing", ResolverSeat, v.Name)
}
}
if strings.Join(got, " ") != "routes route unroute" {
t.Errorf("%s serves %v, not routes, route and unroute", ResolverSeat, got)
if strings.Join(got, " ") != "routes route unroute uplink-names" {
t.Errorf("%s serves %v, not routes, route, unroute and uplink-names", ResolverSeat, got)
}
// The verbs name a link, domains and servers, and never a VPN: the resolver knows nothing of one.
for _, v := range s.Serves {
+6 -5
View File
@@ -7,7 +7,8 @@ import (
)
// The service manager is a seat of the mesh's own with the unit verbs as its contract (novox/hq
// ADR 0177): every verb described, with a schema, taking a scope.
// ADR 0177): every verb described, with a schema, taking a scope but kernel-log, the kernel's messages, which no user
// unit has (issue 1975).
func TestTheServiceManagerSeatServesTheUnitVerbs(t *testing.T) {
seat, ok := SeatNamed("node-service-manager")
if !ok {
@@ -16,7 +17,7 @@ func TestTheServiceManagerSeatServesTheUnitVerbs(t *testing.T) {
if seat.Scope != ScopeNode {
t.Fatalf("the service manager is a role each machine has once, and the seat is %s-scoped", seat.Scope)
}
want := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal", "failed", "reset-failed", "wanted-by", "unlink-dangling"}
want := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal", "kernel-log", "failed", "reset-failed", "wanted-by", "unlink-dangling"}
var got []string
for _, v := range seat.Serves {
got = append(got, v.Name)
@@ -24,7 +25,7 @@ func TestTheServiceManagerSeatServesTheUnitVerbs(t *testing.T) {
t.Fatalf("%s is promised without a description or a schema", v.Name)
}
props, _ := v.Input["properties"].(map[string]any)
if _, has := props["scope"]; !has {
if _, has := props["scope"]; !has && v.Name != "kernel-log" {
t.Fatalf("%s takes no scope, and a user unit could not be asked for", v.Name)
}
}
@@ -41,7 +42,7 @@ func TestFailedIsAnOptionalVerbOfTheServiceManager(t *testing.T) {
holder := func(serves ...string) Manifest {
return Manifest{Module: "systemd", Version: "1", Claims: []Claim{{Name: ServiceManagerSeat, Scope: ScopeNode, Serves: serves}}}
}
eight := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal",
eight := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal", "kernel-log",
"reset-failed", "wanted-by", "unlink-dangling"}
if err := CanHold(holder(eight...), seat); err != nil {
t.Fatalf("a holder without failed is refused: %v", err)
@@ -69,7 +70,7 @@ func TestFailedIsAnOptionalVerbOfTheServiceManager(t *testing.T) {
// back from the store's row they stay required.
func TestResetFailedWantedByAndUnlinkDanglingAreRequiredVerbsOfTheServiceManager(t *testing.T) {
defer UseSeats(DefaultSeats())
nine := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal", "failed"}
nine := []string{"units", "status", "start", "stop", "restart", "enable", "disable", "journal", "kernel-log", "failed"}
all := append(slices.Clone(nine), "reset-failed", "wanted-by", "unlink-dangling")
holder := func(serves ...string) Manifest {
return Manifest{Module: "systemd", Version: "1", Claims: []Claim{{Name: ServiceManagerSeat, Scope: ScopeNode, Serves: serves}}}
+5 -5
View File
@@ -1,7 +1,6 @@
package catalogue
import (
"bytes"
"encoding/json"
"fmt"
"sort"
@@ -62,12 +61,13 @@ func readRequires(raw json.RawMessage) (requiresRead, error) {
}
continue
}
var full requirementForm
dec := json.NewDecoder(bytes.NewReader(e))
dec.DisallowUnknownFields()
if err := dec.Decode(&full); err != nil {
full, unknown, err := readAside[requirementForm](e)
if err != nil {
return requiresRead{}, fmt.Errorf("requires[%d]: a name, or {name, optional} (novox/hq ADR 0330): %w", i, err)
}
for _, path := range unknown {
aside = append(aside, fmt.Sprintf("requires[%d]%s", i, path))
}
if strings.TrimSpace(full.Name) == "" {
return requiresRead{}, fmt.Errorf("requires[%d] names no requirement: {name, optional}", i)
}
+10 -11
View File
@@ -29,20 +29,19 @@ func TestARequirementsLongForm(t *testing.T) {
t.Fatalf("written and read back, it says %v optional %v", again.Requires, again.OptionalRequires)
}
// The long form {name, optional} refuses what it does not know.
for _, raw := range []string{
`{"module":"x","version":"1","requires":[{"name":"influxdb-api","optinal":true}]}`,
`{"module":"x","version":"1","requires":[{"optional":true}]}`,
} {
if _, err := decodeForTest([]byte(raw)); err == nil {
t.Errorf("accepted %s", raw)
}
// The long form {name, optional} sets aside a word it does not know and names it (design 47 H2b §871), and refuses an entry with no name.
if m, err := decodeForTest([]byte(`{"module":"x","version":"1","requires":[{"name":"influxdb-api","optinal":true}]}`)); err != nil ||
!strings.Contains(m.SetAside(), "requires[0].optinal") || strings.Join(m.Requires, " ") != "influxdb-api" || m.IsOptional("influxdb-api") {
t.Errorf("an unknown word of a requires entry: %v, set aside %q, %v", err, m.SetAside(), m.Requires)
}
if _, err := decodeForTest([]byte(`{"module":"x","version":"1","requires":[{"optional":true}]}`)); err == nil {
t.Error("a requires entry with no name was accepted")
}
records := BusStateEntry{Name: "records", Storage: "ledger", Template: "ledger",
Options: map[string]json.RawMessage{"max-mib": json.RawMessage(`1024`)}}
// A ledger type with each of the four effects.
listing := LedgerType{Name: "listing",
listing := LedgerType{Name: "listing", EndsWith: "sold",
Schema: map[string]LedgerField{"price": {Type: "number"}, "seen": {Type: "list"}, "notes": {Type: "map"},
"text": {Type: "text"}, "digest": {Type: "text", DigestOf: "text"}},
Operations: []LedgerOperation{
@@ -53,8 +52,8 @@ func TestARequirementsLongForm(t *testing.T) {
},
Indexes: []LedgerIndex{{Name: "cheapest", On: []string{"price"}}}}
typeJSON, err := json.Marshal(listing)
if err != nil {
t.Fatal(err)
if err != nil || !strings.Contains(string(typeJSON), `"ends-with":"sold"`) || ConfigEndedDays != "ended-days" {
t.Fatalf("a ledger type's ends-with and the configuration name ended-days (H-A-634 (3)): %s (%v)", typeJSON, err)
}
ledger := records
ledger.Types = []LedgerType{listing}
+21 -110
View File
@@ -1,7 +1,6 @@
package catalogue
import (
"maps"
"os"
"slices"
"testing"
@@ -35,127 +34,39 @@ func TestOwnManifestUsesNoWordTheRunningControllerRefuses(t *testing.T) {
if g := packages["go"]; g.Name != "go" || !slices.Equal(g.Paths, []string{"go"}) {
t.Errorf("mesh-sdk's Go package is %+v, want go built from go", g)
}
// The seat verbs its code calls on a module's behalf, in the invokes form, so the indexer orders every module built
// against it after the running versions that serve its start (design 47 G lead answer A-357).
for _, verb := range []string{"seat:mesh-catalog.registrations", "seat:mesh-catalog.revision", "seat:mesh-catalog.entry", "seat:mesh-delivery.source"} {
if !slices.Contains(packages["go"].Calls, verb) {
t.Errorf("mesh-sdk's Go package calls %v, want %s among them", packages["go"].Calls, verb)
}
}
// Its named paths, so the indexer holds them and a change to them is a changed package (design 47 G A-285).
if l := packages["typescript"]; l.Name != "lib" || !slices.Equal(l.Paths, []string{"package.json", "package-lock.json", "tsconfig.json", "src"}) {
t.Errorf("mesh-sdk's TypeScript package is %+v, want lib built from package.json, package-lock.json, tsconfig.json and src", l)
}
// What a reader reads (novox/hq ADR 0614 §4): the baseline is the contract of mesh-sdk f02f142, which every running
// node-engine was built with, and this contract reads all of it; the words added since are the only ones it lacks.
reads, baseline := ManifestReads(), BaselineManifestReads()
var added []string
for _, r := range reads {
if !slices.Contains(baseline, r) {
added = append(added, r)
}
}
// The two seats the milestone renamed (ADR 0634 §9) are read by their new names; a node-engine built with the baseline
// reads the old ones, and a manifest of the new names is the milestone's to deliver after the engines. The word
// `waits` is no longer read: novox/hq ADR 0670 §2 retired it.
renamed := []string{"seat:mesh-enrolment", "seat:mesh-placement", "word:waits"}
for _, b := range baseline {
if !slices.Contains(reads, b) && !slices.Contains(renamed, b) {
t.Errorf("the baseline's %s is no reader capability of this contract", b)
}
}
// What a reader reads (novox/hq ADR 0614 §4): the words, forms and seat names this contract reads.
reads := ManifestReads()
for _, want := range []string{"word:tool-runner", "word:core-credentials", "word:bus-state", "word:bus-state.storage",
// The reference form a registry seat answers (ADR 0605 §9), and the seats the registry milestone adds.
ReadForm + ReferenceFormSeat, ReadForm + ReferenceFormSeatReach, "seat:go-package-registry", "seat:container-image-registry", "seat:oci-artifact-registry"} {
if !slices.Contains(added, want) {
t.Errorf("%s is in the baseline, or not read: added since it are %v", want, added)
ReadForm + ReferenceFormSeat, ReadForm + ReferenceFormSeatReach, "seat:go-package-registry", "seat:container-image-registry", "seat:oci-artifact-registry",
// H-A-388: the declaration Version a node-engine reads and a composer writes, the delivery plan's edge.
"word:declaration-reads", "word:declaration-writes",
// H-A-394: a module's class, core or leaf.
"word:class"} {
if !slices.Contains(reads, want) {
t.Errorf("%s is not read by this contract: %v", want, reads)
}
}
for _, want := range []string{"word:claims.serves", "word:settings.default", "form:config", "form:setting", "seat:mesh-catalog"} {
if !slices.Contains(baseline, want) {
t.Errorf("the baseline lacks %s", want)
for _, want := range []string{"word:claims.serves", "word:settings.default", "form:config", "form:setting", "seat:mesh-catalog",
// H-A-383: every node-engine reads a state's max-mib, so a manifest naming it needs no newer engine.
"word:state.max-mib"} {
if !slices.Contains(reads, want) {
t.Errorf("this contract does not read %s", want)
}
}
if blocks := untaggedBlocks(); len(blocks) != 0 {
t.Errorf("blocks whose words are their Go names, no decoder's keys: %v (name their keys in wireKeys)", blocks)
}
// What a manifest's own words, forms and seat names need, beyond the baseline.
for _, row := range []struct {
why, raw string
needs []string // among its needs
missing []string // what the baseline lacks of them
}{
{"a tool runner", `{"module":"r","version":"1","tool-runner":true}`, []string{"word:tool-runner"}, []string{"word:tool-runner"}},
{"a manifest of the baseline's words", `{"module":"a","version":"1","claims":[{"name":"mesh-catalog","scope":"mesh",` +
`"serves":["modules"]}],"invokes":["seat:mesh-delivery.show"],"config":{"x":{"type":"string","default":""}},` +
`"resources":[{"id":"f","type":"file","content":"${config:x} ${count:-0}"}],"provides":["plain",{"name":"p",` +
`"identity":{"max":20,"in":"x"}}]}`,
[]string{"word:claims.serves", "word:settings.type", "form:config", "seat:mesh-catalog", "seat:mesh-delivery",
"word:provides.identity.max", "word:resources"}, nil},
{"a bus-state entry of requires", `{"module":"b","version":"1","requires":["mesh-bus",{"name":"jobs","storage":"kv"}]}`,
[]string{"word:requires", "word:bus-state.storage"}, []string{"word:bus-state", "word:bus-state.name", "word:bus-state.storage"}},
// A seat's reach, filled from the seat holder's listen (ADR 0632 §1): an engine before it lacks the reading.
{"a seat's reach", `{"module":"s","version":"1","resources":[{"id":"f","type":"file","content":"${seat:container-image-registry:reach}"}]}`,
[]string{"form:seat", "form:seat-reach"}, []string{"form:seat-reach"}},
// The store holder's manifest, distribution's as ADR 0632 leaves it: no reach written, no provision served; an engine
// stating only the baseline lacks the reading that finds the store by it (ADR 0632 §2).
{"the store's holder", `{"module":"distribution","version":"1","claims":[{"name":"container-image-registry",` +
`"scope":"mesh","serves":["list"]}],"listens":[{"name":"registry","port":5000,"from":"mesh"}]}`,
[]string{"form:seat-reach", "seat:container-image-registry"}, []string{"form:seat-reach", "seat:container-image-registry"}},
// docker's daemon file as ADR 0632 leaves it: the manifest unchanged, its template naming the image seat's reach;
// TemplatePaths names the template a reader of the files reads.
{"a template naming a seat's reach", `{"module":"d","version":"1","resources":[{"id":"daemon","type":"file",` +
`"path":"/etc/d.json","template":"files/daemon.json"}]}`, []string{"form:seat", "form:seat-reach"},
[]string{"form:seat-reach"}},
// A resource under a config condition (design 42 zfs-owns-zfs §4, A-13).
{"a resource under if-config", `{"module":"z","version":"1","config":{"k":{"type":"string"}},"resources":[{"id":"f","type":"file",` +
`"if-config":["k"]}]}`, []string{"word:resources.if-config"}, []string{"word:resources.if-config"}},
{"a resource without if-config", `{"module":"z","version":"1","resources":[{"id":"f","type":"file"}]}`,
[]string{"word:resources"}, nil},
// The template forms of the config file and the option lines (design 42 zfs-owns-zfs §3, §9; A-13, A-15, A-25).
{"a template writing config lines", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","template":"files/o.conf"}]}`,
[]string{"form:config-lines"}, []string{"form:config-lines"}},
{"a template writing the config as json", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","template":"files/c.json"}]}`,
[]string{"form:config-json"}, []string{"form:config-json"}},
{"a template of the config form alone", `{"module":"z","version":"1","resources":[{"id":"f","type":"file","template":"files/k"}]}`,
[]string{"form:config"}, nil},
{"a word this contract does not know", `{"module":"u","version":"1","newer-word":{"inside":1}}`, []string{"word:module"}, nil},
} {
templates := map[string]map[string]string{ // the templates' text a row's module names
"a template naming a seat's reach": {"files/daemon.json": `{"x":"${seat:container-image-registry:reach}"}`},
"a template writing config lines": {"files/o.conf": "${config-lines:arc-max:options zfs zfs_arc_max=:mib-bytes}"},
"a template writing the config as json": {"files/c.json": "${config-json}"},
"a template of the config form alone": {"files/k": "${config:k}"},
}[row.why]
needs, err := ModuleNeeds([]byte(row.raw), templates)
if err != nil {
t.Fatalf("%s: %v", row.why, err)
}
if templates != nil {
m, err := Decode([]byte(row.raw))
if paths := TemplatePaths(m); err != nil || !slices.Equal(paths, slices.Sorted(maps.Keys(templates))) {
t.Errorf("%s: TemplatePaths = %v (%v), want %v", row.why, paths, err, slices.Sorted(maps.Keys(templates)))
}
}
for _, n := range row.needs {
if !slices.Contains(needs, n) {
t.Errorf("%s: needs %v, not %s", row.why, needs, n)
}
}
if slices.ContainsFunc(needs, func(n string) bool { return n == "word:newer-word" || n == "form:count" }) {
t.Errorf("%s: needs %v, naming what the contract does not read", row.why, needs)
}
for _, f := range []string{"form:config-lines", "form:config-json"} {
if slices.Contains(needs, f) != (row.why == map[string]string{"form:config-lines": "a template writing config lines",
"form:config-json": "a template writing the config as json"}[f]) {
t.Errorf("%s: needs %v, %s read wrongly", row.why, needs, f)
}
}
if slices.Contains(needs, "word:resources.if-config") != (row.why == "a resource under if-config") {
t.Errorf("%s: needs %v, if-config read wrongly", row.why, needs)
}
if got := MissingManifestReads(needs, nil); !slices.Equal(got, row.missing) {
t.Errorf("%s: an engine stating nothing lacks %v, want %v", row.why, got, row.missing)
}
if got := MissingManifestReads(needs, reads); len(got) != 0 {
t.Errorf("%s: this contract lacks %v", row.why, got)
}
}
if got := MissingManifestReads([]string{"seat:mesh-catalog", "word:module"}, []string{"word:module"}); !slices.Equal(got, []string{"seat:mesh-catalog"}) {
t.Errorf("an engine stating its own reads is read by them alone: lacks %v", got)
}
}
+14 -6
View File
@@ -35,8 +35,8 @@ func TestTheReaderReleaseReadsTheManifestWordsGWrites(t *testing.T) {
// manifest read whole, or refused naming what is wrong, and what the reader gives of it.
func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
for _, c := range []struct {
name, raw, refused string
check func(Manifest) bool
name, raw, refused, asideOf string
check func(Manifest) bool
}{
{name: "a state's cap (§469)", raw: `{"module":"m","version":"1.0","state":["plain",{"name":"pipelines","max-mib":256}]}`,
check: func(m Manifest) bool { return m.State[0].MaxMiB == 0 && m.State[1].MaxMiB == 256 }},
@@ -58,9 +58,15 @@ func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
len(m.InvokeFields) == 1 && slices.Equal(m.InvokeFields["seat:mesh-catalog.revision"], []string{"none-yet"}) &&
strings.Contains(string(out), `"invokes":["*",{"verb":"seat:mesh-catalog.revision","fields":["none-yet"]},"seat:mesh-catalog.entry"]`)
}},
{name: "a long-form invoke with a word it does not know (§617)",
raw: `{"module":"m","version":"1.0","invokes":[{"verb":"seat:mesh-catalog.revision","field":["none-yet"]}]}`,
refused: `invokes[0]: a verb, or {verb, fields}`},
{name: "a long-form invoke with a word it does not know is read without it and names it (§617, design 47 H2b §871)",
raw: `{"module":"m","version":"1.0","invokes":[{"verb":"seat:mesh-catalog.revision","field":["none-yet"],"fields":["a"]}]}`,
asideOf: "invokes[0].field",
check: func(m Manifest) bool {
return slices.Equal(m.Invokes, []string{"seat:mesh-catalog.revision"}) && slices.Equal(m.InvokeFields["seat:mesh-catalog.revision"], []string{"a"})
}},
{name: "a long-form invoke with no verb",
raw: `{"module":"m","version":"1.0","invokes":[{"fields":["a"]}]}`,
refused: `invokes[0]: a long-form entry names its verb`},
} {
m, err := decodeForTest([]byte(c.raw))
switch {
@@ -68,7 +74,9 @@ func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
t.Errorf("%s: read as %v, want refused naming %q", c.name, err, c.refused)
case c.refused == "" && err != nil:
t.Errorf("%s: refused: %v", c.name, err)
case c.refused == "" && (len(m.UnknownField()) != 0 || !c.check(m)):
case c.asideOf != "" && (!strings.Contains(m.SetAside(), c.asideOf) || !c.check(m)):
t.Errorf("%s: read as %+v, set aside %q, want %q named", c.name, m, m.SetAside(), c.asideOf)
case c.refused == "" && c.asideOf == "" && (len(m.UnknownField()) != 0 || !c.check(m)):
t.Errorf("%s: read as %+v (set aside %v)", c.name, m, m.UnknownField())
}
}
+30
View File
@@ -2,6 +2,7 @@ package catalogue
import (
"encoding/json"
"reflect"
"strings"
"testing"
@@ -28,6 +29,35 @@ func TestAManifestMaySayWhatStateItKeepsAndReads(t *testing.T) {
if string(out) != `["servers",{"name":"seen","history":5,"ttl-seconds":3600}]` {
t.Fatalf("written back as %s", out)
}
// Design 47 H2 §812, §814: the validator reads every state, log and objects entry of a manifest that names no cap, in
// the old sections and in requires alike; a capped entry, and an entry of another template, is none of them.
t.Run("each kept store that names no cap", func(t *testing.T) {
m, err := decodeForTest([]byte(`{"module":"x","version":"1",
"state":["seen",{"name":"held","max-mib":8}],
"logs":[{"name":"acts"},{"name":"kept","max-mib":64}],
"objects":[{"name":"outputs","max-mib":256}],
"requires":[{"name":"performed","storage":"key-value","template":"state","options":{"history":1}},
{"name":"taken","storage":"key-value","template":"state","options":{"max-mib":8,"key-ttl":true}},
{"name":"archives","storage":"object-store","template":"objects"},
{"name":"finding-events","storage":"stream","template":"events"}]}`))
if err != nil {
t.Fatal(err)
}
want := []Uncapped{{Name: "seen", Kind: "state", OldSection: true}, {Name: "acts", Kind: "log", OldSection: true},
{Name: "performed", Kind: "state"}, {Name: "archives", Kind: "objects"}}
if got := m.UncappedStores(); !reflect.DeepEqual(got, want) {
t.Fatalf("the uncapped stores are %+v, want %+v", got, want)
}
})
// Design 47 H2 §810 (H-A-394): a manifest says its class, core or leaf; one that names none is a leaf.
t.Run("its class, none a leaf", func(t *testing.T) {
for raw, leaf := range map[string]bool{`"class":"core",`: false, `"class":"leaf",`: true, ``: true} {
m, err := decodeForTest([]byte(`{` + raw + `"module":"x","version":"1"}`))
if err != nil || m.Leaf() != leaf || m.UnknownField() != "" {
t.Errorf("%s read as class %q, leaf %v (%v, unknown %q), want leaf %v", raw, m.Class, m.Leaf(), err, m.UnknownField(), leaf)
}
}
})
}
// 1154/AC1: a state entry may say key-ttl; it is read, written back, and a bare name or an entry without it reads as before.
+1 -1
View File
@@ -15,7 +15,7 @@ const TrustedField = "trusted"
// IfConfigField is the key any resource may carry to be declared only while a config value of its module holds
// (novox/hq design 42 zfs-owns-zfs §2, §4): a list of conditions, `<key>` or `<key>=<value>`. Said in the catalogue and
// read by the node-engine, which states it as the reader capability `word:resources.if-config` (ManifestReads); a
// manifest whose resource carries it needs that capability (ManifestNeeds).
// manifest whose resource carries it needs that capability (the indexer's judge reads it).
const IfConfigField = "if-config"
// TerminalKeys are the settings keys of a module that are set at the controller's terminal alone: places and
-1
View File
@@ -17,7 +17,6 @@ func DefaultSeats() []Seat { return append([]Seat(nil), defaultSeats...) }
// non-test code).
const (
CatalogSeat = "mesh-catalog"
CheckerSeat = "mesh-delivery-checker"
EnrolmentSeat = "mesh-node-enroller"
PlacementSeat = "mesh-module-assigner"
DeliverySeat = "mesh-delivery"
+42
View File
@@ -170,3 +170,45 @@ func removeEvery(v any, key string) int {
}
return n
}
// readAside reads one object of a manifest into a T, setting aside each key T does not know, at any depth, and saying where each
// was, as `.key` or `.entry.key` (design 47 H2b §871): the entry reads as it would without the word. Any other fault in it is the
// decoder's own and is returned.
func readAside[T any](raw json.RawMessage) (T, []string, error) {
var zero T
var tree any
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
if err := dec.Decode(&tree); err != nil {
return zero, nil, err
}
strict := func(into *T) error {
b, err := json.Marshal(tree)
if err != nil {
return err
}
d := json.NewDecoder(bytes.NewReader(b))
d.DisallowUnknownFields()
return typedUnknown(d.Decode(into))
}
var aside []string
for tries := 0; ; tries++ {
var out T
err := strict(&out)
if err == nil {
return out, aside, nil
}
unknown := asUnknownField(err)
if unknown == nil || tries > 64 {
return zero, nil, err
}
path, ok := removalThatHelps(tree, unknown.Field, err.Error(), func() error { var e T; return strict(&e) })
if !ok {
if removeEvery(tree, unknown.Field) == 0 {
return zero, nil, err
}
path = "." + unknown.Field
}
aside = append(aside, path)
}
}
+17 -4
View File
@@ -26,9 +26,10 @@ import (
"git.novox.be/novox/mesh-sdk/go/seal"
)
// Version is the vocabulary this host speaks. A declaration naming any other version is
// refused: an older host handed a newer vocabulary must not quietly do half of it.
const Version = 1
// Version is the vocabulary this host speaks, the declaration's form. A declaration naming a higher version is
// refused: an older host handed a newer vocabulary must not quietly do half of it. A lower one is a part of this
// vocabulary and is read. Version 2 carries a process's drain-bound (design 47 H2 §813 (12), H-A-358, H-A-388).
const Version = 2
// Type names a kind of resource. Every addition widens what a compromised control plane can
// express, so the list is a security artefact and grows deliberately.
@@ -921,6 +922,11 @@ type Process struct {
// runtime of a build seat's holder, whose builds must never slow the operator's desktop. Absent: the machine's
// defaults. For a process that stays up.
Yields *Yields `json:"yields,omitempty"`
// DrainBound is how long, in seconds, the process finishes the calls in flight once stopped before it exits
// (design 47 H2 §813 (12); H-A-358): the node-engine writes the unit's stop so the stop signal reaches this process
// alone and waits that long and the time its children take. Absent: none. For a process that stays up.
DrainBound int `json:"drain-bound,omitempty"`
}
// YieldIdle is the one priority a process yields at: the lowest there is.
@@ -1024,6 +1030,13 @@ func (d *Process) validate(where string, _ bool) []string {
problems = append(problems, where+": a witness judges a process that stays up; a step or a "+
"scheduled run is not running between its runs")
}
if d.DrainBound < 0 {
problems = append(problems, fmt.Sprintf("%s: drain-bound is %d: a bound is seconds, none or more", where, d.DrainBound))
}
if d.DrainBound > 0 && (d.RunOnce || d.Schedule != "") {
problems = append(problems, where+": drain-bound is for a process that stays up; a step or a scheduled run "+
"is not stopped while it serves calls")
}
if strings.ContainsAny(d.NotReversible, "\n\r") {
problems = append(problems, where+": not-reversible is one line")
}
@@ -2349,7 +2362,7 @@ func parse(raw []byte, allowActions bool) (*Declaration, error) {
return nil, &RefusalError{Problems: []string{"not a declaration: " + err.Error()}}
}
if env.Version != Version {
if env.Version < 1 || env.Version > Version {
// Everything below assumes the vocabulary, so there is nothing further to say.
return nil, &RefusalError{Problems: []string{fmt.Sprintf(
"declaration version %d; this host speaks version %d. Refused whole rather than "+
+15 -1
View File
@@ -2,6 +2,7 @@ package declaration
import (
"errors"
"fmt"
"strings"
"testing"
)
@@ -92,9 +93,22 @@ func testAnUnknownVersionIsRefusedWhole(t *testing.T) {
{"id":"a","type":"directory","path":"/etc/mesh"}
]}`)
joined := strings.Join(refusal.Problems, "\n")
if !strings.Contains(joined, "99") || !strings.Contains(joined, "version 1") {
if !strings.Contains(joined, "99") || !strings.Contains(joined, "version 2") {
t.Errorf("the version mismatch was not stated plainly: %v", refusal.Problems)
}
// Design 47 H2 §813 (12), H-A-388: Version is the declaration's form, raised to 2 by drain-bound; a lower one is a
// part of this vocabulary and is read, so a node-engine that reads 2 takes what a composer of 1 still writes.
for _, v := range []int{1, Version} {
if _, err := Parse([]byte(fmt.Sprintf(`{"declaration":%d,"resources":[{"id":"a","type":"directory","path":"/etc/mesh"}]}`, v))); err != nil {
t.Errorf("a declaration of version %d was refused: %v", v, err)
}
}
if Version != 2 {
t.Errorf("the declaration's Version is %d, want 2 (H-A-388)", Version)
}
if r := refusalFor(t, `{"declaration":0,"resources":[]}`); !strings.Contains(strings.Join(r.Problems, " "), "version 0") {
t.Errorf("a declaration of version 0 was refused as %v", r.Problems)
}
// Nothing else is reported, because everything else assumes a vocabulary this host does
// not have — a list of complaints derived from the wrong grammar is noise.
if len(refusal.Problems) != 1 {
+16
View File
@@ -1,6 +1,7 @@
package declaration
import (
"encoding/json"
"strings"
"testing"
)
@@ -99,6 +100,9 @@ func testTheModesAreExclusive(t *testing.T) {
"an unknown priority": func(p *Process) { p.Yields = &Yields{Priority: "low"} },
"a share over the whole": func(p *Process) { p.Yields = &Yields{CPUShare: 150} },
"a yield saying nothing": func(p *Process) { p.Yields = &Yields{} },
// Design 47 H2 §813 (12), H-A-358: a drain bound is seconds, for a process that stays up.
"a step with a drain bound": func(p *Process) { p.RunOnce = true; p.DrainBound = 30 },
"a negative drain bound": func(p *Process) { p.DrainBound = -1 },
} {
p := aProcess()
bad(p)
@@ -106,6 +110,18 @@ func testTheModesAreExclusive(t *testing.T) {
t.Errorf("%s was accepted", name)
}
}
// It travels in the declaration under drain-bound, and so in its digest; absent says none.
up := aProcess()
up.DrainBound = 30
if problems := up.validate("a process", false); len(problems) != 0 {
t.Errorf("a process that stays up with a drain bound was refused: %v", problems)
}
if b, _ := json.Marshal(up); !strings.Contains(string(b), `"drain-bound":30`) {
t.Errorf("the drain bound is not in the declaration: %s", b)
}
if b, _ := json.Marshal(aProcess()); strings.Contains(string(b), "drain-bound") {
t.Errorf("a process with no drain bound says one: %s", b)
}
}
// A cadence that is not a cadence is refused near its author, rather than by a machine at the far
+1 -1
View File
@@ -6,6 +6,7 @@ require (
github.com/klauspost/compress v1.20.0
github.com/nats-io/nats-server/v2 v2.11.17
github.com/nats-io/nats.go v1.54.0
golang.org/x/crypto v0.57.0
)
require (
@@ -15,7 +16,6 @@ require (
github.com/nats-io/jwt/v2 v2.8.1 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
+29 -1
View File
@@ -91,6 +91,9 @@ type BusBinding struct {
State string `json:"state,omitempty"`
Indexes map[string]string `json:"indexes,omitempty"`
Snapshot string `json:"snapshot,omitempty"`
// EndedDays is the whole number of days an ended instance's state, snapshot and index keys are kept; absent while the
// held objects allow no lifetime or the ledger names none (design 47 H2 H-A-634 (3), H-A-685 (1)).
EndedDays int `json:"ended-days,omitempty"`
// Types are a ledger's types, copied by the grants part from the entry the manifest-accepted event carries, so the
// tool runner checks an operation against its type without reading another part's state (ADR 0596, ADR 0597 §1).
Types []catalogue.LedgerType `json:"types,omitempty"`
@@ -167,12 +170,37 @@ type StreamIssued struct {
Subject string `json:"subject"`
}
// HeardIssued is one module stream an assignment hears (ADR 0363 §8).
// HeardIssued is one module stream an assignment hears (ADR 0363 §8), with its consumer's whole spec as the grants part
// composed it (design 47 H2, H-A-472 seventh addendum): a part that creates the consumer itself, such as the tool runner
// for a module's `_tools` twin, creates it from these and computes nothing. EVENTS is heard by an entry like any stream.
// The spec's fields are left out of the wire when unset, so a membership an older grants part wrote still reads (its
// entries carry no spec) and an older reader ignores them.
type HeardIssued struct {
Stream string `json:"stream"`
Consumer string `json:"consumer"`
// Filters are the subjects the consumer receives, already named for the twin, the again filter included.
Filters []string `json:"filters,omitempty"`
// AckWaitSeconds before an unacknowledged delivery is delivered again.
AckWaitSeconds int `json:"ack-wait-seconds,omitempty"`
// MaxDeliver is how often a message is handed over before the consumer gives it up; zero for no bound.
MaxDeliver int `json:"max-deliver,omitempty"`
// MaxAckPending is how many deliveries may stand unacknowledged at once; zero for the server's default.
MaxAckPending int `json:"max-ack-pending,omitempty"`
// DeliverPolicy is where the consumer starts: DeliverFromNow, DeliverLastPerSubject or DeliverAll.
DeliverPolicy string `json:"deliver-policy,omitempty"`
}
// HasSpec says the entry carries its consumer's spec, read as its filters being present (H-A-472 eighth addendum): a
// reader creates the consumer from the spec of an entry that has one, and binds by name an entry an older writer made.
func (h HeardIssued) HasSpec() bool { return len(h.Filters) > 0 }
// The deliver policies a heard entry names, the forms the grants part composes a consumer in.
const (
DeliverFromNow = "from-now"
DeliverLastPerSubject = "last-per-subject"
DeliverAll = "all"
)
// StateIssued is the state this membership issues its module's code by a local name, and whether it does: what every
// runtime that serves a module's state calls reads, so no reader keeps a second copy of the rule (novox/hq issue 1966).
// An entry of the old `state` list wins (ADR 0201); otherwise a binding of a key-value entry the module asks for in
+36 -2
View File
@@ -44,8 +44,8 @@ func TestAMembershipRoundTripsAsIssued(t *testing.T) {
bound := in
bound.Bindings = []BusBinding{{Local: "records", Storage: "ledger", Template: "ledger", History: "forge_records",
Subject: "forge_records.>", State: "forge_records_state", Indexes: map[string]string{"search": "forge_records_search"},
Snapshot: "forge_records_snapshot.>",
Types: []catalogue.LedgerType{{Name: "decision", Schema: map[string]catalogue.LedgerField{"title": {Type: "text"}},
Snapshot: "forge_records_snapshot.>", EndedDays: 30,
Types: []catalogue.LedgerType{{Name: "decision", EndsWith: "ended", Schema: map[string]catalogue.LedgerField{"title": {Type: "text"}},
Operations: []catalogue.LedgerOperation{{Name: "propose", Effect: catalogue.EffectSetFields, Fields: []string{"title"}}}}}}}
boundRaw, err := json.Marshal(bound)
if err != nil {
@@ -55,6 +55,17 @@ func TestAMembershipRoundTripsAsIssued(t *testing.T) {
if err := json.Unmarshal(boundRaw, &boundBack); err != nil || !reflect.DeepEqual(bound, boundBack) {
t.Fatalf("a membership with a ledger binding read back as %+v (%v)", boundBack, err)
}
// Design 47 H2 H-A-634 (3), H-A-685 (1): ended-days and ends-with are named only when set, so a binding without
// them encodes as before.
if !strings.Contains(string(boundRaw), `"ended-days":30`) || !strings.Contains(string(boundRaw), `"ends-with":"ended"`) {
t.Fatalf("the binding does not name ended-days and ends-with: %s", boundRaw)
}
plain := bound
plain.Bindings = []BusBinding{{Local: "records", Storage: "ledger", Types: []catalogue.LedgerType{{Name: "decision"}}}}
plainRaw, _ := json.Marshal(plain)
if strings.Contains(string(plainRaw), "ended-days") || strings.Contains(string(plainRaw), "ends-with") {
t.Fatalf("an absent ended-days or ends-with is written: %s", plainRaw)
}
// Design 47 G §642, §619: a state's binding carries its objects store, the sent store is an entry of its own, and a
// foundation part's old `objects` sections map to their stores.
withObjects := in
@@ -96,6 +107,29 @@ func TestAMembershipRoundTripsAsIssued(t *testing.T) {
if got := issuing.StateNames(); !reflect.DeepEqual(got, []string{"holds", "repos"}) {
t.Errorf("StateNames = %v", got)
}
// H-A-472 (seventh addendum): a heard entry carries its consumer's whole spec and reads back whole; an entry an older
// grants part wrote, naming only the stream and the consumer, still reads, and one without a spec encodes as before.
heard := in
heard.Hears = []HeardIssued{{Stream: "EVENTS", Consumer: "ace_forge_tools",
Filters: []string{"mesh.events.forge-bridge.>", "mesh.again.ace_forge_tools.>"},
AckWaitSeconds: 30, MaxDeliver: 5, MaxAckPending: 1, DeliverPolicy: DeliverFromNow}}
heardRaw, _ := json.Marshal(heard)
var heardBack Membership
if err := json.Unmarshal(heardRaw, &heardBack); err != nil || !reflect.DeepEqual(heard, heardBack) ||
!strings.Contains(string(heardRaw), `"ack-wait-seconds":30,"max-deliver":5,"max-ack-pending":1,"deliver-policy":"from-now"`) {
t.Fatalf("a heard entry with its spec read back as %+v (%v): %s", heardBack, err, heardRaw)
}
var older Membership
if err := json.Unmarshal([]byte(`{"node":"ace","module":"forge","hears":[{"stream":"forge-bridge","consumer":"ace_forge"}]}`), &older); err != nil ||
!reflect.DeepEqual(older.Hears, []HeardIssued{{Stream: "forge-bridge", Consumer: "ace_forge"}}) {
t.Fatalf("an older heard entry read as %+v (%v)", older.Hears, err)
}
if !heardBack.Hears[0].HasSpec() || older.Hears[0].HasSpec() {
t.Fatalf("HasSpec: a new entry %v, an older one %v", heardBack.Hears[0].HasSpec(), older.Hears[0].HasSpec())
}
if bare, _ := json.Marshal(HeardIssued{Stream: "forge-bridge", Consumer: "ace_forge"}); string(bare) != `{"stream":"forge-bridge","consumer":"ace_forge"}` {
t.Fatalf("a heard entry without a spec encodes otherwise than before: %s", bare)
}
var wire map[string]json.RawMessage
_ = json.Unmarshal(raw, &wire)
for _, k := range []string{"receives", "mesh", "seat-traffic"} {
+4 -5
View File
@@ -13,11 +13,10 @@ import "time"
// findings while it is delivered there and raises what still stands when the delivery ends. Before, it lived in the view
// alone (mesh-delivery-view internal/view motionOf), and a second reader would have judged a delivery its own way.
// Want is what the derivation reads of a module's want on a node: its fingerprint and composition, and whether it is removed.
// Want is what the derivation reads of a module's want on a node: its fingerprint, and whether it is removed. A want carries no composed digest, so a have at the wanted fingerprint is the want applied (design 47 H, H-A-78).
type Want struct {
FP string
Composed string
Removed bool
FP string
Removed bool
}
// Have is what it reads of the module's have on that node: the fingerprint and composition it runs, its phase and health
@@ -90,7 +89,7 @@ func MotionOf(w Want, wanted bool, h Have, has bool, stuckWords string, stuck bo
}
m := Motion{Delivering: !has || h.FP != w.FP || h.Phase == PhaseApplying,
Failed: has && (h.Phase == PhaseFailed || (h.FP == w.FP && h.Health == HealthFailed))}
applied := has && h.FP == w.FP && (h.Composed == "" || h.Composed == w.Composed)
applied := has && h.FP == w.FP
switch {
case applied && h.Phase == PhaseRunning && h.Health == HealthOK:
m.State, m.Outcome = MotionSettled, OutcomeRunning
+3 -3
View File
@@ -6,7 +6,7 @@ import "testing"
// delivered on a node, read by the view (moving, settled, stuck, as its motionOf said them) and by the condition keeper
// (delivering, failed, ended). Wants and haves as the assigner and the node-engine write them (a refusal is written as phase failed at the prior fingerprint).
func TestMotionOf(t *testing.T) {
want := Want{FP: "fp-new", Composed: "sha256:new"}
want := Want{FP: "fp-new"}
at := func(fp, composed string, phase, health string, detail string) Have {
return Have{FP: fp, Composed: composed, Phase: phase, Health: health, Detail: detail}
}
@@ -34,8 +34,8 @@ func TestMotionOf(t *testing.T) {
h: at("fp-new", "sha256:new", "checking", "unknown", ""), has: true, state: MotionMoving},
{name: "running healthy at the want", w: want, wanted: true, h: at("fp-new", "sha256:new", PhaseRunning, HealthOK, ""), has: true,
state: MotionSettled, outcome: OutcomeRunning, ended: true},
{name: "running healthy at another composition", w: want, wanted: true, h: at("fp-new", "sha256:other", PhaseRunning, HealthOK, ""), has: true,
state: MotionMoving},
{name: "running healthy at the want, whatever composition the have names (H-A-78)", w: want, wanted: true,
h: at("fp-new", "sha256:other", PhaseRunning, HealthOK, ""), has: true, state: MotionSettled, outcome: OutcomeRunning, ended: true},
{name: "unhealthy at the want", w: want, wanted: true, h: at("fp-new", "sha256:new", PhaseRunning, HealthFailed, "exit 1"), has: true,
state: MotionStuck, outcome: OutcomeFailed, failed: true, ended: true},
{name: "its apply failed at the want", w: want, wanted: true, h: at("fp-new", "sha256:new", PhaseFailed, "unknown", "no image"), has: true,
+17 -1
View File
@@ -72,7 +72,12 @@ var untilTheJoin = []string{
// computesNot are the functions whose computation is one owner's alone (ADR 0593 §2, §7): the indexer computes a
// fingerprint, its named tree and a package's version; the node-engine composes.
var computesNot = []string{"SourceFingerprint", "SourceFingerprint2", "NamedTree", "MeshPackagesOf", "PackageVersionsOf",
"OtherPackages", "Compose", "CompositionsShadow", "JudgeMove", "Run"}
"OtherPackages", "Compose", "CompositionsShadow", "JudgeMove", "Run",
// The reading of a manifest's needs is the indexer's judge's alone (design 47 H2 H-A-622, H-A-639, H-A-671).
"ManifestNeeds", "ModuleNeeds", "BaselineManifestReads", "StatedManifestReads", "MissingManifestReads"}
// movedConsts are the constants that left mesh-sdk with the reader capabilities (design 47 H2 H-A-622, H-A-671).
var movedConsts = []string{"ReadDirectoryContentsOwner"}
// composesNot are the methods of the composition, the node-engine's alone since its rules moved there (ADR 0593 §7):
// mesh-sdk renders no declaration and refuses no composition.
@@ -196,6 +201,17 @@ func TestMeshSDKHoldsOnlyWhatEveryModuleShares(t *testing.T) {
}
}
for _, decl := range file.Decls {
if gen, isGen := decl.(*ast.GenDecl); isGen {
for _, spec := range gen.Specs {
if v, isValue := spec.(*ast.ValueSpec); isValue {
for _, name := range v.Names {
if slices.Contains(movedConsts, name.Name) {
t.Errorf("%s: %s is the node-engine's and the indexer's alone (design 47 H2 H-A-622, H-A-671)", path, name.Name)
}
}
}
}
}
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
+2
View File
@@ -5,6 +5,8 @@
// allow. It answers its seat's verbs through AnswerSeat alone (design 47 G, lead answer A-107). A sibling of stdio,
// which it imports only for stdio's pure types (ErrChanged, CodeChanged, StateEntry, EmitOptions); it never
// touches stdio's current, channel or live(), which stay the bundle's own way to the bus.
//
// Design 47 H1, proof 2: the SDK and its importer delivered in one merge call, 2026-11-21.
package process
import (
+10
View File
@@ -14,6 +14,9 @@ import (
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
// 1171/AC2: given an account file broker-<process id> in the controller's form {url, fingerprint, node,
@@ -268,6 +271,7 @@ func TestModuleAccountNamesAndDialOptions(t *testing.T) {
{"template stream subject", a.BusSubject("events", "snapshot.taken.person"), "mesh.bus.mesh-delivery-teller.events.snapshot.taken.person"},
{"another module's stream subject", ModuleStreamSubject("mesh-delivery-checker", "check"), "mesh.stream.mesh-delivery-checker.event.check"},
{"durable consumer", a.EventConsumerName(), "n1_mesh-delivery-teller"},
{"named durable consumer (H-A-90)", a.namedEventConsumerName("main"), "n1_mesh-delivery-teller_main"},
} {
if c.got != c.want {
t.Errorf("%s: got %q, want %q", c.name, c.got, c.want)
@@ -341,6 +345,12 @@ func subTheOwnBuildIsTheFingerprintTheProcessWasStartedWith(t *testing.T) {
t.Errorf("%s: the process's own build is not said at its start: %+v", name, said)
}
}
// Design 47 H2 §775, §781: Connect reads the module's kept-call pace from its settings, and refuses one that is no
// duration, naming it.
t.Setenv(stdio.SettingWord(busretry.PaceFirstSetting), "soon")
if _, err := Connect(Account{URL: "nats://127.0.0.1:1", User: "n1.m"}); err == nil || !strings.Contains(err.Error(), "kept-call-pace-first") {
t.Errorf("a pace that is no duration connected: %v", err)
}
}
// TestReadAccountYieldsEveryFieldAndToleratesClaims runs the tests of this package that were merged to keep the module within its test budget (design 47 G §419), each as a subtest.
+3
View File
@@ -20,6 +20,9 @@ type bindMsg struct {
func (m *bindMsg) Subject() string { return m.subject }
func (m *bindMsg) Data() []byte { return []byte(m.data) }
func (m *bindMsg) Ack() error { m.acked = true; return nil }
func (m *bindMsg) Metadata() (*jetstream.MsgMetadata, error) {
return &jetstream.MsgMetadata{Stream: "EVENTS"}, nil
}
// design 47 G §577: a process reaches the kept data its `requires` declares through its Binding: `show` of the seat
// mesh-broker at the start, asked again on `recreated` and `dropped` of the entry, and a wait naming the entry until it answers.
+120 -35
View File
@@ -10,6 +10,7 @@ import (
"github.com/nats-io/nats.go"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/busretry"
"git.novox.be/novox/mesh-sdk/go/calladdress"
@@ -52,34 +53,54 @@ func (c *Conn) CallOn(node, key string, body any) (json.RawMessage, error) {
}
// CallKept is Call for a call whose answer the caller keeps and which is safe to make again (a read, or a write the
// callee deduplicates): it is asked again through a transport fault, a timeout or no responders, whether or not the bus
// is blacked out, until it is answered or busretry.Bound has passed (novox/hq ADR 0668, extending ADR 0615 §6; issue
// 1966). A callee that restarts answers no one for seconds; Call fails that at once. The caller keeps a call still
// unanswered past the bound as a wait of its own, and makes it again on the callee's event or its consumer's bind.
// callee deduplicates): mesh-sdk's kept-call form (design 47 H2 §775), asked again through a transport fault, a timeout
// or no responders at the kept-call pace (busretry.KeptPace(), jittered), whether or not the bus is blacked out, until it
// is answered or busretry.Bound has passed (novox/hq ADR 0668, extending ADR 0615 §6; issue 1966). A refusal returns at
// once. A caller with an ask id and a bound of its own uses CallKeptAsk.
func (c *Conn) CallKept(key string, body any) (json.RawMessage, error) {
called, fallback, err := callSubjectsOn(key, "", c.callerToken())
if err != nil {
return nil, err
}
return c.callKeptOn(called, fallback, body)
return c.CallKeptAsk(KeptAsk{}, key, body)
}
// CallKeptOn is CallKept to the tool or seat verb of one named machine, as CallOn is Call's.
func (c *Conn) CallKeptOn(node, key string, body any) (json.RawMessage, error) {
return c.CallKeptAskOn(KeptAsk{}, node, key, body)
}
// KeptAsk is what a caller names of its kept call (design 47 H2 §775): the ask's id, which the call carries in the
// header stdio.AskHeader for the holder to take it once by (H-A-351), the caller's bound (zero is busretry.Bound), and its
// hook (nil gives none): told when the call has waited busretry.WaitSaid and once at its answer, as busretry.Kept's is
// (design 47 H2 H-A-708 (4), H-A-731).
type KeptAsk struct {
ID string
Bound time.Duration
Hook func(busretry.Waited)
}
// CallKeptAsk is CallKept carrying ask's id and stopping at ask's bound: past it the error is a *busretry.Unanswered
// naming every call's time and words.
func (c *Conn) CallKeptAsk(ask KeptAsk, key string, body any) (json.RawMessage, error) {
return c.callKeptAskOn(ask, "", key, body, nil)
}
// CallKeptAskOn is CallKeptAsk to the tool or seat verb of one named machine.
func (c *Conn) CallKeptAskOn(ask KeptAsk, node, key string, body any) (json.RawMessage, error) {
if err := calladdress.CheckNode(node); err != nil {
return nil, err
}
called, fallback, err := callSubjectsOn(key, node, c.callerToken())
if err != nil {
return nil, err
}
return c.callKeptOn(called, fallback, body)
return c.callKeptAskOn(ask, node, key, body, nil)
}
// CallKeptWhileOpen is CallKept for an ask the asker can close or replace: it is asked again only while open says its
// key is still open (design 47 G §351, §460).
func (c *Conn) CallKeptWhileOpen(open busretry.Open, key string, body any) (json.RawMessage, error) {
called, fallback, err := callSubjectsOn(key, "", c.callerToken())
if open.Open == nil {
return nil, fmt.Errorf("the call on %s: a kept call names its key's open function", key)
}
return c.callKeptAskOn(KeptAsk{}, "", key, body, &open)
}
func (c *Conn) callKeptAskOn(ask KeptAsk, node, key string, body any, open *busretry.Open) (json.RawMessage, error) {
called, fallback, err := callSubjectsOn(key, node, c.callerToken())
if err != nil {
return nil, err
}
@@ -87,35 +108,71 @@ func (c *Conn) CallKeptWhileOpen(open busretry.Open, key string, body any) (json
if err != nil {
return nil, err
}
return busretry.DoKept("the call on "+fallback, open, askBoth(c.request, called, fallback, data), nil)
return callKeptWith(keptOf(key, ask, open), c.requestAsking(ask.ID), called, fallback, data)
}
func (c *Conn) callKeptOn(called, fallback string, body any) (json.RawMessage, error) {
data, err := json.Marshal(body)
if err != nil {
return nil, err
// keptOf is the paced form's naming of a call on key: its seat and verb, or its module and tool.
func keptOf(key string, ask KeptAsk, open *busretry.Open) busretry.Kept {
k := busretry.Kept{Ask: ask.ID, Bound: ask.Bound, Open: open, Hook: ask.Hook}
if a, err := calladdress.Parse(key); err == nil {
k.Seat, k.Verb = a.Seat, a.Verb
if a.Seat == "" {
k.Seat, k.Verb = a.Module, a.Tool
}
}
return callKeptWith(c.request, called, fallback, data)
return k
}
// callKeptWith is callWith for a kept call: busretry.DoRepeatable with no blackout probe.
func callKeptWith(request func(string, []byte) (json.RawMessage, error), called, fallback string,
// callKeptWith is callWith for a kept call: busretry.DoPaced with no blackout probe.
func callKeptWith(k busretry.Kept, request func(string, []byte) (json.RawMessage, error), called, fallback string,
data []byte) (json.RawMessage, error) {
return busretry.DoRepeatable("the call on "+fallback, askBoth(request, called, fallback, data), nil)
ask := askBoth(request, called, fallback, data)
return busretry.DoPaced(k, func() (json.RawMessage, error) {
result, err := ask()
if err == nil {
// A holder's answer of the kind away is a transport fault (§776): called again at the pace.
if away := busretry.AwayIn(result); away != nil {
return result, away
}
}
return result, err
})
}
// askBoth asks called, then fallback when nothing answers it.
func askBoth(request func(string, []byte) (json.RawMessage, error), called, fallback string,
data []byte) func() (json.RawMessage, error) {
return func() (json.RawMessage, error) {
start := time.Now()
result, err := request(called, data)
if errors.Is(err, nats.ErrNoResponders) {
result, err = request(fallback, data)
if !errors.Is(err, nats.ErrNoResponders) {
return result, unansweredOn(err, start, called)
}
first := err
start2 := time.Now()
result, err = request(fallback, data)
if err != nil && !isAnswered(err) {
return result, fmt.Errorf("asked on %s (%v), then on %s, unanswered after %s: %w", called, first, fallback,
time.Since(start2).Round(time.Millisecond), err)
}
return result, err
}
}
// unansweredOn names the subject a transport fault was met on and how long it waited, so a log of a call nobody
// answered says where it was asked; a callee's answer keeps its own words.
func unansweredOn(err error, start time.Time, subject string) error {
if err == nil || isAnswered(err) {
return err
}
return fmt.Errorf("asked on %s, unanswered after %s: %w", subject, time.Since(start).Round(time.Millisecond), err)
}
func isAnswered(err error) bool {
var a *busretry.Answered
return errors.As(err, &a)
}
// callOn asks called, then fallback when nothing answers it; while the bus itself answers nothing (a user-list reload
// drops the account's imports for a few seconds, busretry) both are asked again, within busretry.Bound. A call nobody
// answers on a bus that answers is not asked again: its callee is not running. A call that may have been delivered (a
@@ -187,10 +244,28 @@ func callSubjectsOn(key, node, token string) (called, fallback string, err error
// request asks one subject once and reads its reply ({result, error, node}); a reply naming an error is
// the call's failure, not a transport one.
func (c *Conn) request(subject string, data []byte) (json.RawMessage, error) {
ctx, cancel := context.WithTimeout(context.Background(), CallTimeout)
defer cancel()
return c.requestAsk(subject, data, "")
}
// requestAsking is request carrying an ask's id in the header stdio.AskHeader (H-A-351); empty carries none.
func (c *Conn) requestAsking(ask string) func(string, []byte) (json.RawMessage, error) {
return func(subject string, data []byte) (json.RawMessage, error) { return c.requestAsk(subject, data, ask) }
}
// askMsg is the request a call publishes: its ask's id in stdio.AskHeader when it carries one (H-A-351).
func askMsg(subject string, data []byte, ask string) *nats.Msg {
req := nats.NewMsg(subject)
req.Data = data
if ask != "" {
req.Header.Set(stdio.AskHeader, ask)
}
return req
}
func (c *Conn) requestAsk(subject string, data []byte, ask string) (json.RawMessage, error) {
ctx, cancel := context.WithTimeout(context.Background(), CallTimeout)
defer cancel()
req := askMsg(subject, data, ask)
if strings.HasPrefix(subject, "mesh.seat.") {
// Every seat call says it waits for a held call's end; a verb that is not marked ignores it (lead answer A-244).
req.Header.Set(approval.WaitHeader, approval.WaitHeld)
@@ -199,20 +274,30 @@ func (c *Conn) request(subject string, data []byte) (json.RawMessage, error) {
if err != nil {
return nil, err
}
result, held, err := readReply(subject, msg.Data)
if err != nil {
return nil, err
}
if held != nil {
return c.awaitGated(subject, *held)
}
return result, nil
}
// readReply reads one reply ({result, error, error-kind, node, held}): a reply naming an error is the call's failure; a held
// call names its hold.
func readReply(subject string, data []byte) (json.RawMessage, *approval.Held, error) {
var r struct {
Result json.RawMessage `json:"result"`
Error string `json:"error"`
Node string `json:"node"`
Held *approval.Held `json:"held"`
}
if err := json.Unmarshal(msg.Data, &r); err != nil {
return nil, fmt.Errorf("%s answered something that is not a seat's answer: %w", subject, err)
if err := json.Unmarshal(data, &r); err != nil {
return nil, nil, fmt.Errorf("%s answered something that is not a seat's answer: %w", subject, err)
}
if r.Error != "" {
return nil, answered(r.Error)
return nil, nil, answered(r.Error)
}
if r.Held != nil {
return c.awaitGated(subject, *r.Held)
}
return r.Result, nil
return r.Result, r.Held, nil
}
+4 -4
View File
@@ -349,9 +349,9 @@ func TestAnswerSeatServesVerbsWithTheProvedCallerInOneQueueGroup(t *testing.T) {
if err != nil || r.Result["caller"] != "novox.mesh-delivery-builder" || r.Result["body"] != `{"x":1}` || r.Node != "novox" {
t.Fatalf("a caller-named call: %+v, %v", r, err)
}
// An unproven caller is refused before the handler runs (design 47 G §610; lead answers A-165, A-179, A-186).
// An unproven caller is admitted while the definition is read (A-434, A-435).
r, err = ask("mesh.seat.broker-seat.tool.ping")
if err != nil || r.Result != nil || !strings.Contains(r.Error, "broker-seat.ping takes no unproven caller") {
if err != nil || r.Result["caller"] != "" || r.Error != "" {
t.Fatalf("an unproven call: %+v, %v", r, err)
}
if _, err := ask("mesh.seat.broker-seat.call.ping.novox~mesh-delivery-builder"); err != nil {
@@ -359,8 +359,8 @@ func TestAnswerSeatServesVerbsWithTheProvedCallerInOneQueueGroup(t *testing.T) {
}
total := int32(0)
heard.Range(func(_, v any) bool { total += atomic.LoadInt32(v.(*int32)); return true })
if total != 2 {
t.Errorf("two proven calls were answered %d times in all, want once each (one queue group) and the unproven none", total)
if total != 3 {
t.Errorf("three calls were answered %d times in all, want once each (one queue group)", total)
}
if r, err = ask("mesh.seat.broker-seat.call.fail.x"); err != nil || r.Error != "refused: not yours" {
t.Errorf("a handler's error: %+v, %v", r, err)
+182 -7
View File
@@ -1,8 +1,11 @@
package process
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"strings"
"testing"
@@ -10,6 +13,9 @@ import (
"github.com/nats-io/nats.go"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
@@ -128,7 +134,7 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
}
var err error
if row.kept {
_, err = callKeptWith(request, "called", "fallback", nil)
_, err = callKeptWith(busretry.Kept{Seat: "s", Verb: "v"}, request, "called", "fallback", nil)
} else {
_, err = callWith(request, func() bool { return true }, "called", "fallback", nil)
}
@@ -136,6 +142,175 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
t.Errorf("%s: asked %d times (%v), want %d", row.name, asks, err, row.asks)
}
}
// Design 47 H2 §776: a holder's answer of the kind away is a transport fault, called again at the pace; so is a
// refusal of another kind is the caller's answer at once, and so is a reply of the withdrawn kind stopping
// (H-A-570 (3)).
for _, row := range []struct {
name string
answers []string
asks int
replies bool // the answers are the runner's raw replies, read as requestAsk reads them (readReply)
want string // the call's answer, where it is not the last answer
}{
{"away, then answered", []string{`{"error":"x","error-kind":"away","part":"the forge's store","words":"401"}`, `{"merged":true}`}, 2, false, ""},
// H-A-570 (3): a reply of the kind stopping, read from its bytes, is the callee's answer, asked once.
{"stopping withdrawn: answered at once", []string{`{"error":"git's trees was not taken: the tool runner is stopping","error-kind":"stopping"}`,
`{"result":{"merged":true}}`}, 1, true, ""},
{"refused: answered at once", []string{`{"error":"no","error-kind":"refused"}`}, 1, false, ""},
} {
asks := 0
request := func(string, []byte) (json.RawMessage, error) {
a := row.answers[min(asks, len(row.answers)-1)]
asks++
if row.replies {
result, _, err := readReply("mesh.seat.git.call.trees", []byte(a))
return result, err
}
return json.RawMessage(a), nil
}
want := row.want
if want == "" {
want = row.answers[len(row.answers)-1]
}
got, err := callKeptWith(busretry.Kept{Seat: "git", Verb: "merge-pull"}, request, "called", "fallback", nil)
if row.replies && row.want == "" {
if asks != row.asks || err == nil {
t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err)
}
continue
}
if asks != row.asks || err != nil || string(got) != want {
t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err)
}
}
// Design 47 H2 §775, H-A-351: a kept call carries its ask's id in the header, and a holder in a process reads it with
// AskOf while its handler runs; a call carrying none reads empty.
if m := askMsg("mesh.seat.mesh-builds.call.build", []byte(`{}`), "ask-9"); m.Header.Get(stdio.AskHeader) != "ask-9" {
t.Errorf("the ask's id is not in the header: %v", m.Header)
}
if m := askMsg("s", nil, ""); m.Header.Get(stdio.AskHeader) != "" {
t.Errorf("a call with no ask carries one: %v", m.Header)
}
c := &Conn{}
for _, ask := range []string{"ask-9", ""} {
msg := askMsg("mesh.seat.mesh-builds.tool.build", []byte(`{"x":1}`), ask)
read := "unread"
c.answerCall(msg, "mesh.seat.mesh-builds.tool.build", func(_ string, body json.RawMessage, _ bool) (any, *approval.Held, error) {
read = AskOf(body)
return nil, nil, nil
})
if read != ask || AskOf(json.RawMessage(msg.Data)) != "" {
t.Errorf("the holder read the ask %q, want %q, and none once its handler ended", read, ask)
}
}
// Design 47 H2 H-A-708 (2): a handler's `away` fault is answered as §776's `away` (error-kind, part, words) and read back
// by the caller as the transport fault; a plain refusal names no kind.
for _, row := range []struct {
err error
kind string
part string
fault bool
}{
{&busretry.Away{Part: "the trunk's revision 512", Words: "not read yet since 23:35:40"}, "away", "the trunk's revision 512", true},
{fmt.Errorf("reading: %w", &busretry.Away{Part: "the state seat-definitions", Words: "w"}), "away", "the state seat-definitions", true},
{errors.New("refused"), "", "", false},
} {
body := c.answerBody(askMsg("mesh.seat.mesh-catalog.tool.revision", []byte(`{}`), ""), "mesh.seat.mesh-catalog.tool.revision",
func(string, json.RawMessage, bool) (any, *approval.Held, error) { return nil, nil, row.err })
var got struct{ Kind, Part string }
var raw map[string]any
_ = json.Unmarshal(body, &raw)
if inner, ok := raw["result"].(map[string]any); ok {
raw = inner
}
got.Kind, _ = raw["error-kind"].(string)
got.Part, _ = raw["part"].(string)
// Read through the module's own reader, a kept call asks again on an away answer (once more here) and not on a refusal.
asks := 0
request := func(string, []byte) (json.RawMessage, error) {
asks++
if asks > 1 {
return json.RawMessage(`{"ok":true}`), nil
}
result, _, err := readReply("mesh.seat.mesh-catalog.tool.revision", body)
return result, err
}
restore := busretry.Waits(10*time.Second, time.Millisecond, 2*time.Millisecond)
_, kerr := callKeptWith(busretry.Kept{Seat: "mesh-catalog", Verb: "revision"}, request, "called", "fallback", nil)
restore()
if got.Kind != row.kind || got.Part != row.part || (asks == 2) != row.fault || (!row.fault && (asks != 1 || kerr == nil)) {
t.Errorf("%v answered %s, asked %d times (%v)", row.err, body, asks, kerr)
}
}
// Design 47 H2 H-A-731: the hook a caller gives on its KeptAsk reaches the kept-call form, and a caller giving none gives none.
var hooked []busretry.Waited
k := keptOf("seat:mesh-catalog.revision", KeptAsk{ID: "ask-3", Hook: func(w busretry.Waited) { hooked = append(hooked, w) }}, nil)
if k.Hook == nil || k.Seat != "mesh-catalog" || k.Verb != "revision" || k.Ask != "ask-3" {
t.Fatalf("keptOf gave %+v", k)
}
k.Hook(busretry.Waited{Seat: k.Seat, Verb: k.Verb, Ask: k.Ask, Answered: true})
if len(hooked) != 1 || !hooked[0].Answered || keptOf("seat:mesh-catalog.revision", KeptAsk{}, nil).Hook != nil {
t.Errorf("the hook on KeptAsk: told %+v", hooked)
}
// Design 47 H2 §775, H-A-405: a kept chunked call (CallChunksKept, CallFileKept) asks its verb through the kept-call
// form, carries its one ask id on every chunk's acknowledgement, and past its bound ends with the kept call's words.
send := buscalls.SeatChunks{Seat: "node-build-go", Verb: "output", Call: "c1"}
for _, row := range []struct {
name string
answer []error // per ask; the last repeats
bound time.Duration
asks int
chunks int64
unasked bool // ends unanswered past its bound
}{
{"no responders twice, then answered with two chunks", []error{nats.ErrNoResponders, nats.ErrNoResponders, nil}, 0, 3, 2, false},
{"answered at once with three chunks", []error{nil}, 0, 1, 3, false},
{"no responders past its bound", []error{nats.ErrNoResponders}, time.Nanosecond, 2, 0, true},
} {
asks := 0
request := func(string, []byte) (json.RawMessage, error) {
e := row.answer[min(asks, len(row.answer)-1)]
asks++
return json.RawMessage(fmt.Sprintf(`{"chunks":%d}`, row.chunks)), e
}
chunks := make(chan *nats.Msg, row.chunks)
var want bytes.Buffer
for n := int64(1); n <= row.chunks; n++ {
data := []byte(fmt.Sprintf("part %d;", n))
want.Write(data)
body, _ := json.Marshal(buscalls.SeatChunk{N: n, Of: row.chunks, Data: data})
chunks <- &nats.Msg{Subject: send.Chunk(n), Data: body}
}
var acks []string
ack := func(m *nats.Msg) error {
acks = append(acks, m.Subject+" "+m.Header.Get(stdio.AskHeader))
return nil
}
ask := KeptAsk{ID: "ask-7", Bound: row.bound}
asking := func() (json.RawMessage, error) {
return callKeptWith(keptOf("seat:node-build-go.output@ace", ask, nil), request, "called", "fallback", nil)
}
var got bytes.Buffer
_, err := receiveChunks(context.Background(), "seat:node-build-go.output@ace", send, chunks, ask.ID, asking, nil, ack, &got)
var unanswered *busretry.Unanswered
if row.unasked != errors.As(err, &unanswered) || asks != row.asks || (!row.unasked && err != nil) {
t.Errorf("%s: asked %d times (want %d), %v", row.name, asks, row.asks, err)
}
if row.unasked && (unanswered.Ask != "ask-7" || !strings.Contains(err.Error(), "node-build-go.output (ask ask-7) unanswered within its bound")) {
t.Errorf("%s: ended with %v, not the kept call's words", row.name, err)
}
if got.String() != want.String() || int64(len(acks)) != row.chunks {
t.Errorf("%s: received %q and acknowledged %d chunks, want %q and %d", row.name, got.String(), len(acks), want.String(), row.chunks)
}
for n, a := range acks {
if a != send.Ack(int64(n+1))+" ask-7" {
t.Errorf("%s: acknowledgement %d is %q, carrying not the ask's id in its header", row.name, n+1, a)
}
}
}
if _, err := (&Conn{}).CallChunksKept(context.Background(), KeptAsk{}, "seat:node-build-go.output", "c1", nil, nil, &bytes.Buffer{}); err == nil {
t.Error("a kept chunked call naming no ask id was made")
}
}
// A-107: AnswerSeat reads the caller from a call's last token (dots written `~`), "" for anything that is not a
@@ -169,12 +344,12 @@ func TestUserOfTokenAndAnswerSeatRefusals(t *testing.T) {
def func() (seatdef.Definition, bool)
says string
}{
{"an unproven caller", "", defined, "takes no unproven caller"},
{"the definition unread", "novox.mesh-recovery", func() (seatdef.Definition, bool) { return seatdef.Definition{}, false }, "not yet read"},
{"a verb the definition does not name", "novox.mesh-recovery", func() (seatdef.Definition, bool) { return seatdef.Definition{Seat: "seat"}, true }, "names no verb v"},
{"a verb open to none", "novox.mesh-recovery", func() (seatdef.Definition, bool) {
return seatdef.Definition{Seat: "seat", Verbs: []seatdef.Verb{{Name: "v", Callers: &seatdef.Callers{List: []string{}}}}}, true
}, "open to no caller"},
{"an unproven caller", "", defined, ""}, // a read definition admits every caller (the operator, 2026-11-15)
{"the definition unread", "novox.mesh-recovery", func() (seatdef.Definition, bool) { return seatdef.Definition{}, false }, ""},
{"the definition unread, the console's account (A-435)", "novox.node-tools", func() (seatdef.Definition, bool) { return seatdef.Definition{}, false }, "may need approval"},
{"the definition unread, a person (A-435)", "person.jo", func() (seatdef.Definition, bool) { return seatdef.Definition{}, false }, "may need approval"},
{"the definition unread, an unproven caller (A-435)", "", func() (seatdef.Definition, bool) { return seatdef.Definition{}, false }, "may need approval"},
{"a verb the definition does not name", "novox.mesh-recovery", func() (seatdef.Definition, bool) { return seatdef.Definition{Seat: "seat"}, true }, ""},
{"a marked verb with no gate (§677)", "novox.mesh-recovery", func() (seatdef.Definition, bool) {
return seatdef.Definition{Seat: "seat", Verbs: []seatdef.Verb{{Name: "v", NeedsApproval: true}}}, true
}, "through no gate"},
+80 -16
View File
@@ -22,24 +22,77 @@ import (
// is taken), then receives the number of chunks the answer's member `chunks` names, in order, acknowledging each, into w.
// It answers the verb's answer. A chunk that does not come within buscalls.SeatAckWithin, or ctx ending, ends the receive.
func (c *Conn) CallChunks(ctx context.Context, key, call string, body any, accept func(answer json.RawMessage) error, w io.Writer) (json.RawMessage, error) {
a, err := calladdress.Parse(key)
return c.callChunks(ctx, key, call, "", func() (json.RawMessage, error) { return c.Call(key, body) }, accept, w)
}
// CallChunksKept is CallChunks made as a kept call (design 47 H2 §775; H-A-405): the verb is asked through the kept-call
// form (busretry.DoPaced: called again at the kept-call pace on a transport fault, ADR 0664 §1's classes, the call's own
// deadline and the kind away; one journal line per seat at the first fault, then at most once a minute), carrying ask's id
// in the header stdio.AskHeader on the call and on every chunk's acknowledgement, and stopping at ask's bound with the
// words CallKeptAsk gives (a *busretry.Unanswered naming every call). A kept chunked call carries an ask id: one naming
// none is refused before anything is published.
func (c *Conn) CallChunksKept(ctx context.Context, ask KeptAsk, key, call string, body any, accept func(answer json.RawMessage) error,
w io.Writer) (json.RawMessage, error) {
if ask.ID == "" {
return nil, fmt.Errorf("the kept call of %s names no ask id", key)
}
called, fallback, err := callSubjectsOn(key, "", c.callerToken())
if err != nil {
return nil, err
}
if a.Seat == "" {
return nil, fmt.Errorf("%q names no seat verb, so it sends no chunks", key)
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
if call == "" {
return nil, fmt.Errorf("the call of %s names no call token for its chunks", key)
asking := func() (json.RawMessage, error) {
return callKeptWith(keptOf(key, ask, nil), c.requestAsking(ask.ID), called, fallback, data)
}
return c.callChunks(ctx, key, call, ask.ID, asking, accept, w)
}
// callChunks hears the chunks of call before it asks through asking, then receives them (receiveChunks), acknowledging
// each with ask's id in stdio.AskHeader when it carries one.
func (c *Conn) callChunks(ctx context.Context, key, call, ask string, asking func() (json.RawMessage, error),
accept func(answer json.RawMessage) error, w io.Writer) (json.RawMessage, error) {
send, err := chunksOf(key, call)
if err != nil {
return nil, err
}
send := buscalls.SeatChunks{Seat: a.Seat, Verb: a.Verb, Call: call}
chunks := make(chan *nats.Msg, 4)
sub, err := c.nc.ChanSubscribe(send.Chunks(), chunks)
if err != nil {
return nil, fmt.Errorf("the chunks of %s cannot be heard: %w", key, err)
}
defer func() { _ = sub.Unsubscribe() }()
answer, err := c.Call(key, body)
ack := func(m *nats.Msg) error {
_, err := c.nc.RequestMsg(m, buscalls.SeatAckWithin)
return err
}
return receiveChunks(ctx, key, send, chunks, ask, asking, accept, ack, w)
}
// chunksOf is the chunks of call of the seat verb key names; a key naming no seat verb, or no call, is refused.
func chunksOf(key, call string) (buscalls.SeatChunks, error) {
a, err := calladdress.Parse(key)
if err != nil {
return buscalls.SeatChunks{}, err
}
if a.Seat == "" {
return buscalls.SeatChunks{}, fmt.Errorf("%q names no seat verb, so it sends no chunks", key)
}
if call == "" {
return buscalls.SeatChunks{}, fmt.Errorf("the call of %s names no call token for its chunks", key)
}
return buscalls.SeatChunks{Seat: a.Seat, Verb: a.Verb, Call: call}, nil
}
// receiveChunks asks through asking, hands its answer to accept, then receives the number of chunks the answer's member
// `chunks` names from chunks, in order, acknowledging each through ack with a message carrying ask's id in
// stdio.AskHeader (none when empty), into w.
func receiveChunks(ctx context.Context, key string, send buscalls.SeatChunks, chunks <-chan *nats.Msg, ask string,
asking func() (json.RawMessage, error), accept func(answer json.RawMessage) error, ack func(*nats.Msg) error,
w io.Writer) (json.RawMessage, error) {
answer, err := asking()
if err != nil {
return nil, err
}
@@ -66,11 +119,8 @@ func (c *Conn) CallChunks(ctx context.Context, key, call string, body any, accep
return "", nil, ctx.Err()
}
}
ack := func(subject string) error {
_, err := c.nc.Request(subject, []byte("{}"), buscalls.SeatAckWithin)
return err
}
if _, err := send.Receive(count.Chunks, next, ack, w); err != nil {
acked := func(subject string) error { return ack(askMsg(subject, []byte("{}"), ask)) }
if _, err := send.Receive(count.Chunks, next, acked, w); err != nil {
return answer, fmt.Errorf("the answer of %s: %w", key, err)
}
return answer, nil
@@ -80,18 +130,32 @@ func (c *Conn) CallChunks(ctx context.Context, key, call string, body any, accep
// G A-249, A-253): the verb's answer with the whole file added as its member `file` (base64), none when no chunk was sent. The
// call token is body's member `call`.
func (c *Conn) CallFile(key string, body any) (json.RawMessage, error) {
call := callOf(body)
var file bytes.Buffer
answer, err := c.CallChunks(context.Background(), key, call, body, nil, &file)
answer, err := c.CallChunks(context.Background(), key, callOf(body), body, nil, &file)
if err != nil {
return nil, err
}
return withFile(key, answer, file.Bytes())
}
// CallFileKept is CallFile made as a kept call, as CallChunksKept is CallChunks's (design 47 H2 §775; H-A-405).
func (c *Conn) CallFileKept(ask KeptAsk, key string, body any) (json.RawMessage, error) {
var file bytes.Buffer
answer, err := c.CallChunksKept(context.Background(), ask, key, callOf(body), body, nil, &file)
if err != nil {
return nil, err
}
return withFile(key, answer, file.Bytes())
}
// withFile is a chunked verb's answer with file added as its member `file` (base64), none when file is empty.
func withFile(key string, answer json.RawMessage, file []byte) (json.RawMessage, error) {
var whole map[string]any
if err := json.Unmarshal(answer, &whole); err != nil {
return nil, fmt.Errorf("%s answered what is no object: %w", key, err)
}
if file.Len() > 0 {
whole["file"] = base64.StdEncoding.EncodeToString(file.Bytes())
if len(file) > 0 {
whole["file"] = base64.StdEncoding.EncodeToString(file)
}
return json.Marshal(whole)
}
+6
View File
@@ -12,6 +12,9 @@ import (
"sync"
"github.com/nats-io/nats.go"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
// Conn is one process's own connection to the bus (novox/hq ADR 0436 clause 4): dialled with the account
@@ -54,6 +57,9 @@ var refusedPublish = regexp.MustCompile(`(?i)Publish to "(\S+)"`)
// at once.
func Connect(account Account, opts ...nats.Option) (*Conn, error) {
OwnBuild()
if err := busretry.ReadPace(stdio.SettingDuration); err != nil {
return nil, fmt.Errorf("the kept-call pace of the process account %s: %w", account.User, err)
}
c := &Conn{account: account, pending: map[string]map[uint64]context.CancelCauseFunc{}}
nc, err := nats.Connect(account.URL, c.options(opts)...)
if err != nil {
+23
View File
@@ -3,9 +3,11 @@ package process
import (
"context"
"encoding/json"
"errors"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/busretry"
"github.com/nats-io/nats.go/jetstream"
)
@@ -65,3 +67,24 @@ func TestConsumerLedgerKeepsTheFactsAfterEachMessage(t *testing.T) {
t.Errorf("after both applied: %+v, want sequence 8 and none unacknowledged", f)
}
}
// Design 47 H2 §775: the held pull waits after an error at the kept-call pace, doubling to its most, and says each kind of
// error once until a message arrives.
func TestHeldPullPacesAtTheKeptCallPaceAndSaysEachKindOnce(t *testing.T) {
pace := busretry.Pace{First: time.Second, Max: 3 * time.Second}
var f pullFaults
a, b := errors.New("a"), errors.New("b")
for i, row := range []struct {
err error
say bool
wait time.Duration
}{{a, true, time.Second}, {a, false, 2 * time.Second}, {b, true, 3 * time.Second}, {a, false, 3 * time.Second}} {
if say, wait := f.next(row.err, pace); say != row.say || wait != row.wait {
t.Errorf("error %d: said %v, waited %v; want %v, %v", i, say, wait, row.say, row.wait)
}
}
f.ended()
if say, wait := f.next(a, pace); !say || wait != time.Second {
t.Errorf("after a message: said %v, waited %v", say, wait)
}
}
+384
View File
@@ -0,0 +1,384 @@
package process
import (
"fmt"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The event hub's settings, read by the runtime under these names at their defaults when not composed (design 47 H2 H-A-683
// (1), H-A-695 (2), (5)): how many keys are handled at once, and how many messages the hub holds at most.
const (
EventsAtOnceSetting = "events-at-once"
EventsWaitingSetting = "events-waiting"
SlowEventSetting = "slow-event"
EventOverrunSetting = "event-overrun"
defaultSlowEvent = 100 * time.Millisecond
defaultEventOverrun = 60 * time.Second
leastEventOverrun = time.Second
mostEventOverrun = time.Hour
defaultEventsAtOnce = 8
defaultEventsWaiting = 100
mostEventsAtOnce = 64
mostEventsWaiting = 1000
sharedEventKey = "\x00shared"
keyedEventKeyPrefix = "k:"
)
// EventKey is the key a pattern's events are handled under: a function of a message's subject and body (design 47 H2 H-A-683
// (1)). One key's events are handled one at a time in the order heard, different keys side by side.
type EventKey func(subject string, body []byte) string
// Handling is one handling of an event that runs past the setting event-overrun: its subject, its key and since when it ran
// (design 47 H2 H-A-683 (3), H-A-697 (3)).
type Handling struct {
Subject, Key string
Since time.Time
}
// settingCount reads the setting key as a whole number from lo to hi, def when none is composed; one that is no such number
// is an error naming the setting.
func settingCount(key string, def, lo, hi int) (int, error) {
v, ok := stdio.Setting(key)
if v = strings.TrimSpace(v); !ok || v == "" {
return def, nil
}
n, err := strconv.Atoi(v)
if err != nil || n < lo || n > hi {
return 0, fmt.Errorf("the setting %s (%s) holds %q, which is not a whole number from %d to %d", key, stdio.SettingWord(key), v, lo, hi)
}
return n, nil
}
// heldEvent is one message the hub took, held until its handler ends.
type heldEvent struct {
msg jetstream.Msg
handle func(jetstream.Msg)
feed *eventFeed
id string // the stream and its sequence: what a delivery again is told by
key string
subject string
again bool // a delivery again was said already
}
// eventHold is every message the hub holds, across its durables: one queue per key, the keys handled at once bounded.
type eventHold struct {
logf func(string, ...any)
tick ticker
// now and after are the clock and the timer of the timed handlings, a test's to replace: after calls f once d has passed and
// answers what cancels it.
now func() time.Time
after func(d time.Duration, f func()) (cancel func())
// overrun is told the handlings past the bound of event-overrun, oldest first, each time one passes it or ends.
overrun func(past []Handling)
toldMu sync.Mutex // the hook of the overrun is told one at a time
mu sync.Mutex
room *sync.Cond // signalled when a message leaves
atOnce int
bound int
slow time.Duration
over time.Duration
running map[*heldEvent]*timed
queues map[string][]*heldEvent
active map[string]bool
waiting []string // keys with events waiting and no handling running, in the order heard
ids map[string]*heldEvent
atBound bool
stopped bool
}
func newEventHold(logf func(string, ...any), tick ticker) *eventHold {
e := &eventHold{logf: logf, tick: tick, atOnce: defaultEventsAtOnce, bound: defaultEventsWaiting, now: time.Now,
slow: defaultSlowEvent, over: defaultEventOverrun, running: map[*heldEvent]*timed{},
after: func(d time.Duration, f func()) func() { t := time.AfterFunc(d, f); return func() { t.Stop() } },
queues: map[string][]*heldEvent{}, active: map[string]bool{}, ids: map[string]*heldEvent{}}
e.room = sync.NewCond(&e.mu)
return e
}
// settle reads the hub's settings, an error naming one that is none.
func (e *eventHold) settle() error {
atOnce, err := settingCount(EventsAtOnceSetting, defaultEventsAtOnce, 1, mostEventsAtOnce)
if err != nil {
return err
}
bound, err := settingCount(EventsWaitingSetting, defaultEventsWaiting, 1, mostEventsWaiting)
if err != nil {
return err
}
slow, err := stdio.SettingDuration(SlowEventSetting, defaultSlowEvent)
if err != nil {
return err
}
over, err := stdio.SettingDuration(EventOverrunSetting, defaultEventOverrun)
if err != nil {
return err
}
if over < leastEventOverrun || over > mostEventOverrun {
return fmt.Errorf("the setting %s (%s) holds %s, which is not from %s to %s", EventOverrunSetting, stdio.SettingWord(EventOverrunSetting),
over, leastEventOverrun, mostEventOverrun)
}
e.mu.Lock()
e.atOnce, e.bound, e.slow, e.over, e.stopped = atOnce, bound, slow, over, false
e.mu.Unlock()
return nil
}
// take holds a message under its key and hands it on when its key's turn comes. A delivery again of a held message is
// handed to nobody and said once. At the bound of messages held it waits for room, so the hub pulls no more (H-A-695 (2)).
func (e *eventHold) take(h *heldEvent) {
e.mu.Lock()
if first, again := e.ids[h.id]; again && h.id != "" {
if !first.again {
first.again = true
e.logf("events: %s (%s) was given again while it is held, its handling not ended: handed to no handler", h.subject, h.id)
}
e.mu.Unlock()
return
}
if h.id != "" {
e.ids[h.id] = h
}
e.queues[h.key] = append(e.queues[h.key], h)
switch {
case e.active[h.key] || len(e.queues[h.key]) > 1:
// its key is running or already waits its turn: it follows in order
case len(e.active) < e.atOnce:
e.active[h.key] = true
go e.run(h.key)
default:
e.waiting = append(e.waiting, h.key)
}
e.refill()
for len(e.ids) >= e.bound && !e.stopped {
if !e.atBound {
e.atBound = true
e.logf("events: the hub holds %d messages, its bound: it pulls no more until one ends; the key holding most is %s", len(e.ids), e.mostKey())
}
e.room.Wait()
}
e.mu.Unlock()
}
// mostKey names the key that holds most messages; the caller holds mu.
func (e *eventHold) mostKey() string {
best, n := "", 0
keys := make([]string, 0, len(e.queues))
for k := range e.queues {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
held := len(e.queues[k])
if e.active[k] {
held++
}
if held > n {
best, n = k, held
}
}
return displayKey(best)
}
func displayKey(k string) string {
if k == sharedEventKey {
return "the shared key"
}
return strings.TrimPrefix(k, keyedEventKeyPrefix)
}
// refill starts the waiting keys while there are handlings to spare; the caller holds mu.
func (e *eventHold) refill() {
for len(e.waiting) > 0 && len(e.active) < e.atOnce {
k := e.waiting[0]
e.waiting = e.waiting[1:]
e.active[k] = true
go e.run(k)
}
}
// run handles one key's events in the order heard, until it has none; then its turn goes to the next key waiting.
func (e *eventHold) run(key string) {
for {
e.mu.Lock()
q := e.queues[key]
if len(q) == 0 {
delete(e.queues, key)
delete(e.active, key)
e.refill()
e.mu.Unlock()
return
}
h := q[0]
e.queues[key] = q[1:]
e.mu.Unlock()
e.handle(h)
e.mu.Lock()
if h.id != "" {
delete(e.ids, h.id)
}
if e.atBound && len(e.ids) < e.bound {
e.atBound = false
e.logf("events: the hub holds %d messages, below its bound: it pulls again", len(e.ids))
}
e.room.Broadcast()
e.mu.Unlock()
}
}
// timed is one handling that runs: when it began, and whether it is past event-overrun.
type timed struct {
since time.Time
past bool
cancel func()
}
// handle runs a message's handler, timed: past slow-event the journal says how long it took and which key's it was; while it
// runs past event-overrun the hook of the overrun is told at once, and again when it ends (design 47 H2 H-A-683 (3), H-A-697
// (3)). A panic in it is said and the message is left unacknowledged, so the bus gives it again.
func (e *eventHold) handle(h *heldEvent) {
e.mu.Lock()
t := &timed{since: e.now()}
over, slow := e.over, e.slow
e.running[h] = t
e.mu.Unlock()
t.cancel = e.after(over, func() {
e.mu.Lock()
if _, ok := e.running[h]; !ok {
e.mu.Unlock()
return
}
t.past = true
e.mu.Unlock()
e.told()
})
defer func() {
if r := recover(); r != nil {
e.logf("events: the handler of %s failed: %v; the message is not acknowledged", h.subject, r)
}
t.cancel()
e.mu.Lock()
delete(e.running, h)
took := e.now().Sub(t.since)
wasPast := t.past
e.mu.Unlock()
if took > slow {
e.logf("events: the event %s (key %s) took %s to handle, over %s", h.subject, displayKey(h.key), took.Round(time.Millisecond), slow)
}
if wasPast {
e.told()
}
}()
h.handle(h.msg)
}
// pastLocked are the handlings past the bound, the one begun first first; the caller holds mu.
func (e *eventHold) pastLocked() []Handling {
var out []Handling
for h, t := range e.running {
if t.past {
out = append(out, Handling{Subject: h.subject, Key: displayKey(h.key), Since: t.since})
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Since.Equal(out[j].Since) {
return out[i].Since.Before(out[j].Since)
}
return out[i].Subject < out[j].Subject
})
return out
}
// told hands the handlings past the bound, as they are now, to the hook; one call at a time, each reading the handlings after the
// one before it ended, so the hook's last word is the true one.
func (e *eventHold) told() {
if e.overrun == nil {
return
}
e.toldMu.Lock()
defer e.toldMu.Unlock()
e.mu.Lock()
past := e.pastLocked()
e.mu.Unlock()
e.overrun(past)
}
// waitRoom waits while the hub holds as many messages as events-waiting allows, so the pull takes no more.
func (e *eventHold) waitRoom() {
e.mu.Lock()
for len(e.ids) >= e.bound && !e.stopped {
e.room.Wait()
}
e.mu.Unlock()
}
// stop releases a part waiting for room.
func (e *eventHold) stop() {
e.mu.Lock()
e.stopped = true
e.room.Broadcast()
e.mu.Unlock()
}
// heldOf are the messages held that came by feed.
func (e *eventHold) heldOf(f *eventFeed) []jetstream.Msg {
e.mu.Lock()
defer e.mu.Unlock()
var out []jetstream.Msg
for _, h := range e.ids {
if h.feed == f {
out = append(out, h.msg)
}
}
return out
}
// eventFeed is one durable the hub pulls: its one ticker says in progress for every message of it the hub holds, at every
// third of its ack wait (design 47 H2 H-A-695 (1)), read once at the bind as H-A-281 has it.
type eventFeed struct {
hold *eventHold
done chan struct{}
once sync.Once
}
func newEventFeed(h *eventHold) *eventFeed { return &eventFeed{hold: h, done: make(chan struct{})} }
// start begins the feed's ticker for a durable of this ack wait; none when it is unknown.
func (f *eventFeed) start(ackWait time.Duration) {
every := ackWait / 3
if every <= 0 {
return
}
f.once.Do(func() {
ticks, stop := f.hold.tick(every)
go func() {
defer stop()
for {
select {
case <-f.done:
return
case <-ticks:
for _, m := range f.hold.heldOf(f) {
_ = m.InProgress()
}
}
}
}()
})
}
func (f *eventFeed) end() {
select {
case <-f.done:
default:
close(f.done)
}
}
+550 -80
View File
@@ -2,12 +2,19 @@ package process
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/buscompose"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// EventHub is the one pull of a module's durable consumer on the shared events stream (novox/hq ADR 0635 §5): a module
@@ -16,7 +23,8 @@ import (
// handler whose pattern it matches. A message no handler takes is acknowledged and said, never left to be redelivered.
// The hub never makes the stream or the consumer: they are the controller's, and a bus without them is an error of Start.
//
// Register every handler, then Start once: a message heard before its handler is registered would be taken by none.
// Register every handler, then Start once: a message heard before its handler is registered would be taken by none, so a handler
// registered after Start is refused, naming its pattern.
type EventHub struct {
logf func(string, ...any)
@@ -24,11 +32,47 @@ type EventHub struct {
routes []hubRoute
cons jetstream.ConsumeContext
bound []func(created time.Time)
// allHeard are told each time every registered pattern comes to be heard (OnAllHeard).
allHeard []func()
// started is Start's; gen numbers it; bus, cred and ctx are what its wakes bind with; stopWake ends the wake.
started bool
process string
gen int
bus hubBus
cred Account
ctx context.Context
stopWake func()
// heard are the durables bound, by stream; why is what each stream not bound is said to lack.
heard map[string]jetstream.ConsumeContext
why map[string]string
// eventsSubjects are EVENTS' own, read once; unheardNow the patterns not heard as of the last pass; allTold says
// OnAllHeard was told for the present state.
eventsSubjects []string
unheardNow []Unheard
allTold bool
// late are the patterns refused after Start (they stay unheard); lastTold the list the hooks were last told, and toldOnce says
// a pass told them (Start's, whatever the list).
late []Unheard
lastTold []Unheard
toldOnce bool
passed bool
unheardTo []func([]Unheard)
passMu sync.Mutex
// unhandled are told each subject no handler took (OnUnhandled).
unhandled []func(subject string)
// overruns are told the handlings past event-overrun (OnOverrun).
overruns []func(past []Handling)
// held is every message the hub took and has not seen end, across its durables (event_hold.go); feeds are the durables'
// tickers. tick is the clock of the tickers, a test's to replace.
held *eventHold
feeds []*eventFeed
tick ticker
}
type hubRoute struct {
pattern string
handle func(jetstream.Msg)
key EventKey
}
// NewEventHub is a hub saying through logf (nil says nothing).
@@ -36,24 +80,73 @@ func NewEventHub(logf func(string, ...any)) *EventHub {
if logf == nil {
logf = func(string, ...any) {}
}
return &EventHub{logf: logf}
h := &EventHub{logf: logf, tick: realTicker}
h.held = newEventHold(logf, func(d time.Duration) (<-chan time.Time, func()) { return h.tick(d) })
h.held.overrun = func(past []Handling) {
h.mu.RLock()
told := h.overruns
h.mu.RUnlock()
for _, f := range told {
f(past)
}
}
return h
}
// Handle registers handle for the subjects matching pattern (`*` one token, `>` the rest). The handler acknowledges
// the message itself. A pattern that overlaps one registered (one matches every subject of the other) is refused,
// so a message always has one taker.
// so a message always has one taker. Its events are handled under one shared key, one at a time (HandleByKey).
func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg)) error {
return h.handleByKey(pattern, handle, nil)
}
// HandleByKey is Handle for a pattern whose events are held by key (design 47 H2 H-A-683 (1), H-A-737 (1)): key is a function of
// a message's subject and body. One key's events are handled one at a time in the order heard and the events of different keys
// side by side, at most `events-at-once` keys at once; every pattern given no key (Handle) hands its events under one shared key.
func (h *EventHub) HandleByKey(pattern string, key EventKey, handle func(jetstream.Msg)) error {
if key == nil {
return fmt.Errorf("the events %q are given no key function", pattern)
}
return h.handleByKey(pattern, handle, key)
}
func (h *EventHub) handleByKey(pattern string, handle func(jetstream.Msg), keyOf EventKey) error {
if pattern == "" || handle == nil {
return fmt.Errorf("an event handler needs a subject pattern and a handler")
}
h.mu.Lock()
defer h.mu.Unlock()
for _, r := range h.routes {
if subjectsOverlap(r.pattern, pattern) {
h.mu.Unlock()
return fmt.Errorf("the events %q overlap %q, already handled: a message has one taker", pattern, r.pattern)
}
}
h.routes = append(h.routes, hubRoute{pattern, handle})
if h.started {
// An event no registered pattern covers (its first adopt) is not heard; one an earlier handler takes is.
err := fmt.Errorf("the events %q are registered after Start: register every handler, then Start once (design 47 H2b §836 3.)", pattern)
late := Unheard{pattern, "", "registered after Start"}
if !slices.Contains(h.late, late) {
h.late = append(h.late, late)
}
h.mu.Unlock()
h.announce()
return err
}
defer h.mu.Unlock()
h.routes = append(h.routes, hubRoute{pattern, handle, keyOf})
return nil
}
// ForProcess names the process whose own durable the hub binds, on EVENTS and on every kept seat event's stream, in place of the
// module's: `<node>_<module>_<process>`, such as the bus module's keeper's `<node>_nats_keeper` (design 47 H2b §836 5., H-A-876).
// Every other behaviour of Start is unchanged. Call it before Start; after it the call is refused.
func (h *EventHub) ForProcess(process string) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.started {
return fmt.Errorf("the hub is started: name its process before Start")
}
h.process = process
return nil
}
@@ -68,6 +161,42 @@ func (h *EventHub) OnBound(f func(created time.Time)) {
h.mu.Unlock()
}
// OnUnhandled registers f, told the subject of each message no handler takes, after the hub said it in the log and
// acknowledged it: the module's process reader counts them in its finding `event-unhandled` (design 47 H, H-A-166,
// H-A-169).
func (h *EventHub) OnUnhandled(f func(subject string)) {
h.mu.Lock()
h.unhandled = append(h.unhandled, f)
h.mu.Unlock()
}
// OnOverrun registers f, told the handlings of events that run past the setting event-overrun (1 second to 1 hour, 60 seconds by
// default), the one begun first first, each time a handling passes that bound while it still runs and each time one that was
// past it ends: an empty list says none is past it. The process reader wires it into the module's finding `event-overrun`
// (design 47 H2 H-A-683 (3), H-A-697).
func (h *EventHub) OnOverrun(f func(past []Handling)) {
h.mu.Lock()
h.overruns = append(h.overruns, f)
h.mu.Unlock()
}
// OnAllHeard registers f, told each time the hub comes to hear every registered pattern: at Start, or at the bind that completes
// them (design 47 H2b §836 1.). A part that does what waits on its events being live does it there. Register before Start.
func (h *EventHub) OnAllHeard(f func()) {
h.mu.Lock()
h.allHeard = append(h.allHeard, f)
h.mu.Unlock()
}
// OnUnheard registers f, told the patterns the hub does not hear, each with its stream and why, whenever that list changes, Start
// included, and an empty list once every pattern is heard, as OnOverrun is told (design 47 H2b §836 4.): the process reader raises
// the finding `events-unheard` from it. A pattern refused after Start is in the list. Register before Start.
func (h *EventHub) OnUnheard(f func(unheard []Unheard)) {
h.mu.Lock()
h.unheardTo = append(h.unheardTo, f)
h.mu.Unlock()
}
// Patterns are the registered subject patterns, in order.
func (h *EventHub) Patterns() []string {
h.mu.RLock()
@@ -79,97 +208,438 @@ func (h *EventHub) Patterns() []string {
return out
}
// Start binds the module's durable on the shared events stream and pulls it; a call after a start that took does
// nothing. It makes no stream and no consumer: a consumer the bus does not hold yet is the error of this call, and a
// later call (the module's next change of membership) binds it, so a part is not lost for the bus's order.
// durablesComposedSubject is where the seat `mesh-grants` says it composed a module's durables, for the module on its node:
// the hub binds again each stream it has not bound (design 47 H2b §836 2., H-A-835). The subject is the seat's definition's
// alone: the hub reads no body.
func durablesComposedSubject(cred Account) string {
return seatdef.EventSubject(buscompose.GrantsModule, "durables-composed") + "." + cred.Node + "." + cred.Module
}
// Start binds the module's durable `<node>_<module>` (the process's own, `<node>_<module>_<process>`, when ForProcess named one) on the shared events stream and on every kept seat event's stream
// (`SEAT_<seat>_<event>`) that carries a registered pattern, and pulls them (design 47 H2b §836 1.); a call after a start does
// nothing. It makes no stream and no consumer. A durable the bus does not hold yet, or refuses, is no error of this call and
// is not waited for on a timer: it is said (the journal) and bound when the seat `mesh-grants` says it composed the module's
// durables, and at the bus connection's reconnect (§836 2.), and OnAllHeard is told when every pattern is heard. Start's nil says
// the hub is started, never that anything is heard: what waits on a stream being heard goes in OnAllHeard, and the patterns not
// heard are told to OnUnheard (design 47 H2b §836 1., 4., H-A-877).
func (h *EventHub) Start(ctx context.Context, js jetstream.JetStream, cred Account) error {
h.mu.RLock()
process := h.process
h.mu.RUnlock()
return h.start(ctx, natsHubBus{js: js, cred: cred, process: process}, cred)
}
// hubBus is what the hub asks of the bus: the kept streams, the subjects of EVENTS, the pulls of its durables, and the wakes.
type hubBus interface {
streamNames(ctx context.Context) ([]string, error)
streamSubjects(ctx context.Context, stream string) ([]string, error)
// hearEvents pulls the module's durable on EVENTS, held by feed; created is when the bus made the durable.
hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
// wake calls f at each message on subject (a plain subscription); stop ends it.
wake(subject string, f func()) (stop func(), err error)
// reconnected calls f at each reconnect of the bus connection.
reconnected(f func())
}
type natsHubBus struct {
js jetstream.JetStream
cred Account
process string
}
func (b natsHubBus) streamNames(ctx context.Context) ([]string, error) {
names := b.js.StreamNames(ctx)
var out []string
for name := range names.Name() {
out = append(out, name)
}
return out, names.Err()
}
func (b natsHubBus) streamSubjects(ctx context.Context, stream string) ([]string, error) {
s, err := b.js.Stream(ctx, stream)
if err != nil {
return nil, err
}
return s.CachedInfo().Config.Subjects, nil
}
func (b natsHubBus) hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
cons, err := b.js.Consumer(ctx, EventsStream, b.cred.durableOf(b.process))
if err != nil {
return nil, time.Time{}, err
}
if info := cons.CachedInfo(); info != nil {
feed.start(info.Config.AckWait)
}
cc, err := hearHeld(cons, callerOutside(), feed.hold, handle, logf)
if err != nil {
return nil, time.Time{}, err
}
info, err := cons.Info(ctx)
if err != nil {
logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", b.cred.durableOf(b.process), EventsStream, err)
return cc, time.Time{}, nil
}
return cc, info.Created.UTC(), nil
}
func (b natsHubBus) hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
cc, err := b.cred.HearSeatEvents(ctx, b.js, stream, handle, logf, heldBy(feed), forProcess(b.process))
if err != nil {
return nil, time.Time{}, err
}
cons, err := b.js.Consumer(ctx, stream, b.cred.durableOf(b.process))
if err != nil {
return cc, time.Time{}, nil
}
info, err := cons.Info(ctx)
if err != nil {
return cc, time.Time{}, nil
}
return cc, info.Created.UTC(), nil
}
func (b natsHubBus) wake(subject string, f func()) (func(), error) {
sub, err := b.js.Conn().Subscribe(subject, func(*nats.Msg) { f() })
if err != nil {
return nil, err
}
return func() { _ = sub.Unsubscribe() }, nil
}
func (b natsHubBus) reconnected(f func()) {
nc := b.js.Conn()
before := nc.Opts.ReconnectedCB
nc.SetReconnectHandler(func(c *nats.Conn) {
if before != nil {
before(c)
}
f()
})
}
// Unheard is a registered pattern the hub does not hear: the stream that should carry it ("" when none does) and why (design 47
// H2b §836 4.): "no stream carries it", "not composed", "refused: <the bus's words>" or "registered after Start".
type Unheard struct{ Pattern, Stream, Why string }
func (h *EventHub) start(ctx context.Context, bus hubBus, cred Account) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.cons != nil {
if h.started {
h.mu.Unlock()
return nil
}
cons, err := cred.EventConsumer(ctx, js, EventsStream)
if err == nil {
h.cons, err = HearEvents(cons, h.hear, h.logf)
}
h.started = true
h.gen++
gen := h.gen
h.bus, h.cred, h.ctx = bus, cred, ctx
h.mu.Unlock()
rebind := func() { h.rebind(gen) }
// The wake is made before the first bind, so a durable composed while a bind fails is heard (§836 2.).
stop, err := bus.wake(durablesComposedSubject(cred), rebind)
if err != nil {
return fmt.Errorf("the consumer %s on %s is not heard: %w", cred.EventConsumerName(), EventsStream, err)
}
if info, ierr := cons.Info(ctx); ierr != nil {
h.logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", cred.EventConsumerName(), EventsStream, ierr)
h.logf("events: the grants part's word of the module's durables is not heard (%v): a stream not bound is bound at the bus connection's reconnect or the module's next start", err)
} else {
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", cred.EventConsumerName(), EventsStream, info.Created.UTC().Format(time.RFC3339))
for _, f := range h.bound {
f(info.Created.UTC())
}
h.mu.Lock()
h.stopWake = stop
h.mu.Unlock()
}
bus.reconnected(rebind)
h.pass(ctx, bus, cred)
return nil
}
// StartUntilBound is Start that does not give up: when the module's consumer is not there yet it returns that error at
// once, and tries again on a goroutine of its own, after each wait, until it binds or ctx ends; then live is called (nil
// calls nothing), so a part that needs the events path live does what it does only then. wait returns false to stop
// trying (nil waits five seconds or for ctx). The bus makes the consumer when the module's account is composed, which
// says nothing a module can hear before the consumer exists, so the retry is a wait on that, bounded by ctx.
func (h *EventHub) StartUntilBound(ctx context.Context, js jetstream.JetStream, cred Account, wait func(context.Context) bool, live func()) error {
err := h.Start(ctx, js, cred)
if err == nil {
if live != nil {
live()
}
return nil
}
if wait == nil {
wait = func(ctx context.Context) bool {
t := time.NewTimer(5 * time.Second)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
}
go func() {
for wait(ctx) && ctx.Err() == nil {
if h.Start(ctx, js, cred) == nil {
if live != nil {
live()
}
return
}
}
}()
return err
}
// Stop ends the pull.
func (h *EventHub) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
if h.cons != nil {
h.cons.Stop()
h.cons = nil
}
}
func (h *EventHub) hear(m jetstream.Msg) {
// rebind is a pass of the start numbered gen, at a wake or a reconnect; one of an ended or later start does nothing.
func (h *EventHub) rebind(gen int) {
h.mu.RLock()
var take func(jetstream.Msg)
for _, r := range h.routes {
if subjectMatches(r.pattern, m.Subject()) {
take = r.handle
break
ok, ctx, bus, cred := h.started && h.gen == gen, h.ctx, h.bus, h.cred
h.mu.RUnlock()
if ok && ctx.Err() == nil {
h.pass(ctx, bus, cred)
}
}
// pass binds every durable not bound that a registered pattern needs (EVENTS' always), says OnBound at each bind and OnAllHeard
// when the hub comes to hear every registered pattern.
func (h *EventHub) pass(ctx context.Context, bus hubBus, cred Account) {
h.passMu.Lock()
defer h.passMu.Unlock()
patterns := h.Patterns()
names, nerr := bus.streamNames(ctx)
if nerr != nil {
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard now", nerr)
}
h.mu.RLock()
eventsSubjects := h.eventsSubjects
h.mu.RUnlock()
if eventsSubjects == nil {
subjects, err := bus.streamSubjects(ctx, EventsStream)
if err != nil {
h.logf("events: the subjects of %s are not read (%v): every pattern no kept stream takes is taken to be carried by it", EventsStream, err)
} else {
h.mu.Lock()
h.eventsSubjects = subjects
h.mu.Unlock()
eventsSubjects = subjects
}
}
// Each pattern is carried by every kept stream whose subjects take it, else by EVENTS (H-A-834).
carriers := make([][]string, len(patterns))
need := map[string]bool{}
for i, p := range patterns {
for _, stream := range names {
seat, event, ok := keptSeatEvent(stream)
if !ok {
continue
}
subject := seatdef.EventSubject(seat, event)
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
carriers[i] = append(carriers[i], stream)
need[stream] = true
}
}
if len(carriers[i]) == 0 && h.eventsTake(eventsSubjects, p) {
carriers[i] = []string{EventsStream}
}
}
if !h.hasKept(EventsStream) {
h.bindOne(ctx, bus, cred, EventsStream)
}
var streams []string
for stream := range need {
streams = append(streams, stream)
}
slices.Sort(streams)
for _, stream := range streams {
if !h.hasKept(stream) {
h.bindOne(ctx, bus, cred, stream)
}
}
var not []Unheard
h.mu.RLock()
for i, p := range patterns {
if len(carriers[i]) == 0 {
why := "no stream carries it"
if nerr != nil {
why = fmt.Sprintf("the streams are not listed (%v)", nerr)
}
not = append(not, Unheard{p, "", why})
}
for _, stream := range carriers[i] {
if _, bound := h.heard[stream]; !bound {
not = append(not, Unheard{p, stream, h.why[stream]})
}
}
}
h.mu.RUnlock()
if take == nil {
h.logf("events: %s is taken by no handler of this module, acknowledged", m.Subject())
_ = m.Ack()
h.mu.Lock()
h.unheardNow, h.passed = not, true
all := len(not) == 0
tell := all && !h.allTold
h.allTold = all
told := h.allHeard
h.mu.Unlock()
h.announce()
if tell {
for _, f := range told {
f()
}
}
}
// announce says the patterns not heard (the journal, one line each) and tells each OnUnheard hook, when the list differs from the one
// told last or none was told yet (Start's pass tells even an empty list: a restarted program clears what an earlier process raised).
// Nothing is told before a pass has made the list.
func (h *EventHub) announce() {
h.mu.Lock()
if !h.passed {
h.mu.Unlock()
return
}
take(m)
list := append(slices.Clone(h.unheardNow), h.late...)
if h.toldOnce && slices.Equal(list, h.lastTold) {
h.mu.Unlock()
return
}
h.toldOnce, h.lastTold = true, list
hooks := slices.Clone(h.unheardTo)
h.mu.Unlock()
for _, u := range list {
switch {
case u.Stream == "":
h.logf("events: the pattern %s is not heard: %s", u.Pattern, u.Why)
default:
h.logf("events: the pattern %s is not heard on %s: %s", u.Pattern, u.Stream, u.Why)
}
}
for _, f := range hooks {
f(slices.Clone(list))
}
}
// eventsTake says whether EVENTS carries pattern: some subject of its own overlaps it (all of them, when they are not read).
func (h *EventHub) eventsTake(subjects []string, pattern string) bool {
if subjects == nil {
return true
}
for _, s := range subjects {
if subjectsOverlap(s, pattern) {
return true
}
}
return false
}
func (h *EventHub) hasKept(stream string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
_, ok := h.heard[stream]
return ok
}
// bindOne binds the module's durable on stream (EventsStream or a kept seat event's) and says each bind to OnBound; what it
// cannot is said and kept as the stream's reason.
func (h *EventHub) bindOne(ctx context.Context, bus hubBus, cred Account, stream string) {
h.mu.Lock()
feed := h.newFeed()
h.mu.Unlock()
var (
cc jetstream.ConsumeContext
created time.Time
err error
)
if stream == EventsStream {
if err = h.held.settle(); err == nil {
cc, created, err = bus.hearEvents(ctx, feed, h.hearOn(feed), h.logf)
}
} else {
cc, created, err = bus.hearKept(ctx, stream, feed, h.hearOn(feed), h.logf)
}
if err != nil {
feed.end()
why := "refused: " + err.Error()
if errors.Is(err, jetstream.ErrConsumerNotFound) {
why = "not composed: the bus holds no durable " + h.durable(cred) + " on it"
}
h.mu.Lock()
if h.why == nil {
h.why = map[string]string{}
}
changed := h.why[stream] != why
h.why[stream] = why
h.mu.Unlock()
if changed {
h.logf("events: the consumer %s on %s is not heard: %s (%v)", h.durable(cred), stream, why, err)
}
return
}
h.mu.Lock()
if h.heard == nil {
h.heard = map[string]jetstream.ConsumeContext{}
}
h.heard[stream] = cc
delete(h.why, stream)
if stream == EventsStream {
h.cons = cc
}
bound := h.bound
h.mu.Unlock()
if created.IsZero() {
h.logf("events: the consumer %s on %s is heard", h.durable(cred), stream)
return
}
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", h.durable(cred), stream, created.Format(time.RFC3339))
for _, f := range bound {
f(created)
}
}
// durable is the name of the durable the hub binds: the module's, or its process's (ForProcess).
func (h *EventHub) durable(cred Account) string {
h.mu.RLock()
defer h.mu.RUnlock()
return cred.durableOf(h.process)
}
// Stop ends the pulls and the wake.
func (h *EventHub) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
for _, cc := range h.heard {
cc.Stop()
}
h.heard, h.why, h.cons = nil, nil, nil
if h.stopWake != nil {
h.stopWake()
h.stopWake = nil
}
h.started, h.allTold, h.unheardNow = false, false, nil
h.passed, h.toldOnce, h.lastTold, h.late = false, false, nil, nil
for _, f := range h.feeds {
f.end()
}
h.feeds = nil
h.held.stop()
}
// newFeed makes the ticker of one durable the hub pulls (event_hold.go).
func (h *EventHub) newFeed() *eventFeed {
f := newEventFeed(h.held)
h.feeds = append(h.feeds, f)
return f
}
// keptSeatEvent is the seat and the event a kept seat event's stream carries, from its name `SEAT_<seat>_<event>` (seatdef.KeptStream):
// a seat's and an event's names hold no underscore.
func keptSeatEvent(stream string) (seat, event string, ok bool) {
rest, isKept := strings.CutPrefix(stream, seatdef.KeptStreamPrefix)
if !isKept {
return "", "", false
}
seat, event, ok = strings.Cut(rest, "_")
if !ok || seat == "" || event == "" || strings.Contains(event, "_") {
return "", "", false
}
return seat, event, true
}
// hear is hearOn for a message with no durable of its own to say in progress on.
func (h *EventHub) hear(m jetstream.Msg) { h.hearOn(nil)(m) }
// hearOn is the handler of one durable's messages: it finds the message's taker and key, and holds it for them (event_hold.go),
// so the pull goes on while a handler runs and every message held is said in progress by the durable's ticker. A message no
// handler takes is acknowledged and said, never held.
func (h *EventHub) hearOn(feed *eventFeed) func(jetstream.Msg) {
return func(m jetstream.Msg) {
h.mu.RLock()
var route *hubRoute
for i := range h.routes {
if subjectMatches(h.routes[i].pattern, m.Subject()) {
route = &h.routes[i]
break
}
}
told := h.unhandled
h.mu.RUnlock()
if route == nil {
h.logf("events: %s is taken by no handler of this module, acknowledged", m.Subject())
_ = m.Ack()
for _, f := range told {
f(m.Subject())
}
return
}
key := sharedEventKey
if route.key != nil {
key = keyedEventKeyPrefix + route.key(m.Subject(), m.Data())
}
id := ""
if md, err := m.Metadata(); err == nil {
id = md.Stream + "/" + strconv.FormatUint(md.Sequence.Stream, 10)
}
h.held.take(&heldEvent{msg: m, handle: route.handle, feed: feed, id: id, key: key, subject: m.Subject()})
}
}
// subjectMatches says whether subject is one the pattern (`*` one token, `>` the rest) names.
+298 -21
View File
@@ -16,8 +16,8 @@ import (
"git.novox.be/novox/mesh-sdk/go/testbus"
)
// A module whose consumer the bus makes after the module started is not lost for that order: the hub tries again after
// each wait and calls live once it is bound (the checker's "until it starts again" hole).
// A module whose durable the bus makes after the module started is not lost for that order: the hub binds it when the
// grants part says it composed the module's durables, and tells OnAllHeard.
func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
@@ -35,37 +35,44 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
}
cred := process.Account{Node: "n1", Module: "late"}
hub := process.NewEventHub(t.Logf)
waits, live := make(chan chan bool), make(chan struct{}, 1)
wait := func(ctx context.Context) bool {
step := make(chan bool)
select {
case waits <- step:
case <-ctx.Done():
return false
}
return <-step
live := make(chan struct{}, 4)
hub.OnAllHeard(func() { live <- struct{}{} })
if err := hub.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
if err := hub.StartUntilBound(ctx, js, cred, wait, func() { live <- struct{}{} }); err == nil {
t.Fatal("no consumer was there, and the start said nothing")
// Start with no durable composed says nothing is live and arms no timer; the grants part's word that it composed the
// module's durables binds it (design 47 H2b §836 2.).
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
select {
case <-live:
t.Fatal("live before the consumer was there")
default:
default: // Start's pass is synchronous: OnAllHeard is told inside it or not at all
}
step := <-waits
step <- true // tried again: still no consumer
step = <-waits
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
step <- true
if err := nc.Publish("mesh.seat.mesh-grants.event.durables-composed.n1.late", []byte("{}")); err != nil {
t.Fatal(err)
}
select {
case <-live:
case <-ctx.Done():
t.Fatal("the consumer was made and the hub never said it is live")
t.Fatal("the durables were composed and the hub never said it is live")
}
// H-A-90: a durable named for a suffix is bound beside the module's own.
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName() + "_main", AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
named, err := cred.NamedEventConsumer(ctx, js, process.EventsStream, "main")
if err != nil || named.CachedInfo().Name != cred.EventConsumerName()+"_main" {
t.Fatalf("the named consumer: %v, %v", named, err)
}
if _, err := cred.NamedEventConsumer(ctx, js, process.EventsStream, "other"); err == nil {
t.Fatal("a named consumer nobody made was bound")
}
hub.Stop()
}
// W1.12: a module hears a seat's event kept last per subject on its own stream through its durable, made by the maker
@@ -113,7 +120,6 @@ func subAModuleHearsASeatEventKeptOnItsOwnStream(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer cc.Stop()
heard := map[string]bool{}
for len(heard) < 2 {
select {
@@ -141,6 +147,79 @@ func subAModuleHearsASeatEventKeptOnItsOwnStream(t *testing.T) {
case <-ctx.Done():
t.Fatal("the durable was not followed after the read")
}
// Design 47 H2b §836 1., H-A-855: the hub's Start alone binds the kept stream the registered pattern needs and tells OnAllHeard, with
// no StartKept; a handler of the kept seat event then hears it.
cc.Stop()
hub := process.NewEventHub(t.Logf)
allHeard := make(chan struct{}, 1)
hub.OnAllHeard(func() { allHeard <- struct{}{} })
hubHeard := make(chan string, 4)
if err := hub.Handle("mesh.seat.node-engine.event.running.>", func(m jetstream.Msg) { hubHeard <- string(m.Data()); _ = m.Ack() }); err != nil {
t.Fatal(err)
}
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
select {
case <-allHeard:
case <-ctx.Done():
t.Fatal("the hub's start bound the kept stream and said nothing")
}
if _, err := js.Publish(ctx, "mesh.seat.node-engine.event.running.n1.mesh-tools", []byte("fp5")); err != nil {
t.Fatal(err)
}
for heard := ""; heard != "fp5"; {
select {
case heard = <-hubHeard:
case <-ctx.Done():
t.Fatal("the hub's start did not hear the kept seat event")
}
}
// Design 47 H2b §836 5., H-A-876: a hub for a process binds the durable of the process's own name, with the module's gone.
hub.Stop()
if err := js.DeleteConsumer(ctx, kept, cred.EventConsumerName()); err != nil {
t.Fatal(err)
}
own := cred.SeatEventConsumerConfig(subjects, true)
own.Durable = cred.EventConsumerName() + "_keeper"
own.DeliverPolicy = jetstream.DeliverNewPolicy
if _, err := js.CreateOrUpdateConsumer(ctx, kept, own); err != nil {
t.Fatal(err)
}
keeper := process.NewEventHub(t.Logf)
keeperHeard := make(chan string, 4)
keeperAll := make(chan struct{}, 1)
keeper.OnAllHeard(func() { keeperAll <- struct{}{} })
if err := keeper.Handle("mesh.seat.node-engine.event.running.>", func(m jetstream.Msg) { keeperHeard <- string(m.Data()); _ = m.Ack() }); err != nil {
t.Fatal(err)
}
if err := keeper.ForProcess("keeper"); err != nil {
t.Fatal(err)
}
if err := keeper.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer keeper.Stop()
if keeper.ForProcess("other") == nil {
t.Error("a process was named after Start")
}
select {
case <-keeperAll:
case <-ctx.Done():
t.Fatal("the hub for a process did not bind its own durable")
}
if _, err := js.Publish(ctx, "mesh.seat.node-engine.event.running.n1.mesh-tools", []byte("fp6")); err != nil {
t.Fatal(err)
}
// the start read of a stream kept last per subject hands the last of each subject first
for got := ""; got != "fp6"; {
select {
case got = <-keeperHeard:
case <-ctx.Done():
t.Fatal("the process's durable heard nothing")
}
}
}
// A-181: a module hears another module's own stream kept last per subject (a manifest's `streams` entry with `last-per-subject`) as
@@ -278,4 +357,202 @@ func TestTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
t.Run("AModuleHearsASeatEventKeptOnItsOwnStream", subAModuleHearsASeatEventKeptOnItsOwnStream)
t.Run("AModuleHearsAnotherModulesStreamKeptLastPerSubject", subAModuleHearsAnotherModulesStreamKeptLastPerSubject)
t.Run("AModuleHearsAStreamKeptByAgeFromItsFirstMessage", subAModuleHearsAStreamKeptByAgeFromItsFirstMessage)
t.Run("AProcessPullsADurableOnce", subAProcessPullsADurableOnce)
t.Run("TheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled", subTheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled)
t.Run("TheHubDeliversNothingBeyondEventsWaiting", subTheHubDeliversNothingBeyondEventsWaiting)
}
// Design 47 H2 H-A-695 (2), H-A-733: with events-waiting messages held the bus delivers no more to the hub: past several ack
// waits exactly that many are pending, none is given again, and the rest are delivered once room is made.
func subTheHubDeliversNothingBeyondEventsWaiting(t *testing.T) {
t.Setenv("MESH_CONFIG_EVENTS_WAITING", "2")
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
t.Fatal(err)
}
defer nc.Close()
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: process.EventsStream, Subjects: []string{"mesh.mod.*.event.>"}}); err != nil {
t.Fatal(err)
}
cred := process.Account{Node: "n1", Module: "bounded"}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(),
AckPolicy: jetstream.AckExplicitPolicy, AckWait: 600 * time.Millisecond}); err != nil {
t.Fatal(err)
}
hub := process.NewEventHub(t.Logf)
release, handled := make(chan struct{}), make(chan string, 8)
if err := hub.Handle("mesh.mod.m.event.>", func(m jetstream.Msg) { <-release; _ = m.Ack(); handled <- m.Subject() }); err != nil {
t.Fatal(err)
}
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
for i := range 5 {
if _, err := js.Publish(ctx, "mesh.mod.m.event."+string(rune('a'+i)), nil); err != nil {
t.Fatal(err)
}
}
<-time.After(2 * time.Second) // more than three ack waits with the hub full
cons, err := cred.EventConsumer(ctx, js, process.EventsStream)
if err != nil {
t.Fatal(err)
}
if info, err := cons.Info(ctx); err != nil || info.NumAckPending != 2 || info.NumRedelivered != 0 || info.NumPending != 3 {
t.Fatalf("the full hub's durable holds %+v (%v): want 2 pending acks, 3 not delivered, none given again", info, err)
}
close(release)
for range 5 {
<-handled
}
}
// Design 47 H2 H-A-683 (1), H-A-695 (1): with the durable's ack wait shortened and one key's handling blocked past several ack
// waits, no message is given again (the durable's redelivered count stays 0) and another key's events are handled.
func subTheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
t.Fatal(err)
}
defer nc.Close()
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: process.EventsStream, Subjects: []string{"mesh.mod.*.event.>"}}); err != nil {
t.Fatal(err)
}
cred := process.Account{Node: "n1", Module: "keyed"}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(),
AckPolicy: jetstream.AckExplicitPolicy, AckWait: 600 * time.Millisecond}); err != nil {
t.Fatal(err)
}
hub := process.NewEventHub(t.Logf)
release, handled := make(chan struct{}), make(chan string, 4)
if err := hub.HandleByKey("mesh.mod.m.event.>", func(subject string, _ []byte) string { return subject }, func(m jetstream.Msg) {
if strings.HasSuffix(m.Subject(), ".slow") {
<-release
}
_ = m.Ack()
handled <- m.Subject()
}); err != nil {
t.Fatal(err)
}
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
for _, name := range []string{"slow", "fast"} {
if _, err := js.Publish(ctx, "mesh.mod.m.event."+name, nil); err != nil {
t.Fatal(err)
}
}
if got := <-handled; !strings.HasSuffix(got, ".fast") {
t.Fatalf("the first event handled was %s: the blocked key held the other back", got)
}
// Five ack waits pass with the slow key's handling blocked: the hub says its message in progress, so the bus gives none again.
held := time.After(3 * time.Second)
<-held
cons, err := cred.EventConsumer(ctx, js, process.EventsStream)
if err != nil {
t.Fatal(err)
}
if info, err := cons.Info(ctx); err != nil || info.NumRedelivered != 0 || info.NumAckPending != 1 {
t.Fatalf("after five ack waits the durable holds %+v (%v): want one pending and none given again", info, err)
}
close(release)
if got := <-handled; !strings.HasSuffix(got, ".slow") {
t.Fatalf("handled %s", got)
}
}
// A second pull loop on a durable this process already pulls is refused at bind time, naming the durable and both
// binders, and the durable is pulled again once the first loop stopped (design 47 H, H-A-196).
func subAProcessPullsADurableOnce(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
t.Fatal(err)
}
defer nc.Close()
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: process.EventsStream, Subjects: []string{"mesh.mod.*.event.>"}}); err != nil {
t.Fatal(err)
}
cred := process.Account{Node: "n1", Module: "twice"}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
cons, err := cred.EventConsumer(ctx, js, process.EventsStream)
if err != nil {
t.Fatal(err)
}
first, err := process.HearEvents(cons, func(m jetstream.Msg) { _ = m.Ack() }, t.Logf)
if err != nil {
t.Fatal(err)
}
_, err = process.ConsumeOnce(cons, "the follower", func(jetstream.Msg) {})
if err == nil {
t.Fatal("a second pull loop on the durable the process pulls was taken")
}
for _, want := range []string{cred.EventConsumerName(), process.EventsStream, "subAProcessPullsADurableOnce", "the follower"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("the refusal %q does not name %q", err, want)
}
}
if _, err := process.HearEvents(cons, func(jetstream.Msg) {}, t.Logf); err == nil {
t.Fatal("a second HearEvents on the durable the process pulls was taken")
}
first.Stop()
again, err := process.HearEvents(cons, func(m jetstream.Msg) { _ = m.Ack() }, t.Logf)
if err != nil {
t.Fatalf("the durable is not pulled again after its loop stopped: %v", err)
}
// A drain keeps the claim until the loop ended: a bind during it is refused, one after it (Closed) is taken.
held := make(chan struct{})
slow, err := cred.EventConsumer(ctx, js, process.EventsStream)
if err != nil {
t.Fatal(err)
}
again.Stop()
handed := make(chan struct{}, 2)
draining, err := process.ConsumeOnce(slow, "the drained loop", func(m jetstream.Msg) { handed <- struct{}{}; <-held; _ = m.Ack() })
if err != nil {
t.Fatal(err)
}
if _, err := js.Publish(ctx, "mesh.mod.alpha.event.happened", []byte(`{}`)); err != nil {
t.Fatal(err)
}
if _, err := js.Publish(ctx, "mesh.mod.alpha.event.happened", []byte(`{}`)); err != nil {
t.Fatal(err)
}
select {
case <-handed:
case <-ctx.Done():
t.Fatal("the drained loop was handed no message")
}
draining.Drain()
if _, err := process.ConsumeOnce(slow, "a bind during the drain", func(jetstream.Msg) {}); err == nil ||
!strings.Contains(err.Error(), "the drained loop") {
t.Fatalf("a bind while the drain runs was not refused naming the draining loop: %v", err)
}
close(held)
<-draining.Closed()
after, err := process.ConsumeOnce(slow, "a bind after the drain", func(m jetstream.Msg) { _ = m.Ack() })
if err != nil {
t.Fatalf("a bind after the drain ended was refused: %v", err)
}
after.Stop()
}
+589
View File
@@ -2,8 +2,14 @@ package process
import (
"context"
"errors"
"fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/nats-io/nats.go/jetstream"
)
@@ -26,6 +32,7 @@ func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) {
t.Errorf("overlap(%s, %s) = %v", c.a, c.b, got)
}
}
t.Run("TheHubStartBindsEveryPatternAndSaysWhenAllAreHeard", subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard)
h := NewEventHub(nil)
nop := func(jetstream.Msg) {}
if err := h.Handle("mesh.mod.p.event.>", nop); err != nil {
@@ -37,6 +44,15 @@ func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) {
if err := h.Handle("mesh.mod.q.event.>", nop); err != nil {
t.Fatal(err)
}
// H-A-169: a message no handler takes is acknowledged and told to each OnUnhandled hook, with its subject; one taken is not.
var told []string
h.OnUnhandled(func(subject string) { told = append(told, subject) })
taken, lost := &bindMsg{subject: "mesh.mod.q.event.x"}, &bindMsg{subject: "mesh.seat.s.event.nobody"}
h.hear(taken)
h.hear(lost)
if !lost.acked || len(told) != 1 || told[0] != "mesh.seat.s.event.nobody" {
t.Errorf("the unhandled message: acked %v, told %v", lost.acked, told)
}
// W1.12: a seat's event kept in a stream of its own is heard on one bus name and one durable, the maker's and the
// hearer's alike; an event kept last per subject is delivered from the last of each subject. The name is the
// contract's Stream<E> as it stands (seatdef.KeptStream), never made again here: a dotted or unprefixed name is
@@ -57,3 +73,576 @@ func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) {
t.Errorf("the durable on a stream kept with an age starts from its first message, got %v", cfg.DeliverPolicy)
}
}
type pullConsumer struct {
jetstream.Consumer
info *jetstream.ConsumerInfo
handle jetstream.MessageHandler
options []jetstream.PullConsumeOpt
}
func (c *pullConsumer) CachedInfo() *jetstream.ConsumerInfo { return c.info }
func (c *pullConsumer) Consume(handle jetstream.MessageHandler, opts ...jetstream.PullConsumeOpt) (jetstream.ConsumeContext, error) {
c.handle, c.options = handle, opts
return &pullContext{closed: make(chan struct{})}, nil
}
type pullContext struct {
jetstream.ConsumeContext
closed chan struct{}
}
func (p *pullContext) Stop() { close(p.closed) }
func (p *pullContext) Closed() <-chan struct{} { return p.closed }
type slowMsg struct {
jetstream.Msg
said chan struct{}
}
func (m *slowMsg) InProgress() error { m.said <- struct{}{}; return nil }
// H-A-281: the hub pulls at most twenty messages per pull, and says in progress for a message whose handler runs past a
// third of the consumer's ack wait, at each third until it returns; a handler that returns first says nothing.
func TestTheHubPullsSmallBatchesAndKeepsSlowHandlersAlive(t *testing.T) {
cons := &pullConsumer{info: &jetstream.ConsumerInfo{Config: jetstream.ConsumerConfig{AckWait: 30 * time.Second}}}
ticks := make(chan time.Time)
var every time.Duration
stopped := 0
tick := func(d time.Duration) (<-chan time.Time, func()) { every = d; return ticks, func() { stopped++ } }
var handled func(jetstream.Msg)
cc, err := hearEvents(cons, "the test", func(m jetstream.Msg) { handled(m) }, t.Logf, tick)
if err != nil {
t.Fatal(err)
}
defer cc.Stop()
pulls := 0
for _, o := range cons.options {
if n, ok := o.(jetstream.PullMaxMessages); ok {
pulls = int(n)
}
}
if pulls != 20 {
t.Errorf("the hub pulls %d messages per pull, want 20 (0: the bus client's default of 500)", pulls)
}
slow := &slowMsg{said: make(chan struct{}, 4)}
handled = func(jetstream.Msg) {
for range 2 { // two thirds of the ack wait pass while the handler runs
select {
case ticks <- time.Time{}:
case <-time.After(5 * time.Second):
t.Error("no ticker runs while the handler runs")
return
}
select {
case <-slow.said:
case <-time.After(5 * time.Second):
t.Error("a handler running past a third of the ack wait said no in progress")
return
}
}
}
cons.handle(slow)
if every != 10*time.Second || stopped != 1 {
t.Errorf("in progress every %v (want 10s, a third of the ack wait), ticker stopped %d times (want 1)", every, stopped)
}
fast := &slowMsg{said: make(chan struct{}, 1)}
handled = func(jetstream.Msg) {}
cons.handle(fast)
if len(fast.said) != 0 {
t.Error("a handler that returned before a third of the ack wait said in progress")
}
}
// seqMsg is a message of the stream EVENTS at a sequence, counting what is said of it.
type seqMsg struct {
jetstream.Msg
subject string
seq uint64
mu sync.Mutex
progress int
acked bool
}
func (m *seqMsg) Subject() string { return m.subject }
func (m *seqMsg) Data() []byte { return nil }
func (m *seqMsg) Ack() error { m.mu.Lock(); m.acked = true; m.mu.Unlock(); return nil }
func (m *seqMsg) InProgress() error {
m.mu.Lock()
m.progress++
m.mu.Unlock()
return nil
}
func (m *seqMsg) Metadata() (*jetstream.MsgMetadata, error) {
return &jetstream.MsgMetadata{Stream: "EVENTS", Sequence: jetstream.SequencePair{Stream: m.seq}}, nil
}
func (m *seqMsg) said() int { m.mu.Lock(); defer m.mu.Unlock(); return m.progress }
// Design 47 H2 H-A-683 (1), H-A-695 (1) to (3): the hub hands events by key, one key's events one at a time in the order heard
// and different keys side by side, at most events-at-once keys at once; the patterns given no key share one key; every message
// held is said in progress at every third of its durable's ack wait by one ticker, with the handling of its key blocked past
// five ack waits, and handled once; a delivery again of a held sequence reaches no handler; holding events-waiting messages the
// hub takes no more and says so once; a setting not composed reads its default.
func TestTheHubHoldsEventsByKeyAndSaysThemInProgress(t *testing.T) {
events := make(chan string, 32)
gate := map[string]chan struct{}{"a1": make(chan struct{}), "b1": make(chan struct{})}
handler := func(m jetstream.Msg) {
name := m.Subject()[len("mesh.mod.m.event."):]
events <- "start " + name
if g := gate[name]; g != nil {
<-g
}
_ = m.Ack()
events <- "end " + name
}
lastToken := func(subject string, _ []byte) string { return subject[len(subject)-2 : len(subject)-1] }
var journal []string
var jmu sync.Mutex
logf := func(f string, a ...any) { jmu.Lock(); journal = append(journal, fmt.Sprintf(f, a...)); jmu.Unlock() }
newHub := func() (*EventHub, chan time.Time) {
h := NewEventHub(logf)
ticks := make(chan time.Time)
h.tick = func(time.Duration) (<-chan time.Time, func()) { return ticks, func() {} }
if err := h.HandleByKey("mesh.mod.m.event.>", lastToken, handler); err != nil {
t.Fatal(err)
}
if err := h.held.settle(); err != nil {
t.Fatal(err)
}
return h, ticks
}
next := func(want string) {
t.Helper()
select {
case got := <-events:
if got != want {
t.Fatalf("the hub did %q, want %q", got, want)
}
case <-time.After(5 * time.Second):
t.Fatalf("the hub did nothing, want %q", want)
}
}
msg := func(name string, seq uint64) *seqMsg { return &seqMsg{subject: "mesh.mod.m.event." + name, seq: seq} }
t.Run("a blocked key holds back no other key, its own events keep their order, every held message is said in progress", func(t *testing.T) {
h, ticks := newHub()
feed := h.newFeed()
feed.start(30 * time.Second)
first, second, other := msg("a1", 1), msg("a2", 2), msg("b1", 3)
for _, m := range []*seqMsg{first, second, other} {
h.hearOn(feed)(m)
}
started := []string{<-events, <-events}
if slices.Sort(started); strings.Join(started, ",") != "start a1,start b1" {
t.Fatalf("with one key's handler blocked another key's was not handled: %v", started)
}
// five ack waits pass: every held message, handled or waiting, is said in progress at each tick
for range 15 {
ticks <- time.Time{}
}
again := msg("a1", 1) // given again: handed to no handler
h.hearOn(feed)(again)
close(gate["b1"])
next("end b1")
close(gate["a1"])
next("end a1")
next("start a2")
next("end a2")
for _, m := range []*seqMsg{first, second, other} {
if m.said() < 14 {
t.Errorf("%s was said in progress %d times, want one at every tick", m.subject, m.said())
}
}
select {
case got := <-events:
t.Errorf("a delivery again reached a handler: %s", got)
default:
}
h.Stop()
})
t.Run("the patterns given no key share one, and events-at-once bounds the keys", func(t *testing.T) {
started := make(chan string, 8)
blockOn := func(release chan struct{}) func(jetstream.Msg) {
return func(m jetstream.Msg) { started <- m.Subject(); <-release }
}
release := make(chan struct{})
noOther := func(want string, why string) {
t.Helper()
select {
case got := <-started:
t.Fatalf("%s: %s", why, got)
case <-time.After(50 * time.Millisecond):
}
_ = want
}
shared := NewEventHub(logf)
for _, p := range []string{"x.>", "y.>"} {
if err := shared.Handle(p, blockOn(release)); err != nil {
t.Fatal(err)
}
}
go shared.hearOn(nil)(&seqMsg{subject: "x.1", seq: 1})
<-started
go shared.hearOn(nil)(&seqMsg{subject: "y.1", seq: 2})
noOther("", "two patterns given no key were handled side by side")
close(release)
<-started
t.Setenv(stdio.SettingWord(EventsAtOnceSetting), "1")
release2 := make(chan struct{})
one := NewEventHub(logf)
if err := one.HandleByKey("k.>", func(subject string, _ []byte) string { return subject }, blockOn(release2)); err != nil {
t.Fatal(err)
}
if err := one.held.settle(); err != nil {
t.Fatal(err)
}
go one.hearOn(nil)(&seqMsg{subject: "k.a", seq: 1})
<-started
go one.hearOn(nil)(&seqMsg{subject: "k.b", seq: 2})
noOther("", "a second key ran with events-at-once 1")
close(release2)
if got := <-started; got != "k.b" {
t.Fatalf("the waiting key ran %s", got)
}
})
t.Run("holding events-waiting messages it takes no more, said once; defaults when not composed", func(t *testing.T) {
h := NewEventHub(logf)
if err := h.held.settle(); err != nil || h.held.atOnce != 8 || h.held.bound != 100 {
t.Fatalf("defaults: %d at once, %d waiting (%v)", h.held.atOnce, h.held.bound, err)
}
t.Setenv(stdio.SettingWord(EventsWaitingSetting), "2")
release := make(chan struct{})
if err := h.Handle("w.>", func(m jetstream.Msg) { <-release }); err != nil {
t.Fatal(err)
}
if err := h.held.settle(); err != nil {
t.Fatal(err)
}
h.hearOn(nil)(&seqMsg{subject: "w.1", seq: 1})
taken := make(chan struct{})
go func() { h.hearOn(nil)(&seqMsg{subject: "w.2", seq: 2}); close(taken) }()
select {
case <-taken:
t.Fatal("the hub took a message past its bound")
case <-time.After(50 * time.Millisecond):
}
close(release)
select {
case <-taken:
case <-time.After(5 * time.Second):
t.Fatal("the hub took no message once room was made")
}
jmu.Lock()
said := 0
for _, l := range journal {
if strings.Contains(l, "its bound: it pulls no more") {
said++
}
}
jmu.Unlock()
if said != 1 {
t.Errorf("the bound was said %d times, want once", said)
}
t.Setenv(stdio.SettingWord(EventsWaitingSetting), "0")
if err := h.held.settle(); err == nil {
t.Error("a bound of 0 was accepted")
}
})
}
// Design 47 H2 H-A-683 (3), H-A-697 (3): a handling past event-overrun tells the hook once while it runs, naming its subject, key
// and since when, the oldest first, and once more when it ends with none past it; a handling past slow-event is said in the
// journal with its key and how long it took; a setting outside 1 second to 1 hour is refused naming it.
func TestAHandlingPastEventOverrunTellsItsHookWhileItRuns(t *testing.T) {
now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
var clock sync.Mutex
var lines []string
h := NewEventHub(func(f string, a ...any) { clock.Lock(); lines = append(lines, fmt.Sprintf(f, a...)); clock.Unlock() })
h.held.now = func() time.Time { clock.Lock(); defer clock.Unlock(); return now }
advance := func(d time.Duration) { clock.Lock(); now = now.Add(d); clock.Unlock() }
var fire []func()
h.held.after = func(d time.Duration, f func()) func() {
if d != 60*time.Second {
t.Errorf("the overrun is timed at %s, want the default 60s", d)
}
clock.Lock()
fire = append(fire, f)
clock.Unlock()
return func() {}
}
release := make(chan struct{})
entered := make(chan struct{}, 4)
if err := h.HandleByKey("mesh.mod.m.event.>", func(subject string, _ []byte) string { return subject[len("mesh.mod.m.event."):] },
func(jetstream.Msg) { entered <- struct{}{}; <-release }); err != nil {
t.Fatal(err)
}
var told [][]Handling
h.OnOverrun(func(past []Handling) { clock.Lock(); told = append(told, past); clock.Unlock() })
if err := h.held.settle(); err != nil {
t.Fatal(err)
}
h.hearOn(nil)(&seqMsg{subject: "mesh.mod.m.event.first", seq: 1})
<-entered
advance(time.Second)
h.hearOn(nil)(&seqMsg{subject: "mesh.mod.m.event.second", seq: 2})
<-entered
advance(59 * time.Second)
clock.Lock()
timers := fire
clock.Unlock()
for _, f := range timers {
f()
}
clock.Lock()
if len(told) != 2 || len(told[1]) != 2 || told[1][0].Subject != "mesh.mod.m.event.first" || told[1][0].Key != "first" ||
!told[1][0].Since.Equal(now.Add(-60*time.Second)) || told[1][1].Key != "second" {
t.Fatalf("the hook was told %+v", told)
}
clock.Unlock()
close(release)
deadline := time.After(5 * time.Second)
for {
clock.Lock()
n, last := len(told), []Handling(nil)
if n > 0 {
last = told[n-1]
}
clock.Unlock()
if n >= 4 && len(last) == 0 {
break
}
select {
case <-deadline:
t.Fatalf("the hook was told %d times, the last of %v", n, last)
case <-time.After(5 * time.Millisecond):
}
}
clock.Lock()
said := strings.Join(lines, "\n")
clock.Unlock()
if !strings.Contains(said, "the event mesh.mod.m.event.first (key first) took 1m0s to handle, over 100ms") {
t.Errorf("the journal says %q", said)
}
t.Setenv(stdio.SettingWord(EventOverrunSetting), "500ms")
if err := h.held.settle(); err == nil || !strings.Contains(err.Error(), EventOverrunSetting) {
t.Errorf("an overrun of 500ms was accepted: %v", err)
}
}
// Design 47 H2 H-A-737 (1): Handle keeps its earlier form, so a hub handed to a module's own interface (seatlist.ProcessBus's
// EventHandlers) is still one; holding by key is HandleByKey's.
var _ interface {
Handle(string, func(jetstream.Msg)) error
} = (*EventHub)(nil)
// fakeHubBus is the bus the hub's start asks of: which durables are composed, and the wakes it is given.
type fakeHubBus struct {
mu sync.Mutex
streams []string
subjects []string
composed map[string]error // a stream whose durable is composed has a nil entry; any other is not
binds []string
wakeAt string
onWake func()
reconn func()
stopped bool
// missed is called, with no lock held, from inside a bind that finds no durable composed (a test composes it there).
missed func(stream string)
}
func (b *fakeHubBus) streamNames(context.Context) ([]string, error) { return b.streams, nil }
func (b *fakeHubBus) streamSubjects(context.Context, string) ([]string, error) {
return b.subjects, nil
}
func (b *fakeHubBus) bind(stream string) (jetstream.ConsumeContext, time.Time, error) {
b.mu.Lock()
defer b.mu.Unlock()
err, ok := b.composed[stream]
if !ok {
if b.missed != nil {
b.mu.Unlock()
b.missed(stream)
b.mu.Lock()
}
return nil, time.Time{}, fmt.Errorf("no durable: %w", jetstream.ErrConsumerNotFound)
}
if err != nil {
return nil, time.Time{}, err
}
b.binds = append(b.binds, stream)
return &pullContext{closed: make(chan struct{})}, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), nil
}
func (b *fakeHubBus) hearEvents(_ context.Context, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
return b.bind(EventsStream)
}
func (b *fakeHubBus) hearKept(_ context.Context, stream string, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
return b.bind(stream)
}
func (b *fakeHubBus) wake(subject string, f func()) (func(), error) {
b.wakeAt, b.onWake = subject, f
return func() { b.stopped = true }, nil
}
func (b *fakeHubBus) reconnected(f func()) { b.reconn = f }
// Design 47 H2b §836 1., 2. (1984/AC-836a, AC-836b): Start alone binds a kept seat event's stream beside EVENTS and tells OnAllHeard
// once; a durable not composed at Start is bound when the grants part says it composed the module's durables, and again at a
// reconnect when its bind was refused, OnAllHeard told once each time the patterns are all heard, a bound stream never bound again.
func subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard(t *testing.T) {
kept := "SEAT_node-engine_running"
cred := Account{Node: "n1", Module: "teller"}
var unheardTold [][]Unheard // what OnUnheard was told, in order (1984/AC-836e)
var jmu sync.Mutex
var journal []string // the hub's journal lines (1984/AC-836r, AC-836s)
logf := func(f string, a ...any) {
jmu.Lock()
journal = append(journal, fmt.Sprintf(f, a...))
jmu.Unlock()
t.Logf(f, a...)
}
said := func(want string) bool {
jmu.Lock()
defer jmu.Unlock()
return slices.ContainsFunc(journal, func(l string) bool { return strings.Contains(l, want) })
}
newHub := func(bus *fakeHubBus) (h *EventHub, allHeard *int, created *[]time.Time) {
h, allHeard, created = NewEventHub(logf), new(int), new([]time.Time)
unheardTold, journal = nil, nil
h.OnUnheard(func(list []Unheard) { unheardTold = append(unheardTold, list) })
h.OnAllHeard(func() { *allHeard++ })
h.OnBound(func(at time.Time) { *created = append(*created, at) })
if err := h.Handle("mesh.seat.node-engine.event.running.>", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
if err := h.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
return h, allHeard, created
}
base := func(composed map[string]error) *fakeHubBus {
return &fakeHubBus{streams: []string{kept, "SEAT_other_thing", "EVENTS"}, subjects: []string{"mesh.mod.*.event.>"}, composed: composed}
}
t.Run("start alone", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil, kept: nil})
h, allHeard, created := newHub(bus)
if err := h.start(context.Background(), bus, cred); err != nil {
t.Fatal(err)
}
defer h.Stop()
if err := h.Handle("mesh.mod.late.event.y", func(jetstream.Msg) {}); err == nil || !strings.Contains(err.Error(), `"mesh.mod.late.event.y"`) {
t.Errorf("a handler registered after Start: %v", err) // 1984/AC-836d
}
if *allHeard != 1 || len(bus.binds) != 2 || len(*created) != 2 {
t.Errorf("all heard %d times, binds %v, bound told %d times", *allHeard, bus.binds, len(*created))
}
if bus.wakeAt != "mesh.seat.mesh-grants.event.durables-composed.n1.teller" {
t.Errorf("the wake is on %q", bus.wakeAt)
}
bus.onWake()
bus.reconn()
if len(unheardTold) != 2 || len(unheardTold[0]) != 0 || len(unheardTold[1]) != 1 {
t.Errorf("a start that binds everything tells an empty list once, a later wake and reconnect nothing, and the refused late pattern: %v", unheardTold)
}
if *allHeard != 1 || len(bus.binds) != 2 {
t.Errorf("a bound stream was told or bound again: %d, %v", *allHeard, bus.binds)
}
})
t.Run("composed late, refused then bound at a reconnect", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil})
h, allHeard, _ := newHub(bus)
h.start(context.Background(), bus, cred)
defer h.Stop()
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].Stream != kept || !strings.Contains(h.unheardNow[0].Why, "not composed") {
t.Fatalf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
if !said("the pattern mesh.seat.node-engine.event.running.> is not heard on " + kept + ": not composed") {
t.Errorf("the journal names no pattern not heard: %q", journal)
}
bus.composed[kept] = errors.New("the bus refuses")
bus.onWake()
if *allHeard != 0 || !strings.Contains(h.unheardNow[0].Why, "refused") {
t.Fatalf("a refused bind: all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
bus.onWake() // the same reason again: nothing new to tell
bus.composed[kept] = nil
bus.reconn()
bus.onWake()
if *allHeard != 1 || len(h.unheardNow) != 0 || len(bus.binds) != 2 {
t.Errorf("all heard %d, unheard %+v, binds %v", *allHeard, h.unheardNow, bus.binds)
}
if len(unheardTold) != 3 || len(unheardTold[2]) != 0 || len(unheardTold[0]) != 1 || len(unheardTold[1]) != 1 ||
unheardTold[0][0] == unheardTold[1][0] {
t.Errorf("OnUnheard was told %v: the list at Start, its change, then empty once heard", unheardTold)
}
// 1984/AC-836s: a pattern registered after Start is refused and is among those not heard
if err := h.Handle("mesh.mod.p.event.late", func(jetstream.Msg) {}); err == nil {
t.Error("a handler after Start was accepted")
}
if n := len(unheardTold); n != 4 || len(unheardTold[3]) != 1 || unheardTold[3][0] != (Unheard{"mesh.mod.p.event.late", "", "registered after Start"}) {
t.Errorf("OnUnheard was told %v", unheardTold)
}
if !said("the pattern mesh.mod.p.event.late is not heard: registered after Start") {
t.Errorf("the journal says nothing of the pattern refused after Start: %q", journal)
}
})
// AC-836b clause 2: the wake is made before the first bind, so the word that the durables were composed, said from inside
// Start's own failing bind, binds the stream.
t.Run("composed while Start's bind fails", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil})
bus.missed = func(stream string) {
bus.mu.Lock()
bus.composed[stream] = nil
wake := bus.onWake
bus.mu.Unlock()
if wake != nil {
go wake() // the subscription's own goroutine: it waits for Start's pass to end
}
}
h, allHeard, _ := newHub(bus)
heard := make(chan struct{}, 4)
h.OnAllHeard(func() { heard <- struct{}{} })
if err := h.start(context.Background(), bus, cred); err != nil {
t.Fatal(err)
}
defer h.Stop()
select {
case <-heard:
case <-time.After(10 * time.Second):
t.Fatalf("the durable composed during Start's bind was never bound: binds %v", bus.binds)
}
bus.mu.Lock()
defer bus.mu.Unlock()
if *allHeard != 1 || !slices.Contains(bus.binds, kept) {
t.Errorf("all heard %d, binds %v", *allHeard, bus.binds)
}
})
// §836 5., H-A-876: for a process that names one, the durable asked of the bus is the process's own, said in the journal and the reason
t.Run("a process names its durable", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil})
h, _, _ := newHub(bus)
if err := h.ForProcess("keeper"); err != nil {
t.Fatal(err)
}
h.start(context.Background(), bus, cred)
defer h.Stop()
if len(h.unheardNow) != 1 || !strings.Contains(h.unheardNow[0].Why, "no durable n1_teller_keeper on it") || !said("the consumer n1_teller_keeper on EVENTS is heard") {
t.Errorf("unheard %+v, journal %q", h.unheardNow, journal)
}
if h.ForProcess("other") == nil {
t.Error("a process was named after Start")
}
})
t.Run("no stream carries a pattern", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil, kept: nil})
bus.subjects = []string{"mesh.seat.*.event.>"}
h, allHeard, _ := newHub(bus)
h.start(context.Background(), bus, cred)
defer h.Stop()
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].Pattern != "mesh.mod.p.event.x" || h.unheardNow[0].Why != "no stream carries it" {
t.Errorf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
if !said("the pattern mesh.mod.p.event.x is not heard: no stream carries it") {
t.Errorf("the journal names no pattern no stream carries: %q", journal)
}
})
}
+18
View File
@@ -0,0 +1,18 @@
package process
import "testing"
// A-397: a kept seat event's stream names its seat and event; a work queue's stream and any other name are none.
func TestKeptSeatEventOfAStreamName(t *testing.T) {
for _, c := range []struct{ stream, seat, event string }{
{"SEAT_node-build-go_toolchain-reported", "node-build-go", "toolchain-reported"},
{"SEAT_mesh-catalog_versions-filled", "mesh-catalog", "versions-filled"},
{"SEAT_NODE_BUILD_GO", "", ""},
{"EVENTS", "", ""},
} {
seat, event, ok := keptSeatEvent(c.stream)
if ok != (c.seat != "") || seat != c.seat || event != c.event {
t.Errorf("%s: %q %q %v, want %q %q", c.stream, seat, event, ok, c.seat, c.event)
}
}
}
+151 -4
View File
@@ -5,7 +5,9 @@ import (
"errors"
"fmt"
"strings"
"time"
"git.novox.be/novox/mesh-sdk/go/busretry"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -93,10 +95,155 @@ func (a Account) EventConsumer(ctx context.Context, js jetstream.JetStream, stre
return js.Consumer(ctx, stream, a.EventConsumerName())
}
// NamedEventConsumer binds the module's durable consumer named for a suffix on stream: <node>_<module>_<suffix>, beside
// EventConsumer's <node>_<module> (design 47 H §743, H-A-90: the indexer's one durable per watched branch).
func (a Account) NamedEventConsumer(ctx context.Context, js jetstream.JetStream, stream, suffix string) (jetstream.Consumer, error) {
return js.Consumer(ctx, stream, a.namedEventConsumerName(suffix))
}
// durableOf is the module's durable, or the one of the process named process when one is named (EventHub.ForProcess).
func (a Account) durableOf(process string) string {
if process == "" {
return a.EventConsumerName()
}
return a.namedEventConsumerName(process)
}
func (a Account) namedEventConsumerName(suffix string) string {
return a.EventConsumerName() + "_" + suffix
}
// HearEvents pulls from cons, handing each message to handle, and says every error the bus reports while
// hearing through logf ("hearing the bus: ..."). The caller stops the returned context.
// hearing through logf ("hearing the bus: ..."). The caller stops the returned context. A durable this process pulls
// already is refused (ConsumeOnce, design 47 H, H-A-196).
//
// It pulls at most hubPullMessages messages per pull, and says in progress to the bus for a message whose handler runs
// past a third of the consumer's ack wait, again at each further third until the handler returns (design 47 H, H-A-281):
// handlers run one by one, so a large pull's buffered messages would outlive the ack wait and be given again. The ack
// wait is read once, from the consumer's information as the bind read it.
func HearEvents(cons jetstream.Consumer, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, error) {
return cons.Consume(handle, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) {
logf("hearing the bus: %v", err)
}))
return hearEvents(cons, callerOutside(), handle, logf, realTicker)
}
// hubPullMessages is how many messages the event hub pulls at most per pull (design 47 H, H-A-281).
const hubPullMessages = 20
// ticker answers a channel ticking every d and its stop.
type ticker func(d time.Duration) (<-chan time.Time, func())
func realTicker(d time.Duration) (<-chan time.Time, func()) {
t := time.NewTicker(d)
return t.C, t.Stop
}
func hearEvents(cons jetstream.Consumer, binder string, handle func(jetstream.Msg), logf func(string, ...any), tick ticker) (jetstream.ConsumeContext, error) {
var ackWait time.Duration
if info := cons.CachedInfo(); info != nil {
ackWait = info.Config.AckWait
}
return ConsumeOnce(cons, binder, keptInProgress(handle, ackWait/3, tick), jetstream.PullMaxMessages(hubPullMessages),
jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) {
logf("hearing the bus: %v", err)
}))
}
// hearHeld is HearEvents for a handler that holds each message and returns (the event hub's, event_hold.go): the pull says
// nothing in progress itself, since the hub's ticker of the durable does for every message held. It pulls one message at a
// time and only while the hub holds fewer than events-waiting, so no delivered message is left outside the hold: the rest
// wait on the bus, not yet given (design 47 H2 H-A-695 (2), H-A-733).
func hearHeld(cons jetstream.Consumer, binder string, hold *eventHold, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, error) {
release, err := pullOnce(cons, binder)
if err != nil {
return nil, err
}
it, err := cons.Messages(jetstream.PullMaxMessages(1))
if err != nil {
release()
return nil, err
}
pulled := &heldPull{it: it, closed: make(chan struct{})}
go func() {
defer func() { release(); close(pulled.closed) }()
var faults pullFaults
for {
hold.waitRoom()
m, err := it.Next()
if err != nil {
if errors.Is(err, jetstream.ErrMsgIteratorClosed) {
return
}
say, wait := faults.next(err, busretry.KeptPace())
if say {
logf("hearing the bus: %v", err)
}
time.Sleep(wait)
continue
}
faults.ended()
handle(m)
}
}()
return pulled, nil
}
// pullFaults paces hearHeld's pull after an error at the kept-call pace (busretry.KeptPace: the settings
// kept-call-pace-first and kept-call-pace-max), doubling from the first to the most, and says each kind of error once
// until a message arrives (design 47 H2 §775, principle 11).
type pullFaults struct {
wait time.Duration
said map[string]bool
}
// next is the wait after err and whether err is of a kind not yet said.
func (f *pullFaults) next(err error, pace busretry.Pace) (bool, time.Duration) {
if f.wait <= 0 {
f.wait = pace.First
} else {
f.wait = min(f.wait*2, pace.Max)
}
if f.said == nil {
f.said = map[string]bool{}
}
kind := err.Error()
say := !f.said[kind]
f.said[kind] = true
return say, f.wait
}
// ended is a message pulled: the pace and what was said start again.
func (f *pullFaults) ended() { *f = pullFaults{} }
// heldPull is the pull of hearHeld as a ConsumeContext.
type heldPull struct {
it jetstream.MessagesContext
closed chan struct{}
}
func (p *heldPull) Stop() { p.it.Stop() }
func (p *heldPull) Drain() { p.it.Drain() }
func (p *heldPull) Closed() <-chan struct{} { return p.closed }
// keptInProgress is handle that says in progress for its message at every tick of every while the handler runs, the
// ticker stopped at the handler's return (design 47 H, H-A-281); with no every it is handle as it is.
func keptInProgress(handle func(jetstream.Msg), every time.Duration, tick ticker) jetstream.MessageHandler {
if every <= 0 {
return handle
}
return func(m jetstream.Msg) {
ticks, stop := tick(every)
done, ended := make(chan struct{}), make(chan struct{})
go func() {
defer close(ended)
for {
select {
case <-done:
return
case <-ticks:
_ = m.InProgress()
}
}
}()
defer func() { close(done); stop(); <-ended }()
handle(m)
}
}
+137
View File
@@ -0,0 +1,137 @@
package process
import (
"context"
"encoding/json"
"errors"
"log"
"time"
"github.com/nats-io/nats.go/jetstream"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// sayPrune writes a prune's one journal line (design 47 H2 §812).
var sayPrune = func(line string) { log.Print(line) }
// PrunedState is a state a process prunes at its own writes (design 47 H2 §812; H-A-380): the entry's figures are read
// once when it is bound and once after each prune, and between those a running sum of the bytes each write puts
// (stdio.PutBytes, an upper bound) is the judgement; past prune-mark of the cap the oldest keys by their current
// revision are purged down to prune-target, skipping a key kept under stdio.KeepKey. No read per write, no poll, no timer.
// Its reads are the state's own.
type PrunedState struct {
State
pruner *stdio.Pruner
}
// Pruned binds the state for a prune by p, reading its figures once.
func (s State) Pruned(p stdio.Prune) (*PrunedState, error) {
ps := &PrunedState{State: s}
ps.pruner = &stdio.Pruner{State: s.Module + "'s " + s.Name, Prune: p, Say: func(line string) { sayPrune(line) },
Figures: s.figures, Entries: s.entries, Remove: s.purge}
if err := ps.pruner.Bind(); err != nil {
return nil, err
}
return ps, nil
}
// figures is the bucket's bytes and its cap, zero for none.
func (s State) figures() (uint64, uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
defer cancel()
kv, err := s.store(ctx)
if err != nil {
return 0, 0, err
}
st, err := kv.Status(ctx)
if err != nil {
return 0, 0, err
}
return st.Bytes(), uint64(max(st.Config().MaxBytes, 0)), nil
}
// entries is every current value of the bucket with its revision, keeps included, read once.
func (s State) entries() ([]stdio.PruneEntry, error) {
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
defer cancel()
kv, err := s.store(ctx)
if err != nil {
return nil, err
}
w, err := kv.WatchAll(ctx, jetstream.IgnoreDeletes())
if err != nil {
return nil, err
}
defer w.Stop()
var out []stdio.PruneEntry
for {
select {
case e, open := <-w.Updates():
if !open {
return nil, errors.New("the read of the current values ended")
}
if e == nil {
return out, nil
}
if e.Operation() == jetstream.KeyValuePut {
out = append(out, stdio.PruneEntry{Key: e.Key(), Revision: e.Revision(), Bytes: stdio.PutBytes(e.Key(), e.Value()), Value: e.Value()})
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
// purge removes a key with its past values, so its bytes leave the bucket.
func (s State) purge(key string) error {
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
defer cancel()
kv, err := s.store(ctx)
if err != nil {
return err
}
return kv.Purge(ctx, key)
}
// wrote counts a write and prunes past the mark.
func (s *PrunedState) wrote(key string, value any, rev uint64, err error) (uint64, error) {
if err != nil {
return rev, err
}
data, _ := json.Marshal(value)
if _, err := s.pruner.Wrote(stdio.PutBytes(key, data)); err != nil {
return rev, err
}
return rev, nil
}
// Put writes a key whole, counted toward the prune.
func (s *PrunedState) Put(key string, value any) (uint64, error) {
rev, err := s.State.Put(key, value)
return s.wrote(key, value, rev, err)
}
// Create writes a key only when it has none, counted toward the prune.
func (s *PrunedState) Create(key string, value any) (uint64, error) {
rev, err := s.State.Create(key, value)
return s.wrote(key, value, rev, err)
}
// Update writes a key only when it is still at revision, counted toward the prune.
func (s *PrunedState) Update(key string, value any, revision uint64) (uint64, error) {
rev, err := s.State.Update(key, value, revision)
return s.wrote(key, value, rev, err)
}
// PruneNow prunes the state to its target now.
func (s *PrunedState) PruneNow() (stdio.Pruned, error) { return s.pruner.PruneNow() }
// Keep keeps key from the prune until until, written under stdio.KeepKey.
func (s *PrunedState) Keep(key string, until time.Time) error {
if err := stdio.KeepProblem(key, until); err != nil {
return err
}
_, err := s.Put(stdio.KeepKey(key), stdio.Keep{Until: until.UTC()})
return err
}
+62
View File
@@ -0,0 +1,62 @@
package process
import (
"context"
"github.com/nats-io/nats.go/jetstream"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// pruneKV is a fakeKV with a cap: its bytes are what its current values put (stdio.PutBytes), its Status says them
// with the cap, WatchAll hands every current value, and Purge removes a key.
type pruneKV struct {
*fakeKV
cap int64
statuss int
}
type pruneStatus struct {
jetstream.KeyValueStatus
bytes uint64
cap int64
}
func (s pruneStatus) Bytes() uint64 { return s.bytes }
func (s pruneStatus) Config() jetstream.KeyValueConfig {
return jetstream.KeyValueConfig{MaxBytes: s.cap}
}
func (f *pruneKV) held() uint64 {
f.mu.Lock()
defer f.mu.Unlock()
var n uint64
for k, v := range f.values {
n += stdio.PutBytes(k, v)
}
return n
}
func (f *pruneKV) Status(context.Context) (jetstream.KeyValueStatus, error) {
f.statuss++
return pruneStatus{bytes: f.held(), cap: f.cap}, nil
}
func (f *pruneKV) WatchAll(context.Context, ...jetstream.WatchOpt) (jetstream.KeyWatcher, error) {
f.mu.Lock()
defer f.mu.Unlock()
w := &fakeWatcher{updates: make(chan jetstream.KeyValueEntry, len(f.values)+1)}
for k, v := range f.values {
w.updates <- putEntry{fakeEntry{key: k, value: v, rev: f.revs[k]}}
}
w.updates <- nil
return w, nil
}
func (f *pruneKV) Purge(ctx context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
return f.Delete(ctx, key)
}
type putEntry struct{ fakeEntry }
func (putEntry) Operation() jetstream.KeyValueOp { return jetstream.KeyValuePut }
+99
View File
@@ -0,0 +1,99 @@
package process
import (
"fmt"
"runtime"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
)
// A process pulls a durable consumer once (design 47 H, H-A-196): a second pull loop on a durable the same process
// already pulls takes every other event from the first, so each event reaches one loop only and nothing says so. The SDK
// refuses it, loud at bind time, the error naming the durable and both binders. A durable is told by its stream, its name
// and the time the bus made it, so the same names on two buses (two embedded buses in one test process) are two durables.
var pulled = struct {
sync.Mutex
by map[string]string
}{by: map[string]string{}}
// ConsumeOnce is the one way a part of a module pulls a durable consumer: it claims cons for binder (a short label; empty
// is the calling function's name) and pulls it with handle and opts, as cons.Consume does. A durable this process pulls
// already is refused, the error naming it and both binders. The claim is released when the loop is stopped, when a drain
// has ended, or when the bus ends the loop: the context's Closed is closed only once the claim is released, so a part that
// binds again on it is never refused. A consumer that is not durable is no claim.
func ConsumeOnce(cons jetstream.Consumer, binder string, handle jetstream.MessageHandler, opts ...jetstream.PullConsumeOpt) (jetstream.ConsumeContext, error) {
if binder == "" {
binder = callerOutside()
}
release, err := pullOnce(cons, binder)
if err != nil {
return nil, err
}
cc, err := cons.Consume(handle, opts...)
if err != nil {
release()
return nil, err
}
closed := make(chan struct{})
go func() { <-cc.Closed(); release(); close(closed) }()
return pulledOnce{ConsumeContext: cc, release: release, closed: closed}, nil
}
// pullOnce claims the pull of cons, a durable consumer, for binder: it answers the release, or an error when this process
// already pulls that durable, naming it and both binders.
func pullOnce(cons jetstream.Consumer, binder string) (release func(), err error) {
info := cons.CachedInfo()
if info == nil || info.Config.Durable == "" {
return func() {}, nil
}
key := info.Stream + "/" + info.Name + "@" + info.Created.UTC().Format(time.RFC3339Nano)
pulled.Lock()
defer pulled.Unlock()
if first, ok := pulled.by[key]; ok {
return nil, fmt.Errorf("the durable consumer %s on %s is pulled in this process already, by %s: a second pull loop, by %s, "+
"would take every other event from it, so it is refused (design 47 H, H-A-196)", info.Name, info.Stream, first, binder)
}
pulled.by[key] = binder
var once sync.Once
return func() {
once.Do(func() {
pulled.Lock()
delete(pulled.by, key)
pulled.Unlock()
})
}, nil
}
// ownPackage is this package's path as a function's name begins with it.
const ownPackage = "git.novox.be/novox/mesh-sdk/go/process."
// callerOutside is the name of the first function on the stack outside this package: the part that asked the pull.
func callerOutside() string {
pcs := make([]uintptr, 16)
frames := runtime.CallersFrames(pcs[:runtime.Callers(3, pcs)])
for {
f, more := frames.Next()
if !strings.HasPrefix(f.Function, ownPackage) {
return f.Function
}
if !more {
return f.Function
}
}
}
// pulledOnce is a pull loop whose claim is released as it is stopped, before Stop returns (so a re-serve that stops its old
// loop binds the new one at once), and once a drain or the bus ended the loop, never at the drain's start, so a bind
// during a drain cannot run two loops; its Closed is closed after the release.
type pulledOnce struct {
jetstream.ConsumeContext
release func()
closed chan struct{}
}
func (p pulledOnce) Stop() { p.ConsumeContext.Stop(); p.release() }
func (p pulledOnce) Closed() <-chan struct{} { return p.closed }
+5
View File
@@ -71,6 +71,11 @@ func (c *Conn) Consume(ctx context.Context, stream string, handle func(*Message)
if err != nil {
return fmt.Errorf("binding %s's queue consumer %s on %s: %w", c.account.Module, name, stream, err)
}
release, err := pullOnce(cons, callerOutside())
if err != nil {
return err
}
defer release()
return runQueue(ctx, fetchOne(cons), handle)
}
+10 -1
View File
@@ -4,6 +4,7 @@ package process
import (
"context"
"strings"
"testing"
"time"
@@ -90,15 +91,23 @@ func TestConsumeAckRemovesTheMessageFromTheStream(t *testing.T) {
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
got := make(chan *Message, 1)
got, second := make(chan *Message, 1), make(chan error, 1)
go func() {
_ = conn.Consume(ctx, "MAIL_SENDS", func(m *Message) {
// A second pull loop on the durable this process pulls is refused at bind time (design 47 H, H-A-196).
short, stop := context.WithTimeout(context.Background(), time.Second)
second <- conn.Consume(short, "MAIL_SENDS", func(*Message) {})
stop()
got <- m
cancel()
})
}()
msg := recv(t, got, 8*time.Second, "the message")
<-ctx.Done()
if err := <-second; err == nil || !strings.Contains(err.Error(), "pulled in this process already") ||
!strings.Contains(err.Error(), account.QueueConsumerName()) {
t.Fatalf("a second Consume of the queue the process pulls was not refused naming its durable: %v", err)
}
if err := msg.Ack(); err != nil {
t.Fatalf("Ack: %v", err)
}
+29 -6
View File
@@ -49,8 +49,20 @@ type HearOption func(*hearOptions)
type hearOptions struct {
onRead func(state string)
fromFirst bool
// held is the event hub's feed of this durable (EventHub.StartKept): its messages are held and said in progress by the
// hub's ticker, so the pull says none itself.
held *eventFeed
// process is the name of the process whose own durable is bound in place of the module's (EventHub.ForProcess).
process string
}
// heldBy makes the pull of a durable the event hub's: its handler holds each message and returns, and the feed's ticker says in
// progress for every one held, at every third of the durable's ack wait (design 47 H2 H-A-695 (1), (4)).
func heldBy(f *eventFeed) HearOption { return func(o *hearOptions) { o.held = f } }
// forProcess binds the durable of the process named process, `<node>_<module>_<process>`, in place of the module's.
func forProcess(process string) HearOption { return func(o *hearOptions) { o.process = process } }
// OnRead is the callback HearSeatEvents calls with ReadWaiting and then ReadDone around its start read; the module wires it
// to its first views (design 47 G A-19), so this package imports nothing of views.
func OnRead(f func(state string)) HearOption { return func(o *hearOptions) { o.onRead = f } }
@@ -136,14 +148,20 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
for _, f := range opts {
f(&o)
}
cons, err := a.EventConsumer(ctx, js, stream)
durable := a.durableOf(o.process)
cons, err := js.Consumer(ctx, stream, durable)
if err != nil {
return nil, fmt.Errorf("the consumer %s on %s is not there: %w", a.EventConsumerName(), stream, err)
return nil, fmt.Errorf("the consumer %s on %s is not there: %w", durable, stream, err)
}
st, err := js.Stream(ctx, stream)
if err != nil {
return nil, fmt.Errorf("the stream %s is not read: %w", stream, err)
}
if o.held != nil {
if info := cons.CachedInfo(); info != nil {
o.held.start(info.Config.AckWait)
}
}
if from, whole := wholeRead(st.CachedInfo().Config.MaxMsgsPerSubject, o.fromFirst); whole {
if o.onRead != nil {
o.onRead(ReadWaiting)
@@ -161,10 +179,15 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
}
logf("events: %s is read whole at its start", stream)
}
cc, err := HearEvents(cons, handle, logf)
if err != nil {
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", a.EventConsumerName(), stream, err)
var cc jetstream.ConsumeContext
if o.held != nil {
cc, err = hearHeld(cons, callerOutside(), o.held.hold, handle, logf)
} else {
cc, err = HearEvents(cons, handle, logf)
}
logf("events: the consumer %s on %s is heard", a.EventConsumerName(), stream)
if err != nil {
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", durable, stream, err)
}
logf("events: the consumer %s on %s is heard", durable, stream)
return cc, nil
}
+68 -28
View File
@@ -2,14 +2,19 @@ package process
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strings"
"sync"
"unsafe"
"github.com/nats-io/nats.go"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/busretry"
"git.novox.be/novox/mesh-sdk/go/calladdress"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
@@ -121,42 +126,64 @@ func Gated(g *approval.Gate) SeatOption { return func(o *seatOptions) { o.gate =
// heldHandler is a verb's handler behind its checks: its answer, the held answer of a kept call, or its error.
type heldHandler func(caller string, body json.RawMessage, wait bool) (any, *approval.Held, error)
// admitted is h behind the check of its caller against the verb's effective callers (A-179, A-186), and, for a verb the
// definition marks, behind the gate (§677).
// moduleAccount says a proven caller is a module's account, `<node>.<module>`: not a person's, not the tool runner's own
// account (`<node>.node-tools`, the one the mesh MCP server's sessions and agents call as), not an unproven caller (A-433, A-435).
func moduleAccount(caller string) bool {
node, module, ok := strings.Cut(caller, ".")
return ok && node != "person" && node != "" && module != "" && module != "node-tools" && !strings.Contains(module, ".")
}
// admitted is h, and for a verb the definition marks, h behind the gate (§677). Every caller is admitted, whether or not the
// definition is read and whatever callers it names (the operator, 2026-11-15 23:25 CET: every module, agent and operator may
// call anything; approval stays as the mark on a verb).
func (c *Conn) admitted(seat, verb string, definition func() (seatdef.Definition, bool), h SeatHandler, gate *approval.Gate) heldHandler {
return func(caller string, body json.RawMessage, wait bool) (any, *approval.Held, error) {
if caller == "" {
return nil, nil, fmt.Errorf("%s.%s takes no unproven caller: call it on its subject that names its caller, "+
"mesh.seat.%s.call.%s.<caller>", seat, verb, seat, verb)
}
def, read := definition()
if !read {
return nil, nil, fmt.Errorf("the definition of the seat %s is not yet read by this process's seat list, so no caller of %s.%s "+
"is admitted", seat, seat, verb)
if !read && !moduleAccount(caller) {
// A-435: a verb that may need approval is held while its definition is unread, as before, for a caller that is not
// a module's account (the mesh MCP server's, a person's, an unproven one); a module's account runs it (A-433).
return nil, nil, fmt.Errorf("the definition of the seat %s is not yet read by this process's seat list, so %s.%s, which may "+
"need approval, is not run for a caller that is no module's account", seat, seat, verb)
}
for _, v := range def.Verbs {
if v.Name != verb {
continue
if read {
for _, v := range def.Verbs {
if v.Name != verb || !v.NeedsApproval {
continue
}
if gate == nil {
return nil, nil, fmt.Errorf("Not run: %s.%s needs the operator's approval, and its holder serves it through no gate", seat, verb)
}
return gate.Hold(approval.Call{Address: seat + "." + verb, Module: c.account.Module, Seat: seat, Name: verb,
Caller: caller, Args: body, Description: v.Description}, wait, func() (any, error) { return h(caller, body) })
}
if len(v.EffectiveCallers()) == 0 {
return nil, nil, fmt.Errorf("%s.%s is open to no caller", seat, verb)
}
if !v.NeedsApproval {
answer, err := h(caller, body)
return answer, nil, err
}
if gate == nil {
return nil, nil, fmt.Errorf("Not run: %s.%s needs the operator's approval, and its holder serves it through no gate", seat, verb)
}
return gate.Hold(approval.Call{Address: seat + "." + verb, Module: c.account.Module, Seat: seat, Name: verb,
Caller: caller, Args: body, Description: v.Description}, wait, func() (any, error) { return h(caller, body) })
}
return nil, nil, fmt.Errorf("the seat %s's definition names no verb %s, so no caller is admitted", seat, verb)
answer, err := h(caller, body)
return answer, nil, err
}
}
// asks holds the ask id each call in flight carried (stdio.AskHeader), by its body's bytes, while its handler runs.
var asks sync.Map // unsafe.Pointer → string
// AskOf is the ask id the call whose body a SeatHandler was handed carried in stdio.AskHeader (design 47 H2 §775;
// H-A-351): what a holder in a process takes the ask once by. Empty when it carried none. Valid while the handler runs.
func AskOf(body json.RawMessage) string {
if len(body) == 0 {
return ""
}
if a, ok := asks.Load(unsafe.Pointer(unsafe.SliceData(body))); ok {
return a.(string)
}
return ""
}
// answerCall runs h for one call and replies {result, error, node}; a panic in h is the call's error, never silence.
func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) {
_ = msg.Respond(c.answerBody(msg, pattern, h))
}
// answerBody is the reply answerCall sends.
func (c *Conn) answerBody(msg *nats.Msg, pattern string, h heldHandler) []byte {
caller := ""
if strings.HasSuffix(pattern, ".*") {
caller = userOfToken(msg.Subject[strings.LastIndex(msg.Subject, ".")+1:])
@@ -175,10 +202,23 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) {
reply.Error = fmt.Sprintf("%s failed: %v", msg.Subject, r)
}
}()
result, held, err := h(caller, json.RawMessage(msg.Data), wait)
body := json.RawMessage(msg.Data)
if ask := msg.Header.Get(stdio.AskHeader); ask != "" && len(body) > 0 {
key := unsafe.Pointer(unsafe.SliceData(body))
asks.Store(key, ask)
defer asks.Delete(key)
}
result, held, err := h(caller, body, wait)
switch {
case err != nil:
reply.Error = err.Error()
// An `away` fault is the result in AwayAnswer's form (§776, H-A-708 (2), DQ-58), as stdio's serve answers it,
// so the caller's reader hands it on whole; any other fault is an error.
var away *busretry.Away
if errors.As(err, &away) {
reply.Result = busretry.AwayAnswer(away.Part, away.Words)
} else {
reply.Error = err.Error()
}
case held != nil:
reply.Held = held
case result == nil:
@@ -192,5 +232,5 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) {
if err != nil {
body, _ = json.Marshal(map[string]string{"error": "the answer is not JSON: " + err.Error(), "node": c.account.Node})
}
_ = msg.Respond(body)
return body
}
+40 -3
View File
@@ -257,7 +257,7 @@ func (s State) put(key string, value any) (uint64, error) {
return rev, nil
}
// Keys is every key with a current value, sorted; none is an empty list.
// Keys is every key with a current value, sorted; none is an empty list. A keep (stdio.KeepPrefix) is not an entry and is left out.
// Keys waits out a bus that answers nothing for a few seconds (busretry): only a request that reached no one is asked again.
func (s State) Keys() ([]string, error) {
return busretry.Do(s.what("keys"), func() ([]string, error) { return s.keys() }, nil)
@@ -277,8 +277,14 @@ func (s State) keys() ([]string, error) {
if err != nil {
return nil, fmt.Errorf("%s's state %s, keys: %w", s.Module, s.Name, err)
}
sort.Strings(keys)
return keys, nil
entries := keys[:0]
for _, k := range keys {
if !stdio.IsKeep(k) {
entries = append(entries, k)
}
}
sort.Strings(entries)
return entries, nil
}
// watchPattern is a key narrowing as the bus names it: `*` stays one name, `**` is the rest, empty is every key.
@@ -334,6 +340,9 @@ func (s State) Watch(key string, handle func(stdio.StateChange) error) error {
}
}
deliver := func(e jetstream.KeyValueEntry, current bool) error {
if stdio.IsKeep(e.Key()) {
return nil // a keep (stdio.KeepPrefix) is not an entry of the state: no watcher hears it
}
c := stdio.StateChange{State: s.Name, Key: e.Key(), Op: "put", Revision: e.Revision(), Current: current}
if e.Operation() == jetstream.KeyValuePut {
c.Value = json.RawMessage(e.Value())
@@ -398,3 +407,31 @@ func (s State) delete(key string) error {
}
return nil
}
// StateOver is a module's state read and written through kv, a key-value store bound over a link of the caller's own
// rather than a Conn (H-A-364): the node-engine, which serves its seat over its own link, takes asks once on its own
// taken state with it. module and name name it in errors.
func StateOver(module, name string, kv jetstream.KeyValue) *State {
return &State{Module: module, Name: name, kv: func(context.Context) (jetstream.KeyValue, error) { return kv, nil }}
}
// TakenState is the state a holder of a kept call keeps the ids of the asks it took in: stdio.TakenState.
const TakenState = stdio.TakenState
// TakenKey is the key an ask taken from seat is kept under in TakenState: stdio.TakenKey.
func TakenKey(seat, ask string) string { return stdio.TakenKey(seat, ask) }
// TakeOnce says whether this holder takes the ask ask of seat now (design 47 H2 §775; ADR 0668 §2), as
// stdio.KeptState.TakeOnce does for a bundle: the first time it is given, it is kept under TakenKey for the ask's bound
// and TakeOnce answers true; given again within the bound, false, and the holder acts once. s is the holder's
// TakenState, declared `key-ttl`. An ask with no id, or an id that is not one key, is refused: a kept call carries its id.
func (s State) TakeOnce(seat, ask string, bound time.Duration) (bool, error) {
if p := stdio.TakenProblem(seat, ask); p != "" {
return false, fmt.Errorf("taking an ask of %s: %s", seat, p)
}
_, err := s.CreateTTL(TakenKey(seat, ask), map[string]string{"seat": seat, "ask": ask}, max(bound, MinTTL))
if errors.Is(err, stdio.ErrChanged) {
return false, nil
}
return err == nil, err
}
+27
View File
@@ -4,7 +4,9 @@ package process
import (
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
@@ -199,6 +201,31 @@ func TestStatePutAndKeysOnAGrantedBucket(t *testing.T) {
if err != nil || strings.Join(keys, ",") != "a,b" {
t.Fatalf("Keys: %v, %v, want a,b", keys, err)
}
// Design 47 H2 §782: one connection's state calls are safe at once: gets, puts, keys and watches from many goroutines
// through the one handle, under the race detector.
var wg sync.WaitGroup
errs := make(chan error, 16*4)
for i := range 16 {
wg.Add(1)
go func() {
defer wg.Done()
key := fmt.Sprintf("c%d", i)
_, err := s.Put(key, i)
errs <- err
_, err = s.Get(key)
errs <- err
_, err = s.Keys()
errs <- err
errs <- s.Watch(key, func(stdio.StateChange) error { return nil })
}()
}
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatalf("a concurrent state call: %v", err)
}
}
}
// 1840/S2: given a process connection granted its bucket, which already holds two keys and a deleted one,
+90 -18
View File
@@ -3,6 +3,7 @@ package process
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
@@ -227,6 +228,79 @@ func TestStatePutWritesAKeyWhole(t *testing.T) {
if rev, err := dark.Put("k", 1); err != nil || rev == 0 || blackedOut != 0 {
t.Fatalf("a Put through a short blackout: %d, %v", rev, err)
}
// Design 47 H2 §775: a holder given the same ask id twice acts once; the id is kept under <seat>.<ask> with the
// ask's bound as its time to live; an ask with no id, or one that is not one key, is refused.
tkv := newFakeKV()
taken := StateOver("mesh-host", TakenState, tkv) // H-A-364: over a store the caller bound itself
acts := 0
for range 2 {
if first, err := taken.TakeOnce("mesh-builds", "a-7", 10*time.Minute); err != nil {
t.Fatal(err)
} else if first {
acts++
}
}
if acts != 1 || !tkv.withTTL[TakenKey("mesh-builds", "a-7")] || TakenKey("mesh-builds", "a-7") != "mesh-builds.a-7" {
t.Fatalf("acted %d times, keys with a TTL %v", acts, tkv.withTTL)
}
if first, err := taken.TakeOnce("mesh-wants", "a-7", time.Minute); !first || err != nil {
t.Fatalf("the same id on another seat is another ask: %v, %v", first, err)
}
for _, bad := range [][2]string{{"mesh-builds", ""}, {"mesh-builds", "a.7"}, {"", "a-8"}} {
if _, err := taken.TakeOnce(bad[0], bad[1], time.Minute); err == nil {
t.Errorf("seat %q, ask %q was taken", bad[0], bad[1])
}
}
// Design 47 H2 §812 (H-A-380, H-A-386): a process's write that takes its state past prune-mark prunes it, oldest first
// by revision, to prune-target, in one journal line, reading the figures only at the bind and after the prune; a key
// kept under _keep/<key> survives, and no reader counts the keep.
t.Run("a write past its mark prunes to its target and a kept key survives", func(t *testing.T) {
var lines []string
sayPrune = func(line string) { lines = append(lines, line) }
t.Cleanup(func() { sayPrune = func(string) {} })
kv := &pruneKV{fakeKV: newFakeKV(), cap: 10_000}
s, err := stateOn(kv).Pruned(stdio.Prune{Mark: 70, Target: 50})
if err != nil {
t.Fatal(err)
}
value := strings.Repeat("x", 300)
if _, err := s.Put("k00", value); err != nil {
t.Fatal(err)
}
if err := s.Keep("k00", time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
if err := s.Keep("k01", time.Now().Add(-time.Hour)); err == nil {
t.Fatal("a keep until a time past was taken")
}
for i := 1; i < 18; i++ {
if _, err := s.Put(fmt.Sprintf("k%02d", i), value); err != nil {
t.Fatal(err)
}
if len(lines) == 0 && kv.held()*100 > 70*10_000 {
t.Fatalf("the state holds %d of 10000 bytes after k%02d and was not pruned", kv.held(), i)
}
}
if len(lines) != 1 || !strings.Contains(lines[0], "pruned the state mesh-mail's sends") {
t.Fatalf("the prunes said %q, want one line", lines)
}
if kv.statuss != 2 {
t.Fatalf("the figures were read %d times, want 2: at the bind and after the prune", kv.statuss)
}
if held := kv.held(); held*100 > 50*10_000 {
t.Fatalf("the prune left %d of 10000 bytes, above its target of 50 %%", held)
}
keys, err := s.Keys()
if err != nil {
t.Fatal(err)
}
if keys[0] != "k00" || strings.Contains(strings.Join(keys, " "), "_keep") || keys[1] == "k01" || keys[len(keys)-1] != "k17" {
t.Fatalf("after the prune the readers see %v: want k00 kept, the oldest others gone, k17 there, no keep", keys)
}
if e, _ := s.Get(stdio.KeepKey("k00")); e == nil {
t.Fatal("the keep itself was pruned")
}
})
}
// 1840/S1: given a state, when its keys are listed, then they come sorted, and none is an empty list, not an error.
@@ -298,25 +372,23 @@ func TestStateWatchHandsCurrentValuesThenChanges(t *testing.T) {
t.Fatalf("no change %+v", want)
}
}
}
// 1840/S2: a key narrowing reaches the bus as a subject pattern: `*` one name, `**` the rest, empty every key.
func TestStateWatchNarrowing(t *testing.T) {
for key, want := range map[string]string{"": ">", "a.b": "a.b", "a.*": "a.*", "a.**": "a.>", "**": ">"} {
if got := watchPattern(key); got != want {
t.Errorf("watchPattern(%q) = %q, want %q", key, got, want)
// 1840/S2: a key narrowing reaches the bus as a subject pattern: `*` one name, `**` the rest, empty every key.
t.Run("narrowing", func(t *testing.T) {
for key, want := range map[string]string{"": ">", "a.b": "a.b", "a.*": "a.*", "a.**": "a.>", "**": ">"} {
if got := watchPattern(key); got != want {
t.Errorf("watchPattern(%q) = %q, want %q", key, got, want)
}
}
}
}
// 1840/S2: given a handler that refuses a current value, then Watch returns its error.
func TestStateWatchReturnsAHandlersErrorOnCurrentValues(t *testing.T) {
kv := newFakeKV()
kv.initial = []jetstream.KeyValueEntry{watchEntry{fakeEntry{key: "a", value: []byte(`1`), rev: 1}, jetstream.KeyValuePut}}
boom := errors.New("boom")
if err := stateOn(kv).Watch("", func(stdio.StateChange) error { return boom }); !errors.Is(err, boom) {
t.Fatalf("Watch: %v, want the handler's error", err)
}
})
// 1840/S2: given a handler that refuses a current value, then Watch returns its error.
t.Run("a handler's error on the current values is returned", func(t *testing.T) {
kv := newFakeKV()
kv.initial = []jetstream.KeyValueEntry{watchEntry{fakeEntry{key: "a", value: []byte(`1`), rev: 1}, jetstream.KeyValuePut}}
boom := errors.New("boom")
if err := stateOn(kv).Watch("", func(stdio.StateChange) error { return boom }); !errors.Is(err, boom) {
t.Fatalf("Watch: %v, want the handler's error", err)
}
})
}
// 1840/S2: given a connection that closes before the current values arrive, then Watch returns an error.
+373
View File
@@ -0,0 +1,373 @@
package stdio
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
)
// A kept store's owner prunes it toward its cap, judged at its own writes (design 47 H2 §812; H-A-380, H-A-386): when
// the fill passes prune-mark of the cap, the oldest keys by their current revision are removed until it is down to
// prune-target, one journal line per prune, with no extra read, no poll and no timer. A key kept by a person
// (`<module>_state_keep`) is never pruned before its until: the keep lives in the pruned state itself under KeepPrefix.
// The prune's settings and their defaults: prune-mark below the bus module's raise mark of 75 %.
const (
PruneMarkSetting = "prune-mark"
PruneTargetSetting = "prune-target"
PruneMarkDefault = 70
PruneTargetDefault = 50
pruneSettingPercent = "a percentage of the cap between 1 and 100"
)
// KeepPrefix is the reserved prefix a keep lives under in the state it keeps a key of (H-A-386): `_keep/<key>`, with
// its until. A keep is never pruned and never counted as an entry by the readers (Keys, Page, Watch).
const KeepPrefix = "_keep/"
// KeepKey is the key the keep of key lives under.
func KeepKey(key string) string { return KeepPrefix + key }
// IsKeep is whether key is a keep rather than an entry of its state.
func IsKeep(key string) bool { return strings.HasPrefix(key, KeepPrefix) }
// Keep is a keep's value: the key it keeps is never pruned before Until.
type Keep struct {
Until time.Time `json:"until"`
}
// SettingPercent is the config value key read as a percentage ("70" or "70%"): def when none is composed or it is
// empty, an error naming the key for a value that is no whole number from 1 to 100.
func SettingPercent(key string, def int) (int, error) {
v, ok := Setting(key)
if v = strings.TrimSpace(v); !ok || v == "" {
return def, nil
}
n, err := strconv.Atoi(strings.TrimSpace(strings.TrimSuffix(v, "%")))
if err != nil || n < 1 || n > 100 {
return 0, fmt.Errorf("the setting %s (%s) holds %q, which is not %s", key, SettingWord(key), v, pruneSettingPercent)
}
return n, nil
}
// Prune is where a prune starts and where it ends, in percent of the cap.
type Prune struct {
Mark, Target int
}
// PruneSettings is the module's prune-mark and prune-target, read through the settings reader with their defaults; a
// target not below the mark is refused, naming both.
func PruneSettings() (Prune, error) {
mark, err := SettingPercent(PruneMarkSetting, PruneMarkDefault)
if err != nil {
return Prune{}, err
}
target, err := SettingPercent(PruneTargetSetting, PruneTargetDefault)
if err != nil {
return Prune{}, err
}
if target >= mark {
return Prune{}, fmt.Errorf("the setting %s (%d %%) is not below %s (%d %%): a prune would never end below its mark",
PruneTargetSetting, target, PruneMarkSetting, mark)
}
return Prune{Mark: mark, Target: target}, nil
}
// Passed is whether bytes of a cap of maxBytes passes the mark; an entry with no cap never does.
func (p Prune) Passed(bytes, maxBytes uint64) bool {
return maxBytes > 0 && bytes*100 > uint64(p.Mark)*maxBytes
}
// PruneEntry is one current value of a pruned state as the prune reads it: its key, its current revision and the
// bytes it holds on the bus.
type PruneEntry struct {
Key string
Revision uint64
Bytes uint64
Value []byte
}
// Choose is the keys a prune removes, oldest first by their current revision, until bytes is down to the target of
// maxBytes, and how many it skipped for a keep whose until is still to come. A keep itself is never chosen; a keep that
// cannot be read keeps its key (a prune never removes what a person may have kept).
func (p Prune) Choose(entries []PruneEntry, now time.Time, bytes, maxBytes uint64) (drop []string, kept int) {
keeps := map[string]bool{}
for _, e := range entries {
if !IsKeep(e.Key) {
continue
}
var k Keep
if err := json.Unmarshal(e.Value, &k); err != nil || k.Until.After(now) {
keeps[strings.TrimPrefix(e.Key, KeepPrefix)] = true
}
}
sorted := append([]PruneEntry(nil), entries...)
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Revision < sorted[j].Revision })
target := uint64(p.Target) * maxBytes / 100
for _, e := range sorted {
if bytes <= target {
break
}
if IsKeep(e.Key) {
continue
}
if keeps[e.Key] {
kept++
continue
}
drop = append(drop, e.Key)
bytes -= min(bytes, e.Bytes)
}
return drop, kept
}
// Pruned is what one prune did: the state, how many keys it removed and skipped for a keep, and its fill before and
// after against the cap.
type Pruned struct {
State string `json:"state"`
Removed int `json:"removed"`
Kept int `json:"kept"`
From uint64 `json:"from-bytes"`
To uint64 `json:"to-bytes"`
MaxBytes uint64 `json:"max-bytes"`
Mark int `json:"mark"`
Target int `json:"target"`
}
// Line is the prune's one journal line.
func (r Pruned) Line() string {
return fmt.Sprintf("pruned the state %s: removed %d keys oldest first (%d kept by a keep), from %d to %d bytes of its cap of %d (mark %d %%, target %d %%)",
r.State, r.Removed, r.Kept, r.From, r.To, r.MaxBytes, r.Mark, r.Target)
}
// Prunable is a state its owner prunes: the generic tools `<module>_state_prune_now` and `<module>_state_keep` act on it.
type Prunable interface {
// PruneNow prunes the state to its target now, whatever its fill.
PruneNow() (Pruned, error)
// Keep keeps key from the prune until the time given.
Keep(key string, until time.Time) error
}
// Pruner is the prune helper of one state, the same for a process and a bundle: Entries reads the state's current
// values (keeps included) once per prune, Remove removes one key, Figures reads the entry's bytes and cap. A process
// gives Wrote the bytes each write puts and Figures is read at Bind and after each prune; a bundle gives Filled the
// fill its write's answer carries.
type Pruner struct {
State string
Prune Prune
Entries func() ([]PruneEntry, error)
Remove func(key string) error
Figures func() (bytes, maxBytes uint64, err error)
// Say writes the prune's journal line.
Say func(line string)
Now func() time.Time
mu sync.Mutex
bytes, limit uint64
}
// Bind reads the entry's figures once, the base of the running sum Wrote keeps.
func (p *Pruner) Bind() error {
bytes, limit, err := p.Figures()
if err != nil {
return fmt.Errorf("the state %s's fill could not be read for its prune: %w", p.State, err)
}
p.mu.Lock()
p.bytes, p.limit = bytes, limit
p.mu.Unlock()
return nil
}
// Wrote adds the bytes a write put to the running sum and prunes when it passes the mark: the answer is the prune it
// ran, or nil.
func (p *Pruner) Wrote(n uint64) (*Pruned, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.bytes += n
if !p.Prune.Passed(p.bytes, p.limit) {
return nil, nil
}
r, err := p.pruneLocked(p.bytes, p.limit, true)
return &r, err
}
// Filled judges the fill a write's answer carries and prunes when it passes the mark: the answer is the prune it ran,
// or nil.
func (p *Pruner) Filled(f buscalls.Fill) (*Pruned, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.bytes, p.limit = f.Bytes, f.MaxBytes
if !p.Prune.Passed(f.Bytes, f.MaxBytes) {
return nil, nil
}
r, err := p.pruneLocked(f.Bytes, f.MaxBytes, false)
return &r, err
}
// PruneNow reads the figures and prunes to the target now.
func (p *Pruner) PruneNow() (Pruned, error) {
bytes, limit, err := p.Figures()
if err != nil {
return Pruned{State: p.State}, fmt.Errorf("the state %s's fill could not be read for its prune: %w", p.State, err)
}
p.mu.Lock()
defer p.mu.Unlock()
if limit == 0 {
return Pruned{State: p.State}, fmt.Errorf("the state %s names no cap, so it has no target to prune to", p.State)
}
return p.pruneLocked(bytes, limit, true)
}
// pruneLocked removes the oldest keys from bytes down to the target of limit; reread reads the figures after it, the
// new base of the running sum.
func (p *Pruner) pruneLocked(bytes, limit uint64, reread bool) (Pruned, error) {
r := Pruned{State: p.State, From: bytes, MaxBytes: limit, Mark: p.Prune.Mark, Target: p.Prune.Target}
entries, err := p.Entries()
if err != nil {
return r, fmt.Errorf("the state %s could not be read for its prune: %w", p.State, err)
}
// The running sum is an upper bound (an overwrite's past value is the bucket's history to bound), so what the
// current values hold is the start when it is lower.
var held uint64
for _, e := range entries {
held += e.Bytes
}
start := min(bytes, held)
now := time.Now
if p.Now != nil {
now = p.Now
}
drop, kept := p.Prune.Choose(entries, now(), start, limit)
r.Kept, r.To = kept, start
sizes := map[string]uint64{}
for _, e := range entries {
sizes[e.Key] = e.Bytes
}
var errs []error
for _, key := range drop {
if err := p.Remove(key); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", key, err))
continue
}
r.Removed++
r.To -= min(r.To, sizes[key])
}
if reread {
if b, l, err := p.Figures(); err == nil {
r.To, r.MaxBytes = b, l
} else {
errs = append(errs, fmt.Errorf("the fill after the prune: %w", err))
}
}
p.bytes, p.limit = r.To, r.MaxBytes
if p.Say != nil {
p.Say(r.Line())
}
if len(errs) > 0 {
return r, fmt.Errorf("the prune of the state %s: %w", p.State, errors.Join(errs...))
}
return r, nil
}
// PutOverhead is what a write puts on the bus beside its key and its value, an upper bound: the bucket's subject
// prefix, the message's headers and its record.
const PutOverhead = 96
// PutBytes is what a write of value under key puts on the bus, as the prune helper counts it.
func PutBytes(key string, value []byte) uint64 { return uint64(len(key) + len(value) + PutOverhead) }
// PrunedState is a state a bundle prunes at its writes (§812): Put judges the fill the runtime's put answer carries
// (DMC-14, H-A-386) and prunes when it passes the mark. Its other calls are the state's own.
type PrunedState struct {
KeptState
pruner *Pruner
unsaid sync.Once
}
// Pruned is the state pruned by p at its writes.
func (s KeptState) Pruned(p Prune) *PrunedState {
ps := &PrunedState{KeptState: s}
ps.pruner = &Pruner{State: s.name, Prune: p, Say: func(line string) { sayf("%s", line) },
Remove: s.Delete,
Figures: func() (uint64, uint64, error) {
i, err := s.Info()
if err != nil {
return 0, 0, err
}
return i.Bytes, uint64(max(i.MaxBytes, 0)), nil
},
Entries: func() ([]PruneEntry, error) {
var out []PruneEntry
cursor := ""
for {
page, err := s.page(cursor, 768<<10, stateTimeout/2)
if err != nil {
return nil, err
}
for _, e := range page.Entries {
out = append(out, PruneEntry{Key: e.Key, Revision: e.Revision, Bytes: PutBytes(e.Key, e.Value), Value: e.Value})
}
if page.Next == "" || page.Next == cursor {
return out, nil
}
cursor = page.Next
}
}}
return ps
}
// Put writes a key whole and returns the revision written; the fill its answer carries is judged, and past the mark
// the state is pruned to its target before Put returns. A runtime whose answer carries no fill is said once, as a
// state that is never pruned.
func (s *PrunedState) Put(key string, value any) (uint64, error) {
raw, err := s.ask("put", map[string]any{"key": key, "value": value})
if err != nil {
return 0, err
}
var put struct {
Revision uint64 `json:"revision"`
Fill *buscalls.Fill `json:"fill"`
}
if err := json.Unmarshal(raw, &put); err != nil {
return 0, err
}
if put.Fill == nil {
s.unsaid.Do(func() {
sayf("the state %s is never pruned: the runtime's put answer carries no fill (design 47 H2 §812)", s.name)
})
return put.Revision, nil
}
if _, err := s.pruner.Filled(*put.Fill); err != nil {
return put.Revision, err
}
return put.Revision, nil
}
// PruneNow prunes the state to its target now.
func (s *PrunedState) PruneNow() (Pruned, error) { return s.pruner.PruneNow() }
// Keep keeps key from the prune until until, written under KeepKey.
func (s *PrunedState) Keep(key string, until time.Time) error {
if err := KeepProblem(key, until); err != nil {
return err
}
_, err := s.Put(KeepKey(key), Keep{Until: until.UTC()})
return err
}
// KeepProblem is why key cannot be kept until until, or nil: a process and a bundle check a keep alike.
func KeepProblem(key string, until time.Time) error {
switch {
case key == "" || IsKeep(key):
return fmt.Errorf("%q is not a key a keep keeps", key)
case !until.After(time.Now()):
return fmt.Errorf("a keep until %s keeps nothing: until is a time still to come", until.Format(time.RFC3339))
}
return nil
}
+61
View File
@@ -0,0 +1,61 @@
package seal
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"testing"
"golang.org/x/crypto/nacl/box"
)
// anonymousFixture holds the NaCl anonymous boxes golang.org/x/crypto/nacl/box seals (the box the vault's intake opens),
// with their one-time keys, for the SDK's TypeScript sealAnonymous to make byte for byte (design 47 H2, H-A-407).
type anonymousFixture struct {
About string `json:"about"`
Recipient struct {
Public string `json:"public"`
Private string `json:"private"`
} `json:"recipient"`
Vectors []struct {
Plaintext string `json:"plaintext"`
EphSecret string `json:"ephSecret"`
Sealed string `json:"sealed"`
} `json:"vectors"`
}
const anonymousFixturePath = "testdata/sealed-anonymous-by-go.json"
// anonymousVectors seals each plaintext with box.SealAnonymous to a recipient and one-time keys derived from fixed
// labels: test keys that guard nothing.
func anonymousVectors(t *testing.T) anonymousFixture {
t.Helper()
b64 := base64.StdEncoding.EncodeToString
seed := sha256.Sum256([]byte("mesh-sdk anonymous box test recipient"))
pub, priv, err := box.GenerateKey(bytes.NewReader(seed[:]))
if err != nil {
t.Fatal(err)
}
var f anonymousFixture
f.About = "Made by this package's anonymous_test.go with golang.org/x/crypto/nacl/box's SealAnonymous, its one-time keys fixed; the test proves the file is Go's bytes on every run. Test keys; they guard nothing."
f.Recipient.Public, f.Recipient.Private = b64(pub[:]), b64(priv[:])
for i, plain := range []string{"", "a token minted for the forge", "ünïcode and a longer value: " + string(bytes.Repeat([]byte("x"), 300))} {
eph := sha256.Sum256([]byte{byte(i), 'e', 'p', 'h'})
sealed, err := box.SealAnonymous(nil, []byte(plain), pub, bytes.NewReader(eph[:]))
if err != nil {
t.Fatal(err)
}
f.Vectors = append(f.Vectors, struct {
Plaintext string `json:"plaintext"`
EphSecret string `json:"ephSecret"`
Sealed string `json:"sealed"`
}{plain, b64(eph[:]), b64(sealed)})
}
return f
}
func mustJSON(v any) string {
raw, _ := json.Marshal(v)
return string(raw)
}
+68 -35
View File
@@ -6,6 +6,8 @@ import (
"encoding/json"
"os"
"testing"
"golang.org/x/crypto/nacl/box"
)
type fixture struct {
@@ -75,6 +77,39 @@ func TestSealIsByteForByteTheLicenceManagersBox(t *testing.T) {
t.Fatalf("reopened %q, %v", plain, err)
}
}
// The anonymous-box fixture the TypeScript tests read is what box.SealAnonymous makes, and each opens with the
// recipient's key as the vault's intake opens it (box.OpenAnonymous). MESH_SDK_WRITE_FIXTURES=1 writes it anew.
t.Run("the anonymous box fixture is Go's bytes", func(t *testing.T) {
want := anonymousVectors(t)
if os.Getenv("MESH_SDK_WRITE_FIXTURES") == "1" {
raw, _ := json.MarshalIndent(want, "", " ")
if err := os.WriteFile(anonymousFixturePath, append(raw, '\n'), 0o644); err != nil {
t.Fatal(err)
}
}
raw, err := os.ReadFile(anonymousFixturePath)
if err != nil {
t.Fatal(err)
}
var got anonymousFixture
if err := json.Unmarshal(raw, &got); err != nil {
t.Fatal(err)
}
if g, w := mustJSON(got), mustJSON(want); g != w {
t.Fatalf("the fixture is not Go's bytes:\n%s\nwant\n%s", g, w)
}
var pub, priv [32]byte
p, _ := base64.StdEncoding.DecodeString(got.Recipient.Public)
k, _ := base64.StdEncoding.DecodeString(got.Recipient.Private)
copy(pub[:], p)
copy(priv[:], k)
for _, v := range got.Vectors {
sealed, _ := base64.StdEncoding.DecodeString(v.Sealed)
if out, ok := box.OpenAnonymous(nil, sealed, &pub, &priv); !ok || string(out) != v.Plaintext {
t.Errorf("a box does not open to %q: %q, %v", v.Plaintext, out, ok)
}
}
})
}
// A box the agent module's TypeScript sealed (the fixture the licence manager keeps) opens here too.
@@ -117,40 +152,38 @@ func TestABoxOpensOnlyForItsRecipient(t *testing.T) {
if again.Eph == box.Eph || again.IV == box.IV {
t.Fatal("two boxes share a one-time key or iv")
}
}
// A box changed in any field, or of another version, does not open.
func TestATamperedBoxDoesNotOpen(t *testing.T) {
f := readFixture(t)
good := f.Sealed[1].Box
flip := func(s string) string {
b, _ := base64.StdEncoding.DecodeString(s)
b[len(b)-1] ^= 1
return base64.StdEncoding.EncodeToString(b)
}
for name, box := range map[string]Box{
"ct": {V: 1, Eph: good.Eph, IV: good.IV, Tag: good.Tag, Ct: flip(good.Ct)},
"tag": {V: 1, Eph: good.Eph, IV: good.IV, Tag: flip(good.Tag), Ct: good.Ct},
"iv": {V: 1, Eph: good.Eph, IV: flip(good.IV), Tag: good.Tag, Ct: good.Ct},
"eph": {V: 1, Eph: flip(good.Eph), IV: good.IV, Tag: good.Tag, Ct: good.Ct},
"version": {V: 2, Eph: good.Eph, IV: good.IV, Tag: good.Tag, Ct: good.Ct},
} {
if _, err := Open(box, f.Recipient.PrivateKey); err == nil {
t.Fatalf("a box with a changed %s opened", name)
// A box changed in any field, or of another version, does not open.
t.Run("a tampered box does not open", func(t *testing.T) {
f := readFixture(t)
good := f.Sealed[1].Box
flip := func(s string) string {
b, _ := base64.StdEncoding.DecodeString(s)
b[len(b)-1] ^= 1
return base64.StdEncoding.EncodeToString(b)
}
}
}
// A key that is not X25519 PEM is refused, not misread.
func TestAKeyOfAnotherKindIsRefused(t *testing.T) {
if _, err := Seal("x", "not a key"); err == nil {
t.Fatal("sealed to text")
}
f := readFixture(t)
if _, err := Open(f.Sealed[0].Box, f.Recipient.PublicKey); err == nil {
t.Fatal("opened with a public key")
}
if _, err := Seal("x", f.Recipient.PrivateKey); err == nil {
t.Fatal("sealed to a private key")
}
for name, box := range map[string]Box{
"ct": {V: 1, Eph: good.Eph, IV: good.IV, Tag: good.Tag, Ct: flip(good.Ct)},
"tag": {V: 1, Eph: good.Eph, IV: good.IV, Tag: flip(good.Tag), Ct: good.Ct},
"iv": {V: 1, Eph: good.Eph, IV: flip(good.IV), Tag: good.Tag, Ct: good.Ct},
"eph": {V: 1, Eph: flip(good.Eph), IV: good.IV, Tag: good.Tag, Ct: good.Ct},
"version": {V: 2, Eph: good.Eph, IV: good.IV, Tag: good.Tag, Ct: good.Ct},
} {
if _, err := Open(box, f.Recipient.PrivateKey); err == nil {
t.Fatalf("a box with a changed %s opened", name)
}
}
})
// A key that is not X25519 PEM is refused, not misread.
t.Run("a key of another kind is refused", func(t *testing.T) {
if _, err := Seal("x", "not a key"); err == nil {
t.Fatal("sealed to text")
}
f := readFixture(t)
if _, err := Open(f.Sealed[0].Box, f.Recipient.PublicKey); err == nil {
t.Fatal("opened with a public key")
}
if _, err := Seal("x", f.Recipient.PrivateKey); err == nil {
t.Fatal("sealed to a private key")
}
})
}
+24
View File
@@ -0,0 +1,24 @@
{
"about": "Made by this package's anonymous_test.go with golang.org/x/crypto/nacl/box's SealAnonymous, its one-time keys fixed; the test proves the file is Go's bytes on every run. Test keys; they guard nothing.",
"recipient": {
"public": "n2nWtTM35RrjXe1pPBzIHWRfSvoE5AMFxFWA92lYmj4=",
"private": "0zveHnrRJV0at3GITmix/NpjX1sJPgsu0tGZIXFVKos="
},
"vectors": [
{
"plaintext": "",
"ephSecret": "CU2adSGwGEEx6/xxSvrQ8Vfq6Yc+kR+2yX7fFriYCbg=",
"sealed": "8qO+LLqjzgOtuE2KVM6bKDB3dMiMiAuEc0hgRwGe03wNBJ60VwAAIw4xPJLmmT1g"
},
{
"plaintext": "a token minted for the forge",
"ephSecret": "CvmgsKRsGyTmAFRD4EB0mAPpBVN3I4yLJJkkcfbqX0A=",
"sealed": "erK5lMtu+k90Thig1rpUq2jJ9DzF/WZWvVvMPNO+hiPF5uL5jnqNB7h3hQro13ZiKwK4O/hm3MvZm9glM8KqSBoeApTrVWnvP/Ekzg=="
},
{
"plaintext": "ünïcode and a longer value: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ephSecret": "ypSqdS+hEEoCsEDT6K87sc/I/h9yi06j08c1bKEJAQw=",
"sealed": "QQ7wBpBtvQH4BvkicANk50VlTJ/puVD+BhRgD9ccAl6NriByxkFqxb3GQUy++HAhByqR9vd+NSSt59dVmjKIFdiiJKCvH6zgGWkHEcVBtn1F5PUzscO+yhEwxuuPK1pLJ24PBdcef9x111Yu4aKgG31mt5z0Bnxs9YZAobz8Nx2vkPYfz1Fzu6Tqqq9bElH9rbR/Ua+ChpGu0BgnKgAWRQlnXBOjrVUC4DFa4wFDfCROgFWC1rM3fQCd8Tm4OHpa6RMRhE9pafi8OMP0XIwUrL29JDkcyMtGPuDab3f6NTgGI+yTCHxNgbOupxeA18Ied7om9rt1oAsEfo2SrYEvzplFCgYpDuXmf693zNPFKuGHd18FZmQKwp6gODpO2t+UCEzJa5EB/9vaf44BWcRIDLWiLzx2Pg0QA3DxZziSL4eff9TOeN8qUHH5pYdU5Cdu7clbhImNoe9kqNSZb3NOwav+HZh4SjtfzcHrBTMWbKs8i0jZYLgxcEcr"
}
]
}
+70
View File
@@ -2,6 +2,8 @@ package stdio
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
@@ -201,6 +203,38 @@ func (s KeptState) CreateTTL(key string, value any, ttl time.Duration) (uint64,
return s.revisionOf(s.ask("create", map[string]any{"key": key, "value": value, "ttl_seconds": ttlSeconds(ttl)}))
}
// TakenState is the state a holder of a kept call keeps the ids of the asks it took in (design 47 H2 §775, §820): a
// state of 8 MiB whose keys live the ask's bound and are deleted by their time to live alone, never pruned.
const TakenState = "taken"
// TakenKey is the key an ask taken from seat is kept under in TakenState: `<seat>.<ask>`.
func TakenKey(seat, ask string) string { return seat + "." + ask }
// TakenProblem is why seat and ask name no taken key, or empty: a seat's name and an ask's id are each one key token.
func TakenProblem(seat, ask string) string {
switch {
case ask == "" || strings.ContainsAny(ask, ".*> "):
return fmt.Sprintf("%q is not an ask id: an ask id holds no dot and no wildcard, naming one key and no other", ask)
case seat == "" || strings.ContainsAny(seat, ".*> "):
return fmt.Sprintf("%q is not a seat's name", seat)
}
return ""
}
// TakeOnce says whether this holder takes the ask ask of seat now (design 47 H2 §775; ADR 0668 §2; H-A-359): the
// first time it is given it is kept under TakenKey for the ask's bound and TakeOnce answers true; given again within
// the bound, false, and the holder acts once. s is the holder's TakenState, declared `key-ttl`.
func (s KeptState) TakeOnce(seat, ask string, bound time.Duration) (bool, error) {
if p := TakenProblem(seat, ask); p != "" {
return false, fmt.Errorf("taking an ask of %s: %s", seat, p)
}
_, err := s.CreateTTL(TakenKey(seat, ask), map[string]string{"seat": seat, "ask": ask}, max(bound, time.Second))
if errors.Is(err, ErrChanged) {
return false, nil
}
return err == nil, err
}
// Update writes a key only when it is still at revision, and returns the new one; a key changed
// meanwhile is refused, so of two writers that read one value only the first writes.
func (s KeptState) Update(key string, value any, revision uint64) (uint64, error) {
@@ -230,3 +264,39 @@ func subjectMatches(pattern, subject string) bool {
}
return len(p) == len(s)
}
// WaitingAsk is one ask waiting in a seat's work queue, as the runtime reads it without taking it (design 47 H2 §777,
// H-A-410): the ask's id, the module that asked it and its age in seconds. Again says it was handed out and handed back
// (a nak) and no worker holds it: waiting again (H-A-410's addendum).
type WaitingAsk struct {
ID string `json:"id"`
Module string `json:"module"`
AgeSeconds float64 `json:"age_seconds"`
Again bool `json:"again,omitempty"`
}
// Waiting is the asks waiting in a seat's work queue, oldest first as the queue holds them; Capped says the runtime cut
// them at 768 KB.
type Waiting struct {
Asks []WaitingAsk `json:"asks"`
Capped bool `json:"capped"`
}
// QueueWaiting is the asks waiting in the work queue of seat, this holder's own queue, which a holder's asks tool answers
// (design 47 H2 §777, H-A-410): asked of the runtime as mesh/queue.waiting, which reads the queue's waiting messages
// without taking them. A refusal is the runtime's error.
func QueueWaiting(seat string) (Waiting, error) {
c, err := live()
if err != nil {
return Waiting{}, err
}
raw, err := c.ask("mesh/queue.waiting", map[string]any{"seat": seat}, seatTimeout)
if err != nil {
return Waiting{}, err
}
var w Waiting
if err := json.Unmarshal(raw, &w); err != nil {
return Waiting{}, fmt.Errorf("the runtime answered the waiting asks of %s in no form this reads: %w", seat, err)
}
return w, nil
}
-187
View File
@@ -1,187 +0,0 @@
package seatdef
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
)
// Callers says who may call a verb or send an accepted kind. It is read as text (the form every definition on main
// has) or as a list (the form design 47 G §336 writes); the reader release carries both so that a definition in
// either form is read (design 47 G §340), and G's own reader refuses the text.
type Callers struct {
// Text is the callers in words, when the definition gave them so.
Text string
// List is the callers as a list of entries, when the definition gave them so.
List []string
}
// IsText says whether the definition gave its callers in words.
func (c Callers) IsText() bool { return c.List == nil }
// UnmarshalJSON reads a string or a list of strings.
func (c *Callers) UnmarshalJSON(raw []byte) error {
raw = bytes.TrimSpace(raw)
switch {
case len(raw) > 0 && raw[0] == '"':
return json.Unmarshal(raw, &c.Text)
case len(raw) > 0 && raw[0] == '[':
c.List = []string{}
return json.Unmarshal(raw, &c.List)
}
return errors.New("callers is a text or a list of entries")
}
// MarshalJSON writes the form the definition was read in.
func (c Callers) MarshalJSON() ([]byte, error) {
if c.IsText() {
return json.Marshal(c.Text)
}
return json.Marshal(c.List)
}
func checkCallers(where string, c *Callers) Problems {
if c == nil {
return nil
}
if c.IsText() {
if c.Text == "" {
return Problems{{where, "is empty"}}
}
return nil
}
var ps Problems
for i, e := range c.List {
if why := CallerEntryProblem(e); why != "" {
ps = append(ps, Problem{fmt.Sprintf("%s[%d]", where, i), why})
}
}
return ps
}
// The entries of a list of callers that are not a name (design 47 G §336).
const (
CallerOperator = "operator"
CallerHealers = "healers"
CallerPersons = "persons"
CallerSessions = "sessions"
CallerInvokers = "invokers"
)
// The prefixes of the entries that name a seat's holder or a module (design 47 G §392, §336).
const (
CallerSeatPrefix = "seat:"
CallerModulePrefix = "module:"
CallerHolderPrefix = "holder:"
CallerSameNode = "@same-node"
)
// CallerEntryProblem says why an entry of a list of callers is none of the forms of design 47 G §336, §392; empty
// when it is one: `operator`, `healers`, `persons`, `sessions`, `invokers`, `seat:<seat>`, `module:<module>` and
// `holder:<seat>@same-node`. A bare name is refused, since a name such as `mesh-grants` is both a seat and a module.
func CallerEntryProblem(e string) string {
switch e {
case CallerOperator, CallerHealers, CallerPersons, CallerSessions, CallerInvokers:
return ""
}
if n, ok := strings.CutPrefix(e, CallerSeatPrefix); ok && wordName.MatchString(n) {
return ""
}
if n, ok := strings.CutPrefix(e, CallerModulePrefix); ok && wordName.MatchString(n) {
return ""
}
if n, ok := strings.CutPrefix(e, CallerHolderPrefix); ok {
if seat, ok := strings.CutSuffix(n, CallerSameNode); ok && wordName.MatchString(seat) {
return ""
}
}
return fmt.Sprintf("%q is none of operator, healers, persons, sessions, invokers, seat:<seat>, module:<module> and "+
"holder:<seat>@same-node", e)
}
// DefaultCallers are the callers a verb that names none takes by its class (design 47 G §610, amending §391): a read takes
// invokers, persons and sessions; an act, a warrant and an accepted kind (`accept`) the operator, sessions and invokers. A
// verb that names no class is a read.
func DefaultCallers(class string) []string {
switch class {
case ClassAct, ClassWarrant, "accept":
return []string{CallerOperator, CallerSessions, CallerInvokers}
}
return []string{CallerInvokers, CallerPersons, CallerSessions}
}
// EffectiveCallers are the callers the verb is open to: the list it names, or the default of its class. A verb whose
// callers are text, as the definitions before G wrote them, names no list and takes the default.
func (v Verb) EffectiveCallers() []string {
if v.Callers != nil && !v.Callers.IsText() {
return v.Callers.List
}
return DefaultCallers(v.Class)
}
// The classes of a verb (design 47 G §391).
const (
ClassRead = "read"
ClassAct = "act"
ClassWarrant = "warrant"
)
// Classes are the classes a verb's `class` may name.
var Classes = []string{ClassRead, ClassAct, ClassWarrant}
// Keep is an event's `keep`: the string of today's definitions (KeepLastPerSubject or KeepStream, with the message's
// max-age-days and max-mib beside it) or the object of design 47 G §396 (`max-age-days`, `max-mib`,
// `last-per-subject`). The reader release reads both (design 47 G §340, §409).
type Keep struct {
// Mode is the string form; empty when the object form was given.
Mode string
// MaxAgeDays, MaxMiB and LastPerSubject are the object form's fields; MaxAgeDays and MaxMiB are nil when unsaid.
MaxAgeDays *int
MaxMiB *int
LastPerSubject bool
// Object says the object form was given.
Object bool
}
type keepObject struct {
MaxAgeDays *int `json:"max-age-days"`
MaxMiB *int `json:"max-mib"`
LastPerSubject bool `json:"last-per-subject"`
}
// UnmarshalJSON reads the string or the object, the object strictly.
func (k *Keep) UnmarshalJSON(raw []byte) error {
raw = bytes.TrimSpace(raw)
if len(raw) > 0 && raw[0] == '"' {
return json.Unmarshal(raw, &k.Mode)
}
var o keepObject
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&o); err != nil {
return fmt.Errorf("keep is a string or an object of max-age-days, max-mib and last-per-subject: %w", err)
}
*k = Keep{MaxAgeDays: o.MaxAgeDays, MaxMiB: o.MaxMiB, LastPerSubject: o.LastPerSubject, Object: true}
return nil
}
// MarshalJSON writes the form the definition was read in.
func (k Keep) MarshalJSON() ([]byte, error) {
if !k.Object {
return json.Marshal(k.Mode)
}
return json.Marshal(keepObject{k.MaxAgeDays, k.MaxMiB, k.LastPerSubject})
}
func checkKeepObject(where string, k Keep) Problems {
var ps Problems
if k.MaxAgeDays != nil && *k.MaxAgeDays < 0 {
ps = append(ps, Problem{where + ".max-age-days", "is negative (0 is no age limit)"})
}
if k.MaxMiB != nil && *k.MaxMiB <= 0 {
ps = append(ps, Problem{where + ".max-mib", "is not above zero"})
}
return ps
}
+72
View File
@@ -0,0 +1,72 @@
package seatdef
import (
"bytes"
"encoding/json"
"fmt"
)
// The classes of a verb (design 47 G §391).
const (
ClassRead = "read"
ClassAct = "act"
ClassWarrant = "warrant"
)
// Classes are the classes a verb's `class` may name.
var Classes = []string{ClassRead, ClassAct, ClassWarrant}
// Keep is an event's `keep`: the string of today's definitions (KeepLastPerSubject or KeepStream, with the message's
// max-age-days and max-mib beside it) or the object of design 47 G §396 (`max-age-days`, `max-mib`,
// `last-per-subject`). The reader release reads both (design 47 G §340, §409).
type Keep struct {
// Mode is the string form; empty when the object form was given.
Mode string
// MaxAgeDays, MaxMiB and LastPerSubject are the object form's fields; MaxAgeDays and MaxMiB are nil when unsaid.
MaxAgeDays *int
MaxMiB *int
LastPerSubject bool
// Object says the object form was given.
Object bool
}
type keepObject struct {
MaxAgeDays *int `json:"max-age-days"`
MaxMiB *int `json:"max-mib"`
LastPerSubject bool `json:"last-per-subject"`
}
// UnmarshalJSON reads the string or the object, the object strictly.
func (k *Keep) UnmarshalJSON(raw []byte) error {
raw = bytes.TrimSpace(raw)
if len(raw) > 0 && raw[0] == '"' {
return json.Unmarshal(raw, &k.Mode)
}
var o keepObject
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&o); err != nil {
return fmt.Errorf("keep is a string or an object of max-age-days, max-mib and last-per-subject: %w", err)
}
*k = Keep{MaxAgeDays: o.MaxAgeDays, MaxMiB: o.MaxMiB, LastPerSubject: o.LastPerSubject, Object: true}
return nil
}
// MarshalJSON writes the form the definition was read in.
func (k Keep) MarshalJSON() ([]byte, error) {
if !k.Object {
return json.Marshal(k.Mode)
}
return json.Marshal(keepObject{k.MaxAgeDays, k.MaxMiB, k.LastPerSubject})
}
func checkKeepObject(where string, k Keep) Problems {
var ps Problems
if k.MaxAgeDays != nil && *k.MaxAgeDays < 0 {
ps = append(ps, Problem{where + ".max-age-days", "is negative (0 is no age limit)"})
}
if k.MaxMiB != nil && *k.MaxMiB <= 0 {
ps = append(ps, Problem{where + ".max-mib", "is not above zero"})
}
return ps
}
-1
View File
@@ -38,6 +38,5 @@ func subResolveRefsPutsNamedTypesInPlace(t *testing.T) {
// TestResolveRefsPutsNamedTypesInPlace runs the tests of this package that were merged to keep the module within its test budget (design 47 G §419), each as a subtest.
func TestResolveRefsPutsNamedTypesInPlace(t *testing.T) {
t.Run("ResolveRefsPutsNamedTypesInPlace", subResolveRefsPutsNamedTypesInPlace)
t.Run("AVerbWithoutCallersTakesItsClassDefault", subAVerbWithoutCallersTakesItsClassDefault)
t.Run("AKeptEventsStreamIsNamedAndBoundedByItsKeep", subAKeptEventsStreamIsNamedAndBoundedByItsKeep)
}
+72 -14
View File
@@ -49,10 +49,13 @@ var Domains = []string{"Module", "Config", "Core", "Provisioning", "Identity and
// Definition is one seat's contract.
type Definition struct {
Format int `json:"format"`
Seat string `json:"seat"`
Scope string `json:"scope"`
Grain string `json:"grain"`
Format int `json:"format"`
// Form is the definition's form (design 47 H2 §780; H-A-352): raised at every field its values, events, accepts and
// answers add or remove. Absent reads 1; below 1 is refused.
Form int `json:"form,omitempty"`
Seat string `json:"seat"`
Scope string `json:"scope"`
Grain string `json:"grain"`
// Decision is the record that made it a seat.
Decision string `json:"decision"`
// Domain is the glossary domain the seat belongs to, by its heading (ADR 0636 §5): the indexer takes a seat of the
@@ -214,8 +217,6 @@ type Verb struct {
Replaces []string `json:"replaces,omitempty"`
Input map[string]any `json:"input,omitempty"`
Answer map[string]any `json:"answer,omitempty"`
// Callers says who may call it, as a list (design 47 G §336) or, in the definitions before G, in words.
Callers *Callers `json:"callers,omitempty"`
// Class is the verb's class, ClassRead, ClassAct or ClassWarrant (design 47 G §391).
Class string `json:"class,omitempty"`
// NeedsApproval marks the verb for every holder: the operator approves a call of it first (design 46 *The approval
@@ -227,8 +228,17 @@ type Verb struct {
// Chunks says the holder's process sends the answer's file in chunks, each acknowledged by the caller, on the
// subjects mesh.seat.<seat>.chunk.<verb>.<call>.<n> and mesh.seat.<seat>.ack.<verb>.<call>.<n> (design 47 G §681).
Chunks bool `json:"chunks,omitempty"`
// Timeout is the most whole seconds, MinTimeout to MaxTimeout, a caller and the serving tool runner wait for the
// verb's answer; nil, the tool runner's own bound (30 seconds; design 47 H §760, H-A-43).
Timeout *int `json:"timeout,omitempty"`
}
// The bounds of a verb's Timeout, in whole seconds (design 47 H-A-43).
const (
MinTimeout = 1
MaxTimeout = 600
)
// The streams an accepted kind may ride (design 47 G §415).
const (
StreamCheck = "check"
@@ -254,12 +264,44 @@ type Message struct {
// node-engine's running.<node>.<module>, so the last build of every module on every node stays on the bus however
// long ago it was said). An event with a Keep has no dot in its name.
Keep *Keep `json:"keep,omitempty"`
// Callers says who may send an accepted kind, as a verb's (design 47 G §338).
Callers *Callers `json:"callers,omitempty"`
// Stream is the stream an accepted kind rides, StreamCheck or StreamDelivery: its queue, and its subject is the queue's,
// `accept.<stream>`, the kind in the body alone (design 47 G §600, A-170). Its generated names and an invoke name it
// `<stream>.<kind>`, so the same kind name may ride more than one stream (design 47 G §415).
Stream string `json:"stream,omitempty"`
// The work queue's settings an accepted kind names (design 47 H2 §777; H-A-350 DMC-1, H-A-362), from which mesh-sdk's
// buscompose derives the seat's work-queue stream and its one shared worker: durations as Go writes them ("24h",
// "2m", "60s", "20s"), counts as integers. Each absent is buscompose's default.
MaxAge string `json:"max-age,omitempty"`
DuplicatesWindow string `json:"duplicates-window,omitempty"`
AckWait string `json:"ack-wait,omitempty"`
InProgress string `json:"in-progress,omitempty"`
MaxMsgs int `json:"max-msgs,omitempty"`
MaxAckPending int `json:"max-ack-pending,omitempty"`
MaxDeliveries int `json:"max-deliveries,omitempty"`
}
// QueueProblems is what is wrong with an accepted kind's work-queue settings: a duration that is not one above zero, or
// a count below zero.
func (m Message) QueueProblems(where string) Problems {
var ps Problems
for _, d := range []struct{ name, value string }{{"max-age", m.MaxAge}, {"duplicates-window", m.DuplicatesWindow},
{"ack-wait", m.AckWait}, {"in-progress", m.InProgress}} {
if d.value == "" {
continue
}
if v, err := time.ParseDuration(d.value); err != nil || v <= 0 {
ps = append(ps, Problem{where + "." + d.name, fmt.Sprintf("%q is not a duration above zero, as \"24h\" or \"60s\"", d.value)})
}
}
for _, n := range []struct {
name string
value int
}{{"max-msgs", m.MaxMsgs}, {"max-ack-pending", m.MaxAckPending}, {"max-deliveries", m.MaxDeliveries}} {
if n.value < 0 {
ps = append(ps, Problem{where + "." + n.name, fmt.Sprintf("%d is below zero", n.value)})
}
}
return ps
}
// What an event's keep says where it says less (design 47 G §396, §331).
@@ -463,7 +505,9 @@ type Path struct {
// Part is verbs, events and types several definitions include whole.
type Part struct {
Format int `json:"format"`
Format int `json:"format"`
// Form is the part's own form, for what it adds (H-A-352): absent reads 1; below 1 is refused.
Form int `json:"form,omitempty"`
Part string `json:"part"`
Description string `json:"description,omitempty"`
Verbs []Verb `json:"verbs,omitempty"`
@@ -523,9 +567,21 @@ func Parse(raw []byte) (Definition, error) {
if ps := d.check(); len(ps) > 0 {
return Definition{}, ps
}
d.Form = formRead(d.Form)
return d, nil
}
// formRead is a form as read: absent is 1 (H-A-352).
func formRead(n int) int { return max(n, 1) }
// formProblems refuses a form below 1; absent reads 1.
func formProblems(n int) Problems {
if n < 0 {
return Problems{{"form", fmt.Sprintf("form %d: a form is 1 or more, and absent reads 1", n)}}
}
return nil
}
// ParsePart reads one part.
func ParsePart(raw []byte) (Part, error) {
var p Part
@@ -539,11 +595,13 @@ func ParsePart(raw []byte) (Part, error) {
if !wordName.MatchString(p.Part) {
ps = append(ps, Problem{"part", "missing, or not a lower-case name"})
}
ps = append(ps, formProblems(p.Form)...)
ps = append(ps, checkVerbs(p.Verbs, true)...)
ps = append(ps, checkMessages("events", p.Events, true)...)
if len(ps) > 0 {
return Part{}, ps
}
p.Form = formRead(p.Form)
return p, nil
}
@@ -628,6 +686,7 @@ func (d Definition) check() Problems {
if d.Format != Format {
ps = append(ps, Problem{"format", formatProblem(d.Format)})
}
ps = append(ps, formProblems(d.Form)...)
if d.Seat == "" {
ps = append(ps, Problem{"seat", "missing"})
} else if !seatName.MatchString(d.Seat) {
@@ -812,7 +871,9 @@ func checkVerbs(vs []Verb, whole bool) Problems {
ps = append(ps, Problem{where + ".name", fmt.Sprintf("%q twice", v.Name)})
}
seen[v.Name] = true
ps = append(ps, checkCallers(where+".callers", v.Callers)...)
if v.Timeout != nil && (*v.Timeout < MinTimeout || *v.Timeout > MaxTimeout) {
ps = append(ps, Problem{where + ".timeout", fmt.Sprintf("%d is not whole seconds from %d to %d", *v.Timeout, MinTimeout, MaxTimeout)})
}
if v.Class != "" && !slices.Contains(Classes, v.Class) {
ps = append(ps, Problem{where + ".class", fmt.Sprintf("%q is not a class (%s)", v.Class, strings.Join(Classes, ", "))})
}
@@ -861,10 +922,7 @@ func checkMessages(field string, ms []Message, whole bool) Problems {
ps = append(ps, Problem{where + ".keep", "an event of one subject kept last per subject is one message: give it a subject with parts"})
}
}
if m.Callers != nil && field != "accepts" {
ps = append(ps, Problem{where + ".callers", "only an accepted kind carries callers"})
}
ps = append(ps, checkCallers(where+".callers", m.Callers)...)
ps = append(ps, m.QueueProblems(where)...)
if m.Subject != "" && field != "events" {
ps = append(ps, Problem{where + ".subject", "only an event carries a subject of its own"})
} else if why := checkSubject(m); why != "" {
+42 -32
View File
@@ -122,19 +122,16 @@ func TestADefinitionIsReadStrictlyNamingWhatIsWrong(t *testing.T) {
"when: a field the format does not know"},
{"one step on one language twice", strings.Replace(listGrain, `"verbs":`, `"acts":[{"step":"grant"},{"step":"grant","on":"every"}],"verbs":`, 1),
"acts[1]: the step grant on every twice"},
// The reader release (design 47 G §340, §409): the forms G writes beside the ones on main.
{"callers as text", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":"a person",`, 1), ""},
{"callers as a list", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["operator","seat:mesh-grants","invokers"],"class":"read",`, 1), ""},
{"callers as neither", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":7,`, 1), "callers is a text or a list"},
{"a list with an empty entry", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["operator",""],`, 1), "verbs[0].callers[1]"},
{"a bare name among callers", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["mesh-grants"],`, 1), `"mesh-grants" is none of operator`},
{"a class of the old branches", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["holder","invokes","reviewers"],`, 1), `"holder" is none of operator`},
{"every form among callers", strings.Replace(whole, `"name":"list",`,
`"name":"list","callers":["operator","healers","persons","sessions","invokers","seat:mesh-grants","module:mesh-grants","holder:node-backup@same-node"],`, 1), ""},
{"a holder not on the same node", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["holder:node-backup"],`, 1), "none of operator"},
{"a verb's timeout of 120 seconds", strings.Replace(whole, `"name":"list",`, `"name":"list","timeout":120,`, 1), ""},
{"a verb's timeout at either bound", strings.Replace(whole, `"name":"list",`, `"name":"list","timeout":600,`, 1), ""},
{"a verb's timeout of none", strings.Replace(whole, `"name":"list",`, `"name":"list","timeout":0,`, 1), "verbs[0].timeout: 0 is not whole seconds from 1 to 600"},
{"a verb's timeout over ten minutes", strings.Replace(whole, `"name":"list",`, `"name":"list","timeout":601,`, 1), "verbs[0].timeout: 601 is not whole seconds from 1 to 600"},
{"a verb's timeout in fractions", strings.Replace(whole, `"name":"list",`, `"name":"list","timeout":1.5,`, 1), "not a seat definition's JSON"},
{"a verb naming callers", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":["operator"],`, 1), "callers: a field the format does not know"},
{"a verb naming callers in words", strings.Replace(whole, `"name":"list",`, `"name":"list","callers":"a person",`, 1), "callers: a field the format does not know"},
{"an accepted kind naming callers", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"callers":["seat:mesh-pipeline-runner"]}],"events":`, 1), "callers: a field the format does not know"},
{"an event naming callers", strings.Replace(whole, `"name":"created"`, `"name":"created","callers":["operator"]`, 1), "callers: a field the format does not know"},
{"a class that is none", strings.Replace(whole, `"name":"list",`, `"name":"list","class":"free",`, 1), `verbs[0].class: "free" is not a class (read, act, warrant)`},
{"an accepted kind's callers", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"callers":["seat:mesh-pipeline-runner"]}],"events":`, 1), ""},
{"an event's callers", strings.Replace(whole, `"name":"created"`, `"name":"created","callers":["operator"]`, 1), "only an accepted kind carries callers"},
{"keep as an object", strings.Replace(whole, `"name":"created"`,
`"name":"owed","keep":{"max-age-days":7,"max-mib":64}`, 1), ""},
{"keep as an object with no age limit", strings.Replace(whole, `"name":"created"`,
@@ -157,6 +154,10 @@ func TestADefinitionIsReadStrictlyNamingWhatIsWrong(t *testing.T) {
`"accepts":[{"name":"step","body":{},"stream":"check"},{"name":"step","body":{},"stream":"check"}],"events":`, 1), `"step" twice`},
{"a stream that is none", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"stream":"mail"}],"events":`, 1),
`accepts[0].stream: "mail" is not check or delivery`},
// Design 47 H2 §777, H-A-362: an accepted kind names its work queue's settings, durations as Go writes them.
{"a work queue's settings", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"max-age":"24h","duplicates-window":"2m","ack-wait":"60s","in-progress":"20s","max-msgs":10000,"max-ack-pending":64,"max-deliveries":5}],"events":`, 1), ""},
{"a max age that is no duration", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"max-age":"a day"}],"events":`, 1), "accepts[0].max-age"},
{"a negative max-msgs", strings.Replace(whole, `"events":`, `"accepts":[{"name":"step","body":{},"max-msgs":-1}],"events":`, 1), "accepts[0].max-msgs"},
{"an event on a stream", strings.Replace(whole, `"name":"created"`, `"name":"created","stream":"check"`, 1), "only an accepted kind rides a stream"},
{"over 256 KiB", listGrain[:len(listGrain)-1] + `,"description":"` + strings.Repeat("x", MaxSize) + `"}`,
ErrTooLarge.Error()},
@@ -176,6 +177,35 @@ func TestADefinitionIsReadStrictlyNamingWhatIsWrong(t *testing.T) {
`"}`)); !errors.Is(err, ErrTooLarge) {
t.Errorf("over 256 KiB is ErrTooLarge, got %v", err)
}
// Design 47 H2 §780, H-A-352: a definition and a part carry their form; absent reads 1, below 1 is refused.
for _, c := range []struct {
raw string
form int
bad bool
}{
{whole, 1, false},
{strings.Replace(whole, `"seat":`, `"form":3,"seat":`, 1), 3, false},
{strings.Replace(whole, `"seat":`, `"form":-1,"seat":`, 1), 0, true},
} {
d, err := Parse([]byte(c.raw))
if c.bad != (err != nil) || (!c.bad && d.Form != c.form) || (c.bad && !strings.Contains(err.Error(), "form")) {
t.Errorf("a definition of form %d read as %d, %v", c.form, d.Form, err)
}
}
for _, c := range []struct {
raw string
form int
bad bool
}{
{`{"format":1,"part":"registry"}`, 1, false},
{`{"format":1,"form":2,"part":"registry"}`, 2, false},
{`{"format":1,"form":-2,"part":"registry"}`, 0, true},
} {
p, err := ParsePart([]byte(c.raw))
if c.bad != (err != nil) || (!c.bad && p.Form != c.form) {
t.Errorf("a part %s read as form %d, %v", c.raw, p.Form, err)
}
}
// A part is taken in whole, its verbs before the definition's own; a part not given, or a type defined twice,
// is refused.
@@ -341,26 +371,6 @@ func TestAKeptEventsStreamIsNamedFromTheSeatAndTheEvent(t *testing.T) {
}
}
// Design 47 G §391, §610: a verb that names no callers takes its class's default, a verb that names them keeps them.
func subAVerbWithoutCallersTakesItsClassDefault(t *testing.T) {
for _, c := range []struct {
verb Verb
want string
}{
{Verb{}, "invokers persons sessions"},
{Verb{Class: ClassRead}, "invokers persons sessions"},
{Verb{Class: ClassAct}, "operator sessions invokers"},
{Verb{Class: ClassWarrant}, "operator sessions invokers"},
{Verb{Class: ClassAct, Callers: &Callers{List: []string{"seat:mesh-broker"}}}, "seat:mesh-broker"},
{Verb{Class: ClassWarrant, Callers: &Callers{Text: "a person"}}, "operator sessions invokers"},
{Verb{Class: "accept"}, "operator sessions invokers"},
} {
if got := strings.Join(c.verb.EffectiveCallers(), " "); got != c.want {
t.Errorf("%+v is open to %q, want %q", c.verb, got, c.want)
}
}
}
// Design 47 G §260, §396, §331: a kept event's stream is named from the seat and the event, 90 days and 16 MiB unless
// the keep says otherwise, and 0 is no age limit.
func subAKeptEventsStreamIsNamedAndBoundedByItsKeep(t *testing.T) {
File diff suppressed because it is too large Load Diff
+8 -4
View File
@@ -56,7 +56,8 @@
"entries"
]
},
"optional": true
"optional": true,
"class": "read"
},
{
"name": "show",
@@ -67,7 +68,8 @@
"answer": {
"$ref": "#/defs/Held"
},
"optional": true
"optional": true,
"class": "read"
},
{
"name": "check",
@@ -122,7 +124,8 @@
"differences"
]
},
"optional": true
"optional": true,
"class": "read"
},
{
"name": "orphans",
@@ -147,7 +150,8 @@
"entries"
]
},
"optional": true
"optional": true,
"class": "read"
},
{
"name": "create",
File diff suppressed because it is too large Load Diff
-74
View File
@@ -266,80 +266,6 @@
}
],
"description": "the value each module on each node takes for each config key, built from the sources alone"
},
{
"name": "kept",
"template": "state",
"key-forms": [
{
"key": "<owner>.<repository>.<number>.<node>.<module>.<key>",
"value": {
"type": "object",
"description": "an approved held value, kept apart from the values mesh-config resolves, laid only over the composition of its own pull request at its head (ADR 0565 clause 5)",
"properties": {
"pull": {
"type": "string",
"description": "the pull request, owner/repository#number"
},
"head": {
"type": "string",
"description": "the head the declaration was read at"
},
"declaration": {
"type": "string",
"description": "the digest of what the declaration holds the value to; the value stays only while it is the same"
},
"node": {
"type": "string"
},
"module": {
"type": "string"
},
"key": {
"type": "string",
"description": "the config key"
},
"value": {
"description": "the value held, as the operator approved it"
},
"by": {
"type": "string"
},
"via": {
"type": "string",
"description": "where the value was proposed from"
},
"why": {
"type": "string"
},
"approved": {
"type": "string",
"description": "who approved it, as the proposal kept it"
},
"proposal": {
"type": "string",
"description": "the proposal's id"
},
"at": {
"type": "string",
"format": "date-time",
"description": "when it was kept"
}
},
"required": [
"pull",
"head",
"declaration",
"node",
"module",
"key",
"value"
]
},
"description": "one held value: the pull request (owner, repository and number, none holding a dot), the node, the module and the config key, which may hold dots"
}
],
"description": "the approved held values of open pull requests, read by the checker and the assigner's composition check"
}
]
}
@@ -1,862 +0,0 @@
{
"format": 1,
"seat": "mesh-delivery-checker",
"scope": "mesh",
"grain": "whole",
"domain": "Delivery",
"decision": "novox/hq ADR 0547",
"verbs": [
{
"name": "try",
"description": "Try pushed heads before their pull requests are opened: the checker judges them as it judges a delivery group's pull requests, each member merged onto its trunk, its unit and integration levels through the build modules, then the members' manifests, the module graph and the composition on every placed node, and owes the forge nothing. Name the group's members (each a repository and the exact commit), or one repository and its head for a try of one member. Answers the try's id at once; try-read reads where it stands. The same members at the same commits, in any order, are the answer to a second ask while that try waits or runs; at most 4 run on a build node, and 8 wait for one, mesh-wide.",
"optional": true,
"replaces": [
"sh merge-check.sh",
"docker run postgres"
],
"input": {
"properties": {
"head": {
"description": "the full commit to try, 40 or 64 hex digits, for a try of one member (instead of members)",
"type": "string"
},
"level": {
"description": "unit or integration: only this level; both when absent",
"type": "string"
},
"repository": {
"description": "<owner>/<name>, for a try of one member (instead of members)",
"type": "string"
},
"tests": {
"description": "a go test -run pattern: only those tests run, and nothing is kept",
"type": "string"
},
"trunk": {
"description": "the trunk commit to merge it onto, or the trunk's branch for its head now; the trunk's head when absent",
"type": "string"
},
"members": {
"description": "the group: one repository at most once, each at the exact commit asked and the trunk commit it is merged onto; instead of repository and head",
"type": "array",
"items": {
"type": "object",
"properties": {
"repository": {
"description": "<owner>/<name>",
"type": "string"
},
"head": {
"description": "the full commit to try, 40 or 64 hex digits",
"type": "string"
},
"trunk": {
"description": "the trunk commit to merge it onto, or the trunk's branch for its head now; the trunk's head when absent",
"type": "string"
}
},
"required": [
"repository",
"head"
]
}
}
},
"type": "object"
},
"answer": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "the try's id"
},
"state": {
"type": "string",
"description": "its state"
}
},
"required": [
"id"
]
}
},
{
"name": "try-read",
"description": "Where a try stands, as stored: queued, running, or its end (pass, fail, or error when it could not run), with what was said of it, the head and the trunk commit it was merged onto, the time it took and what failed first. Read-only.",
"optional": true,
"input": {
"properties": {
"id": {
"description": "the try's id, try-<digits>",
"type": "string"
}
},
"required": [
"id"
],
"type": "object"
},
"answer": {
"type": "object",
"description": "the try: its state, its steps and its verdict when it has one"
}
},
{
"name": "try-end",
"description": "End a try that waits or runs, as error, by hand: say why (kept in what it says). Its place among the tries is free at once and the next try of its head asks anew with a new id. A try that ended already is refused.",
"optional": true,
"input": {
"properties": {
"id": {
"description": "the try's id, try-<digits>",
"type": "string"
},
"why": {
"description": "why it is ended, in words",
"type": "string"
}
},
"required": [
"id",
"why"
],
"type": "object"
},
"answer": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "the try"
},
"ended": {
"type": "boolean",
"description": "it is ended"
}
},
"required": [
"id",
"ended"
]
}
},
{
"name": "input",
"description": "A checking program's input the checker keeps, by the sha256 of its exact bytes: the facts of a check its verdict is asked of, or the heads its seat list is asked of, as a run ask names it (its input's verb and digest). Answers the digest and the bytes, base64; a digest it keeps no input of is an error. Asked by the build module that runs the program, as its manifest's invokes grants it. Read-only.",
"optional": true,
"input": {
"type": "object",
"properties": {
"digest": {
"type": "string",
"description": "the input's sha256, 64 lowercase hex digits, as the run ask names it"
}
},
"required": [
"digest"
]
},
"answer": {
"type": "object",
"properties": {
"digest": {
"type": "string",
"description": "the digest asked"
},
"input": {
"type": "string",
"description": "the input's exact bytes, base64, so no encoding on the way changes a byte the digest covers"
}
},
"required": [
"digest",
"input"
]
}
}
],
"description": "The merge check's tries: start one, read one, end one. The seat says each check's end as checked and what the checker owes the forge as owed; the checker's other events stay under its own subjects (ADR 0620 §2).",
"family": {
"name": "mesh-delivery-checker.events",
"max-age-days": 7
},
"events": [
{
"name": "checked",
"body": {
"type": "object",
"description": "a candidate checked: its entries judged at the group's heads (design 47 *What each step says*)",
"properties": {
"group": {
"type": "string",
"description": "the group, its branch"
},
"heads": {
"type": "string",
"description": "the heads checked, 12 hex digits, as the candidate's revisions are keyed"
},
"source": {
"type": "integer",
"description": "the source revision the heads are merged onto"
},
"catalog": {
"type": "integer",
"description": "the candidate's catalog graph revision judged, by its number on the seat mesh-catalog"
},
"verdict": {
"type": "string",
"enum": [
"pass",
"fail",
"could not run"
],
"description": "pass, fail, or could not run when a part the check needs did not answer"
},
"words": {
"type": "string",
"description": "what failed first, or the part not heard"
},
"entries": {
"type": "array",
"items": {
"$ref": "#/defs/CheckedEntry"
},
"description": "the entries checked"
},
"at": {
"type": "string",
"format": "date-time",
"description": "when"
}
},
"required": [
"group",
"heads",
"verdict"
]
}
},
{
"name": "owed",
"subject": "owed.<repository>.<number>",
"body": {
"$ref": "#/defs/Owed"
},
"keep": {
"max-age-days": 7,
"max-mib": 64
}
}
],
"holder-events": [
{
"name": "verdict",
"subject": "mesh.stream.<holder>.event.verdict",
"family": "checker.asks",
"body": {
"type": "object",
"properties": {
"repository": {
"type": "string",
"description": "owner/repo"
},
"pull": {
"type": "integer",
"description": "the pull request's number, for a pull request's check"
},
"head": {
"type": "string",
"description": "the commit checked"
},
"verdict": {
"type": "string",
"description": "pass or fail"
},
"out-of-step": {
"type": "array",
"items": {
"type": "string"
},
"description": "the generated files out of step with their seat definitions, each path (design 26)"
},
"series": {
"type": "array",
"items": {
"type": "object",
"properties": {
"module": {
"type": "string",
"description": "the module whose artifact's series changes"
},
"artifact": {
"type": "string",
"description": "its artifact, or the package's ecosystem name as the module's packages name it"
},
"from": {
"type": "string",
"description": "the series on trunk"
},
"to": {
"type": "string",
"description": "the series the checked head gives it"
}
},
"required": [
"module",
"artifact",
"from",
"to"
]
},
"description": "each change of an artifact's series the checked head makes against trunk's manifests, once each (design 32); absent when it changes none"
}
},
"required": [
"repository",
"head",
"verdict"
]
}
},
{
"name": "preview.written",
"subject": "mesh.stream.<holder>.event.preview.written",
"family": "checks"
}
],
"states": [
{
"name": "verdicts",
"template": "state",
"key-forms": [
{
"key": "<group>.<heads>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"group": {
"type": "string"
},
"heads": {
"type": "string",
"description": "12 hex digits"
},
"trunk": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "repository to the trunk head merged onto"
},
"state": {
"type": "string",
"description": "running, pass or fail"
},
"failed": {
"type": "object",
"properties": {
"test": {
"type": "string"
},
"machine": {
"type": "string"
},
"words": {
"type": "string"
}
}
},
"failures": {
"type": "array",
"items": {
"type": "object",
"properties": {
"test": {
"type": "string"
},
"machine": {
"type": "string"
},
"words": {
"type": "string"
}
}
}
},
"levels": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"run": {
"type": "integer"
},
"kept": {
"type": "integer"
},
"skipped": {
"type": "integer"
}
},
"required": [
"run",
"kept"
]
},
"description": "by level, unit or integration"
},
"took": {
"type": "object",
"properties": {
"queue": {
"type": "integer"
},
"clone": {
"type": "integer"
},
"unit": {
"type": "integer"
},
"lint": {
"type": "integer"
},
"integration-setup": {
"type": "integer"
},
"integration-run": {
"type": "integer"
},
"composition": {
"type": "integer"
}
},
"description": "milliseconds"
},
"machines": {
"type": "array",
"items": {
"type": "string"
}
},
"sdk": {
"type": "string"
},
"composition": {
"type": "object",
"properties": {
"state": {
"type": "string",
"description": "not-run, pass or fail"
},
"words": {
"type": "string"
},
"sdk": {
"type": "string"
},
"machines": {
"type": "array",
"items": {
"type": "string"
}
},
"fpset": {
"type": "string"
}
},
"required": [
"state"
]
},
"over-bound": {
"type": "array",
"items": {
"type": "string"
}
},
"beside": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"carried-from": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"series": {
"type": "array",
"items": {
"type": "object",
"properties": {
"module": {
"type": "string"
},
"artifact": {
"type": "string"
},
"from": {
"type": "string"
},
"to": {
"type": "string"
}
},
"required": [
"module",
"artifact",
"from",
"to"
]
}
},
"judged-by": {
"type": "object",
"description": "the checking program that judged the check: where it was built, the key its build is kept under, whether this check's run built it, and the heads it read (ADR 0644, ADR 0656). Absent in a value written before it",
"properties": {
"program": {
"type": "object",
"properties": {
"repository": {
"type": "string"
},
"commit": {
"type": "string"
},
"dir": {
"type": "string"
},
"package": {
"type": "string"
}
},
"required": [
"repository",
"commit",
"dir",
"package"
]
},
"key": {
"type": "string",
"description": "program- and 16 hex digits"
},
"built": {
"type": "boolean"
},
"heads": {
"type": "array",
"items": {
"type": "object",
"properties": {
"repository": {
"type": "string"
},
"commit": {
"type": "string"
}
},
"required": [
"repository",
"commit"
]
}
}
},
"required": [
"program",
"key",
"heads"
]
}
},
"required": [
"group",
"heads",
"state"
],
"description": "one check of a group at one set of heads"
},
"description": "one check of a group; the group is an escaped branch name, heads 12 hex digits"
}
],
"description": "the checker's verdict of each group at each set of heads",
"history": 5
},
{
"name": "kept",
"template": "state",
"key-forms": [
{
"key": "<level>.<digest>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"state": {
"type": "string",
"description": "pass: a failure is never kept"
},
"repository": {
"type": "string"
},
"package": {
"type": "string"
},
"level": {
"type": "string"
},
"tests": {
"type": "integer"
},
"took": {
"type": "integer"
},
"toolchain": {
"type": "string"
},
"at": {
"type": "string",
"description": "when (RFC 3339 time)"
}
},
"required": [
"state",
"repository",
"package",
"level"
],
"description": "one passing level of one package, kept so the next check does not run it again"
},
"description": "a passing level of one package by its content digest"
}
],
"description": "the kept passing levels",
"history": 1
},
{
"name": "owed",
"template": "state",
"key-forms": [
{
"key": "<repository>.<number>.<head>.<act>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"act": {
"type": "string",
"description": "status=<context>, view, note or comment.<seq>"
},
"context": {
"type": "string"
},
"target": {
"type": "string"
},
"state": {
"type": "string"
},
"text": {
"type": "string"
},
"ref": {
"type": "string"
}
},
"required": [
"act"
],
"description": "one act owed to the forge, written by its owner and done by the forge bridge"
},
"description": "the status mesh/check the checker owes the forge for a head (its act is status=mesh/check)"
}
],
"description": "the status the checker owes the forge",
"history": 5
},
{
"name": "previews",
"template": "state",
"key-forms": [
{
"key": "<repository>.<head>.<trunk>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"repository": {
"type": "string"
},
"head": {
"type": "string"
},
"trunk": {
"type": "string"
},
"merge": {
"type": "string",
"description": "the merge commit"
},
"conflicts": {
"type": "array",
"items": {
"type": "string"
},
"description": "files in conflict"
},
"modules": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"tree": {
"type": "string"
},
"manifest": {
"type": "string",
"description": "manifest digest"
},
"locks": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"paths": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"packages": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"tree",
"manifest"
]
},
"description": "by directory"
}
},
"required": [
"repository",
"head",
"trunk"
],
"description": "the merge of a head onto a trunk commit, read before a pull request is checked"
},
"description": "the merge of a head onto a trunk commit"
}
],
"description": "the previews of a head merged onto a trunk",
"history": 5
}
],
"defs": {
"Owed": {
"type": "object",
"description": "the status the checker owes the forge for a head, said under its id and safe to repeat (a status replaces what stands); the forge bridge performs it through the seat git's verb status (design 47 *What the gate owes the forge*)",
"properties": {
"id": {
"type": "string",
"description": "the act's id, the same each time it is said again"
},
"act": {
"type": "string",
"enum": [
"status"
],
"description": "the act: always status"
},
"repository": {
"type": "string",
"description": "the repository, <owner>/<name>",
"minLength": 1
},
"number": {
"type": "integer",
"description": "the pull request's number"
},
"head": {
"type": "string",
"description": "the pull request's head the status is on",
"pattern": "^[0-9a-f]{40}$"
},
"context": {
"type": "string",
"description": "its context, mesh/check"
},
"state": {
"type": "string",
"description": "pending, success, failure or error"
},
"description": {
"type": "string",
"description": "what it says"
},
"target": {
"type": "string",
"description": "the page it links to"
},
"said": {
"type": "string",
"format": "date-time",
"description": "when the checker first said it"
}
},
"required": [
"id",
"act",
"repository",
"number",
"head",
"context",
"state"
]
},
"CheckedEntry": {
"type": "object",
"description": "one entry of the candidate checked: a module at its fingerprint",
"properties": {
"module": {
"type": "string",
"description": "the module"
},
"fp": {
"type": "string",
"description": "the entry's fingerprint"
},
"node": {
"type": "string",
"description": "the node it was composed for, when the check composed it on one"
}
},
"required": [
"module",
"fp"
]
}
}
}
+723
View File
@@ -0,0 +1,723 @@
{
"format": 1,
"seat": "mesh-delivery",
"scope": "mesh",
"grain": "whole",
"domain": "Delivery",
"decision": "novox/hq ADR 0239",
"description": "The delivery gate: reads and steers deliveries, merges and the checks that decide them; the merge is made on the operator's Approve once both checks passed.",
"verbs": [
{
"name": "deliveries",
"description": "Every delivery not final, and those that ended in the last day, one line each: its id (owner/repository@commit), its state, its group, what it waits for and since when. Narrowed by state, repository or group. Filtered by repository, module, outcome and since while it reads, at most 768 KB a page, capped saying the rest is read from the cursor next (design 47 H2 §811).",
"input": {
"properties": {
"all": {
"description": "\"true\": the final ones of the last thirty days too",
"enum": [
"true",
"false"
],
"type": "string"
},
"group": {
"description": "a group's id (its branch name)",
"type": "string"
},
"repository": {
"description": "owner/repository",
"type": "string"
},
"state": {
"description": "one state, e.g. delivering or held",
"type": "string"
},
"module": {
"type": "string",
"description": "only the deliveries that move this module, applied while reading (design 47 H2 §811)"
},
"outcome": {
"type": "string",
"description": "only the deliveries that ended with this outcome, applied while reading (design 47 H2 §811)"
},
"since": {
"type": "string",
"format": "date-time",
"description": "only the deliveries opened at or after this time, applied while reading (design 47 H2 §811)"
},
"next": {
"type": "string",
"description": "the cursor the previous page answered, opaque; absent for the first page (design 47 H2 §779)"
}
},
"type": "object"
},
"answer": {
"type": "object",
"description": "what deliveries answers, as its description says",
"properties": {
"deliveries": {
"type": "array",
"items": {
"type": "object",
"description": "one delivery's record, as the gate keeps it"
},
"description": "this page's deliveries, the open ones first, then the newest"
},
"capped": {
"type": "boolean",
"description": "yes when the answer stopped at 768 KB; the rest is read from next (design 47 H2 §811)"
},
"total": {
"type": "integer",
"description": "how many deliveries the filters hold in all (design 47 H2 §811)"
},
"next": {
"type": "string",
"description": "the cursor of the next page, opaque; empty at the end (design 47 H2 §779)"
}
},
"required": [
"deliveries"
]
},
"class": "read"
},
{
"name": "show",
"description": "One delivery or group whole: its delivery plan (what it builds, what each machine receives, what is not an ordinary send), every transition with when and why, the machine steps of its walk, its group and its order.",
"input": {
"properties": {
"id": {
"description": "a delivery's id, or a group's",
"type": "string"
}
},
"required": [
"id"
],
"type": "object"
},
"answer": {
"type": "object",
"description": "what show answers, as its description says"
},
"class": "read"
},
{
"name": "source",
"description": "One watched branch's source revision (design 47 *Watched branches and the catalog graph per branch*: source.<branch> in place of source.main): The source revision the gate holds: every repository it names, its trunk branch and that trunk's head as the gate merged or seeded it, and the merge call that moved it last. Read, never written: the node-engines read it to call a reverted build's catch-up tool once per repository, never the gate's state (design 47). Given no branch it answers branches alone, the branch of each source key the gate keeps; given a branch, that branch's source revision (design 47 G section 690).",
"input": {
"type": "object",
"properties": {
"branch": {
"type": "string",
"description": "the watched branch, escaped as a key name is; absent: the answer is the list of the branches the gate keeps a source revision of (design 47 G section 690)"
}
}
},
"answer": {
"type": "object",
"properties": {
"revision": {
"type": "integer",
"description": "the source revision's number on the bus; 0 before the first"
},
"call": {
"type": "string",
"description": "the merge call that moved the source revision last; absent before the first"
},
"repositories": {
"type": "array",
"items": {
"$ref": "#/defs/SourceHead"
},
"description": "every repository the source revision names, by name"
},
"error": {
"type": "string",
"description": "why it could not be read"
},
"branch": {
"type": "string",
"description": "the watched branch the source revision is of"
},
"branches": {
"type": "array",
"items": {
"type": "string"
},
"description": "given no branch: the branch name of each source.<branch> key the gate keeps, which every reader of the catalog half follows before the first registrations (design 47 G section 614, section 690)"
}
}
},
"class": "read"
},
{
"name": "stalled",
"description": "Every delivery held past its state's bound, with the transition the table lets healer H2 take for it, or none.",
"input": {
"properties": {},
"type": "object"
},
"answer": {
"type": "object",
"description": "what stalled answers, as its description says"
},
"class": "read"
},
{
"name": "recovery",
"class": "act",
"description": "Mark a merge its author names a recovery: the commit and why; the delivery record is marked recovery with the caller the runtime proves, and recovery-merged is said (design 47 G section 305).",
"input": {
"type": "object",
"properties": {
"repository": {
"type": "string",
"description": "the repository, <owner>/<name>"
},
"commit": {
"type": "string",
"description": "the merge commit"
},
"why": {
"type": "string",
"description": "why the merge is a recovery"
}
},
"required": [
"repository",
"commit",
"why"
]
},
"answer": {
"type": "object",
"properties": {
"repository": {
"type": "string",
"description": "the repository"
},
"commit": {
"type": "string",
"description": "the merge commit"
},
"recovery": {
"type": "boolean"
},
"by": {
"type": "string",
"description": "the caller the runtime proved"
}
},
"required": [
"commit",
"recovery"
]
}
}
],
"family": {
"name": "mesh-delivery.events",
"max-age-days": 7
},
"events": [
{
"name": "owed",
"subject": "owed.<repository>.<number>",
"keep": {
"max-age-days": 7,
"max-mib": 64
},
"body": {
"$ref": "#/defs/Owed"
}
},
{
"name": "record-opened",
"body": {
"type": "object",
"description": "a delivery record opened for one source revision of a merge call (design 47 H §737)",
"properties": {
"record": {
"type": "string",
"description": "the record's id"
},
"milestone": {
"type": "string",
"description": "its milestone, <branch>.<source>"
},
"branch": {
"type": "string",
"description": "the watched branch"
},
"source": {
"type": "integer",
"description": "the source revision"
},
"call": {
"type": "string",
"description": "the merge call"
},
"at": {
"type": "string",
"format": "date-time",
"description": "when"
}
},
"required": [
"record",
"milestone",
"branch",
"source",
"call"
]
},
"subject": "record-opened.<call>"
},
{
"name": "record-ended",
"body": {
"type": "object",
"description": "a delivery record ended: every present node runs its entries",
"properties": {
"record": {
"type": "string",
"description": "the record's id"
},
"milestone": {
"type": "string",
"description": "its milestone, <branch>.<source>"
},
"branch": {
"type": "string",
"description": "the watched branch"
},
"source": {
"type": "integer",
"description": "the source revision"
},
"call": {
"type": "string",
"description": "the merge call"
},
"away": {
"type": "array",
"items": {
"type": "object",
"properties": {
"node": {
"type": "string",
"description": "a node away"
},
"since": {
"type": "string",
"format": "date-time",
"description": "since when"
}
},
"required": [
"node"
]
},
"description": "the nodes away, each with since when; it ends without them"
},
"at": {
"type": "string",
"format": "date-time",
"description": "when"
}
},
"required": [
"record",
"milestone",
"branch",
"source",
"call"
]
}
},
{
"name": "filling",
"body": {
"$ref": "#/defs/Fill"
}
},
{
"name": "full",
"body": {
"$ref": "#/defs/Fill"
}
},
{
"name": "room",
"body": {
"$ref": "#/defs/Fill"
}
},
{
"name": "source-moved",
"subject": "source-moved.<branch>.<source>",
"body": {
"type": "object",
"description": "a source revision of a watched branch, named once per merge call (design 47 H §737)",
"properties": {
"v": {
"type": "integer"
},
"branch": {
"type": "string"
},
"source": {
"type": "integer",
"description": "the source revision, numbered by the gate alone"
},
"call": {
"type": "string",
"description": "the merge call that moved it"
},
"start": {
"type": "boolean",
"description": "true only for a branch's first revision (design 47 H §768)"
},
"heads": {
"type": "array",
"description": "the repositories it moved",
"items": {
"type": "object",
"properties": {
"repository": {
"type": "string"
},
"commit": {
"type": "string",
"pattern": "^[0-9a-f]{40}$"
}
},
"required": [
"repository",
"commit"
]
}
}
},
"required": [
"v",
"branch",
"source",
"call",
"start",
"heads"
]
},
"keep": {
"max-age-days": 30,
"max-mib": 64
}
},
{
"name": "recovery-merged",
"body": {
"type": "object",
"description": "a merge named a recovery, which the teller passes on to every channel (design 47 G section 305)",
"properties": {
"v": {
"type": "integer"
},
"repository": {
"type": "string",
"description": "the repository"
},
"module": {
"type": "string",
"description": "the module the merge changed, from the delivery record"
},
"branch": {
"type": "string",
"description": "the watched branch the merge moved"
},
"commit": {
"type": "string",
"description": "the merge commit"
},
"why": {
"type": "string",
"description": "why"
},
"by": {
"type": "string",
"description": "the caller the runtime proved"
},
"at": {
"type": "string",
"format": "date-time"
}
},
"required": [
"v",
"repository",
"commit",
"why"
]
}
}
],
"states": [
{
"name": "source",
"template": "state",
"key-forms": [
{
"key": "<branch>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"heads": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "repository to the merged head, a full commit"
},
"source": {
"type": "integer",
"description": "the branch's source revision, one above its newest"
},
"call": {
"type": "string",
"description": "the merge call that moved it; a call the newest revision already carries writes nothing (design 47 H §737, H-A-33)"
}
},
"required": [
"source",
"call",
"heads"
],
"description": "every repository's merged head; its revision is the mesh's source revision"
},
"description": "one key per watched branch, written by the holder alone by compare-and-set; deleted when the last registration watching the branch unwatches it"
}
],
"description": "the mesh's source revision",
"history": 64
},
{
"name": "owed",
"template": "state",
"key-forms": [
{
"key": "<repository>.<number>.<head>.<act>",
"value": {
"type": "object",
"properties": {
"v": {
"type": "integer",
"description": "the layout version"
},
"act": {
"type": "string",
"description": "status=<context>, view, note or comment.<seq>"
},
"context": {
"type": "string"
},
"target": {
"type": "string"
},
"state": {
"type": "string"
},
"text": {
"type": "string"
},
"ref": {
"type": "string"
}
},
"required": [
"act"
],
"description": "one act owed to the forge, written by its owner and done by the forge bridge"
},
"description": "one act owed to the forge"
}
],
"description": "the acts the gate owes the forge",
"history": 5
},
{
"name": "heads",
"template": "state",
"history": 1,
"description": "each head the forge bridge's head-moved said that source.<branch> does not name for that repository; deleted when source.<branch> names it (design 47 H §740)",
"key-forms": [
{
"key": "<repository>.<branch>",
"value": {
"type": "object",
"properties": {
"head": {
"type": "string",
"description": "the head head-moved said",
"pattern": "^[0-9a-f]{40}$"
},
"since": {
"type": "string",
"format": "date-time",
"description": "when it was first heard"
}
},
"required": [
"head",
"since"
],
"description": "an untaken head"
},
"description": "one repository on one watched branch"
}
]
}
],
"defs": {
"Owed": {
"type": "object",
"description": "one act the gate owes the forge, said once under its id and safe to repeat at the forge (design 47 *What the gate owes the forge*); the forge bridge performs it through the seat git's verb of the same act",
"properties": {
"id": {
"type": "string",
"description": "the act's id, the same each time it is said again; a comment and a note line carry it, so the forge holds it once"
},
"act": {
"type": "string",
"enum": [
"status",
"view",
"comment",
"note"
],
"description": "the act: status, view, comment or note"
},
"repository": {
"type": "string",
"description": "the repository, <owner>/<name>",
"minLength": 1
},
"number": {
"type": "integer",
"description": "the pull request's number"
},
"head": {
"type": "string",
"description": "the pull request's head the act is for",
"pattern": "^[0-9a-f]{40}$"
},
"commit": {
"type": "string",
"description": "the commit a status or a note line is on; the head when absent",
"pattern": "^[0-9a-f]{40}$"
},
"context": {
"type": "string",
"description": "a status: its context, such as mesh/merge-gate"
},
"state": {
"type": "string",
"description": "a status: its state, pending, success, failure or error"
},
"description": {
"type": "string",
"description": "a status: what it says"
},
"target": {
"type": "string",
"description": "a status: the page it links to"
},
"text": {
"type": "string",
"description": "a comment or the view: the text, markdown"
},
"line": {
"type": "string",
"description": "a note line: the one line"
},
"said": {
"type": "string",
"format": "date-time",
"description": "when the gate first said it"
},
"record": {
"type": "string",
"description": "the delivery record the act is for, by its source revision, <branch>.<source>; absent on an act said before it was named, which bridge_owed_again by record never finds (design 47 H2 §807, H-A-432)"
}
},
"required": [
"id",
"act",
"repository",
"number",
"head"
]
},
"Fill": {
"type": "object",
"description": "the delivery records' ledger's fill against its cap",
"properties": {
"store": {
"type": "string",
"description": "the kept data, by its name in the holder's manifest"
},
"bytes": {
"type": "integer"
},
"cap": {
"type": "integer",
"description": "bytes"
},
"refused": {
"type": "string",
"description": "what full refuses, such as the next record"
},
"at": {
"type": "string",
"format": "date-time",
"description": "when"
}
},
"required": [
"store",
"bytes",
"cap"
]
},
"SourceHead": {
"type": "object",
"description": "one repository of the source revision: its trunk branch and that trunk's head",
"properties": {
"repository": {
"type": "string",
"description": "the repository, <owner>/<name>"
},
"trunk": {
"type": "string",
"description": "its trunk branch, such as main"
},
"head": {
"type": "string",
"description": "the trunk's head the source revision names",
"pattern": "^[0-9a-f]{40}$"
}
},
"required": [
"repository",
"trunk",
"head"
]
}
},
"form": 2
}
+323 -28
View File
@@ -1,11 +1,12 @@
{
"format": 1,
"form": 4,
"seat": "node-engine",
"scope": "node",
"grain": "whole",
"domain": "Core",
"decision": "novox/hq ADR 0563",
"description": "The node seat every node's engine holds (novox/hq ADR 0563, ADR 0618 §3, §4): its hand acts on the operator's warrant, its read-only judgements, its compositions and what it reads of a manifest. Each verb is answered on this node's subject, mesh.seat.node-engine.tool.<verb>.<node>, and each event is published on mesh.seat.node-engine.event.<event>.<node>, the node's name its last token, or, for an event whose subject names <node>, there (composed.<node>, running.<node>.<module>): the grants part grants a node's account only its own node's subjects (ADR 0363 §2).",
"description": "The node seat every node's engine holds (novox/hq ADR 0563, ADR 0618 \u00a73, \u00a74): its hand acts on the operator's warrant, its read-only judgements, its compositions and what it reads of a manifest. Each verb is answered on this node's subject, mesh.seat.node-engine.tool.<verb>.<node>, and each event is published on mesh.seat.node-engine.event.<event>.<node>, the node's name its last token, or, for an event whose subject names <node>, there (composed.<node>, running.<node>.<module>): the grants part grants a node's account only its own node's subjects (ADR 0363 \u00a72).",
"acts": [
{
"step": "compose",
@@ -15,7 +16,7 @@
"verbs": [
{
"name": "hand-over",
"description": "Hand a directory this machine uses as found to the mesh (novox/hq ADR 0563 §3, §5): the engine judges the path as it does every hand-over (absolute, as it states it, used as found, reached through no link) and refuses in words, or asks the operator on their channel at the level approve, binding the owner, group and mode it will set. Nothing changes on the call: only the operator's yes hands it over. One ask is open per path; acts shows where it stands.",
"description": "Hand a directory this machine uses as found to the mesh (novox/hq ADR 0563 \u00a73, \u00a75): the engine judges the path as it does every hand-over (absolute, as it states it, used as found, reached through no link) and refuses in words, or asks the operator on their channel at the level approve, binding the owner, group and mode it will set. Nothing changes on the call: only the operator's yes hands it over. One ask is open per path; acts shows where it stands.",
"input": {
"properties": {
"path": {
@@ -39,7 +40,7 @@
},
{
"name": "access-act",
"description": "Ask the operator for the take act on a library whose root holds data outside its group (novox/hq ADR 0328 §7, ADR 0563 §3, §4), on the library's home engine: the access as declared and its root as last declared, judged and refused in words or asked at the level approve. Only the operator's yes sets the library's group, group write and setgid under its root. One ask is open per access.",
"description": "Ask the operator for the take act on a library whose root holds data outside its group (novox/hq ADR 0328 \u00a77, ADR 0563 \u00a73, \u00a74), on the library's home engine: the access as declared and its root as last declared, judged and refused in words or asked at the level approve. Only the operator's yes sets the library's group, group write and setgid under its root. One ask is open per access.",
"input": {
"properties": {
"access": {
@@ -68,7 +69,7 @@
},
{
"name": "judge-directories",
"description": "Which of this machine's declared directories the engine would refuse to make or keep, one line each (novox/hq ADR 0563 §2). Read-only: changes no owner or mode.",
"description": "Which of this machine's declared directories the engine would refuse to make or keep, one line each (novox/hq ADR 0563 \u00a72). Read-only: changes no owner or mode.",
"input": {
"properties": {},
"type": "object"
@@ -80,7 +81,7 @@
},
{
"name": "setuid-search",
"description": "Throw away the engine's last search for setuid programs and start a full one (novox/hq ADR 0563 §2); until it completes root-free answers that the machine is not judged yet. Refused while one runs, and when one was started within the hour, naming when the next may start.",
"description": "Throw away the engine's last search for setuid programs and start a full one (novox/hq ADR 0563 \u00a72); until it completes root-free answers that the machine is not judged yet. Refused while one runs, and when one was started within the hour, naming when the next may start.",
"input": {
"properties": {
"why": {
@@ -97,7 +98,7 @@
},
{
"name": "root-free",
"description": "Whether this machine is root-free (novox/hq ADR 0259 §8, ADR 0563 §6): free only on the engine's own verdict, at most fifteen minutes old, that the account agents run as cannot become root without a person, and the login shell's execute not served here. Anything else is no pass, and says why. Answered by this machine's engine alone.",
"description": "Whether this machine is root-free (novox/hq ADR 0259 \u00a78, ADR 0563 \u00a76): free only on the engine's own verdict, at most fifteen minutes old, that the account agents run as cannot become root without a person, and the login shell's execute not served here. Anything else is no pass, and says why. Answered by this machine's engine alone.",
"input": {
"properties": {},
"type": "object"
@@ -121,7 +122,7 @@
},
{
"name": "acts",
"description": "Every act this machine's engine was asked through this seat (novox/hq ADR 0563 §9): each hand-over, access act and setuid search, open, done or refused, with who asked, the ask and the operator's warrant. Read-only.",
"description": "Every act this machine's engine was asked through this seat (novox/hq ADR 0563 \u00a79): each hand-over, access act and setuid search, open, done or refused, with who asked, the ask and the operator's warrant. Read-only.",
"input": {
"properties": {
"id": {
@@ -242,7 +243,7 @@
"type": "string"
},
"digest": {
"description": "a composition's digest (sha256:…), to read that revision rather than the latest",
"description": "a composition's digest (sha256:\u2026), to read that revision rather than the latest",
"type": "string"
},
"module": {
@@ -287,7 +288,7 @@
},
"self": {
"type": "boolean",
"description": "the node composes the module itself (ADR 0547 §2)"
"description": "the node composes the module itself (ADR 0547 \u00a72)"
},
"backup": {
"type": "string",
@@ -455,6 +456,32 @@
},
"description": "every resource that differs from what runs, when asked"
},
"drift": {
"type": "array",
"description": "when the diff is asked, each directory entry of what runs that the mesh made, as its record holds, whose owner or mode on disk differ from it (H-A-392 (b), H-A-458 (2)): read-only; the engine sets it right at its next start or apply of the module",
"items": {
"type": "object",
"required": [
"id",
"path",
"drift"
],
"properties": {
"id": {
"type": "string",
"description": "the directory entry's id in the composition"
},
"path": {
"type": "string",
"description": "its path on the machine"
},
"drift": {
"type": "string",
"description": "how its owner or mode on disk differ, in words"
}
}
}
},
"own": {
"type": "object",
"properties": {
@@ -517,6 +544,27 @@
"withheld-unknown": {
"type": "string",
"description": "withheld unknown: the grants part does not answer, when its verb withheld did not answer"
},
"withheld-parts": {
"type": "array",
"description": "each part a compose kept because its read did not answer, with why (design 08 control-verbs \u00a74, H-A-321): for the packet filter's holder the part node-packet-filter.allowed, its filter file kept as it runs",
"items": {
"type": "object",
"required": [
"part",
"why"
],
"properties": {
"part": {
"type": "string",
"description": "the read asked, as <seat>.<verb>"
},
"why": {
"type": "string",
"description": "why it did not answer, naming the holder asked"
}
}
}
}
},
"required": [
@@ -529,6 +577,63 @@
},
"class": "read"
},
{
"name": "composition-diff",
"description": "One module's composed values read by resource (design 47 H2 \u00a7813 (3), H-A-349 DQ-12b): given a module and a revision or a digest of its composition, the entries that differ between the composition that runs and that one, per resource, environment entries by name, a secret's value masked. Read-only. Answered by this machine's engine alone.",
"class": "read",
"input": {
"type": "object",
"required": [
"module"
],
"properties": {
"module": {
"type": "string",
"description": "the module, as placed on this machine; node for the node's own"
},
"revision": {
"type": "integer",
"description": "the revision of the module's composition key to compare with, from the revisions the bucket keeps; give it or digest"
},
"digest": {
"type": "string",
"description": "the digest (sha256:\u2026) of the composition to compare with; give it or revision"
}
}
},
"answer": {
"type": "object",
"required": [
"node",
"module",
"resources"
],
"properties": {
"node": {
"type": "string",
"description": "the node"
},
"module": {
"type": "string",
"description": "the module"
},
"running": {
"type": "string",
"description": "the digest of the composition that runs; absent when nothing runs"
},
"other": {
"$ref": "#/defs/Revision"
},
"resources": {
"type": "array",
"description": "each resource with an entry that differs; empty when none differs",
"items": {
"$ref": "#/defs/CompositionDiffResource"
}
}
}
}
},
{
"name": "compose",
"description": "Compose this machine's modules now and say how it went, so a composition that failed, or a module held, recovers without a restart: what the pass refused or held, each with why, and when the engine composes again on its own after a seat that did not answer (a deadline, no responders: retried with a growing wait; a refusal never). With module, that module's apply is also tried again. Changes only what a pass the engine makes on its own would change.",
@@ -595,17 +700,21 @@
},
{
"name": "compose-candidate",
"description": "Compose a check's candidate on this machine in shadow, with its own sealed values and the indexer's manifest verdicts, and say per module placed here whether it composes (with its digest and whether the candidate changes it), is refused by the candidate or is held without it, each with why, and the verdict of the machine's own composition (novox/hq ADR 0593 §7). Read-only: applies nothing and writes nothing. Answered by this machine's engine alone, within the asker's bound.",
"description": "Compose a check's candidate on this machine in shadow, with its own sealed values and the indexer's manifest verdicts, and say per module placed here whether it composes (with its digest and whether the candidate changes it), is refused by the candidate or is held without it, each with why, and the verdict of the machine's own composition (novox/hq ADR 0593 \u00a77). Read-only: applies nothing and writes nothing. Answered by this machine's engine alone, within the asker's bound.",
"optional": true,
"input": {
"properties": {
"candidate": {
"description": "the key of the indexer's candidate, <group>.<heads hash>",
"description": "the key of the candidate to compose: a check's candidate in the indexer, <group>.<heads hash>; a branch pipeline's catalog graph revision, <branch>.<revision> (the node-engine reads its entries through mesh-catalog.revision); or a run on request's, run-<id>; built and read by the seat's client (nodeengineclient)",
"type": "string"
},
"input": {
"description": "also answer the composition input the candidate was composed from, for the sandbox path",
"type": "boolean"
},
"call": {
"description": "128 random bits the caller chooses: the subject token of the chunks and acknowledgements the composition input is sent in, whatever its size (design 47 G A-237b); an ask with input and no call is answered inline, as before the checker goes (G-6 section 321)",
"type": "string"
}
},
"required": [
@@ -636,7 +745,7 @@
"unready",
"not-judged"
],
"description": "the node's verdict (ADR 0593 §7, §9)"
"description": "the node's verdict (ADR 0593 \u00a77, \u00a79)"
},
"modules": {
"type": "array",
@@ -658,7 +767,12 @@
},
"input": {
"type": "object",
"description": "when asked: the composition input it composed from"
"description": "when asked without a call token: the composition input it composed from, inline, up to what one answer carries (the checker's form, kept until G removes the checker, G-6 section 321)"
},
"chunks": {
"type": "integer",
"minimum": 0,
"description": "when asked with input and a call token: how many chunks of at most 512 KiB carry the composition input, sent on the chunk subject of the call, each acknowledged by the caller (design 47 G A-237b)"
}
},
"required": [
@@ -671,12 +785,13 @@
"took"
]
},
"chunks": true,
"class": "read"
},
{
"name": "manifest-reads",
"optional": true,
"description": "The reader capabilities this machine's engine states (manifest words, forms and seat names it reads, novox/hq ADR 0618 §3) and when it last stated them. An engine built before it said them states none, which a reader takes as the baseline. Read-only. Answered by this machine's engine alone.",
"description": "The reader capabilities this machine's engine states (manifest words, forms and seat names it reads, novox/hq ADR 0618 \u00a73) and when it last stated them. An engine built before it said them states none, which a reader takes as the baseline. Read-only. Answered by this machine's engine alone.",
"input": {
"type": "object",
"properties": {}
@@ -710,13 +825,74 @@
"node",
"stated-at"
],
"description": "what this machine's engine reads of a manifest (ADR 0618 §3)"
"description": "what this machine's engine reads of a manifest (ADR 0618 \u00a73)"
},
"class": "read"
},
{
"name": "apply-order",
"optional": true,
"description": "The order this machine's engine will apply its changed wants in, with why: one row per unapplied changed want, the bus module and the backup holder first, then each pipeline's wants by rank, then the rest by name, its own want last, a reverted module first (design 47 H 771, H-A-46). Read-only. Answered by this machine's engine alone.",
"input": {
"type": "object",
"properties": {}
},
"answer": {
"type": "object",
"properties": {
"order": {
"type": "array",
"items": {
"type": "object",
"properties": {
"module": {
"type": "string",
"description": "the module whose want waits to be applied"
},
"pipeline": {
"type": "string",
"description": "the want's pipeline (its key); absent for a want in none"
},
"rank": {
"type": "integer",
"description": "the mover's tier in its pipeline; absent for a want in none"
},
"position": {
"type": "integer",
"description": "its place in the order, the first applied being 1"
},
"why": {
"type": "string",
"description": "why it stands there, in one sentence"
},
"waits": {
"type": "array",
"items": {
"type": "string"
},
"description": "the modules it waits on; empty when it waits for nothing"
}
},
"required": [
"module",
"position",
"why",
"waits"
]
},
"description": "one row per unapplied changed want, in the order it will be applied"
}
},
"required": [
"order"
],
"description": "the order this machine's engine applies its changed wants in"
},
"class": "read"
},
{
"name": "seat-list",
"description": "The seat list this engine holds and what it waits for (novox/hq ADR 0636 §7): each seat's source (trunk or bootstrap) and digest, the seats held from the bootstrap alone, the definitions refused, the last error and whether the seat mesh-catalog has answered. Read-only.",
"description": "The seat list this engine holds and what it waits for (novox/hq ADR 0636 \u00a77): each seat's source (trunk or bootstrap) and digest, the seats held from the bootstrap alone, the definitions refused, the last error and whether the seat mesh-catalog has answered. Read-only.",
"input": {
"type": "object",
"properties": {}
@@ -727,7 +903,7 @@
},
{
"name": "seat-list-again",
"description": "Make this engine read the seat list from the seat mesh-catalog now (novox/hq ADR 0636 §7), the recovery of a list unread; it answers what it holds afterwards, and the error when the read failed. A read that changed nothing still ends the engine's wait.",
"description": "Make this engine read the seat list from the seat mesh-catalog now (novox/hq ADR 0636 \u00a77), the recovery of a list unread; it answers what it holds afterwards, and the error when the read failed. A read that changed nothing still ends the engine's wait.",
"input": {
"type": "object",
"properties": {}
@@ -986,6 +1162,52 @@
"$ref": "#/defs/ProcessBuilds"
},
"class": "read"
},
{
"name": "converged",
"description": "The node's convergence state, which the node-engine keeps (ADR 0168, ADR 0683; design 33 control-verbs \u00a710): adopted or converged, since when it became so, for an adopted node the kind of the firewall found, and the node's links as the engine classifies them: the tunnel's interface and the outward links (design 47 H-A-325). Read-only: the holder of node-packet-filter asks it at its start and at every allow and disallow, and refuses when it does not answer.",
"class": "read",
"input": {
"type": "object",
"properties": {}
},
"answer": {
"type": "object",
"required": [
"state",
"tunnel",
"outward"
],
"properties": {
"state": {
"type": "string",
"enum": [
"adopted",
"converged"
],
"description": "the node's mode: adopted (the found firewall's terms) or converged (the mesh's own filter)"
},
"since": {
"type": "string",
"description": "when the node became so, RFC 3339; absent where the engine recorded no time for it"
},
"found": {
"type": "string",
"description": "the kind of the firewall found, for an adopted node"
},
"tunnel": {
"type": "string",
"description": "the private network's tunnel interface on this node, as the engine's filter render names it"
},
"outward": {
"type": "array",
"items": {
"type": "string"
},
"description": "the links of this node that face outside, as the engine classifies them for its filter render (ADR 0140); an allowance with no interface never opens one"
}
}
}
}
],
"events": [
@@ -1134,6 +1356,14 @@
"type": "boolean",
"description": "the move changes the build alone"
},
"run": {
"type": "string",
"description": "the composition run's pipeline sequence, in decimal, the module was applied from (design 47 H2 §813 (1), H-A-388): a restarted engine applies no older run again"
},
"pipeline": {
"type": "string",
"description": "the pipeline of the want the module was applied from, its key <branch>.<source>, beside its run (H-A-429 (1), H-A-458 (1)): a want's run is compared with this run only when the want's branch is the same, the key without its last .<source>; absent for a want in none"
},
"kept": {
"type": "array",
"items": {
@@ -1300,6 +1530,13 @@
"refused": {
"type": "string",
"description": "why the module cannot be composed at this fingerprint"
},
"templates": {
"type": "array",
"items": {
"type": "string"
},
"description": "the digests, sorted, of the templates archives the composition was rendered from"
}
},
"required": [
@@ -1618,7 +1855,7 @@
"description": "one finding of the observer that wrote it"
}
],
"description": "the findings this node's engine raises about itself, one key per finding, in the layout of the seat mesh-conditions (its findings state): a key written raises the condition of the same key, a key deleted clears it (novox/hq ADR 0564 §2, ADR 0636 §1); today `machine.<node>.seat-list-unread`"
"description": "the findings this node's engine raises about itself, one key per finding, in the layout of the seat mesh-conditions (its findings state): a key written raises the condition of the same key, a key deleted clears it (novox/hq ADR 0564 \u00a72, ADR 0636 \u00a71); today `machine.<node>.seat-list-unread`"
},
{
"name": "bounds",
@@ -1630,7 +1867,7 @@
"key": "<what>.<id>",
"value": {
"type": "object",
"description": "one bound a wait of the node-engine runs against, kept with its own time to live: its expiry is heard as the bus's delete marker and ends the wait (design 47 G §560, A-77)",
"description": "one bound a wait of the node-engine runs against, kept with its own time to live: its expiry is heard as the bus's delete marker and ends the wait (design 47 G \u00a7560, A-77)",
"properties": {
"v": {
"type": "integer",
@@ -1737,7 +1974,7 @@
},
"auto": {
"type": "boolean",
"description": "the engine asked it itself, on finding a library's root holding data outside its group (ADR 0563 §4)"
"description": "the engine asked it itself, on finding a library's root holding data outside its group (ADR 0563 \u00a74)"
}
},
"required": [
@@ -1747,7 +1984,7 @@
"at",
"state"
],
"description": "one act asked through the seat, as acts reads it (ADR 0563 §9)"
"description": "one act asked through the seat, as acts reads it (ADR 0563 \u00a79)"
},
"ActSaid": {
"type": "object",
@@ -1792,7 +2029,7 @@
"state",
"node"
],
"description": "what the seat says of an act: the act, the path or access, the caller as the runtime proved it and the ask (ADR 0563 §1)"
"description": "what the seat says of an act: the act, the path or access, the caller as the runtime proved it and the ask (ADR 0563 \u00a71)"
},
"Acts": {
"type": "object",
@@ -1838,6 +2075,13 @@
],
"description": "the answer of an act the operator is asked"
},
"ManifestReadWord": {
"type": "string",
"enum": [
"want:version"
],
"description": "the word a node-engine states in manifest-reads when it reads a want by version and not by digests (design 47 H 772, H-A-45); the assigner holds a node whose engine does not state it. Other words in manifest-reads are free"
},
"ManifestReadsChanged": {
"type": "object",
"properties": {
@@ -1876,7 +2120,7 @@
"at",
"why"
],
"description": "what a node-engine says when what it reads changed or its node returned (ADR 0618 §4)"
"description": "what a node-engine says when what it reads changed or its node returned (ADR 0618 \u00a74)"
},
"Module": {
"type": "object",
@@ -1976,7 +2220,7 @@
"why",
"judged"
],
"description": "the engine's root-free verdict (ADR 0563 §6)"
"description": "the engine's root-free verdict (ADR 0563 \u00a76)"
},
"Said": {
"type": "object",
@@ -2021,7 +2265,7 @@
},
"SeatList": {
"type": "object",
"description": "what an engine holds of the seat list (novox/hq ADR 0636 §7)",
"description": "what an engine holds of the seat list (novox/hq ADR 0636 \u00a77)",
"properties": {
"status": {
"type": "object",
@@ -2366,6 +2610,10 @@
"type": "string"
}
},
"declaration-reads": {
"type": "integer",
"description": "the declaration Version its engine reads (design 47 H2 §813 (12), H-A-416 (2), H-A-419): the composer writes this node's declaration at the lower of its own Version and this one, 1 when none is stated"
},
"runner-capabilities": {
"type": "array",
"items": {
@@ -3075,7 +3323,7 @@
},
"Running": {
"type": "object",
"description": "a module's build running on a node, and its health: what the node-engines of other nodes and the grants part decide a seat's pass from (ADR 0660 §2), and the assigner reads a provider's and a canary's health and a put's end from (design 47 G 520); said again on the same subject each time healthy changes and for every module the have holds at the engine's start, kept last per subject with no age limit",
"description": "a module's build running on a node, and its health: what the node-engines of other nodes and the grants part decide a seat's pass from (ADR 0660 \u00a72), and the assigner reads a provider's and a canary's health and a put's end from (design 47 G 520); said again on the same subject each time healthy changes and for every module the have holds at the engine's start, kept last per subject with no age limit",
"properties": {
"v": {
"type": "integer",
@@ -3198,9 +3446,10 @@
"type": "string",
"enum": [
"compose",
"kept-build"
"kept-build",
"placing"
],
"description": "compose: a hold of the composition (a restore point missing, an entry missing, parts that differ, a recovery that waits); kept-build: waiting for a kept build (design 47 G 499, 541)"
"description": "compose: a hold of the composition (a restore point missing, an entry missing, parts that differ, a recovery that waits); kept-build: waiting for a kept build (design 47 G 499, 541); placing: a want of a higher rank held behind a lower one (design 47 H 771, H-A-67)"
},
"node": {
"type": "string",
@@ -3245,6 +3494,52 @@
"step",
"since"
]
},
"CompositionDiffEntry": {
"type": "object",
"required": [
"name"
],
"properties": {
"name": {
"type": "string",
"description": "the entry: an environment entry by its name, else the part of the resource that differs"
},
"running": {
"type": "string",
"description": "its value in the running composition; absent where the running one lacks it or the value is a secret"
},
"other": {
"type": "string",
"description": "its value in the other composition; absent where the other lacks it or the value is a secret"
},
"masked": {
"type": "boolean",
"description": "the value is a secret, so neither value is given"
}
},
"description": "one entry that differs between the running composition and the other"
},
"CompositionDiffResource": {
"type": "object",
"required": [
"resource",
"entries"
],
"properties": {
"resource": {
"type": "string",
"description": "the resource, as the composition names it"
},
"entries": {
"type": "array",
"items": {
"$ref": "#/defs/CompositionDiffEntry"
},
"description": "the entries of the resource that differ"
}
},
"description": "one resource with the entries of it that differ"
}
}
}
+3 -42
View File
@@ -130,7 +130,7 @@
},
"state": {
"type": "string",
"description": "open (open, held and held-back), ended or all; none is open when no key or since is given, else all"
"description": "open (open and held), ended or all; none is open when no key or since is given, else all"
},
"since": {
"type": "string",
@@ -158,11 +158,7 @@
},
"state": {
"type": "string",
"description": "how the ask stands: open, held (no ready channel), held-back (kept open behind the asker's newer asks, ADR 0666 §12), or how it ended (answered, expired, cancelled)"
},
"held-since": {
"type": "string",
"description": "when the ask was held back, RFC 3339; present while its state is held-back"
"description": "how the ask stands: open, held (no ready channel), or how it ended (answered, expired, cancelled)"
}
},
"required": [
@@ -184,37 +180,6 @@
"asks"
]
}
},
{
"name": "ask-again",
"description": "Offer a held-back ask now, on a channel that is ready: the asker's ask kept open behind its newer asks (design 47 G 83, 394).",
"class": "act",
"input": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "<asker>.<id> of the held-back ask"
}
},
"required": [
"key"
],
"additionalProperties": false
},
"answer": {
"type": "object",
"description": "where the ask stands after it was offered",
"properties": {
"state": {
"type": "string"
},
"error": {
"type": "string",
"description": "why it was not offered; set alone"
}
}
}
}
],
"accepts": [
@@ -287,7 +252,7 @@
},
"state": {
"type": "string",
"description": "how it stands: open, held-back (kept open behind the asker's newer asks, ADR 0666 §12), chosen, expired, cancelled, replaced or refused"
"description": "how it stands: open, chosen, expired, cancelled, replaced or refused"
},
"opened": {
"type": "string",
@@ -308,10 +273,6 @@
"type": "boolean",
"description": "its asker has been told how it ended"
},
"held-since": {
"type": "string",
"description": "when the ask was held back, RFC 3339; present while its state is held-back"
},
"warrant": {
"$ref": "#/defs/Warrant"
},
+2 -1
View File
@@ -25,7 +25,8 @@ func TestEveryBootstrappedDefinitionEqualsItsContractsFile(t *testing.T) {
{"mesh-watchdogs", "mesh-contracts", "health-and-repair/seats/mesh-watchdogs/seat.json"},
{"operator-channel", "mesh-contracts", "operator-and-conversation/seats/operator-channel/seat.json"},
{"mesh-catalog", "mesh-delivery", "modules/mesh-delivery-contracts/seats/mesh-catalog/seat.json"},
{"mesh-delivery-checker", "mesh-delivery", "modules/mesh-delivery-contracts/seats/mesh-delivery-checker/seat.json"},
{"mesh-delivery", "mesh-delivery", "modules/mesh-delivery-contracts/seats/mesh-delivery/seat.json"},
{"git", "mesh-delivery", "modules/mesh-delivery-contracts/seats/git/seat.json"},
}
var have []string
for _, d := range Bootstrapped() {
+44
View File
@@ -85,3 +85,47 @@ func HoldersIn[V ~[]byte](values func() (map[string]V, error)) func(seat string)
return out
}
}
// HolderNode is one holder of a seat: its module and the node it holds it on ("" for a seat held once for the mesh).
type HolderNode struct {
Module, Node string
}
// HolderNodesIn is HoldersIn answering each holder of a seat with its module and its node, from the same seat-holders view: the
// node is the suffix of the view's key `<seat>.<node>`, so no module reads the view's keys itself (design 47 H2 H-A-742). Sorted by
// node then module; none while the view cannot be read or nobody holds the seat.
func HolderNodesIn[V ~[]byte](values func() (map[string]V, error)) func(seat string) []HolderNode {
return func(seat string) []HolderNode {
keys, err := values()
if err != nil {
return nil
}
var out []HolderNode
for key, raw := range keys {
if key != seat && !strings.HasPrefix(key, seat+".") {
continue
}
node := strings.TrimPrefix(strings.TrimPrefix(key, seat), ".")
var held struct {
Holders []struct {
Module string `json:"module"`
} `json:"holders"`
}
if json.Unmarshal([]byte(raw), &held) != nil {
continue
}
for _, h := range held.Holders {
if n := (HolderNode{Module: h.Module, Node: node}); h.Module != "" && !slices.Contains(out, n) {
out = append(out, n)
}
}
}
slices.SortFunc(out, func(a, b HolderNode) int {
if c := strings.Compare(a.Node, b.Node); c != 0 {
return c
}
return strings.Compare(a.Module, b.Module)
})
return out
}
}
+26
View File
@@ -3,6 +3,7 @@ package seatlist
import (
"encoding/json"
"errors"
"slices"
"strings"
"testing"
)
@@ -31,3 +32,28 @@ func TestHolderOf(t *testing.T) {
})
}
}
// Design 47 H2 H-A-742: HolderNodesIn answers each holder of a seat with its module and its node, from the keys `<seat>.<node>`
// of the seat-holders view; a seat held once has no node; another seat's key is no holder; HoldersIn still answers the modules.
func TestHolderNodesInAnswersEachHolderWithItsNode(t *testing.T) {
view := map[string][]byte{
"go-package-registry.ace": []byte(`{"holders":[{"module":"registry"}]}`),
"go-package-registry.shanks": []byte(`{"holders":[{"module":"registry"},{"module":"mirror"}]}`),
"go-package-registry-extra.x": []byte(`{"holders":[{"module":"other"}]}`),
"mesh-delivery": []byte(`{"holders":[{"module":"gate"}]}`),
}
values := func() (map[string][]byte, error) { return view, nil }
want := []HolderNode{{"registry", "ace"}, {"mirror", "shanks"}, {"registry", "shanks"}}
if got := HolderNodesIn(values)("go-package-registry"); !slices.Equal(got, want) {
t.Errorf("holders with their nodes %v, want %v", got, want)
}
if got := HolderNodesIn(values)("mesh-delivery"); !slices.Equal(got, []HolderNode{{"gate", ""}}) {
t.Errorf("a seat held once: %v", got)
}
if got := HoldersIn(values)("go-package-registry"); len(got) != 2 {
t.Errorf("HoldersIn answers %v, want the two modules", got)
}
if got := HolderNodesIn(func() (map[string][]byte, error) { return nil, errors.New("unread") })("go-package-registry"); got != nil {
t.Errorf("an unread view answers %v", got)
}
}
+8 -23
View File
@@ -12,33 +12,18 @@ import (
// A part that reads the seat list wires its reader one way (novox/hq ADR 0636 §1, §7): started from the bootstrapped
// definitions, what it holds given to catalogue at once and at every change, read again when the part's path for the
// seat's events becomes live, and its two tools `<prefix>_seat_list` and `<prefix>_seat_list_again` served over whatever
// reader the part holds at the call. Part is that wiring, so no part writes it again; the part names its tools' prefix
// and the callers that may read again, which are its own to give (stdio.VerbCallers' entries).
// reader the part holds at the call. Part is that wiring, so no part writes it again; the part names its tools' prefix.
// Part is a part's reader of the seat list, set once Follow starts it; before, the list counts as unread and the part
// acts on nothing new.
type Part struct {
prefix string
callers []string
reader atomic.Pointer[Reader]
holders atomic.Pointer[func(seat string) []string]
prefix string
reader atomic.Pointer[Reader]
}
// Holders gives the part the function that answers a seat's holders, by which its callers' entries `seat:<seat>` are
// resolved when a call is checked (design 47 G A-295): the part's follower of the assigner's seat-holders view.
func (p *Part) Holders(h func(seat string) []string) { p.holders.Store(&h) }
func (p *Part) holdersOf(seat string) []string {
if h := p.holders.Load(); h != nil && *h != nil {
return (*h)(seat)
}
return nil
}
// NewPart is the wiring of a part whose tools are named `<prefix>_seat_list` and `<prefix>_seat_list_again`, the second
// answered only to callers.
func NewPart(prefix string, callers []string) *Part {
return &Part{prefix: prefix, callers: append([]string(nil), callers...)}
// NewPart is the wiring of a part whose tools are named `<prefix>_seat_list` and `<prefix>_seat_list_again`.
func NewPart(prefix string) *Part {
return &Part{prefix: prefix}
}
// Follow starts the reader over bus from the bootstrapped definitions: what it holds is given to catalogue at once and at
@@ -124,7 +109,7 @@ func (p *Part) ToolNames() (read, again string) {
// reader has not started.
func (p *Part) Tools() []stdio.Tool {
read, again := p.ToolNames()
shape := ToolsWith(&Reader{}, read, again, p.callers, p.holdersOf)
shape := Tools(&Reader{}, read, again)
for i := range shape {
run := i
shape[i].Run = func(args map[string]any) (any, error) {
@@ -132,7 +117,7 @@ func (p *Part) Tools() []stdio.Tool {
if r == nil {
return nil, errors.New("the seat list reader has not started yet: the runtime has not served this module")
}
return ToolsWith(r, read, again, p.callers, p.holdersOf)[run].Run(args)
return Tools(r, read, again)[run].Run(args)
}
}
return shape
+5 -30
View File
@@ -466,15 +466,9 @@ func (r *Reader) changed() {
}
// Tools are the reader's two runtime tools (ADR 0636 §7), for a host's bundle: read, which says what the reader holds
// (every definition, its source and digest) and what it waits for; and again, which makes it read the list now, and
// answers only to the callers the host's list names (the operator and the healers). The host names the tools and the list;
// again records nothing but the read it asked.
func Tools(r *Reader, read, again string, callers []string) []stdio.Tool {
return ToolsWith(r, read, again, callers, nil)
}
// ToolsWith is Tools whose callers' entries `seat:<seat>` are resolved by holders (RefusalWith, design 47 G A-295).
func ToolsWith(r *Reader, read, again string, callers []string, holders func(seat string) []string) []stdio.Tool {
// (every definition, its source and digest) and what it waits for; and again, which makes it read the list now. Every
// caller may call both (design 47 H §752, H-A-66). The host names the tools; again records nothing but the read it asked.
func Tools(r *Reader, read, again string) []stdio.Tool {
return []stdio.Tool{
{Name: read,
Description: "The seat list this part holds (novox/hq ADR 0636): each seat's definition with its source (trunk or bootstrap) and " +
@@ -486,12 +480,9 @@ func ToolsWith(r *Reader, read, again string, callers []string, holders func(sea
}},
{Name: again,
Description: "Read the seat list again now, from the seat " + Seat + " (a hand act for a part that waits or holds a stale definition), " +
"and answer what it holds afterwards. Answered only to the operator and the healers.",
"and answer what it holds afterwards.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
Run: func(args map[string]any) (any, error) {
if err := RefusalWith(again, callers, stdio.CallerOf(args), holders); err != nil {
return nil, err
}
Run: func(map[string]any) (any, error) {
err := r.Reload()
st := r.Status()
out := map[string]any{"status": st, "health": st.Health()}
@@ -502,19 +493,3 @@ func ToolsWith(r *Reader, read, again string, callers []string, holders func(sea
}},
}
}
// Refusal is why caller may not make the reader read again, or nil: the caller's proof, never an argument, against
// callers, the entries of a verb's list as VerbCallers reads them, so stdio.AnyPerson names every operator's session
// the runtime proved (person.<name>) and a module name its instances (ADR 0636 §7).
func Refusal(tool string, callers []string, caller string) error {
return RefusalWith(tool, callers, caller, nil)
}
// RefusalWith is Refusal whose entries `seat:<seat>` allow the modules holders answers for the seat (stdio.VerbCallers.
// AllowedWith, design 47 G A-295).
func RefusalWith(tool string, callers []string, caller string, holders func(seat string) []string) error {
if err := (stdio.VerbCallers{tool: callers}).AllowedWith(tool, caller, holders); err != nil {
return fmt.Errorf("%s is refused to %q: it answers only %s (novox/hq ADR 0636 §7)", tool, caller, strings.Join(callers, ", "))
}
return nil
}
+21 -32
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"reflect"
"slices"
"strings"
"testing"
"time"
@@ -182,6 +183,13 @@ func TestTheBootstrapIsHeldAndNothingNewIsActedOnUntilTheSeatAnswers(t *testing.
if got := len(r.Definitions()); got != len(boot) {
t.Fatalf("the reader holds %d definitions, the bootstrap has %d", got, len(boot))
}
// Design 47 G lead answers A-353, A-362: before the list is read the runner admits the seat verbs its catalog half is
// read by, mesh-delivery's source beside mesh-catalog's registrations, revision and entry.
for _, sv := range [][2]string{{"mesh-catalog", "registrations"}, {"mesh-catalog", "revision"}, {"mesh-catalog", "entry"}, {"mesh-delivery", "source"}} {
if !slices.ContainsFunc(r.Definitions()[sv[0]].Verbs, func(v seatdef.Verb) bool { return v.Name == sv[1] }) {
t.Errorf("with the seat list unread the reader holds no %s.%s", sv[0], sv[1])
}
}
st := r.Status()
if st.Heard || len(st.Waiting) != len(boot) || st.LastError == "" || st.Health() == "" {
t.Fatalf("status %+v: want the seat not heard, every bootstrapped seat waiting, the error and the health said", st)
@@ -228,27 +236,21 @@ func TestTheBootstrapIsHeldAndNothingNewIsActedOnUntilTheSeatAnswers(t *testing.
}
}
// ADR 0636 §7: the two tools read what is held and read again now, the second to its callers only.
func TestTheTwoToolsReadTheHeldListAndReadItAgainForTheirCallers(t *testing.T) {
// ADR 0636 §7: the two tools read what is held and read again now, each to every caller.
func TestTheTwoToolsReadTheHeldListAndReadItAgain(t *testing.T) {
owner := &fakeOwner{down: true, table: map[string]string{"node-b": def("node-b", "node", "put")}}
r, err := Start(Config{Bus: owner, Bootstrap: Bootstrapped()})
if err != nil {
t.Fatal(err)
}
<-r.Ready()
callers := []string{stdio.AnyPerson, "mesh-healers"}
tools := Tools(r, "seat_list", "seat_list_again", callers)
tools := Tools(r, "seat_list", "seat_list_again")
out, err := tools[0].Run(map[string]any{})
if err != nil || out.(map[string]any)["health"] == "" || !strings.Contains(fmt.Sprint(out.(map[string]any)["status"]), "bootstrap") {
t.Fatalf("read: %v %v", out, err)
}
for caller, allowed := range map[string]bool{"person.jo": true, "ace.mesh-healers": true, "ace.mesh-other": false, "person.al": true, stdio.Unproven: false} {
if err := Refusal("seat_list_again", callers, caller); (err == nil) != allowed {
t.Fatalf("%s: %v, allowed %v", caller, err, allowed)
}
}
if _, err := tools[1].Run(map[string]any{}); err == nil || !strings.Contains(err.Error(), "refused") || len(owner.asked) != 1 {
t.Fatalf("a call without a proven caller read the list again: %v, asks %v", err, owner.asked)
if _, err := tools[1].Run(map[string]any{stdio.MetaCaller: "ace.mesh-other"}); err != nil || len(owner.asked) != 2 {
t.Fatalf("again by any caller: %v, asks %v", err, owner.asked)
}
owner.down = false
if err := r.Reload(); err != nil || !r.Status().Heard || len(r.Status().Held) != len(Bootstrapped())+1 {
@@ -259,7 +261,7 @@ func TestTheTwoToolsReadTheHeldListAndReadItAgainForTheirCallers(t *testing.T) {
// the list counts as unread then, and once followed what the reader holds is the catalogue's and a change wakes the part.
saved := catalogue.Seats()
t.Cleanup(func() { catalogue.UseSeats(saved) }) // Follow sets the catalogue's seats, a global; given back after
part := NewPart("assigner", callers)
part := NewPart("assigner")
if read, again := part.ToolNames(); read != "assigner_seat_list" || again != "assigner_seat_list_again" {
t.Fatalf("tool names %s, %s", read, again)
}
@@ -281,26 +283,6 @@ func TestTheTwoToolsReadTheHeldListAndReadItAgainForTheirCallers(t *testing.T) {
if _, ok := catalogue.SeatNamed("node-b"); !ok {
t.Fatal("what the part's reader holds is not the catalogue's")
}
if _, err := part.Tools()[1].Run(map[string]any{}); err == nil || !strings.Contains(err.Error(), "it answers only operator, mesh-healers") {
t.Fatalf("again without a proven caller: %v", err)
}
// A-295: the part's list names seats, `seat:<seat>`, resolved by the holder function it is given when a call is checked.
bySeat := []string{stdio.AnyPerson, "seat:mesh-healers"}
if err := RefusalWith("seat_list_again", bySeat, "ace.mesh-delivery-watchman", part.holdersOf); err == nil {
t.Fatal("a seat entry allowed a module before the part was given its holders")
}
// HoldersIn reads the seat-holders view as the part last heard it: a seat held once by `<seat>`, a node seat by
// `<seat>.<node>`, and no other seat's key.
view := map[string][]byte{"mesh-healers": []byte(`{"seat":"mesh-healers","holders":[{"module":"mesh-delivery-watchman","node":"g14"}]}`),
"node-tool-runner.ace": []byte(`{"seat":"node-tool-runner","node":"ace","holders":[{"module":"node-tools","node":"ace"}]}`),
"mesh-healers-x": []byte(`{"holders":[{"module":"mesh-build-go"}]}`)}
part.Holders(HoldersIn(func() (map[string][]byte, error) { return view, nil }))
bySeat = append(bySeat, "seat:node-tool-runner")
for caller, allowed := range map[string]bool{"ace.mesh-delivery-watchman": true, "ace.mesh-build-go": false, "person.jo": true, "g14.node-tools": true} {
if err := RefusalWith("seat_list_again", bySeat, caller, part.holdersOf); (err == nil) != allowed {
t.Errorf("again by %s through the seat entry: %v, want allowed %v", caller, err, allowed)
}
}
owner2.table["node-c"] = def("node-c", "node", "put")
if err := owner2.say(ChangedEvent, "node-c", SourceTrunk); err != nil || len(woken) == 0 {
t.Fatalf("a change did not wake the part: %v", err)
@@ -388,6 +370,13 @@ func TestTheBootstrapEqualsTheTestsSeatList(t *testing.T) {
t.Errorf("%s: bootstrap/%s.json differs from seatlisttest/seats/%s.json", b.Seat, b.Seat, b.Seat)
}
}
// Design 47 H2, H-A-452: the tests' seat list holds the seats the live list holds, the recovery seat among them, so a
// test judges a manifest against the seats the running validator judges it against.
for _, seat := range []string{"mesh-builds", "mesh-delivery-view", "mesh-grants", "mesh-pipeline-runner", "mesh-recovery"} {
if _, ok := tests[seat]; !ok {
t.Errorf("seatlisttest holds no definition of %s", seat)
}
}
}
// A host whose path for the seat's events became live after the seat spoke reads the list at once, once: a read

Some files were not shown because too many files have changed in this diff Show More