Design 47 H2's corrections: ledger forms, ask once, the event hub by key, the away answers (issue 1984) #215

Merged
mesh-tools merged 16 commits from feat/47-H2-corrections into main 2026-11-25 20:11:45 +00:00
44 changed files with 1966 additions and 954 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)
}
}
+25 -18
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.
@@ -163,26 +177,12 @@ func (u *Unanswered) Error() string {
func (u *Unanswered) Unwrap() error { return u.Last }
// Fault says err is a transport fault of a kept call (§775): a request that reached no one, a call's own deadline
// passing, a holder's answer of the kind away (§776), or a stopping tool runner's answer of the kind stopping (design 47
// H2 H-A-542, H-A-549); a callee's refusal never is.
// passing, or a holder's answer of the kind away (§776); a callee's refusal never is.
func Fault(err error) bool {
var away *Away
var stopping *Stopping
return TimedOut(err) || Undelivered(err) || errors.As(err, &away) || errors.As(err, &stopping)
return TimedOut(err) || Undelivered(err) || errors.As(err, &away)
}
// ErrorKindStopping is the typed fault a stopping tool runner answers each call it does not take with (design 47 H2
// H-A-542): its reply's `error-kind`. Nothing was done, and the new runner answers the call.
const ErrorKindStopping = "stopping"
// Stopping is a tool runner's answer of the kind stopping, read as an error: the runner's words.
type Stopping struct{ Words string }
func (s *Stopping) Error() string { return s.Words }
// ErrorKind is the typed fault the answer named: stopping.
func (s *Stopping) ErrorKind() string { return ErrorKindStopping }
// ErrorKindAway is the seat error kind a holder answers when a part it depends on is away (design 47 H2 §776): its
// answer's `error-kind`, beside `part` (what did not answer) and `words`. A caller reads it as a transport fault.
const ErrorKindAway = "away"
@@ -245,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)
@@ -255,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
+26 -3
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,9 +201,10 @@ func subAKeptCallIsPaced(t *testing.T) {
!strings.Contains(string(raw), `"error-kind":"away"`) {
t.Fatalf("%s read as %+v", raw, a)
}
// A stopping tool runner's answer is a transport fault too (design 47 H2 H-A-549), wrapped or not.
if !Fault(&Stopping{Words: "not taken"}) || !Fault(fmt.Errorf("asked: %w", &Stopping{Words: "not taken"})) {
t.Fatal("a stopping tool runner's answer is no transport fault")
// 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.
+3 -276
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,39 +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
}
// ReadDirectoryContentsOwner is the reader capability of a node-engine that, when a directory's owner changes, gives its
// contents the new owner too (novox/hq design 47 H2, H-A-545 (2), H-A-550, H-A-556): an engine before it changes the
// directory alone, and a module moved to an account of its own then cannot read what it wrote before. A manifest that
// declares runs-as needs it (ManifestNeeds), so the module graph orders such a module's move after that engine runs on
// its node (ADR 0614 §4). The engine states it itself; this contract does not (ManifestReads).
const ReadDirectoryContentsOwner = "directory-contents-owner"
// 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).
@@ -127,161 +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
}
if runsAs, _ := top["runs-as"].(string); runsAs != "" {
used[ReadDirectoryContentsOwner] = 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 {
@@ -325,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 {
@@ -454,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
+3 -3
View File
@@ -42,7 +42,7 @@ func TestARequirementsLongForm(t *testing.T) {
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 +53,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 -112
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,107 +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 module of its own account needs an engine that gives a directory's contents its new owner (H-A-556).
{"a module of its own account", `{"module":"g","version":"1","runs-as":"g"}`,
[]string{"directory-contents-owner", "word:runs-as"}, []string{"directory-contents-owner"}},
{"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)
}
// The node-engine states directory-contents-owner itself, beside this contract's reads (H-A-556).
if got := MissingManifestReads(needs, append(slices.Clone(reads), ReadDirectoryContentsOwner)); 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)
}
}
+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
+3
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"`
+13 -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
+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.
+12 -19
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 == "" {
@@ -189,15 +192,6 @@ func callWith(request func(string, []byte) (json.RawMessage, error), blackout fu
return busretry.Do("the call on "+fallback, askBoth(request, called, fallback, data), blackout)
}
// replyError is the error a reply naming one is the call's: a stopping tool runner's kind stopping is a transport fault a
// kept call's pacing asks again on, as away is (design 47 H2 H-A-542, H-A-549); any other is the callee's answer.
func replyError(words, kind string) error {
if kind == busretry.ErrorKindStopping {
return &busretry.Stopping{Words: words}
}
return answered(words)
}
// answered is the error a callee answered with: delivered, never asked again (busretry.Answered).
func answered(words string) error { return &busretry.Answered{Words: words} }
@@ -290,21 +284,20 @@ func (c *Conn) requestAsk(subject string, data []byte, ask string) (json.RawMess
return result, nil
}
// readReply reads one reply ({result, error, error-kind, node, held}): a reply naming an error is the call's failure,
// of the kind stopping a transport fault a kept call paces on (design 47 H2 H-A-549 (1)); a held call names its hold.
// 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"`
ErrorKind string `json:"error-kind"`
Node string `json:"node"`
Held *approval.Held `json:"held"`
Result json.RawMessage `json:"result"`
Error string `json:"error"`
Node string `json:"node"`
Held *approval.Held `json:"held"`
}
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, nil, replyError(r.Error, r.ErrorKind)
return nil, nil, answered(r.Error)
}
return r.Result, r.Held, nil
}
+60 -5
View File
@@ -143,8 +143,8 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
}
}
// Design 47 H2 §776: a holder's answer of the kind away is a transport fault, called again at the pace; so is a
// stopping tool runner's reply of the kind stopping (H-A-542, H-A-549); a refusal of another kind is the caller's
// answer at once.
// 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
@@ -153,9 +153,9 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
want string // the call's answer, where it is not the last answer
}{
{"away, then answered", []string{`{"error":"x","error-kind":"away","part":"the forge's store","words":"401"}`, `{"merged":true}`}, 2, false, ""},
// H-A-549 (1): the runner's reply of the kind stopping, read from its bytes, is paced on until the new runner answers.
{"stopping, then answered by the new runner", []string{`{"error":"git's trees was not taken: the tool runner is stopping","error-kind":"stopping"}`,
`{"result":{"merged":true}}`}, 2, true, `{"merged":true}`},
// 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
@@ -173,6 +173,12 @@ func TestACallIsAskedAgainOnlyWhenItReachedNoOne(t *testing.T) {
want = row.answers[len(row.answers)-1]
}
got, err := callKeptWith(busretry.Kept{Seat: "git", Verb: "merge-pull"}, request, "called", "fallback", nil)
if row.replies && row.want == "" {
if asks != row.asks || err == nil {
t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err)
}
continue
}
if asks != row.asks || err != nil || string(got) != want {
t.Errorf("%s: asked %d times, %s, %v", row.name, asks, got, err)
}
@@ -197,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)
}
}
+107 -22
View File
@@ -3,6 +3,7 @@ package process
import (
"context"
"fmt"
"strconv"
"strings"
"sync"
"time"
@@ -28,13 +29,21 @@ type EventHub struct {
bound []func(created time.Time)
// unhandled are told each subject no handler took (OnUnhandled).
unhandled []func(subject string)
// overruns are told the handlings past event-overrun (OnOverrun).
overruns []func(past []Handling)
// kept are the module's durables on the kept seat events' streams it handles (StartKept).
kept []jetstream.ConsumeContext
// 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,13 +51,37 @@ 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")
}
@@ -59,7 +92,7 @@ func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg)) error {
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})
h.routes = append(h.routes, hubRoute{pattern, handle, keyOf})
return nil
}
@@ -83,6 +116,16 @@ 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()
}
// Patterns are the registered subject patterns, in order.
func (h *EventHub) Patterns() []string {
h.mu.RLock()
@@ -105,7 +148,17 @@ func (h *EventHub) Start(ctx context.Context, js jetstream.JetStream, cred Accou
}
cons, err := cred.EventConsumer(ctx, js, EventsStream)
if err == nil {
h.cons, err = HearEvents(cons, h.hear, h.logf)
err = h.held.settle()
}
if err == nil {
feed := h.newFeed()
if info := cons.CachedInfo(); info != nil {
feed.start(info.Config.AckWait)
}
h.cons, err = hearHeld(cons, callerOutside(), h.held, h.hearOn(feed), h.logf)
if err != nil {
feed.end()
}
}
if err != nil {
return fmt.Errorf("the consumer %s on %s is not heard: %w", cred.EventConsumerName(), EventsStream, err)
@@ -171,6 +224,18 @@ func (h *EventHub) Stop() {
cc.Stop()
}
h.kept = nil
for _, f := range h.feeds {
f.end()
}
h.feeds = nil
h.held.stop()
}
// newFeed makes the ticker of one durable the hub pulls (event_hold.go).
func (h *EventHub) newFeed() *eventFeed {
f := newEventFeed(h.held)
h.feeds = append(h.feeds, f)
return f
}
// StartKept binds, beside EVENTS, the module's durable on each kept seat event's stream (`SEAT_<seat>_<event>`) whose event a
@@ -209,8 +274,12 @@ func (h *EventHub) StartKept(ctx context.Context, js jetstream.JetStream, cred A
if !taken {
continue
}
cc, err := cred.HearSeatEvents(ctx, js, stream, h.hear, h.logf)
h.mu.Lock()
feed := h.newFeed()
h.mu.Unlock()
cc, err := cred.HearSeatEvents(ctx, js, stream, h.hearOn(feed), h.logf, heldBy(feed))
if err != nil {
feed.end()
h.logf("events: the kept event %s.%s is not heard on %s: %v", seat, event, stream, err)
continue
}
@@ -237,26 +306,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.
+114
View File
@@ -290,6 +290,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
+286
View File
@@ -2,7 +2,11 @@ package process
import (
"context"
"fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -147,3 +151,285 @@ 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)
+77
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"
)
@@ -138,6 +139,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 {
+18 -1
View File
@@ -49,8 +49,15 @@ 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
}
// 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 } }
// 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 } }
@@ -144,6 +151,11 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, 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,7 +173,12 @@ 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)
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)
}
if err != nil {
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", a.EventConsumerName(), stream, err)
}
+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)
}
}
+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)
}
}
+50 -39
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,7 +57,7 @@ type message struct {
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
// Data carries a typed fault's kind, `error-kind` (a stopping tool runner's ErrorKindStopping, design 47 H2 H-A-542).
// 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"`
@@ -82,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).
@@ -143,39 +147,39 @@ func (c *channel) askAs(id, method string, params any, timeout time.Duration) (j
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` (ErrorKindStopping), "" for none.
// kind is the typed fault the answer names, its `error-kind`, "" for none.
kind string
}
func (r *refused) Error() string { return r.message }
// Is makes a compare-and-set the runtime refused because another writer was first ErrChanged, and a call a stopping tool
// runner did not take ErrStopping.
// Is makes a compare-and-set the runtime refused because another writer was first ErrChanged.
func (r *refused) Is(target error) bool {
return target == ErrChanged && r.code == CodeChanged || target == errors.ErrUnsupported && r.code == CodeNoMethod ||
target == ErrStopping && r.kind == ErrorKindStopping
return target == ErrChanged && r.code == CodeChanged || target == errors.ErrUnsupported && r.code == CodeNoMethod
}
// ErrorKind is the typed fault the runtime's answer named (ErrorKindStopping), "" for none: a reader that does not import
// 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 }
// ErrorKindStopping is the typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542):
// the answer's `error-kind`. Ask asks again after a pause until the new runner answers or its bound ends.
const ErrorKindStopping = busretry.ErrorKindStopping
// ErrStopping is a call a stopping tool runner did not take (ErrorKindStopping): nothing was done, and the new runner answers
// it. Told apart by its kind, never by its words.
var ErrStopping = errors.New("the tool runner is stopping")
// CodeNoMethod is the error code the runtime answers a verb it does not have with (JSON-RPC's method not found).
const CodeNoMethod = -32601
@@ -220,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
@@ -297,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
@@ -366,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.
@@ -603,27 +628,19 @@ func Ask(key string, body any) (json.RawMessage, error) {
if err != nil {
return nil, err
}
// A call a stopping tool runner did not take is asked again after a pause, at the kept-call pace, until the new runner
// answers or Ask's own bound (the setting ask-bound) ends; then its fault is the caller's as such, ErrStopping (design 47 H2
// H-A-542, H-A-549).
// 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
}
start, wait := askNow(), busretry.KeptPace().First
for {
left := askBound - askNow().Sub(start)
answer, err := c.ask("mesh/ask", map[string]any{"key": key, "body": body}, left)
if !errors.Is(err, ErrStopping) {
return answer, err
}
if left = askBound - askNow().Sub(start); wait >= left {
return nil, fmt.Errorf("%s: the tool runner was stopping, asked again until Ask's bound of %s: %w", key, askBound, err)
}
fmt.Fprintf(os.Stderr, "[mesh-sdk] %s: the tool runner is stopping (%v); asked again in %s\n", key, err, wait)
pause(wait)
wait = min(wait*2, busretry.KeptPace().Max)
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;
@@ -633,12 +650,6 @@ const (
DefaultAskBound = 60 * time.Second
)
// pause is how Ask waits between two asks and askNow its clock, a test's to replace so nothing sleeps.
var (
pause = time.Sleep
askNow = time.Now
)
// 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.
+160 -26
View File
@@ -2,15 +2,17 @@ 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"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
// A Go bundle serves as the module the runtime names, answers calls concurrently, and emits through
@@ -416,27 +418,21 @@ func subABundleAsksAnAcknowledgedPublishAndASubscriptionForNewMessages(t *testin
_ = inW.Close()
}
// A call a stopping tool runner did not take reaches the bundle as the typed fault stopping and is asked again after a pause,
// at the kept-call pace, until the new runner answers; past Ask's bound the fault is the caller's as such, ErrStopping; a
// plain refusal, and a bare timeout, are never asked again (design 47 H2 H-A-542). Nothing sleeps: the pause moves a clock.
func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T) {
// 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")
clock := time.Unix(0, 0)
var paused []time.Duration
wasPause, wasNow := pause, askNow
t.Cleanup(func() { pause, askNow = wasPause, wasNow })
pause = func(d time.Duration) { paused = append(paused, d); clock = clock.Add(d) }
askNow = func() time.Time { return clock }
// The bound is the setting ask-bound (H-A-549), here 10 s for its default 60 s.
t.Setenv("MESH_CONFIG_ASK_BOUND", "10s")
// 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{"stopping": errors.Is(err, ErrStopping), "words": err.Error()}, nil
return map[string]any{"deadline": errors.Is(err, context.DeadlineExceeded), "words": err.Error()}, nil
}
return json.RawMessage(answer), nil
}}}, inR, outW)
@@ -462,24 +458,28 @@ func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T)
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 by the new runner after two stoppings", []map[string]any{{"error": stopping}, {"error": stopping}, {"result": "published"}}, 3,
`"published"`},
{"stopping past the bound", []map[string]any{{"error": stopping}, {"error": stopping}, {"error": stopping}}, 3,
`"stopping":true`},
{"a plain refusal", []map[string]any{{"error": map[string]any{"code": -32000, "message": "refused"}}}, 1, `"stopping":false`},
{"a bare timeout", []map[string]any{{"error": map[string]any{"code": -32000, "message": "timeout"}}}, 1, `"words":"timeout"`},
{"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) {
clock, paused = time.Unix(0, 0), nil
t.Cleanup(busretry.Waits(time.Second, 2*time.Second, 4*time.Second))
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" {
@@ -494,10 +494,144 @@ func TestAStoppingRunnersCallIsAskedAgainUntilTheNewRunnerAnswers(t *testing.T)
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)
}
if want := row.asks - 1; len(paused) != want || (want >= 2 && paused[1] != 2*paused[0]) {
t.Errorf("paused %v, want %d pauses at the kept-call pace", paused, 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
+22
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,9 @@ 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"
)
// 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 +135,21 @@ 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()}
}
+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()
+69 -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,29 @@ 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)
}
}
// 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 +466,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 +931,7 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
r.mu.Unlock()
if wire {
hub.OnUnhandled(r.unhandled)
hub.OnOverrun(r.overrun)
}
}
r.mu.Lock()
@@ -939,6 +965,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 +979,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.
+103
View File
@@ -58,8 +58,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)
@@ -318,6 +345,82 @@ 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
}
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 "+
+51
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,53 @@ 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)
}
}
+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}
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} {
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) || len(stated.Findings) != 4 {
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
+25 -43
View File
@@ -22,27 +22,10 @@ import { runAs } from "../callers/index.js";
/** The protocol version this speaks; the runtime says the same. */
export const PROTOCOL = "2025-03-26";
/** The typed fault a stopping tool runner answers each call it does not take with (design 47 H2 H-A-542): the runtime's
* answer's `error-kind`, kept on the error as `errorKind`. */
export const ERROR_KIND_STOPPING = "stopping";
/** Whether err is a call a stopping tool runner did not take: told by its kind, never by its words (H-A-542). */
export function isStopping(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { errorKind?: unknown }).errorKind === ERROR_KIND_STOPPING;
}
/** The setting of how long a call is asked again while the tool runner is stopping, and its default: the Go stdio Ask's
* (H-A-544, H-A-549). */
/** 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;
/** How a call waits between two asks while the tool runner is stopping, and its clock: a test's to replace, as the Go
* stdio's pause and askNow are, so nothing sleeps. */
export const askPacing = {
pause: (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms)),
now: (): number => Date.now(),
};
/** 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 {
@@ -60,31 +43,31 @@ function settingMs(key: string, fallback: number): number {
return ms;
}
/** Asks once and again, while the answer is the typed fault stopping, after a pause at the kept-call pace (the settings
* kept-call-pace-first and kept-call-pace-max, 1 s doubling to 30 s by default, as the Go stdio's Ask), until the new
* runner answers or the bound (the setting ask-bound, 60 s by default) ends; then the stopping fault is the caller's as such (H-A-542, H-A-544). A plain refusal
* and a bare timeout are never asked again. */
async function askAgainWhileStopping(key: string, once: () => Promise<unknown>): Promise<unknown> {
const start = askPacing.now();
/** 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 wait = settingMs("kept-call-pace-first", 1000);
const most = settingMs("kept-call-pace-max", 30_000);
for (;;) {
try {
return await once();
} catch (err) {
const left = bound - (askPacing.now() - start);
if (!isStopping(err) || wait >= left) {
if (isStopping(err)) (err as Error).message = `${key}: the tool runner was stopping, asked again until the bound of ${bound}ms: ${(err as Error).message}`;
throw err;
}
process.stderr.write(`[mesh-sdk] ${key}: the tool runner is stopping (${(err as Error).message}); asked again in ${wait}ms\n`);
await askPacing.pause(wait);
wait = Math.min(wait * 2, most);
}
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;
@@ -171,10 +154,9 @@ function startSession(): Session {
throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`);
}
},
// A call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound
// ends, as the Go stdio's Ask does (design 47 H2 H-A-542, H-A-544).
// 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 askAgainWhileStopping(key, () => 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"],
@@ -302,7 +284,7 @@ function startSession(): Session {
if (reply.method === undefined && typeof reply.id === "string" && awaiting.has(reply.id)) {
const waiting = awaiting.get(reply.id)!;
awaiting.delete(reply.id);
// A typed fault rides as the error's data `error-kind` (a stopping tool runner's stopping, H-A-542): kept as errorKind.
// 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);
+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();
-24
View File
@@ -1,24 +0,0 @@
// A launched bundle whose one tool asks a seat's verb through the runtime, and says how the ask ended: its answer, or
// whether its fault was the typed fault stopping, and the pauses between its asks (design 47 H2 H-A-542, H-A-544,
// H-A-549). Its pause moves a clock instead of sleeping.
import { broker } from "../../dist/messaging/index.js";
import { registerModuleTools } from "../../dist/tools/index.js";
import { serveRegisteredOverStdio, isStopping, askPacing } from "../../dist/stdio/index.js";
let clock = 0;
let paused = [];
askPacing.now = () => clock;
askPacing.pause = async (ms) => { paused.push(ms); clock += ms; };
registerModuleTools("builder", () => [
{ name: "publish", description: "asks the registry", input: {}, run: async () => {
clock = 0;
paused = [];
try {
return { answer: await broker().request("seat:go-package-registry.publish", {}), paused };
} catch (err) {
return { stopping: isStopping(err), words: err.message, paused };
}
} },
]);
await serveRegisteredOverStdio();
+12 -12
View File
@@ -379,10 +379,10 @@ async function aBundlesFindingWriter(): Promise<void> {
}
}
test("a call a stopping tool runner did not take is asked again after a pause until the new runner answers or the bound ends; a plain refusal and a bare timeout are not (design 47 H2 H-A-542, H-A-544, H-A-549)", async () => {
const child = spawn(process.execPath, [fileURLToPath(new URL("./fixtures/stdio-stopping.mjs", import.meta.url))],
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_KEPT_CALL_PACE_FIRST: "2s", MESH_CONFIG_KEPT_CALL_PACE_MAX: "4s", MESH_CONFIG_ASK_BOUND: "10s" } });
MESH_CONFIG_ASK_BOUND: "50ms" } });
const seen: any[] = [];
let buffered = "";
let said = "";
@@ -404,16 +404,16 @@ test("a call a stopping tool runner did not take is asked again after a pause un
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 [
// The pace and the bound are the settings (2 s doubling to 4 s, a bound of 10 s, H-A-549); the pause moves a clock.
{ id: 2, answers: [{ error: stopping }, { error: stopping }, { result: { published: true } }],
want: { answer: { published: true }, paused: [2000, 4000] } },
{ id: 3, answers: [{ error: stopping }, { error: stopping }, { error: stopping }],
want: { stopping: true, words: `seat:go-package-registry.publish: the tool runner was stopping, asked again until the bound of 10000ms: ${stopping.message}`, paused: [2000, 4000] } },
{ id: 4, answers: [{ error: { code: -32000, message: "refused" } }], want: { stopping: false, words: "refused", paused: [] } },
{ id: 5, answers: [{ error: { code: -32000, message: "timeout" } }], want: { stopping: false, words: "timeout", paused: [] } },
{ 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})`);
@@ -422,9 +422,9 @@ test("a call a stopping tool runner did not take is asked again after a pause un
}
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 ${row.answers.length} times`);
assert.equal(seen.filter((m) => m.method === "mesh/ask" && !m.answered).length, 0, `asked more than ${Math.max(row.answers.length, 1)} times`);
}
assert.match(said, /the tool runner is stopping/);
assert.doesNotMatch(said, /asked again/);
} finally {
child.kill();
}