package bus import ( "context" "encoding/json" "errors" "fmt" "regexp" "sort" "strconv" "strings" "sync" "time" "git.novox.be/novox/mesh-sdk/go/buscalls" "git.novox.be/novox/mesh-sdk/go/membership" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" ) // A module's state on the bus (novox/hq ADR 0201): key-value buckets the mesh creates from what // the module declared, and issues to each assignment in its membership by the name the module uses — // its own state by the local name, another module's as `.`. // // **The runtime keeps each module to its own buckets.** One account per machine carries every module // on it, so the bus enforces only the union; and a write the bus refuses reaches the writer as a // timeout, not a refusal (measured, novox/hq research 024). So what a module may reach is decided here, // from its membership, and refused with the reason before anything is sent. // StateIssued is one bucket an assignment may reach (ADR 0201). type StateIssued struct { Name string `json:"name"` Bucket string `json:"bucket"` Writes bool `json:"writes,omitempty"` // PerNode says the state is kept one bucket per node (novox/hq ADR 0593 §6, mesh-sdk membership.StateIssued): Bucket is // then the buckets' prefix, each bucket the prefix and a node's name, and a key's first part names its node. It is read // only, served as one state (per_node.go). PerNode bool `json:"per-node,omitempty"` } // StateEntry is one key's current value. type StateEntry struct { Key string `json:"key"` Value json.RawMessage `json:"value"` Revision uint64 `json:"revision"` // At is when the bus wrote this value (the entry's created time), as stdio.StateEntry.At reads it. At time.Time `json:"at,omitzero"` // SeenAgain is set in a page on a value the bus wrote after the read reached its bucket, so a reader knows it replaces // any value it holds for the key (design 47 H2 §779, H-A-382). SeenAgain bool `json:"seen-again,omitempty"` } // StateChange is one change a watch delivers: a key put, deleted, or expired (its own time to live, or the // bucket's age, ended; issue 1952). type StateChange struct { State string `json:"state"` Key string `json:"key"` Op string `json:"op"` Value json.RawMessage `json:"value,omitempty"` Revision uint64 `json:"revision"` // Current is true for a value that was there when the watch began, false for a change since. Current bool `json:"current"` } // StateTimeout bounds one state operation on the bus. var StateTimeout = 10 * time.Second // stateKey is a key the bus can hold: letters, digits and `-/_=.`, no leading or trailing dot. A // module's convention for naming a machine in a key (`all.`, `.`) fits it. var stateKey = regexp.MustCompile(`^[-/_=a-zA-Z0-9]+(\.[-/_=a-zA-Z0-9]+)*$`) // issuedState is the bucket a module may reach by a name, and whether it may write it — or the reason // it may not reach it at all. func (c *Conn) issuedState(module, name string) (StateIssued, error) { m := c.Membership(module) if m == nil { return StateIssued{}, fmt.Errorf("%s has no membership issued on %s yet, so no state of it is reachable "+ "until the mesh issues one (novox/hq ADR 0201)", module, c.node) } // What a membership issues by a local name is mesh-sdk's one rule (membership.StateIssued, issue 1966): the old // `state` list, then a key-value entry the module asks for in `requires` (ADR 0595 §1), by its local name. issuing := membership.Membership{Bindings: m.Bindings} for _, s := range m.State { issuing.State = append(issuing.State, membership.StateIssued{Name: s.Name, Bucket: s.Bucket, Writes: s.Writes, PerNode: s.PerNode}) } if s, ok := issuing.StateIssued(name); ok { return StateIssued{Name: s.Name, Bucket: s.Bucket, Writes: s.Writes, PerNode: s.PerNode}, nil } issued := "none" if names := issuing.StateNames(); len(names) > 0 { issued = strings.Join(names, ", ") } return StateIssued{}, fmt.Errorf("%s keeps and reads no state called %q: it declares what it keeps under "+ "`state` or as a key-value entry in `requires`, and what it reads under `reads` as ., and was "+ "issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued) } // binding is one bucket's binding, or the bind in flight for it: the first asker binds, an asker meanwhile waits for // that bind (done) instead of asking the bus again. type binding struct { done chan struct{} kv jetstream.KeyValue err error } // bucket is the state's binding, bound once for the process (design 47 H lead answers H-A-251): binding a bucket is a // stream-info request on the bus, and asked before every get it made each read two answers. A bind that fails is not // kept, so the next ask binds again. func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) { c.bindMu.Lock() b := c.bound[s.Bucket] if b == nil { if c.bound == nil { c.bound = map[string]*binding{} } b = &binding{done: make(chan struct{})} c.bound[s.Bucket] = b c.bindMu.Unlock() b.kv, b.err = c.bindBucket(ctx, s.Bucket) if b.err != nil { c.bindMu.Lock() if c.bound[s.Bucket] == b { delete(c.bound, s.Bucket) } c.bindMu.Unlock() } close(b.done) } else { c.bindMu.Unlock() select { case <-b.done: case <-ctx.Done(): return nil, ctx.Err() } } if b.err != nil { if errors.Is(b.err, jetstream.ErrBucketNotFound) { return nil, fmt.Errorf("the state %q is issued and its bucket is not on the bus yet: the mesh "+ "creates it from the catalogue on its next raise", s.Name) } return nil, b.err } return b.kv, nil } func (c *Conn) bindBucket(ctx context.Context, bucket string) (jetstream.KeyValue, error) { if c.bind != nil { return c.bind(ctx, bucket) } js, err := jetstream.New(c.nc) if err != nil { return nil, err } return js.KeyValue(ctx, bucket) } // unbind drops a bucket's binding the bus said is gone, when it is still the one kept, so the next ask binds again. func (c *Conn) unbind(bucket string, kv jetstream.KeyValue) { c.bindMu.Lock() defer c.bindMu.Unlock() b := c.bound[bucket] if b == nil { return } select { case <-b.done: // bound: its kv is written default: return // bound again already, in flight } if b.kv == kv { delete(c.bound, bucket) } } // bucketGone is the bus saying a kept binding's bucket is not there (deleted, or deleted and created again): no stream of // the name, or nobody answers on its subjects. func bucketGone(err error) bool { return errors.Is(err, jetstream.ErrStreamNotFound) || errors.Is(err, jetstream.ErrBucketNotFound) || errors.Is(err, jetstream.ErrNoStreamResponse) || errors.Is(err, nats.ErrNoResponders) } // inBucket does one act on the state's kept binding; when the bus says its bucket is gone, the binding is dropped, the // bucket bound again once and the act done once more on the new binding (H-A-251). func inBucket[T any](c *Conn, ctx context.Context, s StateIssued, do func(jetstream.KeyValue) (T, error)) (T, error) { var none T kv, err := c.bucket(ctx, s) if err != nil { return none, err } got, err := do(kv) if !bucketGone(err) { return got, err } c.unbind(s.Bucket, kv) if kv, err = c.bucket(ctx, s); err != nil { return none, err } return do(kv) } func checkKey(key string) error { if !stateKey.MatchString(key) { return fmt.Errorf("%q is not a key the bus can hold: letters, digits and -/_=, in dot-separated "+ "names", key) } return nil } // StateGet is one key's current value, or nil when it has none. func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) { s, err := c.issuedState(module, name) if err != nil { return nil, err } if err := checkKey(key); err != nil { return nil, err } if s.PerNode { return c.perNodeGet(s, key) } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() e, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueEntry, error) { return kv.Get(ctx, key) }) if errors.Is(err, jetstream.ErrKeyNotFound) { return nil, nil } if err != nil { return nil, err } return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil } // StatePage is one page of a read: the values the bus wrote after the cursor's sequence, in sequence order, and the // opaque cursor that continues the read, empty at its end (design 47 H2 §779). type StatePage struct { Entries []StateEntry `json:"entries"` Next string `json:"next,omitempty"` } // StatePageBudget is the time a page spends reading when the asker names none: well under the 30 s a reader waits. const StatePageBudget = 10 * time.Second // StatePageMost is the most a page holds, in keys and values, whatever the asker names (design 47 H2 §779). const StatePageMost = 768 << 10 // PageClock is the time a page's budget counts by, replaced by a test. var PageClock = time.Now // pageCursor is where a read stands, written into the opaque cursor a page answers as next: the bucket's node for a state // kept one bucket per node (empty for one bucket), the sequence of the last message handed, and mark, the bucket's last // sequence when the read reached it, after which every message is marked seen-again (H-A-382 (1)). The runner keeps // nothing per read: the cursor carries it all. type pageCursor struct { node string after, mark uint64 } func (p pageCursor) String() string { return fmt.Sprintf("%s.%d.%d", p.node, p.mark, p.after) } func cursorOf(raw string) (pageCursor, error) { if raw == "" { return pageCursor{}, nil } parts := strings.Split(raw, ".") var p pageCursor var err1, err2 error if len(parts) == 3 { p.node = parts[0] p.mark, err1 = strconv.ParseUint(parts[1], 10, 64) p.after, err2 = strconv.ParseUint(parts[2], 10, 64) } if len(parts) != 3 || err1 != nil || err2 != nil { return pageCursor{}, fmt.Errorf("%q is not a cursor a page answered: hand back the next of the page before", raw) } return p, nil } // StatePage reads one page of a state in the order the bus wrote it (design 47 H2 §779, H-A-254, H-A-382): from an ordered // consumer starting after the cursor's sequence, never a replay of the bucket per page, each kept message once across the // pages of a read, a key's older kept revisions included; a message written after the read reached its bucket comes // marked seen-again, and a deleted key gets no entry. A page holds as many values as fit maxBytes (each key and value; at // most StatePageMost) or the budget allows, at least one, and next continues the read, empty at its end. A state kept one // bucket per node is read one node's bucket after another, in node order. It is a read like StateGet: served to the owner // and to every reader, and writes nothing. func (c *Conn) StatePage(module, name, cursor string, maxBytes int, budget time.Duration) (StatePage, error) { s, err := c.issuedState(module, name) if err != nil { return StatePage{}, err } at, err := cursorOf(cursor) if err != nil { return StatePage{}, err } if budget <= 0 { budget = StatePageBudget } if maxBytes <= 0 || maxBytes > StatePageMost { maxBytes = StatePageMost } r := &pageRead{page: StatePage{Entries: []StateEntry{}}, maxBytes: maxBytes, budget: budget, started: PageClock()} if !s.PerNode { if at.node != "" { return StatePage{}, fmt.Errorf("%q is not a cursor of %s's state %s: it names a node's bucket", cursor, module, name) } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() if _, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) { return struct{}{}, r.bucket(kv, at, cursor != "") }); err != nil { return StatePage{}, err } return r.page, nil } fam := c.family(s) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) nodes, err := fam.Nodes(ctx) cancel() if err != nil { return StatePage{}, err } sort.Strings(nodes) for _, node := range nodes { if node < at.node { continue } from, reached := pageCursor{node: node}, cursor != "" && node == at.node if reached { from = at } octx, ocancel := context.WithTimeout(context.Background(), StateTimeout) kv, err := fam.Open(octx, node) if err == nil && kv != nil { err = r.bucket(kv, from, reached) } ocancel() if err != nil { return StatePage{}, err } if r.page.Next != "" { return r.page, nil } } return r.page, nil } // pageRead is one page being filled. type pageRead struct { page StatePage size int maxBytes int budget time.Duration started time.Time } // bucket reads one bucket after from into the page, until the bucket is read to its end (the page then goes on with the // next bucket, or ends with no next) or the page is full (next set). reached says an earlier page of the read already // reached the bucket, so from carries its mark. func (r *pageRead) bucket(kv jetstream.KeyValue, from pageCursor, reached bool) error { ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() if !reached { // The read reaches this bucket: what the bus writes into it from now on is marked seen-again (H-A-382 (1)). status, err := kv.Status(ctx) if err != nil { return err } bs, ok := status.(*jetstream.KeyValueBucketStatus) if !ok || bs.StreamInfo() == nil { return fmt.Errorf("%s's last sequence is not read, so no page of it can say what is seen again", kv.Bucket()) } from.mark = bs.StreamInfo().State.LastSeq } opts := []jetstream.WatchOpt{jetstream.IncludeHistory(), jetstream.IgnoreDeletes()} if from.after > 0 { opts = append(opts, jetstream.ResumeFromRevision(from.after+1)) } w, err := kv.WatchAll(ctx, opts...) if err != nil { return err } defer func() { _ = w.Stop() // What the watch still hands after its stop is taken and dropped, so its delivery never blocks on a page read no more. go func() { for range w.Updates() { } }() }() for { var e jetstream.KeyValueEntry select { case <-ctx.Done(): return fmt.Errorf("a page of %s is not read: %w", kv.Bucket(), ctx.Err()) case got, ok := <-w.Updates(): if !ok || got == nil { return nil // the bucket is read to its end } e = got } value := valueOf(e.Value()) full := len(r.page.Entries) > 0 && (r.size+len(e.Key())+len(value) > r.maxBytes || PageClock().Sub(r.started) >= r.budget) if full { r.page.Next = from.String() return nil } r.page.Entries = append(r.page.Entries, StateEntry{Key: e.Key(), Value: value, Revision: e.Revision(), At: e.Created().UTC(), SeenAgain: e.Revision() > from.mark}) r.size += len(e.Key()) + len(value) from.after = e.Revision() } } // StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one). type StateKept struct { Key string `json:"key"` Value json.RawMessage `json:"value,omitempty"` Revision uint64 `json:"revision"` Op string `json:"op"` At time.Time `json:"at"` } // StateHistory is every value the bucket still keeps for one key, oldest first, or none (novox/hq ADR // 0307). It is a read like StateGet: served to the owner and to every reader, and writes nothing. func (c *Conn) StateHistory(module, name, key string) ([]StateKept, error) { s, err := c.issuedState(module, name) if err != nil { return nil, err } if err := checkKey(key); err != nil { return nil, err } if s.PerNode { return nil, perNodeRefusal(module, name, "history") } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() entries, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]jetstream.KeyValueEntry, error) { return kv.History(ctx, key) }) kept := []StateKept{} if errors.Is(err, jetstream.ErrKeyNotFound) { return kept, nil } if err != nil { return nil, err } for _, e := range entries { k := StateKept{Key: e.Key(), Revision: e.Revision(), Op: "delete", At: e.Created().UTC()} if e.Operation() == jetstream.KeyValuePut { k.Op = "put" k.Value = valueOf(e.Value()) } kept = append(kept, k) } return kept, nil } // StateInfo is how full a state's bucket is against its caps (tools-are-how-a-module-is-spoken-to): a bundle's tools // say fill against cap from it. type StateInfo struct { State string `json:"state"` Bucket string `json:"bucket"` // Bytes is what the bucket holds now, every kept value and marker counted; Keys how many keys it holds, a key // whose last value is a delete or expiry marker counted until the marker goes. Bytes uint64 `json:"bytes"` Keys uint64 `json:"keys"` // MaxBytes and MaxValueBytes are the bucket's caps; -1 is none. MaxBytes int64 `json:"max_bytes"` MaxValueBytes int32 `json:"max_value_bytes"` // History is how many values a key keeps; TTLSeconds the bucket's age for a value (0 none); KeyTTL whether a key may // carry its own time to live (issue 1952). History int64 `json:"history"` TTLSeconds int64 `json:"ttl_seconds"` KeyTTL bool `json:"key_ttl"` } // StateInfo reads a state's bucket's fill and caps. It is a read like StateGet: served to the owner and every reader. func (c *Conn) StateInfo(module, name string) (*StateInfo, error) { status, info, err := c.bucketStatus(module, name) if err != nil { return nil, err } return &StateInfo{State: name, Bucket: status.Bucket(), Bytes: info.State.Bytes, Keys: uint64(info.State.NumSubjects), MaxBytes: info.Config.MaxBytes, MaxValueBytes: info.Config.MaxMsgSize, History: status.History(), TTLSeconds: int64(status.TTL() / time.Second), KeyTTL: info.Config.AllowMsgTTL && status.LimitMarkerTTL() > 0}, nil } // StateFill is a state's bucket's fill against its cap, buscalls.Fill's form: the messages it keeps, their bytes and its // cap in bytes (0 is none). A put answers it, read from the bound stream's info once per put, since the bus's key-value // put answers no figures of its own (design 47 H2 DMC-14, H-A-386). func (c *Conn) StateFill(module, name string) (buscalls.Fill, error) { _, info, err := c.bucketStatus(module, name) if err != nil { return buscalls.Fill{}, err } return buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: uint64(max(info.Config.MaxBytes, 0))}, nil } // bucketStatus is a state's bucket's status and the info of the stream behind it. func (c *Conn) bucketStatus(module, name string) (jetstream.KeyValueStatus, *jetstream.StreamInfo, error) { s, err := c.issuedState(module, name) if err != nil { return nil, nil, err } if s.PerNode { return nil, nil, perNodeRefusal(module, name, "fill") } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() status, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueStatus, error) { return kv.Status(ctx) }) if err != nil { return nil, nil, err } b, ok := status.(*jetstream.KeyValueBucketStatus) if !ok || b.StreamInfo() == nil { return nil, nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name) } return status, b.StreamInfo(), nil } // StatePut writes one key, as the module, where the module keeps the state. It answers the revision. func (c *Conn) StatePut(module, name, key string, value json.RawMessage) (uint64, error) { s, err := c.writable(module, name) if err != nil { return 0, err } if err := checkKey(key); err != nil { return 0, err } if len(value) == 0 || !json.Valid(value) { return 0, fmt.Errorf("a state value is JSON") } if field := credentialField(value); field != "" { return 0, fmt.Errorf("%s's %s.%s carries a field %q, which names a credential: no secret is kept in state, "+ "sealed or not — a bucket is a stream, and a machine joining a year later reads it whole. Name the "+ "secret and fetch it on request/reply (novox/hq ADR 0201, design 32 §10)", module, name, key, field) } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() return inBucket(c, ctx, s, func(kv jetstream.KeyValue) (uint64, error) { return kv.Put(ctx, key, value) }) } // MinKeyTTL is the shortest time to live a key may be given: the bus counts a key's age in whole seconds (mesh-sdk // process.MinTTL). const MinKeyTTL = time.Second // StateCreateTTL writes one key only when it has no value, with its own time to live (novox/hq ADR 0564 clauses 4 and // 7, issue 1952; mesh-sdk process.State.CreateTTL): the bus removes it when ttl passes and every watch hears the // removal as an expiry, so a bundle's wake needs no timer. A key that has a value is refused as ErrStateChanged. The // bucket must take keys with their own time to live (a state declared `key-ttl`); one that does not is refused, naming // it, before anything is written. func (c *Conn) StateCreateTTL(module, name, key string, value json.RawMessage, ttl time.Duration) (uint64, error) { if ttl < MinKeyTTL { return 0, fmt.Errorf("%s's state %s, key %s: a time to live of %s is shorter than the bus keeps (%s)", module, name, key, ttl, MinKeyTTL) } return c.stateWrite(module, name, key, value, func(ctx context.Context, kv jetstream.KeyValue) (uint64, error) { if err := takesKeyTTL(ctx, kv, module, name); err != nil { return 0, err } return kv.Create(ctx, key, value, jetstream.KeyTTL(ttl)) }) } // StateRenewTTL writes one key whole with a fresh time to live, whatever it held (mesh-sdk process.State.RenewTTL): a // time to live is set only when a key is created, so a live key is deleted first, and its watches hear the delete and // then the new value. func (c *Conn) StateRenewTTL(module, name, key string, value json.RawMessage, ttl time.Duration) (uint64, error) { rev, err := c.StateCreateTTL(module, name, key, value, ttl) if !errors.Is(err, ErrStateChanged) { return rev, err } if err := c.StateDelete(module, name, key); err != nil { return 0, err } return c.StateCreateTTL(module, name, key, value, ttl) } // takesKeyTTL refuses a bucket that does not allow a time to live per key, or leaves no marker when one ends: there the // server would refuse the write, or the key would vanish and no watch would hear it. func takesKeyTTL(ctx context.Context, kv jetstream.KeyValue, module, name string) error { status, err := kv.Status(ctx) if err != nil { return err } allows := status.LimitMarkerTTL() > 0 if b, ok := status.(*jetstream.KeyValueBucketStatus); ok && b.StreamInfo() != nil { allows = allows && b.StreamInfo().Config.AllowMsgTTL } if !allows { return fmt.Errorf("%s's state %s does not take keys with their own time to live: its bucket %s allows none, or "+ "leaves no marker a watch hears when one ends; %s declares the state `key-ttl` for it (novox/hq ADR 0564, "+ "issue 1952)", module, name, status.Bucket(), module) } return nil } // StateDelete removes one key, as the module, where the module keeps the state. A key that was not // there is not an error: what is asked for is that it is gone. func (c *Conn) StateDelete(module, name, key string) error { s, err := c.writable(module, name) if err != nil { return err } if err := checkKey(key); err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() _, err = inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) { return struct{}{}, kv.Delete(ctx, key) }) return err } // StateKeys is every key with a current value, sorted. func (c *Conn) StateKeys(module, name string) ([]string, error) { s, err := c.issuedState(module, name) if err != nil { return nil, err } if s.PerNode { return c.perNodeKeys(s) } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() return inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]string, error) { return keysOf(ctx, kv) }) } // keysOf is every key with a current value in one bucket, sorted. func keysOf(ctx context.Context, kv jetstream.KeyValue) ([]string, error) { lister, err := kv.ListKeys(ctx) if err != nil { return nil, err } defer func() { _ = lister.Stop() }() keys := []string{} for k := range lister.Keys() { keys = append(keys, k) } sort.Strings(keys) return keys, nil } func (c *Conn) writable(module, name string) (StateIssued, error) { s, err := c.issuedState(module, name) if err != nil { return s, err } if !s.Writes { owner := name if dot := strings.LastIndex(name, "."); dot > 0 { owner = name[:dot] } return s, fmt.Errorf("%s reads %s and does not keep it: only %s's own instances write it (novox/hq ADR 0201)", module, name, owner) } return s, nil } // StateWatch hands deliver the current value of every key matching the pattern — none that is // deleted — and then every change, in order (ADR 0201). It returns once the current values are // delivered. **StateTimeout bounds the time without progress, not the whole set** (novox/hq issue // 1726): each current value is a round trip to the bundle, so a state of a few hundred keys outlasts // any fixed bound for all of them; the watch then failed at every attempt, the bundle dropped its // handler, and the newest keys, handed over last, were never taken (the checker's owed, whose newest // verdicts never reached mesh/check). It fails only when no current value arrives, or one is not // taken, within StateTimeout; deliver is called from one goroutine, one change at a time, and an error from it is said // and the watch goes on: state is not a queue, and the next change, or the next start, reads it again. // The pattern is a key, with `*` for one name and `**` for the rest; empty is every key. func (c *Conn) StateWatch(module, name, pattern string, deliver func(StateChange) error) (stop func(), err error) { s, err := c.issuedState(module, name) if err != nil { return nil, err } filter := ">" if pattern != "" { parts := strings.Split(pattern, ".") for i, p := range parts { if p == "**" { if i != len(parts)-1 { return nil, fmt.Errorf("%q: `**` stands for the rest of a key, so it comes last", pattern) } parts[i] = ">" continue } if p != "*" && !stateKey.MatchString(p) { return nil, fmt.Errorf("%q is not a key pattern: names, `*` for one and `**` for the rest", pattern) } } filter = strings.Join(parts, ".") } if s.PerNode { return c.perNodeWatch(module, s, pattern, deliver) } ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) defer cancel() type watching struct{ stop func() } w, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (watching, error) { stop, err := c.watchBucket(module, name, kv, filter, deliver) return watching{stop}, err }) if err != nil { return nil, err } return w.stop, nil } // watchBucket is StateWatch over one bucket: the current values, then every change. func (c *Conn) watchBucket(module, name string, kv jetstream.KeyValue, filter string, deliver func(StateChange) error) (stop func(), err error) { watching, stopWatching := context.WithCancel(context.Background()) w, err := kv.Watch(watching, filter) if err != nil { stopWatching() return nil, err } var once sync.Once stop = func() { once.Do(func() { _ = w.Stop() stopWatching() }) } current := make(chan struct{}) // handed says a current value was handed over or passed by: progress, which restarts the bound. handed := make(chan struct{}, 1) progress := func() { select { case handed <- struct{}{}: default: } } go func() { initial := true for e := range w.Updates() { // A watch given up, or stopped, hands over nothing more, though values stay buffered in the // watcher: they would reach a watch id the bundle no longer holds (issue 774: 1257 orphan // changes after 51 failed watches). if watching.Err() != nil { break } if e == nil { // The end of what was there when the watch began. if initial { initial = false close(current) } continue } if initial { // Arrival from the bus is progress before the bundle is asked: the bound measures the current // values coming in, and restarts when the bundle has taken one. progress() } change := StateChange{State: name, Key: e.Key(), Revision: e.Revision(), Current: initial} switch e.Operation() { case jetstream.KeyValuePut: change.Op = "put" change.Value = valueOf(e.Value()) default: // A deletion among the current values is a key that is not there: not handed over // (measured, research 024 — the server sends its marker among the initial values). if initial { progress() continue } change.Op = "delete" if e.Operation() == jetstream.KeyValuePurge { // The marker the server leaves when a key's time to live ends (Nats-Marker-Reason MaxAge, // read by the client as a purge): nothing else purges a module's state, since neither the // runtime nor mesh-sdk's State offers a purge (issue 1952). change.Op = "expire" } } if watching.Err() != nil { break } if err := deliver(change); err != nil { c.Logf("[mesh-tools] %s did not take %s %s of %s: %v; its next change, or its next start, reads it again", module, change.Op, change.Key, name, err) } if initial { progress() } } if initial { close(current) } }() bound := time.NewTimer(StateTimeout) defer bound.Stop() for { select { case <-current: return stop, nil case <-handed: if !bound.Stop() { select { case <-bound.C: default: } } bound.Reset(StateTimeout) case <-bound.C: stop() return nil, fmt.Errorf("the current values of %s did not arrive in %s: none was handed over in that time", name, StateTimeout) } } } func valueOf(raw []byte) json.RawMessage { if len(raw) == 0 || !json.Valid(raw) { b, _ := json.Marshal(string(raw)) return b } return json.RawMessage(raw) } // credentialEndings are the ends of a field name that say its value is a credential. A guard against // the ordinary mistake, not a determined one: a sealed value is plain text to anything inspecting it, // so the rule is checked where it can be and said to be partial (ADR 0201). var credentialEndings = []string{"password", "passwd", "secret", "token", "credential", "credentials", "authorization", "apikey", "privatekey", "accesskey", "cookie"} // credentialField is the first field anywhere in a JSON value whose name says it is a credential, or "". The one shape a // credential-shaped name may hold is a provider reference, an object of exactly `node` and `module`, both strings: a // the assignment's binding of the provision "secret" to the vault (issue 1126) names who provides it, never its value. Any // other shape under such a name is refused. func credentialField(value json.RawMessage) string { var v any if json.Unmarshal(value, &v) != nil { return "" } var walk func(any) string walk = func(v any) string { switch t := v.(type) { case map[string]any: keys := make([]string, 0, len(t)) for k := range t { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { norm := strings.NewReplacer("-", "", "_", "", " ", "").Replace(strings.ToLower(k)) for _, end := range credentialEndings { if strings.HasSuffix(norm, end) && !providerReference(t[k]) { return k } } if found := walk(t[k]); found != "" { return found } } case []any: for _, x := range t { if found := walk(x); found != "" { return found } } } return "" } return walk(v) } // providerReference says whether v is exactly {"node": , "module": }, each a name as mesh-sdk names them. func providerReference(v any) bool { m, ok := v.(map[string]any) if !ok || len(m) != 2 { return false } node, okN := m["node"].(string) module, okM := m["module"].(string) return okN && okM && referenceName.MatchString(node) && referenceName.MatchString(module) } // referenceName is a node's or a module's name as mesh-sdk names them: lower case, digits and dashes. var referenceName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)