S11 prune helper and tools: a kept store is pruned toward its cap at its own writes
A process judges a running sum of what its writes put against the figures read at the bind and after each prune; a bundle judges the fill the runtime's put answer carries. Past prune-mark (70 %) the oldest keys by revision go down to prune-target (50 %), in one journal line; a key kept under _keep/<key> stays, and no reader counts the keep. The generic tools <module>_state_prune_now and <module>_state_keep act through the hand-act log. Builds: design 47 H2 §812, H-A-380, H-A-386
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// sayPrune writes a prune's one journal line (design 47 H2 §812).
|
||||
var sayPrune = func(line string) { log.Print(line) }
|
||||
|
||||
// PrunedState is a state a process prunes at its own writes (design 47 H2 §812; H-A-380): the entry's figures are read
|
||||
// once when it is bound and once after each prune, and between those a running sum of the bytes each write puts
|
||||
// (stdio.PutBytes, an upper bound) is the judgement; past prune-mark of the cap the oldest keys by their current
|
||||
// revision are purged down to prune-target, skipping a key kept under stdio.KeepKey. No read per write, no poll, no timer.
|
||||
// Its reads are the state's own.
|
||||
type PrunedState struct {
|
||||
State
|
||||
pruner *stdio.Pruner
|
||||
}
|
||||
|
||||
// Pruned binds the state for a prune by p, reading its figures once.
|
||||
func (s State) Pruned(p stdio.Prune) (*PrunedState, error) {
|
||||
ps := &PrunedState{State: s}
|
||||
ps.pruner = &stdio.Pruner{State: s.Module + "'s " + s.Name, Prune: p, Say: func(line string) { sayPrune(line) },
|
||||
Figures: s.figures, Entries: s.entries, Remove: s.purge}
|
||||
if err := ps.pruner.Bind(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
// figures is the bucket's bytes and its cap, zero for none.
|
||||
func (s State) figures() (uint64, uint64, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
|
||||
defer cancel()
|
||||
kv, err := s.store(ctx)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
st, err := kv.Status(ctx)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return st.Bytes(), uint64(max(st.Config().MaxBytes, 0)), nil
|
||||
}
|
||||
|
||||
// entries is every current value of the bucket with its revision, keeps included, read once.
|
||||
func (s State) entries() ([]stdio.PruneEntry, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
|
||||
defer cancel()
|
||||
kv, err := s.store(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w, err := kv.WatchAll(ctx, jetstream.IgnoreDeletes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer w.Stop()
|
||||
var out []stdio.PruneEntry
|
||||
for {
|
||||
select {
|
||||
case e, open := <-w.Updates():
|
||||
if !open {
|
||||
return nil, errors.New("the read of the current values ended")
|
||||
}
|
||||
if e == nil {
|
||||
return out, nil
|
||||
}
|
||||
if e.Operation() == jetstream.KeyValuePut {
|
||||
out = append(out, stdio.PruneEntry{Key: e.Key(), Revision: e.Revision(), Bytes: stdio.PutBytes(e.Key(), e.Value()), Value: e.Value()})
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// purge removes a key with its past values, so its bytes leave the bucket.
|
||||
func (s State) purge(key string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stateTimeout)
|
||||
defer cancel()
|
||||
kv, err := s.store(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return kv.Purge(ctx, key)
|
||||
}
|
||||
|
||||
// wrote counts a write and prunes past the mark.
|
||||
func (s *PrunedState) wrote(key string, value any, rev uint64, err error) (uint64, error) {
|
||||
if err != nil {
|
||||
return rev, err
|
||||
}
|
||||
data, _ := json.Marshal(value)
|
||||
if _, err := s.pruner.Wrote(stdio.PutBytes(key, data)); err != nil {
|
||||
return rev, err
|
||||
}
|
||||
return rev, nil
|
||||
}
|
||||
|
||||
// Put writes a key whole, counted toward the prune.
|
||||
func (s *PrunedState) Put(key string, value any) (uint64, error) {
|
||||
rev, err := s.State.Put(key, value)
|
||||
return s.wrote(key, value, rev, err)
|
||||
}
|
||||
|
||||
// Create writes a key only when it has none, counted toward the prune.
|
||||
func (s *PrunedState) Create(key string, value any) (uint64, error) {
|
||||
rev, err := s.State.Create(key, value)
|
||||
return s.wrote(key, value, rev, err)
|
||||
}
|
||||
|
||||
// Update writes a key only when it is still at revision, counted toward the prune.
|
||||
func (s *PrunedState) Update(key string, value any, revision uint64) (uint64, error) {
|
||||
rev, err := s.State.Update(key, value, revision)
|
||||
return s.wrote(key, value, rev, err)
|
||||
}
|
||||
|
||||
// PruneNow prunes the state to its target now.
|
||||
func (s *PrunedState) PruneNow() (stdio.Pruned, error) { return s.pruner.PruneNow() }
|
||||
|
||||
// Keep keeps key from the prune until until, written under stdio.KeepKey.
|
||||
func (s *PrunedState) Keep(key string, until time.Time) error {
|
||||
if err := stdio.KeepProblem(key, until); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.Put(stdio.KeepKey(key), stdio.Keep{Until: until.UTC()})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// pruneKV is a fakeKV with a cap: its bytes are what its current values put (stdio.PutBytes), its Status says them
|
||||
// with the cap, WatchAll hands every current value, and Purge removes a key.
|
||||
type pruneKV struct {
|
||||
*fakeKV
|
||||
cap int64
|
||||
statuss int
|
||||
}
|
||||
|
||||
type pruneStatus struct {
|
||||
jetstream.KeyValueStatus
|
||||
bytes uint64
|
||||
cap int64
|
||||
}
|
||||
|
||||
func (s pruneStatus) Bytes() uint64 { return s.bytes }
|
||||
func (s pruneStatus) Config() jetstream.KeyValueConfig {
|
||||
return jetstream.KeyValueConfig{MaxBytes: s.cap}
|
||||
}
|
||||
|
||||
func (f *pruneKV) held() uint64 {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var n uint64
|
||||
for k, v := range f.values {
|
||||
n += stdio.PutBytes(k, v)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (f *pruneKV) Status(context.Context) (jetstream.KeyValueStatus, error) {
|
||||
f.statuss++
|
||||
return pruneStatus{bytes: f.held(), cap: f.cap}, nil
|
||||
}
|
||||
|
||||
func (f *pruneKV) WatchAll(context.Context, ...jetstream.WatchOpt) (jetstream.KeyWatcher, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
w := &fakeWatcher{updates: make(chan jetstream.KeyValueEntry, len(f.values)+1)}
|
||||
for k, v := range f.values {
|
||||
w.updates <- putEntry{fakeEntry{key: k, value: v, rev: f.revs[k]}}
|
||||
}
|
||||
w.updates <- nil
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (f *pruneKV) Purge(ctx context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
|
||||
return f.Delete(ctx, key)
|
||||
}
|
||||
|
||||
type putEntry struct{ fakeEntry }
|
||||
|
||||
func (putEntry) Operation() jetstream.KeyValueOp { return jetstream.KeyValuePut }
|
||||
|
||||
// Design 47 H2 §812 (H-A-380, H-A-386): a process's write that takes its state past prune-mark prunes it, oldest first
|
||||
// by revision, to prune-target, in one journal line, reading the figures only at the bind and after the prune; a key
|
||||
// kept under _keep/<key> survives, and no reader counts the keep.
|
||||
func TestAProcessWritePastItsMarkPrunesToItsTargetAndAKeptKeySurvives(t *testing.T) {
|
||||
var lines []string
|
||||
sayPrune = func(line string) { lines = append(lines, line) }
|
||||
t.Cleanup(func() { sayPrune = func(string) {} })
|
||||
kv := &pruneKV{fakeKV: newFakeKV(), cap: 10_000}
|
||||
s, err := stateOn(kv).Pruned(stdio.Prune{Mark: 70, Target: 50})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value := strings.Repeat("x", 300)
|
||||
if _, err := s.Put("k00", value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Keep("k00", time.Now().Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Keep("k01", time.Now().Add(-time.Hour)); err == nil {
|
||||
t.Fatal("a keep until a time past was taken")
|
||||
}
|
||||
for i := 1; i < 18; i++ {
|
||||
if _, err := s.Put(fmt.Sprintf("k%02d", i), value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(lines) == 0 && kv.held()*100 > 70*10_000 {
|
||||
t.Fatalf("the state holds %d of 10000 bytes after k%02d and was not pruned", kv.held(), i)
|
||||
}
|
||||
}
|
||||
if len(lines) != 1 || !strings.Contains(lines[0], "pruned the state mesh-mail's sends") {
|
||||
t.Fatalf("the prunes said %q, want one line", lines)
|
||||
}
|
||||
if kv.statuss != 2 {
|
||||
t.Fatalf("the figures were read %d times, want 2: at the bind and after the prune", kv.statuss)
|
||||
}
|
||||
if held := kv.held(); held*100 > 50*10_000 {
|
||||
t.Fatalf("the prune left %d of 10000 bytes, above its target of 50 %%", held)
|
||||
}
|
||||
keys, err := s.Keys()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keys[0] != "k00" || strings.Contains(strings.Join(keys, " "), "_keep") || keys[1] == "k01" || keys[len(keys)-1] != "k17" {
|
||||
t.Fatalf("after the prune the readers see %v: want k00 kept, the oldest others gone, k17 there, no keep", keys)
|
||||
}
|
||||
if e, _ := s.Get(stdio.KeepKey("k00")); e == nil {
|
||||
t.Fatal("the keep itself was pruned")
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -257,7 +257,7 @@ func (s State) put(key string, value any) (uint64, error) {
|
||||
return rev, nil
|
||||
}
|
||||
|
||||
// Keys is every key with a current value, sorted; none is an empty list.
|
||||
// Keys is every key with a current value, sorted; none is an empty list. A keep (stdio.KeepPrefix) is not an entry and is left out.
|
||||
// Keys waits out a bus that answers nothing for a few seconds (busretry): only a request that reached no one is asked again.
|
||||
func (s State) Keys() ([]string, error) {
|
||||
return busretry.Do(s.what("keys"), func() ([]string, error) { return s.keys() }, nil)
|
||||
@@ -277,8 +277,14 @@ func (s State) keys() ([]string, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s's state %s, keys: %w", s.Module, s.Name, err)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
entries := keys[:0]
|
||||
for _, k := range keys {
|
||||
if !stdio.IsKeep(k) {
|
||||
entries = append(entries, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(entries)
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// watchPattern is a key narrowing as the bus names it: `*` stays one name, `**` is the rest, empty is every key.
|
||||
@@ -334,6 +340,9 @@ func (s State) Watch(key string, handle func(stdio.StateChange) error) error {
|
||||
}
|
||||
}
|
||||
deliver := func(e jetstream.KeyValueEntry, current bool) error {
|
||||
if stdio.IsKeep(e.Key()) {
|
||||
return nil // a keep (stdio.KeepPrefix) is not an entry of the state: no watcher hears it
|
||||
}
|
||||
c := stdio.StateChange{State: s.Name, Key: e.Key(), Op: "put", Revision: e.Revision(), Current: current}
|
||||
if e.Operation() == jetstream.KeyValuePut {
|
||||
c.Value = json.RawMessage(e.Value())
|
||||
|
||||
Reference in New Issue
Block a user