Compare commits
80
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
727e7fe90f | ||
|
|
0b8be7fff5 | ||
|
|
264dfb1660 | ||
|
|
37c350fb89 | ||
|
|
4d2f1ea1f3 | ||
|
|
2778e8f97b | ||
|
|
4df9c4b03b | ||
|
|
6c16ba39e9 | ||
|
|
254fc645fd | ||
|
|
4dbb4a2d4a | ||
|
|
174dead676 | ||
|
|
25c4c52396 | ||
|
|
46b4621316 | ||
|
|
ae8f070916 | ||
|
|
1be74c87cf | ||
|
|
f46e51de26 | ||
|
|
38559d71ec | ||
|
|
531701f390 | ||
|
|
8db99b0205 | ||
|
|
477b3b1a70 | ||
|
|
cbaf0cba57 | ||
|
|
54cf195bcb | ||
|
|
98775336d6 | ||
|
|
f8e40950e1 | ||
|
|
e2e82311c9 | ||
|
|
43711755d6 | ||
|
|
a770848c65 | ||
|
|
9d7c4b2e8c | ||
|
|
a37cde8bcc | ||
|
|
1ebb59a9d7 | ||
|
|
e83a7adb2d | ||
|
|
ce2455d189 | ||
|
|
6f7311820c | ||
|
|
1dbc2b6f88 | ||
|
|
b15c220822 | ||
|
|
cda35e6c42 | ||
|
|
4b6d76d3dd | ||
|
|
fcc24fc468 | ||
|
|
89e5eef3c5 | ||
|
|
99b9b826e5 | ||
|
|
023792c189 | ||
|
|
b7ba5a3535 | ||
|
|
804f5c4ab4 | ||
|
|
f6dbeafeea | ||
|
|
feb0120330 | ||
|
|
5c1911dd7c | ||
|
|
1841bc959e | ||
|
|
64f68ec3f0 | ||
|
|
82abaa03ac | ||
|
|
8aef19934e | ||
|
|
7c1f61f735 | ||
|
|
3f9f976fac | ||
|
|
0aed3065b5 | ||
|
|
5de68de0a0 | ||
|
|
aa1a59c6bc | ||
|
|
e580f54a4b | ||
|
|
141cddf7c9 | ||
|
|
cdae0e0339 | ||
|
|
c055c82bd8 | ||
|
|
b1b7940f4f | ||
|
|
8baa3f5ada | ||
|
|
3b7d5c8328 | ||
|
|
c6f478aee9 | ||
|
|
8f8d749bb8 | ||
|
|
2799ba177c | ||
|
|
c7681636a8 | ||
|
|
9c8ce82151 | ||
|
|
2bf3426efb | ||
|
|
5a82d93ccb | ||
|
|
ef7d3f69d2 | ||
|
|
436e65f0c4 | ||
|
|
a569c80e98 | ||
|
|
c1abd7e210 | ||
|
|
af36f1a617 | ||
|
|
ce04011f96 | ||
|
|
f282a74e59 | ||
|
|
1d9e8d6824 | ||
|
|
89fb416a1d | ||
|
|
7da6ee61aa | ||
|
|
84f1e5b93b |
@@ -5,7 +5,7 @@
|
|||||||
// exempt from that, and said so. Every build module, test step or not, must also hold a test that calls
|
// 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
|
// 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 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
|
package failurekit
|
||||||
|
|
||||||
import (
|
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 "+
|
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))
|
"(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
|
// 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).
|
// 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(")
|
says, err := runsTheKit(dir, "conformance.Passing(")
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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.
|
// claims no node-build-* seat is not judged.
|
||||||
func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n"
|
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
|
kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep
|
||||||
for path, body := range map[string]string{
|
for path, body := range map[string]string{
|
||||||
"modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`,
|
"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/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/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/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/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`,
|
||||||
"modules/e/cmd/e/kit.go": kit, // not a test file
|
"modules/e/cmd/e/kit.go": kit, // not a test file
|
||||||
} {
|
} {
|
||||||
@@ -49,9 +51,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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) {
|
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 {
|
for _, j := range got {
|
||||||
is := "passes"
|
is := "passes"
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ func publishOf(in reg.PublishInput) holder.PublishRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func publishAnswer(a holder.PublishAnswer) reg.PublishAnswer {
|
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}
|
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.
|
// 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)
|
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
|
return out
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,18 +62,37 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
|
|||||||
t.Errorf("%s's body %s is not the contract's: %v", event, b, err)
|
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 {
|
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)
|
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.
|
// 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{}
|
cat := twoDigests{}
|
||||||
for _, c := range []struct{ seat, want string }{{holder.ArtifactSeat, "sha256:blob"}, {holder.ImageSeat, "sha256:manifest"}} {
|
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"}})
|
// and the fingerprint kept for it beside, none where the key names another digest or there is none (H-A-589 (3))
|
||||||
if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" {
|
kept := memKept{holder.FingerprintKey("m/files", "0.1.7"): {Digest: c.want, Fingerprint: "f1"}}
|
||||||
t.Errorf("versions on %s answers %+v, want digest %s", c.seat, got.Versions, c.want)
|
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" {
|
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)
|
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 }
|
||||||
|
|||||||
@@ -74,6 +74,25 @@ func (k kept[T]) List() ([]T, error) {
|
|||||||
return out, nil
|
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 {
|
func say(seat, event string, body holder.Event) error {
|
||||||
return stdio.SeatPublish("mesh.seat."+seat+".event."+event, eventBody(event, body), body.ID)
|
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")
|
base, _ := url.Parse("http://127.0.0.1:5001")
|
||||||
store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}}
|
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),
|
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()}
|
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{},
|
v := &holder.Verbs{Holder: h, Catalog: store, Holds: kept[holder.Hold]{state: "holds", key: holder.Hold.Key}, Mirrors: mirrors{},
|
||||||
Files: files}
|
Files: files}
|
||||||
|
|||||||
@@ -215,9 +215,25 @@ func (m memHolds) List() ([]Hold, error) {
|
|||||||
return out, nil
|
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 {
|
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 := &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 },
|
Store: b.store, Now: func() time.Time { return b.now },
|
||||||
Say: func(seat, event string, body Event) error {
|
Say: func(seat, event string, body Event) error {
|
||||||
b.said = append(b.said, said{seat, event, body})
|
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"))
|
_, err := b.h.Publish(ArtifactSeat, builder, req("t"))
|
||||||
return err
|
return err
|
||||||
}, "the builder did not reserve it"},
|
}, "the builder did not reserve it"},
|
||||||
{"a version the store holds at another digest", func(b *bed) error {
|
{"a version stored while the state fingerprints is at its cap", func(b *bed) error {
|
||||||
b.store.held = map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}}
|
b.h.Fingerprints.(*memFingerprints).full = true
|
||||||
r := req("t")
|
_, _ = b.h.Publish(ArtifactSeat, builder, req("t"))
|
||||||
r.Digest = "sha256:aa"
|
_, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "t", Digest: part.Digest, Last: true, Data: blob})
|
||||||
_, err := b.h.Publish(ArtifactSeat, builder, r) // the reservation names no digest yet: the bed's builder says yes
|
if len(b.store.put) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused {
|
||||||
if !b.findings["publish-refused m/program@0.1.4"] || len(b.store.put) != 0 {
|
return errors.New("stored, or not refused: " + fmt.Sprint(b.said))
|
||||||
return errors.New("not refused loudly, or stored")
|
|
||||||
}
|
}
|
||||||
return err
|
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 {
|
{"an image on the artifact seat", func(b *bed) error {
|
||||||
r := req("t")
|
r := req("t")
|
||||||
r.Kind = KindImage
|
r.Kind = KindImage
|
||||||
@@ -424,8 +439,9 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
|||||||
}
|
}
|
||||||
other := req("other")
|
other := req("other")
|
||||||
other.Digest = digestOf([]byte("other bytes"))
|
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) {
|
// H-A-729, H-A-732: other bytes at the held version are answered, not failed, naming the held layer, and open no transfer.
|
||||||
t.Errorf("other bytes at the held version = %v; want refused naming the held layer %s", err, part.Digest)
|
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 {
|
if len(reg.blobs) != uploads {
|
||||||
t.Errorf("the store took %d blobs more; want none", 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)
|
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) {
|
t.Run("only the missing layers are sent, and an idle transfer is dropped", func(t *testing.T) {
|
||||||
b := newBed(true)
|
b := newBed(true)
|
||||||
other := []byte("layer two")
|
other := []byte("layer two")
|
||||||
@@ -750,13 +833,24 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
|||||||
b := newBed(true)
|
b := newBed(true)
|
||||||
return publishconformance.Bed{
|
return publishconformance.Bed{
|
||||||
Hold: func(d string) { b.store.has[d] = true },
|
Hold: func(d string) { b.store.has[d] = true },
|
||||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
// the holder holds the version at digest d, keeping fingerprint fp for it
|
||||||
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"})
|
HoldWith: func(d, fp string) {
|
||||||
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
|
b.store.held = map[string]heldAt{publishconformance.Name + "@" + publishconformance.Version: {manifest: d, layer: d}}
|
||||||
if len(b.said) > 0 {
|
b.store.has[d] = true
|
||||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
|
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" {
|
if m.Class != "core" {
|
||||||
t.Errorf("class %q, want core", m.Class)
|
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 {
|
for _, st := range m.State {
|
||||||
if st.MaxMiB != 8 {
|
want := 8
|
||||||
t.Errorf("the state %s names max-mib %d, want 8", st.Name, st.MaxMiB)
|
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).
|
// 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.
|
// 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}
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
"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
|
// 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 and TransfersState are the object store and the state distribution asks as bus state.
|
||||||
IncomingObjects = "incoming"
|
IncomingObjects = "incoming"
|
||||||
TransfersState = "transfers"
|
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
|
// 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
|
// 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.
|
// a timer.
|
||||||
@@ -68,6 +72,36 @@ type PublishAnswer struct {
|
|||||||
Missing []string `json:"missing"`
|
Missing []string `json:"missing"`
|
||||||
// Ended says the publish ended at once: everything was held, `published` or `refused` is said.
|
// Ended says the publish ended at once: everything was held, `published` or `refused` is said.
|
||||||
Ended bool `json:"ended,omitempty"`
|
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: `<name>.<version>`, 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.
|
// 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 {
|
type Holder struct {
|
||||||
Objects Objects
|
Objects Objects
|
||||||
Transfers TransferState
|
Transfers TransferState
|
||||||
Builder Builder
|
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
|
||||||
Store Store
|
Fingerprints FingerprintState
|
||||||
Say Say
|
Builder Builder
|
||||||
Finding Finding
|
Store Store
|
||||||
Now func() time.Time
|
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 reads incoming's cap from its binding (parts.BusCap); IncomingCap when nil or when the binding names none.
|
||||||
Cap func() (uint64, error)
|
Cap func() (uint64, error)
|
||||||
// Record records a hand act through the seat mesh-hand-acts (meshhandactsclient.Recorder); a drop by hand is refused
|
// 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
|
return nil
|
||||||
},
|
},
|
||||||
Store: func(t Transfer, held map[string][]byte) error {
|
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)
|
path, err := h.Store.Put(t.Shape.PublishRequest, held)
|
||||||
ref := SeatReference(t.Shape.Seat, path)
|
ref := SeatReference(t.Shape.Seat, path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
reason := "the store did not take it: " + err.Error()
|
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))
|
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
||||||
}
|
}
|
||||||
h.Finding("publish-refused", t.Shape.Name+"@"+t.Shape.Version, "", false)
|
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 {
|
if err != nil {
|
||||||
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
||||||
} else if other != "" {
|
} else if other != "" {
|
||||||
// A second publish of a held version with another digest is refused before the reservation is asked, as the forge
|
// The version is held at another digest: answered with the held digest and the fingerprint kept for it, nothing
|
||||||
// holds the first (A-490j, H-A-393): while the reserved digest is still empty it would pass, and the store's Put
|
// stored, no transfer opened (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)).
|
||||||
// would move the version's tag.
|
return h.heldElsewhere(r, other)
|
||||||
return h.refusePublish(seat, r, fmt.Sprintf("the store holds %s@%s at digest %s, not %s", r.Name, r.Version, other, r.Digest))
|
|
||||||
} else if ref != "" {
|
} else if ref != "" {
|
||||||
return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.timed("the published event on the seat", func() error {
|
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), ""))
|
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
|
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
|
// refusePublish ends a publish refused before anything is stored: its finding raised, refused said on the seat, the reason
|
||||||
// answered.
|
// answered.
|
||||||
func (h *Holder) refusePublish(seat string, r PublishRequest, reason string) (PublishAnswer, error) {
|
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 {
|
if !ok {
|
||||||
return refuse("the builder did not reserve it: " + why)
|
return refuse("the builder did not reserve it: " + why)
|
||||||
}
|
}
|
||||||
|
if err := h.keep(r); err != nil {
|
||||||
|
return refuse(err.Error())
|
||||||
|
}
|
||||||
tag := r
|
tag := r
|
||||||
tag.Parts = []Part{{Digest: r.Digest}}
|
tag.Parts = []Part{{Digest: r.Digest}}
|
||||||
var path string
|
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{})
|
path, err = h.Store.Put(tag, map[string][]byte{})
|
||||||
return err
|
return err
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
|
h.unkeep(r)
|
||||||
return refuse("the store did not tag it: " + err.Error())
|
return refuse("the store did not tag it: " + err.Error())
|
||||||
}
|
}
|
||||||
h.Finding("publish-refused", r.Name+"@"+r.Version, "", false)
|
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
|
return PublishAnswer{}, err
|
||||||
}
|
}
|
||||||
if r.Version != "" {
|
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) {
|
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
|
return err
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
||||||
} else if ref != "" {
|
} else if ref != "" {
|
||||||
return PublishAnswer{Transfer: r.Transfer, Ended: true}, nil
|
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)
|
t, found, err := h.Transfers.Get(r.Transfer)
|
||||||
|
|||||||
@@ -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
|
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)
|
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()) })
|
slices.SortFunc(all, func(a, b Hold) int { return strings.Compare(a.Key(), b.Key()) })
|
||||||
return all, nil
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -255,6 +255,10 @@
|
|||||||
"name": "transfers",
|
"name": "transfers",
|
||||||
"max-mib": 8
|
"max-mib": 8
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "fingerprints",
|
||||||
|
"max-mib": 16
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "idle",
|
"name": "idle",
|
||||||
"key-ttl": true,
|
"key-ttl": true,
|
||||||
|
|||||||
@@ -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
|
**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`
|
`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,
|
(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account: anyone writes, nobody lists, and the
|
||||||
nobody lists; the bundle is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME,
|
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,
|
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
|
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
|
the commit was made or not. A file refused before that (a bad name, a missing hash or spool directory, a name with no
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export type Say = (subject: string, body: unknown, id?: string) => Promise<void>
|
|||||||
|
|
||||||
/** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its
|
/** 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
|
* 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 {
|
export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined {
|
||||||
const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note);
|
const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note);
|
||||||
if (landed.length === 0) return undefined;
|
if (landed.length === 0) return undefined;
|
||||||
|
|||||||
@@ -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. */
|
/** 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";
|
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 { findingKey, findingValue } from "./findings.js";
|
||||||
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<string, unknown> } {
|
|
||||||
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,
|
|
||||||
} };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A part's finding of a first view unanswered past its bound, from the follower's status. */
|
/** 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 {
|
export function unansweredFinding(part: string, s: Status, at: Date): Finding {
|
||||||
|
|||||||
@@ -694,13 +694,6 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
|
|||||||
"cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"},
|
"cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"},
|
||||||
"cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_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 {
|
for _, a := range m.Build.Artifacts {
|
||||||
want, ok := wants[a.From]
|
want, ok := wants[a.From]
|
||||||
if !ok {
|
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)
|
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"} {
|
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
|
||||||
if a.Env[k] != files[a.From][k] {
|
if a.Env[k] != "" {
|
||||||
t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][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])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
// 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,
|
// 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
|
// 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
|
// (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.
|
// replaced it. The file is removed once taken, whether the commit was made or not.
|
||||||
|
|||||||
@@ -452,6 +452,10 @@ func retention(ctx context.Context, f *Forge, only string, keep int, dryRun bool
|
|||||||
} else {
|
} else {
|
||||||
o.Module = c.Package
|
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 {
|
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))
|
s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its removed could not be said: %v", c.Package, c.Version, err))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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) {
|
func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) {
|
||||||
f := aRegistry(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
|
var removed []string
|
||||||
say = func(seat, event string, o packageseats.Outcome) error {
|
say = func(seat, event string, o packageseats.Outcome) error {
|
||||||
removed = append(removed, seat+" "+event+" "+o.Name+"@"+o.Version+" "+o.Reason)
|
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 {
|
if len(p.Deleted) != 4 || len(p.Refused) != 0 {
|
||||||
t.Fatalf("answered %v / %v", p.Deleted, p.Refused)
|
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
|
// 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"`
|
Objects any `json:"objects"`
|
||||||
State any `json:"state"`
|
State any `json:"state"`
|
||||||
}{m.Objects, m.State})
|
}{m.Objects, m.State})
|
||||||
// Each with its cap (design 47 H2 §812, H-A-411 (2)).
|
// 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"`} {
|
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) {
|
if !strings.Contains(string(req), want) {
|
||||||
t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req)
|
t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -227,6 +228,30 @@ func outcomeBody(o packageseats.Outcome) map[string]any {
|
|||||||
"reference": o.Reference, "reason": o.Reason, "module": o.Module}
|
"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.
|
// say says a seat's event; a test hears it instead.
|
||||||
var say = sayOn
|
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.
|
// 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) {
|
func busHolder(forge func() (*Forge, error)) (*packageseats.Holder, error) {
|
||||||
return &packageseats.Holder{Objects: parts.BusObjects(packageseats.IncomingObjects),
|
return &packageseats.Holder{Objects: parts.BusObjects(packageseats.IncomingObjects),
|
||||||
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
|
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
|
||||||
Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say,
|
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
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
a, err := h.Publish(seat, stdio.CallerOf(args), p)
|
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})
|
out, _ := as[PA](map[string]any{"transfer": a.Transfer, "lacks": a.Lacks, "held": a.Ended && len(a.Lacks) == 0})
|
||||||
return out, err
|
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
|
return out, err
|
||||||
})},
|
})},
|
||||||
{Name: seat + "." + packageseats.VerbVersions, Input: obj,
|
{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) {
|
Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) {
|
||||||
in, err := as[VI](args)
|
in, err := as[VI](args)
|
||||||
if err != nil {
|
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{}
|
list := []map[string]any{}
|
||||||
for _, v := range got {
|
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})
|
return as[VA](map[string]any{"name": q.Name, "versions": list})
|
||||||
})},
|
})},
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -229,3 +230,44 @@ func vaultHolding(t *testing.T, account string, held map[string]string) *forgeht
|
|||||||
}
|
}
|
||||||
return v
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -367,7 +367,7 @@ func TestThePackageSeatsWhole(t *testing.T) {
|
|||||||
}
|
}
|
||||||
t.Cleanup(nc.Close)
|
t.Cleanup(nc.Close)
|
||||||
js, _ := jetstream.New(nc)
|
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 {
|
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -482,6 +482,11 @@ func TestThePackageSeatsWhole(t *testing.T) {
|
|||||||
if !bytes.Equal(up, zipped) {
|
if !bytes.Equal(up, zipped) {
|
||||||
t.Errorf("the forge took %d bytes, not the %d published", len(up), len(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)
|
transfers, _ := js.KeyValue(ctx, "gitea_"+packageseats.TransfersState)
|
||||||
if keys, _ := transfers.Keys(ctx); len(keys) != 0 {
|
if keys, _ := transfers.Keys(ctx); len(keys) != 0 {
|
||||||
t.Errorf("an ended transfer is still kept: %v", keys)
|
t.Errorf("an ended transfer is still kept: %v", keys)
|
||||||
|
|||||||
@@ -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<string, unknown> } {
|
||||||
|
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,
|
||||||
|
} };
|
||||||
|
}
|
||||||
@@ -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
|
// 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.
|
// 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
|
// Gitea runs as its own account, so the vault hands these bundles its own secrets; no file stands in for the vault
|
||||||
// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript
|
// (H-A-575: the stand-in of H-A-564 ended with H-A-543's delivery).
|
||||||
// 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.
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"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).
|
// Ask asks one seat verb and answers its reply (stdio.Ask).
|
||||||
type Ask func(address string, args any) (json.RawMessage, error)
|
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
|
// VaultToken is one account's token as this process holds it, read from the vault alone.
|
||||||
// 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).
|
|
||||||
type VaultToken struct {
|
type VaultToken struct {
|
||||||
Account string
|
Account string
|
||||||
// File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none.
|
ask Ask
|
||||||
File string
|
keys seal.KeyPair
|
||||||
// FileByDefault says File is DefaultStateDir's, the manifest naming none.
|
|
||||||
FileByDefault bool
|
|
||||||
ask Ask
|
|
||||||
keys seal.KeyPair
|
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
token string
|
token string
|
||||||
generation int
|
generation int
|
||||||
source string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewVaultToken is an account's token read through ask, sealed to a key made for this process.
|
// 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
|
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 {
|
func (t *VaultToken) Load() error {
|
||||||
raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey})
|
raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey})
|
||||||
if err != nil {
|
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)
|
return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err)
|
||||||
}
|
}
|
||||||
var got struct {
|
var got struct {
|
||||||
@@ -121,45 +80,16 @@ func (t *VaultToken) Load() error {
|
|||||||
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
|
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
|
||||||
}
|
}
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
t.token, t.generation, t.source = token, got.Generation, SourceVault
|
t.token, t.generation = token, got.Generation
|
||||||
t.mu.Unlock()
|
t.mu.Unlock()
|
||||||
return nil
|
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: "<scopes> for <account>").
|
|
||||||
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).
|
// Token is the token held; read from the vault when none is yet (the module mints it first).
|
||||||
func (t *VaultToken) Token() (string, error) {
|
func (t *VaultToken) Token() (string, error) {
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
token, source := t.token, t.source
|
token := t.token
|
||||||
t.mu.Unlock()
|
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 != "" {
|
if token != "" {
|
||||||
return token, nil
|
return token, nil
|
||||||
}
|
}
|
||||||
@@ -208,45 +138,12 @@ func TokenOf(account string) (*VaultToken, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
t.File, t.FileByDefault = TokenFile(account)
|
|
||||||
processTokens[account] = t
|
processTokens[account] = t
|
||||||
return t, nil
|
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
|
// 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.
|
// subscription ends.
|
||||||
func Follow(logf func(format string, args ...any), accounts ...string) error {
|
func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||||
var held []*VaultToken
|
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) {
|
func Start(logf func(format string, args ...any), held ...*VaultToken) {
|
||||||
for _, t := range held {
|
for _, t := range held {
|
||||||
switch err := t.Load(); {
|
if err := t.Load(); err != nil {
|
||||||
case err != nil:
|
|
||||||
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
|
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
|
||||||
case t.Source() == SourceFile:
|
continue
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,33 +4,15 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/seal"
|
"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
|
// H-A-575: a Go bundle reads its token from the vault alone and says it did at start; whatever the vault refuses, no
|
||||||
// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file.
|
// token file stands in (the stand-in of H-A-564 is gone).
|
||||||
func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) {
|
func TestATokenComesFromTheVaultAloneAndNoFileStandsInWhenTheVaultRefuses(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")
|
|
||||||
vaultHolds := func(token string) Ask {
|
vaultHolds := func(token string) Ask {
|
||||||
return func(address string, args any) (json.RawMessage, error) {
|
return func(address string, args any) (json.RawMessage, error) {
|
||||||
a := args.(map[string]any)
|
a := args.(map[string]any)
|
||||||
@@ -45,27 +27,23 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil
|
|||||||
vaultSays := func(said string) Ask {
|
vaultSays := func(said string) Ask {
|
||||||
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
|
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
|
||||||
}
|
}
|
||||||
notModule := vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here")
|
|
||||||
for _, c := range []struct {
|
for _, c := range []struct {
|
||||||
name, account, file string
|
name, account string
|
||||||
ask Ask
|
ask Ask
|
||||||
token, source, err string
|
token, err string
|
||||||
}{
|
}{
|
||||||
{"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""},
|
{"the vault hands it", "mesh-tools", vaultHolds("vault-tools"), "vault-tools", ""},
|
||||||
{"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""},
|
{"the vault refuses the tool runner: no file is read", "mesh-packages",
|
||||||
{"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""},
|
vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here"), "", "no module's account"},
|
||||||
{"another module's account: the file", "mesh-tools", tools,
|
{"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"), "file-tools", SourceFile, ""},
|
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: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"},
|
{"the vault holds none", "mesh-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"},
|
|
||||||
} {
|
} {
|
||||||
t.Run(c.name, func(t *testing.T) {
|
t.Run(c.name, func(t *testing.T) {
|
||||||
v, err := NewVaultToken(c.account, c.ask)
|
v, err := NewVaultToken(c.account, c.ask)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
v.File = c.file
|
|
||||||
var said []string
|
var said []string
|
||||||
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
|
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
|
||||||
got, err := v.Token()
|
got, err := v.Token()
|
||||||
@@ -75,64 +53,12 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil || got != c.token || v.Source() != c.source {
|
if err != nil || got != c.token {
|
||||||
t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source)
|
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) {
|
if len(said) != 1 || strings.Contains(said[0], c.token) || strings.Contains(said[0], "file") {
|
||||||
t.Fatalf("said %q: one line naming %q, never the token", said, c.source)
|
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
|
|
||||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
"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.
|
// 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
|
// 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.
|
// end is the event that drops a transfer left with no chunk for TransferIdle, never a timer.
|
||||||
IdleState = "idle"
|
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 is the one kind a package seat holds.
|
||||||
KindPackage = "package"
|
KindPackage = "package"
|
||||||
// Self is the forge module, the holder every outcome names.
|
// Self is the forge module, the holder every outcome names.
|
||||||
@@ -99,6 +103,36 @@ type Answer struct {
|
|||||||
Transfer string
|
Transfer string
|
||||||
Lacks []string
|
Lacks []string
|
||||||
Ended bool
|
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: `<name>.<version>`, 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.
|
// Version is one version a seat holds of a name.
|
||||||
@@ -106,6 +140,8 @@ type Version struct {
|
|||||||
Version string
|
Version string
|
||||||
Digest string
|
Digest string
|
||||||
Published time.Time
|
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).
|
// Builder answers whether the builder reserved a version with a digest (Reserved).
|
||||||
@@ -129,8 +165,10 @@ type Store interface {
|
|||||||
type Holder struct {
|
type Holder struct {
|
||||||
Objects parts.Objects
|
Objects parts.Objects
|
||||||
Transfers parts.Transfers[Opening]
|
Transfers parts.Transfers[Opening]
|
||||||
Builder Builder
|
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
|
||||||
Store Store
|
Fingerprints FingerprintState
|
||||||
|
Builder Builder
|
||||||
|
Store Store
|
||||||
// Say says an event on a seat's family.
|
// Say says an event on a seat's family.
|
||||||
Say func(seat, event string, o Outcome) error
|
Say func(seat, event string, o Outcome) error
|
||||||
// Finding writes (raised) or clears the module's finding of a kind for a subject.
|
// 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
|
// 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.
|
// arms it on each open that leaves a transfer open. Nil arms nothing.
|
||||||
Idle func(key string, ttl time.Duration) error
|
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.
|
// 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 {
|
Store: func(t Transfer, held map[string][]byte) error {
|
||||||
file := held[t.Shape.Digest]
|
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)
|
module, err := h.Store.Put(t.Shape.Seat, t.Shape.Publish, file)
|
||||||
if err != nil {
|
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()
|
reason := "the forge did not take it: " + err.Error()
|
||||||
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
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 {
|
if err := checkPublish(seat, p); err != nil {
|
||||||
return Answer{}, err
|
return Answer{}, err
|
||||||
}
|
}
|
||||||
// A rebuild of a published version answers it held and uploads nothing; the same version with other content is
|
// A rebuild of a published version answers it held and uploads nothing. The same version with other content is answered
|
||||||
// refused, as the registry would refuse it.
|
// 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 {
|
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)
|
return Answer{}, fmt.Errorf("publish: the forge cannot say whether it holds %s@%s: %w", p.Name, p.Version, err)
|
||||||
} else if ok {
|
} else if ok {
|
||||||
if d != p.Digest {
|
if d != p.Digest {
|
||||||
reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest)
|
return h.heldElsewhere(p, d)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
o := outcomeOf(p, "")
|
o := outcomeOf(p, "")
|
||||||
o.Reference = Reference(p.Name, p.Version)
|
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
|
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.
|
// 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) {
|
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 {
|
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("versions: the forge cannot list %s: %w", name, err)
|
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
|
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)
|
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}
|
o := Outcome{Name: name, Version: version, Kind: KindPackage, Digest: d, Reason: reason}
|
||||||
return o, h.Say(seat, EventRemoved, o)
|
return o, h.Say(seat, EventRemoved, o)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Retained says `removed` for a version the forge's own retention deleted (design 51 *Retention*).
|
// 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 {
|
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})
|
return h.Say(seat, EventRemoved, Outcome{Name: name, Version: version, Kind: KindPackage, Digest: digest, Reason: ReasonRetention})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -112,9 +113,25 @@ type bed struct {
|
|||||||
findings map[string]bool
|
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 {
|
func newBed(numbered bool) *bed {
|
||||||
b := &bed{forge: &forge{files: map[string]map[string][]byte{}}, findings: map[string]bool{}}
|
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) },
|
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 },
|
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 }}
|
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) {
|
t.Run("the publish conformance cases on "+seat, func(t *testing.T) {
|
||||||
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
|
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
|
||||||
b := newBed(true)
|
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{
|
return publishconformance.Bed{
|
||||||
Hold: func(d string) {
|
Hold: func(d string) {
|
||||||
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
||||||
},
|
},
|
||||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
HoldWith: func(d, fp string) {
|
||||||
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest})
|
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
||||||
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
|
if fp != "" {
|
||||||
if len(b.said) > 0 {
|
_ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp})
|
||||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
|
||||||
}
|
}
|
||||||
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"))) },
|
Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) },
|
||||||
PublishWhole: func() publishconformance.Outcome {
|
PublishWhole: func() publishconformance.Outcome {
|
||||||
a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole))
|
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)
|
_, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole)
|
||||||
}
|
}
|
||||||
o := publishconformance.Outcome{Err: err}
|
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 {
|
if len(b.said) > 0 {
|
||||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
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.
|
// 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) {
|
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} {
|
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 {
|
!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)
|
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 = newBed(true)
|
||||||
b.forge.files[NpmSeat] = map[string][]byte{"x@0.1.0": []byte("first")}
|
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 {
|
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, said %+v", err, b.said)
|
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) {
|
t.Run("the builder removes a tagged version; one already gone is said removed all the same", func(t *testing.T) {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export const KEPT: readonly { readonly name: string; readonly readable?: boolean
|
|||||||
{ name: "calls" },
|
{ name: "calls" },
|
||||||
{ name: "bound", readable: true },
|
{ name: "bound", readable: true },
|
||||||
{ name: "findings", readable: true },
|
{ name: "findings", readable: true },
|
||||||
|
{ name: "fingerprints" },
|
||||||
{ name: "failed-steps" },
|
{ name: "failed-steps" },
|
||||||
{ name: "first-views" },
|
{ name: "first-views" },
|
||||||
{ name: "idle" },
|
{ name: "idle" },
|
||||||
|
|||||||
+12
-12
@@ -5,11 +5,11 @@
|
|||||||
// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the
|
// `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
|
// 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
|
// 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
|
// verb answers once, at the call's end: `call` and each member's outcome. A member whose base is 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
|
// whatever its repository (no entry, or an empty set, in the registrations' watched branches, or a set that does not
|
||||||
// addendum): judged against nothing of the module graph, merged plainly in the order named, answered and kept merged with
|
// hold the base), is the forge's business alone (H2 H-A-471 and its addendum, H-A-704): judged against nothing of the
|
||||||
// the note no delivery, and left out of merge-called, so it starts no delivery. A watched repository whose base is no
|
// module graph, merged plainly in the order named, answered and kept merged with the note no delivery, and left out of
|
||||||
// watched branch stays refused. A member is merged plainly only from a view of the watched branches read since the last
|
// 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
|
// registration-changed heard (the second addendum): while the view is unread or stale, every member is refused, never
|
||||||
// merged with the note.
|
// merged with the note.
|
||||||
|
|
||||||
@@ -57,14 +57,14 @@ export interface Member {
|
|||||||
state: MemberOutcome["state"];
|
state: MemberOutcome["state"];
|
||||||
commit?: string;
|
commit?: string;
|
||||||
why?: 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;
|
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;
|
plain?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The note of a member merged plainly: it starts no delivery (H-A-471). */
|
/** 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: the repository has no watched branch";
|
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). */
|
/** 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";
|
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`;
|
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);
|
const branches = watched.get(m.repository);
|
||||||
// A repository of no module: no build-input fingerprint and no required step judge it (H-A-471).
|
// A base no registration watches, whatever the repository: no build-input fingerprint and no required step judge it
|
||||||
if (!branches || branches.size === 0) {
|
// (H-A-471, H-A-704).
|
||||||
|
if (!branches || !branches.has(m.branch)) {
|
||||||
m.plain = true;
|
m.plain = true;
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
if (!branches.has(m.branch)) return `its base ${m.branch} is no watched branch`;
|
|
||||||
const failed = await deps.judge(m.head);
|
const failed = await deps.judge(m.head);
|
||||||
if (failed) {
|
if (failed) {
|
||||||
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
|
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"check-needs": [
|
"check-needs": [
|
||||||
"node-build-node"
|
"node-build-node"
|
||||||
],
|
],
|
||||||
|
"runs-as": "gitea",
|
||||||
"requires": [
|
"requires": [
|
||||||
"postgres-database",
|
"postgres-database",
|
||||||
"route",
|
"route",
|
||||||
@@ -39,6 +40,10 @@
|
|||||||
"admin": "${dir:state}/admin.secret"
|
"admin": "${dir:state}/admin.secret"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"own-secrets": {
|
||||||
|
"broker": "${dir:state}/broker"
|
||||||
|
},
|
||||||
|
"secrets-owner": "gitea",
|
||||||
"capabilities": [
|
"capabilities": [
|
||||||
"container-runtime"
|
"container-runtime"
|
||||||
],
|
],
|
||||||
@@ -271,6 +276,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"resources": [
|
"resources": [
|
||||||
|
{
|
||||||
|
"id": "account",
|
||||||
|
"type": "user",
|
||||||
|
"name": "gitea",
|
||||||
|
"shell": "/usr/bin/nologin",
|
||||||
|
"home": "/var/lib/gitea",
|
||||||
|
"groups": [
|
||||||
|
"docker"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "mesh-state",
|
"id": "mesh-state",
|
||||||
"type": "directory",
|
"type": "directory",
|
||||||
@@ -544,9 +559,7 @@
|
|||||||
"env": {
|
"env": {
|
||||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
|
||||||
"MESH_GITEA_PACKAGES_USER": "mesh-packages",
|
"MESH_GITEA_PACKAGES_USER": "mesh-packages",
|
||||||
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token",
|
|
||||||
"MESH_NPM_OWNER": "novox"
|
"MESH_NPM_OWNER": "novox"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -563,7 +576,6 @@
|
|||||||
"env": {
|
"env": {
|
||||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
|
||||||
"MESH_GITEA_PATCH_DIR": "${dir:forge-patches}"
|
"MESH_GITEA_PATCH_DIR": "${dir:forge-patches}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -662,6 +674,10 @@
|
|||||||
"name": "transfers",
|
"name": "transfers",
|
||||||
"max-mib": 8
|
"max-mib": 8
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "fingerprints",
|
||||||
|
"max-mib": 16
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "idle",
|
"name": "idle",
|
||||||
"key-ttl": true,
|
"key-ttl": true,
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
|
|
||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import { adminFromEnv, MintedToken } from "./token.js";
|
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). */
|
/** The account the package seats write as (internal/forgehttp PackagesAccount). */
|
||||||
export const PACKAGES_ACCOUNT = "mesh-packages";
|
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);
|
const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env);
|
||||||
return new MintedToken({
|
return new MintedToken({
|
||||||
...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log,
|
...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) => {
|
setUp: async (password) => {
|
||||||
const { GiteaAdmin } = await import("./client.js");
|
const { GiteaAdmin } = await import("./client.js");
|
||||||
await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"));
|
await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"));
|
||||||
|
|||||||
@@ -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.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.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");
|
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.
|
// 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("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);
|
await calls.put("00000000000000ee", { by: "lead@shanks", account: "x", at: "2026-11-20T03:03:00Z", members: [noted], said: false } as any);
|
||||||
said.length = 0;
|
said.length = 0;
|
||||||
|
|||||||
@@ -28,6 +28,11 @@ test("a note line is appended once, as the forge's user, in its own repository",
|
|||||||
{ added: true, lines: 2 });
|
{ added: true, lines: 2 });
|
||||||
const append = calls.find((c) => c.includes("append"))!;
|
const append = calls.find((c) => c.includes("append"))!;
|
||||||
assert.deepEqual(append.slice(0, 7), ["docker", "exec", "-u", "git", "gitea", "git", "--git-dir"]);
|
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.equal(append[7], "/data/git/repositories/novox/mesh-catalog.git");
|
||||||
assert.ok(append.includes("--ref=mesh-plan"));
|
assert.ok(append.includes("--ref=mesh-plan"));
|
||||||
assert.throws(() => noteArgs("gitea", "novox", "x; rm -rf /", sha, "mesh-plan"), /not a repository/);
|
assert.throws(() => noteArgs("gitea", "novox", "x; rm -rf /", sha, "mesh-plan"), /not a repository/);
|
||||||
|
|||||||
@@ -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 () => {
|
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");
|
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", "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: "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", () => {
|
test("index.ts says the announcement as the event `states` before the tools are served", () => {
|
||||||
|
|||||||
@@ -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: "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: "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: "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",
|
{ 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) },
|
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/ },
|
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
|
// **A base no registration watches is merged plainly** (design 47 H2 H-A-471 and its addendum, H-A-704): a member whose base
|
||||||
// no watched branch (no entry, or an empty set, in the registrations' watched branches) is judged against nothing of the
|
// 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
|
// 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
|
// out of merge-called; the watched members of the same call are judged and delivered as any call's.
|
||||||
// repository whose base is unwatched stays refused (the row above).
|
test("a member whose base is no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => {
|
||||||
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: its base is no watched branch";
|
||||||
const NOTE = "no delivery: the repository has no watched branch";
|
const rows: { name: string; base: string; watched: Map<string, Set<string>> }[] = [
|
||||||
const rows: { name: string; watched: Map<string, Set<string>> }[] = [
|
{ name: "no entry", base: "main", watched: new Map([["novox/app", new Set(["main"])]]) },
|
||||||
{ name: "no entry", 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<string>()]]) },
|
||||||
{ name: "an empty set", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set<string>()]]) },
|
{ 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) {
|
for (const r of rows) {
|
||||||
const pulls = open();
|
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 f = forge(pulls);
|
||||||
const judged: string[] = [];
|
const judged: string[] = [];
|
||||||
const said: any[] = [];
|
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[0].state, "judged", r.name);
|
||||||
assert.equal(got.members[1].state, "refused", 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.
|
// 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;
|
said.length = 0;
|
||||||
const landed = await call(f2, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } });
|
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`);
|
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);
|
[["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`);
|
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.
|
// 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;
|
said.length = 0;
|
||||||
const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched,
|
const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched,
|
||||||
say: async (_s: string, body: unknown) => { said.push(body); } });
|
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 f3 = forge(pulls());
|
||||||
const landed = await call(f3, hq, { watched: view });
|
const landed = await call(f3, hq, { watched: view });
|
||||||
assert.deepEqual([f3.merges, landed.members.map((m: any) => [m.state, m.note])],
|
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 () => {
|
test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => {
|
||||||
|
|||||||
@@ -10,12 +10,14 @@
|
|||||||
import { test, after } from "node:test";
|
import { test, after } from "node:test";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
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 { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
|
||||||
import { collectTools } from "@novox/mesh-sdk/tools";
|
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 { 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 { tokenLeaseTool } from "../dist/tools/tokenlease.js";
|
||||||
import { fakeBus } from "./fakebus.ts";
|
import { fakeBus } from "./fakebus.ts";
|
||||||
import { GiteaClient } from "../dist/client.js";
|
import { GiteaClient } from "../dist/client.js";
|
||||||
@@ -38,8 +40,10 @@ interface Forge {
|
|||||||
/** How each DELETE named its token: "id" or "name". */
|
/** How each DELETE named its token: "id" or "name". */
|
||||||
deletedBy: string[];
|
deletedBy: string[];
|
||||||
/** Plant a token by name, beside any other of the same name, as a raced mint would. */
|
/** 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<string, string[]>;
|
scopesOf: Map<string, string[]>;
|
||||||
|
/** The account the last mint was for; while it is the tools' account the admin's own list reads empty. */
|
||||||
|
mintedFor: string;
|
||||||
admins: Map<string, string>;
|
admins: Map<string, string>;
|
||||||
pullState: string;
|
pullState: string;
|
||||||
pullTitle: string;
|
pullTitle: string;
|
||||||
@@ -119,7 +123,7 @@ function fakeForge(): Promise<Forge> {
|
|||||||
const all = listed();
|
const all = listed();
|
||||||
res.setHeader("X-Total-Count", String(all.length));
|
res.setHeader("X-Total-Count", String(all.length));
|
||||||
return json(res, 200, all.slice((page - 1) * limit, page * limit)
|
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]) {
|
if (req.method === "DELETE" && tokens[2]) {
|
||||||
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
|
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
|
||||||
@@ -236,14 +240,18 @@ function fakeForge(): Promise<Forge> {
|
|||||||
url: `http://127.0.0.1:${port}`,
|
url: `http://127.0.0.1:${port}`,
|
||||||
get mints() { return forge.mints; },
|
get mints() { return forge.mints; },
|
||||||
get lastScopes() { return forge.lastScopes; },
|
get lastScopes() { return forge.lastScopes; },
|
||||||
|
get mintedFor() { return forge.mintedFor; },
|
||||||
|
set mintedFor(v: string) { forge.mintedFor = v; },
|
||||||
get pullState() { return forge.pullState; },
|
get pullState() { return forge.pullState; },
|
||||||
get pullTitle() { return forge.pullTitle; },
|
get pullTitle() { return forge.pullTitle; },
|
||||||
get branchDeleted() { return forge.branchDeleted; },
|
get branchDeleted() { return forge.branchDeleted; },
|
||||||
tokens: forge.tokens,
|
tokens: forge.tokens,
|
||||||
twins: forge.twins,
|
twins: forge.twins,
|
||||||
deletedBy: forge.deletedBy,
|
deletedBy: forge.deletedBy,
|
||||||
plant: (name: string) => {
|
plant: (name: string, value?: string, scopes?: string[]) => {
|
||||||
const sha1 = `planted-${++forge.nextId}`;
|
const sha1 = value ?? `planted-${++forge.nextId}`;
|
||||||
|
if (value) ++forge.nextId;
|
||||||
|
if (scopes) forge.scopesOf.set(sha1, scopes);
|
||||||
forge.ids.set(sha1, forge.nextId);
|
forge.ids.set(sha1, forge.nextId);
|
||||||
if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 });
|
if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 });
|
||||||
else forge.tokens.set(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" });
|
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
|
||||||
assert.equal(forge.branchDeleted, true);
|
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<string, string>): Promise<void> {
|
||||||
|
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<string, any>(); 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<string, readonly ListedToken[]>) =>
|
||||||
|
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"));
|
||||||
|
});
|
||||||
|
|||||||
@@ -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");
|
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_PACKAGES_USER, PACKAGES_ACCOUNT);
|
||||||
assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined);
|
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
|
// H-A-575: the vault alone hands a token: no artifact is given a token file.
|
||||||
// under its state directory, read when the vault refuses the caller's account; no other artifact is.
|
|
||||||
const files: Record<string, [string | undefined, string | undefined]> = {
|
|
||||||
forge: ["${dir:runtime-state}/token", undefined],
|
|
||||||
"package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"],
|
|
||||||
};
|
|
||||||
for (const a of manifest.build.artifacts) {
|
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`);
|
`${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(","));
|
assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(","));
|
||||||
|
|||||||
+83
-5
@@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state";
|
|||||||
import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js";
|
import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js";
|
||||||
import { keepMainRules } from "./mainrules.js";
|
import { keepMainRules } from "./mainrules.js";
|
||||||
import { durationMs } from "./taken.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). */
|
/** 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";
|
export const TOKEN_NAME = "mesh-tools";
|
||||||
@@ -283,8 +284,16 @@ export interface MintedTokenOptions {
|
|||||||
readonly leaseMs?: number;
|
readonly leaseMs?: number;
|
||||||
/** Who holds the lease when this process does: the node and the process. */
|
/** Who holds the lease when this process does: the node and the process. */
|
||||||
readonly holder?: string;
|
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;
|
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<readonly string[]>;
|
||||||
|
/** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */
|
||||||
|
readonly findings?: FindingSink;
|
||||||
readonly now?: () => Date;
|
readonly now?: () => Date;
|
||||||
readonly log?: (line: string) => void;
|
readonly log?: (line: string) => void;
|
||||||
readonly fetch?: typeof fetch;
|
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. */
|
/** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */
|
||||||
export class MintedToken implements TokenSource {
|
export class MintedToken implements TokenSource {
|
||||||
private held: VaultToken | null = null;
|
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<string> | null = null;
|
private inflight: Promise<string> | null = null;
|
||||||
private readonly scopes: readonly string[];
|
private readonly scopes: readonly string[];
|
||||||
private readonly ttlMs: number;
|
private readonly ttlMs: number;
|
||||||
@@ -330,7 +342,11 @@ export class MintedToken implements TokenSource {
|
|||||||
if (shared) return shared;
|
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)`);
|
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({
|
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.
|
// GiteaAdmin is loaded when first used: client.ts imports this file.
|
||||||
setUp: async (password) => {
|
setUp: async (password) => {
|
||||||
const { GiteaAdmin } = await import("./client.js");
|
const { GiteaAdmin } = await import("./client.js");
|
||||||
@@ -344,12 +360,12 @@ export class MintedToken implements TokenSource {
|
|||||||
private static readonly shared = new Map<string, MintedToken>();
|
private static readonly shared = new Map<string, MintedToken>();
|
||||||
|
|
||||||
/** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */
|
/** 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<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir"> {
|
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir" | "findings"> {
|
||||||
const log = (line: string) => console.log(`[gitea] ${line}`);
|
const log = (line: string) => console.log(`[gitea] ${line}`);
|
||||||
return {
|
return {
|
||||||
vault: sharedVault(), lease: sharedLease(),
|
vault: sharedVault(), lease: sharedLease(),
|
||||||
ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log),
|
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<unknown>("findings"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -364,10 +380,13 @@ export class MintedToken implements TokenSource {
|
|||||||
}
|
}
|
||||||
if (this.held === null) {
|
if (this.held === null) {
|
||||||
this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`);
|
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.
|
// 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}`));
|
if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`));
|
||||||
}
|
}
|
||||||
this.held = kept;
|
this.held = kept;
|
||||||
|
await this.endTokenFiles();
|
||||||
return kept.token;
|
return kept.token;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,7 +422,10 @@ export class MintedToken implements TokenSource {
|
|||||||
private mint(why: string, stale: string | null): Promise<string> {
|
private mint(why: string, stale: string | null): Promise<string> {
|
||||||
if (this.inflight === null) {
|
if (this.inflight === null) {
|
||||||
this.log(why);
|
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;
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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. */
|
/** The admin password, read now. */
|
||||||
private password(): string {
|
private password(): string {
|
||||||
try {
|
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}`);
|
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.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)}`);
|
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.
|
// Only now, with the new token kept, does the one it replaces go.
|
||||||
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;
|
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;
|
||||||
|
|||||||
@@ -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 `<file>.scopes` ("<sorted scopes, comma-joined>",
|
||||||
|
// then " for <account>" 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<readonly ListedToken[]>;
|
||||||
|
/** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */
|
||||||
|
revoke(account: string, id: number): Promise<string | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The module's state `findings`. */
|
||||||
|
export interface FindingSink {
|
||||||
|
put(key: string, value: unknown): Promise<unknown>;
|
||||||
|
delete(key: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tokens each account held when the lists were read. */
|
||||||
|
export type Lists = ReadonlyMap<string, readonly ListedToken[]>;
|
||||||
|
|
||||||
|
/** 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<Lists> {
|
||||||
|
const lists = new Map<string, readonly ListedToken[]>();
|
||||||
|
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<void> {
|
||||||
|
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}`); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ import (
|
|||||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||||
dforgekey "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/forgekey"
|
dforgekey "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/forgekey"
|
||||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||||
)
|
)
|
||||||
|
|
||||||
var commitOK = regexp.MustCompile(`^[0-9a-f]{40}$`)
|
var commitOK = regexp.MustCompile(`^[0-9a-f]{40}$`)
|
||||||
@@ -737,8 +738,33 @@ func cleanDir(dir string) string {
|
|||||||
return strings.Trim(filepath.ToSlash(filepath.Clean(dir)), "/")
|
return strings.Trim(filepath.ToSlash(filepath.Clean(dir)), "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// packagePaths are the named paths of the Go package artifacts of the manifest in the module directory dir of the tree,
|
||||||
|
// as the import step lists them (ModuleImports); none when the directory holds no manifest the catalogue reads.
|
||||||
|
func packagePaths(tree, dir string) []string {
|
||||||
|
raw, err := os.ReadFile(filepath.Join(tree, filepath.FromSlash(dir), "module.json"))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
manifest, err := catalogue.Decode(raw)
|
||||||
|
if err != nil || manifest.Build == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, a := range manifest.Build.Artifacts {
|
||||||
|
if a.Language == "go" && a.Kind == "package" {
|
||||||
|
for _, p := range a.Paths {
|
||||||
|
if p = strings.Trim(strings.TrimSpace(p), "./"); p != "" {
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// scopedDirs are the go.mod directories of all that a module directory dir chooses: dir itself and each directory its
|
// scopedDirs are the go.mod directories of all that a module directory dir chooses: dir itself and each directory its
|
||||||
// go.mod replaces with a local path, followed through their own replaces (design 47 G, A-447), in order. A directory
|
// go.mod replaces with a local path, followed through their own replaces (design 47 G, A-447), in order, and each package
|
||||||
|
// path of the ask holding a go.mod of its own (H-A-762). A directory
|
||||||
// the tree holds no go.mod for is left out. A directory holding no go.mod chooses every go.mod under it (A-447a), and one that
|
// the tree holds no go.mod for is left out. A directory holding no go.mod chooses every go.mod under it (A-447a), and one that
|
||||||
// chooses no Go module at all is an empty scope (H-A-371).
|
// chooses no Go module at all is an empty scope (H-A-371).
|
||||||
func scopedDirs(tree, dir string, paths, all []string) ([]string, error) {
|
func scopedDirs(tree, dir string, paths, all []string) ([]string, error) {
|
||||||
@@ -770,6 +796,17 @@ func scopedDirs(tree, dir string, paths, all []string) ([]string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Each path of the module's Go package artifacts that holds a Go module file of its own (the builder's builds, a state
|
||||||
|
// package beside a program) is a module the fetch gives its own module file, as the build and the import step's listing
|
||||||
|
// of that path run with it (design 47 H2, H-A-762, H-A-765, H-A-633): the paths the module's manifest names, as the
|
||||||
|
// import step lists them, whether or not the ask names paths, and those the ask names.
|
||||||
|
if have[dir] {
|
||||||
|
for _, p := range append(slices.Clone(paths), packagePaths(tree, dir)...) {
|
||||||
|
if d := path.Join(dir, filepath.ToSlash(p)); have[d] {
|
||||||
|
todo = append(todo, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for len(todo) > 0 {
|
for len(todo) > 0 {
|
||||||
d := todo[0]
|
d := todo[0]
|
||||||
todo = todo[1:]
|
todo = todo[1:]
|
||||||
|
|||||||
@@ -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)}}
|
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;
|
// 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.
|
// 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: 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)}}
|
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)}}
|
detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1), "max-mib": float64(8)}}
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"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.
|
// not answer as a transport fault, and a failure of the source (an unknown revision, a checksum) as none.
|
||||||
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
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
|
// 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) {
|
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -65,7 +67,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
|||||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||||
_ = json.Unmarshal(decl, &c)
|
_ = json.Unmarshal(decl, &c)
|
||||||
delay, err := steprun.AgainDelays(c.Default)
|
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)
|
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())
|
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
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -415,6 +415,9 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
|
|||||||
name, own, ownDir, gomods, version string
|
name, own, ownDir, gomods, version string
|
||||||
args map[string]any
|
args map[string]any
|
||||||
narrowed bool
|
narrowed bool
|
||||||
|
files map[string]string // laid over the checkout, after the rest
|
||||||
|
dirs int // the Go module directories the fetch takes (default 1), each with a modfile
|
||||||
|
listed string // a path directory whose import listing must run with its own modfile
|
||||||
}{
|
}{
|
||||||
{name: "whole tree", own: "git.novox.be/novox/mesh-delivery/nested/go", ownDir: "nested/go", gomods: "go.mod\n", version: zero,
|
{name: "whole tree", own: "git.novox.be/novox/mesh-delivery/nested/go", ownDir: "nested/go", gomods: "go.mod\n", version: zero,
|
||||||
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}},
|
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}},
|
||||||
@@ -430,6 +433,27 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
|
|||||||
ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod\n", version: "v0.1.3",
|
ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod\n", version: "v0.1.3",
|
||||||
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-contracts",
|
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-contracts",
|
||||||
"paths": []any{"go/clients/meshcatalogclient"}}, narrowed: true},
|
"paths": []any{"go/clients/meshcatalogclient"}}, narrowed: true},
|
||||||
|
// H-A-762, H-A-765 (with H-A-633), in the live form: the ask names no paths, the module's manifest names its package
|
||||||
|
// paths. mesh-delivery-builder's layout: a bundle and a package `builds` with a module file of its own that the
|
||||||
|
// module's file does not replace; the import step's listing of builds runs with its own modfile.
|
||||||
|
{name: "a package path with a module file of its own, named by the manifest alone", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk",
|
||||||
|
ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-builder/go.mod\nmodules/mesh-delivery-builder/builds/go.mod\n", version: zero,
|
||||||
|
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-builder"},
|
||||||
|
dirs: 2, listed: "modules/mesh-delivery-builder/builds", files: map[string]string{
|
||||||
|
"modules/mesh-delivery-builder/module.json": `{"module":"mesh-delivery-builder","build":{"artifacts":[{"name":"program","kind":"bundle","language":"go","from":"cmd/x","binary":"x"},{"name":"builds","kind":"package","language":"go","paths":["builds"]}]}}`}},
|
||||||
|
// mesh-grants' layout: package paths whose module files the module's file does not replace; one replaces a module of
|
||||||
|
// the same repository by a directory outside its own (builds), whose own requirement lies behind a further local
|
||||||
|
// replace (deep): each module file replaces the own-repository module the graph requires, a replaced module's
|
||||||
|
// requirements included.
|
||||||
|
{name: "a module replacing a package path whose requirements are of the same repository", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk",
|
||||||
|
ownDir: "modules/mesh-delivery-sdk", version: zero,
|
||||||
|
gomods: "modules/mesh-grants/go.mod\nmodules/mesh-grants/grantsstate/go.mod\nmodules/mesh-delivery-builder/builds/go.mod\nmodules/mesh-delivery-builder/builds/deep/go.mod\n",
|
||||||
|
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-grants"},
|
||||||
|
dirs: 4, listed: "modules/mesh-grants/grantsstate", files: map[string]string{
|
||||||
|
"modules/mesh-grants/module.json": `{"module":"mesh-grants","build":{"artifacts":[{"name":"grantsstate","kind":"package","language":"go","paths":["grantsstate"]}]}}`,
|
||||||
|
"modules/mesh-grants/grantsstate/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate\n\ngo 1.26\n\nrequire git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds " + zero +
|
||||||
|
"\n\nreplace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds => ../../mesh-delivery-builder/builds\n",
|
||||||
|
"modules/mesh-delivery-builder/builds/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds\n\ngo 1.26\n\nrequire fixture/deep v0.0.0\n\nreplace fixture/deep => ./deep\n"}},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
ownMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + tc.own + " " + tc.version + "\n)\n"
|
ownMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + tc.own + " " + tc.version + "\n)\n"
|
||||||
@@ -447,6 +471,9 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
|
|||||||
files["modules/mesh-delivery-contracts/module.json"] = `{"module":"mesh-delivery-contracts","build":{"artifacts":[{"name":"go-meshcatalogclient","kind":"package","language":"go","paths":["go/clients/meshcatalogclient"]}]}}`
|
files["modules/mesh-delivery-contracts/module.json"] = `{"module":"mesh-delivery-contracts","build":{"artifacts":[{"name":"go-meshcatalogclient","kind":"package","language":"go","paths":["go/clients/meshcatalogclient"]}]}}`
|
||||||
files["modules/mesh-delivery-view/go.mod"] = "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view\n\ngo 1.26\n"
|
files["modules/mesh-delivery-view/go.mod"] = "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view\n\ngo 1.26\n"
|
||||||
}
|
}
|
||||||
|
for f, body := range tc.files {
|
||||||
|
files[f] = body
|
||||||
|
}
|
||||||
for f, body := range files {
|
for f, body := range files {
|
||||||
os.MkdirAll(filepath.Join(tree, filepath.Dir(f)), 0o755)
|
os.MkdirAll(filepath.Join(tree, filepath.Dir(f)), 0o755)
|
||||||
os.WriteFile(filepath.Join(tree, f), []byte(body), 0o644)
|
os.WriteFile(filepath.Join(tree, f), []byte(body), 0o644)
|
||||||
@@ -469,8 +496,8 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
|
|||||||
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
||||||
}
|
}
|
||||||
modfiles, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "pins", "*", "go.mod"))
|
modfiles, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "pins", "*", "go.mod"))
|
||||||
if len(modfiles) != 1 {
|
if want := max(tc.dirs, 1); len(modfiles) != want {
|
||||||
t.Fatalf("modfiles = %v", modfiles)
|
t.Fatalf("modfiles = %v, want %d", modfiles, want)
|
||||||
}
|
}
|
||||||
root := filepath.Dir(filepath.Dir(filepath.Dir(modfiles[0])))
|
root := filepath.Dir(filepath.Dir(filepath.Dir(modfiles[0])))
|
||||||
where := filepath.Join(root, "tree", filepath.FromSlash(tc.ownDir))
|
where := filepath.Join(root, "tree", filepath.FromSlash(tc.ownDir))
|
||||||
@@ -479,19 +506,26 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
|
|||||||
t.Error("the narrowed tree holds a module the artifact does not require")
|
t.Error("the narrowed tree holds a module the artifact does not require")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
body, _ := os.ReadFile(modfiles[0])
|
for _, modfile := range modfiles {
|
||||||
if !strings.Contains(string(body), "replace "+tc.own+" => "+where+"\n") {
|
body, _ := os.ReadFile(modfile)
|
||||||
t.Errorf("the module of the repository was not replaced into the modfile by %s:\n%s", where, body)
|
if !strings.Contains(string(body), "replace "+tc.own+" => "+where+"\n") {
|
||||||
|
t.Errorf("the module of the repository was not replaced into %s by %s:\n%s", modfile, where, body)
|
||||||
|
}
|
||||||
|
if tc.dirs <= 1 && strings.Count(string(body), "replace ") != 1 {
|
||||||
|
t.Errorf("the modfile replaces more than the one other module (its own directory again?):\n%s", body)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if strings.Count(string(body), "replace ") != 1 {
|
if tc.listed != "" {
|
||||||
t.Errorf("the modfile replaces more than the one other module (its own directory again?):\n%s", body)
|
if env := strings.Join(h.m.buildEnv(filepath.Join(root, "tree", filepath.FromSlash(tc.listed))), " "); !strings.Contains(env, "-modfile=") {
|
||||||
|
t.Errorf("the listing of %s runs without its own modfile: %s", tc.listed, env)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if h.ran(" mod download -json ") || h.ran("ls-remote") {
|
if h.ran(" mod download -json ") || h.ran("ls-remote") {
|
||||||
t.Error("a module of the checked repository was asked of Go or looked for among the pull request heads")
|
t.Error("a module of the checked repository was asked of Go or looked for among the pull request heads")
|
||||||
}
|
}
|
||||||
var res FetchResult
|
var res FetchResult
|
||||||
json.Unmarshal(st.Result, &res)
|
json.Unmarshal(st.Result, &res)
|
||||||
if len(res.Packages) != 1 || res.Packages[0].Package != tc.own || res.Packages[0].Built != "the fetched tree" || res.Packages[0].Named != tc.version {
|
if len(res.Packages) != max(tc.dirs, 1) || res.Packages[0].Package != tc.own || res.Packages[0].Built != "the fetched tree" || res.Packages[0].Named != tc.version {
|
||||||
t.Errorf("the taken versions = %+v, want %s named %s, built from the fetched tree", res.Packages, tc.own, tc.version)
|
t.Errorf("the taken versions = %+v, want %s named %s, built from the fetched tree", res.Packages, tc.own, tc.version)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -89,19 +89,26 @@ func readValues(keys []string, get func(string) (json.RawMessage, error)) ([]jso
|
|||||||
return out, fail
|
return out, fail
|
||||||
}
|
}
|
||||||
|
|
||||||
// stepKey is the key of a step of this node: the id alone, or the whole key <node>.<id> as a step tool answered it.
|
// stepKey is the key of a step of this node: the id alone, or a whole key as a step tool answered it, `<node>.<id>` or an
|
||||||
|
// ask's `<asker>.<node>.<id>` (design 47 G §481); the node of the key is this module's.
|
||||||
func (m *Module) stepKey(id string) (string, error) {
|
func (m *Module) stepKey(id string) (string, error) {
|
||||||
id = strings.TrimSpace(id)
|
id = strings.TrimSpace(id)
|
||||||
if node, rest, ok := strings.Cut(id, "."); ok {
|
if !strings.Contains(id, ".") {
|
||||||
if node != m.Node {
|
return sdkstep.StepKey(m.Node, id)
|
||||||
return "", fmt.Errorf("the step %q is of node %q, this module runs on %q", id, node, m.Node)
|
|
||||||
}
|
|
||||||
id = rest
|
|
||||||
}
|
}
|
||||||
return sdkstep.StepKey(m.Node, id)
|
_, node, _, err := sdkstep.ParseStepKey(id)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if node != m.Node {
|
||||||
|
return "", fmt.Errorf("the step %q is of node %q, this module runs on %q", id, node, m.Node)
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadStep is the stored value of this node's step id (state, reason, result).
|
// ReadStep is the stored value of this node's step id (state, reason, result). A step is stored under `<node>.<id>`, or
|
||||||
|
// under its asker for an ask (`<asker>.<node>.<id>`, design 47 G §481): when the key as given holds none, the keys of the
|
||||||
|
// state are searched for this node's step of that id under either form, as the verb output's read does (EndedHere).
|
||||||
func (m *Module) ReadStep(id string) (sdkstep.Step, error) {
|
func (m *Module) ReadStep(id string) (sdkstep.Step, error) {
|
||||||
key, err := m.stepKey(id)
|
key, err := m.stepKey(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -114,6 +121,24 @@ func (m *Module) ReadStep(id string) (sdkstep.Step, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return sdkstep.Step{}, err
|
return sdkstep.Step{}, err
|
||||||
}
|
}
|
||||||
|
if len(raw) == 0 && m.ReadSteps.Keys != nil {
|
||||||
|
_, _, want, _ := sdkstep.ParseStepKey(key)
|
||||||
|
keys, err := m.ReadSteps.Keys()
|
||||||
|
if err != nil {
|
||||||
|
return sdkstep.Step{}, err
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
if _, node, id, err := sdkstep.ParseStepKey(k); err != nil || node != m.Node || id != want {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if raw, err = m.ReadSteps.Get(k); err != nil {
|
||||||
|
return sdkstep.Step{}, err
|
||||||
|
}
|
||||||
|
if len(raw) > 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if len(raw) == 0 {
|
if len(raw) == 0 {
|
||||||
return sdkstep.Step{}, fmt.Errorf("no step %s in the steps state", key)
|
return sdkstep.Step{}, fmt.Errorf("no step %s in the steps state", key)
|
||||||
}
|
}
|
||||||
@@ -229,9 +254,10 @@ func (m *Module) ReadTools() []stdio.Tool {
|
|||||||
{Name: StepReadTool,
|
{Name: StepReadTool,
|
||||||
Description: "What one step of this machine ended with, as stored in the module's steps state: its tool, state " +
|
Description: "What one step of this machine ended with, as stored in the module's steps state: its tool, state " +
|
||||||
"(running, passed, failed, refused), when it started and ended, why it failed or was refused, and its result " +
|
"(running, passed, failed, refused), when it started and ended, why it failed or was refused, and its result " +
|
||||||
"(a fetch's workspace id is there). id is the step id a step tool answered, or the whole key <node>.<id>. Read-only.",
|
"(a fetch's workspace id is there). id is the step id a step tool answered, or the whole key: <node>.<id>, or <asker>.<node>.<id> " +
|
||||||
|
"for an ask's step, the asker the asking seat's name. Read-only.",
|
||||||
Input: map[string]any{"type": "object", "required": []string{"id"}, "properties": map[string]any{
|
Input: map[string]any{"type": "object", "required": []string{"id"}, "properties": map[string]any{
|
||||||
"id": map[string]any{"type": "string", "description": "the step id, or the key <node>.<id>"}}},
|
"id": map[string]any{"type": "string", "description": "the step id, or the key <node>.<id> or <asker>.<node>.<id>"}}},
|
||||||
Run: func(args map[string]any) (any, error) {
|
Run: func(args map[string]any) (any, error) {
|
||||||
id, _ := args["id"].(string)
|
id, _ := args["id"].(string)
|
||||||
return m.ReadStep(id)
|
return m.ReadStep(id)
|
||||||
|
|||||||
@@ -74,6 +74,16 @@ func TestStepToolAnswersTheStoredStep(t *testing.T) {
|
|||||||
t.Errorf("id %s: step = %+v", id, st)
|
t.Errorf("id %s: step = %+v", id, st)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// An ask's step is stored under its asker (design 47 G §481, issue 1984 note 52): found by its id, or by its whole key.
|
||||||
|
asked, _ := sdkstep.AskStepKey("mesh-wants", "ace", "mwwmppk5788534")
|
||||||
|
b, _ := sdkstep.EncodeStep(sdkstep.Step{ID: "mwwmppk5788534", Tool: "build_go_test", Node: "ace", State: sdkstep.StepPassed, Started: t0, Ended: t0.Add(time.Second)})
|
||||||
|
steps[asked] = b
|
||||||
|
for _, id := range []string{"mwwmppk5788534", "ace.mwwmppk5788534", asked} {
|
||||||
|
out, err := tool(t, m, StepReadTool)(map[string]any{"id": id})
|
||||||
|
if err != nil || out.(sdkstep.Step).ID != "mwwmppk5788534" {
|
||||||
|
t.Errorf("the ask's step by %q = %v, %v", id, out, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
out, _ := tool(t, m, StepReadTool)(map[string]any{"id": "abc2"})
|
out, _ := tool(t, m, StepReadTool)(map[string]any{"id": "abc2"})
|
||||||
if st := out.(sdkstep.Step); st.State != sdkstep.StepRefused || st.Reason != "go cannot be run" {
|
if st := out.(sdkstep.Step); st.State != sdkstep.StepRefused || st.Reason != "go cannot be run" {
|
||||||
t.Errorf("refused step = %+v", st)
|
t.Errorf("refused step = %+v", st)
|
||||||
|
|||||||
@@ -81,10 +81,10 @@
|
|||||||
},
|
},
|
||||||
"again-delays": {
|
"again-delays": {
|
||||||
"type": "string",
|
"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,
|
"trusted": false,
|
||||||
"runtime": true,
|
"runtime": true,
|
||||||
"default": "15s,60s"
|
"default": "15s,90s"
|
||||||
},
|
},
|
||||||
"prune-mark": {
|
"prune-mark": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"ttl-seconds": 172800,
|
"ttl-seconds": 172800,
|
||||||
"objects-max-mib": 256,
|
"objects-max-mib": 256,
|
||||||
"max-mib": 128
|
"max-mib": 64
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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
|
// --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
|
// 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).
|
// 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 != "" {
|
if art.Target != "" {
|
||||||
argv = append(argv, "--target", art.Target)
|
argv = append(argv, "--target", art.Target)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ func TestBuildRunsBuildahRootlessAndAnswersTheDigest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo")
|
dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo")
|
||||||
for _, want := range []string{
|
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",
|
"--file " + dir + "/Dockerfile", "--target final",
|
||||||
"--build-arg DEMO_BASE=docker.io/library/busybox@sha256:0000000000000000000000000000000000000000000000000000000000000001",
|
"--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)
|
m, f, states = setup(t, same)
|
||||||
runBuild(t, m, states, nil)
|
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)
|
t.Fatalf("a build with no version: %+v", bud)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"os/user"
|
"os/user"
|
||||||
@@ -20,6 +21,7 @@ import (
|
|||||||
|
|
||||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
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"
|
||||||
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance"
|
||||||
)
|
)
|
||||||
|
|
||||||
func needTools(t *testing.T, what string, tools ...string) {
|
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.
|
// needBase skips unless the build node can pull the small base the isolation Dockerfiles run in.
|
||||||
func needBase(t *testing.T, m *Module) string {
|
func needBase(t *testing.T, m *Module) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|||||||
@@ -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.
|
// 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) {
|
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
|
// 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) {
|
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -51,7 +51,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
|||||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||||
_ = json.Unmarshal(decl, &c)
|
_ = json.Unmarshal(decl, &c)
|
||||||
delay, err := steprun.AgainDelays(c.Default)
|
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)
|
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -46,10 +46,10 @@
|
|||||||
},
|
},
|
||||||
"again-delays": {
|
"again-delays": {
|
||||||
"type": "string",
|
"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,
|
"trusted": false,
|
||||||
"runtime": true,
|
"runtime": true,
|
||||||
"default": "15s,60s"
|
"default": "15s,90s"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"tools": [
|
"tools": [
|
||||||
|
|||||||
@@ -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.
|
// not answer as a transport fault, and a failure of the source (a package the registry lacks) as none.
|
||||||
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
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
|
// 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) {
|
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -62,7 +62,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
|||||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||||
_ = json.Unmarshal(decl, &c)
|
_ = json.Unmarshal(decl, &c)
|
||||||
delay, err := steprun.AgainDelays(c.Default)
|
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)
|
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())
|
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
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -50,10 +50,10 @@
|
|||||||
},
|
},
|
||||||
"again-delays": {
|
"again-delays": {
|
||||||
"type": "string",
|
"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,
|
"trusted": false,
|
||||||
"runtime": true,
|
"runtime": true,
|
||||||
"default": "15s,60s"
|
"default": "15s,90s"
|
||||||
},
|
},
|
||||||
"prune-mark": {
|
"prune-mark": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
|
|||||||
@@ -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
|
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 {
|
func (r runtimeStore) Put(state, key string, value any) error {
|
||||||
if r.own != nil && ownStates[state] {
|
if r.own != nil && ownStates[state] {
|
||||||
return r.own.write(state, key, value)
|
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{},
|
c := &Config{Store: runtimeStore{own: own}, Logf: logf, Asks: runtimeAsks{},
|
||||||
Delivery: toolDelivery{ask: stdio.Ask}, Vault: toolVault{ask: stdio.Ask, recorder: recorder}}
|
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.
|
// 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)
|
rows, err := c.Renames(strings.TrimSpace(m), true)
|
||||||
return map[string]any{"renames": seatRenames(rows)}, err
|
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,
|
Name: Seat + "." + Verb,
|
||||||
Description: "Set, clear, list or read the history of config values (novox/hq ADR 0348). A value is set at " +
|
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 " +
|
"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)
|
call.Caller = stdio.CallerOf(args)
|
||||||
return c.Do(call)
|
return c.Do(call)
|
||||||
},
|
},
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// callOf reads a call's arguments strictly: an argument it does not know is refused, not ignored.
|
// callOf reads a call's arguments strictly: an argument it does not know is refused, not ignored.
|
||||||
|
|||||||
@@ -95,22 +95,15 @@ func (o *ownerViews) read(state string) (*views.Follower, bool) {
|
|||||||
return f, ok
|
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.
|
// get is one key of a followed state.
|
||||||
func (o *ownerViews) get(state, key string) (*Entry, bool, error) {
|
func (o *ownerViews) get(state, key string) (*Entry, bool, error) {
|
||||||
f, ok := o.read(state)
|
f, ok := o.read(state)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
select {
|
// A first view not answered yet is the fault `away`, naming the view's owner verb (design 47 H2 H-A-708 (2)).
|
||||||
case <-f.Ready():
|
if err := f.Unread(); err != nil {
|
||||||
default:
|
return nil, true, err
|
||||||
return nil, true, errUnanswered(f)
|
|
||||||
}
|
}
|
||||||
v, held := f.Get(key)
|
v, held := f.Get(key)
|
||||||
if !held {
|
if !held {
|
||||||
@@ -125,10 +118,8 @@ func (o *ownerViews) keys(state string) ([]string, bool, error) {
|
|||||||
if !ok {
|
if !ok {
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
select {
|
if err := f.Unread(); err != nil {
|
||||||
case <-f.Ready():
|
return nil, true, err
|
||||||
default:
|
|
||||||
return nil, true, errUnanswered(f)
|
|
||||||
}
|
}
|
||||||
var out []string
|
var out []string
|
||||||
for k := range f.Values() {
|
for k := range f.Values() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -33,7 +34,10 @@ func TestAFollowedStateIsReadFromItsOwnersFirstViewAndEvents(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var changed atomic.Int32
|
var changed atomic.Int32
|
||||||
o := newOwnerViews(ask, func() { changed.Add(1) }, nopFindings{})
|
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)
|
t.Fatalf("before the first view: followed %v, %v", followed, err)
|
||||||
}
|
}
|
||||||
if !o.reader.Follows("mesh-delivery-assigner.wants") {
|
if !o.reader.Follows("mesh-delivery-assigner.wants") {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"sort"
|
||||||
|
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
)
|
)
|
||||||
@@ -36,6 +37,8 @@ func newOwnCopy() *ownCopy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (o *ownCopy) get(state, key string) (*Entry, error) {
|
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)
|
raw, ok, err := o.copy.Get(state, key)
|
||||||
if err != nil || !ok {
|
if err != nil || !ok {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -43,7 +46,34 @@ func (o *ownCopy) get(state, key string) (*Entry, error) {
|
|||||||
return &Entry{Key: key, Value: raw}, nil
|
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.
|
// 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 {
|
func (o *ownCopy) write(state, key string, value any) error {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
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"
|
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
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.
|
// 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])
|
n := len(b.held[ValuesState])
|
||||||
own := b.ownCopy()
|
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++ {
|
for pass := 0; pass < 3; pass++ {
|
||||||
keys, err := own.keys(ValuesState)
|
keys, err := own.keys(ValuesState)
|
||||||
if err != nil || len(keys) != n {
|
if err != nil || len(keys) != n {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
|
|
||||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
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"
|
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"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"github.com/nats-io/nats-server/v2/server"
|
"github.com/nats-io/nats-server/v2/server"
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
@@ -134,6 +135,43 @@ type runtime struct {
|
|||||||
operatorCancels []string
|
operatorCancels []string
|
||||||
// owedSaid are the subjects of the seat events owed the gate said, in order (W11.17).
|
// owedSaid are the subjects of the seat events owed the gate said, in order (W11.17).
|
||||||
owedSaid []string
|
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 {
|
type askedOfMesh struct {
|
||||||
@@ -154,19 +192,28 @@ func (b *testBus) start(t *testing.T) *runtime {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
cmd.Stderr = testLog{t}
|
logs := &testLog{t: t}
|
||||||
|
cmd.Stderr = logs
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
t.Fatal(err)
|
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)
|
go r.read(out)
|
||||||
t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() })
|
t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() })
|
||||||
return r
|
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
|
defer func() { _ = recover() }() // the bundle may speak after the test ended
|
||||||
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
|
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
|
// 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.operatorAsks = append(r.operatorAsks, a)
|
||||||
r.mu.Unlock()
|
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.") {
|
if strings.HasPrefix(p.Subject, "mesh.seat.mesh-delivery.event.owed.") {
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
r.owedSaid = append(r.owedSaid, p.Subject)
|
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)
|
return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key)
|
||||||
}
|
}
|
||||||
switch m.Method {
|
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.
|
// The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory.
|
||||||
r.b.mu.Lock()
|
r.b.mu.Lock()
|
||||||
defer r.b.mu.Unlock()
|
defer r.b.mu.Unlock()
|
||||||
if r.b.ledger == nil {
|
if r.b.ledger == nil {
|
||||||
r.b.ledger = newLedgerFake(r.t)
|
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 {
|
if m.Method == buscalls.LedgerQuery {
|
||||||
var in buscalls.QueryRequest
|
var in buscalls.QueryRequest
|
||||||
if err := json.Unmarshal(m.Params, &in); err != nil {
|
if err := json.Unmarshal(m.Params, &in); err != nil {
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ var stepFamilies = []stepFamily{
|
|||||||
// runner's pipeline-started, pipeline-ended, wait-held and wait-ended on <branch>.<source>, the assigner's wanted on
|
// runner's pipeline-started, pipeline-ended, wait-held and wait-ended on <branch>.<source>, the assigner's wanted on
|
||||||
// <node>.<module> and pipeline-wanted on <branch>.<source>, and the node-engine seat's running on <node>.<module>.
|
// <node>.<module> and pipeline-wanted on <branch>.<source>, and the node-engine seat's running on <node>.<module>.
|
||||||
seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted),
|
seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted),
|
||||||
|
seatFamily(runner.EventMoverAdded, 2, false, decodeMoverAdded),
|
||||||
seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded),
|
seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded),
|
||||||
seatFamily(runner.EventWaitHeld, 2, false, decodeWait),
|
seatFamily(runner.EventWaitHeld, 2, false, decodeWait),
|
||||||
seatFamily(runner.EventWaitEnded, 2, false, decodeWait),
|
seatFamily(runner.EventWaitEnded, 2, false, decodeWait),
|
||||||
@@ -247,9 +248,11 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string {
|
|||||||
return ""
|
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
|
// 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 {
|
func (c *StepConsumer) apply(o StepOutcome, event string) error {
|
||||||
records, err := c.Records.Kept()
|
records, err := c.Records.Kept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -258,12 +261,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error {
|
|||||||
for _, r := range records {
|
for _, r := range records {
|
||||||
_, fromAway := r.Away[o.Node]
|
_, fromAway := r.Away[o.Node]
|
||||||
fromAway = fromAway && 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
|
continue
|
||||||
}
|
}
|
||||||
ro := RecordOutcome{Module: o.Module, Fingerprint: o.Fingerprint, Node: o.Node, Step: o.Step, Outcome: o.Outcome,
|
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}
|
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
|
return err
|
||||||
}
|
}
|
||||||
if fromAway {
|
if fromAway {
|
||||||
@@ -271,6 +276,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error {
|
|||||||
return err
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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).
|
// 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) {
|
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]{
|
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
|
// 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)
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"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/clients/meshhandactsclient"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
)
|
)
|
||||||
@@ -61,9 +63,16 @@ func main() {
|
|||||||
}
|
}
|
||||||
h.init()
|
h.init()
|
||||||
h.SaySeat = stdio.SeatPublish
|
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}
|
Class: seatCatalog{ask: stdio.Ask}.Class}
|
||||||
h.Records.Changed = h.recordChanged
|
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.Forge = seatGit{ask: stdio.Ask}
|
||||||
h.Catalog = seatCatalog{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,
|
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.
|
// 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) {
|
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
|
<-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()
|
go h.Work()
|
||||||
for _, pattern := range followed {
|
for _, pattern := range followed {
|
||||||
pattern := pattern
|
pattern := pattern
|
||||||
@@ -154,7 +177,13 @@ func take(h *Holder, e stdio.Envelope) error {
|
|||||||
h.applying.Lock()
|
h.applying.Lock()
|
||||||
defer h.applying.Unlock()
|
defer h.applying.Unlock()
|
||||||
if h.Consumer != nil && h.Consumer.Takes(e.Key) {
|
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) {
|
if stdio.TopicMatches(headMovedEvent, e.Key) {
|
||||||
return h.HeadMoved(e)
|
return h.HeadMoved(e)
|
||||||
|
|||||||
@@ -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
|
// 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.
|
// 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)
|
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 {
|
for _, f := range stepFamilies {
|
||||||
|
|||||||
@@ -111,6 +111,35 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) {
|
|||||||
want.Round(time.Minute))
|
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
|
// 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
|
// 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.
|
// 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,
|
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"})
|
"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, "") })
|
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.
|
// The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing.
|
||||||
seeded := strings.Repeat("5", 40)
|
seeded := strings.Repeat("5", 40)
|
||||||
|
|||||||
@@ -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).
|
// The operations of a mover's entry; the manifest's type mover declares exactly these (record_test.go).
|
||||||
const (
|
const (
|
||||||
OpMover = "mover" // set-fields: its record's key, its module, its class, its pipeline and its version
|
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.
|
// 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).
|
// OpMovers is the head entry's count of its movers (set-fields movers).
|
||||||
const OpMovers = "movers"
|
const OpMovers = "movers"
|
||||||
@@ -59,6 +60,8 @@ type Mover struct {
|
|||||||
Class string `json:"class,omitempty"`
|
Class string `json:"class,omitempty"`
|
||||||
Entries map[string]RecordEntry `json:"entries,omitempty"`
|
Entries map[string]RecordEntry `json:"entries,omitempty"`
|
||||||
Outcomes map[string]RecordOutcome `json:"outcomes,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.
|
// Running are the machines the mover runs healthy on, each with when it was first said.
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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"
|
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)
|
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"))
|
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): `<seat>.running.<node>.<module>`.
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ type RecordAct struct {
|
|||||||
Words string `json:"words,omitempty"`
|
Words string `json:"words,omitempty"`
|
||||||
At time.Time `json:"at"`
|
At time.Time `json:"at"`
|
||||||
Owed seat.Owed `json:"owed"`
|
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
|
// 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.
|
// 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/<branch.source.act.id>`, escaped as a name.
|
// ActInstance is the entry of a record's act: `act/<branch.source.act.id>`, escaped as a name.
|
||||||
func ActInstance(milestone, id string) (string, error) {
|
func ActInstance(milestone, id string) (string, error) {
|
||||||
|
|||||||
@@ -64,10 +64,6 @@ var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpMovers, OpPhases, Op
|
|||||||
// HeldOperations are the month's list's operations.
|
// HeldOperations are the month's list's operations.
|
||||||
var HeldOperations = []string{OpHold, OpDrop}
|
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.
|
// Record is a delivery record's state, as apply derives it from its operations.
|
||||||
type Record struct {
|
type Record struct {
|
||||||
// Instance is the record's path in the ledger; not in the state.
|
// 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)).
|
// 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"`
|
Acts map[string]RecordAct `json:"acts,omitempty"`
|
||||||
Ended *RecordEnded `json:"ended,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 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"`
|
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
|
// MoverCount is the count of its movers, each with an entry of its own (design 47 H2 §809); Entries and Outcomes above
|
||||||
@@ -197,6 +198,9 @@ type RecordEntry struct {
|
|||||||
Module string `json:"module"`
|
Module string `json:"module"`
|
||||||
Fingerprint string `json:"fingerprint"`
|
Fingerprint string `json:"fingerprint"`
|
||||||
Node string `json:"node,omitempty"`
|
Node string `json:"node,omitempty"`
|
||||||
|
// WantRevision is the revision of the want's key the entry was written from; a want at a lower one for the same node
|
||||||
|
// and module changes nothing (design 47 H §832 5.).
|
||||||
|
WantRevision int64 `json:"want-revision,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EntryKey is the key of an entry: its module, its fingerprint and its node.
|
// EntryKey is the key of an entry: its module, its fingerprint and its node.
|
||||||
@@ -223,16 +227,6 @@ type RecordEnded struct {
|
|||||||
Away []NodeAway `json:"away,omitempty"`
|
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).
|
// 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_-]+$`)
|
var segmentRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||||
|
|
||||||
@@ -270,18 +264,27 @@ func RecordInstance(milestone string) (string, error) {
|
|||||||
return inst, nil
|
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.
|
// RecordLedger is the gate's ledger: an operation applied to one instance, and one instance's state read.
|
||||||
type RecordLedger interface {
|
type RecordLedger interface {
|
||||||
Apply(instance, operation string, body any) (uint64, error)
|
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 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)
|
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 removes a record with its operations and its snapshot through the tool runner's ledger removal.
|
||||||
Remove(instance string) error
|
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 is the instances a declared index names under key (`>` for the rest).
|
||||||
Query(index, key string) ([]string, error)
|
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
|
// sdkLedger is the gate's ledger through the runtime: the tool runner's ledger calls, on the gate's own ledger only
|
||||||
@@ -331,6 +334,32 @@ func (sdkLedger) Remove(instance string) error {
|
|||||||
return nil
|
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) {
|
func (sdkLedger) Query(index, key string) ([]string, error) {
|
||||||
out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key})
|
out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -347,6 +376,24 @@ func (sdkLedger) Query(index, key string) ([]string, error) {
|
|||||||
return insts, nil
|
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) {
|
func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) {
|
||||||
out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance})
|
out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -366,8 +413,6 @@ func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) {
|
|||||||
type Records struct {
|
type Records struct {
|
||||||
Ledger RecordLedger
|
Ledger RecordLedger
|
||||||
Now func() time.Time
|
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,
|
// 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.
|
// full and room (recordfill.go); nil says none.
|
||||||
Say SeatSay
|
Say SeatSay
|
||||||
@@ -382,12 +427,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
|
// 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.
|
// 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)
|
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
|
// held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read,
|
||||||
// gate is their one writer.
|
// then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in
|
||||||
mu sync.Mutex
|
// gone so an event for it is said and changes nothing (design 47 H2 H-A-634 (2), (5)).
|
||||||
held map[string]*Record
|
mu sync.Mutex
|
||||||
loaded bool
|
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
|
// Current is every record kept and not ended, oldest first: read from the ledger at the first call, then as the gate
|
||||||
@@ -423,41 +481,134 @@ func (rs *Records) Kept() ([]*Record, error) {
|
|||||||
return out, nil
|
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/<yyyy-mm>` 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 {
|
func (rs *Records) load() error {
|
||||||
rs.mu.Lock()
|
rs.mu.Lock()
|
||||||
loaded := rs.loaded
|
if rs.loaded {
|
||||||
rs.mu.Unlock()
|
rs.mu.Unlock()
|
||||||
if loaded {
|
|
||||||
return nil
|
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 {
|
if err != nil {
|
||||||
|
rs.mu.Lock()
|
||||||
|
if rs.pending == nil {
|
||||||
|
rs.pending = map[string]struct{}{}
|
||||||
|
}
|
||||||
|
rs.pending[instance] = struct{}{}
|
||||||
|
rs.mu.Unlock()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
rs.mu.Lock()
|
rs.mu.Lock()
|
||||||
defer rs.mu.Unlock()
|
defer rs.mu.Unlock()
|
||||||
if !rs.loaded {
|
delete(rs.pending, instance)
|
||||||
rs.held = map[string]*Record{}
|
if r == nil {
|
||||||
for _, r := range list {
|
return nil
|
||||||
rs.held[r.Instance] = r
|
|
||||||
}
|
|
||||||
rs.loaded = true
|
|
||||||
}
|
}
|
||||||
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rs *Records) keep(r *Record) {
|
// removeMonthList removes a month list the earlier gate wrote, through the ledger's removal, which ends the instance whole
|
||||||
rs.mu.Lock()
|
// (design 47 H2 H-A-721): its operations, its snapshot, its key and its index keys.
|
||||||
defer rs.mu.Unlock()
|
func (rs *Records) removeMonthList(instance string, state json.RawMessage) error {
|
||||||
if rs.loaded {
|
if string(state) == "null" || len(state) == 0 {
|
||||||
rs.held[r.Instance] = r
|
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()
|
rs.mu.Lock()
|
||||||
defer rs.mu.Unlock()
|
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 {
|
func (rs *Records) now() time.Time {
|
||||||
@@ -467,16 +618,6 @@ func (rs *Records) now() time.Time {
|
|||||||
return rs.Now().UTC()
|
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).
|
// 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) {
|
func (rs *Records) Read(instance string) (*Record, error) {
|
||||||
raw, seq, err := rs.Ledger.Get(instance)
|
raw, seq, err := rs.Ledger.Get(instance)
|
||||||
@@ -516,8 +657,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
|
// 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
|
// again opens no second record and says nothing new). Opened says it was opened now. An open writes no month list and
|
||||||
// their retention first (the retention needs no timer: records open as deliveries do).
|
// 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) {
|
func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
|
||||||
if o.Branch == "" || o.Source < 1 || o.Call == "" {
|
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)
|
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 +684,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
|
|||||||
return r, false, nil
|
return r, false, nil
|
||||||
}
|
}
|
||||||
now := rs.now()
|
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)
|
before, read, err := rs.refuseFull(milestone, inst)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
@@ -559,9 +697,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 {
|
if _, err := rs.write(&Record{Milestone: milestone}, inst, OpOpen, body, body); err != nil {
|
||||||
return nil, false, err
|
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 {
|
if read {
|
||||||
rs.sayFilling(inst, before)
|
rs.sayFilling(inst, before)
|
||||||
}
|
}
|
||||||
@@ -571,7 +706,7 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
|
|||||||
if err := rs.SetTrace(r, o.Trace); err != nil {
|
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)
|
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)
|
rs.sayOpened(r)
|
||||||
return r, true, nil
|
return r, true, nil
|
||||||
}
|
}
|
||||||
@@ -585,6 +720,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
|
// 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.
|
// ledger; nil when none is kept.
|
||||||
func (rs *Records) ByMilestone(milestone string) (*Record, error) {
|
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)
|
inst, err := RecordInstance(milestone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -597,7 +741,14 @@ func (rs *Records) ByMilestone(milestone string) (*Record, error) {
|
|||||||
}
|
}
|
||||||
r, err := rs.Read(inst)
|
r, err := rs.Read(inst)
|
||||||
if r != nil {
|
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
|
return r, err
|
||||||
}
|
}
|
||||||
@@ -612,100 +763,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.
|
// SetGroup writes the record's group state, unless it holds that state already.
|
||||||
func (rs *Records) SetGroup(r *Record, g RecordGroup) error {
|
func (rs *Records) SetGroup(r *Record, g RecordGroup) error {
|
||||||
if r.Group != nil && reflect.DeepEqual(*r.Group, g) {
|
if r.Group != nil && reflect.DeepEqual(*r.Group, g) {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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/clients/meshhandactsclient"
|
||||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
"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"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||||
@@ -34,6 +36,53 @@ type ledgerFake struct {
|
|||||||
failOn string
|
failOn string
|
||||||
// fill is what Fill answers; nil, the ledger says no fill.
|
// fill is what Fill answers; nil, the ledger says no fill.
|
||||||
fill *buscalls.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 `<type>/>`) 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) {
|
func (f *ledgerFake) Fill() (buscalls.Fill, error) {
|
||||||
@@ -70,10 +119,36 @@ func newLedgerFake(t *testing.T) *ledgerFake {
|
|||||||
return f
|
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) {
|
func (f *ledgerFake) Apply(instance, operation string, body any) (uint64, error) {
|
||||||
if f.failOn == operation {
|
if f.failOn == operation {
|
||||||
return 0, fmt.Errorf("the ledger is away")
|
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]]
|
ty, ok := f.types[strings.SplitN(instance, "/", 2)[0]]
|
||||||
if !ok {
|
if !ok {
|
||||||
return 0, fmt.Errorf("no type for %s", instance)
|
return 0, fmt.Errorf("no type for %s", instance)
|
||||||
@@ -151,6 +226,7 @@ func (f *ledgerFake) Remove(instance string) error {
|
|||||||
f.seq[instance]++
|
f.seq[instance]++
|
||||||
f.states[instance] = json.RawMessage("null")
|
f.states[instance] = json.RawMessage("null")
|
||||||
f.history = append(f.history, instance+" remove")
|
f.history = append(f.history, instance+" remove")
|
||||||
|
f.change(instance)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,6 +257,25 @@ func (f *ledgerFake) Query(index, key string) ([]string, error) {
|
|||||||
return out, nil
|
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) {
|
func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) {
|
||||||
s := f.states[instance]
|
s := f.states[instance]
|
||||||
if s == nil || string(s) == "null" {
|
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).
|
// 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) {
|
t.Run("a core record ended 11 minutes after merge-called is over its budget", func(t *testing.T) {
|
||||||
now := at
|
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 {
|
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)
|
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 {
|
if err != nil || len(list) != 1 || list[0].Instance != r.Instance {
|
||||||
t.Fatalf("list %+v %v", list, err)
|
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)
|
l := newLedgerFake(t)
|
||||||
now := at
|
now := at
|
||||||
rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }}
|
var journal []string
|
||||||
old, _, _ := rs.Open(opening("main", 46, heads))
|
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)
|
now = at.Add(89 * 24 * time.Hour)
|
||||||
kept, _, _ := rs.Open(opening("main", 47, heads))
|
kept, _, _ := before.Open(opening("main", 47, heads))
|
||||||
if r, _ := rs.Read(old.Instance); r == nil {
|
for _, op := range l.history {
|
||||||
t.Fatal("a record within its retention is removed")
|
if strings.HasPrefix(op, TypeHeld+"/") {
|
||||||
|
t.Fatalf("an open wrote %s: no month list is written", op)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
now = at.Add(91 * 24 * time.Hour)
|
// A month list the gate before H2 wrote, standing at the start.
|
||||||
if _, _, err := rs.Open(opening("main", 48, heads)); err != nil {
|
if _, err := l.Apply("held/2026-11", OpHold, map[string]any{"instance": old.Instance, "opened": at}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if r, _ := rs.Read(old.Instance); r != nil {
|
l.history = nil
|
||||||
t.Fatal("a record past its retention is kept")
|
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 string(l.states["held/2026-11"]) != "null" || !slices.Contains(l.history, "held/2026-11 remove") {
|
||||||
if len(list) != 2 || list[0].Instance != kept.Instance {
|
t.Fatalf("the month list holds %s after %v: removed through the ledger's removal", l.states["held/2026-11"], l.history)
|
||||||
t.Fatalf("list %+v", list)
|
|
||||||
}
|
}
|
||||||
})
|
for _, op := range l.history {
|
||||||
|
if strings.HasSuffix(op, " forget") || strings.HasSuffix(op, " "+OpDrop) || strings.HasSuffix(op, " "+OpHold) {
|
||||||
t.Run("the setting record-retention, in days", func(t *testing.T) {
|
t.Errorf("the gate applied %s: no month list is applied", op)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 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)
|
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"))
|
raw, _ := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||||
if !strings.Contains(string(raw), `"max-mib": 1024`) {
|
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||||
t.Error("the records ledger is not capped at 1 GiB (design 47 H2 §809)")
|
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"}) {
|
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)
|
t.Errorf("the type mover's indexes are %+v, not one %s on its record's key", ix, MoversIndex)
|
||||||
@@ -855,6 +1024,107 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) {
|
|||||||
t.Fatalf("with none open: %+v %v, log %d", again, err, len(log.took))
|
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")
|
||||||
|
}
|
||||||
|
before := len(l.history)
|
||||||
|
if _, err := rs.FollowEnds("the indexes were rebuilt", log); err == nil || len(l.history) != before {
|
||||||
|
t.Fatalf("followed though the hand-act log refused it: %v (wrote %v)", err, l.history[before:])
|
||||||
|
}
|
||||||
|
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) {
|
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)
|
rs, r, said := setup(t)
|
||||||
owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"}
|
owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"}
|
||||||
@@ -1083,3 +1353,121 @@ func opening(branch string, source int64, heads map[string]string) RecordOpening
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ptrTime(t time.Time) *time.Time { return &t }
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -150,8 +151,10 @@ func (rs *Records) end(r *Record, why, by string) error {
|
|||||||
body["delivery-time"], body["class"] = took.String(), class
|
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 := *r
|
||||||
next.Ended = &e
|
next.Ended, next.Ends = &e, r.Ends+1
|
||||||
if took > 0 {
|
if took > 0 {
|
||||||
next.DeliveryTime, next.Class = took.String(), class
|
next.DeliveryTime, next.Class = took.String(), class
|
||||||
}
|
}
|
||||||
@@ -159,11 +162,12 @@ func (rs *Records) end(r *Record, why, by string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
r.Ended, r.Sequence = &e, seq
|
r.Ended, r.Sequence, r.Ends = &e, seq, r.Ends+1
|
||||||
if took > 0 {
|
if took > 0 {
|
||||||
r.DeliveryTime, r.Class = took.String(), class
|
r.DeliveryTime, r.Class = took.String(), class
|
||||||
}
|
}
|
||||||
rs.keep(r)
|
rs.keep(r)
|
||||||
|
rs.endEntries(r, &e)
|
||||||
if rs.Changed != nil {
|
if rs.Changed != nil {
|
||||||
rs.Changed(r, RecordChange{What: "ended", Why: why, Ended: true})
|
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
|
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 {
|
func (rs *Records) sayEnded(r *Record) error {
|
||||||
if r.Ended == nil {
|
if r.Ended == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
at := r.Ended.At
|
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 {
|
for _, a := range r.Ended.Away {
|
||||||
since := a.Since
|
since := a.Since
|
||||||
e.Away = append(e.Away, meshdelivery.RecordEndedEventAwayItem{Node: a.Node, Since: &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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
// 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
|
// 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
|
// 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),
|
// 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.
|
// 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,
|
rs.sayFill(meshdelivery.SubjectFull, "full-"+inst, before,
|
||||||
"the next record, "+inst+" of "+milestone+"; its merge is held until room is said")
|
"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 "+
|
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.
|
// 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
|
// RoomAgain is whether a merge held for a full ledger since then may be handed now: the ledger below FillingPercent of its
|
||||||
// removed first, the ledger below FillingPercent of its cap, said once as room. A fill it cannot read gives no room.
|
// cap, said once as room. A fill it cannot read gives no room.
|
||||||
func (rs *Records) RoomAgain(since time.Time) (bool, error) {
|
func (rs *Records) RoomAgain(since time.Time) (bool, error) {
|
||||||
if err := rs.Sweep(rs.now()); err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
f, err := rs.Fill()
|
f, err := rs.Fill()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -33,6 +33,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
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"
|
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"
|
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)
|
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) {
|
func decodePipelineStarted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
||||||
var p runner.PipelineStartedEvent
|
p, _, err := runner.DecodePipelineStartedEvent(body)
|
||||||
if err := strictly(body, &p); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return nil, namesSource(p.Branch, p.Source, p.Run)
|
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) {
|
func decodePipelineEnded(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
||||||
var p runner.PipelineEndedEvent
|
var p runner.PipelineEndedEvent
|
||||||
if err := strictly(body, &p); err != nil {
|
if err := strictly(body, &p); err != nil {
|
||||||
@@ -75,8 +92,8 @@ func decodeWait(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func decodeWanted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
func decodeWanted(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
||||||
var w wants.WantedEvent
|
w, _, err := wants.DecodeWantedEvent(body)
|
||||||
if err := strictly(body, &w); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if w.Module == "" || w.Node == "" {
|
if w.Module == "" || w.Node == "" {
|
||||||
@@ -134,6 +151,12 @@ func (h *Holder) Follow(event string, body json.RawMessage) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return h.pipelineStarted(p)
|
return h.pipelineStarted(p)
|
||||||
|
case runner.EventMoverAdded:
|
||||||
|
m, err := runnerclient.MoverAdded(body)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return h.moverAdded(m)
|
||||||
case runner.EventPipelineEnded:
|
case runner.EventPipelineEnded:
|
||||||
var p runner.PipelineEndedEvent
|
var p runner.PipelineEndedEvent
|
||||||
if err := json.Unmarshal(body, &p); err != nil || p.Run != "" {
|
if err := json.Unmarshal(body, &p); err != nil || p.Run != "" {
|
||||||
@@ -193,11 +216,45 @@ func (h *Holder) pipelineStarted(p runner.PipelineStartedEvent) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Holder) pipelineEnded(p runner.PipelineEndedEvent) error {
|
// moverAdded counts a mover added to a pipeline in the record that pipeline's key names, as wantWritten finds it (G §144,
|
||||||
r, err := h.openRecord(p.Branch, p.Source)
|
// 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
|
||||||
if err != nil || r == nil {
|
// 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 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()
|
at := h.Now().UTC()
|
||||||
if p.Ended != nil {
|
if p.Ended != nil {
|
||||||
at = p.Ended.UTC()
|
at = p.Ended.UTC()
|
||||||
@@ -269,7 +326,20 @@ func (h *Holder) wantWritten(w wants.WantedEvent) error {
|
|||||||
if r == nil || r.Ended != nil {
|
if r == nil || r.Ended != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := h.Records.AddEntry(r, RecordEntry{Module: w.Module, Fingerprint: w.Fp, Node: w.Node}); err != nil {
|
// A body with no want-revision is the earlier form: it is applied and leaves the held revision as it is (H-A-865).
|
||||||
|
held := w.WantRevision
|
||||||
|
for _, e := range r.Entries {
|
||||||
|
if e.Module != w.Module || e.Node != w.Node {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w.WantRevision > 0 && e.WantRevision > w.WantRevision {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if w.WantRevision == 0 && e.WantRevision > held {
|
||||||
|
held = e.WantRevision
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := h.Records.AddEntry(r, RecordEntry{Module: w.Module, Fingerprint: w.Fp, Node: w.Node, WantRevision: held}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
at := h.Now().UTC()
|
at := h.Now().UTC()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
"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 {
|
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)
|
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", "",
|
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"}`)
|
`{"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")]
|
held := r.Outcomes[OutcomeKey("app", "f", "", "approval")]
|
||||||
@@ -94,15 +103,56 @@ func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) {
|
|||||||
if _, ok := r.Entries[EntryKey("app", "f", "novox")]; ok {
|
if _, ok := r.Entries[EntryKey("app", "f", "novox")]; ok {
|
||||||
t.Fatal("a removed want is an entry")
|
t.Fatal("a removed want is an entry")
|
||||||
}
|
}
|
||||||
|
// Design 47 H2b §832 5. (1984/AC-832g, H-A-832, H-A-842): a want at a want-revision below the one held for that node and
|
||||||
|
// module changes nothing, a repeat of an applied body writes nothing new, and a field the contract does not know is
|
||||||
|
// left unread.
|
||||||
|
for _, w := range []string{
|
||||||
|
`{"v":1,"node":"ace","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12,"want-revision":9,"future":1}`,
|
||||||
|
`{"v":1,"node":"ace","module":"app","fp":"f2","pipeline":"main.1","source":1,"revision":12,"want-revision":8}`,
|
||||||
|
} {
|
||||||
|
hear(t, c, "mesh-wants.wanted.x.app", "", w)
|
||||||
|
}
|
||||||
|
if e, ok := r.Entries[EntryKey("app", "f", "ace")]; !ok || e.WantRevision != 9 {
|
||||||
|
t.Fatalf("the want at want-revision 9 is %+v: applied with its unknown field unread", e)
|
||||||
|
}
|
||||||
|
if _, ok := r.Entries[EntryKey("app", "f2", "ace")]; ok {
|
||||||
|
t.Fatal("a want at want-revision 8, below the 9 held, is an entry")
|
||||||
|
}
|
||||||
|
// A wanted of the earlier form (no want-revision) leaves the held 9 as it is, so a wanted at 8 changes nothing still
|
||||||
|
// (H-A-865); and a body said again under a new id adds no ledger operation (1984/AC-832g).
|
||||||
|
ledger := h.Records.Ledger.(*ledgerFake)
|
||||||
|
hear(t, c, "mesh-wants.wanted.x.app", "", `{"v":1,"node":"ace","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12}`)
|
||||||
|
hear(t, c, "mesh-wants.wanted.x.app", "", `{"v":1,"node":"ace","module":"app","fp":"f3","pipeline":"main.1","source":1,"revision":12,"want-revision":8}`)
|
||||||
|
if e := r.Entries[EntryKey("app", "f", "ace")]; e.WantRevision != 9 {
|
||||||
|
t.Fatalf("the entry is %+v: a wanted with no want-revision keeps the 9 held", e)
|
||||||
|
}
|
||||||
|
if _, ok := r.Entries[EntryKey("app", "f3", "ace")]; ok {
|
||||||
|
t.Fatal("a want at want-revision 8 is an entry after a wanted of the earlier form")
|
||||||
|
}
|
||||||
|
before := len(ledger.history)
|
||||||
|
again := `{"v":1,"node":"ace","module":"app","fp":"f","pipeline":"main.1","source":1,"revision":12,"want-revision":9}`
|
||||||
|
for _, id := range []string{"id-1", "id-2"} {
|
||||||
|
if err := c.Hear(stdio.Envelope{Key: "mesh-wants.wanted.x.app", Body: json.RawMessage(again), Headers: map[string]string{"Nats-Msg-Id": id}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ledger.history) != before {
|
||||||
|
t.Fatalf("a repeated wanted wrote %v", ledger.history[before:])
|
||||||
|
}
|
||||||
hear(t, c, "node-engine.running.ace.app", "ace", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"ace","fingerprint":"f","healthy":true}`)
|
hear(t, c, "node-engine.running.ace.app", "ace", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"ace","fingerprint":"f","healthy":true}`)
|
||||||
hear(t, c, "node-engine.running.g14.app", "g14", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"g14","fingerprint":"f","healthy":true}`)
|
hear(t, c, "node-engine.running.g14.app", "g14", `{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"g14","fingerprint":"f","healthy":true}`)
|
||||||
if o := r.Outcomes[OutcomeKey("app", "f", "g14", StepRunning)]; o.Outcome != OutcomeRunning || r.Ended != nil || len(*ended) != 0 {
|
if o := r.Outcomes[OutcomeKey("app", "f", "g14", StepRunning)]; o.Outcome != OutcomeRunning || r.Ended != nil || len(*ended) != 0 {
|
||||||
t.Fatalf("running is %+v and the record ended %+v: running ends nothing", o, r.Ended)
|
t.Fatalf("running is %+v and the record ended %+v: running ends nothing", o, r.Ended)
|
||||||
}
|
}
|
||||||
hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)
|
hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1.again.2","branch":"main","source":1,"outcome":"running"}`) // an again pipeline's, on its source's subject (AC-824m)
|
||||||
if r.Ended == nil || r.Ended.Why != WhyAllRun || len(*ended) != 1 {
|
if r.Ended == nil || r.Ended.Why != WhyAllRun || len(*ended) != 1 {
|
||||||
t.Fatalf("the record ended %+v, said %v", r.Ended, *ended)
|
t.Fatalf("the record ended %+v, said %v", r.Ended, *ended)
|
||||||
}
|
}
|
||||||
|
// A tier-late said after the running changes nothing (1984/AC-832g).
|
||||||
|
hear(t, c, "mesh-wants.pipeline-wanted.main.1", "", `{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"tier-late","not-running":[{"module":"app","machines":["ace"]}]}`)
|
||||||
|
if r.Ended == nil || r.Ended.Why != WhyAllRun || len(*ended) != 1 {
|
||||||
|
t.Fatalf("the record ended %+v, said %v: a tier-late after the running changes nothing", r.Ended, *ended)
|
||||||
|
}
|
||||||
if got, _ := h.Records.ByKey("main", 1); got != r {
|
if got, _ := h.Records.ByKey("main", 1); got != r {
|
||||||
t.Fatal("the record read by its key is not the one the gate keeps")
|
t.Fatal("the record read by its key is not the one the gate keeps")
|
||||||
}
|
}
|
||||||
@@ -122,39 +172,50 @@ func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, erro
|
|||||||
return seq, err
|
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
|
// heardBed is what the gate said while a row of TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied ran.
|
||||||
// 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
|
type heardBed struct {
|
||||||
// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it
|
ended int // the record-ended said
|
||||||
// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer
|
journal []string // the lines the records said in the journal
|
||||||
// taken before the next event writes the record.
|
}
|
||||||
|
|
||||||
|
// 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) {
|
func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
|
||||||
running := func(node string) stdio.Envelope {
|
running := func(node string) stdio.Envelope {
|
||||||
return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage(
|
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}`)}
|
`{"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 {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
heard func(h *Holder) (any, error)
|
// before hears it before the running, a minute earlier; else it is heard as the running's write lands.
|
||||||
check func(t *testing.T, h *Holder, answer any)
|
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) {
|
{"pipeline-wanted", false, pipelineWanted, func(t *testing.T, h *Holder, _ any, said *heardBed) {
|
||||||
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) {
|
|
||||||
r, err := h.Records.ByKey("main", 1)
|
r, err := h.Records.ByKey("main", 1)
|
||||||
if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore {
|
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 (%v); want 5m0s and core", r.Ended,
|
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.DeliveryTime, r.Class, err)
|
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{}) {
|
for _, tool := range tools(h, &listening{}) {
|
||||||
if tool.Name == Seat+".show" {
|
if tool.Name == Seat+".show" {
|
||||||
return tool.Run(map[string]any{"id": "main.1"})
|
return tool.Run(map[string]any{"id": "main.1"})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("the gate serves no %s.show", Seat)
|
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 {
|
if err := take(h, running("g14")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -173,12 +234,46 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
|
|||||||
t.Fatal(err)
|
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) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)
|
now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)
|
||||||
|
said := &heardBed{}
|
||||||
h := &Holder{Now: func() time.Time { return now }}
|
h := &Holder{Now: func() time.Time { return now }}
|
||||||
ledger := &hookedLedger{ledgerFake: newLedgerFake(t)}
|
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}
|
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 {
|
if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -196,20 +291,33 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
heard := make(chan heardOut, 1)
|
heard := make(chan heardOut, 1)
|
||||||
ledger.after = func(_, operation string, body any) {
|
if tc.before {
|
||||||
if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning {
|
answer, err := tc.heard(h)
|
||||||
return
|
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
|
ledger.failOn = ""
|
||||||
// Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's
|
} else {
|
||||||
// goroutines allow, else on a goroutine of its own, as the runtime hands it.
|
ledger.after = func(_, operation string, body any) {
|
||||||
hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} }
|
if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning {
|
||||||
if h.applying.TryLock() {
|
return
|
||||||
h.applying.Unlock()
|
}
|
||||||
hear()
|
ledger.after = nil
|
||||||
return
|
// 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 {
|
if err := take(h, running("ace")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -218,28 +326,148 @@ func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
|
|||||||
if out.err != nil {
|
if out.err != nil {
|
||||||
t.Fatal(out.err)
|
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
|
// 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.
|
// the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running.
|
||||||
func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) {
|
func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) {
|
||||||
for _, tc := range []struct{ name, key, body, why string }{
|
for _, tc := range []struct{ name, key, body, why, then string }{
|
||||||
{"pipeline failed", "mesh-pipeline-runner.pipeline-ended.main.1",
|
{"pipeline failed", "mesh-pipeline-runner.pipeline-ended.main.1",
|
||||||
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"failed","why":"build failed","movers":[{"module":"app","fingerprint":"f","tier":1,"steps":[{"step":"build","status":"required","outcome":"failed"}]}]}`,
|
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"failed","why":"build failed","movers":[{"module":"app","fingerprint":"f","tier":1,"steps":[{"step":"build","status":"required","outcome":"failed"}]}]}`,
|
||||||
"failed: build failed"},
|
"failed: build failed", ""},
|
||||||
{"pipeline cancelled, no why", "mesh-pipeline-runner.pipeline-ended.main.1",
|
{"pipeline cancelled, no why", "mesh-pipeline-runner.pipeline-ended.main.1",
|
||||||
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"cancelled","movers":[]}`,
|
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","outcome":"cancelled","movers":[]}`,
|
||||||
"failed: the pipeline main.1 ended cancelled"},
|
"failed: the pipeline main.1 ended cancelled", ""},
|
||||||
{"tier late", "mesh-wants.pipeline-wanted.main.1",
|
{"tier late", "mesh-wants.pipeline-wanted.main.1",
|
||||||
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"tier-late","not-running":[{"module":"app","machines":["g14","ace"]}]}`,
|
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"tier-late","not-running":[{"module":"app","machines":["g14","ace"]}]}`,
|
||||||
"failed: a tier is late: not running app on ace, g14"},
|
"failed: a tier is late: not running app on ace, g14", ""},
|
||||||
|
// 1984/AC-824f: a running after a tier-late leaves the record failed.
|
||||||
|
{"running after tier late", "mesh-wants.pipeline-wanted.main.1",
|
||||||
|
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"tier-late","not-running":[{"module":"app","machines":["ace"]}]}`,
|
||||||
|
"failed: a tier is late: not running app on ace",
|
||||||
|
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`},
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
_, c, r, ended := pipelineBed(t)
|
_, c, r, ended := pipelineBed(t)
|
||||||
hear(t, c, tc.key, "", tc.body)
|
hear(t, c, tc.key, "", tc.body)
|
||||||
|
if tc.then != "" {
|
||||||
|
hear(t, c, tc.key, "", tc.then)
|
||||||
|
}
|
||||||
if r.Ended == nil || r.Ended.Why != tc.why || len(*ended) != 1 {
|
if r.Ended == nil || r.Ended.Why != tc.why || len(*ended) != 1 {
|
||||||
t.Fatalf("the record ended %+v, said %v; want %q", r.Ended, *ended, tc.why)
|
t.Fatalf("the record ended %+v, said %v; want %q", r.Ended, *ended, tc.why)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ func (rs *Records) RecordOf(instance, milestone string) ([]recordView, error) {
|
|||||||
if milestone == "" {
|
if milestone == "" {
|
||||||
return nil, errors.New("name a record's instance or a milestone")
|
return nil, errors.New("name a record's instance or a milestone")
|
||||||
}
|
}
|
||||||
list, err := rs.List()
|
list, err := rs.Kept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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.
|
// Lines are every record kept, oldest first, each with its fill against the value limit.
|
||||||
func (rs *Records) Lines() (map[string]any, error) {
|
func (rs *Records) Lines() (map[string]any, error) {
|
||||||
list, err := rs.List()
|
list, err := rs.Kept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -102,8 +102,8 @@ func (rs *Records) Lines() (map[string]any, error) {
|
|||||||
}
|
}
|
||||||
lines = append(lines, l)
|
lines = append(lines, l)
|
||||||
}
|
}
|
||||||
return map[string]any{"records": lines, "open": open, "kept": len(lines), "retention-days": int(rs.retention().Hours() / 24),
|
return map[string]any{"records": lines, "open": open, "kept": len(lines), "ended-days": rs.EndedDays,
|
||||||
"fill": rs.fillLine()}, nil
|
"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
|
// 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) == "" {
|
if strings.TrimSpace(why) == "" {
|
||||||
return nil, errors.New("say why every open record is ended by hand, such as the clean state")
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -216,6 +216,35 @@ func recordTools(h *Holder, acts handActs) []stdio.Tool {
|
|||||||
}
|
}
|
||||||
return h.Records.Lines()
|
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",
|
{Name: "gate_consumer",
|
||||||
Description: "The delivery record's consumer of the step events: per family the events applied and refused " +
|
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.",
|
"since the gate started, the last applied, and why the last was refused.",
|
||||||
|
|||||||
@@ -14,9 +14,6 @@ import (
|
|||||||
|
|
||||||
// Settings are the operator's values for this module.
|
// Settings are the operator's values for this module.
|
||||||
type Settings struct {
|
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
|
// UntakenBoundMinutes is how many minutes a head may stand untaken before head-untaken is raised (design 47 H §740); nil
|
||||||
// keeps DefaultUntakenBound.
|
// keeps DefaultUntakenBound.
|
||||||
UntakenBoundMinutes *int `json:"untaken-bound"`
|
UntakenBoundMinutes *int `json:"untaken-bound"`
|
||||||
@@ -25,7 +22,7 @@ type Settings struct {
|
|||||||
// DefaultUntakenBound is untaken-bound when the setting gives none (§740).
|
// DefaultUntakenBound is untaken-bound when the setting gives none (§740).
|
||||||
const DefaultUntakenBound = 10 * time.Minute
|
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) {
|
func readSettings(path string) (Settings, error) {
|
||||||
var s Settings
|
var s Settings
|
||||||
if path == "" {
|
if path == "" {
|
||||||
@@ -39,17 +36,6 @@ func readSettings(path string) (Settings, error) {
|
|||||||
if err := json.Unmarshal(raw, &loose); err != nil {
|
if err := json.Unmarshal(raw, &loose); err != nil {
|
||||||
return s, fmt.Errorf("the settings file is not JSON: %v", err)
|
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) {
|
switch v := loose["untaken-bound"].(type) {
|
||||||
case nil:
|
case nil:
|
||||||
case float64:
|
case float64:
|
||||||
@@ -63,14 +49,3 @@ func readSettings(path string) (Settings, error) {
|
|||||||
}
|
}
|
||||||
return s, nil
|
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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
{
|
{
|
||||||
"record-retention": 90,
|
|
||||||
"untaken-bound": 10
|
"untaken-bound": 10
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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/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-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/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/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/meshdelivery v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner v0.0.0-00010101000000-000000000000
|
||||||
|
|||||||
@@ -21,3 +21,26 @@ func Consumes() ([]string, error) {
|
|||||||
}
|
}
|
||||||
return m.Consumes, nil
|
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")
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"mesh-delivery-forge-bridge.forge.*.*.*.head-moved",
|
"mesh-delivery-forge-bridge.forge.*.*.*.head-moved",
|
||||||
"mesh-delivery-indexer.take-in.taken",
|
"mesh-delivery-indexer.take-in.taken",
|
||||||
"mesh-pipeline-runner.pipeline-started.*.*",
|
"mesh-pipeline-runner.pipeline-started.*.*",
|
||||||
|
"mesh-pipeline-runner.mover-added.*.*",
|
||||||
"mesh-pipeline-runner.pipeline-ended.*.*",
|
"mesh-pipeline-runner.pipeline-ended.*.*",
|
||||||
"mesh-pipeline-runner.wait-held.*.*",
|
"mesh-pipeline-runner.wait-held.*.*",
|
||||||
"mesh-pipeline-runner.wait-ended.*.*",
|
"mesh-pipeline-runner.wait-ended.*.*",
|
||||||
@@ -36,12 +37,18 @@
|
|||||||
"name": "records",
|
"name": "records",
|
||||||
"storage": "ledger",
|
"storage": "ledger",
|
||||||
"template": "ledger",
|
"template": "ledger",
|
||||||
|
"form": 1,
|
||||||
"options": {
|
"options": {
|
||||||
"max-mib": 1024
|
"max-mib": 3072
|
||||||
|
},
|
||||||
|
"configuration": {
|
||||||
|
"max-age-days": 90,
|
||||||
|
"ended-days": 30
|
||||||
},
|
},
|
||||||
"types": [
|
"types": [
|
||||||
{
|
{
|
||||||
"name": "record",
|
"name": "record",
|
||||||
|
"ends-with": "ended",
|
||||||
"schema": {
|
"schema": {
|
||||||
"milestone": {
|
"milestone": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
@@ -120,6 +127,12 @@
|
|||||||
},
|
},
|
||||||
"phases": {
|
"phases": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
|
},
|
||||||
|
"ends": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"pipeline-ends": {
|
||||||
|
"type": "integer"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"operations": [
|
"operations": [
|
||||||
@@ -193,7 +206,9 @@
|
|||||||
"fields": [
|
"fields": [
|
||||||
"ended",
|
"ended",
|
||||||
"delivery-time",
|
"delivery-time",
|
||||||
"class"
|
"class",
|
||||||
|
"ends",
|
||||||
|
"pipeline-ends"
|
||||||
],
|
],
|
||||||
"sequence": true
|
"sequence": true
|
||||||
}
|
}
|
||||||
@@ -201,6 +216,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "mover",
|
"name": "mover",
|
||||||
|
"ends-with": "ended",
|
||||||
"schema": {
|
"schema": {
|
||||||
"record": {
|
"record": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
@@ -240,6 +256,12 @@
|
|||||||
},
|
},
|
||||||
"class": {
|
"class": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
|
},
|
||||||
|
"ended": {
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"want-revision": {
|
||||||
|
"type": "integer"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"operations": [
|
"operations": [
|
||||||
@@ -262,7 +284,8 @@
|
|||||||
"key",
|
"key",
|
||||||
"module",
|
"module",
|
||||||
"fingerprint",
|
"fingerprint",
|
||||||
"node"
|
"node",
|
||||||
|
"want-revision"
|
||||||
],
|
],
|
||||||
"into": "entries",
|
"into": "entries",
|
||||||
"key": "key",
|
"key": "key",
|
||||||
@@ -285,6 +308,14 @@
|
|||||||
"into": "outcomes",
|
"into": "outcomes",
|
||||||
"key": "key",
|
"key": "key",
|
||||||
"sequence": true
|
"sequence": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "end",
|
||||||
|
"effect": "set-fields",
|
||||||
|
"fields": [
|
||||||
|
"ended"
|
||||||
|
],
|
||||||
|
"sequence": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
@@ -298,6 +329,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "act",
|
"name": "act",
|
||||||
|
"ends-with": "ended",
|
||||||
"schema": {
|
"schema": {
|
||||||
"record": {
|
"record": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
@@ -328,6 +360,9 @@
|
|||||||
},
|
},
|
||||||
"owed": {
|
"owed": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
|
},
|
||||||
|
"ended": {
|
||||||
|
"type": "object"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"operations": [
|
"operations": [
|
||||||
@@ -347,6 +382,14 @@
|
|||||||
"owed"
|
"owed"
|
||||||
],
|
],
|
||||||
"sequence": true
|
"sequence": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "end",
|
||||||
|
"effect": "set-fields",
|
||||||
|
"fields": [
|
||||||
|
"ended"
|
||||||
|
],
|
||||||
|
"sequence": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
@@ -452,6 +495,8 @@
|
|||||||
"gate_record_end",
|
"gate_record_end",
|
||||||
"gate_record_repair",
|
"gate_record_repair",
|
||||||
"gate_records",
|
"gate_records",
|
||||||
|
"gate_records_expiring",
|
||||||
|
"gate_records_follow_ends",
|
||||||
"gate_source",
|
"gate_source",
|
||||||
"gate_source_again",
|
"gate_source_again",
|
||||||
"gate_source_seed",
|
"gate_source_seed",
|
||||||
@@ -461,14 +506,6 @@
|
|||||||
"mesh-delivery-gate_state_prune_now"
|
"mesh-delivery-gate_state_prune_now"
|
||||||
],
|
],
|
||||||
"config": {
|
"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": {
|
"untaken-bound": {
|
||||||
"type": "number",
|
"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.",
|
"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 +560,6 @@
|
|||||||
"path": "${dir:state}/settings.json",
|
"path": "${dir:state}/settings.json",
|
||||||
"mode": "0600",
|
"mode": "0600",
|
||||||
"takes-config": [
|
"takes-config": [
|
||||||
"record-retention",
|
|
||||||
"untaken-bound"
|
"untaken-bound"
|
||||||
],
|
],
|
||||||
"merge": "json",
|
"merge": "json",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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
|
type errFake string
|
||||||
|
|
||||||
func (e errFake) Error() string { return string(e) }
|
func (e errFake) Error() string { return string(e) }
|
||||||
|
|||||||
@@ -88,6 +88,46 @@ func parsePipelineRow(raw json.RawMessage, pr string) (PipelineRow, error) {
|
|||||||
return row, nil
|
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
|
// 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.
|
// commit, `show` of each.
|
||||||
func busPipelines(owner string) Pipelines {
|
func busPipelines(owner string) Pipelines {
|
||||||
@@ -110,11 +150,9 @@ func busPipelines(owner string) Pipelines {
|
|||||||
}
|
}
|
||||||
var rows []PipelineRow
|
var rows []PipelineRow
|
||||||
for _, k := range keys {
|
for _, k := range keys {
|
||||||
raw, err := stdio.Ask("seat:mesh-pipeline-runner.show", map[string]any{"pipeline": k})
|
row, err := readPipeline(func(args map[string]any) (json.RawMessage, error) {
|
||||||
if err != nil {
|
return stdio.Ask("seat:mesh-pipeline-runner.show", args)
|
||||||
return nil, err
|
}, k, pr)
|
||||||
}
|
|
||||||
row, err := parsePipelineRow(raw, pr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ as text. `get` serves each, and any other field a record of hq wrote under `fiel
|
|||||||
## Writing a record
|
## Writing a record
|
||||||
|
|
||||||
1. `reserve` a number for its kind.
|
1. `reserve` a number for its kind.
|
||||||
2. `propose` the record whole. It is refused, naming every reason at once, when it breaks one of the **31 rules
|
2. `propose` the record whole. It is refused, naming every reason at once, when it breaks one of the **32 rules
|
||||||
that judge one record or its prose**. They are hq's checks moved to the write; `PerRecordRules` in `rules.go`
|
that judge one record or its prose**. They are hq's checks moved to the write; `PerRecordRules` in `rules.go`
|
||||||
lists each one with the check it comes from:
|
lists each one with the check it comes from:
|
||||||
- 25 on the structure: kind, reserved number, title, topic, date, deciders, research status, at least one
|
- 25 on the structure: kind, reserved number, title, topic, date, deciders, research status, at least one
|
||||||
@@ -91,6 +91,10 @@ as text. `get` serves each, and any other field a record of hq wrote under `fiel
|
|||||||
- 1 on the operator's ask (hq issue 639): `brief`, a record that needs the operator carries a brief its ask reads
|
- 1 on the operator's ask (hq issue 639): `brief`, a record that needs the operator carries a brief its ask reads
|
||||||
at a glance — a headline of at most 60 characters, a one-line summary of at most 300, at most three points of
|
at a glance — a headline of at most 60 characters, a one-line summary of at most 300, at most three points of
|
||||||
at most 160, and no path, address, dotted name or long word. It holds records dated from 2026-10-13.
|
at most 160, and no path, address, dotted name or long word. It holds records dated from 2026-10-13.
|
||||||
|
- 1 on the form of a section (`section-form`): a part with a plain title, once in the record, whose text holds no
|
||||||
|
local path, no file and line, and no link to a file;
|
||||||
|
- 1 on a progressive insight's links (`insight-links`, hq issue 466): it keeps exactly the accepted record's
|
||||||
|
supersedes and changes links (a cites link may be added); changing them is a new record.
|
||||||
|
|
||||||
A rule holds a record from the day hq's checks began to hold it (`RuleFrom` in `rules.go`):
|
A rule holds a record from the day hq's checks began to hold it (`RuleFrom` in `rules.go`):
|
||||||
- retired words from 2026-10-07 and daemons' lines from 2026-10-09 for a research effort; for a decision record
|
- retired words from 2026-10-07 and daemons' lines from 2026-10-09 for a research effort; for a decision record
|
||||||
|
|||||||
@@ -53,6 +53,11 @@ func TestAnActiveEffortTakesANewVersionWithANewDocument(t *testing.T) {
|
|||||||
first := effortAsk(r.Number, StatusActive, overview)
|
first := effortAsk(r.Number, StatusActive, overview)
|
||||||
w.accepted(t, "author@g14", first)
|
w.accepted(t, "author@g14", first)
|
||||||
key := Key{KindResearch, r.Number}
|
key := Key{KindResearch, r.Number}
|
||||||
|
// 466/AC2: an insight accepted earlier is kept by the new version.
|
||||||
|
corrected := first
|
||||||
|
corrected.Insight = "it said less"
|
||||||
|
w.accepted(t, "author@g14", corrected)
|
||||||
|
insightsAt := mustGet(t, w.k.Store, key).Versions
|
||||||
reviews, versions := len(w.judge.reviews), mustGet(t, w.k.Store, key).Versions
|
reviews, versions := len(w.judge.reviews), mustGet(t, w.k.Store, key).Versions
|
||||||
next := c.next(r.Number)
|
next := c.next(r.Number)
|
||||||
next.Why = c.name
|
next.Why = c.name
|
||||||
@@ -85,7 +90,7 @@ func TestAnActiveEffortTakesANewVersionWithANewDocument(t *testing.T) {
|
|||||||
}
|
}
|
||||||
e = mustGet(t, w.k.Store, key)
|
e = mustGet(t, w.k.Store, key)
|
||||||
cur := e.Current
|
cur := e.Current
|
||||||
if e.Pending != nil || cur.Status != c.status || len(cur.Insights) != 0 || !reflect.DeepEqual(cur.Sections, c.docs) {
|
if e.Pending != nil || cur.Status != c.status || len(cur.Insights) != 1 || !reflect.DeepEqual(cur.Sections, c.docs) {
|
||||||
t.Fatalf("after the review: %s, pending %v, insights %v, sections %+v", cur.Status, e.Pending != nil, cur.Insights, cur.Sections)
|
t.Fatalf("after the review: %s, pending %v, insights %v, sections %+v", cur.Status, e.Pending != nil, cur.Insights, cur.Sections)
|
||||||
}
|
}
|
||||||
if cur.Title != first.Title || cur.Date != first.Date || !reflect.DeepEqual(cur.Deciders, first.Deciders) {
|
if cur.Title != first.Title || cur.Date != first.Date || !reflect.DeepEqual(cur.Deciders, first.Deciders) {
|
||||||
@@ -99,7 +104,7 @@ func TestAnActiveEffortTakesANewVersionWithANewDocument(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
for _, v := range h.Versions {
|
for _, v := range h.Versions {
|
||||||
if v.Insight {
|
if v.Insight && v.N > insightsAt {
|
||||||
t.Errorf("version %d is marked an insight", v.N)
|
t.Errorf("version %d is marked an insight", v.N)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A rule holds a record from the day hq's checks began to hold it (the review of mesh-catalog#206): a dated
|
// A rule holds a record from the day hq's checks began to hold it (the review of mesh-catalog#206): a dated
|
||||||
@@ -95,4 +98,54 @@ func TestAnInsightToADecisionOfOctoberKeepsItsWords(t *testing.T) {
|
|||||||
t.Errorf("an insight to ADR %04d was refused: %v", n, err)
|
t.Errorf("an insight to ADR %04d was refused: %v", n, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 466/AC3: an insight keeps every field of the served version that propose does not take, and a drafted clause
|
||||||
|
// stays drafted.
|
||||||
|
eachStore(t, func(t *testing.T, s Store) {
|
||||||
|
t.Run("keeps what propose does not take", func(t *testing.T) {
|
||||||
|
w := newWorld(t, s, hqMain(t))
|
||||||
|
if _, err := w.k.Import("import@test", ImportAsk{}, hqMain(t)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
key := Key{KindDecision, 276}
|
||||||
|
e := mustGet(t, w.k.Store, key)
|
||||||
|
r := e.Current.Clone()
|
||||||
|
no := false
|
||||||
|
r.Reconstructed, r.Amended, r.Touches = &no, []string{"2026-10-12"}, []string{"the tool runtime"}
|
||||||
|
r.Extra, r.Source, r.Aliases = map[string]string{"owner": "x"}, "hq@abc:02-DECISIONS/0276.md", map[string]string{"old.md": "New"}
|
||||||
|
r.Insights = []Insight{{Date: "2026-10-14", Before: "earlier", By: "someone@ace"}}
|
||||||
|
r.Clauses[0].Source = SourceDrafted
|
||||||
|
if err := w.k.Store.Save(context.Background(), Version{By: "test", At: time.Now(), Why: "seed", Record: r}, true, true, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := w.k.Propose("corrector@ace", insightTo(t, w, key)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w.reviewAll(t)
|
||||||
|
got := mustGet(t, w.k.Store, key).Current
|
||||||
|
if len(got.Insights) != 2 || got.Insights[0].Before != "earlier" || got.Reconstructed == nil || *got.Reconstructed ||
|
||||||
|
!reflect.DeepEqual(got.Amended, r.Amended) || !reflect.DeepEqual(got.Touches, r.Touches) ||
|
||||||
|
!reflect.DeepEqual(got.Extra, r.Extra) || got.Source != r.Source || !reflect.DeepEqual(got.Aliases, r.Aliases) ||
|
||||||
|
got.Clauses[0].Source != SourceDrafted {
|
||||||
|
t.Fatalf("an insight dropped what the served version held: %+v", got)
|
||||||
|
}
|
||||||
|
// 466/AC3: what another record marks on this one while its insight waits is kept at acceptance.
|
||||||
|
q := insightTo(t, w, key)
|
||||||
|
q.Insight = "it said nothing of the count"
|
||||||
|
if _, err := w.k.Propose("corrector@ace", q); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e = mustGet(t, w.k.Store, key)
|
||||||
|
sup := e.Current.Clone()
|
||||||
|
sup.Extra = map[string]string{"owner": "x", "superseded-by": "ADR 9999"}
|
||||||
|
sup.Status = StatusSuperseded
|
||||||
|
if err := w.k.Store.Save(context.Background(), Version{By: "test", At: time.Now(), Why: "superseded", Record: sup}, true, false, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w.reviewAll(t)
|
||||||
|
got = mustGet(t, w.k.Store, key).Current
|
||||||
|
if got.Status != StatusSuperseded || got.Extra["superseded-by"] != "ADR 9999" || len(got.Insights) != 3 {
|
||||||
|
t.Fatalf("an insight accepted after the record was superseded lost the mark: %s %v %d insights", got.Status, got.Extra, len(got.Insights))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -415,6 +415,7 @@ func (k *KB) Propose(caller string, a ProposeAsk) (*Proposed, error) {
|
|||||||
}
|
}
|
||||||
r.AcceptedAt = held.Current.AcceptedAt
|
r.AcceptedAt = held.Current.AcceptedAt
|
||||||
r.Parts = held.Current.Parts
|
r.Parts = held.Current.Parts
|
||||||
|
keepServed(r, held.Current)
|
||||||
if held.Pending != nil {
|
if held.Pending != nil {
|
||||||
// A revision of a pending version keeps its earlier reviews, so the round count goes on (ADR 0665 §1).
|
// A revision of a pending version keeps its earlier reviews, so the round count goes on (ADR 0665 §1).
|
||||||
r.Reviews, r.CountFrom = held.Pending.Reviews, held.Pending.CountFrom
|
r.Reviews, r.CountFrom = held.Pending.Reviews, held.Pending.CountFrom
|
||||||
@@ -513,6 +514,47 @@ func (k *KB) Propose(caller string, a ProposeAsk) (*Proposed, error) {
|
|||||||
return &Proposed{Record: key.String(), Version: n, Status: StatusProposed, Says: says + "."}, nil
|
return &Proposed{Record: key.String(), Version: n, Status: StatusProposed, Says: says + "."}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// keepServed gives a version over an accepted record what the served version holds and propose's arguments do not
|
||||||
|
// carry (novox/hq issue 466; a record keeps every progressive insight its accepted versions made, and every field it
|
||||||
|
// was imported with): the insights, oldest first, so the judgement and the operator's digest see what will be served
|
||||||
|
// and accept only adds the new one; reconstructed, amended, touches, the imported fields, the source and the
|
||||||
|
// aliases; and, for a clause whose text is unchanged, its source, so a drafted clause stays drafted.
|
||||||
|
func keepServed(r, served *Record) {
|
||||||
|
r.Insights = append([]Insight(nil), served.Insights...)
|
||||||
|
keepFields(r, served)
|
||||||
|
for i, c := range r.Clauses {
|
||||||
|
if old := served.Clause(c.N); old != nil && strings.TrimSpace(old.Text) == strings.TrimSpace(c.Text) {
|
||||||
|
r.Clauses[i].Source = old.Source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// keepFields copies the fields of the served version that propose's arguments do not carry: reconstructed, amended,
|
||||||
|
// touches, the imported fields (which hold what the knowledge base marked on the record, such as superseded-by), source
|
||||||
|
// and aliases. accept takes them again from the version served when the version is accepted.
|
||||||
|
func keepFields(r, served *Record) {
|
||||||
|
r.Reconstructed, r.Extra, r.Aliases = nil, nil, nil
|
||||||
|
if served.Reconstructed != nil {
|
||||||
|
v := *served.Reconstructed
|
||||||
|
r.Reconstructed = &v
|
||||||
|
}
|
||||||
|
r.Amended = append([]string(nil), served.Amended...)
|
||||||
|
r.Touches = append([]string(nil), served.Touches...)
|
||||||
|
if len(served.Extra) > 0 {
|
||||||
|
r.Extra = make(map[string]string, len(served.Extra))
|
||||||
|
for k, v := range served.Extra {
|
||||||
|
r.Extra[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.Source = served.Source
|
||||||
|
if len(served.Aliases) > 0 {
|
||||||
|
r.Aliases = make(map[string]string, len(served.Aliases))
|
||||||
|
for k, v := range served.Aliases {
|
||||||
|
r.Aliases[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// activeLimitRefusal (ADR 0629 §4 names only a new effort or one taken up from an idea, never a new version of an active one; a check of the record set beside the one-record rules of ADR 0290 §4) says why a research effort may not be active now: the limit of efforts other than this one
|
// activeLimitRefusal (ADR 0629 §4 names only a new effort or one taken up from an idea, never a new version of an active one; a check of the record set beside the one-record rules of ADR 0290 §4) says why a research effort may not be active now: the limit of efforts other than this one
|
||||||
// already active (accepted at active, or proposed at active and waiting for review) is reached (ADR 0629). Empty
|
// already active (accepted at active, or proposed at active and waiting for review) is reached (ADR 0629). Empty
|
||||||
// when it may.
|
// when it may.
|
||||||
@@ -556,6 +598,10 @@ func (k *KB) accept(ctx context.Context, held *Entry, w *Record, by, why, warran
|
|||||||
in := r.Pending.Insight
|
in := r.Pending.Insight
|
||||||
isInsight := r.IsInsight()
|
isInsight := r.IsInsight()
|
||||||
r.Pending = nil
|
r.Pending = nil
|
||||||
|
// What the record holds now, not what it held when the version was proposed: a record superseded, or marked
|
||||||
|
// by another record's acceptance, while this version waited keeps its marks (novox/hq issue 466).
|
||||||
|
r.Insights = append([]Insight(nil), held.Current.Insights...)
|
||||||
|
keepFields(r, held.Current)
|
||||||
if isInsight {
|
if isInsight {
|
||||||
r.Insights = append(r.Insights, in)
|
r.Insights = append(r.Insights, in)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1030,7 +1030,7 @@ func verbTools(k *KB, caller func(map[string]any) string) []stdio.Tool {
|
|||||||
"clauses, each opening with a bold lead (\"**What is decided.** …\"), and its reasoning in sections (Context, " +
|
"clauses, each opening with a bold lead (\"**What is decided.** …\"), and its reasoning in sections (Context, " +
|
||||||
"Considered Options, Consequences, How it is checked, References); for a research effort its status and documents; its " +
|
"Considered Options, Consequences, How it is checked, References); for a research effort its status and documents; its " +
|
||||||
"links (supersedes, changes \"0276 §4\", extends, became, cites), and whether it needs the operator, with the brief its ask shows. Refused, naming " +
|
"links (supersedes, changes \"0276 §4\", extends, became, cites), and whether it needs the operator, with the brief its ask shows. Refused, naming " +
|
||||||
"every reason at once and writing nothing, when it breaks one of the 31 rules that judge one record or its prose — a " +
|
"every reason at once and writing nothing, when it breaks one of the 32 rules that judge one record or its prose — a " +
|
||||||
"link to nothing, a clause without a bold lead, a superseded record cited alone, an unknown topic, a retired word. A " +
|
"link to nothing, a clause without a bold lead, a superseded record cited alone, an unknown topic, a retired word. A " +
|
||||||
"proposal is revised by proposing it again; an accepted record (an active research effort or an idea excepted, which take new versions; at most as many research efforts are active as the setting research-active-at-most allows, three by default) changes only by a progressive insight (insight: what " +
|
"proposal is revised by proposing it again; an accepted record (an active research effort or an idea excepted, which take new versions; at most as many research efforts are active as the setting research-active-at-most allows, three by default) changes only by a progressive insight (insight: what " +
|
||||||
"stood before). A research effort's new version may leave out its sections, and its title, date and deciders: it then " +
|
"stood before). A research effort's new version may leave out its sections, and its title, date and deciders: it then " +
|
||||||
|
|||||||
@@ -131,6 +131,10 @@ func TestItsProcessesAreThePreparationTheActAndTheJudge(t *testing.T) {
|
|||||||
t.Fatalf("keep %v", keep)
|
t.Fatalf("keep %v", keep)
|
||||||
}
|
}
|
||||||
h, _ := watch["health"].(map[string]any)
|
h, _ := watch["health"].(map[string]any)
|
||||||
|
// 466/AC7: the manifest names knowledge_restore and ModuleTools holds it, in the manifest's order.
|
||||||
|
if !contains(ModuleTools, RestoreTool) || !contains(m.Tools, RestoreTool) {
|
||||||
|
t.Fatalf("knowledge_restore is not in the manifest and ModuleTools: %v %v", m.Tools, ModuleTools)
|
||||||
|
}
|
||||||
if watch == nil || watch["run"].([]any)[1] != "watch" || h["kind"] != "tool" || h["tool"] != HealthTool ||
|
if watch == nil || watch["run"].([]any)[1] != "watch" || h["kind"] != "tool" || h["tool"] != HealthTool ||
|
||||||
!reflect.DeepEqual(m.Tools, ModuleTools) {
|
!reflect.DeepEqual(m.Tools, ModuleTools) {
|
||||||
t.Fatalf("watch %v, tools %v", watch, m.Tools)
|
t.Fatalf("watch %v, tools %v", watch, m.Tools)
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// The restoring version (novox/hq issue 466): a version made by propose before a record kept what the served version
|
||||||
|
// held (kb.go keepServed) dropped its insights, and the fields propose does not take. The module's tool gives them
|
||||||
|
// back from the accepted versions that held them, in one version per record by the knowledge base, taken by its own
|
||||||
|
// check and not by a judgement: only what an earlier accepted version held was added, and nothing else differs.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RestoreTool is the module's tool that lists, dry-runs and runs the restoring versions.
|
||||||
|
const RestoreTool = "knowledge_restore"
|
||||||
|
|
||||||
|
// RestoredRecord is one record a restoring version was written (or would be) for.
|
||||||
|
type RestoredRecord struct {
|
||||||
|
Record string `json:"record"`
|
||||||
|
Restored []string `json:"restored"`
|
||||||
|
Version int `json:"version,omitempty"`
|
||||||
|
Skipped string `json:"skipped,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func insightKey(in Insight) string { return in.Date + "\x00" + in.By + "\x00" + in.Before }
|
||||||
|
|
||||||
|
// restoreField is one field of a record that propose does not take: how to tell it is held, and how to copy it.
|
||||||
|
type restoreField struct {
|
||||||
|
name string
|
||||||
|
has func(*Record) bool
|
||||||
|
copy func(dst, src *Record)
|
||||||
|
value func(*Record) any
|
||||||
|
clear func(*Record)
|
||||||
|
}
|
||||||
|
|
||||||
|
var restoreFields = []restoreField{
|
||||||
|
{"reconstructed", func(r *Record) bool { return r.Reconstructed != nil }, func(d, s *Record) { v := *s.Reconstructed; d.Reconstructed = &v }, func(r *Record) any { return r.Reconstructed }, func(r *Record) { r.Reconstructed = nil }},
|
||||||
|
{"amended", func(r *Record) bool { return len(r.Amended) > 0 }, func(d, s *Record) { d.Amended = append([]string(nil), s.Amended...) }, func(r *Record) any { return r.Amended }, func(r *Record) { r.Amended = nil }},
|
||||||
|
{"touches", func(r *Record) bool { return len(r.Touches) > 0 }, func(d, s *Record) { d.Touches = append([]string(nil), s.Touches...) }, func(r *Record) any { return r.Touches }, func(r *Record) { r.Touches = nil }},
|
||||||
|
{"the imported fields", func(r *Record) bool { return len(r.Extra) > 0 }, func(d, s *Record) {
|
||||||
|
d.Extra = map[string]string{}
|
||||||
|
for k, v := range s.Extra {
|
||||||
|
d.Extra[k] = v
|
||||||
|
}
|
||||||
|
}, func(r *Record) any { return r.Extra }, func(r *Record) { r.Extra = nil }},
|
||||||
|
{"source", func(r *Record) bool { return r.Source != "" }, func(d, s *Record) { d.Source = s.Source }, func(r *Record) any { return r.Source }, func(r *Record) { r.Source = "" }},
|
||||||
|
{"aliases", func(r *Record) bool { return len(r.Aliases) > 0 }, func(d, s *Record) {
|
||||||
|
d.Aliases = map[string]string{}
|
||||||
|
for k, v := range s.Aliases {
|
||||||
|
d.Aliases[k] = v
|
||||||
|
}
|
||||||
|
}, func(r *Record) any { return r.Aliases }, func(r *Record) { r.Aliases = nil }},
|
||||||
|
}
|
||||||
|
|
||||||
|
// restoreStep is a field put back and the index of the accepted version it comes from.
|
||||||
|
type restoreStep struct {
|
||||||
|
field restoreField
|
||||||
|
from int
|
||||||
|
}
|
||||||
|
|
||||||
|
// acceptedByReview says the version is one accept wrote: its why is the one accept is given by the review (review.go) or
|
||||||
|
// by the operator's Approve (operator.go). It is read from the version itself, never from the version before it: a
|
||||||
|
// mark another record's acceptance, or the recompute of marks, writes while the record waits lands between the pending
|
||||||
|
// version and the accepted one.
|
||||||
|
func acceptedByReview(v Version) bool {
|
||||||
|
return strings.HasPrefix(v.Why, "accepted after the knowledge base's review") ||
|
||||||
|
strings.HasPrefix(v.Why, "accepted on the operator's Approve after the knowledge base's review")
|
||||||
|
}
|
||||||
|
|
||||||
|
// droppedByPropose reads the accepted versions in order and finds what a version made by propose dropped: an accepted
|
||||||
|
// version that accept wrote (acceptedByReview, after propose and its reviews) and that
|
||||||
|
// lacks an insight, or a field, the accepted version before it held (a mark is a copy of the served version, so it hides nothing). A version a refresh, a form-only change or a
|
||||||
|
// recomputing of marks wrote is no such version, and what it removed is not taken back. Each entry comes from the
|
||||||
|
// accepted version just before the one that lacks it.
|
||||||
|
func droppedByPropose(versions []Version) (insights map[string]int, fields map[string]restoreStep) {
|
||||||
|
insights, fields = map[string]int{}, map[string]restoreStep{}
|
||||||
|
prev := -1
|
||||||
|
for i, v := range versions {
|
||||||
|
if v.Record == nil || v.Record.Pending != nil || !v.Record.Accepted() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if prev >= 0 && acceptedByReview(v) {
|
||||||
|
before, now := versions[prev].Record, v.Record
|
||||||
|
have := map[string]bool{}
|
||||||
|
for _, in := range now.Insights {
|
||||||
|
have[insightKey(in)] = true
|
||||||
|
}
|
||||||
|
for _, in := range before.Insights {
|
||||||
|
if !have[insightKey(in)] {
|
||||||
|
insights[insightKey(in)] = prev
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range restoreFields {
|
||||||
|
if f.has(before) && !f.has(now) {
|
||||||
|
fields[f.name] = restoreStep{f, prev}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prev = i
|
||||||
|
}
|
||||||
|
return insights, fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func versionNumber(versions []Version, i int) int {
|
||||||
|
if versions[i].N != 0 {
|
||||||
|
return versions[i].N
|
||||||
|
}
|
||||||
|
return i + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// restoredOf is the served record with what a version made by propose dropped put back, and a line for each entry
|
||||||
|
// naming the version it came from; nil when nothing is missing.
|
||||||
|
func restoredOf(served *Record, versions []Version) (*Record, []string, map[string]int) {
|
||||||
|
r := served.Clone()
|
||||||
|
dropped, fields := droppedByPropose(versions)
|
||||||
|
held := map[string]bool{}
|
||||||
|
for _, in := range served.Insights {
|
||||||
|
held[insightKey(in)] = true
|
||||||
|
}
|
||||||
|
var said []string
|
||||||
|
var added []Insight
|
||||||
|
for i, v := range versions {
|
||||||
|
if v.Record == nil || v.Record.Pending != nil || !v.Record.Accepted() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, in := range v.Record.Insights {
|
||||||
|
if from, ok := dropped[insightKey(in)]; ok && from == i && !held[insightKey(in)] {
|
||||||
|
held[insightKey(in)] = true
|
||||||
|
added = append(added, in)
|
||||||
|
said = append(said, fmt.Sprintf("insight %s by %s (version %d)", in.Date, in.By, versionNumber(versions, i)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
from := map[string]int{}
|
||||||
|
for _, f := range restoreFields {
|
||||||
|
if st, ok := fields[f.name]; ok && !f.has(served) {
|
||||||
|
f.copy(r, versions[st.from].Record)
|
||||||
|
from[f.name] = st.from
|
||||||
|
said = append(said, fmt.Sprintf("%s (version %d)", f.name, versionNumber(versions, st.from)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(said) == 0 {
|
||||||
|
return nil, nil, nil
|
||||||
|
}
|
||||||
|
r.Insights = append(append([]Insight(nil), served.Insights...), added...)
|
||||||
|
sort.SliceStable(r.Insights, func(i, j int) bool { return r.Insights[i].Date < r.Insights[j].Date })
|
||||||
|
return r, said, from
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkRestore is the restoring version's own check: every served insight is still there, each insight added is held
|
||||||
|
// by the accepted version it was taken from, each field put back is the value of that version and was empty in the
|
||||||
|
// served record, and no other field of the served record differs.
|
||||||
|
func checkRestore(served, next *Record, versions []Version, fields map[string]int) error {
|
||||||
|
have := map[string]bool{}
|
||||||
|
for _, in := range next.Insights {
|
||||||
|
have[insightKey(in)] = true
|
||||||
|
}
|
||||||
|
for _, in := range served.Insights {
|
||||||
|
if !have[insightKey(in)] {
|
||||||
|
return fmt.Errorf("the insight of %s is missing from the restored version", in.Date)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dropped, _ := droppedByPropose(versions)
|
||||||
|
serves := map[string]bool{}
|
||||||
|
for _, in := range served.Insights {
|
||||||
|
serves[insightKey(in)] = true
|
||||||
|
}
|
||||||
|
for _, in := range next.Insights {
|
||||||
|
from, ok := dropped[insightKey(in)]
|
||||||
|
if serves[insightKey(in)] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("the insight of %s was dropped by no version made by propose", in.Date)
|
||||||
|
}
|
||||||
|
held := false
|
||||||
|
for _, x := range versions[from].Record.Insights {
|
||||||
|
held = held || insightKey(x) == insightKey(in)
|
||||||
|
}
|
||||||
|
if !held {
|
||||||
|
return fmt.Errorf("the insight of %s is not held by version %d", in.Date, versionNumber(versions, from))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a, b := served.Clone(), next.Clone()
|
||||||
|
a.Insights, b.Insights = nil, nil
|
||||||
|
for _, f := range restoreFields {
|
||||||
|
i, put := fields[f.name]
|
||||||
|
if !put {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if f.has(served) || !f.has(next) {
|
||||||
|
return fmt.Errorf("%s was not empty in the served record, or was not put back", f.name)
|
||||||
|
}
|
||||||
|
got, _ := json.Marshal(f.value(next))
|
||||||
|
want, _ := json.Marshal(f.value(versions[i].Record))
|
||||||
|
if string(got) != string(want) {
|
||||||
|
return fmt.Errorf("%s is not the value version %d held", f.name, versionNumber(versions, i))
|
||||||
|
}
|
||||||
|
f.clear(b)
|
||||||
|
}
|
||||||
|
ja, _ := json.Marshal(a)
|
||||||
|
jb, _ := json.Marshal(b)
|
||||||
|
if string(ja) != string(jb) {
|
||||||
|
return fmt.Errorf("a field of the served record other than the insights and the fields put back differs")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore lists (dry), or writes, the restoring version of one record, of one kind, or of every
|
||||||
|
// record that lost something. A record with a version waiting for its review is skipped, saying so; a second run
|
||||||
|
// finds nothing to restore and writes nothing.
|
||||||
|
func (k *KB) Restore(only *Key, kind string, dry bool) ([]RestoredRecord, error) {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
ctx := context.Background()
|
||||||
|
all, err := k.Store.All(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := []RestoredRecord{}
|
||||||
|
for _, e := range all {
|
||||||
|
key := e.Current.Key()
|
||||||
|
if (only != nil && *only != key) || (kind != "" && key.Kind != kind) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if e.Current.Status == StatusReserved || e.Current.Status == StatusWithdrawn {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
versions, err := k.Store.Versions(ctx, key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: its versions cannot be read: %v", key, err)
|
||||||
|
}
|
||||||
|
next, said, fromFields := restoredOf(e.Current, versions)
|
||||||
|
if next == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
rr := RestoredRecord{Record: key.String(), Restored: said}
|
||||||
|
switch {
|
||||||
|
case e.Pending != nil:
|
||||||
|
rr.Skipped = "a version waits for its review: it is restored once that is decided"
|
||||||
|
default:
|
||||||
|
if err := checkRestore(e.Current, next, versions, fromFields); err != nil {
|
||||||
|
rr.Skipped = "the check refused it: " + err.Error()
|
||||||
|
} else if !dry {
|
||||||
|
why := "restored what a version dropped: " + strings.Join(said, "; ")
|
||||||
|
if err := k.Store.Save(ctx, Version{By: "the knowledge base", At: k.now(), Why: why, Record: next}, true, false, e.Revision); err != nil {
|
||||||
|
rr.Skipped = "it could not be written: " + err.Error()
|
||||||
|
} else {
|
||||||
|
rr.Version = e.Versions + 1
|
||||||
|
k.emit(EventChanged, next, "the knowledge base", why, e.Versions+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, rr)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 466/AC5: a record that lost an insight and a field an earlier accepted version held, in a version made by propose
|
||||||
|
// (a pending version, then an accepted one marked insight, as the old accept wrote it), gets them back in one version by
|
||||||
|
// the knowledge base; a dry run lists each entry and writes nothing; a second run writes nothing; what a refresh removed
|
||||||
|
// is not restored; a record with a version waiting for its review is skipped, saying so.
|
||||||
|
func TestRestoreGivesBackWhatAVersionDropped(t *testing.T) {
|
||||||
|
eachStore(t, func(t *testing.T, s Store) {
|
||||||
|
w := imported(t, s)
|
||||||
|
ctx := context.Background()
|
||||||
|
var tools []toolRun
|
||||||
|
for _, tool := range moduleTools(w.k, callerOf) {
|
||||||
|
tools = append(tools, toolRun{tool.Name, tool.Run})
|
||||||
|
}
|
||||||
|
// accepted is a record accepted with reconstructed: false, then given one insight by the knowledge base as it
|
||||||
|
// is now; it answers its key and the number of the version that holds them.
|
||||||
|
accepted := func(t *testing.T) (Key, int) {
|
||||||
|
n := w.reserved(t, "author@g14")
|
||||||
|
p := valid(n)
|
||||||
|
w.accepted(t, "author@g14", p)
|
||||||
|
key := Key{KindDecision, n}
|
||||||
|
e := mustGet(t, s, key)
|
||||||
|
r := e.Current.Clone()
|
||||||
|
no := false
|
||||||
|
r.Reconstructed, r.Source = &no, "hq@abc:02-DECISIONS/x.md"
|
||||||
|
if err := s.Save(ctx, Version{By: "test", At: time.Now(), Why: "seed", Record: r}, true, false, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p.Insight = "it said less"
|
||||||
|
p.Sections[2].Text = "Merges land sooner, by about a minute."
|
||||||
|
w.accepted(t, "author@g14", p)
|
||||||
|
return key, mustGet(t, s, key).Versions
|
||||||
|
}
|
||||||
|
// lose is what an older propose and accept did with a second insight: a pending version, then the accepted one
|
||||||
|
// holding only the new insight and none of the fields.
|
||||||
|
lose := func(t *testing.T, key Key, mark bool) {
|
||||||
|
e := mustGet(t, s, key)
|
||||||
|
in := Insight{Date: "2026-10-12", Before: "it said more", By: "corrector@ace"}
|
||||||
|
pend := e.Current.Clone()
|
||||||
|
pend.Status, pend.Insights, pend.Reconstructed, pend.Source = StatusProposed, nil, nil, ""
|
||||||
|
pend.Pending = &PendingState{Insight: in}
|
||||||
|
if err := s.Save(ctx, Version{By: "corrector@ace", At: time.Now(), Why: "a progressive insight proposed", Record: pend, Insight: true}, false, false, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e = mustGet(t, s, key)
|
||||||
|
if mark {
|
||||||
|
// another record's acceptance, or the recompute of marks, writes a copy of the served version while the
|
||||||
|
// insight waits.
|
||||||
|
if err := s.Save(ctx, Version{By: "the knowledge base", At: time.Now(), Why: "a mark withdrawn", Record: e.Current.Clone()}, true, false, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e = mustGet(t, s, key)
|
||||||
|
}
|
||||||
|
lost := e.Current.Clone()
|
||||||
|
lost.Insights, lost.Reconstructed, lost.Source = []Insight{in}, nil, ""
|
||||||
|
if err := s.Save(ctx, Version{By: "the knowledge base", At: time.Now(), Why: "accepted after the knowledge base's review", Record: lost, Insight: true}, true, true, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run := func(t *testing.T, key Key, args map[string]any) map[string]any {
|
||||||
|
args["kind"], args["number"] = key.Kind, float64(key.Number)
|
||||||
|
out, err := callTool(t, tools, RestoreTool, args)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
records := func(out map[string]any) []map[string]any {
|
||||||
|
var got []map[string]any
|
||||||
|
for _, r := range out["records"].([]any) {
|
||||||
|
got = append(got, r.(map[string]any))
|
||||||
|
}
|
||||||
|
return got
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, mark := range []bool{false, true} {
|
||||||
|
t.Run(fmt.Sprintf("a version made by propose dropped them (a mark between: %v)", mark), func(t *testing.T) {
|
||||||
|
key, held := accepted(t)
|
||||||
|
lose(t, key, mark)
|
||||||
|
before := mustGet(t, s, key).Versions
|
||||||
|
if mark {
|
||||||
|
held += 2 // the entries come from the mark, a copy of the served version, written after the pending version
|
||||||
|
}
|
||||||
|
want := []string{fmt.Sprintf("insight 2026-10-11 by author@g14 (version %d)", held), fmt.Sprintf("reconstructed (version %d)", held), fmt.Sprintf("source (version %d)", held)}
|
||||||
|
dry := run(t, key, map[string]any{"dry-run": true})
|
||||||
|
recs := records(dry)
|
||||||
|
if len(recs) != 1 || fmt.Sprint(recs[0]["restored"]) != fmt.Sprint(toAny(want)) || recs[0]["skipped"] != nil ||
|
||||||
|
dry["written"] != false || mustGet(t, s, key).Versions != before {
|
||||||
|
t.Fatalf("dry run: %v", dry)
|
||||||
|
}
|
||||||
|
out := run(t, key, map[string]any{})
|
||||||
|
e := mustGet(t, s, key)
|
||||||
|
in := e.Current.Insights
|
||||||
|
if out["written"] != true || out["versions-written"] != float64(1) || e.Versions != before+1 || len(in) != 2 ||
|
||||||
|
in[0].Before != "it said less" || in[0].By != "author@g14" || in[1].Before != "it said more" || in[1].By != "corrector@ace" ||
|
||||||
|
e.Current.Reconstructed == nil || *e.Current.Reconstructed || e.Current.Source == "" {
|
||||||
|
t.Fatalf("not restored: %v, %d versions (was %d), %+v", out, e.Versions, before, in)
|
||||||
|
}
|
||||||
|
if got := w.said.of(EventChanged); len(got) == 0 || got[len(got)-1]["by"] != "the knowledge base" {
|
||||||
|
t.Fatalf("no changed event by the knowledge base: %v", got)
|
||||||
|
}
|
||||||
|
again := run(t, key, map[string]any{})
|
||||||
|
if len(records(again)) != 0 || again["written"] != false || mustGet(t, s, key).Versions != before+1 {
|
||||||
|
t.Fatalf("a second run wrote: %v", again)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Run("what a refresh removed is not restored", func(t *testing.T) {
|
||||||
|
key, _ := accepted(t)
|
||||||
|
e := mustGet(t, s, key)
|
||||||
|
refreshed := e.Current.Clone()
|
||||||
|
refreshed.Reconstructed = nil
|
||||||
|
if err := s.Save(ctx, Version{By: "import@test", At: time.Now(), Why: "refreshed", Record: refreshed}, true, false, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
before := mustGet(t, s, key).Versions
|
||||||
|
out := run(t, key, map[string]any{})
|
||||||
|
if e := mustGet(t, s, key); len(records(out)) != 0 || e.Versions != before || e.Current.Reconstructed != nil {
|
||||||
|
t.Fatalf("a field a refresh removed was put back: %v", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a record with a version waiting is skipped, and says so", func(t *testing.T) {
|
||||||
|
key, _ := accepted(t)
|
||||||
|
lose(t, key, false)
|
||||||
|
p := insightTo(t, w, key)
|
||||||
|
p.Insight = "it said nothing of the day"
|
||||||
|
if _, err := w.k.Propose("author@g14", p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
before := mustGet(t, s, key).Versions
|
||||||
|
out := run(t, key, map[string]any{})
|
||||||
|
recs := records(out)
|
||||||
|
if len(recs) != 1 || !strings.Contains(fmt.Sprint(recs[0]["skipped"]), "waits for its review") ||
|
||||||
|
out["written"] != false || mustGet(t, s, key).Versions != before {
|
||||||
|
t.Fatalf("a record with a version waiting: %v", out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func toAny(list []string) []any {
|
||||||
|
out := make([]any, len(list))
|
||||||
|
for i, s := range list {
|
||||||
|
out[i] = s
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -349,49 +349,86 @@ func TestTheOperatorsDeclineLeavesTheRecordProposed(t *testing.T) {
|
|||||||
// An accepted record changes only by a progressive insight, which is reviewed like a proposal while the accepted
|
// An accepted record changes only by a progressive insight, which is reviewed like a proposal while the accepted
|
||||||
// version is served.
|
// version is served.
|
||||||
func TestAnAcceptedRecordChangesOnlyByAnInsightReviewedLikeAProposal(t *testing.T) {
|
func TestAnAcceptedRecordChangesOnlyByAnInsightReviewedLikeAProposal(t *testing.T) {
|
||||||
w := imported(t, newMemStore())
|
eachStore(t, func(t *testing.T, s Store) {
|
||||||
n := w.reserved(t, "author@g14")
|
w := imported(t, s)
|
||||||
w.accepted(t, "author@g14", valid(n))
|
n := w.reserved(t, "author@g14")
|
||||||
p := valid(n)
|
w.accepted(t, "author@g14", valid(n))
|
||||||
p.Sections[2].Text = "Merges land sooner, by about a minute."
|
p := valid(n)
|
||||||
if _, err := w.k.Propose("author@g14", p); err == nil || !strings.Contains(err.Error(), "progressive insight") {
|
p.Sections[2].Text = "Merges land sooner, by about a minute."
|
||||||
t.Fatalf("an accepted record rewritten: %v", err)
|
if _, err := w.k.Propose("author@g14", p); err == nil || !strings.Contains(err.Error(), "progressive insight") {
|
||||||
}
|
t.Fatalf("an accepted record rewritten: %v", err)
|
||||||
p.Insight = "it said only that merges land sooner"
|
}
|
||||||
w.judge.review = `{"verdict":"changes","findings":["Consequences: say what a minute is measured from"]}`
|
p.Insight = "it said only that merges land sooner"
|
||||||
if _, err := w.k.Propose("author@g14", p); err != nil {
|
w.judge.review = `{"verdict":"changes","findings":["Consequences: say what a minute is measured from"]}`
|
||||||
t.Fatal(err)
|
if _, err := w.k.Propose("author@g14", p); err != nil {
|
||||||
}
|
t.Fatal(err)
|
||||||
w.reviewAll(t)
|
}
|
||||||
e := mustGet(t, w.k.Store, Key{KindDecision, n})
|
w.reviewAll(t)
|
||||||
if e.Pending == nil || e.Current.Section("Consequences") != "Merges land sooner." || len(e.Pending.Reviews) != 1 ||
|
e := mustGet(t, w.k.Store, Key{KindDecision, n})
|
||||||
e.Pending.Reviews[0].Verdict != VerdictChanges {
|
if e.Pending == nil || e.Current.Section("Consequences") != "Merges land sooner." || len(e.Pending.Reviews) != 1 ||
|
||||||
t.Fatalf("the insight was served before its review approved it: %+v", e.Current.Sections)
|
e.Pending.Reviews[0].Verdict != VerdictChanges {
|
||||||
}
|
t.Fatalf("the insight was served before its review approved it: %+v", e.Current.Sections)
|
||||||
// 1970/AC2: the same for a pending insight.
|
}
|
||||||
g, err := w.k.Get(GetAsk{Kind: KindDecision, Number: n})
|
// 1970/AC2: the same for a pending insight.
|
||||||
if err != nil {
|
g, err := w.k.Get(GetAsk{Kind: KindDecision, Number: n})
|
||||||
t.Fatal(err)
|
if err != nil {
|
||||||
}
|
t.Fatal(err)
|
||||||
if len(g.PendingReviews) != 1 || !strings.Contains(g.PendingReviews[0].Findings, "what a minute is measured from") ||
|
}
|
||||||
!strings.Contains(g.Pending, "changes asked") {
|
if len(g.PendingReviews) != 1 || !strings.Contains(g.PendingReviews[0].Findings, "what a minute is measured from") ||
|
||||||
t.Fatalf("pending insight findings not shown: %+v, %q", g.PendingReviews, g.Pending)
|
!strings.Contains(g.Pending, "changes asked") {
|
||||||
}
|
t.Fatalf("pending insight findings not shown: %+v, %q", g.PendingReviews, g.Pending)
|
||||||
w.judge.review = ""
|
}
|
||||||
p.Sections[2].Text = "Merges land sooner, by about a minute from the last merge."
|
w.judge.review = ""
|
||||||
if _, err := w.k.Propose("author@g14", p); err != nil {
|
p.Sections[2].Text = "Merges land sooner, by about a minute from the last merge."
|
||||||
t.Fatal(err)
|
if _, err := w.k.Propose("author@g14", p); err != nil {
|
||||||
}
|
t.Fatal(err)
|
||||||
w.reviewAll(t)
|
}
|
||||||
e = mustGet(t, w.k.Store, Key{KindDecision, n})
|
w.reviewAll(t)
|
||||||
if e.Pending != nil || e.Current.Status != StatusAccepted || len(e.Current.Insights) != 1 ||
|
e = mustGet(t, w.k.Store, Key{KindDecision, n})
|
||||||
e.Current.Section("Consequences") != p.Sections[2].Text {
|
if e.Pending != nil || e.Current.Status != StatusAccepted || len(e.Current.Insights) != 1 ||
|
||||||
t.Fatalf("after the insight's review: %+v", e.Current)
|
e.Current.Section("Consequences") != p.Sections[2].Text {
|
||||||
}
|
t.Fatalf("after the insight's review: %+v", e.Current)
|
||||||
// 0276 §1 was changed once, by the acceptance; the insight keeps the link and changes it no further.
|
}
|
||||||
if c := mustGet(t, w.k.Store, Key{KindDecision, 276}).Current.Clause(1); len(c.ChangedBy) != 1 {
|
// 0276 §1 was changed once, by the acceptance; the insight keeps the link and changes it no further.
|
||||||
t.Fatalf("0276 §1 changed again by an insight: %v", c.ChangedBy)
|
if c := mustGet(t, w.k.Store, Key{KindDecision, 276}).Current.Clause(1); len(c.ChangedBy) != 1 {
|
||||||
}
|
t.Fatalf("0276 §1 changed again by an insight: %v", c.ChangedBy)
|
||||||
|
}
|
||||||
|
// 466/AC1: a second insight, by another author on another day, adds to the first and replaces nothing; the
|
||||||
|
// pending version already holds the first, and history between the two accepted versions shows only the second added.
|
||||||
|
first := mustGet(t, w.k.Store, Key{KindDecision, n}).Versions
|
||||||
|
w.clock = w.clock.AddDate(0, 0, 1)
|
||||||
|
p.Insight = "it said only a minute"
|
||||||
|
p.Sections[2].Text = "Merges land sooner, by about a minute from the last merge, as measured."
|
||||||
|
if _, err := w.k.Propose("corrector@ace", p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if e = mustGet(t, w.k.Store, Key{KindDecision, n}); e.Pending == nil || len(e.Pending.Insights) != 1 {
|
||||||
|
t.Fatalf("the pending version does not hold the earlier insight: %+v", e.Pending)
|
||||||
|
}
|
||||||
|
w.reviewAll(t)
|
||||||
|
e = mustGet(t, w.k.Store, Key{KindDecision, n})
|
||||||
|
in := e.Current.Insights
|
||||||
|
if len(in) != 2 || in[0].Before != "it said only that merges land sooner" || in[0].By != "author@g14" || in[0].Date != "2026-10-11" ||
|
||||||
|
in[1].Before != "it said only a minute" || in[1].By != "corrector@ace" || in[1].Date != "2026-10-12" {
|
||||||
|
t.Fatalf("a second insight did not add to the first: %+v", in)
|
||||||
|
}
|
||||||
|
h, err := w.k.History(Key{KindDecision, n}, first, e.Versions, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var added, removed []string
|
||||||
|
for _, l := range h.Diff {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(l, "+insight "):
|
||||||
|
added = append(added, l)
|
||||||
|
case strings.HasPrefix(l, "-insight "):
|
||||||
|
removed = append(removed, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(added) != 1 || !strings.Contains(added[0], "2026-10-12") || len(removed) != 0 {
|
||||||
|
t.Fatalf("history between the accepted versions: added %v, removed %v\n%v", added, removed, h.Diff)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// No verb takes a review from anyone: the review is the knowledge base's own.
|
// No verb takes a review from anyone: the review is the knowledge base's own.
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ package main
|
|||||||
|
|
||||||
// The rules a record is held to (novox/hq ADR 0290 rule 4, to-be 55 §4 and §5).
|
// The rules a record is held to (novox/hq ADR 0290 rule 4, to-be 55 §4 and §5).
|
||||||
//
|
//
|
||||||
// **31 rules judge one record or its prose**, and `propose` refuses a record that breaks any of them, naming every
|
// **32 rules judge one record or its prose**, and `propose` refuses a record that breaks any of them, naming every
|
||||||
// one it breaks at once. They are hq's checks (00-META/checks/records.py, cycle.py, index.py, words.py) as they
|
// one it breaks at once. They are hq's checks (00-META/checks/records.py, cycle.py, index.py, words.py) as they
|
||||||
// judge one record, moved to the write: 25 on its structure, 4 on its prose; and the brief a record that needs
|
// judge one record, moved to the write: 25 on its structure, 4 on its prose; the brief a record that needs
|
||||||
// the operator is asked with (novox/hq issue 639). Each has an id, said in the refusal,
|
// the operator is asked with (novox/hq issue 639); the form of a section (section-form); and the links of a
|
||||||
|
// progressive insight (insight-links, novox/hq issue 466). Each has an id, said in the refusal,
|
||||||
// and one case in the table test (TestEveryPerRecordRuleRefusesAProposal).
|
// and one case in the table test (TestEveryPerRecordRuleRefusesAProposal).
|
||||||
//
|
//
|
||||||
// **4 rules judge the whole record set** (wholeSetRules) and run after every acceptance, and in the check
|
// **4 rules judge the whole record set** (wholeSetRules) and run after every acceptance, and in the check
|
||||||
@@ -28,7 +29,7 @@ type Rule struct {
|
|||||||
From string
|
From string
|
||||||
}
|
}
|
||||||
|
|
||||||
// PerRecordRules are the 31, in the order they are judged.
|
// PerRecordRules are the 32, in the order they are judged.
|
||||||
var PerRecordRules = []Rule{
|
var PerRecordRules = []Rule{
|
||||||
{"kind", "a record is a decision or a research effort", "cycle.py"},
|
{"kind", "a record is a decision or a research effort", "cycle.py"},
|
||||||
{"reserved", "its number was reserved for its kind and holds no other record", "cycle.py (duplicate numbers)"},
|
{"reserved", "its number was reserved for its kind and holds no other record", "cycle.py (duplicate numbers)"},
|
||||||
@@ -61,6 +62,7 @@ var PerRecordRules = []Rule{
|
|||||||
{"insight-form", "a progressive insight its text mentions is in the dated, marked form", "records.py insights"},
|
{"insight-form", "a progressive insight its text mentions is in the dated, marked form", "records.py insights"},
|
||||||
{"brief", "a record that needs the operator carries a brief its ask reads at a glance: a headline, a summary, at most three points, each fit for the phone", "novox/hq issue 639"},
|
{"brief", "a record that needs the operator carries a brief its ask reads at a glance: a headline, a summary, at most three points, each fit for the phone", "novox/hq issue 639"},
|
||||||
{"section-form", "a section is a part with a plain title, once in the record, and its text holds no local path, no file and line, and no link to a file", "to-be 55 §2.2"},
|
{"section-form", "a section is a part with a plain title, once in the record, and its text holds no local path, no file and line, and no link to a file", "to-be 55 §2.2"},
|
||||||
|
{"insight-links", "a progressive insight keeps exactly the accepted record's supersedes and changes links (it may add cites): changing which records a decision supersedes or changes is a new record", "novox/hq issue 466"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refusal is one rule a record breaks, and how.
|
// Refusal is one rule a record breaks, and how.
|
||||||
@@ -121,7 +123,7 @@ func allText(r *Record) string {
|
|||||||
return b.String()
|
return b.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// JudgeRecord holds a proposed record to the 31 rules. held is the entry its number holds (a reservation, the
|
// JudgeRecord holds a proposed record to the 32 rules. held is the entry its number holds (a reservation, the
|
||||||
// proposal being revised, or the accepted record an insight corrects); lookup reads every other record.
|
// proposal being revised, or the accepted record an insight corrects); lookup reads every other record.
|
||||||
func JudgeRecord(r *Record, held *Entry, lookup Lookup, ref *Reference) []Refusal {
|
func JudgeRecord(r *Record, held *Entry, lookup Lookup, ref *Reference) []Refusal {
|
||||||
return JudgeRecordOn(r, held, lookup, ref, r.Date)
|
return JudgeRecordOn(r, held, lookup, ref, r.Date)
|
||||||
@@ -295,6 +297,23 @@ func JudgeRecordOn(r *Record, held *Entry, lookup Lookup, ref *Reference, day st
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if held != nil && held.Current.Accepted() && r.IsInsight() {
|
||||||
|
var changed []string
|
||||||
|
for _, l := range r.Links {
|
||||||
|
if (l.Kind == LinkSupersedes || l.Kind == LinkChanges) && !hasLink(held.Current, l) {
|
||||||
|
changed = append(changed, fmt.Sprintf("added %s", l))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, l := range held.Current.Links {
|
||||||
|
if (l.Kind == LinkSupersedes || l.Kind == LinkChanges) && !hasLink(r, l) {
|
||||||
|
changed = append(changed, fmt.Sprintf("dropped %s", l))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(changed) > 0 {
|
||||||
|
refuse("insight-links", "a progressive insight corrects a fact and leaves the decision standing, so it keeps the supersedes and changes links of the accepted record (%s); "+
|
||||||
|
"changing what a record supersedes or changes is a new record: write one", strings.Join(changed, ", "))
|
||||||
|
}
|
||||||
|
}
|
||||||
if r.Kind == KindResearch && r.Effort == StatusGraduated {
|
if r.Kind == KindResearch && r.Effort == StatusGraduated {
|
||||||
became := false
|
became := false
|
||||||
for _, l := range r.Links {
|
for _, l := range r.Links {
|
||||||
|
|||||||
@@ -96,6 +96,47 @@ func TestEveryPerRecordRuleRefusesAProposal(t *testing.T) {
|
|||||||
{"brief", func(p *ProposeAsk, w *world, t *testing.T) {
|
{"brief", func(p *ProposeAsk, w *world, t *testing.T) {
|
||||||
p.Date, p.NeedsOperator = "2026-10-13", true
|
p.Date, p.NeedsOperator = "2026-10-13", true
|
||||||
}},
|
}},
|
||||||
|
{"insight-links", func(p *ProposeAsk, w *world, t *testing.T) {
|
||||||
|
// 466/AC4: an accepted record holding a supersedes and a changes link; an insight that drops the
|
||||||
|
// supersedes or adds a changes is refused, each link named and a new record asked for; one that adds a
|
||||||
|
// cites link is taken.
|
||||||
|
base := *p
|
||||||
|
base.Links = append(append([]LinkAsk(nil), p.Links...), LinkAsk{Kind: LinkSupersedes, To: "0162"})
|
||||||
|
w.accepted(t, "author@test", base)
|
||||||
|
insight := func(links ...LinkAsk) ProposeAsk {
|
||||||
|
q := base
|
||||||
|
q.Insight = "it said the clause stood"
|
||||||
|
q.Links = links
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
kept := base.Links
|
||||||
|
cites := insight(append(append([]LinkAsk(nil), kept...), LinkAsk{Kind: LinkCites, To: "0011"})...)
|
||||||
|
if _, err := w.k.Propose("author@test", cites); err != nil {
|
||||||
|
t.Fatalf("an insight adding a cites link was refused: %v", err)
|
||||||
|
}
|
||||||
|
dropped := insight(kept[:2]...)
|
||||||
|
added := insight(append(append([]LinkAsk(nil), kept...), LinkAsk{Kind: LinkChanges, To: "0240 §1", From: 2})...)
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
ask ProposeAsk
|
||||||
|
says []string
|
||||||
|
not string
|
||||||
|
}{
|
||||||
|
{"dropping the supersedes", dropped, []string{"dropped supersedes ADR 0162", "write one"}, "added"},
|
||||||
|
{"adding a changes", added, []string{"added §2 changes ADR 0240 §1", "write one"}, "dropped"},
|
||||||
|
} {
|
||||||
|
_, err := w.k.Propose("author@test", c.ask)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "- insight-links:") || strings.Contains(err.Error(), c.not) {
|
||||||
|
t.Fatalf("%s: %v", c.name, err)
|
||||||
|
}
|
||||||
|
for _, says := range c.says {
|
||||||
|
if !strings.Contains(err.Error(), says) {
|
||||||
|
t.Fatalf("%s: the refusal does not say %q: %v", c.name, says, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*p = dropped
|
||||||
|
}},
|
||||||
{"section-form", func(p *ProposeAsk, w *world, t *testing.T) {
|
{"section-form", func(p *ProposeAsk, w *world, t *testing.T) {
|
||||||
p.Date, p.Sections[0].Name = "2026-11-04", "00-context.md"
|
p.Date, p.Sections[0].Name = "2026-11-04", "00-context.md"
|
||||||
}},
|
}},
|
||||||
@@ -109,8 +150,8 @@ func TestEveryPerRecordRuleRefusesAProposal(t *testing.T) {
|
|||||||
t.Errorf("the rule %s has no case", r.ID)
|
t.Errorf("the rule %s has no case", r.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(PerRecordRules) != 31 {
|
if len(PerRecordRules) != 32 {
|
||||||
t.Errorf("%d per-record rules; ADR 0290 counts 29, issue 639 adds the brief and to-be 55 §2.2 the form of a section", len(PerRecordRules))
|
t.Errorf("%d per-record rules; ADR 0290 counts 29, issue 639 adds the brief, to-be 55 §2.2 the form of a section and issue 466 the links of an insight", len(PerRecordRules))
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
t.Run(c.rule, func(t *testing.T) {
|
t.Run(c.rule, func(t *testing.T) {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ const (
|
|||||||
|
|
||||||
// ModuleTools are the module's own tools beside the health tool, in the order the manifest lists them.
|
// ModuleTools are the module's own tools beside the health tool, in the order the manifest lists them.
|
||||||
var ModuleTools = []string{HealthTool, HighestTool, MarksTool, HeadTool, OperationsTool, SectionTool, DraftTool, PartsTool,
|
var ModuleTools = []string{HealthTool, HighestTool, MarksTool, HeadTool, OperationsTool, SectionTool, DraftTool, PartsTool,
|
||||||
AskedTool, FillTool, IndexTool, AgainTool, IntegrityTool, FormTool, MoveTool, MoveCheckTool, OverviewTool, RereadTool}
|
AskedTool, FillTool, IndexTool, AgainTool, IntegrityTool, FormTool, MoveTool, MoveCheckTool, OverviewTool, RereadTool, RestoreTool}
|
||||||
|
|
||||||
var errNotOnLedger = errors.New("the records are still in the database: this tool reads the ledger, which serves them after the move")
|
var errNotOnLedger = errors.New("the records are still in the database: this tool reads the ledger, which serves them after the move")
|
||||||
|
|
||||||
@@ -440,6 +440,48 @@ func moduleTools(k *KB, caller func(map[string]any) string) []stdio.Tool {
|
|||||||
}
|
}
|
||||||
return map[string]any{"source": ms.Source(), "differences": diffs, "clean": len(diffs) == 0}, nil
|
return map[string]any{"source": ms.Source(), "differences": diffs, "clean": len(diffs) == 0}, nil
|
||||||
}},
|
}},
|
||||||
|
{Name: RestoreTool,
|
||||||
|
Description: "List, or write, the restoring versions: a record whose served version lacks a progressive insight, or a field an imported record had " +
|
||||||
|
"(reconstructed, amended, touches, the imported fields, source, aliases), that a version made by propose dropped (an accepted version that lacks what the accepted version " +
|
||||||
|
"before it held; what a refresh, a form-only version or a mark removed is not restored), gets one version by the knowledge base that puts them back, " +
|
||||||
|
"insights in date order each with its own date and author. A check proves only entries the version before the drop held were added; no judgement runs. " +
|
||||||
|
"With dry-run nothing is written. A record with a version waiting for its review is skipped, and the answer names it as skipped. " +
|
||||||
|
"Takes one record, one kind or every record; a second run writes nothing.",
|
||||||
|
Input: schema(nil, map[string]any{"kind": kindArg(), "number": integer("one record; every record that lost something when absent"), "dry-run": flag("list and write nothing")}),
|
||||||
|
Run: func(m map[string]any) (any, error) {
|
||||||
|
a, err := readArgs(RestoreTool, m, "kind", "number", "dry-run")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var only *Key
|
||||||
|
kind := ""
|
||||||
|
if _, has := m["number"]; has {
|
||||||
|
key, err := a.key()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
only = &key
|
||||||
|
} else if kind, err = a.str("kind"); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if kind != "" && !contains(Kinds, kind) {
|
||||||
|
return nil, fmt.Errorf("kind is decision or research, not %q", kind)
|
||||||
|
}
|
||||||
|
dry, err := a.flag("dry-run")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
done, err := k.Restore(only, kind, dry)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
wrote := 0
|
||||||
|
for _, d := range done {
|
||||||
|
if d.Version > 0 {
|
||||||
|
wrote++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map[string]any{"records": done, "versions-written": wrote, "written": wrote > 0}, nil
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ func TestEveryStateTheModuleKeepsHasAToolThatReadsIt(t *testing.T) {
|
|||||||
if _, err := callTool(t, tools, MoveCheckTool, map[string]any{}); err == nil {
|
if _, err := callTool(t, tools, MoveCheckTool, map[string]any{}); err == nil {
|
||||||
t.Fatal("a move check without a database")
|
t.Fatal("a move check without a database")
|
||||||
}
|
}
|
||||||
if len(ModuleTools) != 18 {
|
if len(ModuleTools) != 19 {
|
||||||
t.Fatalf("%v", ModuleTools)
|
t.Fatalf("%v", ModuleTools)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A decision nothing would cite is not accepted: its review asks changes itself, without a judgement, naming the
|
// A decision nothing would cite is not accepted: its review asks changes itself, without a judgement, naming the
|
||||||
@@ -130,7 +131,20 @@ func TestACorrectionThatDropsAChangesLinkWithdrawsTheClausesMark(t *testing.T) {
|
|||||||
}
|
}
|
||||||
a.Links = a.Links[:1] // only extends 0276 now
|
a.Links = a.Links[:1] // only extends 0276 now
|
||||||
a.Insight = "it no longer changes 0276 §1"
|
a.Insight = "it no longer changes 0276 §1"
|
||||||
w.accepted(t, "author@g14", a)
|
// 466/AC4: an insight no longer drops a changes link; a version that did (made before the rule) is written
|
||||||
|
// directly, and its mark is withdrawn.
|
||||||
|
if _, err := w.k.Propose("author@g14", a); err == nil || !strings.Contains(err.Error(), "- insight-links:") {
|
||||||
|
t.Fatalf("an insight dropping a changes link was taken: %v", err)
|
||||||
|
}
|
||||||
|
e := mustGet(t, s, Key{KindDecision, n})
|
||||||
|
r := e.Current.Clone()
|
||||||
|
r.Links = r.Links[:1]
|
||||||
|
if err := s.Save(context.Background(), Version{By: "test", At: time.Now(), Why: "an older insight", Record: r}, true, true, e.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := w.k.RecomputeMarks(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
c := mustGet(t, s, Key{KindDecision, 276}).Current.Clause(1)
|
c := mustGet(t, s, Key{KindDecision, 276}).Current.Clause(1)
|
||||||
if c.Status != ClauseInForce || len(c.ChangedBy) != 0 {
|
if c.Status != ClauseInForce || len(c.ChangedBy) != 0 {
|
||||||
t.Fatalf("0276 §1 keeps a mark no accepted link makes: %+v", c)
|
t.Fatalf("0276 §1 keeps a mark no accepted link makes: %+v", c)
|
||||||
|
|||||||
@@ -188,7 +188,8 @@
|
|||||||
"knowledge_move",
|
"knowledge_move",
|
||||||
"knowledge_move_check",
|
"knowledge_move_check",
|
||||||
"knowledge_overview",
|
"knowledge_overview",
|
||||||
"knowledge_overview_reread"
|
"knowledge_overview_reread",
|
||||||
|
"knowledge_restore"
|
||||||
],
|
],
|
||||||
"emits": [
|
"emits": [
|
||||||
"reserved",
|
"reserved",
|
||||||
|
|||||||
@@ -1738,13 +1738,39 @@ func (w watchingStore) copied(state string) bool {
|
|||||||
return slices.Contains(WatchedReads, state) || slices.Contains(OwnStates, state)
|
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) {
|
func (w watchingStore) Get(state, key string) (*Entry, error) {
|
||||||
get := w.ws.Get
|
if !w.copied(state) {
|
||||||
switch {
|
|
||||||
case !w.copied(state):
|
|
||||||
return w.Store.Get(state, key)
|
return w.Store.Get(state, key)
|
||||||
}
|
}
|
||||||
v, found, err := get(state, key)
|
v, found, err := w.ws.Get(state, key)
|
||||||
if err != nil || !found {
|
if err != nil || !found {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -203,6 +203,10 @@ func TestTheHolderPlansProvidesAndAsksOnTheBus(t *testing.T) {
|
|||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
key := node + ".restic.postgres-database"
|
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 {
|
if _, err := h.ComposeNode(ctx, node); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import (
|
|||||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||||
"git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient"
|
"git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
"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 })
|
}, func(string, string) ([]byte, bool, error) { return nil, false, nil })
|
||||||
m.h.Store = Watching(bus, ws)
|
m.h.Store = Watching(bus, ws)
|
||||||
wk := &work{pending: map[string]bool{}, wake: make(chan struct{}, 1)}
|
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} {
|
for _, r := range []string{ComposedRead, HaveRead} {
|
||||||
ws.Follow(r, func(c stdio.StateChange) error { wk.add(NodesOfNodeKey(c.Key)...); return nil })
|
ws.Follow(r, func(c stdio.StateChange) error { wk.add(NodesOfNodeKey(c.Key)...); return nil })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,6 +79,9 @@ func holderTools(h *Holder) []stdio.Tool {
|
|||||||
if arg(a, "node") == "" {
|
if arg(a, "node") == "" {
|
||||||
return nil, fmt.Errorf("compose names the node")
|
return nil, fmt.Errorf("compose names the node")
|
||||||
}
|
}
|
||||||
|
if err := h.Away(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
many, _ := a["retire-many"].(bool)
|
many, _ := a["retire-many"].(bool)
|
||||||
return h.ComposeNodeWith(context.Background(), arg(a, "node"), many)
|
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.
|
// 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) {
|
func (h *Holder) read(state, key, node, want string) (any, error) {
|
||||||
|
if err := h.Away(state); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if key != "" {
|
if key != "" {
|
||||||
e, err := h.Store.Get(state, key)
|
e, err := h.Store.Get(state, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user