diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go index 560d5659e..a32745934 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go @@ -16,6 +16,8 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/stateobjects" + "git.novox.be/novox/mesh-sdk/go/views" "mesh-delivery-forge-bridge/internal/bridge" "mesh-delivery-forge-bridge/internal/groups" @@ -126,6 +128,27 @@ func askState(s stdio.KeptState, bucket string, bound time.Duration, done func([ } } +// Module is the module whose tools these are; the generic prune tools are named for it (H-A-380 (3), H-A-433). +const Module = "mesh-delivery-forge-bridge" + +// PerformedPruneTools are `mesh-delivery-forge-bridge_state_prune_now` and `mesh-delivery-forge-bridge_state_keep` over +// the state performed (design 47 H2 §812): a prune to prune-target now, and a key kept from the prune under _keep/ +// until a time, each written in the hand-act log first. +func PerformedPruneTools(performed stdio.Prunable, acts views.HandActs) []stdio.Tool { + return stateobjects.PruneTools(Module, []stateobjects.Pruning{{Name: groups.PerformedState, State: performed}}, acts) +} + +// prunedPerformed is the state performed as the prune tools act on it, with the module's prune-mark and prune-target; a +// setting that is no percentage is said, and the defaults hold. +func prunedPerformed() *stdio.PrunedState { + p, err := stdio.PruneSettings() + if err != nil { + fmt.Fprintf(os.Stderr, "[mesh-delivery-forge-bridge-tools] the prune of performed keeps its defaults (%d %%, to %d %%): %v\n", stdio.PruneMarkDefault, stdio.PruneTargetDefault, err) + p = stdio.Prune{Mark: stdio.PruneMarkDefault, Target: stdio.PruneTargetDefault} + } + return stdio.State(groups.PerformedState).Pruned(p) +} + // askCaller calls a tool as this bundle's module, through the runtime (stdio.Ask), the module's own invokes granting it. func askCaller(_ context.Context, key string, body any) (json.RawMessage, error) { return stdio.Ask(key, body) @@ -145,6 +168,7 @@ func main() { _, err := recorder.Record(meshhandactsclient.Request{What: what, Why: why, Cause: "owed-dropped"}) return err }, time.Now)...) + tools = append(tools, PerformedPruneTools(prunedPerformed(), recorder)...) if err := stdio.Serve("", tools); err != nil { fmt.Fprintf(os.Stderr, "[mesh-delivery-forge-bridge-tools] %v\n", err) os.Exit(1) diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go index 832f48ff5..276312f72 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go @@ -10,6 +10,7 @@ import ( seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/views" "mesh-delivery-forge-bridge/internal/groups" ) @@ -164,4 +165,45 @@ func TestTheBridgeTools(t *testing.T) { t.Error("an ask naming no seat was taken") } }) + // Design 47 H2 §812 (H-A-380 (3), H-A-433): the bridge serves the two prune tools over its state performed, named for + // its module, each written in the hand-act log before it acts. + t.Run("the prune tools over performed", func(t *testing.T) { + p := &prunable{} + var recorded []views.HandAct + tools := map[string]stdio.Tool{} + for _, tool := range PerformedPruneTools(p, handActs(func(a views.HandAct) error { recorded = append(recorded, a); return nil })) { + tools[tool.Name] = tool + } + now, keep := tools["mesh-delivery-forge-bridge_state_prune_now"], tools["mesh-delivery-forge-bridge_state_keep"] + if len(tools) != 2 || now.Run == nil || keep.Run == nil { + t.Fatalf("the prune tools are %v, want mesh-delivery-forge-bridge_state_prune_now and _state_keep", tools) + } + until := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + if _, err := now.Run(map[string]any{"entry": "performed", "why": "full"}); err != nil || p.pruned != 1 { + t.Errorf("prune now: %v, pruned %d times", err, p.pruned) + } + if _, err := keep.Run(map[string]any{"entry": "performed", "key": "mesh-delivery.YQ", "until": until, "why": "read it"}); err != nil || p.kept != "mesh-delivery.YQ" { + t.Errorf("keep: %v, kept %q", err, p.kept) + } + if len(recorded) != 2 { + t.Errorf("hand acts %+v, want the prune and the keep", recorded) + } + }) } + +// prunable is a pruned state in memory. +type prunable struct { + pruned int + kept string +} + +func (p *prunable) PruneNow() (stdio.Pruned, error) { + p.pruned++ + return stdio.Pruned{State: "performed"}, nil +} +func (p *prunable) Keep(key string, _ time.Time) error { p.kept = key; return nil } + +// handActs records a hand act through record. +type handActs func(views.HandAct) error + +func (h handActs) RecordHandAct(a views.HandAct) error { return h(a) } diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/bound.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/bound.go index f92d1ca7d..63fc0b06c 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/bound.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/bound.go @@ -10,6 +10,7 @@ import ( "github.com/nats-io/nats.go/jetstream" + stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/process" ) @@ -38,10 +39,15 @@ type boundBucket struct { binding *process.Binding local string js process.BucketOpener + // prune, when set, prunes the entry toward its cap at the bridge's own writes (design 47 H2 §812; H-A-380): the + // bucket is bound through mesh-sdk's process.PrunedState, its figures read once when it is opened (again for a + // recreated entry's new bucket) and after each prune, and every Put is counted toward prune-mark. + prune *stdio.Prune - mu sync.Mutex - name string - kv jetstream.KeyValue + mu sync.Mutex + name string + kv jetstream.KeyValue + pruned *process.PrunedState } func (s *boundBucket) open(ctx context.Context) (jetstream.KeyValue, error) { @@ -61,7 +67,13 @@ func (s *boundBucket) open(ctx context.Context) (jetstream.KeyValue, error) { if err != nil { return nil, fmt.Errorf("the bus entry %q, bucket %s: %w", s.local, names.Bucket, err) } - s.name, s.kv = names.Bucket, kv + var pruned *process.PrunedState + if s.prune != nil { + if pruned, err = process.StateOver(forgeBridgeModule(), s.local, kv).Pruned(*s.prune); err != nil { + return nil, fmt.Errorf("the bus entry %q, bucket %s, cannot be bound for its prune: %w", s.local, names.Bucket, err) + } + } + s.name, s.kv, s.pruned = names.Bucket, kv, pruned return kv, nil } @@ -73,11 +85,19 @@ func (s *boundBucket) Get(ctx context.Context, key string) (jetstream.KeyValueEn return kv.Get(ctx, key) } +// Put writes a key whole; for an entry bound for its prune the write is counted, and past prune-mark the entry is +// pruned to prune-target before Put returns (§812). func (s *boundBucket) Put(ctx context.Context, key string, value []byte) (uint64, error) { kv, err := s.open(ctx) if err != nil { return 0, err } + s.mu.Lock() + pruned := s.pruned + s.mu.Unlock() + if pruned != nil { + return pruned.Put(key, json.RawMessage(value)) + } return kv.Put(ctx, key, value) } diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go index 260c87765..bbcdd7868 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go @@ -181,6 +181,9 @@ func answerOf(answer string) []byte { return []byte(`{"result":` + answer + `,"n // boundPerformed is the bus name the stand-in seat mesh-broker's show answers for the state performed. const boundPerformed = "mod_mesh-delivery-forge-bridge_performed_b1" +// performedCap is the cap of the bed's performed, small so a test fills it to its prune-mark (design 47 H2 §812). +const performedCap = 64 << 10 + // catalog is the repository the stand-in registrations name, its branch main watched (the seat mesh-catalog's fixture). const catalog = "novox/mesh-catalog" @@ -216,7 +219,11 @@ func startBed(t *testing.T, head string) *bed { } } for _, name := range []string{headsBucket(forgeBridgeModule()), boundPerformed, groupkeys.OwedAsksBucket(forgeBridgeModule())} { - if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1}); err != nil { + var capped int64 + if name == boundPerformed { + capped = performedCap + } + if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1, MaxBytes: capped}); err != nil { t.Fatal(err) } } @@ -624,4 +631,102 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { t.Errorf("performed of %s keeps %s, want the outcome, when and the pull request alone", g.ID, e.Value()) } refusedRead(t, b, "mesh-delivery-gate_owed") + + // Design 47 H2 §812 (F2, the bridge's whole test): a write that takes performed past prune-mark (70 % of its cap) + // prunes it, oldest acts first, down to prune-target (50 %); a key kept under _keep/ survives the prune. performed is + // filled while the bridge is stopped, so the bridge's bind at its start reads the fill once (H-A-380 (1)). + fillKey := func(i int) string { return performedKey(seat.Seat, fmt.Sprintf("fill-%03d", i)) } + fillValue := func(i, pad int) []byte { + v, _ := json.Marshal(Performed{Ended: forgemsg.OwedEnded{V: forgemsg.Version, Of: seat.Seat, ID: fmt.Sprintf("fill-%03d", i), + Outcome: forgemsg.OwedRefused, Words: strings.Repeat("w", pad), At: time.Now().UTC()}, Repository: "novox/mesh-sdk", Number: 1}) + return v + } + fillOf := func() uint64 { + t.Helper() + st, err := kept.Status(b.ctx) + if err != nil { + t.Fatal(err) + } + return st.Bytes() + } + mark, target := uint64(performedCap*70/100), uint64(performedCap*50/100) + fills, lastPut := 0, uint64(0) + b.restart(func() { + // The oldest filler (written below) kept from the prune for an hour, as mesh-delivery-forge-bridge_state_keep writes it. + keep, _ := json.Marshal(map[string]any{"until": time.Now().Add(time.Hour).UTC()}) + if _, err := kept.Put(b.ctx, "_keep/"+fillKey(0), keep); err != nil { + t.Fatal(err) + } + // Fill to 150 bytes below the mark: the last filler's words make up what is left, by the bytes one write was seen to put. + for { + before := fillOf() + if before+1200 >= mark { + per := uint64(600) // a put's bytes beside its value, as the first filler showed + if fills > 0 { + per = lastPut - uint64(len(fillValue(fills-1, 300))) + } + pad := int(mark - 150 - before - per - uint64(len(fillValue(fills, 0)))) + if _, err := kept.Put(b.ctx, fillKey(fills), fillValue(fills, pad)); err != nil { + t.Fatal(err) + } + fills++ + break + } + if _, err := kept.Put(b.ctx, fillKey(fills), fillValue(fills, 300)); err != nil { + t.Fatal(err) + } + lastPut = fillOf() - before + fills++ + } + }) + if f := fillOf(); f >= mark || f+400 < mark { + t.Fatalf("performed is filled to %d bytes, want just below its mark %d", f, mark) + } + pruned, err := kept.Watch(b.ctx, fillKey(1), jetstream.UpdatesOnly()) + if err != nil { + t.Fatal(err) + } + defer pruned.Stop() + other["id"] = "status.novox/mesh-sdk#178.aaaaaaaaaaaa.mesh/prune" + pruning, _ := json.Marshal(other) + if _, err := b.js.Publish(b.ctx, subject, pruning); err != nil { + t.Fatal(err) + } + if e := ended(); e.Outcome != forgemsg.OwedPerformed { + t.Errorf("the act that takes performed past its mark: %+v, want performed", e) + } + for gone, bound := false, time.After(20*time.Second); !gone; { + select { + case e := <-pruned.Updates(): + gone = e != nil && e.Operation() == jetstream.KeyValuePurge + case <-bound: + t.Fatalf("performed past its mark (%d of %d bytes) was not pruned within 20 s", fillOf(), uint64(performedCap)) + } + } + held := func(key string) bool { + _, err := kept.Get(b.ctx, key) + return err == nil + } + if !held(fillKey(0)) || !held("_keep/"+fillKey(0)) { + t.Errorf("the act kept under _keep/ was pruned") + } + if !held(performedKey(seat.Seat, "status.novox/mesh-sdk#178.aaaaaaaaaaaa.mesh/prune")) || !held(fillKey(fills-1)) { + t.Errorf("the newest acts were pruned") + } + // What the current values hold is down to the target: the bytes left, counted by mesh-sdk's upper bound per write (its + // key, its value and PutOverhead), which reads a little above the bus's own bytes the prune counted down from, so within + // 4 % of the cap; each purged key's marker aside. The bucket as the bus counts it is below the mark again. + keysLeft, err := kept.ListKeys(b.ctx) + if err != nil { + t.Fatal(err) + } + var left uint64 + for k := range keysLeft.Keys() { + if e, err := kept.Get(b.ctx, k); err == nil { + left += uint64(len(k) + len(e.Value()) + 96) + } + } + if left > target+performedCap*4/100 || left < target/2 || fillOf() >= mark { + t.Errorf("performed holds %d bytes of current values after its prune, want about its target %d (cap %d)", left, target, uint64(performedCap)) + } } diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/main.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/main.go index 5c3b26e6f..9c6ed0e0f 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/main.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/main.go @@ -16,6 +16,7 @@ import ( "syscall" "time" + stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/process" "git.novox.be/novox/mesh-sdk/go/views" @@ -106,7 +107,15 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro if w := binding.Waiting(); w != "" { logger.Printf("the bridge %s: nothing owed to the forge is performed until it is bound", w) } - performedKV := &boundBucket{binding: binding, local: performedLocal, js: js} + // performed is pruned toward its cap at the bridge's own writes (design 47 H2 §812): past prune-mark the oldest acts + // go down to prune-target, in one journal line, a key kept under _keep/ staying. A setting that is no percentage is + // said, and the defaults hold. + prune, err := stdio.PruneSettings() + if err != nil { + logger.Printf("the prune of performed keeps its defaults (%d %%, to %d %%): %v", stdio.PruneMarkDefault, stdio.PruneTargetDefault, err) + prune = stdio.Prune{Mark: stdio.PruneMarkDefault, Target: stdio.PruneTargetDefault} + } + performedKV := &boundBucket{binding: binding, local: performedLocal, js: js, prune: &prune} // What the gate owes the forge, performed through the seat git (design 47 *What the gate owes the forge*). owe := &owing{call: call, pub: js, performed: kvPerformed{performedKV}, acts: streamActs{js: js}, waits: binding.Waiting, now: time.Now, logger: logger} keptCall := keptCallOf(ctx, call) diff --git a/modules/mesh-delivery-forge-bridge/manifest_test.go b/modules/mesh-delivery-forge-bridge/manifest_test.go index 3c81cb8dd..90bd18e1e 100644 --- a/modules/mesh-delivery-forge-bridge/manifest_test.go +++ b/modules/mesh-delivery-forge-bridge/manifest_test.go @@ -26,6 +26,18 @@ type stream struct { type state struct { Name string `json:"name"` History int `json:"history"` + MaxMiB int `json:"max-mib"` +} + +// setting is an entry of config. +type setting struct { + Type string `json:"type"` + Description string `json:"description"` + Trusted bool `json:"trusted"` + Runtime bool `json:"runtime"` + Minimum float64 `json:"minimum"` + Maximum float64 `json:"maximum"` + Default any `json:"default"` } // kept is an entry of requires in its long form: kept data on the bus (novox/hq ADR 0595). @@ -49,19 +61,20 @@ type artifact struct { } type manifest struct { - Module string `json:"module"` - Version string `json:"version"` - Slug string `json:"slug"` - Consumes []string `json:"consumes"` - Streams []stream `json:"streams"` - State []state `json:"state"` - Requires []kept `json:"requires"` - Reads []string `json:"reads"` - Tools []string `json:"tools"` - Invokes []string `json:"invokes"` - OwnSecrets map[string]string `json:"own-secrets"` - SecretsOwner string `json:"secrets-owner"` - Resources []map[string]any `json:"resources"` + Module string `json:"module"` + Version string `json:"version"` + Slug string `json:"slug"` + Consumes []string `json:"consumes"` + Streams []stream `json:"streams"` + State []state `json:"state"` + Requires []kept `json:"requires"` + Reads []string `json:"reads"` + Tools []string `json:"tools"` + Invokes []string `json:"invokes"` + Config map[string]setting `json:"config"` + OwnSecrets map[string]string `json:"own-secrets"` + SecretsOwner string `json:"secrets-owner"` + Resources []map[string]any `json:"resources"` Build struct { Artifacts []artifact `json:"artifacts"` } `json:"build"` @@ -125,20 +138,28 @@ func TestManifestDeclarations(t *testing.T) { // 1235/AC1 if m.SecretsOwner != "mesh-delivery-forge-bridge" { t.Errorf("secrets-owner = %q", m.SecretsOwner) } - // The head held for each watched branch (design 47 H §739), and the asks about what is owed. What it performed of what is - // owed is kept data in the new form, one key per act, kept 7 days as the owner's stream owed is; its size is the - // template's own (design 47 *What the gate owes the forge*, ADR 0595 §3). No inputs, end-asks or findings (H §764, H-A-48). - if !reflect.DeepEqual(m.State, []state{{Name: "heads", History: 1}, {Name: "owed-asks", History: 1}}) { + // The head held for each watched branch (design 47 H §739), and the asks about what is owed, each capped at 8 MiB + // (design 47 H2 §812, H-A-411 (2)). What it performed of what is owed is kept data in the new form, one key per act, + // kept 3 days by the bucket's TTL, performed-keep, and capped at 8 MiB, pruned toward it at the bridge's writes (§812, + // H-A-433). No inputs, end-asks or findings (H §764, H-A-48). + if !reflect.DeepEqual(m.State, []state{{Name: "heads", History: 1, MaxMiB: 8}, {Name: "owed-asks", History: 1, MaxMiB: 8}}) { t.Errorf("state = %+v, want the buckets heads and owed-asks", m.State) } - if want := []kept{{Name: "performed", Storage: "key-value", Template: "state", Options: map[string]any{"history": float64(1), "ttl-seconds": float64(604800)}}}; !reflect.DeepEqual(m.Requires, want) { + if want := []kept{{Name: "performed", Storage: "key-value", Template: "state", Options: map[string]any{"history": float64(1), "ttl-seconds": float64(259200), "max-mib": float64(8)}}}; !reflect.DeepEqual(m.Requires, want) { t.Errorf("requires = %+v, want performed alone as %+v", m.Requires, want) } // bridge_tags reads a package's tags for the builder's floor (design 51); bridge_heads reads the state heads (design 47 - // H-A-85); the owed tools ask the bridge through owed-asks. - if want := []string{"bridge_heads", "bridge_owed", "bridge_owed_again", "bridge_owed_drop", "bridge_tags"}; !reflect.DeepEqual(sorted(m.Tools), want) { + // H-A-85); the owed tools ask the bridge through owed-asks; the two prune tools act on performed (§812, H-A-380 (3)). + if want := []string{"bridge_heads", "bridge_owed", "bridge_owed_again", "bridge_owed_drop", "bridge_tags", + "mesh-delivery-forge-bridge_state_keep", "mesh-delivery-forge-bridge_state_prune_now"}; !reflect.DeepEqual(sorted(m.Tools), want) { t.Errorf("tools = %v, want %v", m.Tools, want) } + // performed's prune starts past prune-mark and ends at prune-target, settings read at run time (§812). + for key, def := range map[string]float64{"prune-mark": 70, "prune-target": 50} { + if c := m.Config[key]; c.Default != any(def) || !c.Runtime { + t.Errorf("config %s = %+v, want a runtime setting defaulting to %v", key, c, def) + } + } // Design 47 H §764 (B3 AC1): the earlier model's names are in no file of the bridge but tests asserting their absence. retired := []string{"pushed", "forge.group.merged", "bridge_groups", "bridge_group_end_again", "bridge_merged_message", "OwedActMerge", "mesh-delivery-checker", "seat:git.merge-pull", "branch-unprotected", "ForgeMerged", "ForgePushed"} diff --git a/modules/mesh-delivery-forge-bridge/module.json b/modules/mesh-delivery-forge-bridge/module.json index 2cdf59b7a..b5a412112 100644 --- a/modules/mesh-delivery-forge-bridge/module.json +++ b/modules/mesh-delivery-forge-bridge/module.json @@ -14,15 +14,17 @@ { "name": "forge", "events": ["forge.**", "owed.ended"], "max-age-days": 7 } ], "state": [ - { "name": "heads", "history": 1 }, - { "name": "owed-asks", "history": 1 } + { "name": "heads", "history": 1, "max-mib": 8 }, + { "name": "owed-asks", "history": 1, "max-mib": 8 } ], "tools": [ "bridge_tags", "bridge_heads", "bridge_owed", "bridge_owed_again", - "bridge_owed_drop" + "bridge_owed_drop", + "mesh-delivery-forge-bridge_state_prune_now", + "mesh-delivery-forge-bridge_state_keep" ], "invokes": [ "seat:git.status", @@ -41,9 +43,29 @@ "name": "performed", "storage": "key-value", "template": "state", - "options": { "history": 1, "ttl-seconds": 604800 } + "options": { "history": 1, "ttl-seconds": 259200, "max-mib": 8 } } ], + "config": { + "prune-mark": { + "type": "number", + "description": "The fill of the bridge's state performed, in percent of its cap, past which the bridge prunes it at its own write, oldest acts first (design 47 H2 §812): below the bus module's raise mark of 75 %.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 70 + }, + "prune-target": { + "type": "number", + "description": "The fill, in percent of the cap, a prune of the bridge's state performed takes it down to (design 47 H2 §812); below prune-mark.", + "trusted": false, + "runtime": true, + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, "own-secrets": { "broker": "${dir:state}/broker" },