T1 page by cursor: a state page continues from an opaque cursor in sequence order
mesh/state.page reads a state from an ordered watch 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, at most 768 KB a page, next the opaque cursor, empty at the end. A value written after the read reached its bucket comes marked seen-again (the cursor carries that mark; the runner keeps nothing per read); a deleted key gets no entry. A state kept one bucket per node is read one node's bucket after another. Builds: design 47 H2 §779, H-A-254, H-A-382
This commit is contained in:
@@ -5,16 +5,14 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||
"git.novox.be/novox/mesh-sdk/go/pernode"
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
@@ -46,6 +44,9 @@ type StateEntry struct {
|
||||
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
|
||||
@@ -228,7 +229,8 @@ func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) {
|
||||
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
|
||||
}
|
||||
|
||||
// StatePage is the current values after a key, in key order, and the key to ask after for the rest.
|
||||
// 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"`
|
||||
@@ -237,99 +239,176 @@ type StatePage struct {
|
||||
// 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
|
||||
|
||||
// StatePage reads the values in key order after `after` in one pass, as many as fit maxBytes (each key and value),
|
||||
// stopping when budget is spent, at least one value, so a bundle asks one request for many values, where StateGet
|
||||
// is one request each. Access is checked once and the bucket bound once. It is a read like StateGet: served to the
|
||||
// owner and to every reader, and writes nothing. Next is the last key given when more follow.
|
||||
func (c *Conn) StatePage(module, name, after string, maxBytes int, budget time.Duration) (StatePage, error) {
|
||||
// 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
|
||||
}
|
||||
// The bind and the listing have a StateTimeout of their own, and each get another: the page's time budget is what
|
||||
// ends a slow page (with Next), never a deadline spread over the whole of it.
|
||||
// ctx covers the bind and the listing alone; every bus request inside the loop takes each().
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||
defer cancel()
|
||||
each := func() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), StateTimeout)
|
||||
if maxBytes <= 0 || maxBytes > StatePageMost {
|
||||
maxBytes = StatePageMost
|
||||
}
|
||||
// Every current value is read in one stream per bucket (currentOf), never one bus request per key: a page of the
|
||||
// assignments (about 330 keys) read key by key took 13 s from a node far from the bus (2026-11-14).
|
||||
current := map[string]*StateEntry{}
|
||||
if s.PerNode {
|
||||
fam := c.family(s)
|
||||
keys, err := fam.Keys(ctx)
|
||||
if err != nil {
|
||||
return StatePage{}, err
|
||||
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)
|
||||
}
|
||||
nodes := map[string]bool{}
|
||||
for _, k := range keys {
|
||||
if node, err := pernode.NodeOf(k); err == nil {
|
||||
nodes[node] = true
|
||||
}
|
||||
}
|
||||
for node := range nodes {
|
||||
octx, ocancel := each() // each node's bucket is a bus request of its own: its own deadline
|
||||
kv, err := fam.Open(octx, node)
|
||||
ocancel()
|
||||
if err != nil {
|
||||
return StatePage{}, err
|
||||
}
|
||||
if kv == nil {
|
||||
continue
|
||||
}
|
||||
wctx, wcancel := each()
|
||||
got, err := currentOf(wctx, kv)
|
||||
wcancel()
|
||||
if err != nil {
|
||||
return StatePage{}, err
|
||||
}
|
||||
maps.Copy(current, got)
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
if current, err = inBucket(c, ctx, s, func(kv jetstream.KeyValue) (map[string]*StateEntry, error) {
|
||||
return currentOf(ctx, kv)
|
||||
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
|
||||
}
|
||||
keys := slices.Collect(maps.Keys(current))
|
||||
get := func(key string) (*StateEntry, error) { return current[key], nil }
|
||||
sort.Strings(keys)
|
||||
page := StatePage{Entries: []StateEntry{}}
|
||||
started := PageClock()
|
||||
size := 0
|
||||
for _, k := range keys {
|
||||
if after != "" && k <= after {
|
||||
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
|
||||
}
|
||||
if len(page.Entries) > 0 && PageClock().Sub(started) >= budget {
|
||||
page.Next = page.Entries[len(page.Entries)-1].Key
|
||||
break
|
||||
from, reached := pageCursor{node: node}, cursor != "" && node == at.node
|
||||
if reached {
|
||||
from = at
|
||||
}
|
||||
e, err := get(k)
|
||||
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 e == nil {
|
||||
continue
|
||||
if r.page.Next != "" {
|
||||
return r.page, nil
|
||||
}
|
||||
if size > 0 && size+len(k)+len(e.Value) > maxBytes {
|
||||
page.Next = page.Entries[len(page.Entries)-1].Key
|
||||
break
|
||||
}
|
||||
page.Entries = append(page.Entries, *e)
|
||||
size += len(k) + len(e.Value)
|
||||
}
|
||||
return 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).
|
||||
@@ -777,28 +856,3 @@ func providerReference(v any) bool {
|
||||
|
||||
// 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-]*$`)
|
||||
|
||||
// currentOf is every current value of a bucket, read in one stream (a watch of every key, deletes left out, ended at its
|
||||
// first nil): the values a page answers, without a bus request per key.
|
||||
func currentOf(ctx context.Context, kv jetstream.KeyValue) (map[string]*StateEntry, error) {
|
||||
w, err := kv.WatchAll(ctx, jetstream.IgnoreDeletes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = w.Stop() }()
|
||||
out := map[string]*StateEntry{}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("the values of %s are not all read: %w", kv.Bucket(), ctx.Err())
|
||||
case e, ok := <-w.Updates():
|
||||
if !ok {
|
||||
return out, nil
|
||||
}
|
||||
if e == nil {
|
||||
return out, nil
|
||||
}
|
||||
out[e.Key()] = &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user