Compare commits
12
Commits
main
...
feat/47-H2b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc6cebd69b | ||
|
|
6df5d82783 | ||
|
|
e49fe6da5c | ||
|
|
c2972eb338 | ||
|
|
df029926d0 | ||
|
|
eaf16ed5dc | ||
|
|
9392930a68 | ||
|
|
dda65f1cf2 | ||
|
|
eca41b2b57 | ||
|
|
6a097cd036 | ||
|
|
9d0478d12e | ||
|
|
2e192b4ebf |
@@ -5,17 +5,25 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 1279/AC4 (ADR 0443 §4): no module is given a way to ask where its consumer starts. A consumes entry is an event's
|
||||
// name; one that carries a key asking for the stream's history is refused by name, so the safe start is the only one.
|
||||
func TestAConsumesEntryAskingWhereItStartsIsRefused(t *testing.T) { // 1279/AC4
|
||||
// 1279/AC4 (ADR 0443 §4), design 47 H2b §871 (H-A-850): no module is given a way to ask where its consumer starts. A consumes entry is an
|
||||
// event's name or {event, …}; a key beside the event (from, start, deliver) is set aside and named with its path, the entry read as
|
||||
// its event alone, so a registration still refuses the manifest by that unknown word; an object with no event is refused by name.
|
||||
func TestAConsumesEntryAskingWhereItStartsIsRefused(t *testing.T) { // 1279/AC4, 1984/AC-871
|
||||
for _, key := range []string{"from", "start", "deliver"} {
|
||||
raw := `{"module":"audit","version":"1","consumes":[{"event":"shop.order.placed","` + key + `":"beginning"}]}`
|
||||
_, err := decodeForTest([]byte(raw))
|
||||
if err == nil {
|
||||
t.Fatalf("a consumes entry with %q was accepted", key)
|
||||
raw := `{"module":"audit","version":"1","consumes":["a.b",{"event":"shop.order.placed","` + key + `":"beginning"}]}`
|
||||
m, err := decodeForTest([]byte(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("a consumes entry with %q was refused: %v", key, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), `"`+key+`"`) || !strings.Contains(err.Error(), "consumes") {
|
||||
t.Errorf("the refusal for %q does not name the key and the field: %v", key, err)
|
||||
if strings.Join(m.Consumes, " ") != "a.b shop.order.placed" || !strings.Contains(m.SetAside(), "consumes[1]."+key) {
|
||||
t.Errorf("%q: consumes %v, set aside %q", key, m.Consumes, m.SetAside())
|
||||
}
|
||||
if !strings.Contains(m.UnknownField(), `"`+key+`"`) {
|
||||
t.Errorf("%q is not named unknown, which is what a registration refuses by: %q", key, m.UnknownField())
|
||||
}
|
||||
_, err = decodeForTest([]byte(`{"module":"audit","version":"1","consumes":[{"` + key + `":"beginning"}]}`))
|
||||
if err == nil || !strings.Contains(err.Error(), `"`+key+`"`) || !strings.Contains(err.Error(), "consumes") {
|
||||
t.Errorf("the refusal of an entry with %q and no event does not name the key and the field: %v", key, err)
|
||||
}
|
||||
}
|
||||
if _, err := decodeForTest([]byte(`{"module":"audit","version":"1","consumes":["shop.order.placed"]}`)); err != nil {
|
||||
|
||||
+62
-30
@@ -1612,10 +1612,11 @@ func (m *Manifest) UnmarshalJSON(raw []byte) error {
|
||||
// Beside `settings` it is refused by name (MixedFormProblems), never merged into it.
|
||||
delete(keys, ConfigField)
|
||||
}
|
||||
if err := consumesEntryProblem(keys["consumes"]); err != nil {
|
||||
consumesAside, err := readConsumes(keys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
invokeFields, err := readInvokes(keys)
|
||||
invokeFields, invokesAside, err := readInvokes(keys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1705,6 +1706,8 @@ func (m *Manifest) UnmarshalJSON(raw []byte) error {
|
||||
requireShares = read.shares
|
||||
busState, busStateAside = read.busState, read.aside
|
||||
}
|
||||
busStateAside = append(busStateAside, consumesAside...)
|
||||
busStateAside = append(busStateAside, invokesAside...)
|
||||
// The stored form's shares (RequireSharesKey).
|
||||
if stored, ok := keys[RequireSharesKey]; ok {
|
||||
if string(stored) != "null" {
|
||||
@@ -1801,35 +1804,37 @@ type invokeLongForm struct {
|
||||
|
||||
// readInvokes reads `invokes` whose entries are verbs or, in their long form, {verb, fields}: it puts the verbs back in
|
||||
// keys as plain names and answers the fields each long-form entry names.
|
||||
func readInvokes(keys map[string]json.RawMessage) (map[string][]string, error) {
|
||||
// An unknown key of a long-form entry is set aside and said as the path `invokes[i].key` (design 47 H2b §871).
|
||||
func readInvokes(keys map[string]json.RawMessage) (map[string][]string, []string, error) {
|
||||
raw, ok := keys["invokes"]
|
||||
if !ok || string(raw) == "null" {
|
||||
return nil, nil
|
||||
return nil, nil, nil
|
||||
}
|
||||
var entries []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &entries); err != nil {
|
||||
return nil, nil // not a list: the field's own decoder says so
|
||||
return nil, nil, nil // not a list: the field's own decoder says so
|
||||
}
|
||||
var verbs []string
|
||||
var verbs, aside []string
|
||||
var fields map[string][]string
|
||||
for i, e := range entries {
|
||||
trimmed := bytes.TrimSpace(e)
|
||||
if len(trimmed) == 0 || trimmed[0] != '{' {
|
||||
var verb string
|
||||
if err := json.Unmarshal(trimmed, &verb); err != nil {
|
||||
return nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
|
||||
return nil, nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
|
||||
}
|
||||
verbs = append(verbs, verb)
|
||||
continue
|
||||
}
|
||||
var long invokeLongForm
|
||||
dec := json.NewDecoder(bytes.NewReader(trimmed))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&long); err != nil {
|
||||
return nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
|
||||
long, unknown, err := readAside[invokeLongForm](trimmed)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invokes[%d]: a verb, or {verb, fields}: %w", i, err)
|
||||
}
|
||||
for _, path := range unknown {
|
||||
aside = append(aside, fmt.Sprintf("invokes[%d]%s", i, path))
|
||||
}
|
||||
if long.Verb == "" {
|
||||
return nil, fmt.Errorf("invokes[%d]: a long-form entry names its verb", i)
|
||||
return nil, nil, fmt.Errorf("invokes[%d]: a long-form entry names its verb", i)
|
||||
}
|
||||
verbs = append(verbs, long.Verb)
|
||||
if len(long.Fields) > 0 {
|
||||
@@ -1841,10 +1846,10 @@ func readInvokes(keys map[string]json.RawMessage) (map[string][]string, error) {
|
||||
}
|
||||
plain, err := json.Marshal(verbs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
keys["invokes"] = plain
|
||||
return fields, nil
|
||||
return fields, aside, nil
|
||||
}
|
||||
|
||||
// checkSharesNotContributed refuses a module whose own `contributes` to s3-bucket names `shares` (ADR 0468 §8).
|
||||
@@ -1859,30 +1864,57 @@ func (m Manifest) checkSharesNotContributed() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// consumesEntryProblem refuses a consumes entry that is more than an event's name. **No manifest word asks where a
|
||||
// consumer starts** (novox/hq ADR 0443 §4): the controller makes every module's consumer from now, and the first module
|
||||
// that needs a stream's history brings a decision that adds the word. An entry carrying a key such as from, start or
|
||||
// deliver would otherwise be read as a bare "cannot unmarshal object", which says nothing of why.
|
||||
func consumesEntryProblem(raw json.RawMessage) error {
|
||||
// consumesLongForm is an entry of `consumes` in its long form: the event it consumes (design 47 H2b §871, H-A-850).
|
||||
type consumesLongForm struct {
|
||||
Event string `json:"event"`
|
||||
}
|
||||
|
||||
// readConsumes reads `consumes` whose entries are an event's name or, in the long form, {event, …}: it puts the names back in keys
|
||||
// as plain names, and answers the paths of the words it set aside in a long-form entry (`consumes[i].key`). **No manifest word asks
|
||||
// where a consumer starts** (novox/hq ADR 0443 §4): the controller makes every module's consumer from now, so an object with no
|
||||
// `event` (a key such as from, start or deliver alone) is refused, with the reason, never read as a bare "cannot unmarshal object".
|
||||
func readConsumes(keys map[string]json.RawMessage) ([]string, error) {
|
||||
raw := keys["consumes"]
|
||||
var entries []json.RawMessage
|
||||
if len(raw) == 0 || json.Unmarshal(raw, &entries) != nil {
|
||||
return nil // not an array: the ordinary decoding says so
|
||||
return nil, nil // not an array: the ordinary decoding says so
|
||||
}
|
||||
var aside []string
|
||||
plain := make([]any, 0, len(entries))
|
||||
long := false
|
||||
for i, e := range entries {
|
||||
var obj map[string]json.RawMessage
|
||||
if json.Unmarshal(e, &obj) != nil {
|
||||
var v any
|
||||
_ = json.Unmarshal(e, &v)
|
||||
plain = append(plain, v)
|
||||
continue
|
||||
}
|
||||
keys := make([]string, 0, len(obj))
|
||||
for k := range obj {
|
||||
keys = append(keys, strconv.Quote(k))
|
||||
read, unknown, err := readAside[consumesLongForm](e)
|
||||
if err != nil || read.Event == "" {
|
||||
names := make([]string, 0, len(obj))
|
||||
for k := range obj {
|
||||
names = append(names, strconv.Quote(k))
|
||||
}
|
||||
sort.Strings(names)
|
||||
return nil, fmt.Errorf("consumes entry %d is the long form {event, …} or an event's name, and carries the key %s with no event: "+
|
||||
"no word asks where a consumer starts, because the controller makes every module's consumer from now (novox/hq ADR 0443 §4)",
|
||||
i, strings.Join(names, ", "))
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return fmt.Errorf("consumes entry %d carries the key %s: an entry is an event's name alone, and no word asks where a "+
|
||||
"consumer starts, because the controller makes every module's consumer from now (novox/hq ADR 0443 §4)",
|
||||
i, strings.Join(keys, ", "))
|
||||
for _, path := range unknown {
|
||||
aside = append(aside, fmt.Sprintf("consumes[%d]%s", i, path))
|
||||
}
|
||||
plain = append(plain, read.Event)
|
||||
long = true
|
||||
}
|
||||
return nil
|
||||
if long {
|
||||
b, err := json.Marshal(plain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys["consumes"] = b
|
||||
}
|
||||
return aside, nil
|
||||
}
|
||||
|
||||
// MarshalJSON writes `secrets` and `contributes` back in the shape they were read: single values,
|
||||
@@ -2304,7 +2336,7 @@ const WhileStopped = "while-stopped"
|
||||
// one reader of the field for a part that holds no Manifest. An entry of neither form is an error, never none.
|
||||
func InvokedVerbs(raw json.RawMessage) ([]string, error) {
|
||||
keys := map[string]json.RawMessage{"invokes": raw}
|
||||
if _, err := readInvokes(keys); err != nil {
|
||||
if _, _, err := readInvokes(keys); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var verbs []string
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
@@ -62,12 +61,13 @@ func readRequires(raw json.RawMessage) (requiresRead, error) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
var full requirementForm
|
||||
dec := json.NewDecoder(bytes.NewReader(e))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&full); err != nil {
|
||||
full, unknown, err := readAside[requirementForm](e)
|
||||
if err != nil {
|
||||
return requiresRead{}, fmt.Errorf("requires[%d]: a name, or {name, optional} (novox/hq ADR 0330): %w", i, err)
|
||||
}
|
||||
for _, path := range unknown {
|
||||
aside = append(aside, fmt.Sprintf("requires[%d]%s", i, path))
|
||||
}
|
||||
if strings.TrimSpace(full.Name) == "" {
|
||||
return requiresRead{}, fmt.Errorf("requires[%d] names no requirement: {name, optional}", i)
|
||||
}
|
||||
|
||||
@@ -29,14 +29,13 @@ func TestARequirementsLongForm(t *testing.T) {
|
||||
t.Fatalf("written and read back, it says %v optional %v", again.Requires, again.OptionalRequires)
|
||||
}
|
||||
|
||||
// The long form {name, optional} refuses what it does not know.
|
||||
for _, raw := range []string{
|
||||
`{"module":"x","version":"1","requires":[{"name":"influxdb-api","optinal":true}]}`,
|
||||
`{"module":"x","version":"1","requires":[{"optional":true}]}`,
|
||||
} {
|
||||
if _, err := decodeForTest([]byte(raw)); err == nil {
|
||||
t.Errorf("accepted %s", raw)
|
||||
}
|
||||
// The long form {name, optional} sets aside a word it does not know and names it (design 47 H2b §871), and refuses an entry with no name.
|
||||
if m, err := decodeForTest([]byte(`{"module":"x","version":"1","requires":[{"name":"influxdb-api","optinal":true}]}`)); err != nil ||
|
||||
!strings.Contains(m.SetAside(), "requires[0].optinal") || strings.Join(m.Requires, " ") != "influxdb-api" || m.IsOptional("influxdb-api") {
|
||||
t.Errorf("an unknown word of a requires entry: %v, set aside %q, %v", err, m.SetAside(), m.Requires)
|
||||
}
|
||||
if _, err := decodeForTest([]byte(`{"module":"x","version":"1","requires":[{"optional":true}]}`)); err == nil {
|
||||
t.Error("a requires entry with no name was accepted")
|
||||
}
|
||||
|
||||
records := BusStateEntry{Name: "records", Storage: "ledger", Template: "ledger",
|
||||
|
||||
@@ -35,8 +35,8 @@ func TestTheReaderReleaseReadsTheManifestWordsGWrites(t *testing.T) {
|
||||
// manifest read whole, or refused naming what is wrong, and what the reader gives of it.
|
||||
func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, raw, refused string
|
||||
check func(Manifest) bool
|
||||
name, raw, refused, asideOf string
|
||||
check func(Manifest) bool
|
||||
}{
|
||||
{name: "a state's cap (§469)", raw: `{"module":"m","version":"1.0","state":["plain",{"name":"pipelines","max-mib":256}]}`,
|
||||
check: func(m Manifest) bool { return m.State[0].MaxMiB == 0 && m.State[1].MaxMiB == 256 }},
|
||||
@@ -58,9 +58,15 @@ func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
|
||||
len(m.InvokeFields) == 1 && slices.Equal(m.InvokeFields["seat:mesh-catalog.revision"], []string{"none-yet"}) &&
|
||||
strings.Contains(string(out), `"invokes":["*",{"verb":"seat:mesh-catalog.revision","fields":["none-yet"]},"seat:mesh-catalog.entry"]`)
|
||||
}},
|
||||
{name: "a long-form invoke with a word it does not know (§617)",
|
||||
raw: `{"module":"m","version":"1.0","invokes":[{"verb":"seat:mesh-catalog.revision","field":["none-yet"]}]}`,
|
||||
refused: `invokes[0]: a verb, or {verb, fields}`},
|
||||
{name: "a long-form invoke with a word it does not know is read without it and names it (§617, design 47 H2b §871)",
|
||||
raw: `{"module":"m","version":"1.0","invokes":[{"verb":"seat:mesh-catalog.revision","field":["none-yet"],"fields":["a"]}]}`,
|
||||
asideOf: "invokes[0].field",
|
||||
check: func(m Manifest) bool {
|
||||
return slices.Equal(m.Invokes, []string{"seat:mesh-catalog.revision"}) && slices.Equal(m.InvokeFields["seat:mesh-catalog.revision"], []string{"a"})
|
||||
}},
|
||||
{name: "a long-form invoke with no verb",
|
||||
raw: `{"module":"m","version":"1.0","invokes":[{"fields":["a"]}]}`,
|
||||
refused: `invokes[0]: a long-form entry names its verb`},
|
||||
} {
|
||||
m, err := decodeForTest([]byte(c.raw))
|
||||
switch {
|
||||
@@ -68,7 +74,9 @@ func TestTheSecondReaderReleaseReadsGsManifestWords(t *testing.T) {
|
||||
t.Errorf("%s: read as %v, want refused naming %q", c.name, err, c.refused)
|
||||
case c.refused == "" && err != nil:
|
||||
t.Errorf("%s: refused: %v", c.name, err)
|
||||
case c.refused == "" && (len(m.UnknownField()) != 0 || !c.check(m)):
|
||||
case c.asideOf != "" && (!strings.Contains(m.SetAside(), c.asideOf) || !c.check(m)):
|
||||
t.Errorf("%s: read as %+v, set aside %q, want %q named", c.name, m, m.SetAside(), c.asideOf)
|
||||
case c.refused == "" && c.asideOf == "" && (len(m.UnknownField()) != 0 || !c.check(m)):
|
||||
t.Errorf("%s: read as %+v (set aside %v)", c.name, m, m.UnknownField())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,3 +170,45 @@ func removeEvery(v any, key string) int {
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// readAside reads one object of a manifest into a T, setting aside each key T does not know, at any depth, and saying where each
|
||||
// was, as `.key` or `.entry.key` (design 47 H2b §871): the entry reads as it would without the word. Any other fault in it is the
|
||||
// decoder's own and is returned.
|
||||
func readAside[T any](raw json.RawMessage) (T, []string, error) {
|
||||
var zero T
|
||||
var tree any
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.UseNumber()
|
||||
if err := dec.Decode(&tree); err != nil {
|
||||
return zero, nil, err
|
||||
}
|
||||
strict := func(into *T) error {
|
||||
b, err := json.Marshal(tree)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(b))
|
||||
d.DisallowUnknownFields()
|
||||
return typedUnknown(d.Decode(into))
|
||||
}
|
||||
var aside []string
|
||||
for tries := 0; ; tries++ {
|
||||
var out T
|
||||
err := strict(&out)
|
||||
if err == nil {
|
||||
return out, aside, nil
|
||||
}
|
||||
unknown := asUnknownField(err)
|
||||
if unknown == nil || tries > 64 {
|
||||
return zero, nil, err
|
||||
}
|
||||
path, ok := removalThatHelps(tree, unknown.Field, err.Error(), func() error { var e T; return strict(&e) })
|
||||
if !ok {
|
||||
if removeEvery(tree, unknown.Field) == 0 {
|
||||
return zero, nil, err
|
||||
}
|
||||
path = "." + unknown.Field
|
||||
}
|
||||
aside = append(aside, path)
|
||||
}
|
||||
}
|
||||
|
||||
+425
-127
@@ -2,14 +2,18 @@ package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
@@ -19,7 +23,8 @@ import (
|
||||
// handler whose pattern it matches. A message no handler takes is acknowledged and said, never left to be redelivered.
|
||||
// The hub never makes the stream or the consumer: they are the controller's, and a bus without them is an error of Start.
|
||||
//
|
||||
// Register every handler, then Start once: a message heard before its handler is registered would be taken by none.
|
||||
// Register every handler, then Start once: a message heard before its handler is registered would be taken by none, so a handler
|
||||
// registered after Start is refused, naming its pattern.
|
||||
type EventHub struct {
|
||||
logf func(string, ...any)
|
||||
|
||||
@@ -27,12 +32,36 @@ type EventHub struct {
|
||||
routes []hubRoute
|
||||
cons jetstream.ConsumeContext
|
||||
bound []func(created time.Time)
|
||||
// allHeard are told each time every registered pattern comes to be heard (OnAllHeard).
|
||||
allHeard []func()
|
||||
// started is Start's; gen numbers it; bus, cred and ctx are what its wakes bind with; stopWake ends the wake.
|
||||
started bool
|
||||
process string
|
||||
gen int
|
||||
bus hubBus
|
||||
cred Account
|
||||
ctx context.Context
|
||||
stopWake func()
|
||||
// heard are the durables bound, by stream; why is what each stream not bound is said to lack.
|
||||
heard map[string]jetstream.ConsumeContext
|
||||
why map[string]string
|
||||
// eventsSubjects are EVENTS' own, read once; unheardNow the patterns not heard as of the last pass; allTold says
|
||||
// OnAllHeard was told for the present state.
|
||||
eventsSubjects []string
|
||||
unheardNow []Unheard
|
||||
allTold bool
|
||||
// late are the patterns refused after Start (they stay unheard); lastTold the list the hooks were last told, and toldOnce says
|
||||
// a pass told them (Start's, whatever the list).
|
||||
late []Unheard
|
||||
lastTold []Unheard
|
||||
toldOnce bool
|
||||
passed bool
|
||||
unheardTo []func([]Unheard)
|
||||
passMu sync.Mutex
|
||||
// unhandled are told each subject no handler took (OnUnhandled).
|
||||
unhandled []func(subject string)
|
||||
// overruns are told the handlings past event-overrun (OnOverrun).
|
||||
overruns []func(past []Handling)
|
||||
// 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
|
||||
@@ -86,16 +115,41 @@ func (h *EventHub) handleByKey(pattern string, handle func(jetstream.Msg), keyOf
|
||||
return fmt.Errorf("an event handler needs a subject pattern and a handler")
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
for _, r := range h.routes {
|
||||
if subjectsOverlap(r.pattern, pattern) {
|
||||
h.mu.Unlock()
|
||||
return fmt.Errorf("the events %q overlap %q, already handled: a message has one taker", pattern, r.pattern)
|
||||
}
|
||||
}
|
||||
if h.started {
|
||||
// An event no registered pattern covers (its first adopt) is not heard; one an earlier handler takes is.
|
||||
err := fmt.Errorf("the events %q are registered after Start: register every handler, then Start once (design 47 H2b §836 3.)", pattern)
|
||||
late := Unheard{pattern, "", "registered after Start"}
|
||||
if !slices.Contains(h.late, late) {
|
||||
h.late = append(h.late, late)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
h.announce()
|
||||
return err
|
||||
}
|
||||
defer h.mu.Unlock()
|
||||
h.routes = append(h.routes, hubRoute{pattern, handle, keyOf})
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForProcess names the process whose own durable the hub binds, on EVENTS and on every kept seat event's stream, in place of the
|
||||
// module's: `<node>_<module>_<process>`, such as the bus module's keeper's `<node>_nats_keeper` (design 47 H2b §836 5., H-A-876).
|
||||
// Every other behaviour of Start is unchanged. Call it before Start; after it the call is refused.
|
||||
func (h *EventHub) ForProcess(process string) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.started {
|
||||
return fmt.Errorf("the hub is started: name its process before Start")
|
||||
}
|
||||
h.process = process
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnBound registers f, told each time the hub binds the module's consumer, with when the bus made it. A consumer is made
|
||||
// from now (ADR 0443), so an event said before it was made is not delivered to it: a part that took a picture before
|
||||
// that must ask its owner again (views.Follower.ConsumerMade). So every handler of an event that ends a kept call's wait
|
||||
@@ -126,6 +180,23 @@ func (h *EventHub) OnOverrun(f func(past []Handling)) {
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// OnAllHeard registers f, told each time the hub comes to hear every registered pattern: at Start, or at the bind that completes
|
||||
// them (design 47 H2b §836 1.). A part that does what waits on its events being live does it there. Register before Start.
|
||||
func (h *EventHub) OnAllHeard(f func()) {
|
||||
h.mu.Lock()
|
||||
h.allHeard = append(h.allHeard, f)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// OnUnheard registers f, told the patterns the hub does not hear, each with its stream and why, whenever that list changes, Start
|
||||
// included, and an empty list once every pattern is heard, as OnOverrun is told (design 47 H2b §836 4.): the process reader raises
|
||||
// the finding `events-unheard` from it. A pattern refused after Start is in the list. Register before Start.
|
||||
func (h *EventHub) OnUnheard(f func(unheard []Unheard)) {
|
||||
h.mu.Lock()
|
||||
h.unheardTo = append(h.unheardTo, f)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// Patterns are the registered subject patterns, in order.
|
||||
func (h *EventHub) Patterns() []string {
|
||||
h.mu.RLock()
|
||||
@@ -137,93 +208,374 @@ func (h *EventHub) Patterns() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// Start binds the module's durable on the shared events stream and pulls it; a call after a start that took does
|
||||
// nothing. It makes no stream and no consumer: a consumer the bus does not hold yet is the error of this call, and a
|
||||
// later call (the module's next change of membership) binds it, so a part is not lost for the bus's order.
|
||||
// durablesComposedSubject is where the seat `mesh-grants` says it composed a module's durables, for the module on its node:
|
||||
// the hub binds again each stream it has not bound (design 47 H2b §836 2., H-A-835). The subject is the seat's definition's
|
||||
// alone: the hub reads no body.
|
||||
func durablesComposedSubject(cred Account) string {
|
||||
return seatdef.EventSubject(buscompose.GrantsModule, "durables-composed") + "." + cred.Node + "." + cred.Module
|
||||
}
|
||||
|
||||
// Start binds the module's durable `<node>_<module>` (the process's own, `<node>_<module>_<process>`, when ForProcess named one) on the shared events stream and on every kept seat event's stream
|
||||
// (`SEAT_<seat>_<event>`) that carries a registered pattern, and pulls them (design 47 H2b §836 1.); a call after a start does
|
||||
// nothing. It makes no stream and no consumer. A durable the bus does not hold yet, or refuses, is no error of this call and
|
||||
// is not waited for on a timer: it is said (the journal) and bound when the seat `mesh-grants` says it composed the module's
|
||||
// durables, and at the bus connection's reconnect (§836 2.), and OnAllHeard is told when every pattern is heard. Start's nil says
|
||||
// the hub is started, never that anything is heard: what waits on a stream being heard goes in OnAllHeard, and the patterns not
|
||||
// heard are told to OnUnheard (design 47 H2b §836 1., 4., H-A-877).
|
||||
func (h *EventHub) Start(ctx context.Context, js jetstream.JetStream, cred Account) error {
|
||||
h.mu.RLock()
|
||||
process := h.process
|
||||
h.mu.RUnlock()
|
||||
return h.start(ctx, natsHubBus{js: js, cred: cred, process: process}, cred)
|
||||
}
|
||||
|
||||
// hubBus is what the hub asks of the bus: the kept streams, the subjects of EVENTS, the pulls of its durables, and the wakes.
|
||||
type hubBus interface {
|
||||
streamNames(ctx context.Context) ([]string, error)
|
||||
streamSubjects(ctx context.Context, stream string) ([]string, error)
|
||||
// hearEvents pulls the module's durable on EVENTS, held by feed; created is when the bus made the durable.
|
||||
hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
|
||||
hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
|
||||
// wake calls f at each message on subject (a plain subscription); stop ends it.
|
||||
wake(subject string, f func()) (stop func(), err error)
|
||||
// reconnected calls f at each reconnect of the bus connection.
|
||||
reconnected(f func())
|
||||
}
|
||||
|
||||
type natsHubBus struct {
|
||||
js jetstream.JetStream
|
||||
cred Account
|
||||
process string
|
||||
}
|
||||
|
||||
func (b natsHubBus) streamNames(ctx context.Context) ([]string, error) {
|
||||
names := b.js.StreamNames(ctx)
|
||||
var out []string
|
||||
for name := range names.Name() {
|
||||
out = append(out, name)
|
||||
}
|
||||
return out, names.Err()
|
||||
}
|
||||
|
||||
func (b natsHubBus) streamSubjects(ctx context.Context, stream string) ([]string, error) {
|
||||
s, err := b.js.Stream(ctx, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.CachedInfo().Config.Subjects, nil
|
||||
}
|
||||
|
||||
func (b natsHubBus) hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
|
||||
cons, err := b.js.Consumer(ctx, EventsStream, b.cred.durableOf(b.process))
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
if info := cons.CachedInfo(); info != nil {
|
||||
feed.start(info.Config.AckWait)
|
||||
}
|
||||
cc, err := hearHeld(cons, callerOutside(), feed.hold, handle, logf)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
info, err := cons.Info(ctx)
|
||||
if err != nil {
|
||||
logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", b.cred.durableOf(b.process), EventsStream, err)
|
||||
return cc, time.Time{}, nil
|
||||
}
|
||||
return cc, info.Created.UTC(), nil
|
||||
}
|
||||
|
||||
func (b natsHubBus) hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
|
||||
cc, err := b.cred.HearSeatEvents(ctx, b.js, stream, handle, logf, heldBy(feed), forProcess(b.process))
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
cons, err := b.js.Consumer(ctx, stream, b.cred.durableOf(b.process))
|
||||
if err != nil {
|
||||
return cc, time.Time{}, nil
|
||||
}
|
||||
info, err := cons.Info(ctx)
|
||||
if err != nil {
|
||||
return cc, time.Time{}, nil
|
||||
}
|
||||
return cc, info.Created.UTC(), nil
|
||||
}
|
||||
|
||||
func (b natsHubBus) wake(subject string, f func()) (func(), error) {
|
||||
sub, err := b.js.Conn().Subscribe(subject, func(*nats.Msg) { f() })
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func() { _ = sub.Unsubscribe() }, nil
|
||||
}
|
||||
|
||||
func (b natsHubBus) reconnected(f func()) {
|
||||
nc := b.js.Conn()
|
||||
before := nc.Opts.ReconnectedCB
|
||||
nc.SetReconnectHandler(func(c *nats.Conn) {
|
||||
if before != nil {
|
||||
before(c)
|
||||
}
|
||||
f()
|
||||
})
|
||||
}
|
||||
|
||||
// Unheard is a registered pattern the hub does not hear: the stream that should carry it ("" when none does) and why (design 47
|
||||
// H2b §836 4.): "no stream carries it", "not composed", "refused: <the bus's words>" or "registered after Start".
|
||||
type Unheard struct{ Pattern, Stream, Why string }
|
||||
|
||||
func (h *EventHub) start(ctx context.Context, bus hubBus, cred Account) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cons != nil {
|
||||
if h.started {
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
cons, err := cred.EventConsumer(ctx, js, EventsStream)
|
||||
if err == nil {
|
||||
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()
|
||||
}
|
||||
}
|
||||
h.started = true
|
||||
h.gen++
|
||||
gen := h.gen
|
||||
h.bus, h.cred, h.ctx = bus, cred, ctx
|
||||
h.mu.Unlock()
|
||||
rebind := func() { h.rebind(gen) }
|
||||
// The wake is made before the first bind, so a durable composed while a bind fails is heard (§836 2.).
|
||||
stop, err := bus.wake(durablesComposedSubject(cred), rebind)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the consumer %s on %s is not heard: %w", cred.EventConsumerName(), EventsStream, err)
|
||||
}
|
||||
if info, ierr := cons.Info(ctx); ierr != nil {
|
||||
h.logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", cred.EventConsumerName(), EventsStream, ierr)
|
||||
h.logf("events: the grants part's word of the module's durables is not heard (%v): a stream not bound is bound at the bus connection's reconnect or the module's next start", err)
|
||||
} else {
|
||||
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", cred.EventConsumerName(), EventsStream, info.Created.UTC().Format(time.RFC3339))
|
||||
for _, f := range h.bound {
|
||||
f(info.Created.UTC())
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.stopWake = stop
|
||||
h.mu.Unlock()
|
||||
}
|
||||
bus.reconnected(rebind)
|
||||
h.pass(ctx, bus, cred)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartUntilBound is Start that does not give up: when the module's consumer is not there yet it returns that error at
|
||||
// once, and tries again on a goroutine of its own, after each wait, until it binds or ctx ends; then live is called (nil
|
||||
// calls nothing), so a part that needs the events path live does what it does only then. wait returns false to stop
|
||||
// trying (nil waits five seconds or for ctx). The bus makes the consumer when the module's account is composed, which
|
||||
// says nothing a module can hear before the consumer exists, so the retry is a wait on that, bounded by ctx.
|
||||
func (h *EventHub) StartUntilBound(ctx context.Context, js jetstream.JetStream, cred Account, wait func(context.Context) bool, live func()) error {
|
||||
err := h.Start(ctx, js, cred)
|
||||
if err == nil {
|
||||
if live != nil {
|
||||
live()
|
||||
}
|
||||
return nil
|
||||
// rebind is a pass of the start numbered gen, at a wake or a reconnect; one of an ended or later start does nothing.
|
||||
func (h *EventHub) rebind(gen int) {
|
||||
h.mu.RLock()
|
||||
ok, ctx, bus, cred := h.started && h.gen == gen, h.ctx, h.bus, h.cred
|
||||
h.mu.RUnlock()
|
||||
if ok && ctx.Err() == nil {
|
||||
h.pass(ctx, bus, cred)
|
||||
}
|
||||
if wait == nil {
|
||||
wait = func(ctx context.Context) bool {
|
||||
t := time.NewTimer(5 * time.Second)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
for wait(ctx) && ctx.Err() == nil {
|
||||
if h.Start(ctx, js, cred) == nil {
|
||||
if live != nil {
|
||||
live()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return err
|
||||
}
|
||||
|
||||
// Stop ends the pull.
|
||||
// pass binds every durable not bound that a registered pattern needs (EVENTS' always), says OnBound at each bind and OnAllHeard
|
||||
// when the hub comes to hear every registered pattern.
|
||||
func (h *EventHub) pass(ctx context.Context, bus hubBus, cred Account) {
|
||||
h.passMu.Lock()
|
||||
defer h.passMu.Unlock()
|
||||
patterns := h.Patterns()
|
||||
names, nerr := bus.streamNames(ctx)
|
||||
if nerr != nil {
|
||||
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard now", nerr)
|
||||
}
|
||||
h.mu.RLock()
|
||||
eventsSubjects := h.eventsSubjects
|
||||
h.mu.RUnlock()
|
||||
if eventsSubjects == nil {
|
||||
subjects, err := bus.streamSubjects(ctx, EventsStream)
|
||||
if err != nil {
|
||||
h.logf("events: the subjects of %s are not read (%v): every pattern no kept stream takes is taken to be carried by it", EventsStream, err)
|
||||
} else {
|
||||
h.mu.Lock()
|
||||
h.eventsSubjects = subjects
|
||||
h.mu.Unlock()
|
||||
eventsSubjects = subjects
|
||||
}
|
||||
}
|
||||
// Each pattern is carried by every kept stream whose subjects take it, else by EVENTS (H-A-834).
|
||||
carriers := make([][]string, len(patterns))
|
||||
need := map[string]bool{}
|
||||
for i, p := range patterns {
|
||||
for _, stream := range names {
|
||||
seat, event, ok := keptSeatEvent(stream)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
subject := seatdef.EventSubject(seat, event)
|
||||
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
|
||||
carriers[i] = append(carriers[i], stream)
|
||||
need[stream] = true
|
||||
}
|
||||
}
|
||||
if len(carriers[i]) == 0 && h.eventsTake(eventsSubjects, p) {
|
||||
carriers[i] = []string{EventsStream}
|
||||
}
|
||||
}
|
||||
if !h.hasKept(EventsStream) {
|
||||
h.bindOne(ctx, bus, cred, EventsStream)
|
||||
}
|
||||
var streams []string
|
||||
for stream := range need {
|
||||
streams = append(streams, stream)
|
||||
}
|
||||
slices.Sort(streams)
|
||||
for _, stream := range streams {
|
||||
if !h.hasKept(stream) {
|
||||
h.bindOne(ctx, bus, cred, stream)
|
||||
}
|
||||
}
|
||||
var not []Unheard
|
||||
h.mu.RLock()
|
||||
for i, p := range patterns {
|
||||
if len(carriers[i]) == 0 {
|
||||
why := "no stream carries it"
|
||||
if nerr != nil {
|
||||
why = fmt.Sprintf("the streams are not listed (%v)", nerr)
|
||||
}
|
||||
not = append(not, Unheard{p, "", why})
|
||||
}
|
||||
for _, stream := range carriers[i] {
|
||||
if _, bound := h.heard[stream]; !bound {
|
||||
not = append(not, Unheard{p, stream, h.why[stream]})
|
||||
}
|
||||
}
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
h.mu.Lock()
|
||||
h.unheardNow, h.passed = not, true
|
||||
all := len(not) == 0
|
||||
tell := all && !h.allTold
|
||||
h.allTold = all
|
||||
told := h.allHeard
|
||||
h.mu.Unlock()
|
||||
h.announce()
|
||||
if tell {
|
||||
for _, f := range told {
|
||||
f()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// announce says the patterns not heard (the journal, one line each) and tells each OnUnheard hook, when the list differs from the one
|
||||
// told last or none was told yet (Start's pass tells even an empty list: a restarted program clears what an earlier process raised).
|
||||
// Nothing is told before a pass has made the list.
|
||||
func (h *EventHub) announce() {
|
||||
h.mu.Lock()
|
||||
if !h.passed {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
list := append(slices.Clone(h.unheardNow), h.late...)
|
||||
if h.toldOnce && slices.Equal(list, h.lastTold) {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
h.toldOnce, h.lastTold = true, list
|
||||
hooks := slices.Clone(h.unheardTo)
|
||||
h.mu.Unlock()
|
||||
for _, u := range list {
|
||||
switch {
|
||||
case u.Stream == "":
|
||||
h.logf("events: the pattern %s is not heard: %s", u.Pattern, u.Why)
|
||||
default:
|
||||
h.logf("events: the pattern %s is not heard on %s: %s", u.Pattern, u.Stream, u.Why)
|
||||
}
|
||||
}
|
||||
for _, f := range hooks {
|
||||
f(slices.Clone(list))
|
||||
}
|
||||
}
|
||||
|
||||
// eventsTake says whether EVENTS carries pattern: some subject of its own overlaps it (all of them, when they are not read).
|
||||
func (h *EventHub) eventsTake(subjects []string, pattern string) bool {
|
||||
if subjects == nil {
|
||||
return true
|
||||
}
|
||||
for _, s := range subjects {
|
||||
if subjectsOverlap(s, pattern) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *EventHub) hasKept(stream string) bool {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
_, ok := h.heard[stream]
|
||||
return ok
|
||||
}
|
||||
|
||||
// bindOne binds the module's durable on stream (EventsStream or a kept seat event's) and says each bind to OnBound; what it
|
||||
// cannot is said and kept as the stream's reason.
|
||||
func (h *EventHub) bindOne(ctx context.Context, bus hubBus, cred Account, stream string) {
|
||||
h.mu.Lock()
|
||||
feed := h.newFeed()
|
||||
h.mu.Unlock()
|
||||
var (
|
||||
cc jetstream.ConsumeContext
|
||||
created time.Time
|
||||
err error
|
||||
)
|
||||
if stream == EventsStream {
|
||||
if err = h.held.settle(); err == nil {
|
||||
cc, created, err = bus.hearEvents(ctx, feed, h.hearOn(feed), h.logf)
|
||||
}
|
||||
} else {
|
||||
cc, created, err = bus.hearKept(ctx, stream, feed, h.hearOn(feed), h.logf)
|
||||
}
|
||||
if err != nil {
|
||||
feed.end()
|
||||
why := "refused: " + err.Error()
|
||||
if errors.Is(err, jetstream.ErrConsumerNotFound) {
|
||||
why = "not composed: the bus holds no durable " + h.durable(cred) + " on it"
|
||||
}
|
||||
h.mu.Lock()
|
||||
if h.why == nil {
|
||||
h.why = map[string]string{}
|
||||
}
|
||||
changed := h.why[stream] != why
|
||||
h.why[stream] = why
|
||||
h.mu.Unlock()
|
||||
if changed {
|
||||
h.logf("events: the consumer %s on %s is not heard: %s (%v)", h.durable(cred), stream, why, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
if h.heard == nil {
|
||||
h.heard = map[string]jetstream.ConsumeContext{}
|
||||
}
|
||||
h.heard[stream] = cc
|
||||
delete(h.why, stream)
|
||||
if stream == EventsStream {
|
||||
h.cons = cc
|
||||
}
|
||||
bound := h.bound
|
||||
h.mu.Unlock()
|
||||
if created.IsZero() {
|
||||
h.logf("events: the consumer %s on %s is heard", h.durable(cred), stream)
|
||||
return
|
||||
}
|
||||
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", h.durable(cred), stream, created.Format(time.RFC3339))
|
||||
for _, f := range bound {
|
||||
f(created)
|
||||
}
|
||||
}
|
||||
|
||||
// durable is the name of the durable the hub binds: the module's, or its process's (ForProcess).
|
||||
func (h *EventHub) durable(cred Account) string {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return cred.durableOf(h.process)
|
||||
}
|
||||
|
||||
// Stop ends the pulls and the wake.
|
||||
func (h *EventHub) Stop() {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cons != nil {
|
||||
h.cons.Stop()
|
||||
h.cons = nil
|
||||
}
|
||||
for _, cc := range h.kept {
|
||||
for _, cc := range h.heard {
|
||||
cc.Stop()
|
||||
}
|
||||
h.kept = nil
|
||||
h.heard, h.why, h.cons = nil, nil, nil
|
||||
if h.stopWake != nil {
|
||||
h.stopWake()
|
||||
h.stopWake = nil
|
||||
}
|
||||
h.started, h.allTold, h.unheardNow = false, false, nil
|
||||
h.passed, h.toldOnce, h.lastTold, h.late = false, false, nil, nil
|
||||
for _, f := range h.feeds {
|
||||
f.end()
|
||||
}
|
||||
@@ -238,60 +590,6 @@ func (h *EventHub) newFeed() *eventFeed {
|
||||
return f
|
||||
}
|
||||
|
||||
// StartKept binds, beside EVENTS, the module's durable on each kept seat event's stream (`SEAT_<seat>_<event>`) whose event a
|
||||
// registered pattern takes: a kept event is never on EVENTS, and the tool runner reads its own twin of that durable (lead
|
||||
// answer A-397), so the program hears it only here. Each stream bound is said, and each it cannot bind (no durable composed
|
||||
// for this module there, or the bus refuses) is said and passed over. It returns how many it bound.
|
||||
func (h *EventHub) StartKept(ctx context.Context, js jetstream.JetStream, cred Account) int {
|
||||
h.mu.RLock()
|
||||
var patterns []string
|
||||
for _, r := range h.routes {
|
||||
patterns = append(patterns, r.pattern)
|
||||
}
|
||||
h.mu.RUnlock()
|
||||
names := js.StreamNames(ctx)
|
||||
var streams []string
|
||||
for name := range names.Name() {
|
||||
streams = append(streams, name)
|
||||
}
|
||||
if err := names.Err(); err != nil {
|
||||
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard", err)
|
||||
}
|
||||
bound := 0
|
||||
for _, stream := range streams {
|
||||
seat, event, ok := keptSeatEvent(stream)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
subject := "mesh.seat." + seat + ".event." + event
|
||||
taken := false
|
||||
for _, p := range patterns {
|
||||
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
|
||||
taken = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !taken {
|
||||
continue
|
||||
}
|
||||
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
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.kept = append(h.kept, cc)
|
||||
h.mu.Unlock()
|
||||
bound++
|
||||
h.logf("events: the consumer %s on %s is heard (the kept event %s.%s)", cred.EventConsumerName(), stream, seat, event)
|
||||
}
|
||||
return bound
|
||||
}
|
||||
|
||||
// keptSeatEvent is the seat and the event a kept seat event's stream carries, from its name `SEAT_<seat>_<event>` (seatdef.KeptStream):
|
||||
// a seat's and an event's names hold no underscore.
|
||||
func keptSeatEvent(stream string) (seat, event string, ok bool) {
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
)
|
||||
|
||||
// A module whose consumer the bus makes after the module started is not lost for that order: the hub tries again after
|
||||
// each wait and calls live once it is bound (the checker's "until it starts again" hole).
|
||||
// A module whose durable the bus makes after the module started is not lost for that order: the hub binds it when the
|
||||
// grants part says it composed the module's durables, and tells OnAllHeard.
|
||||
func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
|
||||
nc, err := nats.Connect(testbus.URL(t))
|
||||
if err != nil {
|
||||
@@ -35,35 +35,32 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
|
||||
}
|
||||
cred := process.Account{Node: "n1", Module: "late"}
|
||||
hub := process.NewEventHub(t.Logf)
|
||||
waits, live := make(chan chan bool), make(chan struct{}, 1)
|
||||
wait := func(ctx context.Context) bool {
|
||||
step := make(chan bool)
|
||||
select {
|
||||
case waits <- step:
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
return <-step
|
||||
live := make(chan struct{}, 4)
|
||||
hub.OnAllHeard(func() { live <- struct{}{} })
|
||||
if err := hub.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := hub.StartUntilBound(ctx, js, cred, wait, func() { live <- struct{}{} }); err == nil {
|
||||
t.Fatal("no consumer was there, and the start said nothing")
|
||||
// Start with no durable composed says nothing is live and arms no timer; the grants part's word that it composed the
|
||||
// module's durables binds it (design 47 H2b §836 2.).
|
||||
if err := hub.Start(ctx, js, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hub.Stop()
|
||||
select {
|
||||
case <-live:
|
||||
t.Fatal("live before the consumer was there")
|
||||
default:
|
||||
default: // Start's pass is synchronous: OnAllHeard is told inside it or not at all
|
||||
}
|
||||
step := <-waits
|
||||
step <- true // tried again: still no consumer
|
||||
step = <-waits
|
||||
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
step <- true
|
||||
if err := nc.Publish("mesh.seat.mesh-grants.event.durables-composed.n1.late", []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-live:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the consumer was made and the hub never said it is live")
|
||||
t.Fatal("the durables were composed and the hub never said it is live")
|
||||
}
|
||||
// H-A-90: a durable named for a suffix is bound beside the module's own.
|
||||
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName() + "_main", AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
|
||||
@@ -76,7 +73,6 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
|
||||
if _, err := cred.NamedEventConsumer(ctx, js, process.EventsStream, "other"); err == nil {
|
||||
t.Fatal("a named consumer nobody made was bound")
|
||||
}
|
||||
hub.Stop()
|
||||
}
|
||||
|
||||
// W1.12: a module hears a seat's event kept last per subject on its own stream through its durable, made by the maker
|
||||
@@ -124,7 +120,6 @@ func subAModuleHearsASeatEventKeptOnItsOwnStream(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cc.Stop()
|
||||
heard := map[string]bool{}
|
||||
for len(heard) < 2 {
|
||||
select {
|
||||
@@ -152,6 +147,79 @@ func subAModuleHearsASeatEventKeptOnItsOwnStream(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the durable was not followed after the read")
|
||||
}
|
||||
// Design 47 H2b §836 1., H-A-855: the hub's Start alone binds the kept stream the registered pattern needs and tells OnAllHeard, with
|
||||
// no StartKept; a handler of the kept seat event then hears it.
|
||||
cc.Stop()
|
||||
hub := process.NewEventHub(t.Logf)
|
||||
allHeard := make(chan struct{}, 1)
|
||||
hub.OnAllHeard(func() { allHeard <- struct{}{} })
|
||||
hubHeard := make(chan string, 4)
|
||||
if err := hub.Handle("mesh.seat.node-engine.event.running.>", func(m jetstream.Msg) { hubHeard <- string(m.Data()); _ = m.Ack() }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := hub.Start(ctx, js, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hub.Stop()
|
||||
select {
|
||||
case <-allHeard:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the hub's start bound the kept stream and said nothing")
|
||||
}
|
||||
if _, err := js.Publish(ctx, "mesh.seat.node-engine.event.running.n1.mesh-tools", []byte("fp5")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for heard := ""; heard != "fp5"; {
|
||||
select {
|
||||
case heard = <-hubHeard:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the hub's start did not hear the kept seat event")
|
||||
}
|
||||
}
|
||||
// Design 47 H2b §836 5., H-A-876: a hub for a process binds the durable of the process's own name, with the module's gone.
|
||||
hub.Stop()
|
||||
if err := js.DeleteConsumer(ctx, kept, cred.EventConsumerName()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
own := cred.SeatEventConsumerConfig(subjects, true)
|
||||
own.Durable = cred.EventConsumerName() + "_keeper"
|
||||
own.DeliverPolicy = jetstream.DeliverNewPolicy
|
||||
if _, err := js.CreateOrUpdateConsumer(ctx, kept, own); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keeper := process.NewEventHub(t.Logf)
|
||||
keeperHeard := make(chan string, 4)
|
||||
keeperAll := make(chan struct{}, 1)
|
||||
keeper.OnAllHeard(func() { keeperAll <- struct{}{} })
|
||||
if err := keeper.Handle("mesh.seat.node-engine.event.running.>", func(m jetstream.Msg) { keeperHeard <- string(m.Data()); _ = m.Ack() }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := keeper.ForProcess("keeper"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := keeper.Start(ctx, js, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer keeper.Stop()
|
||||
if keeper.ForProcess("other") == nil {
|
||||
t.Error("a process was named after Start")
|
||||
}
|
||||
select {
|
||||
case <-keeperAll:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the hub for a process did not bind its own durable")
|
||||
}
|
||||
if _, err := js.Publish(ctx, "mesh.seat.node-engine.event.running.n1.mesh-tools", []byte("fp6")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the start read of a stream kept last per subject hands the last of each subject first
|
||||
for got := ""; got != "fp6"; {
|
||||
select {
|
||||
case got = <-keeperHeard:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the process's durable heard nothing")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A-181: a module hears another module's own stream kept last per subject (a manifest's `streams` entry with `last-per-subject`) as
|
||||
|
||||
@@ -2,6 +2,7 @@ package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"slices"
|
||||
@@ -31,6 +32,7 @@ func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) {
|
||||
t.Errorf("overlap(%s, %s) = %v", c.a, c.b, got)
|
||||
}
|
||||
}
|
||||
t.Run("TheHubStartBindsEveryPatternAndSaysWhenAllAreHeard", subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard)
|
||||
h := NewEventHub(nil)
|
||||
nop := func(jetstream.Msg) {}
|
||||
if err := h.Handle("mesh.mod.p.event.>", nop); err != nil {
|
||||
@@ -433,3 +435,214 @@ func TestAHandlingPastEventOverrunTellsItsHookWhileItRuns(t *testing.T) {
|
||||
var _ interface {
|
||||
Handle(string, func(jetstream.Msg)) error
|
||||
} = (*EventHub)(nil)
|
||||
|
||||
// fakeHubBus is the bus the hub's start asks of: which durables are composed, and the wakes it is given.
|
||||
type fakeHubBus struct {
|
||||
mu sync.Mutex
|
||||
streams []string
|
||||
subjects []string
|
||||
composed map[string]error // a stream whose durable is composed has a nil entry; any other is not
|
||||
binds []string
|
||||
wakeAt string
|
||||
onWake func()
|
||||
reconn func()
|
||||
stopped bool
|
||||
// missed is called, with no lock held, from inside a bind that finds no durable composed (a test composes it there).
|
||||
missed func(stream string)
|
||||
}
|
||||
|
||||
func (b *fakeHubBus) streamNames(context.Context) ([]string, error) { return b.streams, nil }
|
||||
func (b *fakeHubBus) streamSubjects(context.Context, string) ([]string, error) {
|
||||
return b.subjects, nil
|
||||
}
|
||||
func (b *fakeHubBus) bind(stream string) (jetstream.ConsumeContext, time.Time, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
err, ok := b.composed[stream]
|
||||
if !ok {
|
||||
if b.missed != nil {
|
||||
b.mu.Unlock()
|
||||
b.missed(stream)
|
||||
b.mu.Lock()
|
||||
}
|
||||
return nil, time.Time{}, fmt.Errorf("no durable: %w", jetstream.ErrConsumerNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
b.binds = append(b.binds, stream)
|
||||
return &pullContext{closed: make(chan struct{})}, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), nil
|
||||
}
|
||||
func (b *fakeHubBus) hearEvents(_ context.Context, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
|
||||
return b.bind(EventsStream)
|
||||
}
|
||||
func (b *fakeHubBus) hearKept(_ context.Context, stream string, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
|
||||
return b.bind(stream)
|
||||
}
|
||||
func (b *fakeHubBus) wake(subject string, f func()) (func(), error) {
|
||||
b.wakeAt, b.onWake = subject, f
|
||||
return func() { b.stopped = true }, nil
|
||||
}
|
||||
func (b *fakeHubBus) reconnected(f func()) { b.reconn = f }
|
||||
|
||||
// Design 47 H2b §836 1., 2. (1984/AC-836a, AC-836b): Start alone binds a kept seat event's stream beside EVENTS and tells OnAllHeard
|
||||
// once; a durable not composed at Start is bound when the grants part says it composed the module's durables, and again at a
|
||||
// reconnect when its bind was refused, OnAllHeard told once each time the patterns are all heard, a bound stream never bound again.
|
||||
func subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard(t *testing.T) {
|
||||
kept := "SEAT_node-engine_running"
|
||||
cred := Account{Node: "n1", Module: "teller"}
|
||||
var unheardTold [][]Unheard // what OnUnheard was told, in order (1984/AC-836e)
|
||||
var jmu sync.Mutex
|
||||
var journal []string // the hub's journal lines (1984/AC-836r, AC-836s)
|
||||
logf := func(f string, a ...any) {
|
||||
jmu.Lock()
|
||||
journal = append(journal, fmt.Sprintf(f, a...))
|
||||
jmu.Unlock()
|
||||
t.Logf(f, a...)
|
||||
}
|
||||
said := func(want string) bool {
|
||||
jmu.Lock()
|
||||
defer jmu.Unlock()
|
||||
return slices.ContainsFunc(journal, func(l string) bool { return strings.Contains(l, want) })
|
||||
}
|
||||
newHub := func(bus *fakeHubBus) (h *EventHub, allHeard *int, created *[]time.Time) {
|
||||
h, allHeard, created = NewEventHub(logf), new(int), new([]time.Time)
|
||||
unheardTold, journal = nil, nil
|
||||
h.OnUnheard(func(list []Unheard) { unheardTold = append(unheardTold, list) })
|
||||
h.OnAllHeard(func() { *allHeard++ })
|
||||
h.OnBound(func(at time.Time) { *created = append(*created, at) })
|
||||
if err := h.Handle("mesh.seat.node-engine.event.running.>", func(jetstream.Msg) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, allHeard, created
|
||||
}
|
||||
base := func(composed map[string]error) *fakeHubBus {
|
||||
return &fakeHubBus{streams: []string{kept, "SEAT_other_thing", "EVENTS"}, subjects: []string{"mesh.mod.*.event.>"}, composed: composed}
|
||||
}
|
||||
t.Run("start alone", func(t *testing.T) {
|
||||
bus := base(map[string]error{EventsStream: nil, kept: nil})
|
||||
h, allHeard, created := newHub(bus)
|
||||
if err := h.start(context.Background(), bus, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Stop()
|
||||
if err := h.Handle("mesh.mod.late.event.y", func(jetstream.Msg) {}); err == nil || !strings.Contains(err.Error(), `"mesh.mod.late.event.y"`) {
|
||||
t.Errorf("a handler registered after Start: %v", err) // 1984/AC-836d
|
||||
}
|
||||
if *allHeard != 1 || len(bus.binds) != 2 || len(*created) != 2 {
|
||||
t.Errorf("all heard %d times, binds %v, bound told %d times", *allHeard, bus.binds, len(*created))
|
||||
}
|
||||
if bus.wakeAt != "mesh.seat.mesh-grants.event.durables-composed.n1.teller" {
|
||||
t.Errorf("the wake is on %q", bus.wakeAt)
|
||||
}
|
||||
bus.onWake()
|
||||
bus.reconn()
|
||||
if len(unheardTold) != 2 || len(unheardTold[0]) != 0 || len(unheardTold[1]) != 1 {
|
||||
t.Errorf("a start that binds everything tells an empty list once, a later wake and reconnect nothing, and the refused late pattern: %v", unheardTold)
|
||||
}
|
||||
if *allHeard != 1 || len(bus.binds) != 2 {
|
||||
t.Errorf("a bound stream was told or bound again: %d, %v", *allHeard, bus.binds)
|
||||
}
|
||||
})
|
||||
t.Run("composed late, refused then bound at a reconnect", func(t *testing.T) {
|
||||
bus := base(map[string]error{EventsStream: nil})
|
||||
h, allHeard, _ := newHub(bus)
|
||||
h.start(context.Background(), bus, cred)
|
||||
defer h.Stop()
|
||||
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].Stream != kept || !strings.Contains(h.unheardNow[0].Why, "not composed") {
|
||||
t.Fatalf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
|
||||
}
|
||||
if !said("the pattern mesh.seat.node-engine.event.running.> is not heard on " + kept + ": not composed") {
|
||||
t.Errorf("the journal names no pattern not heard: %q", journal)
|
||||
}
|
||||
bus.composed[kept] = errors.New("the bus refuses")
|
||||
bus.onWake()
|
||||
if *allHeard != 0 || !strings.Contains(h.unheardNow[0].Why, "refused") {
|
||||
t.Fatalf("a refused bind: all heard %d, unheard %+v", *allHeard, h.unheardNow)
|
||||
}
|
||||
bus.onWake() // the same reason again: nothing new to tell
|
||||
bus.composed[kept] = nil
|
||||
bus.reconn()
|
||||
bus.onWake()
|
||||
if *allHeard != 1 || len(h.unheardNow) != 0 || len(bus.binds) != 2 {
|
||||
t.Errorf("all heard %d, unheard %+v, binds %v", *allHeard, h.unheardNow, bus.binds)
|
||||
}
|
||||
if len(unheardTold) != 3 || len(unheardTold[2]) != 0 || len(unheardTold[0]) != 1 || len(unheardTold[1]) != 1 ||
|
||||
unheardTold[0][0] == unheardTold[1][0] {
|
||||
t.Errorf("OnUnheard was told %v: the list at Start, its change, then empty once heard", unheardTold)
|
||||
}
|
||||
// 1984/AC-836s: a pattern registered after Start is refused and is among those not heard
|
||||
if err := h.Handle("mesh.mod.p.event.late", func(jetstream.Msg) {}); err == nil {
|
||||
t.Error("a handler after Start was accepted")
|
||||
}
|
||||
if n := len(unheardTold); n != 4 || len(unheardTold[3]) != 1 || unheardTold[3][0] != (Unheard{"mesh.mod.p.event.late", "", "registered after Start"}) {
|
||||
t.Errorf("OnUnheard was told %v", unheardTold)
|
||||
}
|
||||
if !said("the pattern mesh.mod.p.event.late is not heard: registered after Start") {
|
||||
t.Errorf("the journal says nothing of the pattern refused after Start: %q", journal)
|
||||
}
|
||||
})
|
||||
// AC-836b clause 2: the wake is made before the first bind, so the word that the durables were composed, said from inside
|
||||
// Start's own failing bind, binds the stream.
|
||||
t.Run("composed while Start's bind fails", func(t *testing.T) {
|
||||
bus := base(map[string]error{EventsStream: nil})
|
||||
bus.missed = func(stream string) {
|
||||
bus.mu.Lock()
|
||||
bus.composed[stream] = nil
|
||||
wake := bus.onWake
|
||||
bus.mu.Unlock()
|
||||
if wake != nil {
|
||||
go wake() // the subscription's own goroutine: it waits for Start's pass to end
|
||||
}
|
||||
}
|
||||
h, allHeard, _ := newHub(bus)
|
||||
heard := make(chan struct{}, 4)
|
||||
h.OnAllHeard(func() { heard <- struct{}{} })
|
||||
if err := h.start(context.Background(), bus, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Stop()
|
||||
select {
|
||||
case <-heard:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("the durable composed during Start's bind was never bound: binds %v", bus.binds)
|
||||
}
|
||||
bus.mu.Lock()
|
||||
defer bus.mu.Unlock()
|
||||
if *allHeard != 1 || !slices.Contains(bus.binds, kept) {
|
||||
t.Errorf("all heard %d, binds %v", *allHeard, bus.binds)
|
||||
}
|
||||
})
|
||||
// §836 5., H-A-876: for a process that names one, the durable asked of the bus is the process's own, said in the journal and the reason
|
||||
t.Run("a process names its durable", func(t *testing.T) {
|
||||
bus := base(map[string]error{EventsStream: nil})
|
||||
h, _, _ := newHub(bus)
|
||||
if err := h.ForProcess("keeper"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.start(context.Background(), bus, cred)
|
||||
defer h.Stop()
|
||||
if len(h.unheardNow) != 1 || !strings.Contains(h.unheardNow[0].Why, "no durable n1_teller_keeper on it") || !said("the consumer n1_teller_keeper on EVENTS is heard") {
|
||||
t.Errorf("unheard %+v, journal %q", h.unheardNow, journal)
|
||||
}
|
||||
if h.ForProcess("other") == nil {
|
||||
t.Error("a process was named after Start")
|
||||
}
|
||||
})
|
||||
t.Run("no stream carries a pattern", func(t *testing.T) {
|
||||
bus := base(map[string]error{EventsStream: nil, kept: nil})
|
||||
bus.subjects = []string{"mesh.seat.*.event.>"}
|
||||
h, allHeard, _ := newHub(bus)
|
||||
h.start(context.Background(), bus, cred)
|
||||
defer h.Stop()
|
||||
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].Pattern != "mesh.mod.p.event.x" || h.unheardNow[0].Why != "no stream carries it" {
|
||||
t.Errorf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
|
||||
}
|
||||
if !said("the pattern mesh.mod.p.event.x is not heard: no stream carries it") {
|
||||
t.Errorf("the journal names no pattern no stream carries: %q", journal)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -101,6 +101,14 @@ func (a Account) NamedEventConsumer(ctx context.Context, js jetstream.JetStream,
|
||||
return js.Consumer(ctx, stream, a.namedEventConsumerName(suffix))
|
||||
}
|
||||
|
||||
// durableOf is the module's durable, or the one of the process named process when one is named (EventHub.ForProcess).
|
||||
func (a Account) durableOf(process string) string {
|
||||
if process == "" {
|
||||
return a.EventConsumerName()
|
||||
}
|
||||
return a.namedEventConsumerName(process)
|
||||
}
|
||||
|
||||
func (a Account) namedEventConsumerName(suffix string) string {
|
||||
return a.EventConsumerName() + "_" + suffix
|
||||
}
|
||||
|
||||
@@ -52,12 +52,17 @@ type hearOptions struct {
|
||||
// held is the event hub's feed of this durable (EventHub.StartKept): its messages are held and said in progress by the
|
||||
// hub's ticker, so the pull says none itself.
|
||||
held *eventFeed
|
||||
// process is the name of the process whose own durable is bound in place of the module's (EventHub.ForProcess).
|
||||
process string
|
||||
}
|
||||
|
||||
// heldBy makes the pull of a durable the event hub's: its handler holds each message and returns, and the feed's ticker says in
|
||||
// progress for every one held, at every third of the durable's ack wait (design 47 H2 H-A-695 (1), (4)).
|
||||
func heldBy(f *eventFeed) HearOption { return func(o *hearOptions) { o.held = f } }
|
||||
|
||||
// forProcess binds the durable of the process named process, `<node>_<module>_<process>`, in place of the module's.
|
||||
func forProcess(process string) HearOption { return func(o *hearOptions) { o.process = process } }
|
||||
|
||||
// OnRead is the callback HearSeatEvents calls with ReadWaiting and then ReadDone around its start read; the module wires it
|
||||
// to its first views (design 47 G A-19), so this package imports nothing of views.
|
||||
func OnRead(f func(state string)) HearOption { return func(o *hearOptions) { o.onRead = f } }
|
||||
@@ -143,9 +148,10 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
|
||||
for _, f := range opts {
|
||||
f(&o)
|
||||
}
|
||||
cons, err := a.EventConsumer(ctx, js, stream)
|
||||
durable := a.durableOf(o.process)
|
||||
cons, err := js.Consumer(ctx, stream, durable)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the consumer %s on %s is not there: %w", a.EventConsumerName(), stream, err)
|
||||
return nil, fmt.Errorf("the consumer %s on %s is not there: %w", durable, stream, err)
|
||||
}
|
||||
st, err := js.Stream(ctx, stream)
|
||||
if err != nil {
|
||||
@@ -180,8 +186,8 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
|
||||
cc, err = HearEvents(cons, handle, logf)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", a.EventConsumerName(), stream, err)
|
||||
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", durable, stream, err)
|
||||
}
|
||||
logf("events: the consumer %s on %s is heard", a.EventConsumerName(), stream)
|
||||
logf("events: the consumer %s on %s is heard", durable, stream)
|
||||
return cc, nil
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ const (
|
||||
// EventOverrunKind is a process's finding of the handlings of events that run past the setting event-overrun, one per module,
|
||||
// its summary naming each (design 47 H2 H-A-683 (3), H-A-697).
|
||||
EventOverrunKind = "event-overrun"
|
||||
// EventsUnheardKind is a process's finding of the patterns its event hub does not hear, one per module on its node, its summary
|
||||
// naming each with its stream and why (design 47 H2b §836 4.).
|
||||
EventsUnheardKind = "events-unheard"
|
||||
)
|
||||
|
||||
// viewFinding is what a views part says is wrong with a state it owns or follows, in plain fields: kind and id name it, summary
|
||||
@@ -153,3 +156,20 @@ func overrunFinding(module string, past []process.Handling, at time.Time) viewFi
|
||||
summary := fmt.Sprintf("%s has %d event handlings past their bound: %s: the events behind them wait", module, len(past), strings.Join(named, "; "))
|
||||
return viewFinding{kind: EventOverrunKind, id: module, summary: summary, headline: fmt.Sprintf("%s handles an event very slowly", module), at: at.UTC()}
|
||||
}
|
||||
|
||||
// unheardFinding is the module's one finding of the patterns its hub does not hear (design 47 H2b §836 4.): its id `<module>.<node>`,
|
||||
// its summary each pattern with its stream and why, every one named (no bound), and the way through: the node's service
|
||||
// manager restarts the module's unit.
|
||||
func unheardFinding(module, node string, list []process.Unheard, at time.Time) viewFinding {
|
||||
var named []string
|
||||
for _, u := range list {
|
||||
if u.Stream == "" {
|
||||
named = append(named, fmt.Sprintf("%s (%s)", u.Pattern, u.Why))
|
||||
continue
|
||||
}
|
||||
named = append(named, fmt.Sprintf("%s on %s (%s)", u.Pattern, u.Stream, u.Why))
|
||||
}
|
||||
summary := fmt.Sprintf("%s on %s does not hear %d event patterns: %s: what it consumes there it does not act on; a bind the bus refuses while its durable stands is made again by the node's service manager restarting the module's unit",
|
||||
module, node, len(list), strings.Join(named, "; "))
|
||||
return viewFinding{kind: EventsUnheardKind, id: module + "." + node, summary: summary, headline: fmt.Sprintf("%s does not hear all its events", module), at: at.UTC()}
|
||||
}
|
||||
|
||||
@@ -456,6 +456,28 @@ func (r *ProcessReader) overrun(past []process.Handling) {
|
||||
}
|
||||
}
|
||||
|
||||
// unheardPatterns is the event hub's word of the patterns it does not hear: the module's finding `events-unheard`, raised naming
|
||||
// each, cleared on an empty list (design 47 H2b §836 4.). With no findings writer the hub's journal line stands alone (H-A-840).
|
||||
func (r *ProcessReader) unheardPatterns(list []process.Unheard) {
|
||||
if r.Findings == nil {
|
||||
return
|
||||
}
|
||||
w := r.Findings()
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
module, node := w.ModuleNode()
|
||||
if len(list) == 0 {
|
||||
if err := (viewFinding{kind: EventsUnheardKind, id: module + "." + node}).drop(w); err != nil {
|
||||
r.logf("views: the finding %s of %s is not cleared: %v", EventsUnheardKind, r.Module, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := unheardFinding(module, node, list, r.now()).put(w); err != nil {
|
||||
r.logf("views: the finding %s of %s is not written: %v", EventsUnheardKind, r.Module, err)
|
||||
}
|
||||
}
|
||||
|
||||
// clearUnhandled clears the module's findings `event-unhandled` and `event-overrun` at the process's start: a new build may
|
||||
// handle the event (H-A-169), and no handling of the new process runs yet (H-A-697 (1)).
|
||||
func (r *ProcessReader) clearUnhandled() {
|
||||
@@ -932,6 +954,7 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
|
||||
if wire {
|
||||
hub.OnUnhandled(r.unhandled)
|
||||
hub.OnOverrun(r.overrun)
|
||||
hub.OnUnheard(r.unheardPatterns)
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -311,8 +312,8 @@ func subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable(t *testing.T) {
|
||||
default:
|
||||
t.Fatal("the unhandled event after the second start wrote no finding")
|
||||
}
|
||||
// A hub started before the bus holds its durable says so, and binds at a later start: a module is not lost for the
|
||||
// order in which the bus makes its consumer.
|
||||
// A hub started before the bus holds its durable says so, and binds when the grants part says it composed the module's
|
||||
// durables: a module is not lost for the order in which the bus makes its consumer (design 47 H2b §836 2.).
|
||||
late := process.Account{Node: "n1", Module: "late"}
|
||||
lateHub := process.NewEventHub(t.Logf)
|
||||
heard := make(chan string, 1)
|
||||
@@ -320,15 +321,22 @@ func subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lateHub.Stop()
|
||||
if err := lateHub.Start(ctx, js, late); err == nil {
|
||||
t.Fatal("a hub with no durable on the bus started")
|
||||
allHeard := make(chan struct{}, 1)
|
||||
lateHub.OnAllHeard(func() { allHeard <- struct{}{} })
|
||||
if err := lateHub.Start(ctx, js, late); err != nil {
|
||||
t.Fatalf("a hub with no durable on the bus failed its start: %v", err)
|
||||
}
|
||||
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: late.EventConsumerName(),
|
||||
AckPolicy: jetstream.AckExplicitPolicy, FilterSubjects: []string{"mesh.mod.l.event.>"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lateHub.Start(ctx, js, late); err != nil {
|
||||
t.Fatalf("the hub did not bind at its second start: %v", err)
|
||||
if err := nc.Publish("mesh.seat.mesh-grants.event.durables-composed.n1.late", []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-allHeard:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the grants part said the durables are composed and the hub did not bind")
|
||||
}
|
||||
if _, err := js.Publish(ctx, "mesh.mod.l.event.x", []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -399,6 +407,26 @@ func subAHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt(t *test
|
||||
for range 2 { // the start clears event-unhandled and event-overrun
|
||||
<-found.cleared
|
||||
}
|
||||
// design 47 H2b §836 4.: the hub's Start binds every pattern and tells an empty list, so events-unheard an earlier process raised is cleared
|
||||
if got := <-found.cleared; got != "events-unheard reader=2en1" {
|
||||
t.Fatalf("the hub's start cleared %s", got)
|
||||
}
|
||||
// design 47 H2b §836 3., 4. (1984/AC-836s): an event adopted after the hub's Start is refused, said in the module's journal,
|
||||
// and raises events-unheard naming its pattern
|
||||
var mu sync.Mutex
|
||||
var lines []string
|
||||
r.Logf = func(f string, a ...any) { mu.Lock(); lines = append(lines, fmt.Sprintf(f, a...)); mu.Unlock() }
|
||||
if err := r.AdoptEvent("s", "late", func(context.Context, []byte) error { return nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := <-found.put; !strings.HasPrefix(got, "events-unheard ") || !strings.Contains(got, "mesh.seat.s.event.late") || !strings.Contains(got, "registered after Start") {
|
||||
t.Fatalf("the event adopted after Start raised %s", got)
|
||||
}
|
||||
mu.Lock()
|
||||
if len(lines) != 1 || !strings.Contains(lines[0], "mesh.seat.s.event.late is not heard") {
|
||||
t.Errorf("the reader's journal: %q", lines)
|
||||
}
|
||||
mu.Unlock()
|
||||
if _, err := js.Publish(ctx, "mesh.mod.p.event.slow", []byte("{}")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1584,4 +1584,31 @@ func TestTheOverrunFindingNamesTheHandlingsOldestFirst(t *testing.T) {
|
||||
if eight := overrunFinding("builder", past(8), at); !strings.Contains(eight.summary, "and 3 more") || strings.Contains(eight.summary, "e5 ") {
|
||||
t.Errorf("eight handlings: %s", eight.summary)
|
||||
}
|
||||
// Design 47 H2b §836 4. (1984/AC-836e, AC-836r): the finding events-unheard, id `<module>.<node>`, names each pattern with its stream and
|
||||
// why, is cleared by an empty list, and a reader with no findings writer says nothing (the hub's journal line stands alone).
|
||||
list := []process.Unheard{{Pattern: "mesh.seat.s.event.e.>", Stream: "SEAT_s_e", Why: "not composed"}, {Pattern: "mesh.mod.p.event.x", Why: "no stream carries it"}}
|
||||
if f := unheardFinding("builder", "n1", list, at); f.kind != EventsUnheardKind || f.id != "builder.n1" ||
|
||||
!strings.Contains(f.summary, "mesh.seat.s.event.e.> on SEAT_s_e (not composed)") || !strings.Contains(f.summary, "mesh.mod.p.event.x (no stream carries it)") {
|
||||
t.Errorf("the finding: %+v", f)
|
||||
}
|
||||
// §836 4.: each pattern not heard is named, however many
|
||||
var many []process.Unheard
|
||||
for i := range 8 {
|
||||
many = append(many, process.Unheard{Pattern: fmt.Sprintf("mesh.mod.p.event.x%d", i), Why: "no stream carries it"})
|
||||
}
|
||||
if f := unheardFinding("builder", "n1", many, at); !strings.Contains(f.summary, "mesh.mod.p.event.x7 (no stream carries it)") || strings.Contains(f.summary, "more") || !strings.Contains(f.summary, "does not hear 8 event patterns") {
|
||||
t.Errorf("eight patterns not heard were not all named: %s", f.summary)
|
||||
}
|
||||
fm := &findingsMap{}
|
||||
pr := &ProcessReader{Module: "m", Findings: func() WireWriter { return fm }, Now: func() time.Time { return at }}
|
||||
pr.unheardPatterns(list)
|
||||
if _, ok := fm.m["events-unheard/m.n1"]; !ok || len(fm.m) != 1 {
|
||||
t.Errorf("the finding was not raised: %v", fm.m)
|
||||
}
|
||||
pr.unheardPatterns(nil)
|
||||
if len(fm.m) != 0 || fm.deletes != 1 {
|
||||
t.Errorf("an empty list did not clear it: %v", fm.m)
|
||||
}
|
||||
quiet := &ProcessReader{Module: "m", Now: func() time.Time { return at }}
|
||||
quiet.unheardPatterns(list) // no findings writer: nothing written, nothing panics
|
||||
}
|
||||
|
||||
+1
-1
@@ -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, EventUnhandledKind, EventOverrunKind}
|
||||
var ViewKinds = []string{ViewWaitsKind, UnansweredKind, UnsaidKind, TooLargeKind, EntryNotFoundKind, EventUnhandledKind, EventOverrunKind, EventsUnheardKind}
|
||||
|
||||
var (
|
||||
sessionForm = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*@[a-z0-9][a-z0-9-]*$`)
|
||||
|
||||
@@ -452,7 +452,7 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
|
||||
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} {
|
||||
for _, kind := range []string{views.EventUnhandledKind, views.EventOverrunKind, views.EventsUnheardKind} {
|
||||
if err := views.PutViewFinding(r.w, kind, "m", "sum", "head"); err != nil {
|
||||
t.Errorf("a writer given its own kinds refuses %s: %v", kind, err)
|
||||
}
|
||||
@@ -479,7 +479,7 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
|
||||
}
|
||||
}
|
||||
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 {
|
||||
!slices.Contains(stated.Kinds, views.EventUnhandledKind) || !slices.Contains(stated.Kinds, views.EventOverrunKind) || !slices.Contains(stated.Kinds, views.EventsUnheardKind) || len(stated.Findings) != 5 {
|
||||
t.Errorf("the statement: kinds %v, %d findings", stated.Kinds, len(stated.Findings))
|
||||
}
|
||||
if err := views.DropViewFinding(r.w, views.ViewWaitsKind, "m.o.s"); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user