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
56 changed files with 4041 additions and 996 deletions
+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)
}
}
+23 -2
View File
@@ -120,13 +120,27 @@ func jittered(w time.Duration) time.Duration {
// 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.
// 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.
@@ -231,7 +245,7 @@ func DoPaced[T any](k Kept, try func() (T, error)) (T, error) {
}
start, wait := now(), pace.First
var tries []Try
waiting := false
waiting, said := false, false
defer func() {
if waiting {
journal.done(k.Seat, k.Ask)
@@ -241,9 +255,16 @@ func DoPaced[T any](k Kept, try func() (T, error)) (T, error) {
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
+27
View File
@@ -164,6 +164,28 @@ func subAKeptCallIsPaced(t *testing.T) {
}
}
})
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
@@ -179,6 +201,11 @@ func subAKeptCallIsPaced(t *testing.T) {
!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")
}
+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
}
+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.
+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 {
+62 -30
View File
@@ -1612,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
}
@@ -1705,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" {
@@ -1801,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 {
@@ -1841,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).
@@ -1859,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,
@@ -2304,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-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.max-mib
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 {
+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}
+6 -108
View File
@@ -1,7 +1,6 @@
package catalogue
import (
"maps"
"os"
"slices"
"testing"
@@ -47,24 +46,8 @@ func TestOwnManifestUsesNoWordTheRunningControllerRefuses(t *testing.T) {
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",
@@ -72,103 +55,18 @@ func TestOwnManifestUsesNoWordTheRunningControllerRefuses(t *testing.T) {
"word:declaration-reads", "word:declaration-writes",
// H-A-394: a module's class, core or leaf.
"word:class"} {
if !slices.Contains(added, want) {
t.Errorf("%s is in the baseline, or not read: added since it are %v", want, added)
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",
// 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(baseline, want) {
t.Errorf("the baseline lacks %s", want)
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())
}
}
+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
+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)
}
}
+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"} {
+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
+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.
+22 -9
View File
@@ -67,10 +67,13 @@ func (c *Conn) CallKeptOn(node, key string, body any) (json.RawMessage, error) {
}
// 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), and the caller's bound (zero is busretry.Bound).
// 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
@@ -110,7 +113,7 @@ func (c *Conn) callKeptAskOn(ask KeptAsk, node, key string, body any, open *busr
// 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}
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 == "" {
@@ -271,20 +274,30 @@ func (c *Conn) requestAsk(subject string, data []byte, ask string) (json.RawMess
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
}
+74 -5
View File
@@ -142,24 +142,44 @@ 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; a refusal
// of another kind is the caller's answer at once.
// 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},
{"refused: answered at once", []string{`{"error":"no","error-kind":"refused"}`}, 1},
{"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 asks != row.asks || err != nil || string(got) != row.answers[len(row.answers)-1] {
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)
}
}
@@ -183,6 +203,55 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
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"}
+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)
}
}
+514 -131
View File
@@ -2,13 +2,18 @@ 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"
)
@@ -18,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)
@@ -26,15 +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)
// kept are the module's durables on the kept seat events' streams it handles (StartKept).
kept []jetstream.ConsumeContext
// 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).
@@ -42,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
}
@@ -83,6 +170,33 @@ func (h *EventHub) OnUnhandled(f func(subject string)) {
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()
@@ -94,133 +208,386 @@ 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
// 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()
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)
}
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.
// 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()
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
}
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()
if h.cons != nil {
h.cons.Stop()
h.cons = nil
}
for _, cc := range h.kept {
for _, cc := range h.heard {
cc.Stop()
}
h.kept = nil
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()
}
// StartKept binds, beside EVENTS, the module's durable on each kept seat event's stream (`SEAT_<seat>_<event>`) whose event a
// registered pattern takes: a kept event is never on EVENTS, and the tool runner reads its own twin of that durable (lead
// answer A-397), so the program hears it only here. Each stream bound is said, and each it cannot bind (no durable composed
// for this module there, or the bus refuses) is said and passed over. It returns how many it bound.
func (h *EventHub) StartKept(ctx context.Context, js jetstream.JetStream, cred Account) int {
h.mu.RLock()
var patterns []string
for _, r := range h.routes {
patterns = append(patterns, r.pattern)
}
h.mu.RUnlock()
names := js.StreamNames(ctx)
var streams []string
for name := range names.Name() {
streams = append(streams, name)
}
if err := names.Err(); err != nil {
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard", err)
}
bound := 0
for _, stream := range streams {
seat, event, ok := keptSeatEvent(stream)
if !ok {
continue
}
subject := "mesh.seat." + seat + ".event." + event
taken := false
for _, p := range patterns {
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
taken = true
break
}
}
if !taken {
continue
}
cc, err := cred.HearSeatEvents(ctx, js, stream, h.hear, h.logf)
if err != nil {
h.logf("events: the kept event %s.%s is not heard on %s: %v", seat, event, stream, err)
continue
}
h.mu.Lock()
h.kept = append(h.kept, cc)
h.mu.Unlock()
bound++
h.logf("events: the consumer %s on %s is heard (the kept event %s.%s)", cred.EventConsumerName(), stream, seat, event)
}
return bound
// 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):
@@ -237,26 +604,42 @@ func keptSeatEvent(stream string) (seat, event string, ok bool) {
return seat, event, true
}
func (h *EventHub) hear(m jetstream.Msg) {
h.mu.RLock()
var take func(jetstream.Msg)
for _, r := range h.routes {
if subjectMatches(r.pattern, m.Subject()) {
take = r.handle
break
// 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 take == 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())
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
}
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()})
}
take(m)
}
// subjectMatches says whether subject is one the pattern (`*` one token, `>` the rest) names.
+203 -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,35 +35,32 @@ 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 {
@@ -76,7 +73,6 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
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
@@ -124,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 {
@@ -152,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
@@ -290,6 +358,120 @@ func TestTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
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
+499
View File
@@ -2,7 +2,12 @@ package process
import (
"context"
"errors"
"fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -27,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 {
@@ -147,3 +153,496 @@ func TestTheHubPullsSmallBatchesAndKeepsSlowHandlersAlive(t *testing.T) {
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)
}
})
}
+85
View File
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"git.novox.be/novox/mesh-sdk/go/busretry"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -100,6 +101,14 @@ func (a Account) NamedEventConsumer(ctx context.Context, js jetstream.JetStream,
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
}
@@ -138,6 +147,82 @@ func hearEvents(cons jetstream.Consumer, binder string, handle func(jetstream.Ms
}))
}
// 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 {
+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
}
+16 -2
View File
@@ -2,6 +2,7 @@ package process
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
@@ -13,6 +14,7 @@ import (
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"
)
@@ -177,6 +179,11 @@ func AskOf(body json.RawMessage) string {
// 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:])
@@ -204,7 +211,14 @@ func (c *Conn) answerCall(msg *nats.Msg, pattern string, h heldHandler) {
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:
@@ -218,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
}
+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)
}
}
@@ -2,15 +2,83 @@
"format": 1,
"seat": "node-display-session",
"scope": "node",
"grain": "seat-list",
"grain": "whole",
"domain": "Core",
"decision": "novox/hq ADR 0208",
"decision": "novox/hq ADR 0208, ADR 0687",
"verbs": [
{
"name": "reload",
"description": "Reload the session's configuration in place, keeping its windows.",
"input": {
"properties": {},
"properties": {
"force": {
"description": "reload even if the configuration on disk has errors (optional)",
"type": "boolean"
}
},
"type": "object"
},
"answer": {
"properties": {
"reloaded": {
"description": "whether the reload ran",
"type": "boolean"
},
"i3": {
"description": "the outcome of each command the reload ran, given only once it ran (optional)",
"type": "array",
"items": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"error": {
"description": "why it failed (optional)",
"type": "string"
}
},
"required": [
"success"
]
}
},
"errors": {
"description": "the configuration's errors on disk, found by the check that ran first",
"type": "array",
"items": {
"type": "object",
"properties": {
"file": {
"description": "the file holding the error (optional)",
"type": "string"
},
"line": {
"description": "the line holding the error (optional)",
"type": "number"
},
"text": {
"type": "string"
}
},
"required": [
"text"
]
}
},
"watcher": {
"description": "the configuration watcher's status, given only once the reload ran (optional)",
"type": "object"
},
"why": {
"description": "why it did not reload, given only when it did not (optional)",
"type": "string"
}
},
"required": [
"reloaded",
"errors"
],
"type": "object"
}
},
@@ -20,6 +88,48 @@
"input": {
"properties": {},
"type": "object"
},
"answer": {
"properties": {
"workspaces": {
"type": "array",
"items": {
"type": "object",
"properties": {
"num": {
"type": "number"
},
"name": {
"type": "string"
},
"output": {
"type": "string"
},
"visible": {
"type": "boolean"
},
"focused": {
"type": "boolean"
},
"urgent": {
"type": "boolean"
}
},
"required": [
"num",
"name",
"output",
"visible",
"focused",
"urgent"
]
}
}
},
"required": [
"workspaces"
],
"type": "object"
}
},
{
@@ -33,7 +143,130 @@
}
},
"type": "object"
},
"answer": {
"properties": {
"windows": {
"type": "array",
"items": {
"type": "object",
"properties": {
"con_id": {
"type": "number"
},
"window": {
"type": "string"
},
"class": {
"description": "optional",
"type": "string"
},
"instance": {
"description": "optional",
"type": "string"
},
"role": {
"description": "optional",
"type": "string"
},
"title": {
"type": "string"
},
"workspace": {
"type": "string"
},
"output": {
"type": "string"
},
"focused": {
"description": "optional",
"type": "boolean"
},
"urgent": {
"description": "optional",
"type": "boolean"
},
"floating": {
"description": "optional",
"type": "boolean"
},
"fullscreen": {
"description": "optional",
"type": "boolean"
},
"scratchpad": {
"description": "optional",
"type": "boolean"
},
"marks": {
"description": "optional",
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"con_id",
"window",
"title",
"workspace",
"output"
]
}
}
},
"required": [
"windows"
],
"type": "object"
}
},
{
"name": "open",
"description": "Open an http or https address in the person's default browser, for any caller over the bus (ADR 0687 §4, ADR 0689 §3): any holder of the display session (i3 or sway) serves it the same way. A holder percent-encodes every character outside RFC 3986's unreserved set (letters, digits, -, ., _, ~) and the separators a URL needs (: / ? # [ ] @ & = + %) as the bytes of its UTF-8 form, and passes the address as one argument: nothing is refused for a character, and no shell reads it. Refused, naming the reason: a scheme other than http or https (named), no scheme (a file path), no host, an address over 2048 bytes once encoded, no graphical session running, no default program for the scheme, or the opener ending with a failure (its status named).",
"input": {
"properties": {
"address": {
"description": "the http or https address to open",
"type": "string"
}
},
"required": [
"address"
],
"type": "object"
},
"answer": {
"properties": {
"address": {
"description": "the address as handed on, encoded",
"type": "string"
},
"program": {
"description": "the desktop entry that opened it, as browser.desktop; given only once the opener started (optional)",
"type": "string"
},
"command": {
"description": "the first word of that entry's command; given only once the opener started (optional)",
"type": "string"
},
"started": {
"description": "opened when the opener ended well within its bound, opening when it still ran at its bound",
"type": "string",
"enum": [
"opened",
"opening"
]
}
},
"required": [
"address",
"started"
],
"type": "object"
},
"class": "act"
}
],
"receives": [
@@ -2,9 +2,10 @@
"format": 1,
"seat": "node-resolver",
"scope": "node",
"grain": "seat-list",
"grain": "whole",
"domain": "Connectivity",
"decision": "novox/hq ADR 0247",
"decision": "novox/hq ADR 0247, ADR 0687",
"description": "The node seat of the machine's own resolver (ADR 0247), as ADR 0687 §2 changes it: what it sends where (routes), one link given its own servers and taken away (route, unroute), and, from the uplink's check, the host names to resolve over the link carrying the default route (uplink-names), so a working network is rated fully connected again and a network with a sign-in page is rated as one.",
"verbs": [
{
"name": "routes",
@@ -17,6 +18,42 @@
"input": {
"properties": {},
"type": "object"
},
"answer": {
"type": "object",
"required": [
"mesh",
"links",
"uplink_names",
"mesh_resolvers",
"outside_writes"
],
"properties": {
"mesh": {
"$ref": "#/defs/Scope",
"description": "the global scope: the mesh's resolvers, which answer every name nothing routes elsewhere"
},
"links": {
"type": "array",
"items": {
"$ref": "#/defs/Scope"
},
"description": "every link given servers of its own"
},
"uplink_names": {
"$ref": "#/defs/UplinkNames"
},
"mesh_resolvers": {
"$ref": "#/defs/MeshResolvers"
},
"outside_writes": {
"type": "array",
"items": {
"$ref": "#/defs/OutsideWrite"
},
"description": "the resolver file's outside writes it kept, newest first: when, who wrote it as far as the file says, whether a module took it, and when the resolver's own file was put back"
}
}
}
},
{
@@ -48,6 +85,36 @@
"servers"
],
"type": "object"
},
"answer": {
"type": "object",
"required": [
"link",
"servers",
"domains",
"said"
],
"properties": {
"link": {
"type": "string"
},
"servers": {
"type": "array",
"items": {
"type": "string"
}
},
"domains": {
"type": "array",
"items": {
"type": "string"
}
},
"said": {
"type": "string",
"description": "what was done, in words"
}
}
}
},
{
@@ -67,6 +134,70 @@
"link"
],
"type": "object"
},
"answer": {
"type": "object",
"required": [
"link",
"said"
],
"properties": {
"link": {
"type": "string"
},
"said": {
"type": "string",
"description": "what was done, in words"
}
}
}
},
{
"name": "uplink-names",
"description": "Give the resolver the uplink's check's host names, over the link carrying the default route: the list replaces what was given before, and an empty list takes every name away. Refuses, naming the name and the reason, a name that is not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, the mesh's own domain or a name under it, or more than 8 names.",
"input": {
"type": "object",
"required": [
"names"
],
"properties": {
"names": {
"type": "array",
"minItems": 0,
"maxItems": 8,
"items": {
"type": "string",
"minLength": 1,
"maxLength": 253,
"description": "a host name, letters, digits, hyphens and dots, taken lower-cased"
}
}
}
},
"answer": {
"type": "object",
"required": [
"names",
"link",
"set_at"
],
"properties": {
"names": {
"type": "array",
"items": {
"type": "string"
},
"description": "the names now given"
},
"link": {
"type": "string",
"description": "the link they are answered over now; empty when no link carries a default route"
},
"set_at": {
"type": "string",
"description": "when the list was set, RFC 3339"
}
}
}
}
],
@@ -74,5 +205,118 @@
{
"path": "/etc/resolv.conf"
}
]
],
"defs": {
"Scope": {
"type": "object",
"description": "one scope of the resolver's answers: the mesh's global one, or one link given servers of its own",
"required": [
"servers",
"domains"
],
"properties": {
"link": {
"type": "string",
"description": "the link's name; absent for the global scope"
},
"servers": {
"type": "array",
"items": {
"type": "string"
}
},
"domains": {
"type": "array",
"items": {
"type": "string"
},
"description": "the routing domains, without resolved's leading ~: every name under one goes to these servers"
},
"default_route": {
"type": "boolean",
"description": "whether names no domain routes may also go here; only the mesh's resolvers are"
}
}
},
"UplinkNames": {
"type": "object",
"description": "the applied uplink-names list that resolved holds on the named link now",
"required": [
"names",
"link",
"refused"
],
"properties": {
"names": {
"type": "array",
"items": {
"type": "string"
},
"description": "the names of the applied list that resolved holds on that link now"
},
"link": {
"type": "string",
"description": "the link the guard gave the names to"
},
"refused": {
"type": "string",
"description": "the reason resolved last refused them, or empty"
}
}
},
"MeshResolvers": {
"type": "object",
"description": "whether the mesh's resolvers are silent now, by ADR 0688's guard, and since when",
"required": [
"silent",
"since"
],
"properties": {
"silent": {
"type": "boolean"
},
"since": {
"type": "string",
"description": "RFC 3339, since when the silent state has held"
}
}
},
"OutsideWrite": {
"type": "object",
"description": "one outside write of the resolver file the guard displaced, never what it held",
"required": [
"id",
"at"
],
"properties": {
"id": {
"type": "string"
},
"at": {
"type": "string",
"description": "RFC 3339"
},
"writer": {
"type": "string",
"description": "who the file's own header names, or empty"
},
"taken_by": {
"type": "string",
"description": "the module that took it"
},
"taken_at": {
"type": "string",
"description": "when it was taken, RFC 3339"
},
"ended": {
"type": "string",
"description": "when the resolver's own file stood again, RFC 3339"
},
"how": {
"type": "string",
"description": "how it ended"
}
}
}
}
}
+278 -3
View File
@@ -2,9 +2,10 @@
"format": 1,
"seat": "node-uplink",
"scope": "node",
"grain": "seat-list",
"grain": "whole",
"domain": "Connectivity",
"decision": "novox/hq ADR 0117",
"decision": "novox/hq ADR 0117, ADR 0687, ADR 0689",
"description": "The node seat of the machine's uplink (ADR 0117), as ADR 0687 §1 and ADR 0689 change it: the resolver file as it is now and every network link, read by resolvers and links; and the mesh's record of a network's sign-in page, the events sign-in-asked and sign-in-ended, published by the holder on its own machine without the bus and kept in the family node-uplink.events, 7 days. Both events are optional for a holder, and nothing in the mesh consumes them.",
"verbs": [
{
"name": "resolvers",
@@ -13,6 +14,78 @@
"input": {
"properties": {},
"type": "object"
},
"answer": {
"type": "object",
"required": [
"path",
"nameservers",
"written_by_the_mesh",
"changed"
],
"properties": {
"path": {
"type": "string",
"description": "the resolver file's path"
},
"link": {
"type": "string",
"description": "where the file is a link, its target"
},
"nameservers": {
"type": "array",
"items": {
"type": "string"
}
},
"search": {
"type": "array",
"items": {
"type": "string"
},
"description": "the file's search domains"
},
"options": {
"type": "array",
"items": {
"type": "string"
}
},
"header": {
"type": "array",
"items": {
"type": "string"
},
"description": "the file's leading comment lines, up to four"
},
"written_by_the_mesh": {
"type": "boolean",
"description": "the file is the one the uplink holder declares, by its header"
},
"changed": {
"type": "string",
"description": "when the file last changed, RFC 3339"
},
"owner": {
"type": "string",
"description": "the account that owns the file"
},
"writer": {
"type": "string",
"description": "who wrote it when the mesh did not, as far as the machine shows"
},
"why": {
"type": "string",
"description": "why writer is named so"
},
"beside": {
"type": "array",
"items": {
"$ref": "#/defs/BesideFile"
},
"description": "every file next to it whose name starts with its own: a backup a writer kept"
}
}
}
},
{
@@ -22,13 +95,215 @@
"input": {
"properties": {},
"type": "object"
},
"answer": {
"type": "object",
"required": [
"links"
],
"properties": {
"links": {
"type": "array",
"items": {
"$ref": "#/defs/Link"
}
},
"dns_not_read": {
"type": "string",
"description": "the network manager could not be asked for links' names, said rather than read as no resolvers"
}
}
}
}
],
"events": [
{
"name": "sign-in-asked",
"subject": "sign-in-asked.<node>",
"body": {
"$ref": "#/defs/SignInAsked"
}
},
{
"name": "sign-in-ended",
"subject": "sign-in-ended.<node>",
"body": {
"$ref": "#/defs/SignInEnded"
}
}
],
"family": {
"name": "node-uplink.events",
"max-age-days": 7
},
"paths": [
{
"path": "/etc/resolv.conf",
"steps-back-for": "node-resolver"
}
]
],
"defs": {
"BesideFile": {
"type": "object",
"description": "one file beside the resolver file",
"required": [
"path",
"changed"
],
"properties": {
"path": {
"type": "string"
},
"changed": {
"type": "string",
"description": "RFC 3339"
},
"mesh": {
"type": "boolean",
"description": "it begins as the mesh's own file does: the file a writer moved aside"
}
}
},
"Link": {
"type": "object",
"description": "one network link, as the links verb says it",
"required": [
"name",
"state"
],
"properties": {
"name": {
"type": "string"
},
"state": {
"type": "string"
},
"kind": {
"type": "string"
},
"addresses": {
"type": "array",
"items": {
"type": "string"
}
},
"mac": {
"type": "string",
"description": "the link-layer address as ip says it; left out where the link has none"
},
"master": {
"type": "string",
"description": "the bridge or bond the link is enslaved to"
},
"parent": {
"description": "the link it rides on: its name where that link is in this machine's namespace, else its index and namespace id; left out where none"
},
"default_route": {
"type": "boolean",
"description": "the default route leaves through it"
},
"metric": {
"type": "integer",
"description": "that route's metric"
},
"dns": {
"$ref": "#/defs/LinkDNS"
}
}
},
"LinkDNS": {
"type": "object",
"description": "what the network manager knows of one link's names",
"properties": {
"servers": {
"type": "array",
"items": {
"type": "string"
}
},
"domains": {
"type": "array",
"items": {
"type": "string"
}
},
"manager": {
"type": "string",
"description": "the program that said so"
},
"state": {
"type": "string",
"description": "its word for the link"
}
}
},
"SignInAsked": {
"type": "object",
"required": [
"node",
"link",
"network",
"address",
"at"
],
"properties": {
"node": {
"type": "string",
"description": "the node's name"
},
"link": {
"type": "string",
"description": "the interface name of the link the default route leaves through"
},
"network": {
"type": "string",
"description": "the network's name as the network manager knows it, its connection's name"
},
"address": {
"type": "string",
"description": "an http or https address, the one opened"
},
"at": {
"type": "string",
"description": "the time of the change it says, never of its publish, RFC 3339 in UTC to the second"
}
}
},
"SignInEnded": {
"type": "object",
"required": [
"node",
"link",
"network",
"at",
"why"
],
"properties": {
"node": {
"type": "string",
"description": "the node's name"
},
"link": {
"type": "string",
"description": "empty only for a no-longer-asked said with no connection active"
},
"network": {
"type": "string",
"description": "empty only for a no-longer-asked said with no connection active"
},
"at": {
"type": "string",
"description": "the time of the change it says, never of its publish, RFC 3339 in UTC to the second"
},
"why": {
"type": "string",
"enum": [
"signed-in",
"left",
"no-longer-asked"
]
}
}
}
}
}
+33
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/busretry"
"io"
"sort"
"strings"
@@ -610,3 +611,35 @@ func strs(v any) []string {
}
return out
}
// Design 47 H2 H-A-708 (2): Unread says `away`, naming the state and since when, while the state's copy has not taken in its
// current values, whether its watch is not asked for yet or is still handing them over, and nothing once it has.
func TestAWatchedCopyIsUnreadUntilItsCurrentValuesAreIn(t *testing.T) {
release, entered := make(chan struct{}), make(chan struct{})
w := WatchedStatesOver(func(state string, handle func(StateChange) error) error {
close(entered)
<-release
return handle(StateChange{State: state, Key: "a", Op: OpPut, Value: []byte("1"), Current: true})
}, nil)
asAway := func() *busretry.Away {
var away *busretry.Away
if !errors.As(w.Unread("placement"), &away) {
return nil
}
return away
}
if a := asAway(); a == nil || a.Part != "the state placement" || !strings.HasPrefix(a.Words, "not read yet since ") {
t.Fatalf("before the watch is asked: %+v", a)
}
done := make(chan struct{})
go func() { _, _ = w.Keys("placement"); close(done) }()
<-entered
if a := asAway(); a == nil {
t.Fatal("while the watch hands its current values over, the copy is read")
}
close(release)
<-done
if err := w.Unread("placement"); err != nil {
t.Fatalf("after the current values are in: %v", err)
}
}
+68 -4
View File
@@ -14,11 +14,13 @@ package stdio
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"io"
"os"
"strconv"
@@ -55,6 +57,10 @@ type message struct {
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
// Data carries a typed fault's kind, `error-kind` (the kind away, design 47 H2 §776).
Data struct {
ErrorKind string `json:"error-kind"`
} `json:"data"`
} `json:"error,omitempty"`
}
@@ -78,6 +84,8 @@ type channel struct {
watches map[string]*follower[StateChange]
// provisioned are this bundle's watches of its values, by the id each was asked with (provision.go).
provisioned map[string]*follower[ProvisionChange]
// ledgerWatches are this bundle's watches of its ledgers, by the id each was asked with (busstate.go).
ledgerWatches map[string]*follower[buscalls.InstanceChange]
// givenUp are the watches this bundle gave up, by id, each with why (follower.go).
givenUp map[string]string
// logWatches are this bundle's watches of a log, by the id each was asked with (log.go).
@@ -132,21 +140,33 @@ func (c *channel) askAs(id, method string, params any, timeout time.Duration) (j
select {
case m := <-answer:
if m.Error != nil {
return nil, &refused{message: m.Error.Message, code: m.Error.Code}
return nil, &refused{message: m.Error.Message, code: m.Error.Code, kind: m.Error.Data.ErrorKind}
}
return m.Result, nil
case <-time.After(timeout):
c.mu.Lock()
delete(c.waiting, id)
c.mu.Unlock()
return nil, fmt.Errorf("the runtime did not answer %s in %s", method, timeout)
return nil, &noAnswer{method: method, timeout: timeout}
}
}
// noAnswer is the runtime's silence: its deadline passed with no answer to the request.
type noAnswer struct {
method string
timeout time.Duration
}
func (n *noAnswer) Error() string {
return fmt.Sprintf("the runtime did not answer %s in %s", n.method, n.timeout)
}
// refused is the runtime's error answer, as opposed to no answer: what it refused, it did not do.
type refused struct {
message string
code int
// kind is the typed fault the answer names, its `error-kind`, "" for none.
kind string
}
func (r *refused) Error() string { return r.message }
@@ -156,6 +176,10 @@ func (r *refused) Is(target error) bool {
return target == ErrChanged && r.code == CodeChanged || target == errors.ErrUnsupported && r.code == CodeNoMethod
}
// ErrorKind is the typed fault the runtime's answer named, "" for none: a reader that does not import
// this package tells it by this method, never by the words.
func (r *refused) ErrorKind() string { return r.kind }
// CodeNoMethod is the error code the runtime answers a verb it does not have with (JSON-RPC's method not found).
const CodeNoMethod = -32601
@@ -200,7 +224,7 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
byName[t.Name] = t
}
c := &channel{enc: json.NewEncoder(out), waiting: map[string]chan message{}, watches: map[string]*follower[StateChange]{},
provisioned: map[string]*follower[ProvisionChange]{}, logWatches: map[string]func(LogEntry) error{},
provisioned: map[string]*follower[ProvisionChange]{}, ledgerWatches: map[string]*follower[buscalls.InstanceChange]{}, logWatches: map[string]func(LogEntry) error{},
takers: map[string]func(Work) error{}, provers: map[string]func(string, json.RawMessage) (any, error){}}
currentMu.Lock()
current = c
@@ -277,6 +301,12 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
args = map[string]any{}
}
result, err := runAs(t, inFlight{caller, call, ask}, args)
// A tool's `away` fault is its result in §776's form, so it reaches the caller whole (design 47 H2 H-A-708 (2),
// H-A-717 DQ-58); any other fault is an error as before.
var away *busretry.Away
if errors.As(err, &away) {
result, err = busretry.AwayAnswer(away.Part, away.Words), nil
}
if err != nil {
c.say(map[string]any{"id": id, "result": map[string]any{"content": []map[string]any{{"type": "text", "text": err.Error()}}, "isError": true}})
return
@@ -346,6 +376,21 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
}
f.take(*p.Change)
go c.say(map[string]any{"id": id, "result": map[string]any{}})
case buscalls.LedgerWatched:
// One change to an instance of a ledger this bundle watches (WatchLedger), named by the watch's id: taken into the
// watch's follower in the order it came and answered at once, as a state's change is, so a slow handler never counts
// against the runtime's bound on the current states (design 47 H2 H-A-706 on DMC-13).
var change buscalls.InstanceChange
_ = json.Unmarshal(m.Params, &change)
c.mu.Lock()
f := c.ledgerWatches[change.Watch]
c.mu.Unlock()
if f == nil || change.Instance == "" {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32602, "message": c.noWatch(buscalls.LedgerWatched, change.Watch)}})
continue
}
f.take(change)
go c.say(map[string]any{"id": id, "result": map[string]any{}})
case "mesh/log":
// One entry of a log this bundle watches (log.go), named by the watch's id, answered once its handler has
// taken it, in order: the runtime sends the next only after this answer.
@@ -583,9 +628,28 @@ func Ask(key string, body any) (json.RawMessage, error) {
if err != nil {
return nil, err
}
return c.ask("mesh/ask", map[string]any{"key": key, "body": body}, 60*time.Second)
// The call is made once and nothing is asked again here: a call its caller marks safe to repeat is called again by a kept
// call (design 47 H2 §775) through no responders as through every transport fault. At the bound (the setting ask-bound)
// the fault is "no answer within <bound>", a call's own deadline (design 47 H2 H-A-570 (2), (4)).
askBound, err := SettingDuration(AskBoundSetting, DefaultAskBound)
if err != nil {
return nil, err
}
answer, err := c.ask("mesh/ask", map[string]any{"key": key, "body": body}, askBound)
var timedOut *noAnswer
if errors.As(err, &timedOut) {
return nil, fmt.Errorf("no answer within %s: %w", askBound, context.DeadlineExceeded)
}
return answer, err
}
// AskBoundSetting is the module's setting of how long Ask waits for its answer, asks again included, a duration text;
// DefaultAskBound is its default (design 47 H2 H-A-549).
const (
AskBoundSetting = "ask-bound"
DefaultAskBound = 60 * time.Second
)
// TopicMatches says whether an event's type matches a pattern: `*` is one dot-separated segment, `#`
// (or `**`) any number, as the TypeScript SDK matches; the bus's own `>` as the last token matches one or more
// further tokens (design 47 G A-101), so an adopted follower's `<seat>.<event>.>` hears every event on the seat's event.
+222
View File
@@ -2,8 +2,12 @@ package stdio
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/busretry"
"io"
"strings"
"sync"
@@ -413,3 +417,221 @@ func subABundleAsksAnAcknowledgedPublishAndASubscriptionForNewMessages(t *testin
}
_ = inW.Close()
}
// Ask makes its call once and asks nothing again itself (design 47 H2 H-A-570 (2)): a call met by no responders returns that fault
// after one ask, a reply of the withdrawn kind stopping is the runtime's refusal like any other, and at the bound (the setting
// ask-bound) the fault is "no answer within <bound>", a call's own deadline.
func TestAskCallsOnceAndFaultsAtItsBound(t *testing.T) {
servesAlone(t)
t.Setenv(ServedAs, "builder")
// The bound is the setting ask-bound (H-A-570 (4)), here 50 ms for its default 60 s.
t.Setenv("MESH_CONFIG_ASK_BOUND", "50ms")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("", []Tool{{Name: "publish", Run: func(map[string]any) (any, error) {
answer, err := Ask("seat:go-package-registry.publish", map[string]any{})
if err != nil {
return map[string]any{"deadline": errors.Is(err, context.DeadlineExceeded), "words": err.Error()}, nil
}
return json.RawMessage(answer), nil
}}}, inR, outW)
}()
lines := bufio.NewScanner(outR)
next := func() map[string]any {
done := make(chan map[string]any, 1)
go func() {
if lines.Scan() {
var m map[string]any
_ = json.Unmarshal(lines.Bytes(), &m)
done <- m
}
}()
select {
case m := <-done:
return m
case <-time.After(3 * time.Second):
t.Fatal("the bundle said nothing")
return nil
}
}
send := func(m map[string]any) { b, _ := json.Marshal(m); _, _ = inW.Write(append(b, '\n')) }
stopping := map[string]any{"code": -32000, "message": "registry's publish was not taken: the tool runner is stopping",
"data": map[string]any{"error-kind": "stopping"}}
noResponders := map[string]any{"code": -32000, "message": "nats: no responders available for request"}
for i, row := range []struct {
name string
answers []map[string]any // the runtime's answers to the asks, in order: an error, or a result
asks int
want string
}{
{"answered", []map[string]any{{"result": "published"}}, 1, `"published"`},
{"no responders is returned after one ask", []map[string]any{{"error": noResponders}}, 1, `"words":"nats: no responders available for request"`},
{"a reply of the withdrawn kind stopping is a refusal", []map[string]any{{"error": stopping}}, 1, `"deadline":false`},
{"no answer within the bound", nil, 1, `"words":"no answer within 50ms: context deadline exceeded"`},
} {
t.Run(row.name, func(t *testing.T) {
send(map[string]any{"jsonrpc": "2.0", "id": 100 + i, "method": "tools/call", "params": map[string]any{"name": "publish"}})
asks := 0
if row.answers == nil {
m := next()
asks++
if m["method"] != "mesh/ask" {
t.Fatalf("the bundle said %v, want an ask", m)
}
}
for _, a := range row.answers {
m := next()
if m["method"] != "mesh/ask" {
t.Fatalf("the bundle said %v, want an ask", m)
}
asks++
a["jsonrpc"], a["id"] = "2.0", m["id"]
send(a)
}
r := next()
text, _ := json.Marshal(r["result"])
if r["id"] != float64(100+i) || asks != row.asks || !strings.Contains(string(text), strings.ReplaceAll(row.want, `"`, `\"`)) {
t.Errorf("asked %d times, answered %v; want %d asks and %s", asks, r, row.asks, row.want)
}
})
}
_ = inW.Close()
}
// Design 47 H2 H-A-706 on DMC-13: a bundle's ledger watch is asked with `mesh/ledger.watch` under an id it keeps, each
// `mesh/ledger` change naming that id is handed to its handler in the order it came (the current states first, before the
// watch is answered), and a change naming no watch of it is refused as a state's is.
func TestABundlesLedgerWatchIsHandedItsChangesInOrder(t *testing.T) {
servesAlone(t)
t.Setenv(ServedAs, "gate")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
seen := make(chan string, 8)
watched := make(chan error, 1)
go func() {
_ = ServeOn("", []Tool{{Name: "start", Run: func(map[string]any) (any, error) {
go func() {
watched <- WatchLedger("records", "record/>", func(c buscalls.InstanceChange) error {
seen <- c.Instance
return nil
})
}()
return "started", nil
}}}, inR, outW)
}()
lines := bufio.NewScanner(outR)
next := func() map[string]any {
done := make(chan map[string]any, 1)
go func() {
if lines.Scan() {
var m map[string]any
_ = json.Unmarshal(lines.Bytes(), &m)
done <- m
}
}()
select {
case m := <-done:
return m
case <-time.After(3 * time.Second):
t.Fatal("the bundle said nothing")
return nil
}
}
send := func(m map[string]any) { b, _ := json.Marshal(m); _, _ = inW.Write(append(b, '\n')) }
send(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": map[string]any{"name": "start"}})
got := map[string]map[string]any{}
for len(got) < 2 {
m := next()
if m["method"] != nil {
got[m["method"].(string)] = m
} else {
got["answer"] = m
}
}
watch := got[buscalls.LedgerWatch]
if p := watch["params"].(map[string]any); p["ledger"] != "records" || p["instances"] != "record/>" || p["watch"] != watch["id"] {
t.Fatalf("asked to watch %v", p)
}
for i, instance := range []string{"record/a", "record/b"} {
send(map[string]any{"jsonrpc": "2.0", "id": 50 + i, "method": buscalls.LedgerWatched, "params": map[string]any{
"watch": watch["id"], "instance": instance, "state": map[string]any{}, "sequence": 1, "current": true}})
if r := next(); r["id"] != float64(50+i) || r["error"] != nil {
t.Fatalf("a current state was answered %v", r)
}
}
select {
case err := <-watched:
t.Fatalf("the watch returned before it was answered: %v", err)
default:
}
send(map[string]any{"jsonrpc": "2.0", "id": watch["id"], "result": map[string]any{}})
if err := <-watched; err != nil {
t.Fatal(err)
}
send(map[string]any{"jsonrpc": "2.0", "id": 60, "method": buscalls.LedgerWatched, "params": map[string]any{
"watch": watch["id"], "instance": "record/c", "state": map[string]any{}, "sequence": 2}})
if r := next(); r["id"] != float64(60) || r["error"] != nil {
t.Fatalf("a change was answered %v", r)
}
if order := []string{<-seen, <-seen, <-seen}; strings.Join(order, " ") != "record/a record/b record/c" {
t.Fatalf("handled in the order %v", order)
}
send(map[string]any{"jsonrpc": "2.0", "id": 61, "method": buscalls.LedgerWatched, "params": map[string]any{
"watch": "bundle-999", "instance": "record/d", "state": map[string]any{}}})
if r := next(); r["id"] != float64(61) || r["error"] == nil {
t.Fatalf("a change naming no watch of it was answered %v", r)
}
_ = inW.Close()
}
// Design 47 H2 H-A-708 (2), H-A-717 DQ-58: a tool's `away` fault is its result in §776's form (error-kind, part, words), no
// error; a plain refusal stays an error.
func TestAToolsAwayFaultIsItsResultInTheAwayForm(t *testing.T) {
servesAlone(t)
t.Setenv(ServedAs, "indexer")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("", []Tool{
{Name: "revision", Run: func(map[string]any) (any, error) {
return nil, fmt.Errorf("reading: %w", &busretry.Away{Part: "the trunk's revision 512", Words: "not read yet since 23:35:40"})
}},
{Name: "refuse", Run: func(map[string]any) (any, error) { return nil, errors.New("refused") }},
}, inR, outW)
}()
lines := bufio.NewScanner(outR)
for i, row := range []struct {
tool, want string
isError bool
}{
{"revision", string(mustJSON(t, busretry.AwayAnswer("the trunk's revision 512", "not read yet since 23:35:40"))), false},
{"refuse", "refused", true},
} {
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": map[string]any{"name": row.tool}})
_, _ = inW.Write(append(b, '\n'))
if !lines.Scan() {
t.Fatal("the bundle said nothing")
}
var m struct {
Result struct {
Content []struct{ Text string }
IsError bool `json:"isError"`
}
}
_ = json.Unmarshal(lines.Bytes(), &m)
if len(m.Result.Content) != 1 || m.Result.Content[0].Text != row.want || m.Result.IsError != row.isError {
t.Errorf("%s answered %s", row.tool, lines.Text())
}
}
_ = inW.Close()
}
func mustJSON(t *testing.T, v any) []byte {
t.Helper()
b, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
return b
}
-1
View File
@@ -14,7 +14,6 @@ catalogue/graphical_session.go: node-login-manager
catalogue/graphical_session.go: node-notifier
catalogue/graphical_session.go: node-secret-service
catalogue/graphical_session.go: node-terminal-emulator
catalogue/manifest_reads.go: container-image-registry
catalogue/node_resolver.go: node-resolver
catalogue/reads.go: node-reads
catalogue/seat_contributions.go: node-backup
+42
View File
@@ -8,6 +8,7 @@ import (
"time"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/process"
)
// The findings a views part writes in its own state `findings`, which the condition keeper raises and clears
@@ -26,6 +27,12 @@ const (
// EventUnhandledKind is a process's finding of the events its durable consumer delivered that no handler of the module
// took, one per module, counted since the process started (design 47 H, H-A-166, H-A-169).
EventUnhandledKind = "event-unhandled"
// EventOverrunKind is a process's finding of the handlings of events that run past the setting event-overrun, one per module,
// its summary naming each (design 47 H2 H-A-683 (3), H-A-697).
EventOverrunKind = "event-overrun"
// EventsUnheardKind is a process's finding of the patterns its event hub does not hear, one per module on its node, its summary
// naming each with its stream and why (design 47 H2b §836 4.).
EventsUnheardKind = "events-unheard"
)
// viewFinding is what a views part says is wrong with a state it owns or follows, in plain fields: kind and id name it, summary
@@ -131,3 +138,38 @@ func unhandledFinding(module string, count int, last string, since, at time.Time
module, count, since.UTC().Format(time.RFC3339), last)
return viewFinding{kind: EventUnhandledKind, id: module, summary: summary, headline: fmt.Sprintf("%s hears events it does not handle", module), at: at.UTC()}
}
// overrunMost is how many handlings the finding event-overrun names before it says how many more.
const overrunMost = 5
// overrunFinding is the module's one finding of the handlings past event-overrun (H-A-697 (3)): its id the module, its summary
// each handling, the one begun first first, with its subject, its key and since when, at most five and then how many more.
func overrunFinding(module string, past []process.Handling, at time.Time) viewFinding {
var named []string
for i, h := range past {
if i == overrunMost {
named = append(named, fmt.Sprintf("and %d more", len(past)-overrunMost))
break
}
named = append(named, fmt.Sprintf("%s (key %s) since %s", h.Subject, h.Key, h.Since.UTC().Format(time.RFC3339)))
}
summary := fmt.Sprintf("%s has %d event handlings past their bound: %s: the events behind them wait", module, len(past), strings.Join(named, "; "))
return viewFinding{kind: EventOverrunKind, id: module, summary: summary, headline: fmt.Sprintf("%s handles an event very slowly", module), at: at.UTC()}
}
// unheardFinding is the module's one finding of the patterns its hub does not hear (design 47 H2b §836 4.): its id `<module>.<node>`,
// its summary each pattern with its stream and why, every one named (no bound), and the way through: the node's service
// manager restarts the module's unit.
func unheardFinding(module, node string, list []process.Unheard, at time.Time) viewFinding {
var named []string
for _, u := range list {
if u.Stream == "" {
named = append(named, fmt.Sprintf("%s (%s)", u.Pattern, u.Why))
continue
}
named = append(named, fmt.Sprintf("%s on %s (%s)", u.Pattern, u.Stream, u.Why))
}
summary := fmt.Sprintf("%s on %s does not hear %d event patterns: %s: what it consumes there it does not act on; a bind the bus refuses while its durable stands is made again by the node's service manager restarting the module's unit",
module, node, len(list), strings.Join(named, "; "))
return viewFinding{kind: EventsUnheardKind, id: module + "." + node, summary: summary, headline: fmt.Sprintf("%s does not hear all its events", module), at: at.UTC()}
}
+20
View File
@@ -14,6 +14,7 @@ import (
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
// Follower is a reader's picture of one state of an owner (ADR 0615 §4 to §6): it asks the owner's first-view tool at
@@ -67,6 +68,7 @@ type Follower struct {
// catching is set while catchUp runs: one catch-up at a time.
catching bool
ready chan struct{}
born time.Time // when the follower began (Unread)
}
// Status is what a reader's read tool says of one first view (design 25 § 12.2): the owner, the tool and the revision
@@ -186,6 +188,7 @@ func (f *Follower) init() {
f.values = map[string]json.RawMessage{}
f.ready = make(chan struct{})
f.st = Status{Owner: f.Owner, Tool: f.Tool, State: f.State}
f.born = f.now()
}
}
@@ -222,6 +225,23 @@ func (f *Follower) Ready() <-chan struct{} {
return f.ready
}
// Unread says whether the first view was not answered yet: the fault `away` (busretry.Away, design 47 H2 §776) naming the
// view's owner verb (its Tool) and saying "not read yet since <time>" until Ready closes, nil after. A handler asks it before
// it reads, so a call made while the first view is not in is answered `away` at once; Get and Values keep answering what the
// picture holds, an empty one before the first view (design 47 H2 H-A-708 (2)).
func (f *Follower) Unread() error {
f.mu.Lock()
f.init()
ready, since := f.ready, f.born
f.mu.Unlock()
select {
case <-ready:
return nil
default:
}
return &busretry.Away{Part: f.Tool, Words: "not read yet since " + since.UTC().Format("15:04:05")}
}
// Values is a copy of the picture.
func (f *Follower) Values() map[string]json.RawMessage {
f.mu.Lock()
+92 -4
View File
@@ -77,6 +77,8 @@ type ProcessReader struct {
unheard int
lastUnheard string
startedAt time.Time
// phase is the phase the holder's start is in, nil while none runs (BeginPhase).
phase *StartPhase
// hooked is the hub the count of unhandled events is wired on, so a second Start counts no event twice.
hooked *process.EventHub
}
@@ -433,8 +435,51 @@ func (r *ProcessReader) unhandled(subject string) {
}
}
// clearUnhandled clears the module's finding `event-unhandled` at the process's start: a new build may handle the event
// (H-A-169).
// overrun is the event hub's word of the handlings past event-overrun: the module's finding `event-overrun`, written again at
// each handling that passes the bound or ends, and cleared once none is past it (design 47 H2 H-A-697 (3)).
func (r *ProcessReader) overrun(past []process.Handling) {
if r.Findings == nil {
return
}
w := r.Findings()
if w == nil {
return
}
if len(past) == 0 {
if err := (viewFinding{kind: EventOverrunKind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared: %v", EventOverrunKind, r.Module, err)
}
return
}
if err := overrunFinding(r.Module, past, r.now()).put(w); err != nil {
r.logf("views: the finding %s of %s is not written: %v", EventOverrunKind, r.Module, err)
}
}
// unheardPatterns is the event hub's word of the patterns it does not hear: the module's finding `events-unheard`, raised naming
// each, cleared on an empty list (design 47 H2b §836 4.). With no findings writer the hub's journal line stands alone (H-A-840).
func (r *ProcessReader) unheardPatterns(list []process.Unheard) {
if r.Findings == nil {
return
}
w := r.Findings()
if w == nil {
return
}
module, node := w.ModuleNode()
if len(list) == 0 {
if err := (viewFinding{kind: EventsUnheardKind, id: module + "." + node}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared: %v", EventsUnheardKind, r.Module, err)
}
return
}
if err := unheardFinding(module, node, list, r.now()).put(w); err != nil {
r.logf("views: the finding %s of %s is not written: %v", EventsUnheardKind, r.Module, err)
}
}
// clearUnhandled clears the module's findings `event-unhandled` and `event-overrun` at the process's start: a new build may
// handle the event (H-A-169), and no handling of the new process runs yet (H-A-697 (1)).
func (r *ProcessReader) clearUnhandled() {
if r.Findings == nil {
return
@@ -443,8 +488,10 @@ func (r *ProcessReader) clearUnhandled() {
if w == nil {
return
}
if err := (viewFinding{kind: EventUnhandledKind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared at its start: %v", EventUnhandledKind, r.Module, err)
for _, kind := range []string{EventUnhandledKind, EventOverrunKind} {
if err := (viewFinding{kind: kind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared at its start: %v", kind, r.Module, err)
}
}
}
@@ -906,6 +953,8 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
r.mu.Unlock()
if wire {
hub.OnUnhandled(r.unhandled)
hub.OnOverrun(r.overrun)
hub.OnUnheard(r.unheardPatterns)
}
}
r.mu.Lock()
@@ -939,6 +988,7 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
if status != nil {
status.Ready(func(kv jetstream.KeyValue) {
KeepOwnBuild(ctx, kv, process.OwnBuild(), r.logf)
r.keepPhase()
if err := hearAgain(ctx, kv, r.Followers, r.logf); err != nil {
r.logf("views: the hand asks of %s's first views are not heard (%v) until it starts again", r.Module, err)
}
@@ -952,6 +1002,44 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
r.Ask(ctx, said)
}
// BeginPhase says the holder's start is in the phase name since now, ending the one before: it is said in the journal and
// kept at StartPhaseKey of the state `first-views`, which the part's first-views tool answers beside the views, so a call
// that meets `away` while the holder starts says what the start is doing (design 47 H2 H-A-708 (1), H-A-717 DQ-54). EndPhase
// ends it.
func (r *ProcessReader) BeginPhase(name string) {
r.mu.Lock()
r.phase = &StartPhase{Name: name, Since: r.now().UTC()}
r.mu.Unlock()
r.logf("views: %s's start is in the phase %s", r.Module, name)
r.keepPhase()
}
// EndPhase says the holder's start is in no phase.
func (r *ProcessReader) EndPhase() {
r.mu.Lock()
ended := r.phase
r.phase = nil
r.mu.Unlock()
if ended != nil {
r.logf("views: %s's start ends the phase %s", r.Module, ended.Name)
}
r.keepPhase()
}
// keepPhase writes the phase now at StartPhaseKey, once the state is there (a bucket not yet opened keeps it for then).
func (r *ProcessReader) keepPhase() {
r.mu.Lock()
status, phase := r.status, r.phase
r.mu.Unlock()
if status == nil {
return
}
data, _ := json.Marshal(phase)
if _, err := status.Put(context.Background(), StartPhaseKey, data); err != nil {
r.logf("views: the start phase is not kept in %s: %v", StatusState, err)
}
}
// handleEvent registers handle on the hub for a seat's event on its bare subject and on every further part after it
// (`<subject>.>`): one handler, both forms, as the seat's contract says the event on either (design 47 H, H-A-166; one
// subscription per event, design 47 G §532). The two patterns do not overlap, so a message reaches the handler once.
+137 -6
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -58,8 +59,35 @@ func subAReaderHearsAnOwnersChangesAsOrdinaryEvents(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// H-A-708 (1), H-A-717 DQ-54: the phase the start is in, set before the state is there, is kept in it once it is, and
// ended with null.
r.BeginPhase("take-in")
r.Start(ctx, js, cred, process.AwaitBucket(ctx, js, nil, "reader_first-views", "", t.Logf))
<-r.Ready()
phases, err := statusKV.Watch(ctx, views.StartPhaseKey)
if err != nil {
t.Fatal(err)
}
phaseNow := func() string {
for e := range phases.Updates() {
if e != nil {
var p *views.StartPhase
_ = json.Unmarshal(e.Value(), &p)
if p == nil {
return "none"
}
return p.Name
}
}
return "closed"
}
if got := phaseNow(); got != "take-in" {
t.Fatalf("the start's phase is %s", got)
}
r.EndPhase()
if got := phaseNow(); got != "none" {
t.Fatalf("the start's phase after it ended is %s", got)
}
pic, err := r.KeyValue(ctx, "o_modules")
if err != nil {
t.Fatal(err)
@@ -284,8 +312,8 @@ func subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable(t *testing.T) {
default:
t.Fatal("the unhandled event after the second start wrote no finding")
}
// A hub started before the bus holds its durable says so, and binds at a later start: a module is not lost for the
// order in which the bus makes its consumer.
// A hub started before the bus holds its durable says so, and binds when the grants part says it composed the module's
// durables: a module is not lost for the order in which the bus makes its consumer (design 47 H2b §836 2.).
late := process.Account{Node: "n1", Module: "late"}
lateHub := process.NewEventHub(t.Logf)
heard := make(chan string, 1)
@@ -293,15 +321,22 @@ func subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable(t *testing.T) {
t.Fatal(err)
}
defer lateHub.Stop()
if err := lateHub.Start(ctx, js, late); err == nil {
t.Fatal("a hub with no durable on the bus started")
allHeard := make(chan struct{}, 1)
lateHub.OnAllHeard(func() { allHeard <- struct{}{} })
if err := lateHub.Start(ctx, js, late); err != nil {
t.Fatalf("a hub with no durable on the bus failed its start: %v", err)
}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: late.EventConsumerName(),
AckPolicy: jetstream.AckExplicitPolicy, FilterSubjects: []string{"mesh.mod.l.event.>"}}); err != nil {
t.Fatal(err)
}
if err := lateHub.Start(ctx, js, late); err != nil {
t.Fatalf("the hub did not bind at its second start: %v", err)
if err := nc.Publish("mesh.seat.mesh-grants.event.durables-composed.n1.late", []byte("{}")); err != nil {
t.Fatal(err)
}
select {
case <-allHeard:
case <-time.After(10 * time.Second):
t.Fatal("the grants part said the durables are composed and the hub did not bind")
}
if _, err := js.Publish(ctx, "mesh.mod.l.event.x", []byte("{}")); err != nil {
t.Fatal(err)
@@ -318,6 +353,102 @@ func TestAReaderHearsAnOwnersChangesAsOrdinaryEvents(t *testing.T) {
t.Run("AReaderHearsAnOwnersChangesAsOrdinaryEvents", subAReaderHearsAnOwnersChangesAsOrdinaryEvents)
t.Run("TheViewsReaderAndTwoHandlersShareTheModulesOneDurable", subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable)
t.Run("WriterSaysItsEventsAndHearsAsksOnTheBus", subWriterSaysItsEventsAndHearsAsksOnTheBus)
t.Run("AHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt", subAHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt)
}
// clearedFindings is a findings writer that hands each finding written and each cleared to the test.
type clearedFindings struct{ put, cleared chan string }
func (f *clearedFindings) WriteWire(_ context.Context, w map[string]any) error {
f.put <- fmt.Sprintf("%v %v %v", w["kind"], w["id"], w["summary"])
return nil
}
func (f *clearedFindings) Clear(_ context.Context, _, id, kind, _ string) error {
f.cleared <- kind + " " + id
return nil
}
func (f *clearedFindings) ModuleNode() (string, string) { return "reader", "n1" }
// Design 47 H2 H-A-683 (3), H-A-697: a handling past a short event-overrun raises the module's finding event-overrun, naming its
// key and since when, clears it when the handling ends, and the process started again clears it at its start.
func subAHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt(t *testing.T) {
t.Setenv("MESH_CONFIG_EVENT_OVERRUN", "1s")
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: "reader"}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
hub := process.NewEventHub(t.Logf)
release := make(chan struct{})
if err := hub.HandleByKey("mesh.mod.p.event.slow", func(string, []byte) string { return "the-slow-key" },
func(m jetstream.Msg) { <-release; _ = m.Ack() }); err != nil {
t.Fatal(err)
}
found := &clearedFindings{put: make(chan string, 8), cleared: make(chan string, 8)}
r := &views.ProcessReader{Module: "reader", Hub: hub, Logf: t.Logf, Findings: func() views.WireWriter { return found }}
r.Start(ctx, nil, cred, nil)
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
for range 2 { // the start clears event-unhandled and event-overrun
<-found.cleared
}
// design 47 H2b §836 4.: the hub's Start binds every pattern and tells an empty list, so events-unheard an earlier process raised is cleared
if got := <-found.cleared; got != "events-unheard reader=2en1" {
t.Fatalf("the hub's start cleared %s", got)
}
// design 47 H2b §836 3., 4. (1984/AC-836s): an event adopted after the hub's Start is refused, said in the module's journal,
// and raises events-unheard naming its pattern
var mu sync.Mutex
var lines []string
r.Logf = func(f string, a ...any) { mu.Lock(); lines = append(lines, fmt.Sprintf(f, a...)); mu.Unlock() }
if err := r.AdoptEvent("s", "late", func(context.Context, []byte) error { return nil }); err != nil {
t.Fatal(err)
}
if got := <-found.put; !strings.HasPrefix(got, "events-unheard ") || !strings.Contains(got, "mesh.seat.s.event.late") || !strings.Contains(got, "registered after Start") {
t.Fatalf("the event adopted after Start raised %s", got)
}
mu.Lock()
if len(lines) != 1 || !strings.Contains(lines[0], "mesh.seat.s.event.late is not heard") {
t.Errorf("the reader's journal: %q", lines)
}
mu.Unlock()
if _, err := js.Publish(ctx, "mesh.mod.p.event.slow", []byte("{}")); err != nil {
t.Fatal(err)
}
select {
case got := <-found.put:
if !strings.HasPrefix(got, "event-overrun reader ") || !strings.Contains(got, "mesh.mod.p.event.slow (key the-slow-key) since ") {
t.Fatalf("the finding: %s", got)
}
case <-ctx.Done():
t.Fatal("a handling past event-overrun raised no finding")
}
close(release)
if got := <-found.cleared; got != "event-overrun reader" {
t.Fatalf("the handling ended and %s was cleared", got)
}
again := &views.ProcessReader{Module: "reader", Hub: process.NewEventHub(t.Logf), Logf: t.Logf, Findings: func() views.WireWriter { return found }}
again.Start(ctx, nil, cred, nil)
cleared := []string{<-found.cleared, <-found.cleared}
slices.Sort(cleared)
if cleared[0] != "event-overrun reader" || cleared[1] != "event-unhandled reader" {
t.Fatalf("the start cleared %v", cleared)
}
}
// seenFindings is a findings writer that hands each finding written to the test.
+16 -2
View File
@@ -19,6 +19,16 @@ import (
// process serves no tool (ADR 0436), so its read and re-read tools, in its tools bundle, meet it here.
const StatusState = "first-views"
// StartPhaseKey is where a process keeps the phase its start is in (design 47 H2 H-A-708 (1), H-A-717 DQ-54), in its state
// `first-views`: a StartPhase, or null while no phase runs. The read tool answers it beside the views, under this name.
const StartPhaseKey = "start-phase"
// StartPhase is the phase a holder's start is in: its name and since when.
type StartPhase struct {
Name string `json:"name"`
Since time.Time `json:"since"`
}
// StatusKey is where a reader keeps its first view of owner's state.
func StatusKey(owner, state string) string { return owner + "." + state }
@@ -125,7 +135,7 @@ func StatusTools(reader, read, again string, st keptStatus, acts HandActs, now f
}
out := []Status{}
for _, k := range keys {
if strings.HasPrefix(k, "again.") || k == OwnBuildKey {
if strings.HasPrefix(k, "again.") || k == OwnBuildKey || k == StartPhaseKey {
continue
}
e, err := st.Get(k)
@@ -144,7 +154,11 @@ func StatusTools(reader, read, again string, st keptStatus, acts HandActs, now f
own = w
}
}
return map[string]any{"first-views": out, OwnBuildKey: own}, nil
var phase *StartPhase
if e, err := st.Get(StartPhaseKey); err == nil && e != nil {
_ = json.Unmarshal(e.Value, &phase)
}
return map[string]any{"first-views": out, OwnBuildKey: own, StartPhaseKey: phase}, nil
}},
{Name: again,
Description: fmt.Sprintf("Ask %s's first view of an owner's state again now, by hand (a hand act, its caller and why kept in "+
+78
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-sdk/go/busretry"
"maps"
"reflect"
"runtime"
@@ -1534,3 +1535,80 @@ func TestFirstViewsSayTheOwnBuild(t *testing.T) {
t.Errorf("nothing kept: %v", read)
}
}
// Design 47 H2 H-A-708 (1) (2), H-A-717 DQ-54: a first view not yet answered says `away` naming its owner's verb and since when,
// at once, and nothing after Ready; the status tool answers the phase the start is in beside the views.
func TestAFirstViewIsUnreadUntilItsAnswerIsIn(t *testing.T) {
now := time.Date(2026, 11, 25, 23, 35, 40, 0, time.UTC)
f := &Follower{Owner: "mesh-catalog", Tool: "mesh-catalog.seat-definitions", State: "seat-definitions", Now: func() time.Time { return now },
Ask: func(context.Context, string) (Answer, error) { return Answer{}, nil }}
var away *busretry.Away
if err := f.Unread(); !errors.As(err, &away) || away.Part != "mesh-catalog.seat-definitions" || away.Words != "not read yet since 23:35:40" {
t.Fatalf("before the first view: %v", err)
}
if err := f.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := f.Unread(); err != nil {
t.Fatalf("after the first view: %v", err)
}
st := statusWith{StartPhaseKey: []byte(`{"name":"take-in","since":"2026-11-25T23:35:40Z"}`)}
read, _ := StatusTools("m", "m_first_views", "m_first_view_again", st, nil, time.Now)[0].Run(nil)
if p, ok := read.(map[string]any)[StartPhaseKey].(*StartPhase); !ok || p == nil || p.Name != "take-in" || !p.Since.Equal(now) {
t.Fatalf("the status tool says %v", read)
}
none, _ := StatusTools("m", "r", "a", statusWith{}, nil, time.Now)[0].Run(nil)
if p := none.(map[string]any)[StartPhaseKey].(*StartPhase); p != nil {
t.Fatalf("no phase kept: %v", none)
}
}
// Design 47 H2 H-A-697 (3): the finding event-overrun names each handling past the bound, the one begun first first, with its
// subject, its key and since when, at most five and then how many more.
func TestTheOverrunFindingNamesTheHandlingsOldestFirst(t *testing.T) {
at := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
past := func(n int) []process.Handling {
var out []process.Handling
for i := range n {
out = append(out, process.Handling{Subject: fmt.Sprintf("mesh.mod.m.event.e%d", i), Key: fmt.Sprintf("key%d", i), Since: at.Add(time.Duration(i) * time.Minute)})
}
return out
}
three := overrunFinding("builder", past(3), at)
if three.kind != EventOverrunKind || three.id != "builder" || !strings.Contains(three.summary, "3 event handlings") ||
strings.Index(three.summary, "e0 (key key0)") > strings.Index(three.summary, "e1 (key key1)") ||
strings.Index(three.summary, "e1 (key key1)") > strings.Index(three.summary, "e2 (key key2) since 2026-11-25T12:02:00Z") ||
strings.Contains(three.summary, "more") {
t.Errorf("three handlings: %+v", three)
}
if eight := overrunFinding("builder", past(8), at); !strings.Contains(eight.summary, "and 3 more") || strings.Contains(eight.summary, "e5 ") {
t.Errorf("eight handlings: %s", eight.summary)
}
// Design 47 H2b §836 4. (1984/AC-836e, AC-836r): the finding events-unheard, id `<module>.<node>`, names each pattern with its stream and
// why, is cleared by an empty list, and a reader with no findings writer says nothing (the hub's journal line stands alone).
list := []process.Unheard{{Pattern: "mesh.seat.s.event.e.>", Stream: "SEAT_s_e", Why: "not composed"}, {Pattern: "mesh.mod.p.event.x", Why: "no stream carries it"}}
if f := unheardFinding("builder", "n1", list, at); f.kind != EventsUnheardKind || f.id != "builder.n1" ||
!strings.Contains(f.summary, "mesh.seat.s.event.e.> on SEAT_s_e (not composed)") || !strings.Contains(f.summary, "mesh.mod.p.event.x (no stream carries it)") {
t.Errorf("the finding: %+v", f)
}
// §836 4.: each pattern not heard is named, however many
var many []process.Unheard
for i := range 8 {
many = append(many, process.Unheard{Pattern: fmt.Sprintf("mesh.mod.p.event.x%d", i), Why: "no stream carries it"})
}
if f := unheardFinding("builder", "n1", many, at); !strings.Contains(f.summary, "mesh.mod.p.event.x7 (no stream carries it)") || strings.Contains(f.summary, "more") || !strings.Contains(f.summary, "does not hear 8 event patterns") {
t.Errorf("eight patterns not heard were not all named: %s", f.summary)
}
fm := &findingsMap{}
pr := &ProcessReader{Module: "m", Findings: func() WireWriter { return fm }, Now: func() time.Time { return at }}
pr.unheardPatterns(list)
if _, ok := fm.m["events-unheard/m.n1"]; !ok || len(fm.m) != 1 {
t.Errorf("the finding was not raised: %v", fm.m)
}
pr.unheardPatterns(nil)
if len(fm.m) != 0 || fm.deletes != 1 {
t.Errorf("an empty list did not clear it: %v", fm.m)
}
quiet := &ProcessReader{Module: "m", Now: func() time.Time { return at }}
quiet.unheardPatterns(list) // no findings writer: nothing written, nothing panics
}
+1 -1
View File
@@ -74,7 +74,7 @@ func requireFields[T any](what string, fields ...string) error {
}
// ViewKinds are the finding kinds a views reader writes through the part's writer (design 47 G §639).
var ViewKinds = []string{ViewWaitsKind, UnansweredKind, UnsaidKind, TooLargeKind, EntryNotFoundKind}
var ViewKinds = []string{ViewWaitsKind, UnansweredKind, UnsaidKind, TooLargeKind, EntryNotFoundKind, EventUnhandledKind, EventOverrunKind, EventsUnheardKind}
var (
sessionForm = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*@[a-z0-9][a-z0-9-]*$`)
+8 -1
View File
@@ -451,6 +451,12 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
if err := views.PutViewFinding(r.w, views.ViewWaitsKind, "m.o.s", "waits", ""); err != nil {
t.Fatal(err)
}
// H-A-697 (2): a writer given its own kinds writes event-unhandled and event-overrun too, and states them.
for _, kind := range []string{views.EventUnhandledKind, views.EventOverrunKind, views.EventsUnheardKind} {
if err := views.PutViewFinding(r.w, kind, "m", "sum", "head"); err != nil {
t.Errorf("a writer given its own kinds refuses %s: %v", kind, err)
}
}
r.observe = func(context.Context) (testObserved, error) {
return testObserved{Findings: []testFinding{finding("a", "observed")}}, nil
}
@@ -472,7 +478,8 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
_ = json.Unmarshal(e.data, &stated)
}
}
if !slices.Contains(stated.Kinds, "k") || !slices.Contains(stated.Kinds, views.ViewWaitsKind) || len(stated.Findings) != 2 {
if !slices.Contains(stated.Kinds, "k") || !slices.Contains(stated.Kinds, views.ViewWaitsKind) ||
!slices.Contains(stated.Kinds, views.EventUnhandledKind) || !slices.Contains(stated.Kinds, views.EventOverrunKind) || !slices.Contains(stated.Kinds, views.EventsUnheardKind) || len(stated.Findings) != 5 {
t.Errorf("the statement: kinds %v, %d findings", stated.Kinds, len(stated.Findings))
}
if err := views.DropViewFinding(r.w, views.ViewWaitsKind, "m.o.s"); err != nil {
+29 -2
View File
@@ -2,6 +2,7 @@ package stdio
import (
"fmt"
"git.novox.be/novox/mesh-sdk/go/busretry"
"sort"
"sync"
"time"
@@ -22,12 +23,15 @@ type WatchedStates struct {
// once holds each value read with Once, by state and key, for the process's life: a few kilobytes per manifest
// digest. Past onceAtMost keys it is emptied, which costs only a read again.
once map[string][]byte
// born is when the copy was made: a state not yet asked for is unread since then (Unread).
born time.Time
}
// onceAtMost bounds the values Once keeps.
const onceAtMost = 4096
type watchedState struct {
asked time.Time // when its watch began (Unread)
ready chan struct{} // closed once the watch's current values are all in the copy, or it was refused
err error
@@ -60,7 +64,7 @@ func NewWatchedStates() *WatchedStates {
// every current value and returns once they are handled, then hands every change; get reads one key.
func WatchedStatesOver(watch func(state string, handle func(StateChange) error) error,
get func(state, key string) ([]byte, bool, error)) *WatchedStates {
return &WatchedStates{watch: watch, get: get, states: map[string]*watchedState{}, once: map[string][]byte{}}
return &WatchedStates{watch: watch, get: get, states: map[string]*watchedState{}, once: map[string][]byte{}, born: time.Now()}
}
// watched is the state's copy, its watch started now when it has none, the caller waiting until its current values
@@ -81,7 +85,7 @@ func (w *WatchedStates) watched(state string, then func(StateChange) error) (*wa
}
return s, nil
}
s = &watchedState{ready: make(chan struct{}), values: map[string][]byte{}, revs: map[string]uint64{}}
s = &watchedState{asked: time.Now(), ready: make(chan struct{}), values: map[string][]byte{}, revs: map[string]uint64{}}
if then != nil {
s.then = []func(StateChange) error{then}
}
@@ -130,6 +134,29 @@ func (w *WatchedStates) watched(state string, then func(StateChange) error) (*wa
return s, nil
}
// Unread says whether the copy of state has not taken in its current values yet: the fault `away` (busretry.Away, design
// 47 H2 §776) with `part` naming the state and `words` "not read yet since <time>", while the state's watch has not
// handed them all over (or was never asked for, since the copy was made); nil once it has, and nothing after. A handler
// asks it before it reads, so a call made while the module starts is answered `away` at once; a read itself still waits
// (watched) for the module's own start (design 47 H2 H-A-708 (2)).
func (w *WatchedStates) Unread(state string) error {
w.mu.Lock()
s, ok := w.states[state]
w.mu.Unlock()
since := w.born
if ok {
select {
case <-s.ready:
if s.err == nil {
return nil
}
default:
}
since = s.asked
}
return &busretry.Away{Part: "the state " + state, Words: "not read yet since " + since.UTC().Format("15:04:05")}
}
// join adds then to a state already watched (a read started its watch first) and runs it over the copy's current values
// before any later change, so no change that landed before it joined is lost to it (review of ADR 0580 §2: a read
// beat the follower to the watch at start-up). Under thenMu, so a later change waits for these; a change the copy took
+1 -1
View File
@@ -22,7 +22,7 @@
"dist"
],
"scripts": {
"build": "tsc",
"build": "tsc && node src/declared-imports.mjs",
"pretest": "tsc --noEmit",
"test": "node --test --experimental-strip-types 'test/*.test.ts'",
"prepare": "tsc"
+57
View File
@@ -0,0 +1,57 @@
// The package's check that its built files import only what it declares (design 47 H2, H-A-491): every bare import in
// dist/**/*.js is a Node built-in, the package itself, or a package its package.json names under dependencies or
// peerDependencies. The build runs it after tsc, so a build whose files import an undeclared package fails before
// npm pack, and the builder never publishes it: an importer's bundle never meets "Could not resolve".
//
// It lives under src because the builder's workspace holds only the artifact's paths; tsc does not compile it and the
// published files (dist) do not carry it.
import { readFileSync, readdirSync } from "node:fs";
import { builtinModules } from "node:module";
import { join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
const builtins = new Set(builtinModules);
// packageOf is the package a bare specifier names: its first segment, or its first two for a scoped one.
function packageOf(spec) {
const parts = spec.split("/");
return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
}
function jsFiles(dir) {
const out = [];
for (const e of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, e.name);
if (e.isDirectory()) out.push(...jsFiles(p));
else if (e.name.endsWith(".js")) out.push(p);
}
return out.sort();
}
// undeclared answers, for the package at root, each import of its dist/**/*.js that names a package its package.json
// does not declare, as "file: specifier"; none when every import resolves to a declared package or a built-in.
export function undeclared(root) {
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const declared = new Set([pkg.name, ...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.peerDependencies ?? {})]);
const found = [];
for (const file of jsFiles(join(root, "dist"))) {
const { importedFiles } = ts.preProcessFile(readFileSync(file, "utf8"), true, true);
for (const { fileName: spec } of importedFiles) {
if (spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("node:") || builtins.has(spec)) continue;
if (builtins.has(packageOf(spec)) || declared.has(packageOf(spec))) continue;
found.push(`${relative(root, file)}: ${spec}`);
}
}
return found;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const root = join(fileURLToPath(new URL(".", import.meta.url)), "..");
const found = undeclared(root);
if (found.length > 0) {
console.error("the built files import packages package.json does not declare under dependencies (H-A-491):");
for (const f of found) console.error(" " + f);
process.exit(1);
}
}
+55 -3
View File
@@ -22,6 +22,52 @@ import { runAs } from "../callers/index.js";
/** The protocol version this speaks; the runtime says the same. */
export const PROTOCOL = "2025-03-26";
/** The setting of how long a call waits for its answer, and its default: the Go stdio Ask's (design 47 H2 H-A-570 (4)). */
export const ASK_BOUND_SETTING = "ask-bound";
const DEFAULT_ASK_BOUND_MS = 60_000;
/** A duration setting as the node-engine composes it (MESH_CONFIG_<KEY>, design 47 H2 H-A-370), in milliseconds: Go's
* duration text ("1s", "250ms", "1m30s"); an absent setting is its default, one that is no duration is an error naming it. */
function settingMs(key: string, fallback: number): number {
const word = process.env[`MESH_CONFIG_${key.toUpperCase().replace(/[-.]/g, "_")}`];
if (word === undefined || word === "") return fallback;
const unit: Record<string, number> = { ns: 1e-6, us: 1e-3, "µs": 1e-3, ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
let ms = 0;
let rest = word.trim();
while (rest !== "") {
const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(rest);
if (!part) throw new Error(`the setting ${key} (${word}) is no duration`);
ms += Number(part[1]) * unit[part[2]];
rest = rest.slice(part[0].length);
}
return ms;
}
/** Asks once, as the Go stdio's Ask does, and asks nothing again itself: a call its caller marks safe to repeat is called
* again by a kept call through no responders as through every transport fault. A call met by no responders is the runtime's
* refusal, returned as such; at the bound (the setting ask-bound, 60 s by default) the fault is "no answer within <bound>"
* (design 47 H2 H-A-570 (2), (4)). */
async function askWithinBound(once: () => Promise<unknown>): Promise<unknown> {
const bound = settingMs(ASK_BOUND_SETTING, DEFAULT_ASK_BOUND_MS);
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`no answer within ${boundText(bound)}`)), bound);
});
try {
return await Promise.race([once(), late]);
} finally {
clearTimeout(timer);
}
}
/** A bound as Go's duration prints it for the whole milliseconds a setting gives ("50ms", "10s", "1m0s"). */
function boundText(ms: number): string {
if (ms < 1000) return `${ms}ms`;
const s = ms / 1000;
if (s < 60) return `${s}s`;
return `${Math.floor(s / 60)}m${s % 60}s`;
}
interface Request {
jsonrpc: string;
id?: number | string | null;
@@ -108,8 +154,9 @@ function startSession(): Session {
throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`);
}
},
// A call is made once and its fault said at the bound, as the Go stdio's Ask does (design 47 H2 H-A-570 (2), (4)).
request: (async <Req, Res>(key: string, body: Req): Promise<Res> =>
(await ask("mesh/ask", { key, body })) as Res) as Broker["request"],
(await askWithinBound(() => ask("mesh/ask", { key, body }))) as Res) as Broker["request"],
handle: (async () => {
throw new Error("a launched bundle answers through its tools, not by binding subjects (novox/hq ADR 0193)");
}) as Broker["handle"],
@@ -230,11 +277,16 @@ function startSession(): Session {
continue; // not framed; nobody to answer
}
// The runtime's answer to something this bundle asked.
const reply = request as unknown as { id?: string; method?: string; result?: unknown; error?: { message?: string; code?: number } };
const reply = request as unknown as {
id?: string; method?: string; result?: unknown;
error?: { message?: string; code?: number; data?: { "error-kind"?: string } };
};
if (reply.method === undefined && typeof reply.id === "string" && awaiting.has(reply.id)) {
const waiting = awaiting.get(reply.id)!;
awaiting.delete(reply.id);
if (reply.error) waiting.reject(Object.assign(new Error(reply.error.message ?? "the runtime refused"), { code: reply.error.code }));
// A typed fault rides as the error's data `error-kind` (an `away`, §776): kept as errorKind.
if (reply.error) waiting.reject(Object.assign(new Error(reply.error.message ?? "the runtime refused"),
{ code: reply.error.code, errorKind: reply.error.data?.["error-kind"] }));
else waiting.resolve(reply.result);
continue;
}
+31
View File
@@ -0,0 +1,31 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { undeclared } from "../src/declared-imports.mjs";
// The package's built files import only what it declares (design 47 H2, H-A-491): the SDK itself passes, and a built
// file importing a package package.json leaves out is named, as the forge's bundle met blakejs.
test("every bare import of the built files is a declared dependency or a built-in", () => {
assert.deepEqual(undeclared(join(import.meta.dirname, "..")), []);
const root = mkdtempSync(join(tmpdir(), "declared-"));
try {
mkdirSync(join(root, "dist", "seal"), { recursive: true });
writeFileSync(join(root, "package.json"), JSON.stringify({ name: "@novox/x", dependencies: { tweetnacl: "1.0.3" }, devDependencies: { blakejs: "1.2.1" } }));
writeFileSync(join(root, "dist", "seal", "index.js"), [
'import nacl from "tweetnacl";',
'import blakejs from "blakejs";',
'import { createHash } from "node:crypto";',
'import fs from "fs/promises";',
'export * from "./other.js";',
'export { a } from "@novox/x/tools";',
'const m = await import("@scope/lazy/sub");',
].join("\n"));
assert.deepEqual(undeclared(root), ["dist/seal/index.js: blakejs", "dist/seal/index.js: @scope/lazy/sub"]);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
+16
View File
@@ -0,0 +1,16 @@
// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or the
// words of its fault (design 47 H2 H-A-570 (2), (4)).
import { broker } from "../../dist/messaging/index.js";
import { registerModuleTools } from "../../dist/tools/index.js";
import { serveRegisteredOverStdio } from "../../dist/stdio/index.js";
registerModuleTools("builder", () => [
{ name: "publish", description: "asks the registry", input: {}, run: async () => {
try {
return { answer: await broker().request("seat:go-package-registry.publish", {}) };
} catch (err) {
return { words: err.message };
}
} },
]);
await serveRegisteredOverStdio();
+51
View File
@@ -378,3 +378,54 @@ async function aBundlesFindingWriter(): Promise<void> {
child.kill();
}
}
test("a call is made once: no responders is returned after one ask, a reply of the withdrawn kind stopping is a refusal, and at the bound the fault is no answer within <bound> (design 47 H2 H-A-570 (2), (4))", async () => {
const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-ask.mjs", import.meta.url))],
{ stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, MESH_SERVED_MODULE: "builder",
MESH_CONFIG_ASK_BOUND: "50ms" } });
const seen: any[] = [];
let buffered = "";
let said = "";
child.stderr.on("data", (d) => (said += d.toString()));
child.stdout.on("data", (d) => {
buffered += d.toString();
let at: number;
while ((at = buffered.indexOf("\n")) >= 0) {
seen.push(JSON.parse(buffered.slice(0, at)));
buffered = buffered.slice(at + 1);
}
});
const until = async (match: (m: any) => boolean) => {
for (let i = 0; i < 150 && !seen.some(match); i++) await new Promise((r) => setTimeout(r, 20));
return seen.find(match);
};
const send = (m: unknown) => child.stdin.write(JSON.stringify(m) + "\n");
const stopping = { code: -32000, message: "registry's publish was not taken: the tool runner is stopping", data: { "error-kind": "stopping" } };
try {
send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {} } });
await until((m) => m.id === 1);
const noResponders = { code: -32000, message: "nats: no responders available for request" };
for (const row of [
{ id: 2, answers: [{ result: { published: true } }], want: { answer: { published: true } } },
{ id: 3, answers: [{ error: noResponders }], want: { words: noResponders.message } },
{ id: 4, answers: [{ error: stopping }], want: { words: stopping.message } },
{ id: 5, answers: [{ error: { code: -32000, message: "refused" } }], want: { words: "refused" } },
{ id: 6, answers: [], want: { words: "no answer within 50ms" } },
]) {
send({ jsonrpc: "2.0", id: row.id, method: "tools/call", params: { name: "publish", arguments: {} } });
if (row.answers.length === 0) await until((m) => m.method === "mesh/ask" && !m.answered).then((m) => { m.answered = true; });
for (const a of row.answers) {
const asked = await until((m) => m.method === "mesh/ask" && !m.answered);
assert.ok(asked, `the bundle did not ask again (row ${row.id})`);
asked.answered = true;
send({ jsonrpc: "2.0", id: asked.id, ...a });
}
const done = await until((m) => m.id === row.id);
assert.deepEqual(JSON.parse(done.result.content[0].text), row.want);
assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${Math.max(row.answers.length, 1)} times`);
}
assert.doesNotMatch(said, /asked again/);
} finally {
child.kill();
}
});