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()}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1206,8 +1206,9 @@ type stateAsked struct {
|
||||
// TTLSeconds gives a created or put key its own time to live (issue 1952): create makes it only when it has no
|
||||
// value, put renews it whole. Zero is none.
|
||||
TTLSeconds int `json:"ttl_seconds"`
|
||||
// After and MaxBytes are a `page`'s start key and its size in keys and values (zero is a megabyte).
|
||||
After string `json:"after"`
|
||||
// Cursor and MaxBytes are a `page`'s opaque cursor, the next of the page before (empty: from the start), and its size in
|
||||
// keys and values (zero, or above 768 KB, is 768 KB; design 47 H2 §779).
|
||||
Cursor string `json:"cursor"`
|
||||
MaxBytes int `json:"max_bytes"`
|
||||
// BudgetMS is the time a `page` may spend reading, in milliseconds (zero is the runtime's own, well under 30 s).
|
||||
BudgetMS int `json:"budget_ms"`
|
||||
@@ -1239,11 +1240,8 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
|
||||
}
|
||||
answer = entry
|
||||
case "page":
|
||||
// The values after a key in key order, one request for many (a first view's page of a slow state).
|
||||
if asked.MaxBytes <= 0 {
|
||||
asked.MaxBytes = 1 << 20
|
||||
}
|
||||
page, err := conn.StatePage(b.module, asked.State, asked.After, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
|
||||
// One page of the state in the order the bus wrote it, after the cursor, one request for many (design 47 H2 §779).
|
||||
page, err := conn.StatePage(b.module, asked.State, asked.Cursor, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -150,35 +150,61 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
|
||||
!strings.Contains(err.Error(), "not a key") {
|
||||
t.Errorf("history of a key the bus cannot hold: %v", err)
|
||||
}
|
||||
// A page is the values in key order after a key, in one request, to the owner and to a reader, never to a
|
||||
// module not issued the state; a page too small for two values still gives one and says where it goes on.
|
||||
for k, v := range map[string]string{"2": `"bb"`, "3": `"cc"`} {
|
||||
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": k, "value": json.RawMessage(v)}); err != nil {
|
||||
// A page is the values in the order the bus wrote them after the cursor, in one request, to the owner and to a reader,
|
||||
// never to a module not issued the state; a page too small for two values still gives one and says where the read goes
|
||||
// on; a value written after the read began comes marked seen-again, and a fresh read hands each kept message, a key's
|
||||
// older kept revision included (design 47 H2 §779, H-A-382).
|
||||
for _, kv := range [][2]string{{"2", `"bb"`}, {"3", `"cc"`}} {
|
||||
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": kv[0], "value": json.RawMessage(kv[1])}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
type page struct {
|
||||
Entries []kept `json:"entries"`
|
||||
Next string `json:"next"`
|
||||
type entry struct {
|
||||
Key string `json:"key"`
|
||||
SeenAgain bool `json:"seen-again"`
|
||||
}
|
||||
for _, c := range []struct {
|
||||
who, state, after string
|
||||
max int
|
||||
keys []string
|
||||
next string
|
||||
}{{"owner", "issues", "", 1 << 20, []string{"1", "2", "3"}, ""}, {"reader", "issues.issues", "1", 1 << 20, []string{"2", "3"}, ""},
|
||||
{"owner", "issues", "", 1, []string{"1"}, "1"}, {"owner", "issues", "1", 9, []string{"2"}, "2"}} {
|
||||
b := map[string]launch.Bus{"owner": owner, "reader": reader}[c.who]
|
||||
raw, err := ask(b, "page", map[string]any{"state": c.state, "after": c.after, "max_bytes": c.max})
|
||||
type page struct {
|
||||
Entries []entry `json:"entries"`
|
||||
Next string `json:"next"`
|
||||
}
|
||||
read := func(who launch.Bus, state, cursor string, most int) page {
|
||||
t.Helper()
|
||||
raw, err := ask(who, "page", map[string]any{"state": state, "cursor": cursor, "max_bytes": most})
|
||||
var p page
|
||||
if err != nil || json.Unmarshal(raw, &p) != nil || p.Next != c.next || len(p.Entries) != len(c.keys) {
|
||||
t.Fatalf("page %+v = %s, %v", c, raw, err)
|
||||
if err != nil || json.Unmarshal(raw, &p) != nil {
|
||||
t.Fatalf("page of %s after %q = %s, %v", state, cursor, raw, err)
|
||||
}
|
||||
for i, k := range c.keys {
|
||||
if p.Entries[i].Key != k {
|
||||
t.Errorf("page %+v: entry %d is %s, want %s", c, i, p.Entries[i].Key, k)
|
||||
}
|
||||
return p
|
||||
}
|
||||
said := func(p page) string {
|
||||
var out []string
|
||||
for _, e := range p.Entries {
|
||||
out = append(out, e.Key+map[bool]string{true: "+again"}[e.SeenAgain])
|
||||
}
|
||||
return strings.Join(out, ",") + map[bool]string{true: " (more)"}[p.Next != ""]
|
||||
}
|
||||
for who, b := range map[string]launch.Bus{"issues": owner, "issues.issues": reader} {
|
||||
if got := said(read(b, who, "", 1<<20)); got != "1,2,3" {
|
||||
t.Errorf("a whole page of %s is %s, want 1,2,3", who, got)
|
||||
}
|
||||
}
|
||||
first := read(owner, "issues", "", 1)
|
||||
second := read(owner, "issues", first.Next, 1)
|
||||
if said(first) != "1 (more)" || said(second) != "2 (more)" {
|
||||
t.Fatalf("pages of one value are %s and %s, want 1 (more) and 2 (more)", said(first), said(second))
|
||||
}
|
||||
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "1", "value": 11}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := said(read(owner, "issues", second.Next, 1<<20)); got != "3,1+again" {
|
||||
t.Errorf("the rest of the read is %s, want 3 and 1 written again since the read began, marked: 3,1+again", got)
|
||||
}
|
||||
if got := said(read(owner, "issues", "", 1<<20)); got != "1,2,3,1" {
|
||||
t.Errorf("a fresh read is %s, want each kept message once, 1's older revision first: 1,2,3,1", got)
|
||||
}
|
||||
if _, err := ask(owner, "page", map[string]any{"state": "issues", "cursor": "2"}); err == nil ||
|
||||
!strings.Contains(err.Error(), "not a cursor") {
|
||||
t.Errorf("a page after a key, not a cursor, answered %v; want it refused", err)
|
||||
}
|
||||
// A page stops when its time budget is spent, after one value at least, and says where it goes on.
|
||||
step := time.Time{}
|
||||
@@ -186,7 +212,7 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
|
||||
defer func() { bus.PageClock = time.Now }()
|
||||
raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000})
|
||||
var cut page
|
||||
if err != nil || json.Unmarshal(raw, &cut) != nil || len(cut.Entries) != 1 || cut.Next != "1" {
|
||||
if err != nil || json.Unmarshal(raw, &cut) != nil || said(cut) != "1 (more)" {
|
||||
t.Fatalf("a page past its budget = %s, %v", raw, err)
|
||||
}
|
||||
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
|
||||
|
||||
Reference in New Issue
Block a user