diff --git a/checks/failurekit/failurekit.go b/checks/failurekit/failurekit.go index 561138846..5d5f2c871 100644 --- a/checks/failurekit/failurekit.go +++ b/checks/failurekit/failurekit.go @@ -5,7 +5,7 @@ // exempt from that, and said so. Every build module, test step or not, must also hold a test that calls // conformance.LeftRunning with its own start sweep, so a step a previous process left running is ended at its start // (issue 1890), and one that calls conformance.Passing, so a step whose network did not answer is said as a transport fault -// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24). Its manifest asks the capability seat-settle-delay (ADR 0664 §5). +// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24), and one that calls conformance.Reproducible, so its build gives one digest per artifact in any folder (design 47 H2 H-A-591 (4)). Its manifest asks the capability seat-settle-delay (ADR 0664 §5). package failurekit import ( @@ -110,6 +110,16 @@ func Judge(root string) ([]Judged, error) { refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.StepEnds "+ "(mesh-delivery-sdk steprun/conformance): run the kit's step-ends case with the module's own steps (design 47 G §24)", seat)) } + // H-A-591 (4): every build module builds one source at one version to one digest, in any folder and at any time, so every one + // runs the kit's reproducible case over its fixture of each kind it builds. + same, err := runsTheKit(dir, "conformance.Reproducible(") + if err != nil { + return nil, err + } + if !same { + refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.Reproducible "+ + "(mesh-delivery-sdk steprun/conformance): run the kit's case that its build gives one digest per artifact from two folders (design 47 H2 H-A-591)", seat)) + } // Every build module meets the network (a fetch, a download, an install, a publish), so every one runs the passing case: its // steps say a network that did not answer as a transport fault the bus gives the ask again for (ADR 0664, issue 1748). says, err := runsTheKit(dir, "conformance.Passing(") diff --git a/checks/failurekit/failurekit_test.go b/checks/failurekit/failurekit_test.go index 27dad2f4e..1dc1d04c2 100644 --- a/checks/failurekit/failurekit_test.go +++ b/checks/failurekit/failurekit_test.go @@ -8,12 +8,12 @@ import ( // 1901/AC7 and 1890/AC8: a build module with a test step and no kit is refused, one that runs the kit passes, one with no // test step is exempt from the failure cases but not from the left-running case, a module that runs only the failure -// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), and a module that +// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), a module that runs the rest of the kit but not the reproducible case is refused (design 47 H2 H-A-591 (4)), and a module that // claims no node-build-* seat is not judged. func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { root := t.TempDir() const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n" - const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n" + const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n" kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep for path, body := range map[string]string{ "modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`, @@ -33,7 +33,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { "modules/j/module.json": `{"claims":[{"name":"node-build-j"}],"capabilities":["seat-settle-delay"],"tools":["build_j_build"]}`, // the rest of the kit, and no step-ends case "modules/j/cmd/j/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n", "modules/k/module.json": `{"claims":[{"name":"node-build-k"}],"capabilities":["seat-settle-delay"],"tools":["build_k_build"]}`, // no runs-counted case - "modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\n", + "modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n", + "modules/l/module.json": `{"claims":[{"name":"node-build-l"}],"capabilities":["seat-settle-delay"],"tools":["build_l_build"]}`, // the rest of the kit, and no reproducible case + "modules/l/cmd/l/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n", "modules/e/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`, "modules/e/cmd/e/kit.go": kit, // not a test file } { @@ -49,9 +51,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) { if err != nil { t.Fatal(err) } - want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused"} + want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused", "l": "refused"} if len(got) != len(want) { - t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j and k", got) + t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j, k and l", got) } for _, j := range got { is := "passes" diff --git a/modules/distribution/cmd/distribution-tools/contract.go b/modules/distribution/cmd/distribution-tools/contract.go index 6e4e08f1b..50cc8b3af 100644 --- a/modules/distribution/cmd/distribution-tools/contract.go +++ b/modules/distribution/cmd/distribution-tools/contract.go @@ -25,6 +25,10 @@ func publishOf(in reg.PublishInput) holder.PublishRequest { } func publishAnswer(a holder.PublishAnswer) reg.PublishAnswer { + if a.OtherBytes != nil { + // No transfer is opened, so none is named (design 47 H2 H-A-732). + return reg.PublishAnswer{OtherBytes: ®.PublishAnswerOtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}} + } return reg.PublishAnswer{Transfer: a.Transfer, Lacks: a.Missing, Held: a.Ended && len(a.Missing) == 0} } @@ -49,7 +53,11 @@ func versionsAnswer(v *holder.Verbs, kind string, a holder.VersionsAnswer) reg.V // The contract's answer has no field for why; the version is answered with no digest and the reason said here. logf("versions: %s %s on %s answers no digest: %v", a.Name, ver, a.Seat, err) } - out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind}) + fp, err := v.VersionFingerprint(a.Name, ver, d) + if err != nil { + logf("versions: the fingerprint kept for %s %s on %s cannot be read: %v", a.Name, ver, a.Seat, err) + } + out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind, Fingerprint: fp}) } return out } diff --git a/modules/distribution/cmd/distribution-tools/contract_test.go b/modules/distribution/cmd/distribution-tools/contract_test.go index 436ff9566..c8df89af5 100644 --- a/modules/distribution/cmd/distribution-tools/contract_test.go +++ b/modules/distribution/cmd/distribution-tools/contract_test.go @@ -62,18 +62,37 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) { t.Errorf("%s's body %s is not the contract's: %v", event, b, err) } } + // an other-bytes answer carries its digest and fingerprint and names no transfer (H-A-729, H-A-732) + if a := publishAnswer(holder.PublishAnswer{OtherBytes: &holder.OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}); a.Transfer != "" || a.OtherBytes == nil || a.OtherBytes.Digest != "sha256:bb" || a.OtherBytes.Fingerprint != "f1" { + t.Errorf("publish answers %+v for other bytes", a) + } else if b, _ := json.Marshal(a); strings.Contains(string(b), `"transfer"`) { + t.Errorf("the other-bytes answer %s names a transfer", b) + } if a := publishAnswer(holder.PublishAnswer{Transfer: "t", Missing: []string{"sha256:bb"}}); !reflect.DeepEqual(a.Lacks, []string{"sha256:bb"}) || a.Held { t.Errorf("publish answers %+v", a) } // versions answers the digest a reference names (design 47 G A-430a): the blob on the artifact seat, the manifest on the image seat. cat := twoDigests{} for _, c := range []struct{ seat, want string }{{holder.ArtifactSeat, "sha256:blob"}, {holder.ImageSeat, "sha256:manifest"}} { - got := versionsAnswer(&holder.Verbs{Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}) - if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" { - t.Errorf("versions on %s answers %+v, want digest %s", c.seat, got.Versions, c.want) + // and the fingerprint kept for it beside, none where the key names another digest or there is none (H-A-589 (3)) + kept := memKept{holder.FingerprintKey("m/files", "0.1.7"): {Digest: c.want, Fingerprint: "f1"}} + got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}) + if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" || got.Versions[0].Fingerprint != "f1" { + t.Errorf("versions on %s answers %+v, want digest %s, fingerprint f1", c.seat, got.Versions, c.want) + } + kept[holder.FingerprintKey("m/files", "0.1.7")] = holder.Kept{Digest: "sha256:other", Fingerprint: "f1"} + if got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}); got.Versions[0].Fingerprint != "" { + t.Errorf("versions on %s answers fingerprint %q of a key naming another digest", c.seat, got.Versions[0].Fingerprint) } } if r, err := partOf(reg.PublishPartInput{Transfer: "t", Part: "sha256:bb", Data: "aGk=", Last: true}); err != nil || string(r.Data) != "hi" || r.Digest != "sha256:bb" { t.Errorf("publish-part read %+v, %v", r, err) } } + +// memKept is the state fingerprints in memory. +type memKept map[string]holder.Kept + +func (m memKept) Get(k string) (holder.Kept, bool, error) { v, ok := m[k]; return v, ok, nil } +func (m memKept) Put(k string, v holder.Kept) error { m[k] = v; return nil } +func (m memKept) Delete(k string) error { delete(m, k); return nil } diff --git a/modules/distribution/cmd/distribution-tools/main.go b/modules/distribution/cmd/distribution-tools/main.go index a28d28791..288bda11f 100644 --- a/modules/distribution/cmd/distribution-tools/main.go +++ b/modules/distribution/cmd/distribution-tools/main.go @@ -74,6 +74,25 @@ func (k kept[T]) List() ([]T, error) { return out, nil } +// fingerprints is the state fingerprints through the runtime: a write at its cap fails (design 47 H2 H-A-589 (2)). +type fingerprints struct{} + +func (fingerprints) Get(key string) (holder.Kept, bool, error) { + var k holder.Kept + e, err := stdio.State(holder.FingerprintsState).Get(key) + if err != nil || e == nil { + return k, false, err + } + return k, true, json.Unmarshal(e.Value, &k) +} +func (fingerprints) Put(key string, k holder.Kept) error { + _, err := stdio.State(holder.FingerprintsState).Put(key, k) + return err +} +func (fingerprints) Delete(key string) error { + return stdio.State(holder.FingerprintsState).Delete(key) +} + func say(seat, event string, body holder.Event) error { return stdio.SeatPublish("mesh.seat."+seat+".event."+event, eventBody(event, body), body.ID) } @@ -497,7 +516,7 @@ func main() { base, _ := url.Parse("http://127.0.0.1:5001") store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}} h := &holder.Holder{Logf: logf, Objects: boundedObjects{parts.BusObjects(holder.IncomingObjects), busstate.ObjectsOf(holder.IncomingObjects).Purge}, Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: boundedFinding(findings.Say), - Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))} + Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Fingerprints: fingerprints{}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))} files := &holder.Files{Container: or(os.Getenv("MESH_REGISTRY_CONTAINER"), "mesh-registry"), Run: holder.ExecRunner, UID: os.Getuid()} v := &holder.Verbs{Holder: h, Catalog: store, Holds: kept[holder.Hold]{state: "holds", key: holder.Hold.Key}, Mirrors: mirrors{}, Files: files} diff --git a/modules/distribution/internal/holder/holder_test.go b/modules/distribution/internal/holder/holder_test.go index ec051f903..cc1c59c78 100644 --- a/modules/distribution/internal/holder/holder_test.go +++ b/modules/distribution/internal/holder/holder_test.go @@ -215,9 +215,25 @@ func (m memHolds) List() ([]Hold, error) { return out, nil } +// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap. +type memFingerprints struct { + m map[string]Kept + full bool +} + +func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil } +func (f *memFingerprints) Put(k string, v Kept) error { + if f.full { + return errors.New("the bucket is at its cap") + } + f.m[k] = v + return nil +} +func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil } + func newBed(builderOK bool) *bed { b := &bed{store: &fakeStore{has: map[string]bool{}}, findings: map[string]bool{}, now: time.Unix(1000, 0), cat: &fakeCatalog{tags: map[string]string{}}} - b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: fakeBuilder{ok: builderOK}, + b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: fakeBuilder{ok: builderOK}, Store: b.store, Now: func() time.Time { return b.now }, Say: func(seat, event string, body Event) error { b.said = append(b.said, said{seat, event, body}) @@ -353,16 +369,15 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { _, err := b.h.Publish(ArtifactSeat, builder, req("t")) return err }, "the builder did not reserve it"}, - {"a version the store holds at another digest", func(b *bed) error { - b.store.held = map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}} - r := req("t") - r.Digest = "sha256:aa" - _, err := b.h.Publish(ArtifactSeat, builder, r) // the reservation names no digest yet: the bed's builder says yes - if !b.findings["publish-refused m/program@0.1.4"] || len(b.store.put) != 0 { - return errors.New("not refused loudly, or stored") + {"a version stored while the state fingerprints is at its cap", func(b *bed) error { + b.h.Fingerprints.(*memFingerprints).full = true + _, _ = b.h.Publish(ArtifactSeat, builder, req("t")) + _, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "t", Digest: part.Digest, Last: true, Data: blob}) + if len(b.store.put) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused { + return errors.New("stored, or not refused: " + fmt.Sprint(b.said)) } return err - }, "the store holds m/program@0.1.4 at digest sha256:bb, not sha256:aa"}, + }, "fingerprints did not take the key"}, {"an image on the artifact seat", func(b *bed) error { r := req("t") r.Kind = KindImage @@ -424,8 +439,9 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { } other := req("other") other.Digest = digestOf([]byte("other bytes")) - if _, err := b.h.Publish(ArtifactSeat, builder, other); err == nil || !strings.Contains(err.Error(), "at digest "+part.Digest+", not "+other.Digest) { - t.Errorf("other bytes at the held version = %v; want refused naming the held layer %s", err, part.Digest) + // H-A-729, H-A-732: other bytes at the held version are answered, not failed, naming the held layer, and open no transfer. + if a, err := b.h.Publish(ArtifactSeat, builder, other); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != part.Digest || a.Transfer != "" || len(b.said) != 1 { + t.Errorf("other bytes at the held version = %+v, %v; want other-bytes naming the held layer %s, no transfer", a, err, part.Digest) } if len(reg.blobs) != uploads { t.Errorf("the store took %d blobs more; want none", len(reg.blobs)-uploads) @@ -437,6 +453,73 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { t.Errorf("an image held at its manifest = %q, %q, %v; want held", ref, other, err) } }) + // H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered by the fingerprint the holder keeps for it. + t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) { + held := map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}} + offer := func(b *bed, fp string) PublishRequest { + r := req("t") + r.Digest, r.Fingerprint = "sha256:aa", fp + b.store.held = held + return r + } + keep := func(b *bed, fp string) { + _ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4"), Kept{Digest: "sha256:bb", Fingerprint: fp}) + } + for _, c := range []struct { + name string + kept, offer string // the fingerprint kept (none when empty or noKey), the one offered + noKey bool + want *OtherBytes + }{ + {name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}, + {name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}, + {name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", want: &OtherBytes{Digest: "sha256:bb"}}, + {name: "no fingerprint offered is other-bytes", kept: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}, + } { + b := newBed(true) + r := offer(b, c.offer) + if !c.noKey { + keep(b, c.kept) + } + a, err := b.h.Publish(ArtifactSeat, builder, r) + if err != nil || !reflect.DeepEqual(a.OtherBytes, c.want) || a.Transfer != "" || a.Ended || len(b.store.put) != 0 || len(a.Missing) != 0 || len(b.h.Transfers.(memTransfers)) != 0 || len(b.said) != 0 { + t.Errorf("%s: answered %+v, %v; stored %d, transfers %d, said %+v", c.name, a, err, len(b.store.put), len(b.h.Transfers.(memTransfers)), b.said) + } + // the ask given again reads the same state afresh and answers the same + if a2, err := b.h.Repeat(ArtifactSeat, builder, r); err != nil || !reflect.DeepEqual(a2.OtherBytes, c.want) { + t.Errorf("%s: repeated ask answered %+v, %v", c.name, a2, err) + } + } + // the key is written when the version is stored, read by versions, and deleted at removed + b := newBed(true) + r := req("k") + r.Fingerprint = "f9" + if _, err := b.h.Publish(ArtifactSeat, builder, r); err != nil { + t.Fatal(err) + } + if _, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "k", Digest: part.Digest, Last: true, Data: blob}); err != nil { + t.Fatal(err) + } + if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4")); !ok || k != (Kept{Digest: part.Digest, Fingerprint: "f9"}) { + t.Errorf("the key after the store = %+v, %v", k, ok) + } + if fp, err := b.v.VersionFingerprint("m/program", "0.1.4", part.Digest); err != nil || fp != "f9" { + t.Errorf("versions answers fingerprint %q, %v", fp, err) + } + if fp, _ := b.v.VersionFingerprint("m/program", "0.1.4", "sha256:other"); fp != "" { + t.Errorf("a key naming another digest than the held one answered %q", fp) + } + b.cat.tags = map[string]string{"m/program:0.1.4-b": part.Digest} + r2 := req("k") + r2.Version = "0.1.4-b" + _ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4-b"), Kept{Digest: part.Digest, Fingerprint: "f9"}) + if _, err := b.v.Remove(ArtifactSeat, "novox.mesh-delivery-builder", RemoveRequest{Name: "m/program", Version: "0.1.4-b", Reason: "branch ended"}); err != nil { + t.Fatal(err) + } + if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4-b")); ok { + t.Errorf("the key stayed after removed") + } + }) t.Run("only the missing layers are sent, and an idle transfer is dropped", func(t *testing.T) { b := newBed(true) other := []byte("layer two") @@ -750,13 +833,24 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { b := newBed(true) return publishconformance.Bed{ Hold: func(d string) { b.store.has[d] = true }, - Publish: func(name, version, digest string) publishconformance.Outcome { - got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"}) - o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err} - if len(b.said) > 0 { - o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason + // the holder holds the version at digest d, keeping fingerprint fp for it + HoldWith: func(d, fp string) { + b.store.held = map[string]heldAt{publishconformance.Name + "@" + publishconformance.Version: {manifest: d, layer: d}} + b.store.has[d] = true + if fp != "" { + _ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp}) } - return o + }, + Held: func(name, version string) (string, string) { + at := b.store.held[name+"@"+version] + fp, _ := b.v.VersionFingerprint(name, version, at.layer) + return at.layer, fp + }, + Publish: func(name, version, digest string) publishconformance.Outcome { + return publish(b, name, version, digest, "") + }, + PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome { + return publish(b, name, version, digest, fingerprint) }} }) }) @@ -1003,9 +1097,14 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { if m.Class != "core" { t.Errorf("class %q, want core", m.Class) } + // The state fingerprints names its own cap, 16 MiB (H-A-589 (2)). for _, st := range m.State { - if st.MaxMiB != 8 { - t.Errorf("the state %s names max-mib %d, want 8", st.Name, st.MaxMiB) + want := 8 + if st.Name == FingerprintsState { + want = 16 + } + if st.MaxMiB != want { + t.Errorf("the state %s names max-mib %d, want %d", st.Name, st.MaxMiB, want) } } // The reservation is asked through the seat mesh-builds, so the manifest takes no package of the builder (design 47 §381). @@ -1116,3 +1215,17 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) { // registryForms reads a reference of the registry form, with the two seats' names this holder answers for. var registryForms = artifactref.Seats{Image: ImageSeat, Object: ArtifactSeat} + +// publish is a no-parts publish of a bundle through the holder as the publish conformance kit makes it, with the outcome the +// kit reads. +func publish(b *bed, name, version, digest, fingerprint string) publishconformance.Outcome { + got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Fingerprint: fingerprint, Transfer: "t"}) + o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err} + if got.OtherBytes != nil { + o.Other = &publishconformance.OtherBytes{Digest: got.OtherBytes.Digest, Fingerprint: got.OtherBytes.Fingerprint} + } + if len(b.said) > 0 { + o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason + } + return o +} diff --git a/modules/distribution/internal/holder/transfer.go b/modules/distribution/internal/holder/transfer.go index 4114ae5e3..2b95eafa4 100644 --- a/modules/distribution/internal/holder/transfer.go +++ b/modules/distribution/internal/holder/transfer.go @@ -11,6 +11,7 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts" + keyparts "git.novox.be/novox/mesh-sdk/go/keys" ) // The bounds of incoming (design 51 *Publishing*, ADR 0611): a part is at most 1 MiB, a transfer with no part for 24 @@ -25,6 +26,9 @@ const ( // IncomingObjects and TransfersState are the object store and the state distribution asks as bus state. IncomingObjects = "incoming" TransfersState = "transfers" + // FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published + // with (design 47 H2 H-A-589 (2)). + FingerprintsState = "fingerprints" // IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): the // bus's marker of its end is the event that drops a transfer left with no part for TransferIdle (ADR 0611 §3), never // a timer. @@ -68,6 +72,36 @@ type PublishAnswer struct { Missing []string `json:"missing"` // Ended says the publish ended at once: everything was held, `published` or `refused` is said. Ended bool `json:"ended,omitempty"` + // OtherBytes is set when the holder holds the publish's name and version with another digest and keeps another + // fingerprint for it, or none: the call does not fail, and no transfer is opened (design 47 H2 H-A-729, H-A-732). + OtherBytes *OtherBytes `json:"other_bytes,omitempty"` +} + +// OtherBytes is the digest a holder holds for a name and version, and the fingerprint it keeps for them, empty where it +// keeps none. +type OtherBytes struct { + Digest string `json:"digest"` + Fingerprint string `json:"fingerprint,omitempty"` +} + +// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named. +type Kept struct { + Digest string `json:"digest"` + Fingerprint string `json:"fingerprint,omitempty"` +} + +// FingerprintKey is the key of name at version in the state fingerprints: `.`, each token escaped as a key's +// name is (design 47 H2 H-A-589 (2)). +func FingerprintKey(name, version string) string { + return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version) +} + +// FingerprintState is distribution's own state fingerprints (bus state, template state; ADR 0595), reached by the holder +// alone; a write at its cap fails. +type FingerprintState interface { + Get(key string) (Kept, bool, error) + Put(key string, k Kept) error + Delete(key string) error } // PartRequest is the body of `publish-part` (ADR 0611 §2): one chunk of one part. @@ -165,11 +199,13 @@ type Finding func(kind, subject, words string, raised bool) type Holder struct { Objects Objects Transfers TransferState - Builder Builder - Store Store - Say Say - Finding Finding - Now func() time.Time + // Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)). + Fingerprints FingerprintState + Builder Builder + Store Store + Say Say + Finding Finding + Now func() time.Time // Cap reads incoming's cap from its binding (parts.BusCap); IncomingCap when nil or when the binding names none. Cap func() (uint64, error) // Record records a hand act through the seat mesh-hand-acts (meshhandactsclient.Recorder); a drop by hand is refused @@ -229,10 +265,15 @@ func (h *Holder) receiver() *parts.Receiver[Opening] { return nil }, Store: func(t Transfer, held map[string][]byte) error { + if err := h.keep(t.Shape.PublishRequest); err != nil { + reason := err.Error() + return errors.Join(errors.New("refused: "+reason), h.refused(t, reason)) + } path, err := h.Store.Put(t.Shape.PublishRequest, held) ref := SeatReference(t.Shape.Seat, path) if err != nil { reason := "the store did not take it: " + err.Error() + h.unkeep(t.Shape.PublishRequest) return errors.Join(errors.New("refused: "+reason), h.refused(t, reason)) } h.Finding("publish-refused", t.Shape.Name+"@"+t.Shape.Version, "", false) @@ -276,10 +317,9 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer, if err != nil { return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err) } else if other != "" { - // A second publish of a held version with another digest is refused before the reservation is asked, as the forge - // holds the first (A-490j, H-A-393): while the reserved digest is still empty it would pass, and the store's Put - // would move the version's tag. - return h.refusePublish(seat, r, fmt.Sprintf("the store holds %s@%s at digest %s, not %s", r.Name, r.Version, other, r.Digest)) + // The version is held at another digest: answered with the held digest and the fingerprint kept for it, nothing + // stored, no transfer opened (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). + return h.heldElsewhere(r, other) } else if ref != "" { return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.timed("the published event on the seat", func() error { return h.Say(seat, EventPublished, h.eventOf(seat, r, SeatReference(seat, ref), "")) @@ -304,6 +344,60 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer, return answerOf(got), nil } +// keptFor is the fingerprint the holder keeps for name at version, empty when it keeps none; a key naming another digest +// than the one the store holds speaks for nothing. +func (h *Holder) keptFor(r PublishRequest, held string) (string, error) { + k, found, err := h.Fingerprints.Get(FingerprintKey(r.Name, r.Version)) + if err != nil { + return "", fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", r.Name, r.Version, err) + } + if !found || k.Digest != held { + return "", nil + } + return k.Fingerprint, nil +} + +// heldElsewhere answers a publish of a version the store holds at the digest other, not the publish's: other-bytes, the held +// digest and the fingerprint kept for it, the call not failing, nothing stored and no transfer opened. The reader compares the +// kept fingerprint with the publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both +// fingerprints. +func (h *Holder) heldElsewhere(r PublishRequest, other string) (PublishAnswer, error) { + kept, err := h.keptFor(r, other) + if err != nil { + return PublishAnswer{}, err + } + h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", r.Name, r.Version, other, kept, r.Digest, r.Fingerprint) + return PublishAnswer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil +} + +// keep writes the key of a version about to be stored; a write the state refuses (at its cap) is the publish's refusal, so +// nothing is stored. A publish with no version keeps none. +func (h *Holder) keep(r PublishRequest) error { + if r.Version == "" { + return nil + } + if err := h.Fingerprints.Put(FingerprintKey(r.Name, r.Version), Kept{Digest: r.Digest, Fingerprint: r.Fingerprint}); err != nil { + return fmt.Errorf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %w", FingerprintsState, r.Name, r.Version, err) + } + return nil +} + +// unkeep deletes the key keep wrote when the store did not take the version. +func (h *Holder) unkeep(r PublishRequest) { + if r.Version == "" { + return + } + if err := h.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil { + h.logf("publish: the key of %s@%s stays in the state %s: %v", r.Name, r.Version, FingerprintsState, err) + } +} + +func (h *Holder) logf(format string, a ...any) { + if h.Logf != nil { + h.Logf(format, a...) + } +} + // refusePublish ends a publish refused before anything is stored: its finding raised, refused said on the seat, the reason // answered. func (h *Holder) refusePublish(seat string, r PublishRequest, reason string) (PublishAnswer, error) { @@ -338,6 +432,9 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) { if !ok { return refuse("the builder did not reserve it: " + why) } + if err := h.keep(r); err != nil { + return refuse(err.Error()) + } tag := r tag.Parts = []Part{{Digest: r.Digest}} var path string @@ -345,6 +442,7 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) { path, err = h.Store.Put(tag, map[string][]byte{}) return err }); err != nil { + h.unkeep(r) return refuse("the store did not tag it: " + err.Error()) } h.Finding("publish-refused", r.Name+"@"+r.Version, "", false) @@ -416,15 +514,18 @@ func (h *Holder) Repeat(seat, caller string, r PublishRequest) (PublishAnswer, e return PublishAnswer{}, err } if r.Version != "" { - var ref string + var ref, other string err := h.timed("the store's read of what it holds (the program's registry)", func() (err error) { - ref, _, err = h.Store.Held(r) + ref, other, err = h.Store.Held(r) return err }) if err != nil { return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err) } else if ref != "" { return PublishAnswer{Transfer: r.Transfer, Ended: true}, nil + } else if other != "" { + // The act's state as it stands: held at another digest, answered as the act answered it, saying nothing again. + return h.heldElsewhere(r, other) } } t, found, err := h.Transfers.Get(r.Transfer) diff --git a/modules/distribution/internal/holder/verbs.go b/modules/distribution/internal/holder/verbs.go index 0edb6caa4..cf206e917 100644 --- a/modules/distribution/internal/holder/verbs.go +++ b/modules/distribution/internal/holder/verbs.go @@ -201,6 +201,9 @@ func (v *Verbs) Remove(seat, caller string, r RemoveRequest) (Removal, error) { } } ev.Digest = d // a version already gone is said removed all the same, so the builder's retry ends + if err := v.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil { + return Removal{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", r.Name, r.Version, FingerprintsState, err) + } } return Removal{Removed: true}, v.Say(seat, EventRemoved, ev) } @@ -450,3 +453,13 @@ func (v *Verbs) HeldNow() ([]Hold, error) { slices.SortFunc(all, func(a, b Hold) int { return strings.Compare(a.Key(), b.Key()) }) return all, nil } + +// VersionFingerprint is the fingerprint kept for name at version when the key names the digest the store holds there, empty +// where none is kept (`versions`, design 47 H2 H-A-589 (3)). +func (v *Verbs) VersionFingerprint(name, version, digest string) (string, error) { + k, found, err := v.Fingerprints.Get(FingerprintKey(name, version)) + if err != nil || !found || k.Digest != digest { + return "", err + } + return k.Fingerprint, nil +} diff --git a/modules/distribution/module.json b/modules/distribution/module.json index 54d97d94d..5ec49763a 100644 --- a/modules/distribution/module.json +++ b/modules/distribution/module.json @@ -255,6 +255,10 @@ "name": "transfers", "max-mib": 8 }, + { + "name": "fingerprints", + "max-mib": 16 + }, { "name": "idle", "key-ttl": true, diff --git a/modules/gitea/README.md b/modules/gitea/README.md index 321c54e1f..2da6d395a 100644 --- a/modules/gitea/README.md +++ b/modules/gitea/README.md @@ -72,8 +72,9 @@ Approve names. **A patch too large to type** (novox/hq issue 852: a feature's diff is megabytes) goes as `patch_file`, with `patch_sha256`. The caller writes the patch into the module's spool directory `forge-patches` -(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account, which the tools run as: anyone writes, -nobody lists; the bundle is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME, +(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account: anyone writes, nobody lists, and the +tools, which run as the module's own account gitea, read and remove the named file as any other account may; the bundle +is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME, 32 to 64 characters of `0-9a-f` that the caller chooses at random, never a path. The tool then reads that one file, applies it exactly as it applies `patch` (same size limit, same answer) and removes it once it has found it, whether the commit was made or not. A file refused before that (a bad name, a missing hash or spool directory, a name with no diff --git a/modules/gitea/calls.ts b/modules/gitea/calls.ts index d4b4e40c9..f94891b57 100644 --- a/modules/gitea/calls.ts +++ b/modules/gitea/calls.ts @@ -79,7 +79,7 @@ export type Say = (subject: string, body: unknown, id?: string) => Promise /** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its * refused ones; undefined for a call that landed no member, which says none. A member merged plainly, carrying the note - * no delivery (its repository has no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */ + * no delivery (its base is no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */ export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined { const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note); if (landed.length === 0) return undefined; diff --git a/modules/gitea/catalog.ts b/modules/gitea/catalog.ts index b02664536..eee2af55e 100644 --- a/modules/gitea/catalog.ts +++ b/modules/gitea/catalog.ts @@ -127,20 +127,7 @@ export class CatalogView { /** The kind of a finding of a first view unanswered past its bound (ADR 0615 §6), as mesh-sdk's Go views writes it. */ export const UNANSWERED_KIND = "first-view-unanswered"; -/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */ -export function findingKey(scope: string, id: string, kind: string): string { - return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join("."); -} - -/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */ -export function findingValue(f: Finding): { key: string; value: Record } { - const key = findingKey("module", f.id, f.kind); - return { key, value: { - v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline, - explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`, - observer: f.observer, at: f.at, - } }; -} +export { findingKey, findingValue } from "./findings.js"; /** A part's finding of a first view unanswered past its bound, from the follower's status. */ export function unansweredFinding(part: string, s: Status, at: Date): Finding { diff --git a/modules/gitea/cmd/forge/forge_test.go b/modules/gitea/cmd/forge/forge_test.go index 1113d946b..a1f320dd2 100644 --- a/modules/gitea/cmd/forge/forge_test.go +++ b/modules/gitea/cmd/forge/forge_test.go @@ -694,13 +694,6 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) { "cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"}, "cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_USER"}, } - // H-A-564: until gitea runs as its own account, each Go bundle is handed the token files gitea's TypeScript bundle - // keeps under its state directory, read when the vault refuses the caller's account. - files := map[string]map[string]string{ - "cmd/forge": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token"}, - "cmd/package-registry": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token", - "MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token"}, - } for _, a := range m.Build.Artifacts { want, ok := wants[a.From] if !ok { @@ -720,9 +713,10 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) { t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k) } } + // H-A-575: the vault alone hands a token; no bundle is given a token file. for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} { - if a.Env[k] != files[a.From][k] { - t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][k]) + if a.Env[k] != "" { + t.Errorf("%s is given %s %q: a token is read from the vault alone (H-A-575)", a.From, k, a.Env[k]) } } } diff --git a/modules/gitea/cmd/forge/patchfile.go b/modules/gitea/cmd/forge/patchfile.go index ba040f916..0a4b0fa7c 100644 --- a/modules/gitea/cmd/forge/patchfile.go +++ b/modules/gitea/cmd/forge/patchfile.go @@ -15,7 +15,7 @@ import ( // A patch too large to type into a call is handed over as a file (novox/hq issue 852). The caller writes it into // one spool directory the module declares (mode 0733: anyone writes, nobody lists) and names it in patch_file, -// with the file's SHA-256. The tool runs as the machine's account, so it reads nothing but that directory: the +// with the file's SHA-256. The tool runs as the module's own account gitea, and reads nothing but that directory: the // name is 32 to 64 characters of [0-9a-f], so it holds no separator and no dot; the file must be a regular file // (never a symlink); and its hash must be the caller's, because without the sticky bit another writer could have // replaced it. The file is removed once taken, whether the commit was made or not. diff --git a/modules/gitea/cmd/package-registry/retention.go b/modules/gitea/cmd/package-registry/retention.go index d0a162051..394b2b0b9 100644 --- a/modules/gitea/cmd/package-registry/retention.go +++ b/modules/gitea/cmd/package-registry/retention.go @@ -452,6 +452,10 @@ func retention(ctx context.Context, f *Forge, only string, keep int, dryRun bool } else { o.Module = c.Package } + // The key kept for the version goes with it (design 47 H2 H-A-589 (2)). + if err := unkept(c.Package, o.Version); err != nil { + s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its key in the state %s is not: %v", c.Package, c.Version, packageseats.FingerprintsState, err)) + } if err := say(seat, packageseats.EventRemoved, o); err != nil { s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its removed could not be said: %v", c.Package, c.Version, err)) } diff --git a/modules/gitea/cmd/package-registry/retention_test.go b/modules/gitea/cmd/package-registry/retention_test.go index 9dd5ee5cd..c41c33a36 100644 --- a/modules/gitea/cmd/package-registry/retention_test.go +++ b/modules/gitea/cmd/package-registry/retention_test.go @@ -281,8 +281,18 @@ func TestARealRunWithoutWhyIsRefusedBeforeAnythingIsRead(t *testing.T) { } } +// init: no test of retention reaches the runtime's state `fingerprints`, whose call waits for a runtime a test has none of; a +// test that reads what retention deletes there sets its own hook. +func init() { unkept = func(string, string) error { return nil } } + func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) { f := aRegistry(t) + // the key kept for each version goes with it (design 47 H2 H-A-589 (2)) + var unkeys []string + unkept = func(name, version string) error { + unkeys = append(unkeys, packageseats.FingerprintKey(name, version)) + return nil + } var removed []string say = func(seat, event string, o packageseats.Outcome) error { removed = append(removed, seat+" "+event+" "+o.Name+"@"+o.Version+" "+o.Reason) @@ -303,6 +313,9 @@ func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) { if len(p.Deleted) != 4 || len(p.Refused) != 0 { t.Fatalf("answered %v / %v", p.Deleted, p.Refused) } + if sort.Strings(unkeys); len(unkeys) != 4 || unkeys[0] != packageseats.FingerprintKey("@acme/sdk", "0.1.1") { + t.Errorf("keys deleted %v, want one per deleted version", unkeys) + } } // TestAVersionAGoModRequiresSurvivesGoRetention: the Go seat keeps what the npm seat keeps (design 51 *Retention*): a @@ -480,8 +493,8 @@ func TestToolsAreTheOnesTheReadmeNamesAndSayWhatTheyDo(t *testing.T) { Objects any `json:"objects"` State any `json:"state"` }{m.Objects, m.State}) - // Each with its cap (design 47 H2 §812, H-A-411 (2)). - for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`} { + // Each with its cap (design 47 H2 §812, H-A-411 (2)); the state fingerprints names its own, 16 MiB (H-A-589 (2)). + for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`, `"max-mib":16,"name":"fingerprints"`} { if !strings.Contains(string(req), want) { t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req) } diff --git a/modules/gitea/cmd/package-registry/seats.go b/modules/gitea/cmd/package-registry/seats.go index 63ddb1f49..0d0233bf9 100644 --- a/modules/gitea/cmd/package-registry/seats.go +++ b/modules/gitea/cmd/package-registry/seats.go @@ -22,6 +22,7 @@ import ( "io" "net/http" "net/url" + "os" "path" "strings" @@ -227,6 +228,30 @@ func outcomeBody(o packageseats.Outcome) map[string]any { "reference": o.Reference, "reason": o.Reason, "module": o.Module} } +// fingerprintsState is the state fingerprints through the runtime; a write at its cap fails (design 47 H2 H-A-589 (2)). +type fingerprintsState struct{} + +func (fingerprintsState) Get(key string) (packageseats.Kept, bool, error) { + var k packageseats.Kept + e, err := stdio.State(packageseats.FingerprintsState).Get(key) + if err != nil || e == nil { + return k, false, err + } + return k, true, json.Unmarshal(e.Value, &k) +} +func (fingerprintsState) Put(key string, k packageseats.Kept) error { + _, err := stdio.State(packageseats.FingerprintsState).Put(key, k) + return err +} +func (fingerprintsState) Delete(key string) error { + return stdio.State(packageseats.FingerprintsState).Delete(key) +} + +// unkept deletes the key kept for name at version, as retention removes the version itself; a test replaces it. +var unkept = func(name, version string) error { + return fingerprintsState{}.Delete(packageseats.FingerprintKey(name, version)) +} + // say says a seat's event; a test hears it instead. var say = sayOn @@ -257,8 +282,9 @@ var boundCap = parts.BusCap(packageseats.IncomingObjects) // busHolder is the holder over the runtime's bus state, the builder's reservation and the forge. func busHolder(forge func() (*Forge, error)) (*packageseats.Holder, error) { return &packageseats.Holder{Objects: parts.BusObjects(packageseats.IncomingObjects), - Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState), - Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say, + Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState), + Fingerprints: fingerprintsState{}, Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) }, + Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say, Cap: boundCap, Record: recordAct, Idle: parts.BusArm(packageseats.IdleState)}, nil } @@ -302,6 +328,15 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func() return nil, err } a, err := h.Publish(seat, stdio.CallerOf(args), p) + if a.OtherBytes != nil { + // No transfer is opened, so none is named (design 47 H2 H-A-732). + other := map[string]any{"digest": a.OtherBytes.Digest} + if a.OtherBytes.Fingerprint != "" { + other["fingerprint"] = a.OtherBytes.Fingerprint + } + out, _ := as[PA](map[string]any{"other-bytes": other}) + return out, err + } out, _ := as[PA](map[string]any{"transfer": a.Transfer, "lacks": a.Lacks, "held": a.Ended && len(a.Lacks) == 0}) return out, err })}, @@ -325,7 +360,7 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func() return out, err })}, {Name: seat + "." + packageseats.VerbVersions, Input: obj, - Description: "The versions the seat holds of one package, newest first, each with its digest.", + Description: "The versions the seat holds of one package, newest first, each with its digest and the fingerprint kept for it where one is kept.", Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) { in, err := as[VI](args) if err != nil { @@ -338,7 +373,11 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func() } list := []map[string]any{} for _, v := range got { - list = append(list, map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage}) + entry := map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage} + if v.Fingerprint != "" { + entry["fingerprint"] = v.Fingerprint + } + list = append(list, entry) } return as[VA](map[string]any{"name": q.Name, "versions": list}) })}, diff --git a/modules/gitea/cmd/package-registry/seats_test.go b/modules/gitea/cmd/package-registry/seats_test.go index 5d30aff98..472024bd2 100644 --- a/modules/gitea/cmd/package-registry/seats_test.go +++ b/modules/gitea/cmd/package-registry/seats_test.go @@ -9,6 +9,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -229,3 +230,44 @@ func vaultHolding(t *testing.T, account string, held map[string]string) *forgeht } return v } + +// otherStore is a forge registry holding name@version at one digest. +type otherStore struct{ digest string } + +func (s otherStore) Held(string, string, string) (string, bool, error) { return s.digest, true, nil } +func (otherStore) Put(string, packageseats.Publish, []byte) (string, error) { + return "", errors.New("stored") +} +func (otherStore) Versions(string, string) ([]packageseats.Version, error) { return nil, nil } +func (otherStore) Remove(string, string, string) error { return nil } + +type keptState map[string]packageseats.Kept + +func (k keptState) Get(key string) (packageseats.Kept, bool, error) { + v, ok := k[key] + return v, ok, nil +} +func (k keptState) Put(key string, v packageseats.Kept) error { k[key] = v; return nil } +func (k keptState) Delete(key string) error { delete(k, key); return nil } + +// A publish of a version the forge holds at another digest is answered with other-bytes, the held digest and the fingerprint +// kept, in each seat's contract, and the answer names no transfer, as no transfer is opened (design 47 H2 H-A-729, H-A-732). +func TestAPublishOfAHeldVersionIsAnsweredOtherBytesWithNoTransfer(t *testing.T) { + h := &packageseats.Holder{Store: otherStore{digest: "sha256:aa"}, Fingerprints: keptState{ + packageseats.FingerprintKey("sdk", "0.1.15"): {Digest: "sha256:aa", Fingerprint: "f1"}}} + for _, seat := range []string{packageseats.NpmSeat, packageseats.GoSeat} { + for _, tool := range SeatTools(func() (*packageseats.Holder, error) { return h, nil }) { + if tool.Name != seat+".publish" { + continue + } + got, err := tool.Run(map[string]any{"name": "sdk", "version": "0.1.15", "kind": "package", "digest": "sha256:bb", "transfer": "t1"}) + if err != nil { + t.Fatalf("%s: %v", seat, err) + } + raw, _ := json.Marshal(got) + if !strings.Contains(string(raw), `"other-bytes":{"digest":"sha256:aa","fingerprint":"f1"}`) || strings.Contains(string(raw), `"transfer"`) { + t.Errorf("%s: publish answered %s, want other-bytes with the held digest and kept fingerprint and no transfer", seat, raw) + } + } + } +} diff --git a/modules/gitea/cmd/package-registry/whole_integration_test.go b/modules/gitea/cmd/package-registry/whole_integration_test.go index 1f4f511f4..2f1271e4e 100644 --- a/modules/gitea/cmd/package-registry/whole_integration_test.go +++ b/modules/gitea/cmd/package-registry/whole_integration_test.go @@ -367,7 +367,7 @@ func TestThePackageSeatsWhole(t *testing.T) { } t.Cleanup(nc.Close) js, _ := jetstream.New(nc) - for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings"} { + for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings", "gitea_" + packageseats.FingerprintsState} { if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b}); err != nil { t.Fatal(err) } @@ -482,6 +482,11 @@ func TestThePackageSeatsWhole(t *testing.T) { if !bytes.Equal(up, zipped) { t.Errorf("the forge took %d bytes, not the %d published", len(up), len(zipped)) } + // The key of the stored version is kept in the state fingerprints (design 47 H2 H-A-589 (2)). + fingerprints, _ := js.KeyValue(ctx, "gitea_"+packageseats.FingerprintsState) + if e, err := fingerprints.Get(ctx, packageseats.FingerprintKey("git.example/acme/sdk", "0.1.15")); err != nil || !strings.Contains(string(e.Value()), digest) { + t.Errorf("the stored version's key in the state fingerprints: %v", err) + } transfers, _ := js.KeyValue(ctx, "gitea_"+packageseats.TransfersState) if keys, _ := transfers.Keys(ctx); len(keys) != 0 { t.Errorf("an ended transfer is still kept: %v", keys) diff --git a/modules/gitea/findings.ts b/modules/gitea/findings.ts new file mode 100644 index 000000000..b9fd41b06 --- /dev/null +++ b/modules/gitea/findings.ts @@ -0,0 +1,19 @@ +// The key and the value of a finding a part writes into its own state `findings`, as the condition keeper reads it +// (kept apart from catalog.ts, which loads the catalog seat's contract, so a part that only writes a finding loads nothing else). + +import type { Finding } from "@novox/mesh-sdk/views"; + +/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */ +export function findingKey(scope: string, id: string, kind: string): string { + return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join("."); +} + +/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */ +export function findingValue(f: Finding): { key: string; value: Record } { + const key = findingKey("module", f.id, f.kind); + return { key, value: { + v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline, + explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`, + observer: f.observer, at: f.at, + } }; +} diff --git a/modules/gitea/internal/forgehttp/vault.go b/modules/gitea/internal/forgehttp/vault.go index 3ed8dbeff..a78552200 100644 --- a/modules/gitea/internal/forgehttp/vault.go +++ b/modules/gitea/internal/forgehttp/vault.go @@ -5,18 +5,13 @@ package forgehttp // through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at // each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it. // -// Until gitea runs as its own account (H-A-543), the vault refuses the tool runner's account these bundles are called -// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript -// bundle keeps it in under its state directory (MESH_GITEA_TOKEN_FILE for the tools' account, -// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, each with its scopes line beside it), and Follow says once -// at start which source each token came from. The fallback ends with H-A-543's delivery. +// Gitea runs as its own account, so the vault hands these bundles its own secrets; no file stands in for the vault +// (H-A-575: the stand-in of H-A-564 ended with H-A-543's delivery). import ( "encoding/json" "errors" "fmt" - "os" - "path/filepath" "strings" "sync" @@ -36,41 +31,15 @@ func VaultName(account string) string { return "module/gitea/" + account } // Ask asks one seat verb and answers its reply (stdio.Ask). type Ask func(address string, args any) (json.RawMessage, error) -// Refusals are what the vault answers when it refuses the caller's account a module's own secret (mesh-vault's -// callerModule and its own-secret judgement): the only answers the token file is read after (H-A-564). -var Refusals = []string{"is no module's account", "handed only to an account of"} - -// refused is whether err is the vault refusing the caller's account. -func refused(err error) bool { - for _, r := range Refusals { - if strings.Contains(err.Error(), r) { - return true - } - } - return false -} - -// Sources of a token: the vault, or the file gitea's TypeScript bundle keeps (H-A-564). -const ( - SourceVault = "the vault" - SourceFile = "the file gitea keeps" -) - -// VaultToken is one account's token as this process holds it, read from the vault, or from File when the vault -// refuses the caller's account (H-A-564). +// VaultToken is one account's token as this process holds it, read from the vault alone. type VaultToken struct { Account string - // File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none. - File string - // FileByDefault says File is DefaultStateDir's, the manifest naming none. - FileByDefault bool - ask Ask - keys seal.KeyPair + ask Ask + keys seal.KeyPair mu sync.Mutex token string generation int - source string } // NewVaultToken is an account's token read through ask, sealed to a key made for this process. @@ -82,20 +51,10 @@ func NewVaultToken(account string, ask Ask) (*VaultToken, error) { return &VaultToken{Account: account, ask: ask, keys: keys}, nil } -// Load reads the account's token from the vault again; from File when the vault refuses the caller's account. +// Load reads the account's token from the vault again. func (t *VaultToken) Load() error { raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey}) if err != nil { - if t.File != "" && refused(err) { - token, ferr := t.fromFile() - if ferr != nil { - return fmt.Errorf("the vault did not hand %s (%v), and %w", VaultName(t.Account), err, ferr) - } - t.mu.Lock() - t.token, t.generation, t.source = token, 0, SourceFile - t.mu.Unlock() - return nil - } return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err) } var got struct { @@ -121,45 +80,16 @@ func (t *VaultToken) Load() error { return fmt.Errorf("the vault's %s is empty", VaultName(t.Account)) } t.mu.Lock() - t.token, t.generation, t.source = token, got.Generation, SourceVault + t.token, t.generation = token, got.Generation t.mu.Unlock() return nil } -// fromFile is the token gitea's TypeScript bundle keeps in File, refused unless its scopes line names Account (as the -// bundle writes it: " for "). -func (t *VaultToken) fromFile() (string, error) { - raw, err := os.ReadFile(t.File) - if err != nil { - return "", fmt.Errorf("the token file gitea keeps for %s cannot be read: %w", t.Account, err) - } - line, err := os.ReadFile(t.File + ".scopes") - if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+t.Account) { - return "", fmt.Errorf("the token kept at %s is not %s's (its scopes line does not name it); nothing is sent", t.File, t.Account) - } - token := strings.TrimSpace(string(raw)) - if token == "" { - return "", fmt.Errorf("the token kept at %s is empty; nothing is sent", t.File) - } - return token, nil -} - -// Source is where the token held came from, SourceVault or SourceFile; "" when none is held. -func (t *VaultToken) Source() string { - t.mu.Lock() - defer t.mu.Unlock() - return t.source -} - // Token is the token held; read from the vault when none is yet (the module mints it first). func (t *VaultToken) Token() (string, error) { t.mu.Lock() - token, source := t.token, t.source + token := t.token t.mu.Unlock() - if source == SourceFile { - // gitea's TypeScript bundle mints into its file again on a refusal: the file is read at each call, as before C4. - return t.fromFile() - } if token != "" { return token, nil } @@ -208,45 +138,12 @@ func TokenOf(account string) (*VaultToken, error) { if err != nil { return nil, err } - t.File, t.FileByDefault = TokenFile(account) processTokens[account] = t return t, nil } -// DefaultStateDir is gitea's runtime-state directory (the manifest's `${dir:mesh-state}/state`), where its TypeScript -// bundle keeps the token files, for a composition that hands the Go bundles no token file (gitea 0.1.316 hands them -// no variable naming that directory either; H-A-564). -const DefaultStateDir = "/var/lib/mesh/gitea/state" - -// TokenFile is the file the manifest names for account's token as gitea's TypeScript bundle keeps it (H-A-564): -// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, MESH_GITEA_TOKEN_FILE for the tools' account; when the -// variable is not handed, the file in DefaultStateDir, and byDefault says so. "" for any other account. -func TokenFile(account string) (file string, byDefault bool) { - packages := os.Getenv("MESH_GITEA_PACKAGES_USER") - if packages == "" { - packages = PackagesAccount - } - tools := os.Getenv("MESH_GITEA_TOOLS_USER") - if tools == "" { - tools = ToolsAccount - } - variable, name := "", "" - switch account { - case packages: - variable, name = "MESH_GITEA_PACKAGES_TOKEN_FILE", "packages-token" - case tools: - variable, name = "MESH_GITEA_TOKEN_FILE", "token" - default: - return "", false - } - if f := os.Getenv(variable); f != "" { - return f, false - } - return filepath.Join(DefaultStateDir, name), true -} - // Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying -// through logf what it read and, once at start, from which source (never the token). It returns when the +// through logf what it read (never the token). It returns when the // subscription ends. func Follow(logf func(format string, args ...any), accounts ...string) error { var held []*VaultToken @@ -273,21 +170,13 @@ func Follow(logf func(format string, args ...any), accounts ...string) error { }) } -// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token. +// Start reads each token once and says, through logf, that it did (never the token). func Start(logf func(format string, args ...any), held ...*VaultToken) { for _, t := range held { - switch err := t.Load(); { - case err != nil: + if err := t.Load(); err != nil { logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err) - case t.Source() == SourceFile: - how := "named by the manifest" - if t.FileByDefault { - how = "the default path, the manifest naming none" - } - logf("the vault refuses %s to this process's account, so %s's token is read from %s, %s (%s; H-A-564)", - VaultName(t.Account), t.Account, SourceFile, t.File, how) - default: - logf("read %s at generation %d from %s", VaultName(t.Account), t.Generation(), SourceVault) + continue } + logf("read %s at generation %d", VaultName(t.Account), t.Generation()) } } diff --git a/modules/gitea/internal/forgehttp/vault_test.go b/modules/gitea/internal/forgehttp/vault_test.go index b89e1a6a7..1f485cb50 100644 --- a/modules/gitea/internal/forgehttp/vault_test.go +++ b/modules/gitea/internal/forgehttp/vault_test.go @@ -4,33 +4,15 @@ import ( "encoding/json" "errors" "fmt" - "os" - "path/filepath" "strings" "testing" "git.novox.be/novox/mesh-sdk/go/seal" ) -// H-A-564: until gitea runs as its own account, a Go bundle the vault refuses reads the token gitea's TypeScript -// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file. -func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) { - dir := t.TempDir() - keep := func(name, token, scopes string) string { - p := filepath.Join(dir, name) - if err := os.WriteFile(p, []byte(token+"\n"), 0o600); err != nil { - t.Fatal(err) - } - if scopes != "" { - if err := os.WriteFile(p+".scopes", []byte(scopes+"\n"), 0o600); err != nil { - t.Fatal(err) - } - } - return p - } - tools := keep("token", "file-tools", "read:package,read:user,write:issue,write:repository for mesh-tools") - packages := keep("packages-token", "file-packages", "write:package for mesh-packages") - admins := keep("admins-token", "file-admin", "write:admin") +// H-A-575: a Go bundle reads its token from the vault alone and says it did at start; whatever the vault refuses, no +// token file stands in (the stand-in of H-A-564 is gone). +func TestATokenComesFromTheVaultAloneAndNoFileStandsInWhenTheVaultRefuses(t *testing.T) { vaultHolds := func(token string) Ask { return func(address string, args any) (json.RawMessage, error) { a := args.(map[string]any) @@ -45,27 +27,23 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil vaultSays := func(said string) Ask { return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) } } - notModule := vaultSays("novox.node-tools is no module's account (.), so it has no own secret here") for _, c := range []struct { - name, account, file string - ask Ask - token, source, err string + name, account string + ask Ask + token, err string }{ - {"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""}, - {"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""}, - {"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""}, - {"another module's account: the file", "mesh-tools", tools, - vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "file-tools", SourceFile, ""}, - {"the vault holds none: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"}, - {"no file named: the refusal stands", "mesh-tools", "", notModule, "", "", "no module's account"}, - {"a file whose scopes line names another account is not sent", "mesh-tools", admins, notModule, "", "", "is not mesh-tools's"}, + {"the vault hands it", "mesh-tools", vaultHolds("vault-tools"), "vault-tools", ""}, + {"the vault refuses the tool runner: no file is read", "mesh-packages", + vaultSays("novox.node-tools is no module's account (.), so it has no own secret here"), "", "no module's account"}, + {"another module's account: no file is read", "mesh-tools", + vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "", "handed only to an account of gitea"}, + {"the vault holds none", "mesh-tools", vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "holds no secret"}, } { t.Run(c.name, func(t *testing.T) { v, err := NewVaultToken(c.account, c.ask) if err != nil { t.Fatal(err) } - v.File = c.file var said []string Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v) got, err := v.Token() @@ -75,64 +53,12 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil } return } - if err != nil || got != c.token || v.Source() != c.source { - t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source) + if err != nil || got != c.token { + t.Fatalf("token %q (%v); want %q", got, err, c.token) } - if len(said) != 1 || !strings.Contains(said[0], c.source) || strings.Contains(said[0], c.token) { - t.Fatalf("said %q: one line naming %q, never the token", said, c.source) + if len(said) != 1 || strings.Contains(said[0], c.token) || strings.Contains(said[0], "file") { + t.Fatalf("said %q: one line, never the token and naming no file", said) } }) } - // A token gitea mints into its file again is the one sent next. - v, _ := NewVaultToken("mesh-tools", notModule) - v.File = tools - Start(func(string, ...any) {}, v) - keep("token", "file-tools-2", "read:package for mesh-tools") - if got, _ := v.Token(); got != "file-tools-2" { - t.Fatalf("after gitea minted again, %q is sent", got) - } -} - -// H-A-564: the manifest's file for each account wins; without it, the file in gitea's runtime-state directory, said -// as the default. -func TestTheTokenFileOfAnAccountIsTheOneTheManifestNamesForItElseTheDefault(t *testing.T) { - type file struct { - path string - byDefault bool - } - for _, c := range []struct { - name string - tools, packs string - want map[string]file - }{ - {"named by the manifest", "/s/token", "/s/packages-token", map[string]file{ - "mesh-tools": {"/s/token", false}, "mesh-packages": {"/s/packages-token", false}, "other": {"", false}}}, - {"named by none: the default", "", "", map[string]file{ - "mesh-tools": {"/var/lib/mesh/gitea/state/token", true}, - "mesh-packages": {"/var/lib/mesh/gitea/state/packages-token", true}, "other": {"", false}}}, - } { - t.Run(c.name, func(t *testing.T) { - t.Setenv("MESH_GITEA_TOKEN_FILE", c.tools) - t.Setenv("MESH_GITEA_PACKAGES_TOKEN_FILE", c.packs) - for account, want := range c.want { - if p, d := TokenFile(account); (file{p, d}) != want { - t.Errorf("TokenFile(%s) = %q, %v; want %q, %v", account, p, d, want.path, want.byDefault) - } - } - }) - } - // The start line says the default as such. - dir := t.TempDir() - p := filepath.Join(dir, "token") - _ = os.WriteFile(p, []byte("t\n"), 0o600) - _ = os.WriteFile(p+".scopes", []byte("read:user for mesh-tools\n"), 0o600) - v, _ := NewVaultToken("mesh-tools", func(string, any) (json.RawMessage, error) { - return nil, errors.New("novox.node-tools is no module's account") - }) - v.File, v.FileByDefault = p, true - var said string - Start(func(f string, a ...any) { said = fmt.Sprintf(f, a...) }, v) - if !strings.Contains(said, "the default path") { - t.Fatalf("said %q, not that the file is the default", said) - } } diff --git a/modules/gitea/internal/packageseats/holder.go b/modules/gitea/internal/packageseats/holder.go index 53ca97aa0..8006f5871 100644 --- a/modules/gitea/internal/packageseats/holder.go +++ b/modules/gitea/internal/packageseats/holder.go @@ -14,6 +14,7 @@ import ( "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts" + keyparts "git.novox.be/novox/mesh-sdk/go/keys" ) // The seats the forge module holds. @@ -56,6 +57,9 @@ const ( // IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): its // end is the event that drops a transfer left with no chunk for TransferIdle, never a timer. IdleState = "idle" + // FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published + // with (design 47 H2 H-A-589 (2)). + FingerprintsState = "fingerprints" // KindPackage is the one kind a package seat holds. KindPackage = "package" // Self is the forge module, the holder every outcome names. @@ -99,6 +103,36 @@ type Answer struct { Transfer string Lacks []string Ended bool + // OtherBytes is set when the forge holds the publish's name and version with another digest and keeps another + // fingerprint for it, or none: the call does not fail and no transfer is opened (design 47 H2 H-A-729, H-A-732). + OtherBytes *OtherBytes +} + +// OtherBytes is the digest the forge holds for a name and version, and the fingerprint it keeps for them, empty where it +// keeps none. +type OtherBytes struct { + Digest string + Fingerprint string +} + +// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named. +type Kept struct { + Digest string `json:"digest"` + Fingerprint string `json:"fingerprint,omitempty"` +} + +// FingerprintKey is the key of name at version in the state fingerprints: `.`, each token escaped as a key's +// name is (design 47 H2 H-A-589 (2)). +func FingerprintKey(name, version string) string { + return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version) +} + +// FingerprintState is the holder's own state fingerprints (bus state, template state; ADR 0595), reached by the holder +// alone; a write at its cap fails. +type FingerprintState interface { + Get(key string) (Kept, bool, error) + Put(key string, k Kept) error + Delete(key string) error } // Version is one version a seat holds of a name. @@ -106,6 +140,8 @@ type Version struct { Version string Digest string Published time.Time + // Fingerprint is the one kept for the version, empty where none is kept (H-A-589 (3)). + Fingerprint string } // Builder answers whether the builder reserved a version with a digest (Reserved). @@ -129,8 +165,10 @@ type Store interface { type Holder struct { Objects parts.Objects Transfers parts.Transfers[Opening] - Builder Builder - Store Store + // Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)). + Fingerprints FingerprintState + Builder Builder + Store Store // Say says an event on a seat's family. Say func(seat, event string, o Outcome) error // Finding writes (raised) or clears the module's finding of a kind for a subject. @@ -144,6 +182,8 @@ type Holder struct { // Idle writes a transfer's idle key with its own time to live, once (parts.BusArm over IdleState); the receiver // arms it on each open that leaves a transfer open. Nil arms nothing. Idle func(key string, ttl time.Duration) error + // Logf is the journal; nil says nothing. + Logf func(string, ...any) } // CapNow is incoming's cap as its binding carries it. @@ -178,8 +218,16 @@ func (h *Holder) receiver() *parts.Receiver[Opening] { }, Store: func(t Transfer, held map[string][]byte) error { file := held[t.Shape.Digest] + // The key is written before the forge takes the version: a write the state refuses at its cap refuses the publish. + if err := h.Fingerprints.Put(FingerprintKey(t.Shape.Name, t.Shape.Version), Kept{Digest: t.Shape.Digest, Fingerprint: t.Shape.Fingerprint}); err != nil { + reason := fmt.Sprintf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %v", FingerprintsState, t.Shape.Name, t.Shape.Version, err) + return errors.Join(errors.New("refused: "+reason), h.refused(t, reason)) + } module, err := h.Store.Put(t.Shape.Seat, t.Shape.Publish, file) if err != nil { + if derr := h.Fingerprints.Delete(FingerprintKey(t.Shape.Name, t.Shape.Version)); derr != nil { + h.logf("publish: the key of %s@%s stays in the state %s: %v", t.Shape.Name, t.Shape.Version, FingerprintsState, derr) + } reason := "the forge did not take it: " + err.Error() return errors.Join(errors.New("refused: "+reason), h.refused(t, reason)) } @@ -220,21 +268,13 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) { if err := checkPublish(seat, p); err != nil { return Answer{}, err } - // A rebuild of a published version answers it held and uploads nothing; the same version with other content is - // refused, as the registry would refuse it. + // A rebuild of a published version answers it held and uploads nothing. The same version with other content is answered + // other-bytes with the fingerprint the holder keeps for it (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). if d, ok, err := h.Store.Held(seat, p.Name, p.Version); err != nil { return Answer{}, fmt.Errorf("publish: the forge cannot say whether it holds %s@%s: %w", p.Name, p.Version, err) } else if ok { if d != p.Digest { - reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest) - if len(p.Parts) == 0 { - // The builder's publish again names nothing the forge holds under that digest: refused as not stored (A-490, - // A-490a), the words its republish recognises. - reason = "not stored: " + reason - return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)) - } - // A one-part publish of a taken version is refused with an event only, as the registry would (the builder's "version taken"). - return Answer{Transfer: p.Transfer, Ended: true}, h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason) + return h.heldElsewhere(p, d) } o := outcomeOf(p, "") o.Reference = Reference(p.Name, p.Version) @@ -258,6 +298,29 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) { return h.answer(p.Transfer, got), nil } +// heldElsewhere answers a publish of a version the forge holds at the digest other, not the publish's: other-bytes, the held +// digest and the fingerprint kept for it (empty where none, a key naming another digest than the forge holds speaks for +// nothing), the call not failing, nothing stored and no transfer opened. The reader compares the kept fingerprint with the +// publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both fingerprints. +func (h *Holder) heldElsewhere(p Publish, other string) (Answer, error) { + k, found, err := h.Fingerprints.Get(FingerprintKey(p.Name, p.Version)) + if err != nil { + return Answer{}, fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", p.Name, p.Version, err) + } + kept := "" + if found && k.Digest == other { + kept = k.Fingerprint + } + h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", p.Name, p.Version, other, kept, p.Digest, p.Fingerprint) + return Answer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil +} + +func (h *Holder) logf(format string, a ...any) { + if h.Logf != nil { + h.Logf(format, a...) + } +} + // PublishPart is `publish-part`: one chunk, from the caller that opened the transfer alone. func (h *Holder) PublishPart(seat, caller, transfer, part string, sequence int, last bool, data []byte) (Answer, error) { got, err := h.receiver().Take(key(seat, transfer), caller, part, sequence, last, data, func(t Transfer) error { @@ -284,6 +347,15 @@ func (h *Holder) Versions(seat, caller, name string) ([]Version, error) { if err != nil { return nil, fmt.Errorf("versions: the forge cannot list %s: %w", name, err) } + for i := range v { + k, found, err := h.Fingerprints.Get(FingerprintKey(name, v[i].Version)) + if err != nil { + return nil, fmt.Errorf("versions: the fingerprint kept for %s@%s cannot be read: %w", name, v[i].Version, err) + } + if found && k.Digest == v[i].Digest { + v[i].Fingerprint = k.Fingerprint + } + } return v, nil } @@ -308,12 +380,18 @@ func (h *Holder) Remove(seat, caller, name, version, reason string) (Outcome, er return Outcome{}, fmt.Errorf("remove: the forge did not remove %s@%s: %w", name, version, err) } } + if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil { + return Outcome{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err) + } o := Outcome{Name: name, Version: version, Kind: KindPackage, Digest: d, Reason: reason} return o, h.Say(seat, EventRemoved, o) } // Retained says `removed` for a version the forge's own retention deleted (design 51 *Retention*). func (h *Holder) Retained(seat, name, version, digest string) error { + if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil { + return fmt.Errorf("retained: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err) + } return h.Say(seat, EventRemoved, Outcome{Name: name, Version: version, Kind: KindPackage, Digest: digest, Reason: ReasonRetention}) } diff --git a/modules/gitea/internal/packageseats/holder_test.go b/modules/gitea/internal/packageseats/holder_test.go index 405b9e210..461235145 100644 --- a/modules/gitea/internal/packageseats/holder_test.go +++ b/modules/gitea/internal/packageseats/holder_test.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "reflect" "strings" "testing" "time" @@ -112,9 +113,25 @@ type bed struct { findings map[string]bool } +// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap. +type memFingerprints struct { + m map[string]Kept + full bool +} + +func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil } +func (f *memFingerprints) Put(k string, v Kept) error { + if f.full { + return errors.New("the bucket is at its cap") + } + f.m[k] = v + return nil +} +func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil } + func newBed(numbered bool) *bed { b := &bed{forge: &forge{files: map[string]map[string][]byte{}}, findings: map[string]bool{}} - b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: builder{ok: numbered}, + b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: builder{ok: numbered}, Store: b.forge, Now: func() time.Time { return time.Unix(1e9, 0) }, Say: func(seat, event string, o Outcome) error { b.said = append(b.said, said{seat, event, o}); return nil }, Finding: func(kind, subject, _ string, raised bool) { b.findings[kind+" "+subject] = raised }} @@ -168,17 +185,40 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) { t.Run("the publish conformance cases on "+seat, func(t *testing.T) { publishconformance.Run(t, func(t *testing.T) publishconformance.Bed { b := newBed(true) + publish := func(name, version, digest, fingerprint string) publishconformance.Outcome { + a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest, Fingerprint: fingerprint}) + o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err} + if a.OtherBytes != nil { + o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint} + } + if len(b.said) > 0 { + o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason + } + return o + } return publishconformance.Bed{ Hold: func(d string) { b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d) }, - Publish: func(name, version, digest string) publishconformance.Outcome { - a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest}) - o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err} - if len(b.said) > 0 { - o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason + HoldWith: func(d, fp string) { + b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d) + if fp != "" { + _ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp}) } - return o + }, + Held: func(name, version string) (string, string) { + d, _, _ := b.forge.Held(seat, name, version) + k, found, _ := b.h.Fingerprints.Get(FingerprintKey(name, version)) + if !found || k.Digest != d { + return d, "" + } + return d, k.Fingerprint + }, + Publish: func(name, version, digest string) publishconformance.Outcome { + return publish(name, version, digest, "") + }, + PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome { + return publish(name, version, digest, fingerprint) }} }) }) @@ -206,10 +246,13 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) { Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) }, PublishWhole: func() publishconformance.Outcome { a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole)) - if err == nil && !a.Ended { + if err == nil && !a.Ended && a.OtherBytes == nil { _, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole) } o := publishconformance.Outcome{Err: err} + if a.OtherBytes != nil { + o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint} + } if len(b.said) > 0 { o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason } @@ -218,6 +261,72 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) { }) }) } + // H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered other-bytes with the fingerprint the holder keeps, per seat. + t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) { + for _, seat := range []string{NpmSeat, GoSeat} { + for _, c := range []struct { + name string + kept, offer string + noKey bool + wantOther *OtherBytes + noParts bool + }{ + {name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}}, + {name: "the same, with no parts", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true}, + {name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}}, + {name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first"))}}, + {name: "no fingerprint offered is other-bytes", kept: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true}, + } { + b := newBed(true) + b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) + if !c.noKey { + _ = b.h.Fingerprints.Put(FingerprintKey("mesh-sdk", "0.1.19"), Kept{Digest: digest([]byte("first")), Fingerprint: c.kept}) + } + p := pub("mesh-sdk", "0.1.19", file) + p.Fingerprint = c.offer + if c.noParts { + p.Parts = nil + } + a, err := b.h.Publish(seat, goBuild, p) + if err != nil || !reflect.DeepEqual(a.OtherBytes, c.wantOther) || len(b.forge.files[seat]) != 0 || len(a.Lacks) != 0 || len(b.h.Transfers.(memTransfers)) != 0 { + t.Errorf("%s, %s: answered %+v, %v; stored %v", seat, c.name, a, err, b.forge.files[seat]) + } + if a.Ended || a.Transfer != "" || len(b.said) != 0 { + t.Errorf("%s, %s: answered %+v, said %+v; want no transfer, not ended, nothing said", seat, c.name, a, b.said) + } + } + // the key is written when a version is stored, read by versions, deleted at removed + b := newBed(true) + p := pub("mesh-sdk", "0.1.19-b", file) + p.Fingerprint = "f9" + if _, err := b.h.Publish(seat, goBuild, p); err != nil { + t.Fatal(err) + } + if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err != nil { + t.Fatal(err) + } + if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); !ok || k != (Kept{Digest: digest(file), Fingerprint: "f9"}) { + t.Errorf("%s: the key after the store = %+v, %v", seat, k, ok) + } + if v, _ := b.h.Versions(seat, "g14.anyone", "mesh-sdk"); len(v) != 1 || v[0].Fingerprint != "f9" { + t.Errorf("%s: versions answered %+v, want fingerprint f9", seat, v) + } + if _, err := b.h.Remove(seat, "novox.mesh-delivery-builder", "mesh-sdk", "0.1.19-b", "tag-gone"); err != nil { + t.Fatal(err) + } + if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); ok { + t.Errorf("%s: the key stayed after removed", seat) + } + // a version stored while the state is at its cap is refused and nothing is stored + b = newBed(true) + b.h.Fingerprints.(*memFingerprints).full = true + p = pub("mesh-sdk", "0.1.20", file) + _, _ = b.h.Publish(seat, goBuild, p) + if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err == nil || !strings.Contains(err.Error(), "fingerprints did not take the key") || len(b.forge.files[seat]) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused { + t.Errorf("%s: a version at the state's cap = %v; said %+v; stored %v", seat, err, b.said, b.forge.files[seat]) + } + } + }) // Design 47 G A-73, A-417: the builder's publish again names the version and the digest and no parts. t.Run("a publish with a digest and no parts is published when held, refused as not stored when not", func(t *testing.T) { for _, seat := range []string{NpmSeat, GoSeat} { @@ -367,11 +476,11 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) { !strings.Contains(err.Error(), "send the part again") || len(b.said) != 0 || len(b.forge.files[NpmSeat]) != 0 { t.Errorf("a part with other bytes: %v, said %+v", err, b.said) } - // The same version published with other content is refused, never uploaded over. + // The same version published with other content is answered other-bytes, never uploaded over (H-A-729). b = newBed(true) b.forge.files[NpmSeat] = map[string][]byte{"x@0.1.0": []byte("first")} - if _, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || len(b.said) != 1 || b.said[0].event != EventRefused { - t.Errorf("a published version with other content: %v, said %+v", err, b.said) + if a, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != digest([]byte("first")) || len(b.said) != 0 || string(b.forge.files[NpmSeat]["x@0.1.0"]) != "first" { + t.Errorf("a published version with other content: %+v, %v, said %+v", a, err, b.said) } }) t.Run("the builder removes a tagged version; one already gone is said removed all the same", func(t *testing.T) { diff --git a/modules/gitea/kept.ts b/modules/gitea/kept.ts index deba4f89d..d39c1abc9 100644 --- a/modules/gitea/kept.ts +++ b/modules/gitea/kept.ts @@ -9,6 +9,7 @@ export const KEPT: readonly { readonly name: string; readonly readable?: boolean { name: "calls" }, { name: "bound", readable: true }, { name: "findings", readable: true }, + { name: "fingerprints" }, { name: "failed-steps" }, { name: "first-views" }, { name: "idle" }, diff --git a/modules/gitea/mergecall.ts b/modules/gitea/mergecall.ts index 22326da15..abadf030c 100644 --- a/modules/gitea/mergecall.ts +++ b/modules/gitea/mergecall.ts @@ -5,11 +5,11 @@ // `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the // module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged // and the answer names every refused member and why; else the members are merged in the order the call names them. The -// verb answers once, at the call's end: `call` and each member's outcome. A member whose repository has no watched branch -// (no entry, or an empty set, in the registrations' watched branches) is the forge's business alone (H2 H-A-471 and its -// addendum): judged against nothing of the module graph, merged plainly in the order named, answered and kept merged with -// the note no delivery, and left out of merge-called, so it starts no delivery. A watched repository whose base is no -// watched branch stays refused. A member is merged plainly only from a view of the watched branches read since the last +// verb answers once, at the call's end: `call` and each member's outcome. A member whose base is no watched branch, +// whatever its repository (no entry, or an empty set, in the registrations' watched branches, or a set that does not +// hold the base), is the forge's business alone (H2 H-A-471 and its addendum, H-A-704): judged against nothing of the +// module graph, merged plainly in the order named, answered and kept merged with the note no delivery, and left out of +// merge-called, so it starts no delivery. A member is merged plainly only from a view of the watched branches read since the last // registration-changed heard (the second addendum): while the view is unread or stale, every member is refused, never // merged with the note. @@ -57,14 +57,14 @@ export interface Member { state: MemberOutcome["state"]; commit?: string; why?: string; - /** Set on a member merged plainly, its repository having no watched branch (H-A-471). */ + /** Set on a member merged plainly, its base being no watched branch (H-A-471, H-A-704). */ note?: string; - /** Its repository has no watched branch: judged against nothing of the module graph (H-A-471). */ + /** Its base is no watched branch: judged against nothing of the module graph (H-A-471, H-A-704). */ plain?: boolean; } -/** The note of a member merged plainly: it starts no delivery (H-A-471). */ -export const NO_DELIVERY = "no delivery: the repository has no watched branch"; +/** The note of a member merged plainly: it starts no delivery (H-A-471, H-A-704; its words H-A-717, DQ-49). */ +export const NO_DELIVERY = "no delivery: its base is no watched branch"; /** Why every member is refused while the watched branches are unread or stale (H-A-471, second addendum). */ export const NOT_READ = "the watched branches are not read yet"; @@ -107,12 +107,12 @@ async function judgeMember(forge: CallForge, deps: CallDeps, watched: ReadonlyMa return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`; } const branches = watched.get(m.repository); - // A repository of no module: no build-input fingerprint and no required step judge it (H-A-471). - if (!branches || branches.size === 0) { + // A base no registration watches, whatever the repository: no build-input fingerprint and no required step judge it + // (H-A-471, H-A-704). + if (!branches || !branches.has(m.branch)) { m.plain = true; return ""; } - if (!branches.has(m.branch)) return `its base ${m.branch} is no watched branch`; const failed = await deps.judge(m.head); if (failed) { return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`; diff --git a/modules/gitea/module.json b/modules/gitea/module.json index 35d4a05f6..2c5fc6742 100644 --- a/modules/gitea/module.json +++ b/modules/gitea/module.json @@ -6,6 +6,7 @@ "check-needs": [ "node-build-node" ], + "runs-as": "gitea", "requires": [ "postgres-database", "route", @@ -39,6 +40,10 @@ "admin": "${dir:state}/admin.secret" } }, + "own-secrets": { + "broker": "${dir:state}/broker" + }, + "secrets-owner": "gitea", "capabilities": [ "container-runtime" ], @@ -271,6 +276,16 @@ } }, "resources": [ + { + "id": "account", + "type": "user", + "name": "gitea", + "shell": "/usr/bin/nologin", + "home": "/var/lib/gitea", + "groups": [ + "docker" + ] + }, { "id": "mesh-state", "type": "directory", @@ -544,9 +559,7 @@ "env": { "MESH_GITEA_URL": "http://127.0.0.1:${port:3000}", "MESH_GITEA_TOOLS_USER": "mesh-tools", - "MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token", "MESH_GITEA_PACKAGES_USER": "mesh-packages", - "MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token", "MESH_NPM_OWNER": "novox" } }, @@ -563,7 +576,6 @@ "env": { "MESH_GITEA_URL": "http://127.0.0.1:${port:3000}", "MESH_GITEA_TOOLS_USER": "mesh-tools", - "MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token", "MESH_GITEA_PATCH_DIR": "${dir:forge-patches}" } }, @@ -662,6 +674,10 @@ "name": "transfers", "max-mib": 8 }, + { + "name": "fingerprints", + "max-mib": 16 + }, { "name": "idle", "key-ttl": true, diff --git a/modules/gitea/packages-account.ts b/modules/gitea/packages-account.ts index bc264d44d..e0adb5c83 100644 --- a/modules/gitea/packages-account.ts +++ b/modules/gitea/packages-account.ts @@ -19,7 +19,7 @@ import { randomBytes } from "node:crypto"; import { adminFromEnv, MintedToken } from "./token.js"; -import { TOOLS_ORG, type ToolsForge } from "./tools-account.js"; +import { TOOLS_ACCOUNT, TOOLS_ORG, type ToolsForge } from "./tools-account.js"; /** The account the package seats write as (internal/forgehttp PackagesAccount). */ export const PACKAGES_ACCOUNT = "mesh-packages"; @@ -52,6 +52,7 @@ export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env, const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env); return new MintedToken({ ...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log, + tokenFile: "packages-token", listAccounts: async () => [account, env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT], setUp: async (password) => { const { GiteaAdmin } = await import("./client.js"); await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url")); diff --git a/modules/gitea/test/calls.test.ts b/modules/gitea/test/calls.test.ts index 08da5871b..f0d0b0e48 100644 --- a/modules/gitea/test/calls.test.ts +++ b/modules/gitea/test/calls.test.ts @@ -91,9 +91,9 @@ test("a call says one merge-called of what landed; none for a call that landed n assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[1, 2]]); assert.equal(said[0].body.refused, undefined, "a member not merged after a stop is no refused member"); assert.deepEqual(await sayUnsaid(calls, say), [], "said once"); - // A member merged plainly, its repository having no watched branch, starts no delivery: the start's re-say leaves it + // A member merged plainly, its base being no watched branch, starts no delivery: the start's re-say leaves it // out by the kept note (design 47 H2 H-A-471 addendum (2)), and a call of such members alone says none. - const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: the repository has no watched branch" }; + const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: its base is no watched branch" }; await calls.put("00000000000000dd", { by: "lead@shanks", account: "x", at: "2026-11-20T03:02:00Z", members: [noted, m(5, "merged")], said: false } as any); await calls.put("00000000000000ee", { by: "lead@shanks", account: "x", at: "2026-11-20T03:03:00Z", members: [noted], said: false } as any); said.length = 0; diff --git a/modules/gitea/test/delivery.test.ts b/modules/gitea/test/delivery.test.ts index b134f8696..2a097c071 100644 --- a/modules/gitea/test/delivery.test.ts +++ b/modules/gitea/test/delivery.test.ts @@ -28,6 +28,11 @@ test("a note line is appended once, as the forge's user, in its own repository", { added: true, lines: 2 }); const append = calls.find((c) => c.includes("append"))!; assert.deepEqual(append.slice(0, 7), ["docker", "exec", "-u", "git", "gitea", "git", "--git-dir"]); + // The note is run by docker, so the account the module runs as is in the group docker (H-A-543, H-A-545). + const { readFileSync } = await import("node:fs"); + const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8")); + const account = manifest.resources.find((r: { type: string; name: string }) => r.type === "user" && r.name === manifest["runs-as"]); + assert.ok(account?.groups?.includes("docker"), `the account ${manifest["runs-as"]} the module runs as is not in the group docker`); assert.equal(append[7], "/data/git/repositories/novox/mesh-catalog.git"); assert.ok(append.includes("--ref=mesh-plan")); assert.throws(() => noteArgs("gitea", "novox", "x; rm -rf /", sha, "mesh-plan"), /not a repository/); diff --git a/modules/gitea/test/kept.test.ts b/modules/gitea/test/kept.test.ts index 5595321c0..7d254630c 100644 --- a/modules/gitea/test/kept.test.ts +++ b/modules/gitea/test/kept.test.ts @@ -16,8 +16,8 @@ test("the states the module announces are the states its manifest declares", asy test("the announcement has the layout mesh-sdk's go/announce reads: version 1, the module, the node, the states sorted by name", async () => { const { statesAnnouncement } = await import("../kept.ts"); - assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); - assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); + assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "fingerprints" }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); + assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "fingerprints" }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] }); }); test("index.ts says the announcement as the event `states` before the tools are served", () => { diff --git a/modules/gitea/test/merge-call.test.ts b/modules/gitea/test/merge-call.test.ts index e44d0c27f..6ebf27942 100644 --- a/modules/gitea/test/merge-call.test.ts +++ b/modules/gitea/test/merge-call.test.ts @@ -66,7 +66,6 @@ test("a member refused at judging merges none and names every refused member and { name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ }, { name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ }, { name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ }, - { name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ }, { name: "a required step failed at its head's fingerprint", set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) }, why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ }, @@ -83,20 +82,22 @@ test("a member refused at judging merges none and names every refused member and } }); -// **A repository of no module is merged plainly** (design 47 H2 H-A-471 and its addendum): a member whose repository has -// no watched branch (no entry, or an empty set, in the registrations' watched branches) is judged against nothing of the +// **A base no registration watches is merged plainly** (design 47 H2 H-A-471 and its addendum, H-A-704): a member whose base +// is no watched branch, whatever its repository (no entry, an empty set, or a set that does not hold the base, in the +// registrations' watched branches), is judged against nothing of the // module graph (no failed required step), merged in the order named, answered merged with the note no delivery, and left -// out of merge-called; the watched members of the same call are judged and delivered as any call's. A watched -// repository whose base is unwatched stays refused (the row above). -test("a member of a repository with no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => { - const NOTE = "no delivery: the repository has no watched branch"; - const rows: { name: string; watched: Map> }[] = [ - { name: "no entry", watched: new Map([["novox/app", new Set(["main"])]]) }, - { name: "an empty set", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set()]]) }, +// out of merge-called; the watched members of the same call are judged and delivered as any call's. +test("a member whose base is no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => { + const NOTE = "no delivery: its base is no watched branch"; + const rows: { name: string; base: string; watched: Map> }[] = [ + { name: "no entry", base: "main", watched: new Map([["novox/app", new Set(["main"])]]) }, + { name: "an empty set", base: "main", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set()]]) }, + { name: "a watched repository's pull request into a branch it does not watch", base: "feat/x", + watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set(["main"])]]) }, ]; for (const r of rows) { const pulls = open(); - pulls["novox/hq#799"] = { base: "main", head: B, state: "open", merged: false }; + pulls["novox/hq#799"] = { base: r.base, head: B, state: "open", merged: false }; const f = forge(pulls); const judged: string[] = []; const said: any[] = []; @@ -109,7 +110,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n assert.equal(got.members[0].state, "judged", r.name); assert.equal(got.members[1].state, "refused", r.name); // Without the failed step the call lands both: the unwatched noted, merge-called naming only the watched. - const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: "main", head: B, state: "open", merged: false } })); + const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } })); said.length = 0; const landed = await call(f2, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } }); assert.deepEqual(f2.merges, ["novox/hq#799", "novox/app#5"], `${r.name}: merged in the order named`); @@ -117,7 +118,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n [["novox/hq", "merged", NOTE, undefined], ["novox/app", "merged", undefined, undefined]], r.name); assert.deepEqual(said.map((b) => b.members.map((m: any) => m.repository)), [["novox/app"]], `${r.name}: merge-called leaves it out`); // A call of unwatched members alone merges and starts no delivery: no merge-called. - const f3 = forge({ "novox/hq#799": { base: "main", head: B, state: "open", merged: false } }); + const f3 = forge({ "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } }); said.length = 0; const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } }); @@ -170,7 +171,7 @@ test("a member is merged plainly only from a watched-branches view read since th const f3 = forge(pulls()); const landed = await call(f3, hq, { watched: view }); assert.deepEqual([f3.merges, landed.members.map((m: any) => [m.state, m.note])], - [["novox/hq#799", "novox/app#5"], [["merged", "no delivery: the repository has no watched branch"], ["merged", undefined]]]); + [["novox/hq#799", "novox/app#5"], [["merged", "no delivery: its base is no watched branch"], ["merged", undefined]]]); }); test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => { diff --git a/modules/gitea/test/token.test.ts b/modules/gitea/test/token.test.ts index 0bd3e0008..18e5b6d1b 100644 --- a/modules/gitea/test/token.test.ts +++ b/modules/gitea/test/token.test.ts @@ -10,12 +10,14 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; -import { mkdtemp, stat, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { collectTools } from "@novox/mesh-sdk/tools"; import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js"; +import { TOKEN_FILE_UNREVOKED, passOver, type ForgeTokens, type ListedToken } from "../dist/tokenfiles.js"; +import { PACKAGES_TOKEN_NAME, PACKAGES_TOKEN_SCOPES } from "../dist/packages-account.js"; import { tokenLeaseTool } from "../dist/tools/tokenlease.js"; import { fakeBus } from "./fakebus.ts"; import { GiteaClient } from "../dist/client.js"; @@ -38,8 +40,10 @@ interface Forge { /** How each DELETE named its token: "id" or "name". */ deletedBy: string[]; /** Plant a token by name, beside any other of the same name, as a raced mint would. */ - plant(name: string): void; + plant(name: string, sha1?: string, scopes?: string[]): void; scopesOf: Map; + /** The account the last mint was for; while it is the tools' account the admin's own list reads empty. */ + mintedFor: string; admins: Map; pullState: string; pullTitle: string; @@ -119,7 +123,7 @@ function fakeForge(): Promise { const all = listed(); res.setHeader("X-Total-Count", String(all.length)); return json(res, 200, all.slice((page - 1) * limit, page * limit) - .map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: [] }))); + .map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: forge.scopesOf.get(t.sha1) ?? [] }))); } if (req.method === "DELETE" && tokens[2]) { // gitea: "identified by ID and if not available by name" — and a name held twice is refused. @@ -236,14 +240,18 @@ function fakeForge(): Promise { url: `http://127.0.0.1:${port}`, get mints() { return forge.mints; }, get lastScopes() { return forge.lastScopes; }, + get mintedFor() { return forge.mintedFor; }, + set mintedFor(v: string) { forge.mintedFor = v; }, get pullState() { return forge.pullState; }, get pullTitle() { return forge.pullTitle; }, get branchDeleted() { return forge.branchDeleted; }, tokens: forge.tokens, twins: forge.twins, deletedBy: forge.deletedBy, - plant: (name: string) => { - const sha1 = `planted-${++forge.nextId}`; + plant: (name: string, value?: string, scopes?: string[]) => { + const sha1 = value ?? `planted-${++forge.nextId}`; + if (value) ++forge.nextId; + if (scopes) forge.scopesOf.set(sha1, scopes); forge.ids.set(sha1, forge.nextId); if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 }); else forge.tokens.set(name, sha1); @@ -665,3 +673,127 @@ test("a pull request can be closed, read and cleaned up through the tools", asyn await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" }); assert.equal(forge.branchDeleted, true); }); + +// ---- The token files an earlier build kept (H-A-575, H-A-602, H-A-642, H-A-699): ended at a start, never read. ---- + +const HEX = "0123456789abcdef0123456789abcdef01234567"; +const SCOPES = ["write:repository", "read:user"]; +const SCOPES_LINE = "read:user,write:repository for mesh-tools"; + +/** The state directory of a start, with the files an earlier build left: the token, its scopes, and what `extra` adds. */ +async function leftFiles(env: NodeJS.ProcessEnv, files: Record): Promise { + const dir = env.MESH_GITEA_STATE_DIR!; + await mkdir(dir, { recursive: true }); + for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text); + +} +const left = async (env: NodeJS.ProcessEnv) => (await readdir(env.MESH_GITEA_STATE_DIR!).catch(() => [] as string[])).filter((f) => f.includes("token")).sort(); +/** The findings a start wrote, by key. */ +const sink = () => { const held = new Map(); return { held, put: async (k: string, v: unknown) => { held.set(k, v); }, delete: async (k: string) => { held.delete(k); } }; }; + +test("a start ends the token files: the lists are read before the first mint drops the old name, the pair is revoked by its id and deleted, and a cut .tmp goes unrevoked (H-A-575, H-A-699)", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); + forge.plant(TOKEN_NAME, HEX, SCOPES); + await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "token.tmp": "cut-off", "token.scopes.tmp": SCOPES_LINE + "\n" }); + const findings = sink(); + ORDER.length = 0; + forge.deletedBy.length = 0; + + await new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings, + listAccounts: async () => ["mesh-tools", "mesh-packages"] })).listRepos(); + + // The planted token was listed before the first mint's drop deleted it, so the file's token matched and its revocation found it gone. + assert.deepEqual(await left(env), [], logs.join("\n")); + assert.equal(findings.held.size, 0); + assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, `delete ${TOKEN_NAME}`], "the own-put, then the drop of the old name"); + assert.ok(logs.some((l) => l.includes("token.tmp") && l.includes("no whole token")), logs.join("\n")); + assert.ok(logs.every((l) => !l.includes(HEX) && !l.includes(vaulted(bus))), "no line names a token"); + + // A `.tmp` holding a whole token goes with its pair: revoked at the forge by its id, then deleted (H-A-699). + const HEX2 = "fedcba9876543210fedcba9876543210fedcba98"; + forge.tokens.clear(); + forge.plant("kept-by-the-tmp", HEX2, SCOPES); + await leftFiles(env, { "token.tmp": HEX2 + "\n", "token.scopes": SCOPES_LINE + "\n" }); + forge.deletedBy.length = 0; + await minted(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings, listAccounts: async () => ["mesh-tools"] }).listRepos(); + assert.deepEqual(await left(env), [], logs.join("\n")); + assert.equal(forge.tokens.has("kept-by-the-tmp"), false, "the .tmp's token is revoked at the forge"); + + // Both pairs, the tools' `token` and the packages' `packages-token`, go at a first mint, each by its own source. + const env2 = (await delivered(forge)).env; + forge.tokens.clear(); + forge.plant(TOKEN_NAME, HEX, SCOPES); + forge.plant(PACKAGES_TOKEN_NAME, HEX2, PACKAGES_TOKEN_SCOPES); + await leftFiles(env2, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "packages-token": HEX2 + "\n", "packages-token.scopes": "write:package for mesh-packages\n" }); + const both = { stateDir: env2.MESH_GITEA_STATE_DIR, tokenFile: "token", findings, listAccounts: async () => ["mesh-tools", "mesh-packages"] }; + await new GiteaClient(env2.MESH_GITEA_URL!, source(env2, logs, both)).listRepos(); + await source(env2, logs, { ...both, account: "mesh-packages", oldName: PACKAGES_TOKEN_NAME, + scopes: PACKAGES_TOKEN_SCOPES, tokenFile: "packages-token" }).current(); + assert.deepEqual(await left(env2), [], logs.join("\n")); + assert.equal(forge.tokens.has(PACKAGES_TOKEN_NAME), false, "the packages file's token is revoked at the forge"); +}); + +test("a token file stays when the vault refuses the own-put, and when the forge refuses the revocation or matches nothing: said, written as a finding, cleared once the pair goes", async () => { + const { env, logs } = await delivered(forge); + forge.tokens.clear(); + forge.plant(TOKEN_NAME, HEX, SCOPES); + await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" }); + const refusing = source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", + vault: { get: vaultOverBus().get, put: async () => { throw new Error("the vault is away"); } } }); + await assert.rejects(new GiteaClient(env.MESH_GITEA_URL!, refusing).listRepos(), /the vault is away/); + assert.deepEqual(await left(env), ["token", "token.scopes"], "an own-put refused leaves the files and their token"); + + // The forge refuses the revocation: the pair stays and the finding names the answer; the next start's success clears it. + const findings = sink(); + const listed: ListedToken[] = [{ id: 7, token_last_eight: HEX.slice(-8), scopes: SCOPES }]; + let answer: string | null = "403 forbidden"; + const forgeTokens: ForgeTokens = { list: async () => listed, revoke: async () => answer }; + const run = (lists: Map) => + passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "token", lists, forge: forgeTokens, findings, log: (l) => logs.push(l) }); + await run(new Map([["mesh-tools", listed]])); + const key = [...findings.held.keys()]; + assert.equal(key.length, 1); + assert.match(key[0], new RegExp(`token\\.${TOKEN_FILE_UNREVOKED}$`)); + assert.match(findings.held.get(key[0]).summary, /403 forbidden/); + assert.deepEqual(await left(env), ["token", "token.scopes"]); + answer = null; + await run(new Map([["mesh-tools", listed]])); + assert.deepEqual([await left(env), findings.held.size], [[], 0]); + + // No token at the forge matches the last eight characters and the scopes: the pair stays and says so. + await leftFiles(env, { "packages-token": HEX + "\n", "packages-token.scopes": "write:package for mesh-packages\n" }); + await passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "packages-token", lists: new Map([["mesh-packages", listed]]), forge: forgeTokens, + findings, log: (l) => logs.push(l) }); + assert.deepEqual(await left(env), ["packages-token", "packages-token.scopes"]); + assert.equal(findings.held.size, 1); +}); + +test("a start with the vault holding a token and a file left runs the pass; with no file it lists nothing at the forge", async () => { + const { env, logs } = await delivered(forge); + forge.tokens.clear(); + await minted(env, logs).listRepos(); + forge.plant("kept-by-the-earlier-build", HEX, SCOPES); + await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" }); + const again: string[] = []; + const options = { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", listAccounts: async () => ["mesh-tools"] }; + + await new GiteaClient(env.MESH_GITEA_URL!, source(env, again, options)).listRepos(); + + assert.ok(again.some((l) => l.startsWith("reusing the token the vault keeps")), again.join("\n")); + assert.deepEqual(await left(env), []); + assert.equal(forge.tokens.has("kept-by-the-earlier-build"), false, "its token is revoked at the forge"); + const quiet: string[] = []; + const failing = { ...options, listAccounts: async () => { throw new Error("no lists without files"); } }; + await new GiteaClient(env.MESH_GITEA_URL!, source(env, quiet, failing)).listRepos(); + assert.ok(quiet.every((l) => !l.includes("no lists")), quiet.join("\n")); + + // With a retire file left too, the lists are read before the admin's old token goes, so a file holding that token ends (H-A-699 (2)). + forge.mintedFor = ""; // the admin's own list holds the old token, as the forge would list it + forge.plant(TOKEN_NAME, HEX, SCOPES); + await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "mesh-tools.retire-admin": "now\n" }); + const retiring: string[] = []; + await new GiteaClient(env.MESH_GITEA_URL!, source(env, retiring, { ...options, findings: sink() })).listRepos(); + assert.ok(retiring.some((l) => l.includes(`deleted 1 token(s) named "${TOKEN_NAME}"`)), retiring.join("\n")); + assert.deepEqual(await left(env), [], retiring.join("\n")); +}); diff --git a/modules/gitea/test/tools-account.test.ts b/modules/gitea/test/tools-account.test.ts index 69f4efc43..db8193b6a 100644 --- a/modules/gitea/test/tools-account.test.ts +++ b/modules/gitea/test/tools-account.test.ts @@ -374,14 +374,9 @@ test("the manifest hands the tools their account, and the Go forge bundle holds const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry"); assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT); assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined); - // H-A-564: until gitea runs as its own account, the Go bundles are handed the token files the TypeScript bundle keeps - // under its state directory, read when the vault refuses the caller's account; no other artifact is. - const files: Record = { - forge: ["${dir:runtime-state}/token", undefined], - "package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"], - }; + // H-A-575: the vault alone hands a token: no artifact is given a token file. for (const a of manifest.build.artifacts) { - assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [undefined, undefined], + assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], [undefined, undefined], `${a.name}'s token files`); } assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(",")); diff --git a/modules/gitea/token.ts b/modules/gitea/token.ts index c02c3fa01..edbd7593f 100644 --- a/modules/gitea/token.ts +++ b/modules/gitea/token.ts @@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state"; import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js"; import { keepMainRules } from "./mainrules.js"; import { durationMs } from "./taken.js"; +import { passOver, readLists, remaining, type FindingSink, type ForgeTokens, type Lists } from "./tokenfiles.js"; /** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */ export const TOKEN_NAME = "mesh-tools"; @@ -283,8 +284,16 @@ export interface MintedTokenOptions { readonly leaseMs?: number; /** Who holds the lease when this process does: the node and the process. */ readonly holder?: string; - /** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */ + /** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered, and + * where an earlier build kept the token files (tokenfiles.ts). */ readonly stateDir?: string; + /** The name of the token file an earlier build kept for this account (`token`, `packages-token`): at each start while + * it remains, it is ended once this start's token is held (H-A-575, H-A-699). */ + readonly tokenFile?: string; + /** The accounts whose tokens at the forge are listed to find the files' tokens, besides the admin's (H-A-699 (2)). */ + readonly listAccounts?: () => Promise; + /** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */ + readonly findings?: FindingSink; readonly now?: () => Date; readonly log?: (line: string) => void; readonly fetch?: typeof fetch; @@ -293,6 +302,9 @@ export interface MintedTokenOptions { /** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */ export class MintedToken implements TokenSource { private held: VaultToken | null = null; + /** The forge's token lists, read once at this start before it deletes any token there: null when they could not be read. */ + private fileLists: Lists | null | undefined; + private filesPassed = false; private inflight: Promise | null = null; private readonly scopes: readonly string[]; private readonly ttlMs: number; @@ -330,7 +342,11 @@ export class MintedToken implements TokenSource { if (shared) return shared; if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`); const source = new MintedToken({ - ...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, + ...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, tokenFile: "token", + listAccounts: async () => { + const { PACKAGES_ACCOUNT } = await import("./packages-account.js"); + return [account, env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT]; + }, // GiteaAdmin is loaded when first used: client.ts imports this file. setUp: async (password) => { const { GiteaAdmin } = await import("./client.js"); @@ -344,12 +360,12 @@ export class MintedToken implements TokenSource { private static readonly shared = new Map(); /** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */ - static settingsFromEnv(env: NodeJS.ProcessEnv): Pick { + static settingsFromEnv(env: NodeJS.ProcessEnv): Pick { const log = (line: string) => console.log(`[gitea] ${line}`); return { vault: sharedVault(), lease: sharedLease(), ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log), - stateDir: env.MESH_GITEA_STATE_DIR || undefined, + stateDir: env.MESH_GITEA_STATE_DIR || undefined, findings: state("findings"), }; } @@ -364,10 +380,13 @@ export class MintedToken implements TokenSource { } if (this.held === null) { this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`); + // The forge's token lists are read before this start deletes any token (H-A-699 (2)). + await this.readFileLists(); // A retirement of the admin's old token that failed after the mint is tried again, once a process. if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`)); } this.held = kept; + await this.endTokenFiles(); return kept.token; } @@ -403,7 +422,10 @@ export class MintedToken implements TokenSource { private mint(why: string, stale: string | null): Promise { if (this.inflight === null) { this.log(why); - this.inflight = this.leased(stale).finally(() => { + this.inflight = this.leased(stale).then(async (token) => { + await this.endTokenFiles(); + return token; + }).finally(() => { this.inflight = null; }); } @@ -438,6 +460,59 @@ export class MintedToken implements TokenSource { } } + /** The forge's token lists, once a start, when a token file of this account remains; a read that fails is said and + * leaves every file standing. */ + private async readFileLists(admin: AdminCall = this.adminCall()): Promise { + if (this.fileLists !== undefined || !this.opts.stateDir || !this.opts.tokenFile) return; + if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return; + try { + const accounts = [...(await this.opts.listAccounts?.() ?? [this.opts.account]), this.opts.admin]; + this.fileLists = await readLists(this.forgeTokens(admin), accounts); + } catch (err) { + this.fileLists = null; + this.log(`the forge's token lists could not be read, so the token files an earlier build kept stay: ${err instanceof Error ? err.message : err}`); + } + } + + private forgeTokens(admin: AdminCall): ForgeTokens { + return { + list: async (account) => { + const out: { id: number; token_last_eight: string; scopes: string[] }[] = []; + for (let page = 1; page <= 100; page++) { + const listed = await admin("GET", `/users/${encodeURIComponent(account)}/tokens?page=${page}&limit=50`); + if (listed.status !== 200 || !Array.isArray(listed.body)) throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`); + if (listed.body.length === 0) break; + for (const t of listed.body) { + if (typeof t?.id === "number" && typeof t?.token_last_eight === "string") { + out.push({ id: t.id, token_last_eight: t.token_last_eight, scopes: Array.isArray(t.scopes) ? t.scopes.map(String) : [] }); + } + } + } + return out; + }, + revoke: async (account, id) => { + const res = await admin("DELETE", `/users/${encodeURIComponent(account)}/tokens/${id}`); + return res.status === 204 || res.status === 404 ? null : `${res.status} ${detail(res.body)}`; + }, + }; + } + + /** The earlier build's token files end once this start's token is held, at the first time in this process (H-A-575, + * H-A-602, H-A-699): never a failure of the token. */ + private async endTokenFiles(): Promise { + if (this.filesPassed || !this.opts.stateDir || !this.opts.tokenFile) return; + this.filesPassed = true; + if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return; + try { + await this.readFileLists(); + if (!this.fileLists) return; + await passOver({ dir: this.opts.stateDir, base: this.opts.tokenFile, lists: this.fileLists, forge: this.forgeTokens(this.adminCall()), + findings: this.opts.findings, log: (l) => this.log(l), now: this.now }); + } catch (err) { + this.log(`the token files an earlier build kept could not be ended: ${err instanceof Error ? err.message : err}`); + } + } + /** The admin password, read now. */ private password(): string { try { @@ -528,6 +603,9 @@ export class MintedToken implements TokenSource { if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`); this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() }; this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`); + // The lists are read now, after the own-put and before the drop of the old fixed name below: the earlier build's + // token files hold tokens of that name (H-A-699 (2)). + await this.readFileLists(admin); // Only now, with the new token kept, does the one it replaces go. const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName; diff --git a/modules/gitea/tokenfiles.ts b/modules/gitea/tokenfiles.ts new file mode 100644 index 000000000..1a09cb9ed --- /dev/null +++ b/modules/gitea/tokenfiles.ts @@ -0,0 +1,121 @@ +// The token files an earlier build kept under the module's state directory, and their end (design 47 H2 H-A-575, +// H-A-602, H-A-642, H-A-699). An earlier build wrote each account's token to `token` (the tools') or `packages-token` +// (the packages account's), the scopes it was minted with beside it in `.scopes` ("", +// then " for " for an account that is not the admin), each written through a `.tmp` and renamed. The vault +// keeps the tokens now, so no build writes these files and this pass ends them: +// +// - it runs at each start of the process while any of the files remains, once this start's token is held; +// - a file's token is found at the forge by the last eight characters of the token and the scopes its `.scopes` names, +// in the lists read before this start deleted any token there; a matched pair is revoked at the forge by its id, +// then both files are deleted; a `.tmp` goes with its pair, and one holding no whole token (forty hexadecimal +// characters) is deleted with no revocation, since it names no token at the forge; +// - a pair with no match, and a pair whose revocation the forge refused, stay, said in the journal and written as the +// finding `token-file-unrevoked` (id the file) in the module's `findings`, cleared when the pair is deleted. + +import { existsSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { findingKey, findingValue } from "./findings.js"; + +export const TOKEN_FILE_UNREVOKED = "token-file-unrevoked"; + +/** A token as the forge lists it: never its value, its id, its last eight characters and its scopes. */ +export interface ListedToken { readonly id: number; readonly token_last_eight: string; readonly scopes: readonly string[] } + +/** What the pass asks of the forge, as the administrator. */ +export interface ForgeTokens { + /** Every token an account holds. */ + list(account: string): Promise; + /** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */ + revoke(account: string, id: number): Promise; +} + +/** The module's state `findings`. */ +export interface FindingSink { + put(key: string, value: unknown): Promise; + delete(key: string): Promise; +} + +/** The tokens each account held when the lists were read. */ +export type Lists = ReadonlyMap; + +/** The files one token file's name stands for: the token, its scopes, and a `.tmp` of each. */ +export const filesOf = (base: string): string[] => [base, `${base}.tmp`, `${base}.scopes`, `${base}.scopes.tmp`]; + +/** The files of `base` that remain under `dir`. */ +export const remaining = (dir: string, base: string): string[] => filesOf(base).filter((f) => existsSync(join(dir, f))); + +/** The lists of each account, read once. */ +export async function readLists(forge: ForgeTokens, accounts: readonly string[]): Promise { + const lists = new Map(); + for (const account of accounts) if (!lists.has(account)) lists.set(account, await forge.list(account)); + return lists; +} + +const WHOLE = /^[0-9a-f]{40}$/; +const sorted = (scopes: readonly string[]): string => [...scopes].sort().join(","); + +export interface PassOptions { + readonly dir: string; + /** `token` or `packages-token`. */ + readonly base: string; + readonly lists: Lists; + readonly forge: ForgeTokens; + readonly findings?: FindingSink; + readonly log: (line: string) => void; + readonly now?: () => Date; +} + +/** The pass over one token file's pair and their `.tmp` files. Never throws for a file it cannot end: it stays, said. */ +export async function passOver(o: PassOptions): Promise { + const at = (o.now ?? (() => new Date()))().toISOString(); + const path = (f: string) => join(o.dir, f); + const scopesFile = [`${o.base}.scopes`, `${o.base}.scopes.tmp`].find((f) => existsSync(path(f))); + // The scopes its `.scopes` names, without the account they are "for". + const named = scopesFile === undefined ? null : sorted(readFileSync(path(scopesFile), "utf8").trim().split(" for ")[0].split(",").filter(Boolean)); + const clear = async (file: string) => { await o.findings?.delete(findingKey("module", file, TOKEN_FILE_UNREVOKED)); }; + const keep = async (file: string, why: string) => { + o.log(`the token file ${file} stays: ${why}`); + const f = findingValue({ observer: "gitea", kind: TOKEN_FILE_UNREVOKED, id: file, at, + summary: `the token file ${file} under gitea's state directory stays: ${why}`, + headline: `gitea could not end the token file ${file}`, + explanation: `An earlier build of gitea kept its token in ${file}. The vault keeps the tokens now, so the file is revoked at the forge and ` + + `deleted at each start of the module; this one stays because ${why}. It is tried again at the next start; delete the token at the forge by hand and the file with it to end it.` }); + await o.findings?.put(f.key, f.value); + }; + for (const file of [o.base, `${o.base}.tmp`]) { + if (!existsSync(path(file))) continue; + const token = readFileSync(path(file), "utf8").trim().split("\n")[0].trim(); + if (!WHOLE.test(token)) { + rmSync(path(file), { force: true }); + o.log(`deleted the token file ${file}: it holds no whole token, so nothing is revoked at the forge`); + await clear(file); + continue; + } + const last = token.slice(-8); + let found: { account: string; id: number } | null = null; + if (named !== null) { + for (const [account, tokens] of o.lists) { + const t = tokens.find((x) => x.token_last_eight === last && sorted(x.scopes) === named); + if (t) { found = { account, id: t.id }; break; } + } + } + if (found === null) { + await keep(file, named === null ? "its scopes file is gone, so no token at the forge can be matched to it" : "no token at the forge matches its last eight characters and its scopes"); + continue; + } + const refused = await o.forge.revoke(found.account, found.id).catch((err) => err instanceof Error ? err.message : String(err)); + if (refused !== null) { + await keep(file, `the forge refused to revoke its token (${refused})`); + continue; + } + rmSync(path(file), { force: true }); + o.log(`revoked the token ${file} held, at the forge, and deleted ${file}`); + await clear(file); + } + // The scopes hold no token: they go when no token file of the pair remains. + if (![o.base, `${o.base}.tmp`].some((f) => existsSync(path(f)))) { + for (const f of [`${o.base}.scopes`, `${o.base}.scopes.tmp`]) { + if (existsSync(path(f))) { rmSync(path(f), { force: true }); o.log(`deleted ${f}`); } + } + } +} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go b/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go index 8b6fbd31d..fc834d0cc 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/forge_test.go @@ -153,7 +153,7 @@ func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *test kept := map[string]any{"name": "kept-builds", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024)}} // steps: a step's end over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313; // H2 H-A-412 addendum), read by the verb answer. - steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(128)}} + steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(64)}} // outputs: a run's test output, read by the verb output (design 47 H2 §791, §820: 1 GiB, 7 days). outputs := map[string]any{"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}} detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1), "max-mib": float64(8)}} diff --git a/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go b/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go index fc8ed61e9..d59364eda 100644 --- a/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go +++ b/modules/mesh-build-go/cmd/mesh-build-go/kit_test.go @@ -4,7 +4,9 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -46,7 +48,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // not answer as a transport fault, and a failure of the source (an unknown revision, a checksum) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its - // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + // first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603). t.Run("again-delays is declared and read", func(t *testing.T) { raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { @@ -65,7 +67,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { decl, ok := m.Config[steprun.AgainDelaysSetting] _ = json.Unmarshal(decl, &c) delay, err := steprun.AgainDelays(c.Default) - if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second { t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) } }) @@ -121,3 +123,59 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) { return m.Puller(nil, steprun.NewFakeAsks()) }) } + +// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step builds a fixture of each kind it builds (a bundle with the real +// go, an archive, a Go package) twice, in two workspace folders of other names and other file times, and the archive's digest is the same: nothing of +// the folder, the clock or the commit is in the program or its archive. +func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) { + if _, err := exec.LookPath("go"); err != nil { + t.Skip("NOT RUN: no go installed where this check runs") + } + fill := func(dir string) error { + module := filepath.Join(dir, "ws1", "tree", "modules", "demo") + files := map[string]string{ + "module.json": manifestWith(goBundle + `,{"name":"files","kind":"archive","from":"files"},` + + `{"name":"lib","kind":"package","language":"go","paths":["lib"]}`), + "files/a.txt": "a", + "files/b/c.txt": "c", + "lib/go.mod": "module git.example/demo/lib\n\ngo 1.26\n", + "lib/lib.go": "package lib\n", + "go.mod": "module demo\n\ngo 1.26\n", + "cmd/demo-tools/main.go": "package main\n\nimport \"fmt\"\n\nvar meshVersion, builtFor string\n\nfunc main() { fmt.Println(\"demo\", meshVersion, builtFor) }\n", + } + for name, body := range files { + if err := os.MkdirAll(filepath.Dir(filepath.Join(module, name)), 0o755); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil { + return err + } + } + return nil + } + conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) { + states := newStates() + m := moduleWith(states, "go1.27.1") + m.Home, m.Work, m.Cache = t.TempDir(), dir, t.TempDir() + m.Inside = true // the compile runs as itself: the kit's folders hold the whole difference + run := StepRunner(m.Home) + // no go.work of a folder above the kit's (a checker's, a placement's) takes the fixture into its workspace + m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran { + return run(ctx, append(env, "GOWORK=off"), name, args...) + } + withStore(t, m) + out := map[string]string{} + for _, artifact := range []string{"tools", "files", "lib"} { + args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact, "version": askedVersion} + if artifact == "lib" { + args["seat"] = GoPackageSeat + } + res, st := runBuildArgs(t, m, states, args) + if st.State != sdkstep.StepPassed { + return nil, fmt.Errorf("the build step of %s ended %s: %s", artifact, st.State, st.Reason) + } + out[artifact] = res.Digest + } + return out, nil + }) +} diff --git a/modules/mesh-build-go/module.json b/modules/mesh-build-go/module.json index 2de4a290b..8d9e51120 100644 --- a/modules/mesh-build-go/module.json +++ b/modules/mesh-build-go/module.json @@ -81,10 +81,10 @@ }, "again-delays": { "type": "string", - "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", "trusted": false, "runtime": true, - "default": "15s,60s" + "default": "15s,90s" }, "prune-mark": { "type": "number", @@ -131,7 +131,7 @@ "options": { "ttl-seconds": 172800, "objects-max-mib": 256, - "max-mib": 128 + "max-mib": 64 } }, { diff --git a/modules/mesh-build-image/cmd/mesh-build-image/build.go b/modules/mesh-build-image/cmd/mesh-build-image/build.go index 037583836..cb28d0ac1 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/build.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/build.go @@ -165,7 +165,10 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) { // --network pasta: a RUN step's network is pasta's, in user space. buildah's default for a rootless RUN is a // netavark bridge whose nftables rules cannot be applied for an account without a user session, so every RUN // failed before it started ("setup network: netavark: nftables error"; issue 1703, reproduced with buildah 1.45.2). - argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--tag", local, "--file", dockerfile) + // --timestamp 0: the image's creation time and the time of every file in its layers are the Unix epoch, so one source at one + // version is one digest in any folder at any time; no label or annotation below names a commit, a folder, a time or a node + // (design 47 H2 H-A-591 (3)). + argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--timestamp", "0", "--tag", local, "--file", dockerfile) if art.Target != "" { argv = append(argv, "--target", art.Target) } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/build_test.go b/modules/mesh-build-image/cmd/mesh-build-image/build_test.go index b8a6cdf14..69be6e909 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/build_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/build_test.go @@ -85,7 +85,7 @@ func TestBuildRunsBuildahRootlessAndAnswersTheDigest(t *testing.T) { } dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo") for _, want := range []string{ - "--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta", + "--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta", "--timestamp 0 ", "--file " + dir + "/Dockerfile", "--target final", "--build-arg DEMO_BASE=docker.io/library/busybox@sha256:0000000000000000000000000000000000000000000000000000000000000001", } { @@ -343,7 +343,7 @@ func TestTheImageBuildGetsTheVersionTheAskCarriesAsMeshVersion(t *testing.T) { } m, f, states = setup(t, same) runBuild(t, m, states, nil) - if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version")) { + if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version") || strings.Contains(bud[0].line, "--label")) { t.Fatalf("a build with no version: %+v", bud) } } diff --git a/modules/mesh-build-image/cmd/mesh-build-image/integration_test.go b/modules/mesh-build-image/cmd/mesh-build-image/integration_test.go index 0e71cd816..3240f5ab6 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/integration_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/integration_test.go @@ -10,6 +10,7 @@ package main import ( "context" "encoding/json" + "fmt" "os" "os/exec" "os/user" @@ -20,6 +21,7 @@ import ( sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance" ) func needTools(t *testing.T, what string, tools ...string) { @@ -159,6 +161,37 @@ func TestARealBuildAnswersTheImagesDigest(t *testing.T) { } } +// The kit's `reproducible` case over a real build (design 47 H2 H-A-591 (3), H-A-593 (3)): the image fixture, with no step that +// fetches, built by real buildah in two workspace folders of other names and other file times gives one manifest digest. +func TestARealImageBuildIsOneDigestInAnyFolder(t *testing.T) { + needTools(t, "a rootless build", "buildah", "newuidmap") + fill := func(dir string) error { + module := filepath.Join(dir, "ws1", "tree", "modules", "img") + if err := os.MkdirAll(module, 0o755); err != nil { + return err + } + for name, body := range map[string]string{ + "module.json": `{"module":"img","version":"1","build":{"artifacts":[{"name":"server","kind":"image","from":"Dockerfile"}]}}`, + "Dockerfile": "FROM scratch\nCOPY hello.txt /hello.txt\n", + "hello.txt": "hello\n", + } { + if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil { + return err + } + } + return nil + } + conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) { + m, states := realModule(t) + m.Work = dir + res, st := buildReal(t, m, states) + if st.State != sdkstep.StepPassed { + return nil, fmt.Errorf("the build step ended %s: %s", st.State, st.Reason) + } + return map[string]string{"server": res.Digest}, nil + }) +} + // needBase skips unless the build node can pull the small base the isolation Dockerfiles run in. func needBase(t *testing.T, m *Module) string { t.Helper() diff --git a/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go b/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go index 4fde49f59..a64cf7b9f 100644 --- a/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go +++ b/modules/mesh-build-image/cmd/mesh-build-image/kit_test.go @@ -32,7 +32,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // did not answer as a transport fault, and a failure of the source (a RUN line that fails) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its - // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + // first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603). t.Run("again-delays is declared and read", func(t *testing.T) { raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { @@ -51,7 +51,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { decl, ok := m.Config[steprun.AgainDelaysSetting] _ = json.Unmarshal(decl, &c) delay, err := steprun.AgainDelays(c.Default) - if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second { t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) } }) diff --git a/modules/mesh-build-image/module.json b/modules/mesh-build-image/module.json index 4ef6ba7b6..00c5606d6 100644 --- a/modules/mesh-build-image/module.json +++ b/modules/mesh-build-image/module.json @@ -46,10 +46,10 @@ }, "again-delays": { "type": "string", - "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", "trusted": false, "runtime": true, - "default": "15s,60s" + "default": "15s,90s" } }, "tools": [ diff --git a/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go b/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go index ddadfe488..cdf5b4235 100644 --- a/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go +++ b/modules/mesh-build-node/cmd/mesh-build-node/kit_test.go @@ -43,7 +43,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) { // not answer as a transport fault, and a failure of the source (a package the registry lacks) as none. func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { // A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its - // first run and 60 s after its second by default (design 47 H2 §799; H-A-390). + // first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603). t.Run("again-delays is declared and read", func(t *testing.T) { raw, err := os.ReadFile(filepath.Join("..", "..", "module.json")) if err != nil { @@ -62,7 +62,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) { decl, ok := m.Config[steprun.AgainDelaysSetting] _ = json.Unmarshal(decl, &c) delay, err := steprun.AgainDelays(c.Default) - if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second { + if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second { t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err) } }) @@ -115,3 +115,24 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) { return m.Puller(nil, steprun.NewFakeAsks()) }) } + +// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step packs a fixture bundle twice, in two +// workspace folders of other names and other file times (the compiler and the bundler stand in, as in every build test of this +// module, and write what they would from the same source), and the archive's digest is the same: nothing of the folder or +// the clock is in the pack. +func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) { + conformance.Reproducible(t, func(dir string) error { + workspaceWith(t, dir, map[string]string{"modules/m/module.json": strings.Replace(bundleManifest, "%s", "", 1), + "modules/m/tools/index.ts": "export {}"}) + return nil + }, func(dir string) (map[string]string, error) { + m, f, _ := newMachine(t) + m.Work = dir + f.effect = esbuildEffect(t) + out, err := m.build(context.Background(), buildArgs()) + if err != nil { + return nil, err + } + return map[string]string{"tools": out.(BuildResult).Digest}, nil + }) +} diff --git a/modules/mesh-build-node/module.json b/modules/mesh-build-node/module.json index b0a1f50f4..ededee9ac 100644 --- a/modules/mesh-build-node/module.json +++ b/modules/mesh-build-node/module.json @@ -50,10 +50,10 @@ }, "again-delays": { "type": "string", - "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", + "description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.", "trusted": false, "runtime": true, - "default": "15s,60s" + "default": "15s,90s" }, "prune-mark": { "type": "number", diff --git a/modules/mesh-config/cmd/mesh-config/main.go b/modules/mesh-config/cmd/mesh-config/main.go index 383708344..3d1a2d9d5 100644 --- a/modules/mesh-config/cmd/mesh-config/main.go +++ b/modules/mesh-config/cmd/mesh-config/main.go @@ -58,6 +58,30 @@ func (r runtimeStore) Get(state, key string) (*Entry, error) { return &Entry{Key: e.Key, Value: e.Value, Revision: e.Revision}, nil } +// Away is the fault `away` while a copy of this module's own states is not read yet: a verb or tool handler asks it +// (asking), the module's own start never does (design 47 H2 H-A-708 (2)). The first views of the owners stay the fault +// `away` at the read itself, since a picture not answered yet is no answer for a pass to resolve from. +func (r runtimeStore) Away() error { + if r.own == nil { + return nil + } + return r.own.Unread() +} + +// asking is a tool whose handler answers `away` at once while what it reads is not read yet (design 47 H2 H-A-708 (2)). +func asking(c *Config, t stdio.Tool) stdio.Tool { + run := t.Run + t.Run = func(a map[string]any) (any, error) { + if s, ok := c.Store.(interface{ Away() error }); ok { + if err := s.Away(); err != nil { + return nil, err + } + } + return run(a) + } + return t +} + func (r runtimeStore) Put(state, key string, value any) error { if r.own != nil && ownStates[state] { return r.own.write(state, key, value) @@ -149,6 +173,7 @@ func main() { } } } + own.follow() c := &Config{Store: runtimeStore{own: own}, Logf: logf, Asks: runtimeAsks{}, Delivery: toolDelivery{ask: stdio.Ask}, Vault: toolVault{ask: stdio.Ask, recorder: recorder}} // The module's one held writer (design 47 G §689, A-16, A-29, A-32): the renames' and retirements' findings and the views reader's go through it. @@ -417,7 +442,11 @@ func Tools(c *Config) []stdio.Tool { rows, err := c.Renames(strings.TrimSpace(m), true) return map[string]any{"renames": seatRenames(rows)}, err }} - return append(append(switchTools(c), viewTools(c, func() *ownerViews { return theViews })...), renames, stdio.Tool{ + var own []stdio.Tool + for _, t := range switchTools(c) { + own = append(own, asking(c, t)) + } + return append(append(own, viewTools(c, func() *ownerViews { return theViews })...), asking(c, renames), asking(c, stdio.Tool{ Name: Seat + "." + Verb, Description: "Set, clear, list or read the history of config values (novox/hq ADR 0348). A value is set at " + "one level: mesh config (no module, no node) or node config (a node) for a predefined key, or a " + @@ -451,7 +480,7 @@ func Tools(c *Config) []stdio.Tool { call.Caller = stdio.CallerOf(args) return c.Do(call) }, - }) + })) } // callOf reads a call's arguments strictly: an argument it does not know is refused, not ignored. diff --git a/modules/mesh-config/cmd/mesh-config/ownerviews.go b/modules/mesh-config/cmd/mesh-config/ownerviews.go index 8ff66ee26..a0d0037d3 100644 --- a/modules/mesh-config/cmd/mesh-config/ownerviews.go +++ b/modules/mesh-config/cmd/mesh-config/ownerviews.go @@ -95,22 +95,15 @@ func (o *ownerViews) read(state string) (*views.Follower, bool) { return f, ok } -// errUnanswered says a first view is not answered yet: a reader waits, and its next resolution reads it. -func errUnanswered(f *views.Follower) error { - s := f.Status() - return fmt.Errorf("the first view of %s's %s is not answered yet (%s asked %d times)", s.Owner, s.State, s.Tool, s.Asks) -} - // get is one key of a followed state. func (o *ownerViews) get(state, key string) (*Entry, bool, error) { f, ok := o.read(state) if !ok { return nil, false, nil } - select { - case <-f.Ready(): - default: - return nil, true, errUnanswered(f) + // A first view not answered yet is the fault `away`, naming the view's owner verb (design 47 H2 H-A-708 (2)). + if err := f.Unread(); err != nil { + return nil, true, err } v, held := f.Get(key) if !held { @@ -125,10 +118,8 @@ func (o *ownerViews) keys(state string) ([]string, bool, error) { if !ok { return nil, false, nil } - select { - case <-f.Ready(): - default: - return nil, true, errUnanswered(f) + if err := f.Unread(); err != nil { + return nil, true, err } var out []string for k := range f.Values() { diff --git a/modules/mesh-config/cmd/mesh-config/ownerviews_test.go b/modules/mesh-config/cmd/mesh-config/ownerviews_test.go index 908f6eedb..d961539fa 100644 --- a/modules/mesh-config/cmd/mesh-config/ownerviews_test.go +++ b/modules/mesh-config/cmd/mesh-config/ownerviews_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/views" ) @@ -33,7 +34,10 @@ func TestAFollowedStateIsReadFromItsOwnersFirstViewAndEvents(t *testing.T) { } var changed atomic.Int32 o := newOwnerViews(ask, func() { changed.Add(1) }, nopFindings{}) - if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || err == nil || !strings.Contains(err.Error(), "not answered yet") { + // H-A-708 (2): a read before the first view is answered `away`, naming the view's owner verb, at once. + var away *busretry.Away + if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || !errors.As(err, &away) || away.Part != "mesh-delivery-assigner.assigner_read_wants" || + !strings.HasPrefix(away.Words, "not read yet since ") { t.Fatalf("before the first view: followed %v, %v", followed, err) } if !o.reader.Follows("mesh-delivery-assigner.wants") { diff --git a/modules/mesh-config/cmd/mesh-config/ownstates.go b/modules/mesh-config/cmd/mesh-config/ownstates.go index b27778d50..e1c7e3a1a 100644 --- a/modules/mesh-config/cmd/mesh-config/ownstates.go +++ b/modules/mesh-config/cmd/mesh-config/ownstates.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "sort" stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -36,6 +37,8 @@ func newOwnCopy() *ownCopy { } func (o *ownCopy) get(state, key string) (*Entry, error) { + // A read waits for a state whose copy is not read yet: the module's own start (the first decision, the deadline, the + // start judgement) is one. A verb or tool handler asks Unread first (design 47 H2 H-A-708 (2)). raw, ok, err := o.copy.Get(state, key) if err != nil || !ok { return nil, err @@ -43,7 +46,34 @@ func (o *ownCopy) get(state, key string) (*Entry, error) { return &Entry{Key: key, Value: raw}, nil } -func (o *ownCopy) keys(state string) ([]string, error) { return o.copy.Keys(state) } +func (o *ownCopy) keys(state string) ([]string, error) { + return o.copy.Keys(state) +} + +// Unread is the fault `away` naming the first state, in name order, whose copy is not read yet, nil when every one is: a +// verb or tool handler asks it before it reads, so a call made while the module starts is answered at once (design 47 H2 +// H-A-708 (2)); the module's own reads wait for the copy. +func (o *ownCopy) Unread() error { + states := make([]string, 0, len(ownStates)) + for state := range ownStates { + states = append(states, state) + } + sort.Strings(states) + for _, state := range states { + if err := o.copy.Unread(state); err != nil { + return err + } + } + return nil +} + +// follow starts the watch of every state the copy holds, each on its goroutine, so a handler's ask is answered `away` until +// the copy is read (Unread; design 47 H2 H-A-708 (2)). +func (o *ownCopy) follow() { + for state := range ownStates { + go o.copy.Follow(state, nil) + } +} // write puts a key and takes it into the copy at the revision the bus answered. func (o *ownCopy) write(state, key string, value any) error { diff --git a/modules/mesh-config/cmd/mesh-config/quiet_test.go b/modules/mesh-config/cmd/mesh-config/quiet_test.go index 77861b841..0036270b3 100644 --- a/modules/mesh-config/cmd/mesh-config/quiet_test.go +++ b/modules/mesh-config/cmd/mesh-config/quiet_test.go @@ -16,6 +16,7 @@ import ( occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/busretry" ) // countingStore counts the reads of the states by state: what the bus would be asked. @@ -203,6 +204,24 @@ func TestAnOwnStateIsReadFromItsWatchedCopyNotKeyByKey(t *testing.T) { } n := len(b.held[ValuesState]) own := b.ownCopy() + // H-A-708 (2): a handler asks Unread and is answered `away` at once, naming the state; the module's own read waits for the + // copy, which the start's watch reads, so its first decision and its deadline are never lost to `away`. + var away *busretry.Away + if err := own.Unread(); !errors.As(err, &away) || !strings.HasPrefix(away.Part, "the state ") || !strings.HasPrefix(away.Words, "not read yet since ") { + t.Fatalf("before the copy is read: %v", err) + } + c := &Config{Store: runtimeStore{own: own}} + ran := false + tool := asking(c, stdio.Tool{Name: "t", Run: func(map[string]any) (any, error) { ran = true; return nil, nil }}) + if _, err := tool.Run(nil); !errors.As(err, &away) || ran { + t.Fatalf("a tool's handler before the copy is read: ran %v, %v", ran, err) + } + waited := make(chan error, 1) + go func() { _, err := own.keys(ValuesState); waited <- err }() + own.copy.Follow(ValuesState, nil) + if err := <-waited; err != nil { + t.Fatalf("the module's own read before the copy is read must wait for it, not answer away: %v", err) + } for pass := 0; pass < 3; pass++ { keys, err := own.keys(ValuesState) if err != nil || len(keys) != n { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go index 65e5fce31..c3beeac72 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go @@ -20,6 +20,7 @@ import ( oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" + meshdelivery "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" stdio "git.novox.be/novox/mesh-sdk/go" "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats.go" @@ -134,6 +135,43 @@ type runtime struct { operatorCancels []string // owedSaid are the subjects of the seat events owed the gate said, in order (W11.17). owedSaid []string + // endedSaid are the bodies of the record-ended events the gate said, in order (AC-G4a, AC-G4b). + endedSaid []json.RawMessage + // logs is what the bundle said in its journal. + logs *testLog +} + +// endedSays are the end counts the gate said record-ended with for a record, in order. +func (r *runtime) endedSays(record string) []int64 { + r.mu.Lock() + defer r.mu.Unlock() + var out []int64 + for _, raw := range r.endedSaid { + var e struct { + Record string `json:"record"` + Ends int64 `json:"ends"` + } + if json.Unmarshal(raw, &e) == nil && e.Record == record { + out = append(out, e.Ends) + } + } + return out +} + +// journalHas is whether the bundle said a line in its journal holding every one of words. +func (r *runtime) journalHas(words ...string) bool { + r.logs.mu.Lock() + defer r.logs.mu.Unlock() + for _, l := range r.logs.said { + all := true + for _, w := range words { + all = all && strings.Contains(l, w) + } + if all { + return true + } + } + return false } type askedOfMesh struct { @@ -154,19 +192,28 @@ func (b *testBus) start(t *testing.T) *runtime { if err != nil { t.Fatal(err) } - cmd.Stderr = testLog{t} + logs := &testLog{t: t} + cmd.Stderr = logs if err := cmd.Start(); err != nil { t.Fatal(err) } - r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64)} + r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64), logs: logs} go r.read(out) t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() }) return r } -type testLog struct{ t *testing.T } +// testLog is the bundle's journal: said in the test's log, and kept for journalHas. +type testLog struct { + t *testing.T + mu sync.Mutex + said []string +} -func (w testLog) Write(p []byte) (int, error) { +func (w *testLog) Write(p []byte) (int, error) { + w.mu.Lock() + w.said = append(w.said, string(p)) + w.mu.Unlock() defer func() { _ = recover() }() // the bundle may speak after the test ended w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n")) // Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once @@ -322,6 +369,11 @@ func (r *runtime) answer(m rpcMessage) { r.operatorAsks = append(r.operatorAsks, a) r.mu.Unlock() } + if p.Subject == meshdelivery.SubjectRecordEnded { + r.mu.Lock() + r.endedSaid = append(r.endedSaid, p.Body) + r.mu.Unlock() + } if strings.HasPrefix(p.Subject, "mesh.seat.mesh-delivery.event.owed.") { r.mu.Lock() r.owedSaid = append(r.owedSaid, p.Subject) @@ -400,13 +452,31 @@ func (r *runtime) answer(m rpcMessage) { return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key) } switch m.Method { - case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove: + case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove, buscalls.LedgerWatch: // The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory. r.b.mu.Lock() defer r.b.mu.Unlock() if r.b.ledger == nil { r.b.ledger = newLedgerFake(r.t) } + if m.Method == buscalls.LedgerWatch { + // The tool runner's ledger watch (design 47 H2 H-A-706): the current states first, each handed to the bundle as a + // `mesh/ledger` call named by the watch's id, then each change the ledger makes; answered once the current are sent. + var in buscalls.LedgerWatchRequest + if err := json.Unmarshal(m.Params, &in); err != nil { + return nil, err + } + err := r.b.ledger.Watch(in.Instances, func(instance string, state json.RawMessage) error { + r.mu.Lock() + n := r.next + r.next++ + r.mu.Unlock() + r.say(map[string]any{"id": fmt.Sprintf("ledger-%d", n), "method": buscalls.LedgerWatched, + "params": buscalls.InstanceChange{Watch: in.Watch, Instance: instance, State: state}}) + return nil + }) + return map[string]any{}, err + } if m.Method == buscalls.LedgerQuery { var in buscalls.QueryRequest if err := json.Unmarshal(m.Params, &in); err != nil { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go index f61195ae0..ba22da41c 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go @@ -63,6 +63,7 @@ var stepFamilies = []stepFamily{ // runner's pipeline-started, pipeline-ended, wait-held and wait-ended on ., the assigner's wanted on // . and pipeline-wanted on ., and the node-engine seat's running on .. seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted), + seatFamily(runner.EventMoverAdded, 2, false, decodeMoverAdded), seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded), seatFamily(runner.EventWaitHeld, 2, false, decodeWait), seatFamily(runner.EventWaitEnded, 2, false, decodeWait), @@ -247,9 +248,11 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string { return "" } -// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one +// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, one // that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown -// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)). +// away), or one that ended before a running of its movers was heard (H-A-585: the running is applied to it, and its end +// written again from it, Records.RanAfterEnd). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, +// H-A-89 (4)). func (c *StepConsumer) apply(o StepOutcome, event string) error { records, err := c.Records.Kept() if err != nil { @@ -258,12 +261,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error { for _, r := range records { _, fromAway := r.Away[o.Node] fromAway = fromAway && o.Node != "" - if (r.Ended != nil && !fromAway) || !holds(r, o) { + ranAfter := r.Ended != nil && o.Step == StepRunning && o.Outcome == OutcomeRunning + if (r.Ended != nil && !fromAway && !ranAfter) || !holds(r, o) { continue } ro := RecordOutcome{Module: o.Module, Fingerprint: o.Fingerprint, Node: o.Node, Step: o.Step, Outcome: o.Outcome, Why: o.Why, At: o.At, Event: event} - if _, err := c.Records.Outcome(r, ro); err != nil { + applied, err := c.Records.Outcome(r, ro) + if err != nil { return err } if fromAway { @@ -271,6 +276,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error { return err } } + if ranAfter { + // The running as the record keeps it, applied now or by an event offered again after its end could not be + // written. + kept := r.Outcomes[OutcomeKey(o.Module, o.Fingerprint, o.Node, o.Step)] + if err := c.Records.RanAfterEnd(r, kept, applied); err != nil { + return err + } + } } return nil } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go index e9c5afe16..ef18861c1 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/findings.go @@ -29,7 +29,7 @@ type FindingWriter interface { // generated contract of the seat that defines it (A-17). It is started once the runtime serves (A-40). func NewFindingWriter() (*views.HeldWriter[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent], error) { return views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{ - Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge}}) + Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge, IndexBehind, RecordEndUnwritten}}) } // recordTooLarge raises record-too-large for a delivery record's entry the gate refused over EntryLimit, its subject the @@ -69,3 +69,75 @@ func (h *Holder) recordTooLarge(record, instance string, bytes int, raised bool) h.Logf("[mesh-delivery] record-too-large of %s (%s) is not said: %v", instance, record, err) } } + +// The findings of the gate's ledger indexes and of an end not written (design 47 H2 H-A-690 (3), (4)). +const ( + // IndexBehind has the ledger index for its id: a call that keeps it failed, or `lag` still names it behind after its whole + // reindex; cleared at the next `lag` that names it not behind. + IndexBehind = "index-behind" + // RecordEndUnwritten has the record's instance for its id: the end of a mover or an act, or its emptying at a reopening, + // was not written; cleared when the pass for the record writes it. + RecordEndUnwritten = "record-end-unwritten" +) + +// indexBehind raises index-behind for a ledger index with why, or clears it (Records.IndexBehind). +func (h *Holder) indexBehind(index, why string, behind bool) { + if h.Findings == nil { + return + } + var err error + if behind { + now := h.Now().UTC() + err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: index, Kind: IndexBehind, + Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now, + Summary: fmt.Sprintf("the index %s of the delivery records is behind its history: %s", index, why), + Headline: "A delivery record index is behind", Subject: meshconditions.Subject{Scope: FindingScope, ID: index}, + Explanation: "The gate keeps the index by a call of the tool runner's repair reindex at each change; it clears at the " + + "next lag that names the index not behind (the gate's next start, or after ledger_reindex by hand)."}) + } else if h.heldFinding(IndexBehind, index) { + err = h.Findings.Clear(context.Background(), FindingScope, index, IndexBehind, "lag names the index not behind") + } + if err != nil && h.Logf != nil { + h.Logf("[mesh-delivery] index-behind of %s is not said: %v", index, err) + } +} + +// endUnwritten raises record-end-unwritten for a record, naming the instance and the error, or clears it +// (Records.EndUnwritten). +func (h *Holder) endUnwritten(record, instance string, cause error, raised bool) { + if h.Findings == nil { + return + } + var err error + if raised { + now := h.Now().UTC() + what := record + if instance != "" { + what = instance + } + err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: record, Kind: RecordEndUnwritten, + Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now, + Summary: fmt.Sprintf("the end of %s of the record %s is not written: %v", what, record, cause), + Headline: "A delivery record's end is not written to all its entries", Subject: meshconditions.Subject{Scope: FindingScope, ID: record}, + Explanation: "A mover or an act of the record does not hold the record's end, so its key does not take the lifetime of the " + + "end. The gate writes it at the record's next event, or at its next start, and the finding clears when it is written."}) + } else if h.heldFinding(RecordEndUnwritten, record) { + err = h.Findings.Clear(context.Background(), FindingScope, record, RecordEndUnwritten, "the end is written to every entry") + } + if err != nil && h.Logf != nil { + h.Logf("[mesh-delivery] record-end-unwritten of %s is not said: %v", record, err) + } +} + +// heldFinding is whether the writer holds the finding of the kind under the id. +func (h *Holder) heldFinding(kind, id string) bool { + if h.Findings == nil { + return false + } + for _, f := range h.Findings.Held() { + if f.Scope == FindingScope && f.Kind == kind && f.ID == id { + return true + } + } + return false +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go index a8658de1f..c2c1d608f 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/main.go @@ -16,6 +16,8 @@ import ( "sync" "time" + ownmanifest "mesh-delivery-gate" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" stdio "git.novox.be/novox/mesh-sdk/go" ) @@ -61,9 +63,16 @@ func main() { } h.init() h.SaySeat = stdio.SeatPublish - h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, + h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge, Class: seatCatalog{ask: stdio.Ask}.Class} h.Records.Changed = h.recordChanged + h.Records.IndexBehind, h.Records.EndUnwritten = h.indexBehind, h.endUnwritten + h.Records.EndPending = func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) } + var daysErr error + if h.Records.KeepingDays, h.Records.EndedDays, daysErr = ownmanifest.RecordsDays(); daysErr != nil { + logf("%v", daysErr) + os.Exit(1) + } h.Forge = seatGit{ask: stdio.Ask} h.Catalog = seatCatalog{ask: stdio.Ask} h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn, @@ -98,6 +107,20 @@ func main() { // tick, no forge poll, no reconcile loop. Each step is retried, each failure said, never given up on quietly. func run(h *Holder, l *listening) { <-stdio.Served() // Serve first: the state is reached through it, and an event is heard from as soon as it serves + // The indexes first: built again where behind, each record's movers and acts given its end, then watched (H-A-690 (2)). + for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) { + err := h.Records.KeepIndexes() + if err == nil { + break + } + l.set("not yet: " + err.Error()) + logf("[mesh-delivery] the record indexes are not kept yet (%v); asking again in %s", err, wait) + time.Sleep(wait) + } + // The acts owed to the forge that have no outcome are said again, once the records are read after the indexes (G §165). + h.applying.Lock() + h.sayUnanswered("the gate's start") + h.applying.Unlock() go h.Work() for _, pattern := range followed { pattern := pattern @@ -154,7 +177,13 @@ func take(h *Holder, e stdio.Envelope) error { h.applying.Lock() defer h.applying.Unlock() if h.Consumer != nil && h.Consumer.Takes(e.Key) { - return h.Consumer.Hear(e) + err := h.Consumer.Hear(e) + if err == nil && bridgeRunning(e.Key) { + // The forge bridge runs (again): its answer to an act owed is heard whichever of it and the gate was delivered + // first (H-A-717, DQ-51). + h.sayUnanswered("the forge bridge runs") + } + return err } if stdio.TopicMatches(headMovedEvent, e.Key) { return h.HeadMoved(e) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go index 304fee87e..ea99aa79e 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/manifest_test.go @@ -117,7 +117,7 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) { } // The names move (milestone 47/G): the families heard from another module are its manifest's consumes, and no Go // source of the gate names those modules. - if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 8 { + if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 9 { t.Fatalf("owed.ended is %q and the step families %+v, not the manifest's consumes %v", owedEndedEvent, stepFamilies, m.Consumes) } for _, f := range stepFamilies { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go index c21674dd2..2712ac830 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/mergecall_bus_test.go @@ -111,6 +111,35 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) { want.Round(time.Minute)) } + // AC-G4b (H-A-609 (2), H-A-617, H-A-728), over the bus: a mover-added counts its mover in the record its pipeline names, a + // pipeline-ended of a higher end count reopens the ended record, and its next end says record-ended with ends 2. + rt.until("the first end said record-ended with ends 1", eventWithin, func() bool { + says := rt.endedSays(instance) + return len(says) == 1 && says[0] == 1 + }) + b.publish(t, "mesh.seat.mesh-pipeline-runner.event.mover-added."+escaped+".1", map[string]any{"v": 1, "pipeline": recordMilestone(branch, 1), + "revision": 4, "module": "extra", "fingerprint": "x", "from": recordMilestone(branch, 1) + ".again.1"}) + added, _ := MoverInstance(recordMilestone(branch, 1), "extra") + rt.until("the added mover counted in the record that carries its pipeline", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + return strings.Contains(string(b.ledger.states[added]), `"module":"extra"`) + }) + b.publish(t, "mesh.seat.mesh-pipeline-runner.event.pipeline-ended."+escaped+".1", map[string]any{"v": 1, "branch": branch, "source": 1, + "pipeline": recordMilestone(branch, 1), "outcome": "passed", "end-count": 2, "movers": []any{}}) + rt.until("the record reopened by the pipeline's higher end", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + reopened := Record{} + return json.Unmarshal(b.ledger.states[instance], &reopened) == nil && reopened.Ended == nil && reopened.PipelineEnds == 2 + }) + b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".1", map[string]any{"v": 1, "branch": branch, + "source": 1, "pipeline": recordMilestone(branch, 1), "outcome": "running"}) + rt.until("the reopened record ended again with ends 2", eventWithin, func() bool { + says := rt.endedSays(instance) + return len(says) == 2 && says[1] == 2 + }) + // GT1 (design 47 H2 §809; H-A-385, H-A-391, H-A-453 (3), H-A-455): a record of 126 movers writes 127 entries, its head // and one per mover, and its acts owed the forge each an entry of its own, none over 64 KiB, the head counting 126 and // holding no act; an entry made too large raises record-too-large, and the record's end clears it. @@ -179,6 +208,46 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) { b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".2", map[string]any{"v": 1, "branch": branch, "source": 2, "pipeline": recordMilestone(branch, 2), "outcome": "running"}) rt.until("record-too-large cleared at the record's end", eventWithin, func() bool { return !findingHeld(ctx, b, RecordTooLarge, "") }) + // H-A-585: the record ended on pipeline-wanted before any of its movers' running was applied, with no delivery time; a + // running of one of them heard after takes it, its ended and delivery-time written again, and says so in the journal. + late := taken[1].(map[string]any) + b.publish(t, "mesh.seat.node-engine.event.running.test."+late["module"].(string), map[string]any{"v": 1, "module": late["module"], + "node": "test", "fingerprint": late["fingerprint"], "at": time.Now().UTC().Format(time.RFC3339)}) + var ended2 Record + rt.until("the ended record's delivery time written from a running heard after its end", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + ended2 = Record{} + return json.Unmarshal(b.ledger.states[instance2], &ended2) == nil && ended2.Ended != nil && ended2.DeliveryTime != "" + }) + rt.until("the journal line naming the record, the mover on test and both times", eventWithin, func() bool { + return rt.journalHas(instance2, late["module"].(string)+" on test", "after it ended") + }) + // AC-G4a (H-A-597, H-A-609 (2)), over the bus: the late running said record-ended again with ends 2, and the same running + // heard again moves nothing and says nothing. A running from a machine that was away at the end cannot be heard here: no + // event of the gate's marks a machine away (only the unit tests mark one). + rt.until("record-ended said again with ends 2", eventWithin, func() bool { + says := rt.endedSays(instance2) + return len(says) == 2 && says[0] == 1 && says[1] == 2 + }) + endedAt := ended2.Ended.At + b.publish(t, "mesh.seat.node-engine.event.running.test."+late["module"].(string), map[string]any{"v": 1, "module": late["module"], + "node": "test", "fingerprint": late["fingerprint"], "at": time.Now().Add(time.Minute).UTC().Format(time.RFC3339)}) + b.publish(t, "mesh.seat.mesh-pipeline-runner.event.mover-added."+escaped+".2", map[string]any{"v": 1, "pipeline": recordMilestone(branch, 2), + "revision": 4, "module": "witness", "fingerprint": "w", "from": recordMilestone(branch, 2) + ".again.1"}) + witness, _ := MoverInstance(recordMilestone(branch, 2), "witness") + rt.until("the event heard after the repeated running", eventWithin, func() bool { + b.mu.Lock() + defer b.mu.Unlock() + return strings.Contains(string(b.ledger.states[witness]), `"module":"witness"`) + }) + b.mu.Lock() + again := Record{} + err = json.Unmarshal(b.ledger.states[instance2], &again) + b.mu.Unlock() + if says := rt.endedSays(instance2); err != nil || again.Ends != 2 || !again.Ended.At.Equal(endedAt) || len(says) != 2 { + t.Errorf("a repeated running left the record at end %d, ended %v (was %v), said %v: want it unchanged, ends 2", again.Ends, again.Ended, endedAt, says) + } // The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing. seeded := strings.Repeat("5", 40) diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go index 8e3ca90ea..80649aaca 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/movers.go @@ -29,11 +29,12 @@ const MoversIndex = "movers" // The operations of a mover's entry; the manifest's type mover declares exactly these (record_test.go). const ( OpMover = "mover" // set-fields: its record's key, its module, its class, its pipeline and its version - // OpEntry and OpOutcome write its entries and outcomes as they did on the whole record. + // OpEntry and OpOutcome write its entries and outcomes as they did on the whole record; OpEnd (record.go) gives it the + // head's ended, its type's ends-with (design 47 H2 H-A-634 (2)). ) // MoverOperations are a mover's operations, in the order the manifest's type allows them. -var MoverOperations = []string{OpMover, OpEntry, OpOutcome} +var MoverOperations = []string{OpMover, OpEntry, OpOutcome, OpEnd} // OpMovers is the head entry's count of its movers (set-fields movers). const OpMovers = "movers" @@ -59,6 +60,8 @@ type Mover struct { Class string `json:"class,omitempty"` Entries map[string]RecordEntry `json:"entries,omitempty"` Outcomes map[string]RecordOutcome `json:"outcomes,omitempty"` + // Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)). + Ended *RecordEnded `json:"ended,omitempty"` } // Running are the machines the mover runs healthy on, each with when it was first said. diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go index b297ff9dc..8bcedd25d 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts.go @@ -7,6 +7,7 @@ import ( "strconv" "strings" + nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" ) @@ -114,3 +115,60 @@ func endedFailedOrHeld(r *Record) string { sort.Strings(lines) return fmt.Sprintf("The delivery record %s ended (%s), with outcomes failed or held:\n%s", r.Instance, r.Ended.Why, strings.Join(lines, "\n")) } + +// sayUnanswered says again, under each act's id and first said time, every act of every record kept that has no outcome yet +// (design 47 G §165, H-A-712 (3), H-A-717 on DMC-15), with one journal line naming the count and why: the owner of the act +// answers one it performed already by its kept outcome. An act that cannot be said is counted and shown as refused; the +// others go on. The caller holds the gate's applying lock where events may be heard. +func (h *Holder) sayUnanswered(why string) { + if h.Owed == nil || h.Records == nil { + return + } + kept, err := h.Records.Kept() + if err != nil { + h.Refuse(fmt.Errorf("the acts owed to the forge are not said again (%s): the records are not read: %w", why, err)) + return + } + said, failed := 0, 0 + for _, r := range kept { + ids := make([]string, 0, len(r.Acts)) + for id, a := range r.Acts { + if a.Outcome == "" { + ids = append(ids, id) + } + } + sort.Strings(ids) + for _, id := range ids { + a := r.Acts[id] + o := a.Owed + o.Record = r.Milestone + if o.ID == "" { + o.ID = a.ID + } + if o.Said == nil { + at := a.At + o.Said = &at + } + if err := h.Owed.Say(o); err != nil { + failed++ + h.Refuse(fmt.Errorf("the %s owed on %s#%d for the record %s is not said again: %w", a.Act, a.Repository, a.Number, r.Instance, err)) + continue + } + said++ + } + } + if h.Logf != nil { + h.Logf("[mesh-delivery] %s: %d acts owed to the forge without an outcome said again, %d not said", why, said, failed) + } +} + +// bridgeRunning is whether the key is the node-engine seat's running of the module that owns the event owed.ended, the forge +// bridge, found from the manifest's consumes (the gate names no other module in code): `.running..`. +func bridgeRunning(key string) bool { + owner, _, ok := strings.Cut(owedEndedEvent, ".") + if !ok || owner == "" { + return false + } + parts := strings.Split(key, ".") + return len(parts) == 4 && parts[1] == nodeengine.EventRunning && parts[3] == owner +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go index 30c7c83b0..b5d478df8 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedacts_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "fmt" "strings" "testing" "time" @@ -179,3 +180,47 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing. } }) } + +// Design 47 G §165, H-A-712 (3), H-A-717 (DMC-15, DQ-51): the gate says again, at its start and when it hears the forge bridge's +// module running, every act owed that has no outcome, under its id and first said time, with one journal line naming the count. +func TestTheGateSaysItsUnansweredActsAgain(t *testing.T) { + at := time.Date(2026, 11, 25, 17, 0, 0, 0, time.UTC) + head := strings.Repeat("1", 40) + var journal []string + rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }} + first := &sayerFake{} + h := &Holder{Now: func() time.Time { return at }, Owed: first, Records: rs, Logf: func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }} + rs.Changed = h.recordChanged + r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@7": head})) + if err != nil { + t.Fatal(err) + } + if err := rs.AddEntry(r, RecordEntry{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace"}); err != nil { + t.Fatal(err) + } + if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt}); err != nil || len(first.said) != 2 { + t.Fatalf("%v, said %d", err, len(first.said)) + } + // One act is answered: it is not said again. + answered := first.said[0] + body, err := forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, ID: answered.ID, Of: seat.Seat, Outcome: forgemsg.OwedNotNeeded, Words: "closed", At: at}) + if err != nil { + t.Fatal(err) + } + if err := h.OwedEnded(body); err != nil { + t.Fatal(err) + } + again := &sayerFake{} + h.Owed = again + h.sayUnanswered("the gate's start") + if len(again.said) != 1 || again.said[0].ID != first.said[1].ID || again.said[0].Said == nil || !again.said[0].Said.Equal(*first.said[1].Said) || + len(journal) != 1 || !strings.Contains(journal[0], "1 acts owed to the forge without an outcome said again") { + t.Fatalf("said %+v, journal %v", again.said, journal) + } + for key, want := range map[string]bool{"node-engine.running.ace.mesh-delivery-forge-bridge": true, "node-engine.running.ace.mesh-x": false, + "node-engine.wait-held.ace.mesh-delivery-forge-bridge": false} { + if got := bridgeRunning(key); got != want { + t.Errorf("bridgeRunning(%s) is %v", key, got) + } + } +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go index d8e6e6319..858423576 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/owedended.go @@ -71,6 +71,8 @@ type RecordAct struct { Words string `json:"words,omitempty"` At time.Time `json:"at"` Owed seat.Owed `json:"owed"` + // Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)). + Ended *RecordEnded `json:"ended,omitempty"` } // TypeAct is the ledger type of an act's entry, and ActsIndex the ledger's index of the acts' entries on their record's key @@ -81,7 +83,7 @@ const ( ) // ActOperations are an act's operations, in the order the manifest's type act allows them. -var ActOperations = []string{OpAct} +var ActOperations = []string{OpAct, OpEnd} // ActInstance is the entry of a record's act: `act/`, escaped as a name. func ActInstance(milestone, id string) (string, error) { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go index b7f4804ee..58a428756 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record.go @@ -64,10 +64,6 @@ var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpMovers, OpPhases, Op // HeldOperations are the month's list's operations. var HeldOperations = []string{OpHold, OpDrop} -// DefaultRecordRetention is how long a record is kept when the setting record-retention gives none (design 47: 90 days -// covers every trace the operator has asked of a past delivery so far). -const DefaultRecordRetention = 90 * 24 * time.Hour - // Record is a delivery record's state, as apply derives it from its operations. type Record struct { // Instance is the record's path in the ledger; not in the state. @@ -99,6 +95,11 @@ type Record struct { // entry of its own, joined when read, never on the head entry (design 47 H2 §809, H-A-455 (1)). Acts map[string]RecordAct `json:"acts,omitempty"` Ended *RecordEnded `json:"ended,omitempty"` + // Ends is the record's end count, one higher at each end and said by record-ended; PipelineEnds the highest + // pipeline-ended end count the record heard: a pipeline-ended of a higher count reopens it. Both absent read as 0, and a + // reopening empties neither (design 47 H2 H-A-728, H-A-597, H-A-609 (2), H-A-617). + Ends int `json:"ends,omitempty"` + PipelineEnds int `json:"pipeline-ends,omitempty"` // Recovery marks the merge its author named a recovery by the seat's verb recovery (design 47 G §81, A-23). Recovery *RecordRecovery `json:"recovery,omitempty"` // MoverCount is the count of its movers, each with an entry of its own (design 47 H2 §809); Entries and Outcomes above @@ -223,16 +224,6 @@ type RecordEnded struct { Away []NodeAway `json:"away,omitempty"` } -// heldList is a month's list of records: each record opened that month, by instance. -type heldList struct { - Records map[string]heldEntry `json:"records,omitempty"` -} - -type heldEntry struct { - Instance string `json:"instance"` - Opened time.Time `json:"opened"` -} - // segmentRe is what one part of an instance's path may hold (the tool runner's rule). var segmentRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) @@ -270,18 +261,27 @@ func RecordInstance(milestone string) (string, error) { return inst, nil } -// heldInstance is the list of the records opened in a month: `held/2026-11`. -func heldInstance(t time.Time) string { return TypeHeld + "/" + t.UTC().Format("2006-01") } - // RecordLedger is the gate's ledger: an operation applied to one instance, and one instance's state read. type RecordLedger interface { Apply(instance, operation string, body any) (uint64, error) // Get is the instance's state and the sequence of its last operation; a nil state when it has none. Get(instance string) (json.RawMessage, uint64, error) + // Expires is when the bus ends the instance's state key, as `get` reads it from the bus (its time and the lifetime it + // carries); nil while the instance has not ended (design 47 H2 H-A-689 (2)). + Expires(instance string) (*time.Time, error) // Remove removes a record with its operations and its snapshot through the tool runner's ledger removal. Remove(instance string) error + // Reindex builds a declared index again from the history: of the one instance only, or whole when instance is empty + // (buscalls.LedgerReindex, design 47 H2 H-A-690 (1)); the entries it wrote. + Reindex(index, instance string) (int, error) + // Lag is every instance and index behind its history (buscalls.LedgerLag). + Lag() (buscalls.Lagged, error) // Query is the instances a declared index names under key (`>` for the rest). Query(index, key string) ([]string, error) + // Watch hands handle the current state of each instance `instances` names (an instance, `*` for one name, `>` for the + // rest), then each change, in the order it came: the instance and its state, null once its key has gone (ADR 0597 §10, + // design 47 H2 H-A-634 (5)); it answers once the current states are handled. + Watch(instances string, handle func(instance string, state json.RawMessage) error) error } // sdkLedger is the gate's ledger through the runtime: the tool runner's ledger calls, on the gate's own ledger only @@ -331,6 +331,32 @@ func (sdkLedger) Remove(instance string) error { return nil } +// Reindex is the tool runner's repair `reindex` of the gate's own ledger. +func (sdkLedger) Reindex(index, instance string) (int, error) { + out, err := ledgerCall(buscalls.LedgerReindex, buscalls.ReindexRequest{Ledger: RecordsLedger, Index: index, Instance: instance}) + if err != nil { + return 0, err + } + var got buscalls.Repaired + if err := json.Unmarshal(out, &got); err != nil { + return 0, fmt.Errorf("the ledger's answer to the reindex of %s is not readable: %w", index, err) + } + return got.Written, nil +} + +// Lag is the tool runner's `lag` of the gate's own ledger. +func (sdkLedger) Lag() (buscalls.Lagged, error) { + var got buscalls.Lagged + out, err := ledgerCall(buscalls.LedgerLag, buscalls.LedgerRequest{Ledger: RecordsLedger}) + if err != nil { + return got, err + } + if err := json.Unmarshal(out, &got); err != nil { + return got, fmt.Errorf("the ledger's answer to lag is not readable: %w", err) + } + return got, nil +} + func (sdkLedger) Query(index, key string) ([]string, error) { out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key}) if err != nil { @@ -347,6 +373,24 @@ func (sdkLedger) Query(index, key string) ([]string, error) { return insts, nil } +// Watch is the tool runner's watch of the gate's own ledger (mesh-sdk's stdio.WatchLedger), the current states first. +func (sdkLedger) Watch(instances string, handle func(string, json.RawMessage) error) error { + return stdio.WatchLedger(RecordsLedger, instances, func(c buscalls.InstanceChange) error { return handle(c.Instance, c.State) }) +} + +// Expires is the `expires` the tool runner's `get` answers for the instance. +func (sdkLedger) Expires(instance string) (*time.Time, error) { + out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) + if err != nil { + return nil, err + } + var got buscalls.InstanceState + if err := json.Unmarshal(out, &got); err != nil { + return nil, fmt.Errorf("the ledger's state of %s is not readable: %w", instance, err) + } + return got.Expires, nil +} + func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance}) if err != nil { @@ -366,8 +410,6 @@ func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) { type Records struct { Ledger RecordLedger Now func() time.Time - // Retention is how long a record is kept; nil keeps DefaultRecordRetention. - Retention func() time.Duration // Say says the seat mesh-delivery's events of the records: pinned, freed, record-ended (recordevents.go), filling, // full and room (recordfill.go); nil says none. Say SeatSay @@ -382,12 +424,25 @@ type Records struct { // TooLarge raises (raised) or clears record-too-large for an entry of the record named by its head's instance, the // finding's subject (§809; H-A-460); an empty instance clears every one held of the record (its end). nil raises none. TooLarge func(record, instance string, bytes int, raised bool) + // KeepingDays and EndedDays are the ledger's `max-age-days` and `ended-days` its manifest gives, said by the read tools + // (design 47 H2 H-A-634 (7)); zero says none. + KeepingDays, EndedDays int + // IndexBehind raises (behind) or clears the finding index-behind for a ledger index, with why (design 47 H2 H-A-690 (3)); + // nil says none. EndUnwritten raises (raised) or clears record-end-unwritten for a record, naming the instance and the + // error (H-A-690 (4)); EndPending says whether the record holds one, so its next event finishes it; nil: none held. + IndexBehind func(index, why string, behind bool) + EndUnwritten func(record, instance string, err error, raised bool) + EndPending func(record string) bool - // held are the records kept, by instance, read once from the ledger (Current) and kept as the gate writes them: the - // gate is their one writer. - mu sync.Mutex - held map[string]*Record - loaded bool + // held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read, + // then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in + // gone so an event for it is said and changes nothing (design 47 H2 H-A-634 (2), (5)). + mu sync.Mutex + held map[string]*Record + gone map[string]bool + pending map[string]struct{} + watching bool + loaded bool } // Current is every record kept and not ended, oldest first: read from the ledger at the first call, then as the gate @@ -423,41 +478,134 @@ func (rs *Records) Kept() ([]*Record, error) { return out, nil } +// load starts the gate's watch of its ledger's `record/>` once, at the first read: the key and opening of every record the +// ledger holds come as current states, each read as today, then each change; and the month lists `held/` the +// earlier gate wrote, a watch of `held/>` hands with a state, are removed through the ledger's removal (H-A-721). A record +// that could not be read is read again at the next call. func (rs *Records) load() error { rs.mu.Lock() - loaded := rs.loaded - rs.mu.Unlock() - if loaded { + if rs.loaded { + rs.mu.Unlock() return nil } - list, err := rs.List() + started := rs.watching + rs.watching = true + rs.mu.Unlock() + if !started { + if err := rs.Ledger.Watch(TypeRecord+"/>", rs.heardRecord); err != nil { + rs.mu.Lock() + rs.watching = false + rs.mu.Unlock() + return fmt.Errorf("the delivery records cannot be watched: %w", err) + } + if err := rs.Ledger.Watch(TypeHeld+"/>", rs.removeMonthList); err != nil { + rs.log("the month lists of the records cannot be watched, so none is removed: %v", err) + } + } + rs.mu.Lock() + var pending []string + for inst := range rs.pending { + pending = append(pending, inst) + } + rs.mu.Unlock() + for _, inst := range pending { + if err := rs.heardRecord(inst, json.RawMessage("true")); err != nil { + return err + } + } + rs.mu.Lock() + defer rs.mu.Unlock() + if rs.held == nil { + rs.held = map[string]*Record{} + } + rs.loaded = true + return nil +} + +// heardRecord takes one record's state from the watch: null drops the record, as a key gone by its lifetime; a record the +// gate holds is current already, being the one writer; any other is read and kept. A record that cannot be read stays pending. +func (rs *Records) heardRecord(instance string, state json.RawMessage) error { + if string(state) == "null" || len(state) == 0 { + rs.mu.Lock() + delete(rs.held, instance) + delete(rs.pending, instance) + if rs.gone == nil { + rs.gone = map[string]bool{} + } + known := rs.gone[instance] + rs.gone[instance] = true + rs.mu.Unlock() + if !known { + rs.log("the record %s's key has gone: it is no longer read", instance) + } + return nil + } + rs.mu.Lock() + _, have := rs.held[instance] + rs.mu.Unlock() + if have { + return nil + } + r, err := rs.Read(instance) if err != nil { + rs.mu.Lock() + if rs.pending == nil { + rs.pending = map[string]struct{}{} + } + rs.pending[instance] = struct{}{} + rs.mu.Unlock() return err } rs.mu.Lock() defer rs.mu.Unlock() - if !rs.loaded { - rs.held = map[string]*Record{} - for _, r := range list { - rs.held[r.Instance] = r - } - rs.loaded = true + delete(rs.pending, instance) + if r == nil { + return nil } + if rs.held == nil { + rs.held = map[string]*Record{} + } + if _, have := rs.held[instance]; !have { + rs.held[instance] = r + } + delete(rs.gone, instance) return nil } -func (rs *Records) keep(r *Record) { - rs.mu.Lock() - defer rs.mu.Unlock() - if rs.loaded { - rs.held[r.Instance] = r +// removeMonthList removes a month list the earlier gate wrote, through the ledger's removal, which ends the instance whole +// (design 47 H2 H-A-721): its operations, its snapshot, its key and its index keys. +func (rs *Records) removeMonthList(instance string, state json.RawMessage) error { + if string(state) == "null" || len(state) == 0 { + return nil + } + if err := rs.Ledger.Remove(instance); err != nil { + rs.log("the month list %s is not removed: %v", instance, err) + return err + } + rs.log("the month list %s is removed: the gate lists its records from a watch of the ledger", instance) + return nil +} + +func (rs *Records) log(format string, a ...any) { + if rs.Logf != nil { + rs.Logf("[mesh-delivery] "+format, a...) } } -func (rs *Records) forget(instance string) { +// keep holds a record the gate writes once it keeps its records, and answers the one held under its instance: the record +// a watch handed first stays the one every reader writes through. +func (rs *Records) keep(r *Record) *Record { rs.mu.Lock() defer rs.mu.Unlock() - delete(rs.held, instance) + if !rs.loaded { + return r + } + if held, ok := rs.held[r.Instance]; ok && held != r { + return held + } + rs.held[r.Instance] = r + delete(rs.gone, r.Instance) + return r } func (rs *Records) now() time.Time { @@ -467,16 +615,6 @@ func (rs *Records) now() time.Time { return rs.Now().UTC() } -func (rs *Records) retention() time.Duration { - if rs.Retention == nil { - return DefaultRecordRetention - } - if d := rs.Retention(); d > 0 { - return d - } - return DefaultRecordRetention -} - // Read is one record, or nil when the ledger holds none at that instance (or one removed). func (rs *Records) Read(instance string) (*Record, error) { raw, seq, err := rs.Ledger.Get(instance) @@ -516,8 +654,8 @@ type RecordOpening struct { } // Open opens the record of a source revision, unless one is there already, which is left as it is (a merge call heard -// again opens no second record and says nothing new). Opened says it was opened now. Each open removes the records past -// their retention first (the retention needs no timer: records open as deliveries do). +// again opens no second record and says nothing new). Opened says it was opened now. An open writes no month list and +// removes nothing: the bus ends an ended record's keys by the ledger's ended-days (design 47 H2 H-A-634 (2), (5), (6)). func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if o.Branch == "" || o.Source < 1 || o.Call == "" { return nil, false, fmt.Errorf("a delivery record names its branch, its source revision and its merge call (%q, %d, %q)", o.Branch, o.Source, o.Call) @@ -543,9 +681,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { return r, false, nil } now := rs.now() - if err := rs.Sweep(now); err != nil { - return nil, false, fmt.Errorf("the records past their retention cannot be removed, so no record is opened: %w", err) - } before, read, err := rs.refuseFull(milestone, inst) if err != nil { return nil, false, err @@ -559,9 +694,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if _, err := rs.write(&Record{Milestone: milestone}, inst, OpOpen, body, body); err != nil { return nil, false, err } - if _, err := rs.Ledger.Apply(heldInstance(now), OpHold, heldEntry{Instance: inst, Opened: now}); err != nil { - return nil, false, fmt.Errorf("the record %s is opened but not listed: %w", inst, err) - } if read { rs.sayFilling(inst, before) } @@ -571,7 +703,7 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) { if err := rs.SetTrace(r, o.Trace); err != nil { return r, true, fmt.Errorf("the record %s is opened and its trace is not written: %w", inst, err) } - rs.keep(r) + r = rs.keep(r) rs.sayOpened(r) return r, true, nil } @@ -585,6 +717,15 @@ func (rs *Records) ByKey(branch string, source int64) (*Record, error) { // the gate keeps as it writes it when it holds it, so a write through it is seen by every reader, else read from the // ledger; nil when none is kept. func (rs *Records) ByMilestone(milestone string) (*Record, error) { + r, err := rs.byMilestone(milestone) + if r != nil && err == nil && rs.EndPending != nil && rs.EndPending(r.Instance) { + // The next event of a record whose end was not written in full finishes it, by the pass for it alone (H-A-690 (4)). + _, _ = rs.followRecord(r) + } + return r, err +} + +func (rs *Records) byMilestone(milestone string) (*Record, error) { inst, err := RecordInstance(milestone) if err != nil { return nil, err @@ -597,7 +738,14 @@ func (rs *Records) ByMilestone(milestone string) (*Record, error) { } r, err := rs.Read(inst) if r != nil { - rs.keep(r) + r = rs.keep(r) + } else if err == nil { + rs.mu.Lock() + gone := rs.gone[inst] + rs.mu.Unlock() + if gone { + rs.log("the record %s's key has gone: an event for it changes nothing", inst) + } } return r, err } @@ -612,100 +760,6 @@ func (rs *Records) sayOpened(r *Record) { } } -// List is every record kept, opened within the retention and a month more, oldest first. -func (rs *Records) List() ([]*Record, error) { - now := rs.now() - var out []*Record - for _, m := range rs.months(now) { - list, err := rs.heldIn(m) - if err != nil { - return nil, err - } - for _, e := range list { - r, err := rs.Read(e.Instance) - if err != nil { - return nil, err - } - if r != nil { - out = append(out, r) - } - } - } - sort.SliceStable(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) }) - return out, nil -} - -// months are the months' lists a record within the retention can be in, oldest first, one more at each end. -func (rs *Records) months(now time.Time) []string { - from := now.Add(-rs.retention()).AddDate(0, -1, 0) - var out []string - for m := time.Date(from.Year(), from.Month(), 1, 0, 0, 0, 0, time.UTC); !m.After(now); m = m.AddDate(0, 1, 0) { - out = append(out, heldInstance(m)) - } - return out -} - -func (rs *Records) heldIn(month string) ([]heldEntry, error) { - raw, _, err := rs.Ledger.Get(month) - if err != nil || raw == nil { - return nil, err - } - var l heldList - if err := json.Unmarshal(raw, &l); err != nil { - return nil, fmt.Errorf("the list of records %s is not readable: %w", month, err) - } - out := make([]heldEntry, 0, len(l.Records)) - for _, e := range l.Records { - out = append(out, e) - } - sort.Slice(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) }) - return out, nil -} - -// Sweep removes every record opened longer ago than the retention. Nothing else is removed to make room. -func (rs *Records) Sweep(now time.Time) error { - cut := now.Add(-rs.retention()) - for _, m := range rs.months(now) { - list, err := rs.heldIn(m) - if err != nil { - return err - } - for _, e := range list { - if !e.Opened.Before(cut) { - continue - } - r, err := rs.Read(e.Instance) - if err != nil { - return err - } - if r != nil { - for _, m := range r.movers { - if err := rs.Ledger.Remove(m.Instance); err != nil { - return err - } - } - for id := range r.Acts { - inst, err := ActInstance(r.Milestone, id) - if err != nil { - return err - } - if err := rs.Ledger.Remove(inst); err != nil { - return err - } - } - if err := rs.Ledger.Remove(e.Instance); err != nil { - return err - } - rs.forget(e.Instance) - } - if _, err := rs.Ledger.Apply(m, OpDrop, map[string]any{"instance": e.Instance}); err != nil { - return err - } - } - } - return nil -} - // SetGroup writes the record's group state, unless it holds that state already. func (rs *Records) SetGroup(r *Record, g RecordGroup) error { if r.Group != nil && reflect.DeepEqual(*r.Group, g) { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go index 513150b59..bdfb449c3 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/record_test.go @@ -12,6 +12,8 @@ import ( "testing" "time" + ownmanifest "mesh-delivery-gate" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" @@ -34,6 +36,53 @@ type ledgerFake struct { failOn string // fill is what Fill answers; nil, the ledger says no fill. fill *buscalls.Fill + // lagged is what Lag answers; a whole Reindex of an index takes it out unless stuck names it. calls is every reindex and every + // `end` applied, in order; reindexErr fails every Reindex; endErr fails the `end` of an instance. + lagged buscalls.Lagged + stuck string + calls []string + reindexErr error + endErr string + // watchers are the watches the gate started, each told of every change to an instance its pattern names. + watchers []ledgerWatch +} + +// ledgerWatch is one watch of the fake ledger: the instances it names (an instance path, or a type's `/>`) and its handler. +type ledgerWatch struct { + instances string + handle func(instance string, state json.RawMessage) error +} + +func (w ledgerWatch) names(instance string) bool { + return w.instances == instance || strings.HasSuffix(w.instances, ">") && strings.HasPrefix(instance, strings.TrimSuffix(w.instances, ">")) +} + +// Watch hands the current state of each instance the pattern names, in order, and keeps the handler for change. +func (f *ledgerFake) Watch(instances string, handle func(string, json.RawMessage) error) error { + w := ledgerWatch{instances: instances, handle: handle} + f.watchers = append(f.watchers, w) + var names []string + for inst, raw := range f.states { + if w.names(inst) && string(raw) != "null" { + names = append(names, inst) + } + } + sort.Strings(names) + for _, inst := range names { + if err := handle(inst, f.states[inst]); err != nil { + return err + } + } + return nil +} + +// change hands an instance's state, null once its key has gone, to every watch that names it. +func (f *ledgerFake) change(instance string) { + for _, w := range f.watchers { + if w.names(instance) { + _ = w.handle(instance, f.states[instance]) + } + } } func (f *ledgerFake) Fill() (buscalls.Fill, error) { @@ -70,10 +119,36 @@ func newLedgerFake(t *testing.T) *ledgerFake { return f } +// Reindex records the call; a whole one makes the index not behind, unless it is stuck. +func (f *ledgerFake) Reindex(index, instance string) (int, error) { + f.calls = append(f.calls, "reindex "+index+" "+instance) + if f.reindexErr != nil { + return 0, f.reindexErr + } + if instance == "" && index != f.stuck { + var keep []buscalls.IndexLag + for _, l := range f.lagged.Indexes { + if l.Index != index { + keep = append(keep, l) + } + } + f.lagged.Indexes = keep + } + return 3, nil +} + +func (f *ledgerFake) Lag() (buscalls.Lagged, error) { return f.lagged, nil } + func (f *ledgerFake) Apply(instance, operation string, body any) (uint64, error) { if f.failOn == operation { return 0, fmt.Errorf("the ledger is away") } + if operation == OpEnd { + f.calls = append(f.calls, "end "+instance) + if f.endErr == instance { + return 0, fmt.Errorf("the ledger did not take the end of %s", instance) + } + } ty, ok := f.types[strings.SplitN(instance, "/", 2)[0]] if !ok { return 0, fmt.Errorf("no type for %s", instance) @@ -151,6 +226,7 @@ func (f *ledgerFake) Remove(instance string) error { f.seq[instance]++ f.states[instance] = json.RawMessage("null") f.history = append(f.history, instance+" remove") + f.change(instance) return nil } @@ -181,6 +257,25 @@ func (f *ledgerFake) Query(index, key string) ([]string, error) { return out, nil } +// Expires is the end of the instance plus the manifest's ended-days, as `get` answers it; nil while it has no end. +func (f *ledgerFake) Expires(instance string) (*time.Time, error) { + if f.failOn == "expires" { + return nil, errors.New("the ledger is away") + } + var st struct { + Ended *RecordEnded `json:"ended"` + } + if raw := f.states[instance]; raw != nil { + _ = json.Unmarshal(raw, &st) + } + if st.Ended == nil { + return nil, nil + } + _, days, _ := ownmanifest.RecordsDays() + at := st.Ended.At.AddDate(0, 0, days) + return &at, nil +} + func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) { s := f.states[instance] if s == nil || string(s) == "null" { @@ -274,6 +369,50 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T } }) + // Design 47 H2 H-A-634 (2): a record's end writes the head's end first, then an end on each of its movers and acts with the + // head's ended; a reopening empties theirs first, then the head's; an end written again moves every one's alike. + t.Run("an end writes the head, then each mover and act with its ended; a reopening empties theirs first", func(t *testing.T) { + l := newLedgerFake(t) + rs := &Records{Ledger: l, Now: func() time.Time { return at }} + r, _, err := rs.Open(opening("main", 91, heads)) + if err != nil { + t.Fatal(err) + } + for _, module := range []string{"mod-b", "mod-a"} { + if err := rs.AddEntry(r, RecordEntry{Module: module, Fingerprint: "src2:f" + module}); err != nil { + t.Fatal(err) + } + } + if err := rs.Act(r, RecordAct{ID: "view@1.a", Act: "view", Repository: "novox/app", Number: 3, Head: heads["novox/app@3"]}); err != nil { + t.Fatal(err) + } + l.history = nil + if err := rs.End(r, "by hand", "person"); err != nil { + t.Fatal(err) + } + if len(l.history) != 4 || !strings.HasPrefix(l.history[0], "record/") || !strings.HasPrefix(l.history[3], "act/") || + !strings.Contains(l.history[1], "mod-a") || !strings.Contains(l.history[2], "mod-b") { + t.Fatalf("an end wrote %v: the head's first, then each mover's by module, then each act's", l.history) + } + for _, inst := range l.history[1:3] { + inst = strings.TrimSuffix(inst, " end") + if !strings.Contains(string(l.states[inst]), `"ended":{"at":`) || !strings.Contains(string(l.states[inst]), `"why":"by hand"`) { + t.Errorf("%s holds %s: the head's ended copied", inst, l.states[inst]) + } + } + l.history = nil + if err := rs.Reopen(r, 2); err != nil { + t.Fatal(err) + } + if len(l.history) != 4 || l.history[3] != r.Instance+" end" { + t.Fatalf("a reopening wrote %v: the movers' and acts' ended first, the head's last", l.history) + } + if inst := strings.TrimSuffix(l.history[0], " end"); !strings.HasPrefix(inst, "mover/") || strings.Contains(string(l.states[inst]), `"at"`) || + r.Ended != nil || r.Movers()["mod-a"].Ended != nil { + t.Errorf("a reopened record's mover holds %s, the record ended %+v", l.states[inst], r.Ended) + } + }) + // A record keeps its delivery time and class; gate_times judges them against the budgets (design 47 H2 §810; H-A-394). t.Run("a core record ended 11 minutes after merge-called is over its budget", func(t *testing.T) { now := at @@ -379,7 +518,7 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T if byKey, err := rs.ByKey("main", 47); err != nil || byKey == nil || byKey.Instance != r.Instance { t.Fatalf("read by its key: %+v %v", byKey, err) } - list, err := rs.List() + list, err := rs.Kept() if err != nil || len(list) != 1 || list[0].Instance != r.Instance { t.Fatalf("list %+v %v", list, err) } @@ -420,58 +559,58 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T } }) - t.Run("a record past its retention is removed at the next open", func(t *testing.T) { + // Design 47 H2 H-A-634 (2), (5), H-A-721: the gate lists its records from a watch of its ledger's `record/>`; an open + // writes no month list and removes nothing; a month list standing at the start is removed through the ledger's removal and no + // forget is applied; a key gone drops the record from every list, and an event for it changes nothing and is said. + t.Run("the records are listed from a watch: a month list standing is removed at the start, a gone key drops its record and an event for it changes nothing", func(t *testing.T) { l := newLedgerFake(t) now := at - rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }} - old, _, _ := rs.Open(opening("main", 46, heads)) + var journal []string + logf := func(format string, a ...any) { journal = append(journal, fmt.Sprintf(format, a...)) } + before := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf} + old, _, _ := before.Open(opening("main", 46, heads)) now = at.Add(89 * 24 * time.Hour) - kept, _, _ := rs.Open(opening("main", 47, heads)) - if r, _ := rs.Read(old.Instance); r == nil { - t.Fatal("a record within its retention is removed") + kept, _, _ := before.Open(opening("main", 47, heads)) + for _, op := range l.history { + if strings.HasPrefix(op, TypeHeld+"/") { + t.Fatalf("an open wrote %s: no month list is written", op) + } } - now = at.Add(91 * 24 * time.Hour) - if _, _, err := rs.Open(opening("main", 48, heads)); err != nil { + // A month list the gate before H2 wrote, standing at the start. + if _, err := l.Apply("held/2026-11", OpHold, map[string]any{"instance": old.Instance, "opened": at}); err != nil { t.Fatal(err) } - if r, _ := rs.Read(old.Instance); r != nil { - t.Fatal("a record past its retention is kept") + l.history = nil + rs := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf} + list, err := rs.Kept() + if err != nil || len(list) != 2 || list[0].Instance != old.Instance || list[1].Instance != kept.Instance { + t.Fatalf("the records listed from the watch are %+v (%v): the two, oldest first", list, err) } - list, _ := rs.List() - if len(list) != 2 || list[0].Instance != kept.Instance { - t.Fatalf("list %+v", list) + if string(l.states["held/2026-11"]) != "null" || !slices.Contains(l.history, "held/2026-11 remove") { + t.Fatalf("the month list holds %s after %v: removed through the ledger's removal", l.states["held/2026-11"], l.history) } - }) - - t.Run("the setting record-retention, in days", func(t *testing.T) { - dir := t.TempDir() - for _, c := range []struct { - file string - want time.Duration - bad bool - }{ - {`{}`, DefaultRecordRetention, false}, - {`{"record-retention": 30}`, 30 * 24 * time.Hour, false}, - {`{"record-retention": 0}`, 0, true}, - {`{"record-retention": 1.5}`, 0, true}, - {`{"record-retention": "90"}`, 0, true}, - } { - p := filepath.Join(dir, "settings.json") - if err := os.WriteFile(p, []byte(c.file), 0o600); err != nil { - t.Fatal(err) - } - s, err := readSettings(p) - if (err != nil) != c.bad { - t.Fatalf("%s: %v", c.file, err) - } - if c.bad { - continue - } - h := &Holder{Settings: func() Settings { return s }} - if got := h.recordRetention(); got != c.want { - t.Fatalf("%s: %s, wanted %s", c.file, got, c.want) + for _, op := range l.history { + if strings.HasSuffix(op, " forget") || strings.HasSuffix(op, " "+OpDrop) || strings.HasSuffix(op, " "+OpHold) { + t.Errorf("the gate applied %s: no month list is applied", op) } } + // The key of the older record goes by its lifetime: the bus hands it removed. + l.states[old.Instance] = json.RawMessage("null") + l.change(old.Instance) + if list, _ := rs.Kept(); len(list) != 1 || list[0].Instance != kept.Instance { + t.Fatalf("after its key went the records are %+v: one", list) + } + if cur, _ := rs.Current(); len(cur) != 1 { + t.Fatalf("after its key went the open records are %+v: one", cur) + } + n := len(l.history) + journal = nil + if r, err := rs.ByKey("main", 46); err != nil || r != nil { + t.Fatalf("an event's record is %+v (%v): none, its key has gone", r, err) + } + if len(l.history) != n || !strings.Contains(strings.Join(journal, "\n"), "key has gone: an event for it changes nothing") { + t.Fatalf("the ledger took %v and the journal says %q: nothing written, said once", l.history[n:], journal) + } }) } @@ -488,9 +627,39 @@ func TestTheManifestsLedgerTypesAreTheRecordsOperations(t *testing.T) { t.Errorf("the type %s allows %v, the gate applies %v", name, got, want) } } + // The records ledger's cap and its own configuration (design 47 H2 H-A-688, H-A-634 (2)): 3 GiB, its history kept 90 days, + // an ended instance's keys 30 days (7 or more, the judge's floor for a record a person may still read), and the ending + // types; the month lists' operations stay declared for the replay of the history and are applied by no part (H-A-691, + // H-A-721: no forget). + var manifest struct { + Requires []catalogue.BusStateEntry `json:"requires"` + Config map[string]json.RawMessage `json:"config"` + } raw, _ := os.ReadFile(filepath.Join("..", "..", "module.json")) - if !strings.Contains(string(raw), `"max-mib": 1024`) { - t.Error("the records ledger is not capped at 1 GiB (design 47 H2 §809)") + if err := json.Unmarshal(raw, &manifest); err != nil { + t.Fatal(err) + } + for _, e := range manifest.Requires { + if e.Name != RecordsLedger { + continue + } + var days, kept int + _ = json.Unmarshal(e.Configuration[catalogue.ConfigEndedDays], &days) + _ = json.Unmarshal(e.Configuration[catalogue.OptionAgeDays], &kept) + if string(e.Options[catalogue.OptionCapMiB]) != "3072" || days < 7 || days > 30 || kept != 90 { + t.Errorf("the records ledger asks %v and %v: want max-mib 3072, ended-days from 7 to 30 and max-age-days 90", e.Options, e.Configuration) + } + for _, ty := range e.Types { + if (ty.Name == TypeRecord || ty.Name == TypeMover || ty.Name == TypeAct) != (ty.EndsWith == "ended") { + t.Errorf("the type %s ends with %q: record, mover and act end with ended, held with nothing", ty.Name, ty.EndsWith) + } + if _, has := ty.Schema["ended"]; ty.EndsWith != "" && !has { + t.Errorf("the type %s ends with a field its schema lacks", ty.Name) + } + } + } + if _, kept := manifest.Config["record-retention"]; kept || strings.Contains(string(raw), "forget") { + t.Error("the manifest keeps the setting record-retention or a forget: the bus ends a record's keys by ended-days (H-A-634 (2), H-A-721)") } if ix := l.types[TypeMover].Indexes; len(ix) != 1 || ix[0].Name != MoversIndex || !slices.Equal(ix[0].On, []string{"record"}) { t.Errorf("the type mover's indexes are %+v, not one %s on its record's key", ix, MoversIndex) @@ -855,6 +1024,106 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) { t.Fatalf("with none open: %+v %v, log %d", again, err, len(log.took)) } }) + // H-A-634 (7), H-A-689 (2): gate_records_expiring names what the bus ends when, read from the bus, and no open record. + t.Run("gate_records_expiring names an ended record's expires thirty days after its end, and no open record", func(t *testing.T) { + rs, r, _ := setup(t) + rs.EndedDays, rs.KeepingDays = 30, 90 + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)})) + if err != nil { + t.Fatal(err) + } + if err := rs.End(r, "done", "jochen@shanks"); err != nil { + t.Fatal(err) + } + got, err := rs.Expiring(0, "") + lines, _ := got["records"].([]expiringLine) + want := at.AddDate(0, 0, 30).UTC().Format(time.RFC3339) + if err != nil || len(lines) != 1 || lines[0].Instance != r.Instance || lines[0].Expires != want || got["open"] != 1 || + lines[0].Movers != (counts{Counted: 1, Indexed: 1}) || got["capped"] != false { + t.Fatalf("%+v %v", got, err) + } + for _, l := range lines { + if l.Instance == open.Instance { + t.Fatal("an open record is named") + } + } + if short, _ := rs.Expiring(1, ""); short["total"] != 0 { + t.Fatalf("within one day: %+v", short) + } + if _, err := rs.Expiring(3651, ""); err == nil { + t.Fatal("within 3651 days was taken") + } + if _, err := rs.Expiring(0, "not-a-cursor"); err == nil { + t.Fatal("a cursor this tool never answered was taken") + } + if lines, _ := rs.Lines(); lines["soonest-expires"] != want || lines["ended-days"] != 30 || lines["keeping-days"] != 90 { + t.Fatalf("gate_records says %v, %v, %v", lines["soonest-expires"], lines["ended-days"], lines["keeping-days"]) + } + rs.Ledger.(*ledgerFake).failOn = "expires" + if got, _ := rs.Expiring(0, ""); got["unread"] == nil { + t.Fatalf("an expires that could not be read is not said: %+v", got) + } + }) + // H-A-634 (7): gate_records_follow_ends gives an ended record's movers and acts its end and takes it from an open one's, once + // the hand-act log took it. + t.Run("gate_records_follow_ends gives an ended record's entries its end and takes it from an open record's", func(t *testing.T) { + rs, r, _ := setup(t) + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + if err := rs.Act(r, RecordAct{ID: "a1", Act: "merge", Repository: "novox/app", Number: 1, At: at}); err != nil { + t.Fatal(err) + } + open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)})) + if err != nil { + t.Fatal(err) + } + if err := rs.SetMover(open, "mesh-y", "src2:f2", "main.48", "0.1.0"); err != nil { + t.Fatal(err) + } + if err := rs.End(r, "done", "jochen@shanks"); err != nil { + t.Fatal(err) + } + l := rs.Ledger.(*ledgerFake) + moverX, _ := MoverInstance(r.Milestone, "mesh-x") + actA, _ := ActInstance(r.Milestone, "a1") + moverY, _ := MoverInstance(open.Milestone, "mesh-y") + // The earlier gate left the entries as the end found them: the ended record's with none, the open one's with an end. + for inst, ended := range map[string]any{moverX: nil, actA: nil, moverY: RecordEnded{At: at, Why: "stale"}} { + if _, err := l.Apply(inst, OpEnd, map[string]any{"ended": ended}); err != nil { + t.Fatal(err) + } + } + log := &handActsFake{refuse: errors.New("no responders")} + if _, err := rs.FollowEnds("", log); err == nil { + t.Fatal("followed with no reason") + } + if _, err := rs.FollowEnds("the indexes were rebuilt", log); err == nil || len(l.history) == 0 || strings.HasSuffix(l.history[len(l.history)-1], moverX+" end") { + t.Fatalf("followed though the hand-act log refused it: %v", err) + } + endedOf := func(inst string) any { + var st map[string]any + _ = json.Unmarshal(l.states[inst], &st) + return st["ended"] + } + if endedOf(moverX) != nil || endedOf(moverY) == nil { + t.Fatal("an entry was written while no hand act was recorded") + } + log.refuse = nil + got, err := rs.FollowEnds("the indexes were rebuilt", log) + if err != nil || got["written"] != 3 || len(log.took) != 1 { + t.Fatalf("%+v %v (log %+v)", got, err, log.took) + } + if endedOf(moverX) == nil || endedOf(actA) == nil || endedOf(moverY) != nil { + t.Fatalf("the ends: %v %v %v", endedOf(moverX), endedOf(actA), endedOf(moverY)) + } + if again, err := rs.FollowEnds("again", log); err != nil || again["written"] != 0 { + t.Fatalf("a second pass wrote: %+v %v", again, err) + } + }) t.Run("gate_record_repair asks the owners for the outcomes an entry lacks, applies what they answer, and ends the record", func(t *testing.T) { rs, r, said := setup(t) owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"} @@ -1083,3 +1352,121 @@ func opening(branch string, source int64, heads map[string]string) RecordOpening } func ptrTime(t time.Time) *time.Time { return &t } + +// H-A-690 (2) to (4): the gate keeps its ledger's indexes by a watcher, builds an index behind again whole at its start before the +// pass of the ends, says what fails as index-behind and record-end-unwritten, and finishes an end at the record's next event. +func TestTheGateKeepsItsLedgerIndexesByAWatcher(t *testing.T) { + at := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + heads := map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)} + setup := func(t *testing.T) (*Records, *Holder, *ledgerFake, *Record, string) { + l := newLedgerFake(t) + h := &Holder{Findings: &findingsFake{held: map[string]meshconditions.Finding{}}, Now: func() time.Time { return at }} + rs := &Records{Ledger: l, Now: func() time.Time { return at }, IndexBehind: h.indexBehind, EndUnwritten: h.endUnwritten, + EndPending: func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) }} + r, _, err := rs.Open(opening("main", 47, heads)) + if err != nil { + t.Fatal(err) + } + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil { + t.Fatal(err) + } + inst, _ := MoverInstance(r.Milestone, "mesh-x") + return rs, h, l, r, inst + } + count := func(l *ledgerFake, call string) (n int) { + for _, c := range l.calls { + if c == call { + n++ + } + } + return n + } + t.Run("a change the watch hands makes one reindex naming it, and the current states none", func(t *testing.T) { + rs, _, l, r, mover := setup(t) + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if len(l.calls) != 0 { + t.Fatalf("the start called %v", l.calls) + } + if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.48", "0.1.1"); err != nil { + t.Fatal(err) + } + l.change(mover) + if got := count(l, "reindex movers "+mover); got != 1 || len(l.calls) != 1 { + t.Fatalf("calls %v", l.calls) + } + l.states[mover] = json.RawMessage("null") + l.change(mover) // a key gone by its lifetime needs no call + if len(l.calls) != 1 { + t.Fatalf("a key gone called %v", l.calls) + } + }) + t.Run("an index behind is built again whole before the pass of the ends, and still behind it is raised", func(t *testing.T) { + rs, h, l, r, mover := setup(t) + if err := rs.End(r, "done", "x"); err != nil { + t.Fatal(err) + } + if _, err := l.Apply(mover, OpEnd, map[string]any{"ended": nil}); err != nil { // the mover lost its end + t.Fatal(err) + } + l.calls = nil + l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}} + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if len(l.calls) < 2 || l.calls[0] != "reindex movers " || l.calls[1] != "end "+mover { + t.Fatalf("the start called %v", l.calls) + } + if h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("an index built again is still raised") + } + l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}} + l.stuck = MoversIndex + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + if !h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("an index still behind after its whole reindex is not raised") + } + l.stuck, l.lagged = "", buscalls.Lagged{} + if err := rs.KeepIndexes(); err != nil || h.heldFinding(IndexBehind, MoversIndex) { + t.Fatalf("lag naming it not behind did not clear it: %v", err) + } + }) + t.Run("a failed call raises index-behind and is made again at the instance's next change", func(t *testing.T) { + rs, h, l, _, mover := setup(t) + if err := rs.KeepIndexes(); err != nil { + t.Fatal(err) + } + l.reindexErr = errors.New("the tool runner is away") + l.change(mover) + if !h.heldFinding(IndexBehind, MoversIndex) { + t.Fatal("a failed reindex is not raised") + } + l.reindexErr = nil + l.change(mover) + if got := count(l, "reindex movers "+mover); got != 2 { + t.Fatalf("calls %v", l.calls) + } + }) + t.Run("a failed end raises record-end-unwritten, and the record's next event writes it and clears it", func(t *testing.T) { + rs, h, l, r, mover := setup(t) + l.endErr = mover + if err := rs.End(r, "done", "x"); err != nil { + t.Fatal(err) // the record's end stands + } + if !h.heldFinding(RecordEndUnwritten, r.Instance) || r.Ended == nil { + t.Fatal("a failed end of an entry is not raised") + } + l.endErr = "" + if got, err := rs.ByMilestone(r.Milestone); err != nil || got == nil { + t.Fatalf("%v %v", got, err) + } + var st struct{ Ended *RecordEnded } + _ = json.Unmarshal(l.states[mover], &st) + if st.Ended == nil || h.heldFinding(RecordEndUnwritten, r.Instance) { + t.Fatalf("the next event did not write the end (%v) or clear the finding", st.Ended) + } + }) +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go new file mode 100644 index 000000000..8d3570152 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordends.go @@ -0,0 +1,306 @@ +package main + +// What the ledger's lifetimes make of the records, read and mended by hand (design 47 H2 H-A-634 (7), H-A-689): when an ended +// record's key goes (gate_records_expiring) and the end each of its movers and acts holds (gate_records_follow_ends), found +// through the ledger's indexes `movers` and `acts`. + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "strings" + "time" + + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + "git.novox.be/novox/mesh-sdk/go/views" +) + +// expiry is one ended record with the time the bus ends its key. +type expiry struct { + r *Record + expires time.Time +} + +// expiries are the ended records of list whose key the bus ends, each with its `expires` as the ledger's `get` reads it from the +// bus, the soonest first; a record whose `expires` cannot be read is named in unread with the error. +func (rs *Records) expiries(list []*Record) (out []expiry, unread []string) { + for _, r := range list { + if r.Ended == nil { + continue + } + at, err := rs.Ledger.Expires(r.Instance) + if err != nil { + unread = append(unread, r.Instance+": "+err.Error()) + continue + } + if at == nil { + continue + } + out = append(out, expiry{r: r, expires: at.UTC()}) + } + sort.SliceStable(out, func(i, j int) bool { + if !out[i].expires.Equal(out[j].expires) { + return out[i].expires.Before(out[j].expires) + } + return out[i].r.Instance < out[j].r.Instance + }) + return out, unread +} + +// expiringLine is one ended record as gate_records_expiring lists it: its movers and acts as the head counts them and as the +// ledger's indexes name them. +type expiringLine struct { + Instance string `json:"instance"` + Opened string `json:"opened"` + Ended string `json:"ended"` + Expires string `json:"expires"` + Movers counts `json:"movers"` + Acts counts `json:"acts"` +} + +type counts struct { + Counted int `json:"counted"` + Indexed int `json:"indexed"` +} + +// MaxWithinDays is the most days gate_records_expiring looks ahead. +const MaxWithinDays = 3650 + +// Expiring reads what goes when, removing nothing: every ended record whose key expires within `within` days (the ledger's +// ended-days when 0), the soonest first, and how many open records are kept whatever their age, at most views.PageBytes a page +// with capped, total and the cursor (design 47 H2 §811, H-A-634 (7), H-A-689 (2)). +func (rs *Records) Expiring(within int, next string) (map[string]any, error) { + if within == 0 { + within = rs.EndedDays + } + if within < 1 || within > MaxWithinDays { + return nil, fmt.Errorf("within is a number of days from 1 to %d", MaxWithinDays) + } + list, err := rs.Kept() + if err != nil { + return nil, err + } + open := 0 + for _, r := range list { + if r.Ended == nil { + open++ + } + } + until := rs.now().Add(time.Duration(within) * 24 * time.Hour) + var all []expiry + got, unread := rs.expiries(list) + for _, e := range got { + if !e.expires.After(until) { + all = append(all, e) + } + } + page, size, capped, cursor := []expiringLine{}, 0, false, "" + for _, e := range all { + if next != "" { + at, err := beforeExpiry(e, next) + if err != nil { + return nil, err + } + if at { + continue + } + } + line, err := rs.expiringLine(e) + if err != nil { + return nil, err + } + raw, _ := json.Marshal(line) + if size+len(raw) > views.PageBytes && len(page) > 0 { + capped = true + break + } + size += len(raw) + page, cursor = append(page, line), expiryCursor(e) + } + out := map[string]any{"within-days": within, "ended-days": rs.EndedDays, "records": page, "total": len(all), "open": open, + "capped": capped} + if capped { + out["next"] = cursor + } else { + out["next"] = "" + } + if len(unread) > 0 { + out["unread"] = unread + } + return out, nil +} + +func (rs *Records) expiringLine(e expiry) (expiringLine, error) { + ms, err := rs.Ledger.Query(MoversIndex, moversKey(e.r.Milestone)) + if err != nil { + return expiringLine{}, fmt.Errorf("the movers of the record %s cannot be read: %w", e.r.Instance, err) + } + as, err := rs.Ledger.Query(ActsIndex, moversKey(e.r.Milestone)) + if err != nil { + return expiringLine{}, fmt.Errorf("the acts of the record %s cannot be read: %w", e.r.Instance, err) + } + return expiringLine{Instance: e.r.Instance, Opened: timeText(&e.r.Opened), Ended: timeText(&e.r.Ended.At), + Expires: timeText(&e.expires), Movers: counts{Counted: e.r.MoverCount, Indexed: len(ms)}, + Acts: counts{Counted: len(e.r.Acts), Indexed: len(as)}}, nil +} + +// expiryCursor is the opaque cursor of a page of gate_records_expiring: the place of the last record it answered. +func expiryCursor(e expiry) string { + return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d|%s", e.expires.UnixNano(), e.r.Instance))) +} + +// beforeExpiry is whether e comes at or before the place the cursor names. +func beforeExpiry(e expiry, cursor string) (bool, error) { + raw, err := base64.RawURLEncoding.DecodeString(cursor) + at, inst, ok := strings.Cut(string(raw), "|") + n, perr := strconv.ParseInt(at, 10, 64) + if err != nil || !ok || perr != nil { + return false, fmt.Errorf("gate_records_expiring: %q is no cursor this tool answered", cursor) + } + if e.expires.UnixNano() != n { + return e.expires.UnixNano() < n, nil + } + return e.r.Instance <= inst, nil +} + +// soonest is the earliest `expires` among the ended records, "" when none ends or none could be read. +func (rs *Records) soonest(list []*Record) string { + got, _ := rs.expiries(list) + if len(got) == 0 { + return "" + } + return timeText(&got[0].expires) +} + +// sameEnded is whether two ends are one: the time, the reason, who and the nodes away. +func sameEnded(a, b *RecordEnded) bool { + if a == nil || b == nil { + return a == nil && b == nil + } + if !a.At.Equal(b.At) || a.Why != b.Why || a.By != b.By || len(a.Away) != len(b.Away) { + return false + } + for i := range a.Away { + if a.Away[i].Node != b.Away[i].Node || !a.Away[i].Since.Equal(b.Away[i].Since) { + return false + } + } + return true +} + +// followRecord gives every mover and act of the record, found through the indexes `movers` and `acts`, the record's end where +// they hold another, and takes it from those of an open record, by their `end` (H-A-634 (2), (7)): the instances it wrote. It +// stops at the first write that fails, naming it. +func (rs *Records) followRecord(r *Record) ([]string, error) { + written, err := rs.followEnds(r) + if rs.EndUnwritten != nil { + rs.EndUnwritten(r.Instance, "", err, err != nil) + } + if err != nil { + rs.log("the record %s: its movers and acts do not all hold its end: %v", r.Instance, err) + } + return written, err +} + +func (rs *Records) followEnds(r *Record) ([]string, error) { + var written []string + for _, index := range []string{MoversIndex, ActsIndex} { + insts, err := rs.Ledger.Query(index, moversKey(r.Milestone)) + if err != nil { + return written, fmt.Errorf("the %s of the record %s cannot be read: %w", index, r.Instance, err) + } + sort.Strings(insts) + for _, inst := range insts { + raw, _, err := rs.Ledger.Get(inst) + if err != nil { + return written, err + } + if raw == nil { + continue + } + var m Mover + var a RecordAct + var held, state any + var heldEnded *RecordEnded + if index == MoversIndex { + if err := json.Unmarshal(raw, &m); err != nil { + return written, fmt.Errorf("the mover %s is not readable: %w", inst, err) + } + heldEnded = m.Ended + m.Ended = copyEnded(r.Ended) + held, state = m.Ended, m + } else { + if err := json.Unmarshal(raw, &a); err != nil { + return written, fmt.Errorf("the act %s is not readable: %w", inst, err) + } + heldEnded = a.Ended + a.Ended = copyEnded(r.Ended) + held, state = a.Ended, a + } + if sameEnded(heldEnded, r.Ended) { + continue + } + var value any + if r.Ended != nil { + value = *held.(*RecordEnded) + } + if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, state); err != nil { + return written, fmt.Errorf("the end of %s is not written: %w", inst, err) + } + written = append(written, inst) + } + } + return written, nil +} + +// FollowEnds does by hand the pass the gate makes at its start: every record's movers and acts take the record's end, or none +// while it is open, read through the indexes. Recorded first in the hand-act log of the seat mesh-hand-acts: nothing is written +// when the log did not take it. It answers each record and the instances it wrote; a record whose pass failed is named with +// the error and the rest go on. +func (rs *Records) FollowEnds(why string, acts handActs) (map[string]any, error) { + if strings.TrimSpace(why) == "" { + return nil, errors.New("say why the ends are followed by hand, such as the indexes were rebuilt") + } + if acts == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was written") + } + list, err := rs.Kept() + if err != nil { + return nil, err + } + if _, err := acts.Record(meshhandactsclient.Request{What: "gave the movers and acts of every delivery record its end by hand", + Why: why, Cause: "gate_records_follow_ends", Verb: "follow-ends"}); err != nil { + return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was written: %w", err) + } + type line struct { + Record string `json:"record"` + Ended bool `json:"ended"` + Written []string `json:"written"` + Failed string `json:"failed,omitempty"` + } + lines, total, failed := []line{}, 0, 0 + for _, r := range list { + w, err := rs.followRecord(r) + if len(w) == 0 && err == nil { + continue + } + l := line{Record: r.Instance, Ended: r.Ended != nil, Written: w} + if l.Written == nil { + l.Written = []string{} + } + if err != nil { + l.Failed = err.Error() + failed++ + } + total += len(w) + lines = append(lines, l) + } + out := map[string]any{"records": lines, "read": len(list), "written": total, "failed": failed} + if failed > 0 { + return out, fmt.Errorf("the ends of %d records were not followed in full", failed) + } + return out, nil +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go index 5d5bc3640..3818199b4 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordevents.go @@ -8,6 +8,7 @@ package main import ( "fmt" "sort" + "strconv" "strings" "time" @@ -150,8 +151,10 @@ func (rs *Records) end(r *Record, why, by string) error { body["delivery-time"], body["class"] = took.String(), class } } + // The end count one higher, and the highest pipeline end count the record heard (H-A-728). + body["ends"], body["pipeline-ends"] = r.Ends+1, r.PipelineEnds next := *r - next.Ended = &e + next.Ended, next.Ends = &e, r.Ends+1 if took > 0 { next.DeliveryTime, next.Class = took.String(), class } @@ -159,11 +162,12 @@ func (rs *Records) end(r *Record, why, by string) error { if err != nil { return err } - r.Ended, r.Sequence = &e, seq + r.Ended, r.Sequence, r.Ends = &e, seq, r.Ends+1 if took > 0 { r.DeliveryTime, r.Class = took.String(), class } rs.keep(r) + rs.endEntries(r, &e) if rs.Changed != nil { rs.Changed(r, RecordChange{What: "ended", Why: why, Ended: true}) } @@ -172,15 +176,161 @@ func (rs *Records) end(r *Record, why, by string) error { return nil } +// RanAfterEnd writes a record's end again from a running of one of its movers kept after the record ended (H-A-585, H-A-597, +// H-A-617): when that running is the first of its mover's version from a machine present at the end and later than the +// record's ended, ended takes its time and, for a record that ended with every mover running, delivery-time runs to it, with +// the class its movers' entries kept when they opened (H2 §810, H-A-394 (3)); the end count goes one higher and +// record-ended is said again with it. A running from a machine that was away at the end (a machine back, ADR 0603 §7), or +// a repeated one, marks the mover's entry (the caller applied it) and changes neither time nor count. The journal says the +// record, the module, the machine and both times when the time moved. Applied says the running was applied now; one applied +// before and not later than the end (its end written from it already) changes and says nothing. +func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error { + if r.Ended == nil { + return nil + } + for _, a := range r.Ended.Away { + if a.Node == o.Node { + return nil + } + } + was := r.Ended.At + if !o.At.After(was) { + return nil + } + e := *r.Ended + e.At = o.At + ends := r.Ends + 1 + body := map[string]any{"ended": e, "ends": ends} + next := *r + next.Ended, next.Ends = &e, ends + var took time.Duration + class := r.Class + if e.Why == WhyAllRun { + var kept string + if took, kept = timesAtEnd(r); took > 0 { + class = firstOf(class, kept) + body["delivery-time"], body["class"] = took.String(), class + next.DeliveryTime, next.Class = took.String(), class + } + } + seq, err := rs.write(r, r.Instance, OpEnd, body, next.head()) + if err != nil { + return err + } + r.Ended, r.Sequence, r.Ends = &e, seq, ends + if took > 0 { + r.DeliveryTime, r.Class = took.String(), class + } + rs.keep(r) + rs.endEntries(r, &e) + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q, end %d", + r.Instance, o.Module, o.Node, o.At.UTC().Format(time.RFC3339Nano), was.UTC().Format(time.RFC3339Nano), + r.Ended.At.UTC().Format(time.RFC3339Nano), r.DeliveryTime, ends) + } + return rs.sayEnded(r) +} + +// endEntries writes the head's ended, or none (nil, a reopening), on each of the record's movers and acts by their `end`, so +// an ended record's entries all take the lifetime of its end and an open one's none (design 47 H2 H-A-634 (2)). A write that +// fails is said in the journal, the record, the instance and the error, and the record's end stands. +func (rs *Records) endEntries(r *Record, e *RecordEnded) { + var value any + if e != nil { + value = *e + } + say := func(instance string, err error) { + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s: the end of its entry %s is not written: %v", r.Instance, instance, err) + } + if rs.EndUnwritten != nil { + rs.EndUnwritten(r.Instance, instance, err, true) + } + } + modules := make([]string, 0, len(r.movers)) + for module := range r.movers { + modules = append(modules, module) + } + sort.Strings(modules) + for _, module := range modules { + m := r.movers[module] + next := *m + next.Ended = copyEnded(e) + seq, err := rs.write(r, m.Instance, OpEnd, map[string]any{"ended": value}, next) + if err != nil { + say(m.Instance, err) + continue + } + m.Ended, m.Sequence = next.Ended, seq + } + ids := make([]string, 0, len(r.Acts)) + for id := range r.Acts { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + inst, err := ActInstance(r.Milestone, id) + if err != nil { + say(id, err) + continue + } + a := r.Acts[id] + a.Ended = copyEnded(e) + if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, a); err != nil { + say(inst, err) + continue + } + r.Acts[id] = a + } +} + +func copyEnded(e *RecordEnded) *RecordEnded { + if e == nil { + return nil + } + c := *e + return &c +} + +// Reopen reopens an ended record whose pipeline ended again with a higher end count (H-A-609 (2), H-A-728): its `ended` is +// emptied and pipeline-ends takes the count, its own end count staying; the next end says ends one higher. +func (rs *Records) Reopen(r *Record, pipelineEnds int) error { + if r.Ended == nil { + return nil + } + // Its movers' and acts' ended first, then the head's, so no open head has an entry whose key is ageing (H-A-634 (2)). + rs.endEntries(r, nil) + next := *r + next.Ended, next.PipelineEnds = nil, pipelineEnds + seq, err := rs.write(r, r.Instance, OpEnd, map[string]any{"ended": nil, "pipeline-ends": pipelineEnds}, next.head()) + if err != nil { + return err + } + was := r.Ended.At + r.Ended, r.PipelineEnds, r.Sequence = nil, pipelineEnds, seq + rs.keep(r) + if rs.Logf != nil { + rs.Logf("[mesh-delivery] the record %s, ended at %s, is open again: its pipeline ended again, end %d", r.Instance, + was.UTC().Format(time.RFC3339Nano), pipelineEnds) + } + return nil +} + func (rs *Records) sayEnded(r *Record) error { if r.Ended == nil { return nil } at := r.Ended.At - e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at} + e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at, + Ends: int64(r.Ends)} for _, a := range r.Ended.Away { since := a.Since e.Away = append(e.Away, meshdelivery.RecordEndedEventAwayItem{Node: a.Node, Since: &since}) } - return rs.say(meshdelivery.SubjectRecordEnded, e, "record-ended."+r.Instance) + // Each end is said under an id of its own, so an end said again is kept once and the next end is said (H-A-597, H-A-617). + id := "record-ended." + r.Instance + if r.Ends > 1 { + id += "." + strconv.Itoa(r.Ends) + } + return rs.say(meshdelivery.SubjectRecordEnded, e, id) } diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go index 00a9bd0b1..e8bec47ed 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordfill.go @@ -4,7 +4,7 @@ package main // full"): the gate reads its ledger's fill through the tool runner (mesh-sdk buscalls.LedgerFill), says `filling` of the // seat mesh-delivery when a record it opens takes the ledger past 80 % of its cap, refuses the next record when the // ledger has no room for one and says `full`, and holds that record's merge until the ledger is below 80 % again, when -// it says `room` and hands the merge. Nothing is dropped to make room: only the retention removes a record. The fill +// it says `room` and hands the merge. Nothing is dropped to make room: the bus ends an ended record's keys by the ledger's ended-days. The fill // is read from the bus at each judgement, and which merges wait for room is kept on their deliveries (Ready.HeldFull), // so a restarted gate judges as the one before it. @@ -95,7 +95,7 @@ func (rs *Records) refuseFull(milestone, inst string) (before buscalls.Fill, rea rs.sayFill(meshdelivery.SubjectFull, "full-"+inst, before, "the next record, "+inst+" of "+milestone+"; its merge is held until room is said") return before, true, fmt.Errorf("%w (%d of %d bytes): the record %s of %s is not opened, and its merge is held until "+ - "room is said: the setting record-retention or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone) + "room is said: ended-days of the ledger's own configuration or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone) } // sayFilling says filling when the record just opened took the ledger past FillingPercent of its cap. @@ -109,12 +109,9 @@ func (rs *Records) sayFilling(inst string, before buscalls.Fill) { } } -// RoomAgain is whether a merge held for a full ledger since then may be handed now: the records past their retention -// removed first, the ledger below FillingPercent of its cap, said once as room. A fill it cannot read gives no room. +// RoomAgain is whether a merge held for a full ledger since then may be handed now: the ledger below FillingPercent of its +// cap, said once as room. A fill it cannot read gives no room. func (rs *Records) RoomAgain(since time.Time) (bool, error) { - if err := rs.Sweep(rs.now()); err != nil { - return false, err - } f, err := rs.Fill() if err != nil { return false, err diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go new file mode 100644 index 000000000..29d553034 --- /dev/null +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordindexes.go @@ -0,0 +1,110 @@ +package main + +// The gate keeps the ledger's indexes `movers` and `acts` by a watcher of its own process (design 47 H2 H-A-690 (2) to (4); ADR +// 0597 §4): the tool runner stays the one writer of index keys, the gate asks it, by the repair `reindex`, for each instance +// that changed; at its start it reads `lag`, builds again whole each index behind, and gives every record's movers and acts its +// end before it follows the changes. + +import ( + "encoding/json" + "fmt" + "sync/atomic" + + "git.novox.be/novox/mesh-sdk/go/buscalls" +) + +// KeepIndexes is the gate's start of its indexes: `lag`, a whole `reindex` of each index it names behind (said with the count +// written), the finding index-behind for an index still behind after it and its clearing for one not, the pass of the ends over +// every record, then a watch of the ledger's `mover/>` and `act/>` that makes one `reindex` naming each instance a change +// hands after the current states. What fails is said and made again at the next change or the next start, never given up. +func (rs *Records) KeepIndexes() error { + rs.reindexBehind() + list, err := rs.Kept() + if err != nil { + return err + } + for _, r := range list { + if _, err := rs.followRecord(r); err != nil { + continue // said, and the finding raised, by the pass + } + } + var caught atomic.Bool + watch := func(index string) func(string, json.RawMessage) error { + return func(instance string, state json.RawMessage) error { + // The current states are not changes; a key gone by its lifetime (or removed) has no index key left to write. + if !caught.Load() || len(state) == 0 || string(state) == "null" { + return nil + } + rs.reindexInstance(index, instance) + return nil + } + } + for _, w := range []struct{ prefix, index string }{{TypeMover + "/>", MoversIndex}, {TypeAct + "/>", ActsIndex}} { + if err := rs.Ledger.Watch(w.prefix, watch(w.index)); err != nil { + return fmt.Errorf("the ledger's %s cannot be watched: %w", w.prefix, err) + } + } + caught.Store(true) + return nil +} + +// reindexInstance asks the tool runner to write one instance's entries of an index again; a call that fails is said and +// raises index-behind, and is made again at that instance's next change (H-A-690 (2), (3)). +func (rs *Records) reindexInstance(index, instance string) { + if _, err := rs.Ledger.Reindex(index, instance); err != nil { + rs.log("the index %s is not kept for %s: %v", index, instance, err) + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("the reindex of %s failed: %v", instance, err), true) + } + } +} + +// reindexBehind reads `lag` and builds again whole each index it names behind; an index still behind after it is raised as +// index-behind, one `lag` does not name is cleared (H-A-690 (2), (3)). +func (rs *Records) reindexBehind() { + lag, err := rs.Ledger.Lag() + if err != nil { + rs.log("the ledger's lag cannot be read, so no index is built again at this start: %v", err) + return + } + for _, index := range []string{MoversIndex, ActsIndex} { + if !behind(lag, index) { + if rs.IndexBehind != nil { + rs.IndexBehind(index, "", false) + } + continue + } + n, err := rs.Ledger.Reindex(index, "") + if err != nil { + rs.log("the index %s is behind and its reindex failed: %v", index, err) + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("the whole reindex failed: %v", err), true) + } + continue + } + rs.log("the index %s was behind its history and is built again: %d entries written", index, n) + again, err := rs.Ledger.Lag() + switch { + case err != nil: + rs.log("the ledger's lag cannot be read after the reindex of %s: %v", index, err) + case behind(again, index): + if rs.IndexBehind != nil { + rs.IndexBehind(index, fmt.Sprintf("still behind its history after a whole reindex (%d entries written)", n), true) + } + default: + if rs.IndexBehind != nil { + rs.IndexBehind(index, "", false) + } + } + } +} + +// behind is whether lag names the index behind its history. +func behind(l buscalls.Lagged, index string) bool { + for _, i := range l.Indexes { + if i.Index == index && i.Behind > 0 { + return true + } + } + return false +} diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go index aec852ae0..8dd091e59 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline.go @@ -33,6 +33,7 @@ import ( "time" nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine" + runnerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient" runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner" wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants" ) @@ -47,14 +48,30 @@ func strictly(body json.RawMessage, into any) error { return dec.Decode(into) } +// decodePipelineStarted reads a pipeline-started with the contract's decoder, so a field of the runner's other form that this +// reader does not know is left unread and the movers of the earlier form and of the new are taken alike (design 47 H2 +// H-A-709 (3)). func decodePipelineStarted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { - var p runner.PipelineStartedEvent - if err := strictly(body, &p); err != nil { + p, _, err := runner.DecodePipelineStartedEvent(body) + if err != nil { return nil, err } return nil, namesSource(p.Branch, p.Source, p.Run) } +// decodeMoverAdded reads a mover-added with the client's decoder, which refuses one naming none or two of from, caller and +// take-in (design 47 H2 H-A-645). +func decodeMoverAdded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { + m, err := runnerclient.MoverAdded(body) + if err != nil { + return nil, err + } + if m.Module == "" || m.Pipeline == "" { + return nil, fmt.Errorf("a mover-added names no module or pipeline") + } + return nil, nil +} + func decodePipelineEnded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) { var p runner.PipelineEndedEvent if err := strictly(body, &p); err != nil { @@ -134,6 +151,12 @@ func (h *Holder) Follow(event string, body json.RawMessage) error { return nil } return h.pipelineStarted(p) + case runner.EventMoverAdded: + m, err := runnerclient.MoverAdded(body) + if err != nil { + return nil + } + return h.moverAdded(m) case runner.EventPipelineEnded: var p runner.PipelineEndedEvent if err := json.Unmarshal(body, &p); err != nil || p.Run != "" { @@ -193,11 +216,45 @@ func (h *Holder) pipelineStarted(p runner.PipelineStartedEvent) error { return nil } -func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error { - r, err := h.openRecord(p.Branch, p.Source) - if err != nil || r == nil { +// moverAdded counts a mover added to a pipeline in the record that pipeline's key names, as wantWritten finds it (G §144, +// design 47 H2 H-A-609 (2), H-A-645): a mover carried into a pipeline whose record ended is counted there too, and the +// pipeline's next end with a higher end count reopens the record. +func (h *Holder) moverAdded(m runner.MoverAddedEvent) error { + milestone, _, _ := strings.Cut(m.Pipeline, ".published.") + r, err := h.Records.ByMilestone(milestone) + if err != nil { + return fmt.Errorf("the record of the pipeline %s cannot be read: %w", m.Pipeline, err) + } + if r == nil { + return nil + } + if err := h.Records.AddEntry(r, RecordEntry{Module: m.Module, Fingerprint: m.Fingerprint}); err != nil { return err } + return h.Records.SetMover(r, m.Module, m.Fingerprint, m.Pipeline, "") +} + +func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error { + r, err := h.Records.ByKey(p.Branch, p.Source) + if err != nil { + return fmt.Errorf("the record of %s at %d cannot be read: %w", p.Branch, p.Source, err) + } + if r == nil { + return nil + } + count := int(p.EndCount) + if r.Ended != nil { + // A pipeline that ended again, with an end count higher than the record heard, reopens its record; its first end + // reopens nothing (H-A-609 (2), H-A-728). + if count < 2 || count <= r.PipelineEnds { + return nil + } + if err := h.Records.Reopen(r, count); err != nil { + return err + } + } else if count > r.PipelineEnds { + r.PipelineEnds = count + } at := h.Now().UTC() if p.Ended != nil { at = p.Ended.UTC() diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go index 89d4e6b71..01ce3a4e6 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordpipeline_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" stdio "git.novox.be/novox/mesh-sdk/go" "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -61,6 +62,14 @@ func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) { if _, ok := r.Entries[EntryKey("app", "f", "")]; !ok || len(r.Entries) != 1 { t.Fatalf("entries %v: the mover is one, a run's none", r.Entries) } + // Design 47 H2 H-A-709 (3): a pipeline-started of the earlier form, whose movers carry fields the new form's StartedMover + // leaves out, is taken as the new form is: its movers are entries. + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"older","commit":"c","fingerprint":"o","repository":"novox/older","tier":1,"published":true,"widens":["x"],"tests":{"passed":3},"over-budget":false}]}`) + if _, ok := r.Entries[EntryKey("older", "o", "")]; !ok || len(r.Entries) != 2 { + t.Fatalf("entries %v: the earlier form's mover is one too", r.Entries) + } + delete(r.Entries, EntryKey("older", "o", "")) hear(t, c, "mesh-pipeline-runner.wait-held.main.1", "", `{"v":1,"branch":"main","source":1,"pipeline":"main.1","module":"app","fingerprint":"f","step":"approval","on":"person","who":"the operator","since":"2026-11-20T03:01:00Z"}`) held := r.Outcomes[OutcomeKey("app", "f", "", "approval")] @@ -122,39 +131,50 @@ func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, erro return seq, err } -// 721/AC1 (issue 721 note 11; design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so -// one can be heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits -// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it -// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer -// taken before the next event writes the record. +// heardBed is what the gate said while a row of TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied ran. +type heardBed struct { + ended int // the record-ended said + journal []string // the lines the records said in the journal +} + +// Issue 721 note 11 (design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so one can be +// heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits until the running +// is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it ended the record +// with neither, the delivery time lost), and the call show answers the record with the running, its answer taken before the +// next event writes the record. A pipeline-wanted heard before the running (H-A-585) ends the record, and the running heard +// after is applied to it: ended and delivery-time are written again from it, the class kept, record-ended said once and the +// journal told, also when that end could first not be written and the running is offered again. func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { running := func(node string) stdio.Envelope { return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage( `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"` + node + `","fingerprint":"f","healthy":true}`)} } + pipelineWanted := func(h *Holder) (any, error) { + return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage( + `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)}) + } for _, tc := range []struct { - name string - heard func(h *Holder) (any, error) - check func(t *testing.T, h *Holder, answer any) + name string + // before hears it before the running, a minute earlier; else it is heard as the running's write lands. + before bool + heard func(h *Holder) (any, error) + check func(t *testing.T, h *Holder, answer any, said *heardBed) }{ - {"pipeline-wanted", func(h *Holder) (any, error) { - return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage( - `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)}) - }, func(t *testing.T, h *Holder, _ any) { + {"pipeline-wanted", false, pipelineWanted, func(t *testing.T, h *Holder, _ any, said *heardBed) { r, err := h.Records.ByKey("main", 1) - if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore { - t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q (%v); want 5m0s and core", r.Ended, - r.DeliveryTime, r.Class, err) + if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore || said.ended != 1 { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, said %d times (%v); want 5m0s and core, once", + r.Ended, r.DeliveryTime, r.Class, said.ended, err) } }}, - {"the call show", func(h *Holder) (any, error) { + {"the call show", false, func(h *Holder) (any, error) { for _, tool := range tools(h, &listening{}) { if tool.Name == Seat+".show" { return tool.Run(map[string]any{"id": "main.1"}) } } return nil, fmt.Errorf("the gate serves no %s.show", Seat) - }, func(t *testing.T, h *Holder, answer any) { + }, func(t *testing.T, h *Holder, answer any, _ *heardBed) { if err := take(h, running("g14")); err != nil { t.Fatal(err) } @@ -173,12 +193,46 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { t.Fatal(err) } }}, + {"pipeline-wanted before the running (H-A-585)", true, pipelineWanted, func(t *testing.T, h *Holder, _ any, said *heardBed) { + r, err := h.Records.ByKey("main", 1) + ran := time.Date(2026, 11, 20, 3, 6, 0, 0, time.UTC) + if err != nil || r == nil || r.Ended == nil || !r.Ended.At.Equal(ran) || r.Ended.Why != WhyAllRun || r.DeliveryTime != "6m0s" || + r.Class != catalogue.ClassCore || said.ended != 2 || r.Ends != 2 { + t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q, end %d, said %d times (%v); want ended at the "+ + "running, 6m0s and core, said at its end and again at the late running (H-A-597)", r.Ended, r.DeliveryTime, r.Class, r.Ends, said.ended, err) + } + if o := r.Outcomes[OutcomeKey("app", "f", "ace", StepRunning)]; o.Outcome != OutcomeRunning { + t.Fatalf("the running after the end is %+v", o) + } + var lines []string + for _, l := range said.journal { + if strings.Contains(l, "after it ended") { + lines = append(lines, l) + } + } + if len(lines) != 1 || !strings.Contains(lines[0], r.Instance) || !strings.Contains(lines[0], "app on ace") || + !strings.Contains(lines[0], "03:05:00Z") || !strings.Contains(lines[0], "03:06:00Z") { + t.Fatalf("the journal says %q: want one line naming the record, the module, the machine and both times", said.journal) + } + // The ledger holds what memory does. + back, err := h.Records.Read(r.Instance) + if err != nil || back.Ended == nil || !back.Ended.At.Equal(ran) || back.DeliveryTime != "6m0s" || back.Class != catalogue.ClassCore || back.Ends != 2 { + t.Fatalf("the ledger keeps %+v, %q, %q, end %d (%v)", back.Ended, back.DeliveryTime, back.Class, back.Ends, err) + } + }}, } { t.Run(tc.name, func(t *testing.T) { now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + said := &heardBed{} h := &Holder{Now: func() time.Time { return now }} ledger := &hookedLedger{ledgerFake: newLedgerFake(t)} - h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }} + h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }, + Say: func(subject string, _ any, _ string) error { + if strings.Contains(subject, "record-ended") { + said.ended++ + } + return nil + }, Logf: func(format string, a ...any) { said.journal = append(said.journal, fmt.Sprintf(format, a...)) }} h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { t.Fatal(err) @@ -196,20 +250,33 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { err error } heard := make(chan heardOut, 1) - ledger.after = func(_, operation string, body any) { - if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning { - return + if tc.before { + answer, err := tc.heard(h) + heard <- heardOut{answer, err} + now = now.Add(time.Minute) + // The end written again from the running is refused at first: the running is offered again (the take below), + // and the end is written then. + ledger.failOn = OpEnd + if err := take(h, running("ace")); err == nil { + t.Fatal("a running whose end could not be written again is taken") } - ledger.after = nil - // Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's - // goroutines allow, else on a goroutine of its own, as the runtime hands it. - hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} } - if h.applying.TryLock() { - h.applying.Unlock() - hear() - return + ledger.failOn = "" + } else { + ledger.after = func(_, operation string, body any) { + if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning { + return + } + ledger.after = nil + // Heard as the running's write lands: taken there and then when nothing holds the records, as the + // runtime's goroutines allow, else on a goroutine of its own, as the runtime hands it. + hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} } + if h.applying.TryLock() { + h.applying.Unlock() + hear() + return + } + go hear() } - go hear() } if err := take(h, running("ace")); err != nil { t.Fatal(err) @@ -218,11 +285,123 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) { if out.err != nil { t.Fatal(out.err) } - tc.check(t, h, out.answer) + tc.check(t, h, out.answer, said) }) } } +// Design 47 H2 H-A-597, H-A-609 (2), H-A-617, H-A-645, H-A-728: a first end says ends 1; a late running from a machine present +// at the end moves the end and says record-ended again with ends 2, one from a machine that was away and a repeated one +// move nothing; a pipeline-ended of a first end, or of a count not higher than the record heard, reopens nothing and a +// higher one reopens it, its next end saying ends one higher; a mover-added counts its mover in the record its pipeline +// names, and one naming none or two of from, caller and take-in is refused. +func TestARecordsEndCountIsSaidAtEachEndAndAHigherPipelineEndReopensIt(t *testing.T) { + now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC) + var said []meshdelivery.RecordEndedEvent + var ids []string + h := &Holder{Now: func() time.Time { return now }} + h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now, Say: func(subject string, body any, id string) error { + if e, ok := body.(meshdelivery.RecordEndedEvent); ok { + said, ids = append(said, e), append(ids, id) + } + return nil + }} + if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil { + t.Fatal(err) + } + if _, err := h.Records.Kept(); err != nil { + t.Fatal(err) + } + r, _ := h.Records.ByKey("main", 1) + c := &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow} + hear(t, c, "mesh-pipeline-runner.pipeline-started.main.1", "", + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`) + for _, node := range []string{"ace", "g14"} { + hear(t, c, "mesh-wants.wanted.x.app", "", `{"v":1,"node":"`+node+`","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12}`) + } + if err := h.Records.NodeAway(r, "g14", now); err != nil { + t.Fatal(err) + } + running := func(node string) { + hear(t, c, "node-engine.running."+node+".app", node, `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"`+node+`","fingerprint":"f","healthy":true}`) + } + pipelineWanted := func() { + hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`) + } + pipelineEnded := func(count int) { + hear(t, c, "mesh-pipeline-runner.pipeline-ended.main.1", "", fmt.Sprintf( + `{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"passed","end-count":%d,"movers":[]}`, count)) + } + // The first end, with ace not heard running yet and g14 away: ends 1. + now = now.Add(time.Minute) + pipelineWanted() + if r.Ended == nil || r.Ends != 1 || len(said) != 1 || said[0].Ends != 1 || ids[0] != "record-ended."+r.Instance { + t.Fatalf("the record ended %+v at end %d, said %+v under %v: want the first end, ends 1", r.Ended, r.Ends, said, ids) + } + endedAt := r.Ended.At + // A running from the machine that was away at the end moves nothing; a late one from ace, present at the end, moves it. + now = now.Add(time.Minute) + running("g14") + if !r.Ended.At.Equal(endedAt) || r.Ends != 1 || len(said) != 1 { + t.Fatalf("a machine back moved the end to %v, end %d, said %d times", r.Ended.At, r.Ends, len(said)) + } + now = now.Add(time.Minute) + running("ace") + if !r.Ended.At.Equal(now) || r.Ends != 2 || len(said) != 2 || said[1].Ends != 2 || ids[1] != "record-ended."+r.Instance+".2" { + t.Fatalf("a late running left the end at %v, end %d, said %+v under %v: want it moved, ends 2, said again under an id of its own", r.Ended.At, r.Ends, said, ids) + } + now = now.Add(time.Minute) + running("ace") + if r.Ends != 2 || len(said) != 2 { + t.Fatalf("a repeated running changed the end to %d, said %d times", r.Ends, len(said)) + } + back, err := h.Records.Read(r.Instance) + if err != nil || back.Ends != 2 || back.PipelineEnds != 0 { + t.Fatalf("the ledger keeps end %d and pipeline end %d (%v): the late running leaves the pipeline's count unchanged", back.Ends, back.PipelineEnds, err) + } + // A pipeline's first end, and a count not higher than the record heard, reopen nothing; a higher one reopens it. + pipelineEnded(1) + if r.Ended == nil { + t.Fatal("a first pipeline end reopened the record") + } + pipelineEnded(2) + if r.Ended != nil || r.PipelineEnds != 2 || r.Ends != 2 { + t.Fatalf("a pipeline ended again left the record ended %+v, pipeline end %d, end %d: want it open, both counts kept", r.Ended, r.PipelineEnds, r.Ends) + } + pipelineWanted() + if r.Ended == nil || r.Ends != 3 || len(said) != 3 || said[2].Ends != 3 || ids[2] != "record-ended."+r.Instance+".3" { + t.Fatalf("the reopened record ended %+v at end %d, said %+v: want ends 3", r.Ended, r.Ends, said) + } + pipelineEnded(2) + if r.Ended == nil || r.Ends != 3 { + t.Fatalf("a pipeline end not higher than the record heard reopened it: %+v, end %d", r.Ended, r.Ends) + } + if back, err = h.Records.Read(r.Instance); err != nil || back.Ended == nil || back.Ends != 3 || back.PipelineEnds != 2 { + t.Fatalf("the ledger keeps %+v, end %d, pipeline end %d (%v)", back.Ended, back.Ends, back.PipelineEnds, err) + } + // A mover-added counts its mover in the record its pipeline's key names; one naming none or two of its sources is refused. + hear(t, c, "mesh-pipeline-runner.mover-added.main.1", "", `{"v":1,"pipeline":"main.1","revision":4,"module":"extra","fingerprint":"x","from":"main.1.again.1"}`) + var refusals []string + c.Logf = func(format string, a ...any) { refusals = append(refusals, fmt.Sprintf(format, a...)) } + for _, bad := range []string{ + `{"v":1,"pipeline":"main.1","revision":4,"module":"never","fingerprint":"y"}`, + `{"v":1,"pipeline":"main.1","revision":4,"module":"never","fingerprint":"y","from":"a","take-in":3}`, + } { + hear(t, c, "mesh-pipeline-runner.mover-added.main.1", "", bad) + } + // Each is refused by the client's decoder and said (AC-DC2c, H-A-645). + if len(refusals) != 2 || !strings.Contains(refusals[0]+refusals[1], "meshpipelinerunnerclient: mover-added names exactly one of from, caller and take-in, not 0") || + !strings.Contains(refusals[1], "not 2") { + t.Errorf("the refusals said %q: want the client decoder's, one naming none and one naming two", refusals) + } + if _, ok := r.Entries[EntryKey("extra", "x", "")]; !ok { + t.Errorf("a mover-added counted no mover: %v", r.Entries) + } + if _, ok := r.Entries[EntryKey("never", "y", "")]; ok { + t.Errorf("a mover-added naming none or two of its sources counted a mover: %v", r.Entries) + } +} + // GATE-5/AC (design 47 H §738, §751; H-A-75, H-A-89 (3), (4)): a pipeline-ended not passed ends the record failed naming // the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running. func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) { diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go index c8ab68e22..9568424aa 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/recordtools.go @@ -51,7 +51,7 @@ func (rs *Records) RecordOf(instance, milestone string) ([]recordView, error) { if milestone == "" { return nil, errors.New("name a record's instance or a milestone") } - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } @@ -84,7 +84,7 @@ type recordLine struct { // Lines are every record kept, oldest first, each with its fill against the value limit. func (rs *Records) Lines() (map[string]any, error) { - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } @@ -102,8 +102,8 @@ func (rs *Records) Lines() (map[string]any, error) { } lines = append(lines, l) } - return map[string]any{"records": lines, "open": open, "kept": len(lines), "retention-days": int(rs.retention().Hours() / 24), - "fill": rs.fillLine()}, nil + return map[string]any{"records": lines, "open": open, "kept": len(lines), "ended-days": rs.EndedDays, + "keeping-days": rs.KeepingDays, "soonest-expires": rs.soonest(list), "fill": rs.fillLine()}, nil } // EndByHand ends one open record by hand, with the reason, recorded in the hand-act log first: nothing is ended when the @@ -143,7 +143,7 @@ func (rs *Records) EndAllByHand(why, by string, acts handActs) (map[string]any, if strings.TrimSpace(why) == "" { return nil, errors.New("say why every open record is ended by hand, such as the clean state") } - list, err := rs.List() + list, err := rs.Kept() if err != nil { return nil, err } @@ -216,6 +216,35 @@ func recordTools(h *Holder, acts handActs) []stdio.Tool { } return h.Records.Lines() }}, + {Name: "gate_records_expiring", + Description: "What the ledger's lifetimes take, removing nothing (design 47 H2 H-A-634 (7)): every ended delivery record whose " + + "key the bus ends within within days (1 to 3650, default the ledger's ended-days), the soonest first, with its key, " + + "when it opened and ended, its expires as the bus holds it, and its movers and acts as the head counts them and as the " + + "indexes name them; and how many open records are kept, whatever their age. At most 768 KB a page, with capped, total " + + "and the next page's cursor.", + Input: map[string]any{"type": "object", "properties": map[string]any{ + "within": map[string]any{"type": "integer", "description": "days from now, 1 to 3650; the ledger's ended-days when absent"}, + "next": str("the cursor the previous page answered")}}, + Run: func(a map[string]any) (any, error) { + if h.Records == nil { + return none() + } + within, _ := a["within"].(float64) + return h.Records.Expiring(int(within), strArg(a, "next")) + }}, + {Name: "gate_records_follow_ends", + Description: "Do by hand the pass the gate makes at its start (design 47 H2 H-A-634 (7)): give every mover and act of an ended " + + "delivery record that record's end where they hold another, and take it from those of an open record, found through " + + "the ledger's indexes movers and acts; answers each record and the instances it wrote. Recorded in the hand-act log " + + "of the seat mesh-hand-acts first.", + Input: map[string]any{"type": "object", "properties": map[string]any{ + "why": str("why the ends are followed by hand, in plain words")}, "required": []string{"why"}}, + Run: func(a map[string]any) (any, error) { + if h.Records == nil { + return none() + } + return h.Records.FollowEnds(strArg(a, "why"), acts) + }}, {Name: "gate_consumer", Description: "The delivery record's consumer of the step events: per family the events applied and refused " + "since the gate started, the last applied, and why the last was refused.", diff --git a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go index becf0c8f7..bf9cef69d 100644 --- a/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go +++ b/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/settings.go @@ -14,9 +14,6 @@ import ( // Settings are the operator's values for this module. type Settings struct { - // RecordRetentionDays is how many days a delivery record is kept from when it opened (design 47 *The delivery - // record*); nil keeps DefaultRecordRetention. - RecordRetentionDays *int `json:"record-retention"` // UntakenBoundMinutes is how many minutes a head may stand untaken before head-untaken is raised (design 47 H §740); nil // keeps DefaultUntakenBound. UntakenBoundMinutes *int `json:"untaken-bound"` @@ -25,7 +22,7 @@ type Settings struct { // DefaultUntakenBound is untaken-bound when the setting gives none (§740). const DefaultUntakenBound = 10 * time.Minute -// readSettings reads the settings file; a value that is not a whole number of days, from 1 to 3650, is refused. +// readSettings reads the settings file; a value that is not a whole number of minutes, at least 1, is refused. func readSettings(path string) (Settings, error) { var s Settings if path == "" { @@ -39,17 +36,6 @@ func readSettings(path string) (Settings, error) { if err := json.Unmarshal(raw, &loose); err != nil { return s, fmt.Errorf("the settings file is not JSON: %v", err) } - switch v := loose["record-retention"].(type) { - case nil: - case float64: - n := int(v) - if v < 1 || v > 3650 || v != float64(n) { - return Settings{}, errors.New("record-retention is not a whole number of days, from 1 to 3650") - } - s.RecordRetentionDays = &n - default: - return Settings{}, errors.New("record-retention is not a number") - } switch v := loose["untaken-bound"].(type) { case nil: case float64: @@ -63,14 +49,3 @@ func readSettings(path string) (Settings, error) { } return s, nil } - -// recordRetention is how long a delivery record is kept from when it opened. -func (h *Holder) recordRetention() time.Duration { - if h.Settings == nil { - return DefaultRecordRetention - } - if n := h.Settings().RecordRetentionDays; n != nil { - return time.Duration(*n) * 24 * time.Hour - } - return DefaultRecordRetention -} diff --git a/modules/mesh-delivery-gate/files/settings.json b/modules/mesh-delivery-gate/files/settings.json index 63414735c..b3b492a24 100644 --- a/modules/mesh-delivery-gate/files/settings.json +++ b/modules/mesh-delivery-gate/files/settings.json @@ -1,4 +1,3 @@ { - "record-retention": 90, "untaken-bound": 10 } diff --git a/modules/mesh-delivery-gate/go.mod b/modules/mesh-delivery-gate/go.mod index 1cfa2af70..fdb7c73c3 100644 --- a/modules/mesh-delivery-gate/go.mod +++ b/modules/mesh-delivery-gate/go.mod @@ -9,6 +9,7 @@ require ( git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshpipelinerunnerclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner v0.0.0-00010101000000-000000000000 diff --git a/modules/mesh-delivery-gate/manifest.go b/modules/mesh-delivery-gate/manifest.go index a6214ed30..a20fab017 100644 --- a/modules/mesh-delivery-gate/manifest.go +++ b/modules/mesh-delivery-gate/manifest.go @@ -21,3 +21,26 @@ func Consumes() ([]string, error) { } return m.Consumes, nil } + +// RecordsDays are the days the manifest's ledger `records` keeps its history (`max-age-days`) and an ended instance's state +// (`ended-days`), as its `configuration` says them (design 47 H2 H-A-634 (7)); the gate's read tools say them beside the records. +func RecordsDays() (keeping, ended int, err error) { + var m struct { + Requires []struct { + Name string `json:"name"` + Configuration map[string]any `json:"configuration"` + } `json:"requires"` + } + if err := json.Unmarshal(manifest, &m); err != nil { + return 0, 0, fmt.Errorf("the gate's own manifest is not readable: %w", err) + } + for _, r := range m.Requires { + if r.Name != "records" { + continue + } + k, _ := r.Configuration["max-age-days"].(float64) + e, _ := r.Configuration["ended-days"].(float64) + return int(k), int(e), nil + } + return 0, 0, fmt.Errorf("the gate's own manifest asks for no ledger records") +} diff --git a/modules/mesh-delivery-gate/module.json b/modules/mesh-delivery-gate/module.json index a6cb5797e..82a713dcb 100644 --- a/modules/mesh-delivery-gate/module.json +++ b/modules/mesh-delivery-gate/module.json @@ -22,6 +22,7 @@ "mesh-delivery-forge-bridge.forge.*.*.*.head-moved", "mesh-delivery-indexer.take-in.taken", "mesh-pipeline-runner.pipeline-started.*.*", + "mesh-pipeline-runner.mover-added.*.*", "mesh-pipeline-runner.pipeline-ended.*.*", "mesh-pipeline-runner.wait-held.*.*", "mesh-pipeline-runner.wait-ended.*.*", @@ -37,11 +38,16 @@ "storage": "ledger", "template": "ledger", "options": { - "max-mib": 1024 + "max-mib": 3072 + }, + "configuration": { + "max-age-days": 90, + "ended-days": 30 }, "types": [ { "name": "record", + "ends-with": "ended", "schema": { "milestone": { "type": "string" @@ -120,6 +126,12 @@ }, "phases": { "type": "object" + }, + "ends": { + "type": "integer" + }, + "pipeline-ends": { + "type": "integer" } }, "operations": [ @@ -193,7 +205,9 @@ "fields": [ "ended", "delivery-time", - "class" + "class", + "ends", + "pipeline-ends" ], "sequence": true } @@ -201,6 +215,7 @@ }, { "name": "mover", + "ends-with": "ended", "schema": { "record": { "type": "string" @@ -240,6 +255,9 @@ }, "class": { "type": "string" + }, + "ended": { + "type": "object" } }, "operations": [ @@ -285,6 +303,14 @@ "into": "outcomes", "key": "key", "sequence": true + }, + { + "name": "end", + "effect": "set-fields", + "fields": [ + "ended" + ], + "sequence": true } ], "indexes": [ @@ -298,6 +324,7 @@ }, { "name": "act", + "ends-with": "ended", "schema": { "record": { "type": "string" @@ -328,6 +355,9 @@ }, "owed": { "type": "object" + }, + "ended": { + "type": "object" } }, "operations": [ @@ -347,6 +377,14 @@ "owed" ], "sequence": true + }, + { + "name": "end", + "effect": "set-fields", + "fields": [ + "ended" + ], + "sequence": true } ], "indexes": [ @@ -452,6 +490,8 @@ "gate_record_end", "gate_record_repair", "gate_records", + "gate_records_expiring", + "gate_records_follow_ends", "gate_source", "gate_source_again", "gate_source_seed", @@ -461,14 +501,6 @@ "mesh-delivery-gate_state_prune_now" ], "config": { - "record-retention": { - "type": "number", - "description": "days a delivery record is kept from when it opened (design 47 *The delivery record*): ninety covers every trace asked of a past delivery so far; when a record is removed at its retention, the gate says freed for each graph revision it pinned. Nothing else is removed to make room.", - "minimum": 1, - "maximum": 3650, - "trusted": false, - "default": 90 - }, "untaken-bound": { "type": "number", "description": "minutes a watched branch's head may stand that no merge call delivered before the gate raises head-untaken (design 47 H §740); the gate keeps one deadline timer for the earliest.", @@ -523,7 +555,6 @@ "path": "${dir:state}/settings.json", "mode": "0600", "takes-config": [ - "record-retention", "untaken-bound" ], "merge": "json", diff --git a/modules/mesh-issues/cmd/mesh-issues/fixtime_test.go b/modules/mesh-issues/cmd/mesh-issues/fixtime_test.go index 8de5cfe94..ada4388b5 100644 --- a/modules/mesh-issues/cmd/mesh-issues/fixtime_test.go +++ b/modules/mesh-issues/cmd/mesh-issues/fixtime_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "fmt" "strings" "testing" "time" @@ -471,6 +472,42 @@ func TestTheReviewEndsAtTheFirstPassedReviewStepOfTheRunner(t *testing.T) { } } +// H-A-709 (2): the runner's `show` is read to its last page; the steps of every page are the row's; a page that fails writes no row. +func TestTheRunnersShowIsReadToItsLastPage(t *testing.T) { + page := func(next, step, outcome, ended string) json.RawMessage { + e := "" + if ended != "" { + e = `,"ended":"` + ended + `"` + } + return json.RawMessage(`{"pipeline":{"pipeline":"b.1.m","module":"m","outcome":"passed","steps":[{"step":"` + step + `","outcome":"` + outcome + `"` + e + `}]},"capped":` + + fmt.Sprint(next != "") + `,"next":"` + next + `"}`) + } + pages := map[string]json.RawMessage{"": page("c1", "lint", "passed", ""), "c1": page("c2", "unit", "passed", ""), + "c2": page("", "review", "passed", "2026-10-12T09:05:00Z")} + var asked []string + row, err := readPipeline(func(a map[string]any) (json.RawMessage, error) { + next, _ := a["next"].(string) + asked = append(asked, next) + return pages[next], nil + }, "b.1.m", "r#1") + if err != nil || len(row.Steps) != 3 || row.reviewed.IsZero() || fmt.Sprint(asked) != "[ c1 c2]" { + t.Fatalf("row %+v, asked %q, %v: every page's steps are the row's, the last page's review among them", row, asked, err) + } + // A page that fails: no row, the error names the page. + if row, err := readPipeline(func(a map[string]any) (json.RawMessage, error) { + if a["next"] == "c1" { + return nil, errFake("the runner is away") + } + return pages[""], nil + }, "b.1.m", "r#1"); err == nil || !strings.Contains(err.Error(), "page 2") || row.Module != "" { + t.Fatalf("row %+v, error %v", row, err) + } + // A cursor answered again is no endless read. + if _, err := readPipeline(func(map[string]any) (json.RawMessage, error) { return page("c1", "lint", "passed", ""), nil }, "b.1.m", "r#1"); err == nil { + t.Fatal("a cursor repeated was read on") + } +} + type errFake string func (e errFake) Error() string { return string(e) } diff --git a/modules/mesh-issues/cmd/mesh-issues/pipelines.go b/modules/mesh-issues/cmd/mesh-issues/pipelines.go index 78465a7a4..bc2c983ae 100644 --- a/modules/mesh-issues/cmd/mesh-issues/pipelines.go +++ b/modules/mesh-issues/cmd/mesh-issues/pipelines.go @@ -88,6 +88,46 @@ func parsePipelineRow(raw json.RawMessage, pr string) (PipelineRow, error) { return row, nil } +// readPipeline reads one pipeline through `show`, page after page: each page's `next` is asked until none is left, the steps of +// every page are the row's (design 47 H2 H-A-709 (2): the runner answers within a bound). A page that fails fails the read, +// so no row is written from the pages before it. +func readPipeline(ask func(args map[string]any) (json.RawMessage, error), key, pr string) (PipelineRow, error) { + var row PipelineRow + next, seen := "", map[string]bool{} + for page := 1; ; page++ { + args := map[string]any{"pipeline": key} + if next != "" { + args["next"] = next + } + raw, err := ask(args) + if err != nil { + return PipelineRow{}, fmt.Errorf("page %d of %s: %w", page, key, err) + } + got, err := parsePipelineRow(raw, pr) + if err != nil { + return PipelineRow{}, fmt.Errorf("page %d of %s: %w", page, key, err) + } + if page == 1 { + row = got + } else { + row.Steps = append(row.Steps, got.Steps...) + if !got.reviewed.IsZero() && (row.reviewed.IsZero() || got.reviewed.Before(row.reviewed)) { + row.reviewed = got.reviewed + } + } + m, _ := answerOf(raw, "mesh-pipeline-runner.show") + next = "" + _ = json.Unmarshal(m["next"], &next) + if next == "" { + return row, nil + } + if seen[next] { + return PipelineRow{}, fmt.Errorf("page %d of %s: the runner answered the cursor %q again", page, key, next) + } + seen[next] = true + } +} + // busPipelines reads a pull request's head from the seat `git`, then its pipelines from the runner: `list` given the head // commit, `show` of each. func busPipelines(owner string) Pipelines { @@ -110,11 +150,9 @@ func busPipelines(owner string) Pipelines { } var rows []PipelineRow for _, k := range keys { - raw, err := stdio.Ask("seat:mesh-pipeline-runner.show", map[string]any{"pipeline": k}) - if err != nil { - return nil, err - } - row, err := parsePipelineRow(raw, pr) + row, err := readPipeline(func(args map[string]any) (json.RawMessage, error) { + return stdio.Ask("seat:mesh-pipeline-runner.show", args) + }, k, pr) if err != nil { return nil, err } diff --git a/modules/mesh-provisioner/cmd/mesh-provisioner/holder.go b/modules/mesh-provisioner/cmd/mesh-provisioner/holder.go index 476dae2e5..460739f58 100644 --- a/modules/mesh-provisioner/cmd/mesh-provisioner/holder.go +++ b/modules/mesh-provisioner/cmd/mesh-provisioner/holder.go @@ -1738,13 +1738,39 @@ func (w watchingStore) copied(state string) bool { return slices.Contains(WatchedReads, state) || slices.Contains(OwnStates, state) } +// Unread is the fault `away` while the copy of a state the holder follows from its start is not read yet (design 47 H2 +// H-A-708 (2), H-A-717 DQ-55). A verb or tool handler asks it (Holder.Away) so a call made then is answered at once; the +// store's own reads, the passes' and the start's, wait for the copy. +func (w watchingStore) Unread(state string) error { + if !slices.Contains(WatchedReads, state) { + return nil + } + return w.ws.Unread(state) +} + +// Away is the fault `away` when the copy of any of these states, or of every followed state when none is named, is not +// read yet: a verb or tool handler asks it before it reads, never the passes (design 47 H2 H-A-708 (2)). +func (h *Holder) Away(states ...string) error { + u, ok := h.Store.(interface{ Unread(string) error }) + if !ok { + return nil + } + if len(states) == 0 { + states = WatchedReads + } + for _, state := range states { + if err := u.Unread(state); err != nil { + return err + } + } + return nil +} + func (w watchingStore) Get(state, key string) (*Entry, error) { - get := w.ws.Get - switch { - case !w.copied(state): + if !w.copied(state) { return w.Store.Get(state, key) } - v, found, err := get(state, key) + v, found, err := w.ws.Get(state, key) if err != nil || !found { return nil, err } diff --git a/modules/mesh-provisioner/cmd/mesh-provisioner/holder_integration_test.go b/modules/mesh-provisioner/cmd/mesh-provisioner/holder_integration_test.go index 5c529a0eb..2242eab4d 100644 --- a/modules/mesh-provisioner/cmd/mesh-provisioner/holder_integration_test.go +++ b/modules/mesh-provisioner/cmd/mesh-provisioner/holder_integration_test.go @@ -203,6 +203,10 @@ func TestTheHolderPlansProvidesAndAsksOnTheBus(t *testing.T) { return p } key := node + ".restic.postgres-database" + // The holder follows its states from its start (main.go), so a read finds its copies read (H-A-708 (2)). + for _, r := range WatchedReads { + ws.Follow(r, nil) + } if _, err := h.ComposeNode(ctx, node); err != nil { t.Fatal(err) } diff --git a/modules/mesh-provisioner/cmd/mesh-provisioner/holder_test.go b/modules/mesh-provisioner/cmd/mesh-provisioner/holder_test.go index dcd74f76f..d18157f19 100644 --- a/modules/mesh-provisioner/cmd/mesh-provisioner/holder_test.go +++ b/modules/mesh-provisioner/cmd/mesh-provisioner/holder_test.go @@ -21,6 +21,7 @@ import ( oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" "git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/catalogue" ) @@ -486,6 +487,22 @@ func TestAModuleHeldWithoutAWantIsComposedAtTheBuildItRuns(t *testing.T) { }, func(string, string) ([]byte, bool, error) { return nil, false, nil }) m.h.Store = Watching(bus, ws) wk := &work{pending: map[string]bool{}, wake: make(chan struct{}, 1)} + // H-A-708 (2): a state the holder follows from its start, asked before its copy is read, is the fault `away` at once. + var away *busretry.Away + // A handler asks Away and is answered at once; the holder's own reads (the passes, the start) wait, so the first read + // starts the watch and is answered from it, never `away`. + if err := m.h.Away(); !errors.As(err, &away) || !strings.HasPrefix(away.Words, "not read yet since ") || len(watches) != 0 { + t.Fatalf("a handler's ask before the copy: %v, watches %v", err, watches) + } + if _, err := m.h.Store.Keys(WantsRead); err != nil || watches[WantsRead] != 1 { + t.Fatalf("the holder's own read before the copy is read: %v, watches %v", err, watches) + } + if _, err := m.h.read(WantsRead, "", "", ""); err != nil { + t.Fatalf("a handler's read of a state whose copy is read: %v", err) + } + for _, r := range []string{AssignmentsRead, WantsRead} { + ws.Follow(r, nil) + } for _, r := range []string{ComposedRead, HaveRead} { ws.Follow(r, func(c stdio.StateChange) error { wk.add(NodesOfNodeKey(c.Key)...); return nil }) } diff --git a/modules/mesh-provisioner/cmd/mesh-provisioner/holdertools.go b/modules/mesh-provisioner/cmd/mesh-provisioner/holdertools.go index 227695642..e535607ea 100644 --- a/modules/mesh-provisioner/cmd/mesh-provisioner/holdertools.go +++ b/modules/mesh-provisioner/cmd/mesh-provisioner/holdertools.go @@ -79,6 +79,9 @@ func holderTools(h *Holder) []stdio.Tool { if arg(a, "node") == "" { return nil, fmt.Errorf("compose names the node") } + if err := h.Away(); err != nil { + return nil, err + } many, _ := a["retire-many"].(bool) return h.ComposeNodeWith(context.Background(), arg(a, "node"), many) }}, @@ -118,6 +121,9 @@ func (h *Holder) health() health.Answer { // read is a state's keys narrowed, or one whole, with the state's fill. func (h *Holder) read(state, key, node, want string) (any, error) { + if err := h.Away(state); err != nil { + return nil, err + } if key != "" { e, err := h.Store.Get(state, key) if err != nil { diff --git a/modules/mesh-vault/cmd/mesh-vault/assignmentsview.go b/modules/mesh-vault/cmd/mesh-vault/assignmentsview.go index 2c144ddea..193a2f044 100644 --- a/modules/mesh-vault/cmd/mesh-vault/assignmentsview.go +++ b/modules/mesh-vault/cmd/mesh-vault/assignmentsview.go @@ -77,21 +77,18 @@ func unwrapToolAnswer(raw json.RawMessage) []byte { return raw } -// viewAssignments is the assignments reader over the picture: a key asked before the first view is answered is an error, so -// the caller waits (the "not yet" of the vault's other reads), never a read of the owner's bucket. +// viewAssignments is the assignments reader over the picture: a key asked before the first view is answered is the fault +// `away` naming the view's owner verb (design 47 H2 H-A-708 (2), H-A-717 DQ-55), never a read of the owner's bucket. func viewAssignments(f func() *views.Follower) AssignerReader { ready := func() (*views.Follower, error) { fol := f() if fol == nil { return nil, fmt.Errorf("the vault reads the assigner's assignments only when it runs as the module") } - select { - case <-fol.Ready(): - return fol, nil - default: - s := fol.Status() - return nil, fmt.Errorf("the first view of the assigner's assignments is not answered yet (%s asked %d times)", s.Tool, s.Asks) + if err := fol.Unread(); err != nil { + return nil, err } + return fol, nil } return AssignerReader{ Keys: func() ([]string, error) { diff --git a/modules/mesh-vault/cmd/mesh-vault/assignmentsview_test.go b/modules/mesh-vault/cmd/mesh-vault/assignmentsview_test.go index ae5118c49..63633ef7a 100644 --- a/modules/mesh-vault/cmd/mesh-vault/assignmentsview_test.go +++ b/modules/mesh-vault/cmd/mesh-vault/assignmentsview_test.go @@ -5,10 +5,12 @@ import ( "encoding/json" "errors" "fmt" + "strings" "sync" "testing" "time" + "git.novox.be/novox/mesh-sdk/go/busretry" "git.novox.be/novox/mesh-sdk/go/views" ) @@ -32,8 +34,13 @@ func TestAnUnansweredFirstViewOfTheAssignmentsIsAFindingTheAnswerClears(t *testi f, _ := newAssignmentsView(ask, func(string) {}, nil, heldFindings{&mu, held}) f.Bound, f.Wait = 30*time.Millisecond, 10*time.Millisecond reader := viewAssignments(func() *views.Follower { return f }) - if _, err := reader.Keys(); err == nil { - t.Fatal("the assignments was read before its first view") + // H-A-708 (2): before the first view a read is the fault `away` naming the view's owner verb, at once. + var away *busretry.Away + if _, err := reader.Keys(); !errors.As(err, &away) || away.Part != AssignmentsTool || !strings.HasPrefix(away.Words, "not read yet since ") { + t.Fatalf("the assignments was read before its first view, or not as away: %v", err) + } + if _, err := reader.Read("g14.node"); !errors.As(err, &away) { + t.Fatalf("a read before the first view: %v", err) } done := make(chan error, 1) go func() { done <- f.Start(context.Background()) }() diff --git a/modules/nats/cmd/nats-tools/broker.go b/modules/nats/cmd/nats-tools/broker.go index 86421c683..14f4c9f36 100644 --- a/modules/nats/cmd/nats-tools/broker.go +++ b/modules/nats/cmd/nats-tools/broker.go @@ -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"` } @@ -96,7 +97,7 @@ func streamsHeld(jsz []byte) (map[string]busStream, error) { // heldOf is one entry as the seat's list, show and orphans answer it (mesh-contracts meshbroker.Held): its bus name, its // template, its options or configuration as the manifest asked them, the settings the bus holds of each of its objects // by stream, and its fill summed over them against their caps. -func heldOf(module, local string, m keeper.Made, held map[string]busStream) meshbroker.Held { +func heldOf(module, local string, m keeper.Made, held map[string]busStream, objects bool) meshbroker.Held { h := meshbroker.Held{BusName: keeper.BusName(module, local), Module: module, LocalName: local, StorageType: m.Plan.Storage, Template: m.Plan.Template, Options: anyOf(m.Plan.Entry.Options), Configuration: anyOf(m.Plan.Entry.Configuration)} settings := map[string]any{} @@ -110,6 +111,11 @@ func heldOf(module, local string, m keeper.Made, held map[string]busStream) mesh fill.Bytes += int64(s.State.Bytes) fill.Count += int64(s.State.Messages) fill.Cap += s.Config.MaxBytes + if objects { + // show's fill keeps the entry's sum and gains one item per object (design 47 H2 H-A-634 (9), H-A-687 (3)). + fill.Objects = append(fill.Objects, meshbroker.ObjectFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: int64(s.State.Messages), + Bytes: int64(s.State.Bytes), Cap: s.Config.MaxBytes}) + } } if len(settings) > 0 { h.Settings, h.Fill = settings, &fill @@ -189,7 +195,7 @@ func brokerTools(read heldEntries, status func() (keeper.Status, error), jsz fun for _, module := range sortedNames(entries) { for _, local := range sortedNames(entries[module].Made) { if m := entries[module].Made[local]; keep(m) { - out = append(out, heldOf(module, local, m, held)) + out = append(out, heldOf(module, local, m, held, false)) } } } @@ -227,7 +233,7 @@ func brokerTools(read heldEntries, status func() (keeper.Status, error), jsz fun if !ok { return nil, fmt.Errorf("the bus module made no entry %q of %q", local, module) } - return heldOf(module, local, m, held), nil + return heldOf(module, local, m, held, true), nil }}, {Name: "mesh-broker.check", Description: "What the bus holds against what was asked, entry by entry: each object missing, or differing from its manifest's settings, with both. A difference that only grows is applied by the bus module itself; any other is a drift, raised to the operator.", diff --git a/modules/nats/cmd/nats-tools/broker_test.go b/modules/nats/cmd/nats-tools/broker_test.go index 348b7b4eb..21bb3636b 100644 --- a/modules/nats/cmd/nats-tools/broker_test.go +++ b/modules/nats/cmd/nats-tools/broker_test.go @@ -67,6 +67,9 @@ func TestTheSeatsReadingVerbsAnswerFromTheKeeperAndTheBus(t *testing.T) { {"mesh-broker.list", nil, []string{`"caps":{"account-limit-mib":2048,"server-limit-mib":4096,"sum-mib":1376`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "log"}, []string{`"bus-name":"m_log"`, `"template":"log"`, `"m_log":{"max-bytes":33554432`}, ""}, + // show's fill keeps the entry's sum and gains one item per object (design 47 H2 H-A-634 (9), H-A-687 (3)). + {"mesh-broker.show", map[string]any{"module": "m", "local-name": "drafts"}, []string{`"fill":{"bytes":1048576,"cap":83886080,"count":3,"objects":[{"bytes":1048576,"cap":67108864,"count":3,"object":"KV_m_drafts"}`, + `{"bytes":0,"cap":16777216,"count":0,"object":"OBJ_m_drafts-objects"}]}`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "later"}, []string{`"local-name":"later"`}, ""}, {"mesh-broker.show", map[string]any{"module": "m", "local-name": "none"}, nil, `made no entry "none" of "m"`}, {"mesh-broker.check", nil, []string{`{"differences":[{`, `"local-name":"log"`, `"asked":{"m_log":{"max-bytes":16777216`, diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index 8f9ca6c45..f9aa7e903 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -22,6 +22,7 @@ import ( "github.com/nats-io/nats.go/jetstream" "git.novox.be/novox/mesh-contracts/go/seats/meshbroker" + "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions" occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" @@ -400,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}) @@ -638,6 +639,192 @@ func TestTheBusModuleRunsWhole(t *testing.T) { onBranch("main", "sb", 6, nil) eventually(t, "sb's plan deleted", func() bool { _, _, found, _ := store.Get(keeper.StatePlans, "sb"); return !found }) }) + // Design 47 H2 H-A-634 (3), H-A-687 (1): a ledger giving ended-days is made with a lifetime per key on its state and + // index buckets and a lifetime per message on its snapshot store, which refuses when full. + t.Run("a ledger giving ended-days is made with lifetimes and a snapshot store that refuses when full", func(t *testing.T) { + ending := entry("records", "ledger", "ledger", map[string]string{"max-mib": "4"}) + ending.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("30"), "max-age-days": json.RawMessage("90")} + ending.Types = []catalogue.LedgerType{{Name: "record", EndsWith: "ended", Schema: map[string]catalogue.LedgerField{"ended": {Type: "map"}}, + Operations: []catalogue.LedgerOperation{{Name: "end", Effect: catalogue.EffectSetFields, Fields: []string{"ended"}}}}} + accepted("ld", 9, ending) + eventually(t, "created ld records", saidHas("created ld records")) + if info, ok := held("ld_records_snapshot"); !ok || !info.Config.AllowMsgTTL || info.Config.Discard != jetstream.DiscardNew { + t.Errorf("the snapshot store is %+v: a lifetime per message, refusing when full", info) + } + if info, ok := held("KV_ld_records_state"); !ok || !info.Config.AllowMsgTTL { + t.Errorf("the state bucket is %+v: a lifetime per key", info) + } + if got := k.Held()["ld"].Made["records"].Plan.Binding.EndedDays; got != 30 { + t.Errorf("the binding names ended-days %d, want 30: the bus holds every lifetime", got) + } + }) + // Design 47 H2 H-A-686, AC-G15b: a ledger holding messages and keys, recreated on the operator's warrant with a lifetime per + // message and per key turned on, keeps them all and takes the lifetime on its next write, the change entering through the + // request, the ask's warrant and the router's decided event as the live path does. + t.Run("a recreate on the warrant changes a ledger in place, keeping its messages and keys", func(t *testing.T) { + plain := entry("records", "ledger", "ledger", map[string]string{"max-mib": "4"}) + plain.Configuration = map[string]json.RawMessage{"max-age-days": json.RawMessage("90")} + plain.Types = []catalogue.LedgerType{{Name: "record", EndsWith: "ended", Schema: map[string]catalogue.LedgerField{"ended": {Type: "map"}}, + Operations: []catalogue.LedgerOperation{{Name: "end", Effect: catalogue.EffectSetFields, Fields: []string{"ended"}}}}} + accepted("rc", 20, plain) + eventually(t, "created rc records", saidHas("created rc records")) + snap, ok := held("rc_records_snapshot") + if !ok { + t.Fatal("the bus holds no rc_records_snapshot") + } + // The snapshot store as a keeper before H2 made it: dropping its oldest when full, which the asked form refuses. + old := snap.Config + old.Discard = jetstream.DiscardOld + if _, err := js.UpdateStream(ctx, old); err != nil { + t.Fatal(err) + } + // A message in the history, which the shorter age asked keeps (it is younger than the age). + hist, ok := held("rc_records") + if !ok || hist.Config.MaxAge != 90*24*time.Hour { + t.Fatalf("the history is %+v: want its age 90 days", hist) + } + if _, err := js.Publish(ctx, strings.TrimSuffix(hist.Config.Subjects[0], ">")+"i1", []byte("x")); err != nil { + t.Fatal(err) + } + for i := range 3 { + if _, err := js.Publish(ctx, strings.TrimSuffix(snap.Config.Subjects[0], ">")+fmt.Sprintf("k%d", i), []byte("x")); err != nil { + t.Fatal(err) + } + } + kv, err := js.KeyValue(ctx, "rc_records_state") + if err != nil { + t.Fatal(err) + } + for _, key := range []string{"a", "b"} { + if _, err := kv.Put(ctx, key, []byte("v")); err != nil { + t.Fatal(err) + } + } + ending := plain + ending.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("30"), "max-age-days": json.RawMessage("30")} + accepted("rc", 21, ending) + eventually(t, "drifted rc records", saidHas("drifted rc records")) + r := keeper.Request{ID: "rc1", Verb: keeper.VerbRecreate, Module: "rc", Local: "records", Caller: "person.jo", Why: "take the lifetimes", At: time.Now(), AskExpires: time.Now().Add(keeper.AskLasts)} + a, err := askFor(r, "") + if err != nil { + t.Fatal(err) + } + r.Ask = a.ID + w := &oc.Warrant{Ask: a.ID, Asker: keeper.Module, Outcome: occ.OutcomeChosen, By: &oc.Person{Who: occ.Operator}, + Option: "go", Label: "Rebuild", Level: occ.Approve, At: occ.FormatTime(time.Now()), AskDigest: occ.Digest(a)} + raw, _ := json.Marshal(map[string]any{"asker": keeper.Module, "ask": a, "state": "open", "warrant": w}) + if _, err := asksKV.Put(ctx, keeper.Module+"."+a.ID, raw); err != nil { + t.Fatal(err) + } + raw, _ = json.Marshal(r) + if _, err := store.Put(keeper.StateRequests, r.ID, raw); err != nil { + t.Fatal(err) + } + body, _ := json.Marshal(w) + if _, err := js.Publish(ctx, DecidedSubject, body); err != nil { + t.Fatal(err) + } + eventually(t, "recreated rc records", saidHas("recreated rc records")) + snap, _ = held("rc_records_snapshot") + state, _ := held("KV_rc_records_state") + if hist, _ = held("rc_records"); hist.Config.MaxAge != 30*24*time.Hour || hist.State.Msgs != 1 { + t.Errorf("the history holds %d messages (want 1) at the age %s (want 30 days): changed in place to the shorter age", hist.State.Msgs, hist.Config.MaxAge) + } + if snap.Config.Discard != jetstream.DiscardNew { + t.Errorf("the snapshot store still drops its oldest when full (discard %v): the refusal when full turned on in place", snap.Config.Discard) + } + if snap.State.Msgs != 3 || state.State.Msgs != 2 || !snap.Config.AllowMsgTTL || !state.Config.AllowMsgTTL { + t.Errorf("the snapshot store holds %d messages (want 3, AllowMsgTTL %v), the state bucket %d keys (want 2, AllowMsgTTL %v): changed in place", + snap.State.Msgs, snap.Config.AllowMsgTTL, state.State.Msgs, state.Config.AllowMsgTTL) + } + msg := &nats.Msg{Subject: strings.TrimSuffix(snap.Config.Subjects[0], ">") + "late", Data: []byte("x"), Header: nats.Header{"Nats-TTL": []string{"60s"}}} + if _, err := js.PublishMsg(ctx, msg); err != nil { + t.Errorf("a message with a lifetime of its own is refused after the recreate: %v", err) + } + if _, err := kv.Create(ctx, "c", []byte("v"), jetstream.KeyTTL(time.Minute)); err != nil { + t.Errorf("a key with a lifetime of its own is refused after the recreate: %v", err) + } + if k.Held()["rc"].Made["records"].Drift != "" { + t.Errorf("the drift stays after the recreate: %s", k.Held()["rc"].Made["records"].Drift) + } + }) + // Design 47 H2 H-A-600, H-A-615, H-A-621: nats_consumer_narrow on the real bus keeps the consumer's delivery position, delivers it + // no message of a removed subject, and refuses every filter, a subject not filtered and one the module's entry consumes. + t.Run("nats_consumer_narrow keeps a consumer's position and delivers none of a removed subject", func(t *testing.T) { + if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "NARROW", Subjects: []string{"mesh.stream.nw.event.>"}}); err != nil { + t.Fatal(err) + } + cons, err := js.CreateOrUpdateConsumer(ctx, "NARROW", jetstream.ConsumerConfig{Durable: "ace_nw", AckPolicy: jetstream.AckExplicitPolicy, + FilterSubjects: []string{"mesh.stream.nw.event.a", "mesh.stream.nw.event.b", "mesh.stream.nw.event.c"}}) + if err != nil { + t.Fatal(err) + } + for _, subject := range []string{"mesh.stream.nw.event.a", "mesh.stream.nw.event.c", "mesh.stream.nw.event.b"} { + if _, err := js.Publish(ctx, subject, []byte(subject)); err != nil { + t.Fatal(err) + } + } + first, err := cons.Fetch(2, jetstream.FetchMaxWait(2*time.Second)) + if err != nil { + t.Fatal(err) + } + for m := range first.Messages() { + _ = m.Ack() + } + before, _ := cons.Info(ctx) + bus := func(context.Context) (jetstream.JetStream, func(), error) { return js, func() {}, nil } + accepted := func() (map[string]keeper.Planned, error) { return map[string]keeper.Planned{"nw": {Module: "nw"}}, nil } + consumes := func(context.Context, string) ([]string, error) { return []string{"nw.a"}, nil } + var handActs []meshhandactsclient.Request + record := func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil } + call := func(remove ...any) (any, error) { + return NarrowConsumer(ctx, bus, accepted, consumes, record, map[string]any{"stream": "NARROW", "durable": "ace_nw", "remove": remove, "why": "its module no longer consumes them"}) + } + for what, c := range map[string]struct { + remove []any + want string + }{ + "a subject the entry still consumes": {[]any{"mesh.stream.nw.event.a"}, "still consumes mesh.stream.nw.event.a"}, + "a subject it does not filter": {[]any{"mesh.stream.nw.event.b", "mesh.stream.nw.event.d"}, "does not filter mesh.stream.nw.event.d"}, + } { + if _, err := call(c.remove...); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: %v, want a refusal saying %q", what, err, c.want) + } + } + consumes = func(context.Context, string) ([]string, error) { return nil, nil } + if _, err := call("mesh.stream.nw.event.a", "mesh.stream.nw.event.b", "mesh.stream.nw.event.c"); err == nil || !strings.Contains(err.Error(), "takes every filter") { + t.Errorf("removing every filter: %v, want a refusal", err) + } + if len(handActs) != 0 { + t.Errorf("a refused narrowing recorded hand acts %v", handActs) + } + got, err := call("mesh.stream.nw.event.c") + if err != nil { + t.Fatal(err) + } + after, _ := cons.Info(ctx) + if n := got.(ConsumerNarrowed); fmt.Sprint(n.After) != "[mesh.stream.nw.event.a mesh.stream.nw.event.b]" || len(handActs) != 1 || handActs[0].Cause != "consumer-narrow" { + t.Errorf("narrowed %+v with hand acts %v", n, handActs) + } + if after.Delivered.Stream != before.Delivered.Stream || after.Delivered.Consumer != before.Delivered.Consumer || after.Config.AckWait != before.Config.AckWait || fmt.Sprint(after.Config.FilterSubjects) != "[mesh.stream.nw.event.a mesh.stream.nw.event.b]" { + t.Errorf("the consumer after is %+v, before %+v: its position and its other settings kept, its filters narrowed", after, before) + } + if _, err := js.Publish(ctx, "mesh.stream.nw.event.c", []byte("late")); err != nil { + t.Fatal(err) + } + next, err := cons.Fetch(5, jetstream.FetchMaxWait(time.Second)) + if err != nil { + t.Fatal(err) + } + var delivered []string + for m := range next.Messages() { + delivered = append(delivered, m.Subject()) + _ = m.Ack() + } + if fmt.Sprint(delivered) != "[mesh.stream.nw.event.b]" { + t.Errorf("delivered %v after the narrowing: the one mesh.stream.nw.event.b still owed, and none of mesh.stream.nw.event.c", delivered) + } + }) t.Run("nats_first_view_again asks at once and records the hand act", func(t *testing.T) { raw, _ := json.Marshal(keeper.Request{ID: "r3", Verb: keeper.VerbFirstViewAgain, Why: "a verdict thought missed", Caller: "person.jo"}) _, _ = store.Put(keeper.StateRequests, "r3", raw) diff --git a/modules/nats/cmd/nats-tools/main.go b/modules/nats/cmd/nats-tools/main.go index fc35315a5..9bd48ae92 100644 --- a/modules/nats/cmd/nats-tools/main.go +++ b/modules/nats/cmd/nats-tools/main.go @@ -191,12 +191,23 @@ func allTools() []stdio.Tool { defer cancel() return monitor(ctx, heldJsz) } - out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState, PlansInState, RecordedBySeat, bundleTwinCurrent)...) + out := append(tools(monitor, ReadUsers, UsersWritten), removalTools(LiveBus(), SaidByTheRuntime, HeldInState, PlansInState, RecordedBySeat, bundleTwinCurrent, ConsumesBySeat)...) out = append(out, expiryTools(LiveBus(), SaidByTheRuntime, RecordedBySeat)...) out = append(out, brokerTools(HeldInState, StatusInState, jsz, StreamHistory(LiveBus()))...) 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)...) diff --git a/modules/nats/cmd/nats-tools/manifest_test.go b/modules/nats/cmd/nats-tools/manifest_test.go index 4c0790563..1d533b2b9 100644 --- a/modules/nats/cmd/nats-tools/manifest_test.go +++ b/modules/nats/cmd/nats-tools/manifest_test.go @@ -140,7 +140,7 @@ func TestTheBussManifestMountsItsProgramsIntoTheUpstreamImage(t *testing.T) { } // The tools that change the bus (issue 1952 N1-N3): listed, their audit events declared, and the credential // they dial with the module's own secret `broker`. - for _, want := range []string{"nats_consumer_remove", "nats_bucket_remove", "nats_stream_remove", "nats_bucket_expiry"} { + for _, want := range []string{"nats_consumer_remove", "nats_consumer_narrow", "nats_bucket_remove", "nats_stream_remove", "nats_bucket_expiry"} { if !slices.Contains(m.Tools, want) { t.Errorf("tools do not list %s", want) } diff --git a/modules/nats/cmd/nats-tools/recreateask.go b/modules/nats/cmd/nats-tools/recreateask.go new file mode 100644 index 000000000..681a873cd --- /dev/null +++ b/modules/nats/cmd/nats-tools/recreateask.go @@ -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 +} diff --git a/modules/nats/cmd/nats-tools/removal.go b/modules/nats/cmd/nats-tools/removal.go index df6c982dc..69161828f 100644 --- a/modules/nats/cmd/nats-tools/removal.go +++ b/modules/nats/cmd/nats-tools/removal.go @@ -17,12 +17,15 @@ import ( "errors" "fmt" "regexp" + "slices" "sort" "strings" "time" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" + "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" stdio "git.novox.be/novox/mesh-sdk/go" + "git.novox.be/novox/mesh-sdk/go/buscompose" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" @@ -348,7 +351,7 @@ func RemoveStream(ctx context.Context, bus Bus, said Said, a map[string]any) (an // every module it heard as accepted, its state plans, one key per module of a watched branch's newest revision whether // it asks for kept data or not, design 47 G §538) is refused, on any stream; every other durable is an orphan and goes, `why` its warrant, at once, and its removal is // recorded as a hand act through mesh-hand-acts, as nats_bucket_expiry's change is. -func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration) []stdio.Tool { +func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration, consumes Consumes) []stdio.Tool { removeConsumer := func(a map[string]any) (any, error) { within := DefaultTwinCurrentHours * time.Hour if twinWithin != nil { @@ -401,6 +404,14 @@ func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModu Input: map[string]any{"stream": str("the stream, e.g. SEAT_NODE_BUILD_GO"), "below": num("the first sequence kept: every message below it is purged"), "why": str("why they are purged, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "read the stream, purge nothing"}}, Run: run(PurgeStream)}, + {Name: "nats_consumer_narrow", + Description: "Narrows one live JetStream consumer: removes some of its filter subjects (`remove`) and keeps the others, its other settings and its delivery position, by the consumer's create-or-update call (design 47 H2, H-A-600), e.g. the subjects a module's durable no longer consumes after a change of its manifest, so the bus delivers it none of them. Refuses to remove every filter of the consumer and a subject the consumer does not filter; judges the durable's module by name as nats_consumer_remove does (_ or __..., against the keeper's accepted set) and refuses a subject that module's accepted manifest still consumes, read as the `consumes` of its entry in the seat mesh-catalog (its trunk fingerprint from `modules`, then `entry`), naming the subject (H-A-615, H-A-621, H-A-657). Needs `why`, its warrant, recorded as a hand act through mesh-hand-acts before the consumer is changed (ADR 0640 §3); reads the consumer first and answers its filters before and after.", + Input: map[string]any{"stream": str("the stream the consumer is on, e.g. EVENTS"), "durable": str("the durable consumer's name, e.g. novox_mesh-delivery-indexer"), + "remove": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "the filter subjects to remove, each one the consumer filters"}, + "why": str("why they are removed, for the audit trail (required)")}, + Run: func(a map[string]any) (any, error) { + return NarrowConsumer(context.Background(), bus, accepted, consumes, record, a) + }}, {Name: "nats_bucket_remove", Description: "Removes (purges) keys from a key-value bucket: one node's keys (`node`, the keys starting `.`) or the keys under a `prefix`, e.g. a full acts bucket of the node-engine. Needs `why`, kept in the audit trail; never the whole bucket. Counts the keys first and lists them (`dry_run` only counts; `expect` refuses when the count differs); removes only those keys, and their history. See the buckets and their keys with nats_buckets. The bus refuses any bucket the module's credential is not granted.", Input: map[string]any{"bucket": str("the bucket as nats_buckets lists it, e.g. mesh-host_acts"), "node": str("a node whose keys (`.`) go"), "prefix": str("key prefix instead of node"), @@ -409,6 +420,189 @@ func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModu } } +// Consumes reads the subjects the accepted manifest of a module consumes, as the seat mesh-catalog's entry of the module +// at trunk carries them (design 47 H2, H-A-621, H-A-657). +type Consumes func(ctx context.Context, module string) ([]string, error) + +// ConsumesBySeat asks the seat mesh-catalog's `modules` for the module's trunk fingerprint and its `entry` with it, and +// answers that entry's `consumes` (design 47 H2, H-A-657): an entry that cannot be read refuses, since what the module +// consumes is then not known. +func ConsumesBySeat(_ context.Context, module string) ([]string, error) { + raw, err := stdio.Ask("seat:mesh-catalog.modules", map[string]any{}) + if err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's modules cannot be read: %w", err) + } + var mods meshcatalog.ModulesAnswer + if err := json.Unmarshal(raw, &mods); err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's modules answered what cannot be read: %w", err) + } + for _, m := range mods.Modules { + if m.Module != module { + continue + } + if m.Fp == "" { + return nil, fmt.Errorf("the trunk holds %s with no fingerprint (%s)", module, m.None) + } + raw, err := stdio.Ask("seat:mesh-catalog.entry", meshcatalog.EntryInput{Fingerprint: m.Fp}) + if err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's entry %s of %s cannot be read: %w", m.Fp, module, err) + } + var e meshcatalog.EntryAnswer + if err := json.Unmarshal(raw, &e); err != nil { + return nil, fmt.Errorf("the seat mesh-catalog's entry of %s answered what cannot be read: %w", module, err) + } + return e.Entry.Consumes, nil + } + return nil, fmt.Errorf("the trunk holds no module %s", module) +} + +// ConsumerNarrowed is what nats_consumer_narrow answers. +type ConsumerNarrowed struct { + Stream string `json:"stream"` + Durable string `json:"durable"` + Why string `json:"why"` + Module string `json:"module,omitempty"` + Before []string `json:"filters_before"` + After []string `json:"filters_after"` + Removed []string `json:"removed"` + At time.Time `json:"at"` +} + +// moduleOfDurable is the module of the keeper's accepted set a durable _ or __... belongs to, +// as refuseAcceptedDurable judges it (design 47 H, H-A-127, H-A-128); "" for a durable of none. +func moduleOfDurable(held map[string]keeper.Planned, durable string) string { + _, module, ok := strings.Cut(durable, "_") + if !ok || module == "" { + return "" + } + best := "" + for m := range held { + if (module == m || strings.HasPrefix(module, m+"_")) && len(m) > len(best) { + best = m + } + } + return best +} + +// filtersOf are the filter subjects of a consumer, whether it names one or many. +func filtersOf(c jetstream.ConsumerConfig) []string { + if len(c.FilterSubjects) > 0 { + return slices.Clone(c.FilterSubjects) + } + if c.FilterSubject != "" { + return []string{c.FilterSubject} + } + return nil +} + +// NarrowConsumer removes some filter subjects of one live consumer by its create-or-update call, keeping its other +// settings and its delivery position (design 47 H2, H-A-600). It refuses with nothing changed: no `why`, no hand-act log, +// a subject to remove that the consumer does not filter, every filter, and a subject the entry of the durable's module in +// the seat mesh-catalog still consumes (H-A-615, H-A-621); a module whose consumption cannot be read is refused too. +func NarrowConsumer(ctx context.Context, bus Bus, accepted acceptedModules, consumes Consumes, record Recorded, a map[string]any) (any, error) { + w, err := why(a) + if err != nil { + return nil, err + } + stream, durable := arg(a, "stream"), arg(a, "durable") + if !name.MatchString(stream) || !name.MatchString(durable) { + return nil, errors.New("stream and durable are required, each one name (letters, digits, - and _): nothing was narrowed") + } + var remove []string + if list, ok := a["remove"].([]any); ok { + for _, v := range list { + subject, ok := v.(string) + if !ok || strings.TrimSpace(subject) == "" || strings.ContainsAny(subject, " \t") { + return nil, errors.New("remove is a list of filter subjects, each one text without spaces: nothing was narrowed") + } + remove = append(remove, subject) + } + } + if len(remove) == 0 { + return nil, errors.New("remove is required, the filter subjects to remove: nothing was narrowed") + } + module := "" + if accepted != nil { + held, err := accepted() + if err != nil { + return nil, fmt.Errorf("whether %s is the durable of a module of an accepted manifest cannot be read (%v), so nothing was narrowed", durable, err) + } + module = moduleOfDurable(held, durable) + } + if module != "" { + if consumes == nil { + return nil, fmt.Errorf("what %s consumes cannot be read here, so nothing was narrowed", module) + } + still, err := consumes(ctx, module) + if err != nil { + return nil, fmt.Errorf("what %s consumes cannot be read (%v), so nothing was narrowed", module, err) + } + for _, subject := range remove { + if stillConsumed(still, subject) { + return nil, fmt.Errorf("%s still consumes %s, its accepted manifest says so: it is not removed from %s; nothing was narrowed", module, subject, durable) + } + } + } + js, closeBus, err := bus(ctx) + if err != nil { + return nil, err + } + defer closeBus() + sctx, cancel := step(ctx) + info, err := readConsumer(sctx, js, stream, durable) + cancel() + if err != nil { + if errors.Is(err, jetstream.ErrConsumerNotFound) || errors.Is(err, jetstream.ErrStreamNotFound) { + return nil, fmt.Errorf("%s has no consumer %s (%v): nothing was narrowed", stream, durable, err) + } + return nil, unanswered(err, fmt.Sprintf("the consumer %s of %s could not be read, so it was not narrowed", durable, stream)) + } + before := filtersOf(info.Config) + for _, subject := range remove { + if !slices.Contains(before, subject) { + return nil, fmt.Errorf("%s does not filter %s (it filters %v): nothing was narrowed", durable, subject, before) + } + } + var kept []string + for _, f := range before { + if !slices.Contains(remove, f) { + kept = append(kept, f) + } + } + if len(kept) == 0 { + return nil, fmt.Errorf("removing %v takes every filter of %s: a consumer is narrowed, never left with none; nothing was narrowed", remove, durable) + } + what := fmt.Sprintf("narrowed the consumer %s of the stream %s: removed the filter subjects %s, kept %s", durable, stream, strings.Join(remove, ", "), strings.Join(kept, ", ")) + if record == nil { + return nil, errors.New("the hand-act log cannot be reached here, so nothing was narrowed") + } + if err := record(meshhandactsclient.Request{What: what, Why: w, Cause: "consumer-narrow"}); err != nil { + return nil, fmt.Errorf("the hand act could not be recorded, so nothing was narrowed: %w", err) + } + cfg := info.Config + cfg.FilterSubject, cfg.FilterSubjects = "", kept + sctx, cancel = step(ctx) + _, err = js.CreateOrUpdateConsumer(sctx, stream, cfg) + cancel() + if err != nil { + return nil, unanswered(err, fmt.Sprintf("consumer %s of %s was not narrowed (its hand act was recorded)", durable, stream)) + } + sctx, cancel = step(ctx) + after, err := readConsumer(sctx, js, stream, durable) + cancel() + if err != nil { + return nil, unanswered(err, fmt.Sprintf("the narrowing of consumer %s of %s was accepted but could not be confirmed", durable, stream)) + } + got := filtersOf(after.Config) + slices.Sort(got) + want := slices.Clone(kept) + slices.Sort(want) + if !slices.Equal(got, want) { + return nil, fmt.Errorf("consumer %s of %s filters %v after the narrowing was accepted, not %v", durable, stream, got, kept) + } + return ConsumerNarrowed{Stream: stream, Durable: durable, Why: w, Module: module, Before: before, After: kept, Removed: remove, At: time.Now().UTC()}, nil +} + // refuseAcceptedDurable refuses a durable named _, or beginning __, for a module of the // keeper's accepted set, on any node (design 47 H, H-A-127, H-A-128): every module it heard as accepted, read from its // state plans (design 47 G §538), never from its state asked, which holds only a module that asks for kept data (a @@ -622,3 +816,15 @@ func PurgeStream(ctx context.Context, bus Bus, said Said, a map[string]any) (any } return out, nil } + +// stillConsumed says whether a filter subject of a durable is one of the words the module's entry `consumes`: a word is +// `.` and its filter is the bus subject that names the event in a namespace (`mesh.mod..event.`, +// the seat's or the stream's), so the subject goes to its word by the mesh-sdk's own mapping before the two are compared, a +// word with a wildcard standing for the subjects it overlaps (H-A-615, H-A-621). A subject that is no event's is compared as it is. +func stillConsumed(consumes []string, subject string) bool { + word := subject + if name, _, ok := buscompose.EventName(subject); ok { + word = name + } + return slices.ContainsFunc(consumes, func(c string) bool { return buscompose.Overlaps(c, word) }) +} diff --git a/modules/nats/cmd/nats-tools/removal_test.go b/modules/nats/cmd/nats-tools/removal_test.go index 257431722..e6301ac9a 100644 --- a/modules/nats/cmd/nats-tools/removal_test.go +++ b/modules/nats/cmd/nats-tools/removal_test.go @@ -197,7 +197,7 @@ accounts { MESH { jetstream: enabled, users: [ // Through the tool, `why` its warrant: each removal is recorded as a hand act (design 47 H, H-A-127). var handActs []meshhandactsclient.Request var removeConsumer func(map[string]any) (any, error) - for _, tl := range removalTools(bus, say, nil, nil, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + for _, tl := range removalTools(bus, say, nil, nil, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil, nil) { if tl.Name == "nats_consumer_remove" { removeConsumer = tl.Run } @@ -279,7 +279,7 @@ accounts { MESH { jetstream: enabled, users: [ } } handActs = nil - for _, tl := range removalTools(adminBus, say, nil, accepted, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil) { + for _, tl := range removalTools(adminBus, say, nil, accepted, func(q meshhandactsclient.Request) error { handActs = append(handActs, q); return nil }, nil, nil) { if tl.Name == "nats_consumer_remove" { removeConsumer = tl.Run } diff --git a/modules/nats/cmd/nats-tools/requests.go b/modules/nats/cmd/nats-tools/requests.go index b0902d809..8627ace09 100644 --- a/modules/nats/cmd/nats-tools/requests.go +++ b/modules/nats/cmd/nats-tools/requests.go @@ -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 @@ -186,8 +189,8 @@ func askFor(r keeper.Request) (oc.Ask, error) { OnExpiry: "nothing is removed and the entry stays as it is", 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), + Explanation: fmt.Sprintf("%s asks to %s %s on the bus, %s. A snapshot of it is taken first.", r.Caller, what, name, r.Why) + + map[bool]string{true: " Its data is lost from the bus."}[r.Verb == keeper.VerbDrop] + 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 } @@ -338,7 +349,7 @@ func requestTools(rs requestStore) []stdio.Tool { firstView, tool(keeper.VerbCreate, "Create one entry of a module's kept data on the bus now, as its accepted manifest asks for it (design 25 § 12.3): handed to the bus module's keeper, which alone may create, and recorded as a hand act."), tool(keeper.VerbApply, "Apply what a module's manifest asks of one entry where the bus holds less (a larger cap, a longer age): only a difference that grows; handed to the keeper and recorded as a hand act."), - tool(keeper.VerbRecreate, "Rebuild one entry whose settings drifted in a way that does not grow: the operator is asked first, and the keeper acts only on their warrant, after a snapshot of the entry. Its data is lost from the bus (the snapshot keeps it). Dangerous."), + tool(keeper.VerbRecreate, "Rebuild one entry whose settings drifted in a way that does not grow: the operator is asked first, and the keeper acts only on their warrant, after a snapshot of the entry. The ask names, per object, what is kept and what is made empty (the snapshot keeps the data). Dangerous."), tool(keeper.VerbDrop, "Remove one orphan, an entry no accepted manifest asks for: the operator is asked first, and the keeper acts only on their warrant, after a snapshot of the entry. Dangerous."), } } diff --git a/modules/nats/cmd/nats-tools/requests_test.go b/modules/nats/cmd/nats-tools/requests_test.go index b7c380fbb..900a25a2e 100644 --- a/modules/nats/cmd/nats-tools/requests_test.go +++ b/modules/nats/cmd/nats-tools/requests_test.go @@ -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,47 @@ 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) + } + // The recreate's words come from the per-object lines, which keep the data: it never says the data is lost (H-A-686 (3)). + if strings.Contains(ask.Explanation, "lost from the bus") { + t.Errorf("the recreate's ask says its data is lost: %s", ask.Explanation) + } + if drop, _ := askFor(keeper.Request{Verb: keeper.VerbDrop, Module: "m", Local: "records", Why: "w", Caller: "c", AskExpires: now}, ""); !strings.Contains(drop.Explanation, "lost from the bus") { + t.Errorf("the drop's ask does not say its data is lost: %s", drop.Explanation) + } +} diff --git a/modules/nats/cmd/nats-tools/tools_test.go b/modules/nats/cmd/nats-tools/tools_test.go index 1bc0b8eb4..8316f9532 100644 --- a/modules/nats/cmd/nats-tools/tools_test.go +++ b/modules/nats/cmd/nats-tools/tools_test.go @@ -277,9 +277,23 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { // H-A-472 (1): a twin that cannot be read keeps the durable refused, saying so. {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_m", "why": "x"}, "its twin novox_m_tools on EVENTS cannot be read"}, {"nats_consumer_remove", map[string]any{"stream": "EVENTS", "consumer": "novox_quiet_tools", "why": "x"}, "its twin novox_quiet on EVENTS cannot be read"}, + // Design 47 H2 H-A-600, H-A-615, H-A-621: a narrowing needs its warrant, a stream, a durable and subjects to remove, and + // refuses a subject the durable's module still consumes (the entry's `consumes`) before the bus is reached. + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "remove": []any{"a.b"}}, "why is required"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "why": "x"}, "remove is required"}, + {"nats_consumer_narrow", map[string]any{"stream": "A.B", "durable": "d", "remove": []any{"a"}, "why": "x"}, "stream and durable are required"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "remove": []any{"mesh.mod.m.event.still.taken"}, "why": "x"}, "m still consumes mesh.mod.m.event.still.taken"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m", "remove": []any{"mesh.seat.m.event.still.taken"}, "why": "x"}, "m still consumes mesh.seat.m.event.still.taken"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_m_tools", "remove": []any{"mesh.mod.m.event.still.taken"}, "why": "x"}, "m still consumes mesh.mod.m.event.still.taken"}, + {"nats_consumer_narrow", map[string]any{"stream": "EVENTS", "durable": "novox_quiet", "remove": []any{"a"}, "why": "x"}, "what quiet consumes cannot be read"}, } { var run func(map[string]any) (any, error) - for _, tl := range removalTools(bus, said, newForm, accepted, nil, nil) { + for _, tl := range removalTools(bus, said, newForm, accepted, nil, nil, func(_ context.Context, module string) ([]string, error) { + if module == "m" { + return []string{"m.still.taken"}, nil + } + return nil, errors.New("the entry is not read") + }) { if tl.Name == c.tool { run = tl.Run } @@ -339,7 +353,7 @@ func TestTheRemovalToolsRefuseBeforeTheyReachTheBus(t *testing.T) { unreachable := func(context.Context) (jetstream.JetStream, func(), error) { return nil, nil, errors.New("the bus is not reached here") } - for _, tl := range removalTools(unreachable, said, newForm, accepted, nil, nil) { + for _, tl := range removalTools(unreachable, said, newForm, accepted, nil, nil, nil) { if tl.Name != "nats_consumer_remove" { continue } diff --git a/modules/nats/internal/keeper/fill.go b/modules/nats/internal/keeper/fill.go index 87a9de1e7..75a9e0173 100644 --- a/modules/nats/internal/keeper/fill.go +++ b/modules/nats/internal/keeper/fill.go @@ -38,6 +38,7 @@ func (k *Keeper) FillPass() { continue } var most int64 = -1 + var judged *EventFill for _, o := range m.Plan.Objects { if !o.Settings.Refuses() || o.Settings.MaxBytes <= 0 { continue @@ -48,6 +49,7 @@ func (k *Keeper) FillPass() { } if p := int64(f.Bytes) * 100 / o.Settings.MaxBytes; p > most { most = p + judged = &EventFill{Count: f.Messages, Bytes: f.Bytes, Cap: o.Settings.MaxBytes, Object: o.Stream(), Part: m.Plan.PartOf(o)} } } if most < 0 { @@ -58,13 +60,13 @@ func (k *Keeper) FillPass() { switch { case !m.Full && most >= raise: m.Full = true - k.emit(EventFull, m.Plan, held.Revision, fmt.Sprintf("%d%% of its cap, past the raise mark %d%%", most, raise), nil, nil) + k.emitFill(EventFull, m.Plan, held.Revision, fmt.Sprintf("%s holds %d%% of its cap, past the raise mark %d%%", nameOf(judged), most, raise), nil, nil, judged) k.raise(conditionFull, module, local, occ.SeverityWarning, "Kept data is filling up", "a larger cap in the module's manifest, or data removed", - fmt.Sprintf("%s of %s holds %d%% of its cap and refuses new data when full; it is cleared below %d%%", local, module, most, clear)) + fmt.Sprintf("%s of %s of %s holds %d%% of its cap and refuses new data when full; it is cleared below %d%%", nameOf(judged), local, module, most, clear)) case m.Full && most < clear: m.Full = false - k.emit(EventFullCleared, m.Plan, held.Revision, fmt.Sprintf("%d%% of its cap, below the clear mark %d%%", most, clear), nil, nil) + k.emitFill(EventFullCleared, m.Plan, held.Revision, fmt.Sprintf("%s holds %d%% of its cap, below the clear mark %d%%", nameOf(judged), most, clear), nil, nil, judged) k.clear(conditionFull, module, local) } if m.Fill != was.Fill || m.Full != was.Full { @@ -77,3 +79,15 @@ func (k *Keeper) FillPass() { } k.setStatus(func(s *Status) { s.Pass = k.now() }) } + +// nameOf names the object a fill is of in words: its part and its bus name for a ledger, its bus name alone for an entry of +// one object (design 47 H2 H-A-634 (9): the state `KV_mesh-delivery-gate_records_state`). +func nameOf(f *EventFill) string { + if f == nil { + return "it" + } + if f.Part == "" { + return "`" + f.Object + "`" + } + return "the " + f.Part + " `" + f.Object + "`" +} diff --git a/modules/nats/internal/keeper/jetstream.go b/modules/nats/internal/keeper/jetstream.go index c5bd4b628..8e487f121 100644 --- a/modules/nats/internal/keeper/jetstream.go +++ b/modules/nats/internal/keeper/jetstream.go @@ -80,6 +80,7 @@ func SettingsOf(kind string, c jetstream.StreamConfig) Settings { case KindObjects: s.DuplicatesSeconds = 0 default: + s.KeyTTL = c.AllowMsgTTL if c.MaxMsgsPerSubject > 0 { s.History = c.MaxMsgsPerSubject } @@ -119,7 +120,8 @@ func limitMarker(on bool) time.Duration { func streamConfig(o Object) jetstream.StreamConfig { c := jetstream.StreamConfig{Name: o.Name, Subjects: o.Subjects, Retention: jetstream.LimitsPolicy, MaxBytes: o.Settings.MaxBytes, MaxAge: time.Duration(o.Settings.MaxAgeSeconds) * time.Second, - Discard: jetstream.DiscardOld, Storage: jetstream.FileStorage, Replicas: 1, MaxMsgs: -1, MaxMsgsPerSubject: -1} + Discard: jetstream.DiscardOld, Storage: jetstream.FileStorage, Replicas: 1, MaxMsgs: -1, MaxMsgsPerSubject: -1, + AllowMsgTTL: o.Settings.KeyTTL} if o.Settings.Discard == DiscardNew { c.Discard = jetstream.DiscardNew } @@ -152,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) } diff --git a/modules/nats/internal/keeper/keeper.go b/modules/nats/internal/keeper/keeper.go index 41428e100..733532246 100644 --- a/modules/nats/internal/keeper/keeper.go +++ b/modules/nats/internal/keeper/keeper.go @@ -71,16 +71,24 @@ type Event struct { Asked map[string]Settings `json:"asked,omitempty"` Held map[string]Settings `json:"held,omitempty"` Fill *EventFill `json:"fill,omitempty"` - Snapshot string `json:"snapshot,omitempty"` - Why string `json:"why,omitempty"` - Revision uint64 `json:"revision"` + // Before and After are what each object of a recreated entry held before and after it, said by `recreated` (design 47 H2 + // H-A-740). + Before []EventFill `json:"before,omitempty"` + After []EventFill `json:"after,omitempty"` + Snapshot string `json:"snapshot,omitempty"` + Why string `json:"why,omitempty"` + Revision uint64 `json:"revision"` } -// EventFill is an entry's fill as an event says it: its messages, its bytes and its cap. +// EventFill is the fill an event says: the object it is of, its messages, its bytes and its cap; Object is its name on the +// bus and Part the place it has in the entry's binding (history, state, `index ` or snapshot of a ledger), absent for an +// entry of one object (design 47 H2 H-A-634 (9), H-A-687 (3)). type EventFill struct { - Count uint64 `json:"count"` - Bytes uint64 `json:"bytes"` - Cap int64 `json:"cap"` + Count uint64 `json:"count"` + Bytes uint64 `json:"bytes"` + Cap int64 `json:"cap"` + Object string `json:"object,omitempty"` + Part string `json:"part,omitempty"` } // Accepted is one module's entry as the catalog half's watched branches give it (design 47 G §344, §433, §532): the @@ -174,6 +182,9 @@ type Made struct { Fill int64 `json:"fill,omitempty"` // Orphaned says no manifest asks for it any more: it goes only by drop. Orphaned bool `json:"orphaned,omitempty"` + // Said is the binding its last `created` or `recreated` said (design 47 H2 H-A-685 (2)): a binding the keeper would say + // that differs from it is said again with `created`. Absent where none was kept, which differs from any. + Said *membership.BusBinding `json:"said,omitempty"` } // Status is the keeper's own state, KeyStatus: what its health tool reads. @@ -305,7 +316,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 } @@ -813,7 +824,11 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { if wasRefused { k.clear(conditionRefused, held.Module, m.Plan.Local) } - if !m.Created || madeLater { + // The binding names ended-days only once the bus holds every object that asks a lifetime with one (design 47 H2 H-A-685 + // (1)); one that differs from the binding last said is said again (H-A-685 (2)), by an entry the keeper creates alone. + m.Plan.Binding = bindingHeld(m.Plan, holds) + changed := create && m.Created && !sameBinding(m.Said, m.Plan.Binding) + if !m.Created || madeLater || changed { // Marked created only once `created` is said whole: the grants part binds on it, so one the bus did not take is // said again on the backoff (Waiting), never marked made and forgotten. if err := k.sayNow(EventCreated, m.Plan, held.Revision, "", asked, holds); err != nil { @@ -821,6 +836,8 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { return } m.Created = true + said := m.Plan.Binding + m.Said = &said } drift := strings.Join(drifts, "; ") switch { @@ -837,6 +854,43 @@ func (k *Keeper) ensureMade(held *Asked, m *Made, create bool) { } } +// endedDaysOf is the ended-days a ledger entry's own configuration gives, 0 where it gives none. +func endedDaysOf(e catalogue.BusStateEntry) int { + n, err := options{raw: e.Configuration}.int(catalogue.ConfigEndedDays, 0) + if err != nil || n < 1 { + return 0 + } + return int(n) +} + +// bindingHeld is the plan's binding as the keeper says it given what the bus holds: it names ended-days only when the +// ledger's configuration gives it and every object the plan asks a lifetime of, a bucket's key or a stream's message, is held +// with one (design 47 H2 H-A-685 (1)). +func bindingHeld(p Plan, holds map[string]Settings) membership.BusBinding { + b := p.Binding + b.EndedDays = endedDaysOf(p.Entry) + if b.EndedDays == 0 { + return b + } + for _, o := range p.Objects { + if o.Settings.KeyTTL && !holds[o.Name].KeyTTL { + b.EndedDays = 0 + break + } + } + return b +} + +// sameBinding is whether the binding last said is the one the keeper would say; none said differs from any. +func sameBinding(said *membership.BusBinding, b membership.BusBinding) bool { + if said == nil { + return false + } + a, _ := json.Marshal(*said) + c, _ := json.Marshal(b) + return string(a) == string(c) +} + // CheckAll compares every entry the keeper holds with the bus, making what is missing (design 25 § 12.2's check at // start) and making again what waits; it answers what it found, one line per entry. func (k *Keeper) CheckAll() []CheckLine { @@ -994,10 +1048,21 @@ func (k *Keeper) SayUnsaid() { // emit says one event; one the bus did not take whole is kept in the keeper's status and said again, on the subjects // left, at the next fill pass. func (k *Keeper) emit(event string, p Plan, revision uint64, why string, asked, held map[string]Settings) { + k.emitFill(event, p, revision, why, asked, held, nil) +} + +// emitFill is emit with the fill of the object judged, which full and full-cleared carry (design 47 H2 H-A-634 (9)). +func (k *Keeper) emitFill(event string, p Plan, revision uint64, why string, asked, held map[string]Settings, fill *EventFill) { + k.emitBody(event, p, revision, why, asked, held, func(b *Event) { b.Fill = fill }) +} + +// emitBody is emit with the body changed before it is said. +func (k *Keeper) emitBody(event string, p Plan, revision uint64, why string, asked, held map[string]Settings, change func(*Event)) { if k.Emit == nil { return } s := k.saying(event, p, revision, why, asked, held) + change(&s.Body) if err := k.Emit(&s); err != nil { s.Error = err.Error() k.setStatus(func(st *Status) { st.Unsaid = append(st.Unsaid, s) }) @@ -1028,7 +1093,7 @@ func (k *Keeper) sayNow(event string, p Plan, revision uint64, why string, asked } func (k *Keeper) saying(event string, p Plan, revision uint64, why string, asked, held map[string]Settings) Saying { - body := Event{V: 1, Module: p.Module, Local: p.Local, Storage: p.Storage, Template: p.Template, Options: p.Entry.Options, + body := Event{V: 2, Module: p.Module, Local: p.Local, Storage: p.Storage, Template: p.Template, Options: p.Entry.Options, Configuration: p.Entry.Configuration, BusName: BusName(p.Module, p.Local), Binding: p.Binding, Asked: asked, Held: held, Why: why, Revision: revision} if event == EventDropped { diff --git a/modules/nats/internal/keeper/keeper_test.go b/modules/nats/internal/keeper/keeper_test.go index aaa61f679..10e5a20c9 100644 --- a/modules/nats/internal/keeper/keeper_test.go +++ b/modules/nats/internal/keeper/keeper_test.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "os" + "slices" "sort" "strings" "sync" @@ -109,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 @@ -332,6 +336,13 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { bigLedger.Types = ledger.Types plainLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, nil) plainLedger.Types = ledger.Types + // A ledger whose own configuration gives ended-days: its state and index buckets with a lifetime per key, its snapshot + // store refusing when full with a lifetime per message (design 47 H2 H-A-634 (3), H-A-687 (1)). + endingLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + endingLedger.Types = ledger.Types + endingLedger.Configuration = map[string]json.RawMessage{"max-age-days": json.RawMessage("90"), "ended-days": json.RawMessage("30")} + badEnding := endingLedger + badEnding.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("3651")} bare := entry("raw", catalogue.StorageStream, "", nil) bare.Configuration = map[string]json.RawMessage{"when-full": json.RawMessage(`"drop-oldest"`), "max-mib": json.RawMessage("8"), "max-age-days": json.RawMessage("3")} forGood := entry("reviews", catalogue.StorageStream, "", nil) @@ -375,20 +386,27 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {16 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {16 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {16 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, {name: "ledger naming max-mib 1024 and past values: its state and index buckets at 1 GiB, no other option reaching them (H-A-636)", entry: bigLedger, objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, {name: "ledger naming no max-mib: its state and index buckets at the state default (H-A-636)", entry: plainLedger, objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " + "key-value mesh-knowledge_records_state {64 MiB, age 0, history 1, new, size 262144}; " + "key-value mesh-knowledge_records_index-by-topic {64 MiB, age 0, history 1, new, size 262144}; " + - "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}", + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0}", binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"}, + {name: "ledger giving ended-days 30 and max-age-days 90: key-ttl on its state, index and snapshot, its history aged 90 days, the binding naming ended-days (H-A-634 (3), H-A-687)", entry: endingLedger, + objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 7776000, history 0, new, size 262144}; " + + "key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144, key-ttl}; " + + "key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144, key-ttl}; " + + "stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, new, size 0, key-ttl}", + binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot, ended-days 30"}, + {name: "a ledger giving ended-days past 3650", entry: badEnding, refused: "not a whole number of days from 1 to 3650"}, {name: "bare stream", entry: bare, objects: "stream mesh-knowledge_raw [mesh.bus.mesh-knowledge.raw.>] {8 MiB, age 259200, history 0, old, size 0}", binding: "stream mesh-knowledge_raw on mesh.bus.mesh-knowledge.raw"}, @@ -428,6 +446,9 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { if s.WorkQueue { w += fmt.Sprintf(", work-queue, duplicates %d", s.DuplicatesSeconds) } + if s.KeyTTL { + w += ", key-ttl" + } objs = append(objs, w+"}") } if got := strings.Join(objs, "; "); got != row.objects { @@ -438,6 +459,9 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) { switch { case b.History != "": binding = fmt.Sprintf("history %s on %s, state %s, indexes %v, snapshot %s", b.History, b.Subject, b.State, b.Indexes, b.Snapshot) + if b.EndedDays > 0 { + binding += fmt.Sprintf(", ended-days %d", b.EndedDays) + } case b.Stream != "": binding = fmt.Sprintf("stream %s on %s", b.Stream, b.Subject) case b.Bucket != "": @@ -697,6 +721,109 @@ func TestTheKeeperMakesWhatAVerdictAsksForAndSaysIt(t *testing.T) { t.Errorf("said %v %v: cleared once asked as held", out.events, out.conds) } }}, + // Design 47 H2 H-A-634 (3), H-A-685 (1) (2), H-A-687 (1) (5): a held snapshot store that drops its oldest differs from one + // that refuses; a binding names ended-days only once every object that asks a lifetime holds one, and is said again + // when it differs from the one last said. + {"a ledger's binding names ended-days once its held objects allow lifetimes, and a changed binding is said again (H-A-685)", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + plain := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}) + plain.Types = []catalogue.LedgerType{{Name: "record", Operations: []catalogue.LedgerOperation{{Name: "open"}}}} + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{plain}}) + ending := plain + ending.Configuration = map[string]json.RawMessage{"ended-days": json.RawMessage("30")} + out.reset() + k.Heard(Accepted{Module: "m", Revision: 2, BusState: []catalogue.BusStateEntry{ending}}) + drift := k.Held()["m"].Made["records"].Drift + if !strings.Contains(drift, "m_records_state: key-ttl asked true, held false") || !strings.Contains(drift, "m_records_snapshot") || + fmt.Sprint(out.events) != "[drifted m records]" || out.bodies[0].Binding.EndedDays != 0 { + t.Fatalf("drift %q, said %v %+v: lifetimes asked of objects that allow none drift, the binding naming no ended-days", drift, out.events, out.bodies) + } + // The bus now allows them (as a recreate in place leaves them): the binding is said again with ended-days. + for _, name := range []string{"KV_m_records_state", "m_records_snapshot"} { + s := bus.held[name] + s.KeyTTL = true + bus.held[name] = s + } + s := bus.held["m_records_snapshot"] + s.Discard = DiscardNew + bus.held["m_records_snapshot"] = s + out.reset() + k.CheckAll() + if fmt.Sprint(out.events) != "[created m records drift-cleared m records]" || out.bodies[0].Binding.EndedDays != 30 { + t.Fatalf("said %v (%q): the drift cleared and created said again naming ended-days 30", out.events, k.Held()["m"].Made["records"].Drift) + } + out.reset() + k.CheckAll() + if len(out.events) != 0 { + t.Errorf("said %v: a binding the same as the one said is said no more", out.events) + } + // A type gaining an operation changes the binding: created again with it, and no recreate. + more := ending + more.Types = []catalogue.LedgerType{{Name: "record", Operations: []catalogue.LedgerOperation{{Name: "open"}, {Name: "end"}}}} + k.Heard(Accepted{Module: "m", Revision: 3, BusState: []catalogue.BusStateEntry{more}}) + if fmt.Sprint(out.events) != "[created m records]" || len(out.bodies[0].Binding.Types[0].Operations) != 2 || len(bus.deleted) != 0 { + t.Errorf("said %v %+v deleted %v: created again with the new operation", out.events, out.bodies, bus.deleted) + } + }}, + {"a held snapshot store that drops its oldest differs from one that refuses when full (H-A-687 (1))", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + s := bus.held["m_records_snapshot"] + s.Discard = DiscardOld + bus.held["m_records_snapshot"] = s + out.reset() + k.CheckAll() + if d := k.Held()["m"].Made["records"].Drift; !strings.Contains(d, "m_records_snapshot: discard asked new, held old") || fmt.Sprint(out.events) != "[drifted m records]" { + t.Errorf("drift %q, said %v: a snapshot store that drops its oldest drifts", d, out.events) + } + }}, + // Design 47 H2 H-A-634 (9), H-A-636, H-A-687 (3): full and full-cleared carry the fill of the object judged, naming it and its + // part; a ledger whose state holds 100 MiB under its cap of 1 GiB says none, at 75% its state is named, and a snapshot store + // at 75% is named with the part snapshot. + {"a ledger's full names the object it judged and its part", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + out.reset() + bus.fill["KV_m_records_state"] = 100 * uint64(MiB) + bus.fill["m_records"] = 200 * uint64(MiB) + k.FillPass() + if len(out.events) != 0 { + t.Fatalf("said %v: a state at 100 MiB of 1 GiB and a history at 20%% are not full (H-A-636)", out.events) + } + bus.fill["KV_m_records_state"] = 768 * uint64(MiB) + k.FillPass() + if fmt.Sprint(out.events) != "[full m records]" || out.bodies[0].V != 2 { + t.Fatalf("said %v", out.events) + } + if f := out.bodies[0].Fill; f == nil || f.Object != "KV_m_records_state" || f.Part != "state" || f.Bytes != 768*uint64(MiB) || f.Cap != 1024*MiB || + !strings.Contains(out.bodies[0].Why, "the state `KV_m_records_state` holds 75%") { + t.Fatalf("full carries %+v and says %q: the state, at 75%% of 1 GiB", f, out.bodies[0].Why) + } + if !slices.ContainsFunc(out.conds, func(c string) bool { return strings.HasPrefix(c, "raised") }) { + t.Fatalf("conditions %v", out.conds) + } + bus.fill["KV_m_records_state"] = 0 + bus.fill["m_records_snapshot"] = 768 * uint64(MiB) + k.FillPass() + k.FillPass() + if len(out.events) != 1 { + t.Fatalf("said %v: the entry stays full while any object holds past the clear mark", out.events) + } + bus.fill["m_records_snapshot"] = 10 * uint64(MiB) + k.FillPass() + if cleared := out.bodies[len(out.bodies)-1]; fmt.Sprint(out.events) != "[full m records full-cleared m records]" || cleared.Fill == nil || cleared.Fill.Part != "history" { + t.Fatalf("said %v", out.events) + } + }}, + {"a ledger's snapshot store at 75% says full with the part snapshot", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { + ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024"}) + k.Heard(Accepted{Module: "m", Revision: 1, BusState: []catalogue.BusStateEntry{ledger}}) + out.reset() + bus.fill["m_records_snapshot"] = 768 * uint64(MiB) + k.FillPass() + if f := out.bodies[0].Fill; fmt.Sprint(out.events) != "[full m records]" || f == nil || f.Object != "m_records_snapshot" || f.Part != "snapshot" { + t.Fatalf("said %v: full naming the snapshot store %+v", out.events, f) + } + }}, {"a plan whose caps pass the account's storage limit is refused, naming the sum and the limit, and the caps made stay (§547)", func(t *testing.T, k *Keeper, bus *fakeBus, out *said) { // drafts: 64 MiB state + 16 MiB objects = 80 MiB; log: 1024 MiB. bus.limits = Limits{AccountBytes: 100 * MiB} @@ -1232,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) { @@ -1254,6 +1381,83 @@ 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 + // The bus holds the first object at a cap other than the one asked (a drift the first change left). + wasHeld := bus.held[objects[0].Stream()] + wasHeld.MaxBytes = objects[0].Settings.MaxBytes * 2 + bus.held[objects[0].Stream()] = wasHeld + heldCap := wasHeld.MaxBytes + 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 != "" || + len(out.bodies) == 0 || len(out.bodies[len(out.bodies)-1].Before) != len(objects) || len(out.bodies[len(out.bodies)-1].After) != len(objects) || + out.bodies[len(out.bodies)-1].Why != "" { + t.Fatalf("the change in place: %q, updated %v, deleted %v, said %v", got.Error, bus.updated, bus.deleted, out.events) + } + // The before names the cap the object held, never the cap asked (H-A-686 (3)). + if b, a := out.bodies[len(out.bodies)-1].Before[0], out.bodies[len(out.bodies)-1].After[0]; b.Cap != heldCap || heldCap == objects[0].Settings.MaxBytes || a.Cap != objects[0].Settings.MaxBytes { + t.Errorf("before names the cap %d, after %d: the held cap was %d, the asked %d", b.Cap, a.Cap, heldCap, objects[0].Settings.MaxBytes) + } + }}, // 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) { diff --git a/modules/nats/internal/keeper/plan.go b/modules/nats/internal/keeper/plan.go index c9c8fb2f1..2fd614c3f 100644 --- a/modules/nats/internal/keeper/plan.go +++ b/modules/nats/internal/keeper/plan.go @@ -37,6 +37,8 @@ const ( ValueMost = 256 << 10 EntryMost = 256 << 10 DefaultCapMiB = 1024 + // EndedDaysMost is the most whole days a ledger's ended-days gives (design 47 H2 H-A-634 (3)). + EndedDaysMost = 3650 EventsDays = 7 ) @@ -83,7 +85,7 @@ type Settings struct { MaxMsgSize int64 `json:"max-msg-size,omitempty"` // DuplicatesSeconds is a work queue's duplicate window. DuplicatesSeconds int64 `json:"duplicates-seconds,omitempty"` - // KeyTTL says a bucket's key may be given a lifetime of its own. + // KeyTTL says a bucket's key, or a stream's message, may be given a lifetime of its own. KeyTTL bool `json:"key-ttl,omitempty"` } @@ -127,6 +129,29 @@ type Plan struct { Entry catalogue.BusStateEntry `json:"entry"` } +// PartOf is the place an object has in its entry's binding, for a ledger: `history`, `state`, `index ` or `snapshot`; +// empty for an entry of one object (design 47 H2 H-A-634 (9), H-A-687 (3)). +func (p Plan) PartOf(o Object) string { + if p.Storage != catalogue.StorageLedger { + return "" + } + b := p.Binding + switch { + case o.Name == b.History && b.History != "": + return "history" + case o.Name == b.State && b.State != "": + return "state" + case b.History != "" && o.Name == b.History+"_snapshot": + return "snapshot" + } + for name, bucket := range b.Indexes { + if o.Name == bucket { + return "index " + name + } + } + return "" +} + // BusName is `_`, the name the mesh gives an entry on the bus (design 25 § 12.1). func BusName(module, local string) string { return module + Separator + local } @@ -229,6 +254,15 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { return Plan{}, err } history.MaxAgeSeconds = days(age) + // A ledger whose own configuration gives ended-days has its ended instances' keys go by the bus's lifetime per key + // and per message (design 47 H2 H-A-634 (3), ADR 0690 §2): whole days, 1 to 3650. + endedDays, err := conf.int(catalogue.ConfigEndedDays, 0) + if err != nil { + return Plan{}, err + } + if _, given := conf.raw[catalogue.ConfigEndedDays]; given && (endedDays < 1 || endedDays > EndedDaysMost) { + return Plan{}, fmt.Errorf("the configuration %s of %q is %d, not a whole number of days from 1 to %d", catalogue.ConfigEndedDays, e.Name, endedDays, EndedDaysMost) + } // The state bucket and each index bucket take the ledger's own max-mib, as its history and snapshot do, and no // other option of it; with none they keep the state default (design 47 H2's corrections, item 12, H-A-636). stateOpts := options{} @@ -239,12 +273,14 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { if err != nil { return Plan{}, err } + state.KeyTTL = endedDays > 0 subject := buscompose.LedgerHistorySubject(module, e.Name) snapshot := buscompose.LedgerSnapshotSubject(module, e.Name) p.Binding.History, p.Binding.Subject = name, subject p.Binding.State = name + "_state" p.Binding.Snapshot = snapshot p.Binding.Types = e.Types + p.Binding.EndedDays = int(endedDays) p.Objects = []Object{ {Kind: KindStream, Name: name, Subjects: []string{subject + ".>"}, Settings: history}, {Kind: KindBucket, Name: p.Binding.State, Settings: state}, @@ -266,9 +302,11 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) { p.Binding.Indexes[ix] = name + "_index-" + ix p.Objects = append(p.Objects, Object{Kind: KindBucket, Name: p.Binding.Indexes[ix], Settings: state}) } - // The snapshot: the latest state per instance, never expiring (ADR 0597 §8), one message per subject. + // The snapshot: the latest state per instance, one message per subject, refusing when full at the ledger's cap (ADR 0595 + // §3, ADR 0597 §8, ADR 0690 §2: a snapshot goes only with its key), with a lifetime per message where the ledger gives + // ended-days (design 47 H2 H-A-634 (3), H-A-687 (1)). p.Objects = append(p.Objects, Object{Kind: KindStream, Name: name + "_snapshot", Subjects: []string{snapshot + ".>"}, - Settings: Settings{MaxBytes: history.MaxBytes, History: 1, Discard: DiscardOld}}) + Settings: Settings{MaxBytes: history.MaxBytes, History: 1, Discard: DiscardNew, KeyTTL: endedDays > 0}}) case e.Storage == catalogue.StorageStream && e.Template == "": // A bare stream: its own configuration, which must give when full, a cap and an age (design 25 § 12.1). var full string @@ -402,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 { @@ -431,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, "; ") } diff --git a/modules/nats/internal/keeper/requests.go b/modules/nats/internal/keeper/requests.go index 0f1b08821..53d80f0f7 100644 --- a/modules/nats/internal/keeper/requests.go +++ b/modules/nats/internal/keeper/requests.go @@ -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, was: st}) + } + // 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,24 +294,69 @@ 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 + var before, after []EventFill + 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) + } } + _, now, _, _ := k.Bus.Held(ctx, o) + before = append(before, EventFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: st.before.Messages, Bytes: st.before.Bytes, Cap: st.was.MaxBytes}) + after = append(after, EventFill{Object: o.Stream(), Part: m.Plan.PartOf(o), Count: now.Messages, Bytes: now.Bytes, Cap: o.Settings.MaxBytes}) + 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, now.Messages, now.Bytes)) } wasDrift := m.Drift != "" m.Drift = "" + // Every object is as asked again, so its binding names ended-days as the ledger's configuration gives it (H-A-685 (1)). + madeAs := map[string]Settings{} + for _, o := range m.Plan.Objects { + madeAs[o.Name] = o.Settings + } + m.Plan.Binding = bindingHeld(m.Plan, madeAs) + said := m.Plan.Binding + m.Said = &said held.Made[r.Local] = m k.write(held) - k.emit(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil) + k.emitBody(EventRecreated, m.Plan, held.Revision, r.Why, nil, nil, func(b *Event) { b.Before, b.After = before, after }) 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 + was Settings // what the object held before: its cap is the before's, never the asked one } // warranted holds a recreate or a drop to the operator's warrant on the ask its tool raised: chosen by the operator, diff --git a/modules/nats/module.json b/modules/nats/module.json index 57b75d50d..a94ab7a54 100644 --- a/modules/nats/module.json +++ b/modules/nats/module.json @@ -67,7 +67,9 @@ "seat:mesh-catalog.revision", "seat:mesh-catalog.registrations", "seat:mesh-delivery.source", - "seat:mesh-catalog.seat-definitions" + "seat:mesh-catalog.seat-definitions", + "seat:mesh-catalog.modules", + "seat:mesh-catalog.entry" ], "consumes": [ "mesh-catalog.catalog-revision", @@ -97,7 +99,8 @@ "type": "number", "description": "How many hours since a module's durable's twin last delivered it is current (design 47 H2, H-A-472): nats_consumer_remove removes a module's durable with no pulls waiting only while its twin has pulls waiting and a delivery within these hours. The grants part's manifest names the same setting for its orphaned durables. The tool reads it as its configuration at each call.", "minimum": 1, - "default": 24 + "default": 24, + "runtime": true } }, "streams": [ @@ -178,6 +181,7 @@ "nats_user_can", "nats_snapshot_verify", "nats_consumer_remove", + "nats_consumer_narrow", "nats_bucket_remove", "nats_stream_remove", "nats_stream_purge",