G15 recreate-in-place: a recreate reads the account's room first, changes each object in place where the bus takes it, makes empty only a retention that changes, stops at a refused change; the ask names each object

Builds: design 47 H2 H-A-686 (1) (2) (3), H-A-634 (3), H-A-706 (DQ-42) (hq 95cf2052, 999e6525, 543e6963)
This commit is contained in:
2026-11-25 17:33:19 +01:00
parent 5de68de0a0
commit 8aef19934e
11 changed files with 427 additions and 26 deletions
+3 -2
View File
@@ -66,8 +66,9 @@ func capsOf(all map[string]keeper.Asked, status func() (keeper.Status, error)) *
type busStream struct {
Config jetstream.StreamConfig `json:"config"`
State struct {
Messages uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
Messages uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
FirstTS time.Time `json:"first_ts"`
} `json:"state"`
}
@@ -401,7 +401,7 @@ func TestTheBusModuleRunsWhole(t *testing.T) {
put(keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused"})
eventually(t, "the drop with no ask refused", func() bool { return strings.Contains(get("r1").Error, "operator's warrant") })
r := keeper.Request{ID: "r2", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Caller: "person.jo", Why: "unused", At: time.Now(), AskExpires: time.Now().Add(keeper.AskLasts)}
a, _ := askFor(r)
a, _ := askFor(r, "")
r.Ask = a.ID
record := func(w *oc.Warrant) {
raw, _ := json.Marshal(map[string]any{"asker": keeper.Module, "ask": a, "state": "open", "warrant": w})
@@ -757,3 +757,71 @@ func entry(name, storage, template string, options map[string]string) catalogue.
}
return e
}
// Design 47 H2 H-A-686: the change the bus takes in place keeps what the object holds. On the real bus, a stream holding
// messages is changed to a shorter age, a lifetime per message and a refusal when full, keeps its messages, and takes a lifetime
// on its next write; a bucket changed to a lifetime per key keeps its keys.
func TestTheBusTakesARecreatesChangeInPlace(t *testing.T) {
s, err := server.NewServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir(), NoLog: true, NoSigs: true})
if err != nil {
t.Fatal(err)
}
go s.Start()
if !s.ReadyForConnections(5 * time.Second) {
t.Fatal("the server did not start")
}
defer s.Shutdown()
nc, err := nats.Connect(s.ClientURL())
if err != nil {
t.Fatal(err)
}
defer nc.Close()
js, _ := jetstream.New(nc)
ctx := context.Background()
bus := keeper.JetStream{JS: js}
stream := keeper.Object{Kind: keeper.KindStream, Name: "m_events", Subjects: []string{"m.events.>"},
Settings: keeper.Settings{MaxBytes: 4 << 20, MaxAgeSeconds: 0, Discard: keeper.DiscardOld}}
bucket := keeper.Object{Kind: keeper.KindBucket, Name: "m_state", Settings: keeper.Settings{MaxBytes: 4 << 20, History: 1, Discard: keeper.DiscardNew}}
for _, o := range []keeper.Object{stream, bucket} {
if err := bus.Create(ctx, o); err != nil {
t.Fatal(err)
}
}
for i := range 5 {
if _, err := js.Publish(ctx, fmt.Sprintf("m.events.%d", i), []byte("x")); err != nil {
t.Fatal(err)
}
}
kv, _ := js.KeyValue(ctx, "m_state")
for _, k := range []string{"a", "b"} {
if _, err := kv.Put(ctx, k, []byte("v")); err != nil {
t.Fatal(err)
}
}
stream.Settings = keeper.Settings{MaxBytes: 4 << 20, MaxAgeSeconds: 3600, Discard: keeper.DiscardNew, KeyTTL: true}
bucket.Settings.KeyTTL = true
for _, o := range []keeper.Object{stream, bucket} {
if err := bus.Update(ctx, o); err != nil {
t.Fatalf("%s: %v", o.Stream(), err)
}
}
held, fill, _, err := bus.Held(ctx, stream)
if err != nil || fill.Messages != 5 || held.MaxAgeSeconds != 3600 || held.Discard != keeper.DiscardNew || !held.KeyTTL {
t.Fatalf("the stream holds %+v, %+v (%v): it keeps its messages and takes the settings", held, fill, err)
}
msg := &nats.Msg{Subject: "m.events.9", Data: []byte("x"), Header: nats.Header{"Nats-TTL": []string{"60s"}}}
if _, err := js.PublishMsg(ctx, msg); err != nil {
t.Fatalf("a message with a lifetime of its own is refused after the change: %v", err)
}
if _, fill, _, _ := bus.Held(ctx, bucket); fill.Messages != 2 {
t.Fatalf("the bucket holds %d keys, want 2", fill.Messages)
}
if _, err := kv.Create(ctx, "c", []byte("v"), jetstream.KeyTTL(time.Minute)); err != nil {
t.Fatalf("a key with a lifetime of its own is refused after the change: %v", err)
}
// A held lifetime is never turned off by an Update: the bus would refuse it, and the keeper's comparison matches it.
stream.Settings.KeyTTL = false
if err := bus.Update(ctx, stream); err != nil {
t.Fatalf("an ask of no lifetime over a held one: %v", err)
}
}
+11
View File
@@ -197,6 +197,17 @@ func allTools() []stdio.Tool {
out = append(out, keeperHealthTool(StatusInState, HeldInState, jsz))
out = append(out, readTools(jsz, LiveMsgGet(LiveBus()))...)
rs := RequestsInState()
rs.Explain = func(r keeper.Request) (string, error) {
held, err := HeldInState()
if err != nil {
return "", err
}
raw, err := jsz()
if err != nil {
return "", err
}
return recreateWords(held, StatusInState, raw, time.Now(), LiveOlderThan(LiveBus()), r.Module, r.Local)
}
out = append(out, snapshotListTool(rs, bundleKeepDays)...)
out = append(out, plansTool(PlansInState))
return append(out, requestTools(rs)...)
+127
View File
@@ -0,0 +1,127 @@
package main
// What the operator's ask for a recreate names (design 47 H2 H-A-686 (3), H-A-706 on DQ-42): per object whether it is changed in
// place or made again empty, its held and asked settings, the messages, bytes and oldest message's time it holds, read when
// the ask is raised, and what the change removes; and the room the caps it asks need on the bus's account.
import (
"context"
"fmt"
"strings"
"time"
"github.com/nats-io/nats.go/jetstream"
"nats-tools/internal/keeper"
)
// olderThan counts the messages of a stream stored before a time.
type olderThan func(stream string, before time.Time) (uint64, error)
// LiveOlderThan counts them on the bus by an ordered consumer that starts at the time: the messages before it are those the
// stream holds less the ones the consumer has pending.
func LiveOlderThan(bus Bus) olderThan {
return func(stream string, before time.Time) (uint64, error) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
js, closeBus, err := bus(ctx)
if err != nil {
return 0, err
}
defer closeBus()
s, err := js.Stream(ctx, stream)
if err != nil {
return 0, err
}
info, err := s.Info(ctx)
if err != nil {
return 0, err
}
c, err := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{DeliverPolicy: jetstream.DeliverByStartTimePolicy,
OptStartTime: &before, AckPolicy: jetstream.AckNonePolicy, InactiveThreshold: time.Minute})
if err != nil {
return 0, err
}
ci, err := c.Info(ctx)
if err != nil {
return 0, err
}
_ = s.DeleteConsumer(ctx, ci.Name)
if info.State.Msgs < ci.NumPending {
return 0, nil
}
return info.State.Msgs - ci.NumPending, nil
}
}
func settingsWords(s keeper.Settings) string {
age := "no age"
if s.MaxAgeSeconds > 0 {
age = "age " + (time.Duration(s.MaxAgeSeconds) * time.Second).String()
}
return fmt.Sprintf("cap %d MiB, %s, history %d, discard %s, lifetime %v", s.MaxBytes/keeper.MiB, age, s.History, s.Discard, s.KeyTTL)
}
// recreateWords says, for each object of the entry, what the rebuild does and removes, read from the entry the keeper made and
// the bus's streams as the monitoring endpoint answers them; and the room its caps need.
func recreateWords(held map[string]keeper.Asked, status func() (keeper.Status, error), jsz []byte, now time.Time, older olderThan,
module, local string) (string, error) {
m, ok := held[module].Made[local]
if !ok || !m.Created {
return "", fmt.Errorf("the bus module made no %s of %s", local, module)
}
streams, err := streamsHeld(jsz)
if err != nil {
return "", err
}
var lines []string
var caps int64
for _, o := range m.Plan.Objects {
caps += o.Settings.MaxBytes
s, found := streams[o.Stream()]
if !found {
lines = append(lines, fmt.Sprintf("%s: the bus holds none, so it is made, holding nothing to remove", o.Stream()))
continue
}
have := keeper.SettingsOf(o.Kind, s.Config)
inPlace := have.WorkQueue == o.Settings.WorkQueue
oldest := "none"
if !s.State.FirstTS.IsZero() && s.State.Messages > 0 {
oldest = s.State.FirstTS.UTC().Format(time.RFC3339)
}
how, removes := "changed in place", []string{}
if !inPlace {
how, removes = "made again empty, its retention changes", []string{fmt.Sprintf("every message (%d)", s.State.Messages)}
} else {
if over := int64(s.State.Bytes) - o.Settings.MaxBytes; over > 0 {
removes = append(removes, fmt.Sprintf("the oldest messages beyond the cap, %d bytes over it", over))
}
if age := o.Settings.MaxAgeSeconds; age > 0 && (have.MaxAgeSeconds == 0 || age < have.MaxAgeSeconds) && s.State.Messages > 0 {
cutoff := now.Add(-time.Duration(age) * time.Second)
switch {
case !s.State.FirstTS.Before(cutoff):
removes = append(removes, "no message older than the age")
case older == nil:
removes = append(removes, "the messages older than the age, not counted here")
default:
n, err := older(o.Stream(), cutoff)
if err != nil {
return "", fmt.Errorf("the messages of %s older than the age cannot be counted: %w", o.Stream(), err)
}
removes = append(removes, fmt.Sprintf("%d messages older than the age", n))
}
}
}
if len(removes) == 0 {
removes = []string{"nothing"}
}
lines = append(lines, fmt.Sprintf("%s %s; held {%s}, asked {%s}; it holds %d messages, %d bytes, the oldest from %s; the change removes: %s",
o.Stream(), how, settingsWords(have), settingsWords(o.Settings), s.State.Messages, s.State.Bytes, oldest, strings.Join(removes, ", ")))
}
room := fmt.Sprintf("The caps it asks sum to %d MiB", caps/keeper.MiB)
if st, err := status(); err == nil && st.Limits.AccountBytes > 0 {
need := caps + keeper.CapSum(held, module, local) + st.OldBytes
room += fmt.Sprintf(", %d MiB with every other cap of the bus, against the account's storage limit of %d MiB", need/keeper.MiB, st.Limits.AccountBytes/keeper.MiB)
}
return room + ". Per object: " + strings.Join(lines, " | "), nil
}
+14 -3
View File
@@ -43,6 +43,9 @@ type requestStore struct {
// Standing reads the router's record of one of this module's asks, by its id, or nil while it holds none (design 47
// H-A-237, H-A-239).
Standing func(askID string) (*stdio.StateEntry, error)
// Explain says what a recreate of the request's entry does to each of its objects and removes, and the room its caps need,
// read when the ask is raised (design 47 H2 H-A-686 (3), H-A-706); nil says none.
Explain func(r keeper.Request) (string, error)
}
// RequestsInState is the store through the runtime that launched this bundle: one watch of the state requests for the
@@ -175,7 +178,7 @@ func askExpiry(a map[string]any) (time.Duration, error) {
// the approve level until a channel carries a destroy answer, ending at the request's AskExpires, the caller's (design
// 47 H-A-237); the bend ends with the research effort that designs the channel carrying the destroy proof (design 47 H2
// §813 (11)).
func askFor(r keeper.Request) (oc.Ask, error) {
func askFor(r keeper.Request, explained string) (oc.Ask, error) {
binds, err := occ.ActDigest(r.Act())
if err != nil {
return oc.Ask{}, err
@@ -187,7 +190,7 @@ func askFor(r keeper.Request) (oc.Ask, error) {
About: keeper.ConditionKey(map[string]string{keeper.VerbDrop: "orphaned", keeper.VerbRecreate: "drifted"}[r.Verb], r.Module, r.Local),
Headline: fmt.Sprintf("%s's kept data %s: %s it?", r.Module, r.Local, what),
Explanation: fmt.Sprintf("%s asks to %s %s on the bus, %s. A snapshot of it is taken first; its data is lost from the bus.",
r.Caller, what, name, r.Why),
r.Caller, what, name, r.Why) + explained,
Options: []oc.Option{
{ID: "go", Label: strings.ToUpper(what[:1]) + what[1:], Does: fmt.Sprintf("%s %s after a snapshot", what, name), Level: occ.Approve, Binds: binds},
{ID: "keep", Label: "Keep it", Does: "nothing is removed", Level: occ.Acknowledge},
@@ -289,7 +292,15 @@ func requestTools(rs requestStore) []stdio.Tool {
return nil, err
}
r.AskExpires = r.At.Add(lasts)
ask, err := askFor(r)
var explained string
if verb == keeper.VerbRecreate && rs.Explain != nil {
words, err := rs.Explain(r)
if err != nil {
return nil, fmt.Errorf("the ask cannot name what the rebuild changes and removes, so nothing is asked: %w", err)
}
explained = " " + words
}
ask, err := askFor(r, explained)
if err != nil {
return nil, err
}
+38 -1
View File
@@ -156,7 +156,7 @@ func TestAPersonsRequestIsHandedToTheKeeperAsTheProvedCaller(t *testing.T) {
func TestTheAskLastsTheCallersExpiryAndTheToolSaysTheRoutersStanding(t *testing.T) {
now := time.Now()
r := keeper.Request{ID: "r1", Verb: keeper.VerbDrop, Module: "m", Local: "drafts", Why: "unused", Caller: "person.jo", AskExpires: now.Add(1430 * time.Minute)}
a, err := askFor(r)
a, err := askFor(r, "")
if err != nil {
t.Fatal(err)
}
@@ -200,3 +200,40 @@ func TestTheAskLastsTheCallersExpiryAndTheToolSaysTheRoutersStanding(t *testing.
}
}
}
// Design 47 H2 H-A-686 (3), H-A-706 (DQ-42): the ask of a recreate names, per object, in place or made empty, what it holds and
// what the change removes (a shorter age's older messages, a smaller cap's bytes over it, every message of a retention change),
// and the room the caps need.
func TestTheAskOfARecreateNamesEachObjectAndWhatItRemoves(t *testing.T) {
now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
hist := keeper.Object{Kind: keeper.KindStream, Name: "m_records", Settings: keeper.Settings{MaxBytes: 4 * keeper.MiB, MaxAgeSeconds: 3600, Discard: keeper.DiscardNew}}
state := keeper.Object{Kind: keeper.KindBucket, Name: "m_records_state", Settings: keeper.Settings{MaxBytes: 8 * keeper.MiB, History: 1, Discard: keeper.DiscardNew}}
queue := keeper.Object{Kind: keeper.KindStream, Name: "m_queue", Settings: keeper.Settings{MaxBytes: 8 * keeper.MiB, Discard: keeper.DiscardNew, WorkQueue: true}}
held := map[string]keeper.Asked{"m": {Module: "m", Made: map[string]keeper.Made{"records": {Created: true,
Plan: keeper.Plan{Module: "m", Local: "records", Objects: []keeper.Object{hist, state, queue}}}}}}
old := now.Add(-3 * time.Hour).Format(time.RFC3339)
jsz := []byte(`{"account_details":[{"stream_detail":[
{"name":"m_records","config":{"name":"m_records","max_bytes":16777216,"max_age":0,"discard":"new"},"state":{"messages":50,"bytes":1048576,"first_ts":"` + old + `"}},
{"name":"KV_m_records_state","config":{"name":"KV_m_records_state","max_bytes":33554432,"max_msgs_per_subject":1,"discard":"new"},"state":{"messages":9,"bytes":12582912,"first_ts":"` + old + `"}},
{"name":"m_queue","config":{"name":"m_queue","max_bytes":8388608,"retention":"limits","discard":"new"},"state":{"messages":7,"bytes":100,"first_ts":"` + old + `"}}]}]}`)
var asked time.Time
words, err := recreateWords(held, func() (keeper.Status, error) {
return keeper.Status{Limits: keeper.Limits{AccountBytes: 100 * keeper.MiB}}, nil
}, jsz, now, func(stream string, before time.Time) (uint64, error) { asked = before; return 42, nil }, "m", "records")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"m_records changed in place", "42 messages older than the age", "50 messages, 1048576 bytes",
"KV_m_records_state changed in place", "4194304 bytes over it", "m_queue made again empty", "every message (7)", "against the account's storage limit of 100 MiB"} {
if !strings.Contains(words, want) {
t.Errorf("the ask does not say %q:\n%s", want, words)
}
}
if !asked.Equal(now.Add(-time.Hour)) {
t.Errorf("the messages were counted before %v", asked)
}
ask, err := askFor(keeper.Request{Verb: keeper.VerbRecreate, Module: "m", Local: "records", Why: "w", Caller: "c", AskExpires: now}, " "+words)
if err != nil || !strings.Contains(ask.Explanation, "42 messages older than the age") {
t.Fatalf("the ask %+v %v", ask, err)
}
}
+12
View File
@@ -154,6 +154,18 @@ func (b JetStream) Update(ctx context.Context, o Object) error {
if o.Settings.History > 0 {
c.MaxMsgsPerSubject = o.Settings.History
}
// The discard, and a lifetime per key or per message turned on; a held one is never turned off, which the bus refuses
// (design 47 H2 H-A-686); a bucket's key lifetime brings its limit marker, as the bucket is made with it.
c.Discard = jetstream.DiscardOld
if o.Settings.Discard == DiscardNew {
c.Discard = jetstream.DiscardNew
}
if o.Settings.KeyTTL {
c.AllowMsgTTL = true
if o.Kind == KindBucket && c.SubjectDeleteMarkerTTL == 0 {
c.SubjectDeleteMarkerTTL = limitMarker(true)
}
}
_, err = b.JS.UpdateStream(ctx, c)
return retryable(err)
}
+1 -1
View File
@@ -312,7 +312,7 @@ func (k *Keeper) capRoom(ctx context.Context, held *Asked, m *Made) error {
sum += o.Settings.MaxBytes
}
if sum > lim.AccountBytes {
return fmt.Errorf("the plan takes the sum of the bus's caps to %d MiB, past the account's storage limit of %d MiB", sum/MiB, lim.AccountBytes/MiB)
return fmt.Errorf("the plan takes the sum of the bus's caps to %d MiB, past the account's storage limit of %d MiB, short by %d MiB", sum/MiB, lim.AccountBytes/MiB, (sum-lim.AccountBytes+MiB-1)/MiB)
}
return nil
}
+71 -2
View File
@@ -110,6 +110,9 @@ func (b *fakeBus) Create(_ context.Context, o Object) error {
func (b *fakeBus) Update(_ context.Context, o Object) error {
b.mu.Lock()
defer b.mu.Unlock()
if err := b.refuse["update "+o.Stream()]; err != nil {
return err
}
b.held[o.Stream()] = o.Settings
b.updated = append(b.updated, o.Stream())
return nil
@@ -1356,8 +1359,8 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) {
raw, _ := json.Marshal(Request{ID: "r8", Verb: VerbRecreate, Module: "m", Local: "findings", Ask: "bus-8"})
_, _ = store.Put(StateRequests, "r8", raw)
k.ActOnRequests()
if fmt.Sprint(bus.deleted) != "[KV_m_findings]" || bus.held["OBJ_m_findings-objects"].MaxBytes != 8*MiB {
t.Errorf("deleted %v, store held %+v: the recreate rebuilds the bucket alone", bus.deleted, bus.held["OBJ_m_findings-objects"])
if fmt.Sprint(bus.updated) != "[KV_m_findings]" || len(bus.deleted) != 0 || bus.held["OBJ_m_findings-objects"].MaxBytes != 8*MiB {
t.Errorf("updated %v, deleted %v, store held %+v: the recreate changes the bucket alone, in place", bus.updated, bus.deleted, bus.held["OBJ_m_findings-objects"])
}
}},
{"a recreate rebuilds a drifted entry after a snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) {
@@ -1378,6 +1381,72 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) {
t.Errorf("held %+v, said %v %v: rebuilt as asked, the drift cleared", bus.held["m_log"], out.events, out.conds)
}
}},
// Design 47 H2 H-A-686, H-A-706 (DQ-42): a held lifetime matches an ask with none; a recreate changes each object in place
// and stops at the bus's refusal, empties nothing and says no recreated; short of room it changes nothing and takes no
// snapshot, the warrant spent.
{"a recreate changes a ledger in place, stops at a refused change, and stops short of room", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) {
if Differs(Settings{MaxBytes: 8, Discard: DiscardNew}, Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}) != "" ||
!Grows(Settings{MaxBytes: 16, Discard: DiscardNew}, Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}) ||
Differs(Settings{MaxBytes: 8, Discard: DiscardNew, KeyTTL: true}, Settings{MaxBytes: 8, Discard: DiscardNew}) == "" {
t.Fatal("a held lifetime does not match an ask with none, or an asked one matches a held none")
}
store := k.Store.(*memStore)
big, small := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}),
entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "8"})
big.Types = []catalogue.LedgerType{{Name: "decision", Indexes: []catalogue.LedgerIndex{{Name: "by-topic", On: []string{"topic"}}}}}
small.Types = big.Types
k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{big}})
k.Heard(Accepted{Module: "m", Revision: 2, BusState: []catalogue.BusStateEntry{small}})
if k.Held()["m"].Made["records"].Drift == "" {
t.Fatal("a smaller cap is no drift")
}
objects := k.Held()["m"].Made["records"].Plan.Objects
recreate := func(id string) Request {
ask := oc.Ask{ID: "bus-" + id, Who: occ.Operator, Expires: occ.FormatTime(k.now().Add(time.Hour)), Options: []oc.Option{{ID: "go", Label: "Rebuild", Level: occ.Destroy,
Binds: func() string {
b, _ := occ.ActDigest(occ.Act{"verb": "recreate", "module": "m", "local": "records"})
return b
}()}}}
w := &oc.Warrant{Ask: ask.ID, Asker: Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator},
Option: "go", Label: "Rebuild", Level: occ.Destroy, At: occ.FormatTime(k.now()), AskDigest: occ.Digest(ask)}
k.Warrant = func(string) (*oc.Ask, *oc.Warrant, error) { return &ask, w, nil }
raw, _ := json.Marshal(Request{ID: id, Verb: VerbRecreate, Module: "m", Local: "records", Ask: ask.ID})
_, _ = store.Put(StateRequests, id, raw)
k.ActOnRequests()
raw, _, _, _ = store.Get(StateRequests, id)
var got Request
_ = json.Unmarshal(raw, &got)
return got
}
// Short of room: the account holds less than the caps ask.
bus.limits = Limits{AccountBytes: 4 * MiB}
out.reset()
snaps := len(bus.snaps)
if got := recreate("r1"); !strings.Contains(got.Error, "short by") || len(bus.updated) != 0 || len(bus.deleted) != 0 || len(bus.snaps) != snaps ||
len(out.events) != 0 {
t.Fatalf("short of room: %q, updated %v, deleted %v, snapshots %d, said %v", got.Error, bus.updated, bus.deleted, len(bus.snaps)-snaps, out.events)
}
if _, _, spent, _ := store.Get(StateSpent, "bus-r1"); !spent {
t.Error("the warrant of a recreate short of room is not spent")
}
// A refused change in place stops it: the first object changed, the second refused, none emptied or changed after.
bus.limits = Limits{}
bus.refuse["update "+objects[1].Stream()] = errors.New("the bus refuses this change")
out.reset()
got := recreate("r2")
if !strings.Contains(got.Error, objects[1].Stream()) || len(bus.deleted) != 0 || fmt.Sprint(bus.updated) != "["+objects[0].Stream()+"]" ||
len(out.events) != 0 || k.Held()["m"].Made["records"].Drift == "" {
t.Fatalf("a refused change: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events)
}
// Without the refusal, a new warrant changes every object in place, keeping what they keep, and says what it held.
delete(bus.refuse, "update "+objects[1].Stream())
out.reset()
bus.updated = nil
if got := recreate("r3"); got.Error != "" || len(bus.deleted) != 0 || len(bus.updated) != len(objects) ||
fmt.Sprint(out.events) != "[recreated m records]" || k.Held()["m"].Made["records"].Drift != "" {
t.Fatalf("the change in place: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events)
}
}},
// Review round 1 (security F2; design 25 § 12.3): a warrant acts once, spent by compare-and-set before anything is
// deleted; a second request naming the same ask is refused and deletes nothing.
{"a warrant acts once", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) {
+11 -2
View File
@@ -440,12 +440,19 @@ func (o options) bool(name string) (bool, error) {
// settings grow by nothing and are no difference (Differs).
func Grows(asked, held Settings) bool {
if asked.Discard != held.Discard || asked.WorkQueue != held.WorkQueue || asked.MaxMsgSize != held.MaxMsgSize ||
asked.DuplicatesSeconds != held.DuplicatesSeconds || asked.KeyTTL != held.KeyTTL {
asked.DuplicatesSeconds != held.DuplicatesSeconds || !lifetimeMatches(asked, held) {
return false
}
return asked.MaxBytes >= held.MaxBytes && longer(asked.MaxAgeSeconds, held.MaxAgeSeconds) && asked.History >= held.History
}
// lifetimeMatches is whether a held lifetime per key (a bucket's) or per message (a stream's) matches the asked one: equal,
// or held while the ask gives none, since allowing a lifetime is no setting a write must use and the bus refuses to turn it
// off in place (design 47 H2 H-A-686 (1)).
func lifetimeMatches(asked, held Settings) bool {
return asked.KeyTTL == held.KeyTTL || held.KeyTTL && !asked.KeyTTL
}
// longer is whether age a keeps at least as long as b, 0 being for ever.
func longer(a, b int64) bool {
if a == 0 {
@@ -469,7 +476,9 @@ func Differs(asked, held Settings) string {
add("work-queue", asked.WorkQueue, held.WorkQueue)
add("max-msg-size", asked.MaxMsgSize, held.MaxMsgSize)
add("duplicates-seconds", asked.DuplicatesSeconds, held.DuplicatesSeconds)
add("key-ttl", asked.KeyTTL, held.KeyTTL)
if !lifetimeMatches(asked, held) {
add("key-ttl", asked.KeyTTL, held.KeyTTL)
}
return strings.Join(out, "; ")
}
+70 -14
View File
@@ -241,6 +241,29 @@ func (k *Keeper) act(r *Request) (string, error) {
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
// A recreate reads each object before anything is changed: whether the bus takes its asked settings in place (all but a
// retention that changes, which it refuses to change), and what it holds now (design 47 H2 H-A-686, H-A-634 (3)).
var steps []rebuild
if r.Verb == VerbRecreate {
for _, o := range m.Plan.Objects {
st, fill, found, err := k.Bus.Held(ctx, o)
if err != nil {
return "nothing done", fmt.Errorf("%s cannot be read, so nothing was changed: %w", o.Stream(), err)
}
steps = append(steps, rebuild{o: o, found: found, inPlace: found && st.WorkQueue == o.Settings.WorkQueue, before: fill})
}
// Short of room for the caps it asks, no object is changed and no snapshot taken; the warrant is spent (H-A-706, DQ-42).
if err := k.capRoom(ctx, &held, &m); err != nil {
if errors.Is(err, ErrRetry) {
return "nothing done", err
}
if serr := k.spend(r); serr != nil {
return "nothing done", serr
}
k.record(r, fmt.Sprintf("recreate of %s of %s refused: %v", r.Local, r.Module, err))
return "nothing done", fmt.Errorf("%s of %s was not rebuilt, no snapshot was taken and no object was changed: %w", r.Local, r.Module, err)
}
}
var streams []string
for _, o := range m.Plan.Objects {
streams = append(streams, o.Stream())
@@ -258,12 +281,12 @@ func (k *Keeper) act(r *Request) (string, error) {
if err := k.spend(r); err != nil {
return "nothing done", err
}
for _, o := range m.Plan.Objects {
if err := k.Bus.Delete(ctx, o); err != nil {
return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err)
}
}
if r.Verb == VerbDrop {
for _, o := range m.Plan.Objects {
if err := k.Bus.Delete(ctx, o); err != nil {
return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err)
}
}
delete(held.Made, r.Local)
k.write(held)
k.emit(EventDropped, m.Plan, held.Revision, r.Why, nil, nil)
@@ -271,13 +294,38 @@ func (k *Keeper) act(r *Request) (string, error) {
k.record(r, fmt.Sprintf("dropped %s of %s on the operator's warrant (snapshot %s)", r.Local, r.Module, path))
return fmt.Sprintf("dropped %s, its snapshot at %s", BusName(r.Module, r.Local), path), nil
}
for _, o := range m.Plan.Objects {
if err := k.Bus.Create(ctx, o); err != nil {
m.Created, m.Refused = false, fmt.Sprintf("%s: %v", o.Stream(), err)
held.Made[r.Local] = m
k.write(held)
return "partly done", fmt.Errorf("%s was removed and could not be made again (its snapshot at %s): %w", o.Stream(), path, err)
// Each object changed in place where the bus takes the asked settings, keeping what they keep; made again empty only one
// whose retention changes. A change the bus refuses stops it: no object made empty, none changed after, the refusal naming
// the object, no recreated, drifted left naming what differs (H-A-686 (2)).
var words []string
for i, st := range steps {
o := st.o
switch {
case st.inPlace:
if err := k.Bus.Update(ctx, o); err != nil {
return "partly done", fmt.Errorf("%s was refused its change in place: %w; the rebuild stopped there: no object was made empty, "+
"none after it was changed, the drift stays, and its snapshot is at %s (%d of %d objects were changed before it)", o.Stream(), err, path, i, len(steps))
}
default:
if st.found {
if err := k.Bus.Delete(ctx, o); err != nil {
return "partly done", fmt.Errorf("%s could not be removed after its snapshot at %s: %w", o.Stream(), path, err)
}
}
if err := k.Bus.Create(ctx, o); err != nil {
m.Created, m.Refused = false, fmt.Sprintf("%s: %v", o.Stream(), err)
held.Made[r.Local] = m
k.write(held)
return "partly done", fmt.Errorf("%s was removed and could not be made again (its snapshot at %s): %w", o.Stream(), path, err)
}
}
_, after, _, _ := k.Bus.Held(ctx, o)
how := "changed in place"
if !st.inPlace {
how = "made again empty"
}
words = append(words, fmt.Sprintf("%s %s: held %d messages, %d bytes before, %d messages, %d bytes after", o.Stream(), how,
st.before.Messages, st.before.Bytes, after.Messages, after.Bytes))
}
wasDrift := m.Drift != ""
m.Drift = ""
@@ -291,12 +339,20 @@ func (k *Keeper) act(r *Request) (string, error) {
m.Said = &said
held.Made[r.Local] = m
k.write(held)
k.emit(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil)
k.emit(EventRecreated, m.Plan, held.Revision, r.Why+" ("+strings.Join(words, "; ")+")", nil, nil)
if wasDrift {
k.clear(conditionDrifted, r.Module, r.Local)
}
k.record(r, fmt.Sprintf("recreated %s of %s on the operator's warrant (snapshot %s)", r.Local, r.Module, path))
return fmt.Sprintf("recreated %s as asked, its old data's snapshot at %s", BusName(r.Module, r.Local), path), nil
k.record(r, fmt.Sprintf("recreated %s of %s on the operator's warrant (snapshot %s): %s", r.Local, r.Module, path, strings.Join(words, "; ")))
return fmt.Sprintf("recreated %s as asked, its old data's snapshot at %s: %s", BusName(r.Module, r.Local), path, strings.Join(words, "; ")), nil
}
// rebuild is one object of a recreate: whether it was found, whether the bus takes its asked settings in place, and what it
// held before.
type rebuild struct {
o Object
found, inPlace bool
before Fill
}
// warranted holds a recreate or a drop to the operator's warrant on the ask its tool raised: chosen by the operator,