Compare commits
392
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0102fc95c5 | ||
|
|
3ad4e78c11 | ||
|
|
56296ccc43 | ||
|
|
8101731ebc | ||
|
|
f04f4d4128 | ||
|
|
c98e92afae | ||
|
|
50945e9b9a | ||
|
|
ec21db3158 | ||
|
|
74f280b843 | ||
|
|
abd2e6e50f | ||
|
|
465a6d4cd9 | ||
|
|
f3d678d88d | ||
|
|
da551f530a | ||
|
|
5e25feee3a | ||
|
|
b77cdf1513 | ||
|
|
39f78836d2 | ||
|
|
781108b07e | ||
|
|
c9599c8b82 | ||
|
|
b371f980d5 | ||
|
|
3ab7943882 | ||
|
|
e296f57489 | ||
|
|
bd655b28c5 | ||
|
|
e061c319f1 | ||
|
|
e06c204af3 | ||
|
|
896b0e1f75 | ||
|
|
613e89c8e3 | ||
|
|
e8f398be64 | ||
|
|
f4a9ea5e3f | ||
|
|
30817f1f39 | ||
|
|
dc3986313f | ||
|
|
3fe271acf3 | ||
|
|
f9232d5e60 | ||
|
|
bfefd71b4c | ||
|
|
3089814382 | ||
|
|
16dc5a0bd0 | ||
|
|
6e75c4198a | ||
|
|
ae12fa5988 | ||
|
|
016e2e94d7 | ||
|
|
b2f3b2e2d3 | ||
|
|
a16654e248 | ||
|
|
9141bd514a | ||
|
|
0c3c930979 | ||
|
|
0941bd6d09 | ||
|
|
388626ac82 | ||
|
|
3c9be07489 | ||
|
|
5162465293 | ||
|
|
83cbf2e464 | ||
|
|
b44a9ee1dc | ||
|
|
499bb15eae | ||
|
|
aea1e6129c | ||
|
|
4eae3d6847 | ||
|
|
ca4735f35f | ||
|
|
aef199cb83 | ||
|
|
f05fb8ab55 | ||
|
|
79c0bf8e90 | ||
|
|
45c9d20baf | ||
|
|
8371945725 | ||
|
|
b5e3b94489 | ||
|
|
891256f413 | ||
|
|
a90572e297 | ||
|
|
cecf4142e6 | ||
|
|
d36511022f | ||
|
|
6f21579887 | ||
|
|
21370394d7 | ||
|
|
bcd6ac4e60 | ||
|
|
ff22c20d66 | ||
|
|
a807a4511e | ||
|
|
e706f2577e | ||
|
|
2aadb3f08b | ||
|
|
5717fd5036 | ||
|
|
ad56d96bc4 | ||
|
|
982a059e42 | ||
|
|
64a27c2cab | ||
|
|
b87689e990 | ||
|
|
2dc707782f | ||
|
|
2f8571cb6b | ||
|
|
5a855b9d84 | ||
|
|
9e08d230e7 | ||
|
|
0049f591c5 | ||
|
|
587bda939e | ||
|
|
642564629a | ||
|
|
b423f14c4c | ||
|
|
4aeba1e9ea | ||
|
|
3775523cb9 | ||
|
|
cc9d7cbe06 | ||
|
|
65c0f748e6 | ||
|
|
fa8a248c9f | ||
|
|
e6ad987a6d | ||
|
|
220a72aaae | ||
|
|
ab8623cda7 | ||
|
|
56cfc9027d | ||
|
|
b85d463f66 | ||
|
|
14df4c6906 | ||
|
|
55265b0753 | ||
|
|
7bb1a147b5 | ||
|
|
4afacfe5b2 | ||
|
|
788b57a164 | ||
|
|
dc7258af0c | ||
|
|
ca220cb0da | ||
|
|
08515e2706 | ||
|
|
8826604016 | ||
|
|
7614f74414 | ||
|
|
f6c8fa46e0 | ||
|
|
1f88ce7a24 | ||
|
|
82b0a0f26c | ||
|
|
c8d5b64004 | ||
|
|
ec00d887c0 | ||
|
|
250713ecf4 | ||
|
|
6f5eb7f2a7 | ||
|
|
dd0cdf2f8e | ||
|
|
c41168ff34 | ||
|
|
64b3445ee3 | ||
|
|
a75bd951a7 | ||
|
|
d3e5ecb910 | ||
|
|
c2d2877fc4 | ||
|
|
b96c3f1bd8 | ||
|
|
d4f9fd013d | ||
|
|
4c129749b0 | ||
|
|
49505af6ca | ||
|
|
a28caf25f6 | ||
|
|
8c5445d1e2 | ||
|
|
d5ddc3a302 | ||
|
|
530f6c9204 | ||
|
|
e37d2ba71d | ||
|
|
602a9e0157 | ||
|
|
13461ecb70 | ||
|
|
80218cf378 | ||
|
|
76212a0d4d | ||
|
|
63b44f8c37 | ||
|
|
6fb40eac2f | ||
|
|
ca04a5acbe | ||
|
|
02a0426fbe | ||
|
|
e328543706 | ||
|
|
a9ca7cfc3e | ||
|
|
388526b9e8 | ||
|
|
e32824be26 | ||
|
|
b636ccdf7f | ||
|
|
18e5be507d | ||
|
|
c7b137863e | ||
|
|
419bf9734a | ||
|
|
2bc0f27282 | ||
|
|
c452f2cc07 | ||
|
|
a37d32d5e0 | ||
|
|
070f62ceca | ||
|
|
ed846d58ab | ||
|
|
48003b3f4f | ||
|
|
3f80b4e02f | ||
|
|
c27393fb5e | ||
|
|
3b11d7a38d | ||
|
|
5e9fd3bd28 | ||
|
|
249e4b3466 | ||
|
|
41047c69f2 | ||
|
|
ac9711c532 | ||
|
|
6ae3c4582e | ||
|
|
9ac80923da | ||
|
|
43d83c3a30 | ||
|
|
9907de906d | ||
|
|
78813b0bcf | ||
|
|
7fead3b364 | ||
|
|
48038105fc | ||
|
|
675360751e | ||
|
|
602aeadec0 | ||
|
|
3dc67f4dc8 | ||
|
|
697716ca48 | ||
|
|
f77d6d76e1 | ||
|
|
b0ef5ef6e4 | ||
|
|
88bdd4bd33 | ||
|
|
bbbcf9f148 | ||
|
|
cc607f38e6 | ||
|
|
861c753f96 | ||
|
|
7b983a6afe | ||
|
|
87e7912220 | ||
|
|
52f716741e | ||
|
|
584e04682d | ||
|
|
dfc675cf00 | ||
|
|
64398c792b | ||
|
|
1b4d7e5c8d | ||
|
|
72ef5dc7c4 | ||
|
|
5922da0a92 | ||
|
|
f1f2d352e5 | ||
|
|
4f8e850512 | ||
|
|
9b264704f9 | ||
|
|
fd4d28badb | ||
|
|
382145eddc | ||
|
|
a84db91177 | ||
|
|
c7c65556db | ||
|
|
c9de0c6245 | ||
|
|
69ed0d95f4 | ||
|
|
db3e853cb7 | ||
|
|
0a3eb550eb | ||
|
|
d9f733318c | ||
|
|
b24dd11ff4 | ||
|
|
3bb8413dbd | ||
|
|
43f2ebc4ba | ||
|
|
d77bff56c4 | ||
|
|
61a6811cd5 | ||
|
|
bcf170a003 | ||
|
|
df890b8a7c | ||
|
|
336d2abaa8 | ||
|
|
13eccb33b3 | ||
|
|
04d912b5c8 | ||
|
|
cb8046c355 | ||
|
|
94afdcb6b4 | ||
|
|
c87d5fe6ab | ||
|
|
7f67e209e6 | ||
|
|
b7a3d85514 | ||
|
|
dd78f05b56 | ||
|
|
ca91d4e85b | ||
|
|
7401951a86 | ||
|
|
3baef9df5b | ||
|
|
8f36311d08 | ||
|
|
d4ea1f3445 | ||
|
|
b0d915f6d0 | ||
|
|
2eccf99693 | ||
|
|
af5a7e5870 | ||
|
|
34c5cc9079 | ||
|
|
05dcdf4bf5 | ||
|
|
c0b3fc4138 | ||
|
|
b79b3a6300 | ||
|
|
d8f0d4b1fb | ||
|
|
9dfc0dc4cc | ||
|
|
9f09149362 | ||
|
|
152af6dd29 | ||
|
|
c04e5e364c | ||
|
|
6af989cece | ||
|
|
1d0b2d3e07 | ||
|
|
fdfe2db0f3 | ||
|
|
a58daa9cf7 | ||
|
|
b7dc1dc3e1 | ||
|
|
661203451f | ||
|
|
de7110032b | ||
|
|
0239cf3ac4 | ||
|
|
13485c371e | ||
|
|
899d6ac0e3 | ||
|
|
13c9fb430e | ||
|
|
354e943d24 | ||
|
|
423d06faac | ||
|
|
14208c808c | ||
|
|
81bf6c7cc9 | ||
|
|
e0f69f73d3 | ||
|
|
25e9d71e19 | ||
|
|
19f8f6b637 | ||
|
|
dc6669f768 | ||
|
|
6dc9164504 | ||
|
|
f3e68c6646 | ||
|
|
8865d61bec | ||
|
|
c8f9e1b8d3 | ||
|
|
991f93c51b | ||
|
|
9ebf400457 | ||
|
|
98a9c199c1 | ||
|
|
628d5be5b6 | ||
|
|
9d98b2352b | ||
|
|
2349289444 | ||
|
|
3b1f03ce5b | ||
|
|
0509270388 | ||
|
|
ef8dd1207a | ||
|
|
501ff49abe | ||
|
|
3f1e4aea03 | ||
|
|
b71bc6fbaf | ||
|
|
b810407f50 | ||
|
|
3bc30b7284 | ||
|
|
377a0c27db | ||
|
|
7b1756e59c | ||
|
|
773ba91222 | ||
|
|
5884f8ed7b | ||
|
|
a46f14ba23 | ||
|
|
dc2ddb871a | ||
|
|
051e104f1b | ||
|
|
8a1605d283 | ||
|
|
4bcc12d7b1 | ||
|
|
024c137b94 | ||
|
|
b7b3891a4a | ||
|
|
b1493ede79 | ||
|
|
ee80b0be47 | ||
|
|
83f858df7a | ||
|
|
8e600d3a52 | ||
|
|
a118976bc0 | ||
|
|
828f905694 | ||
|
|
d0a04b77f0 | ||
|
|
e9673046cb | ||
|
|
1a8b7c8591 | ||
|
|
3fc9e194b9 | ||
|
|
8bbe956102 | ||
|
|
6715389a88 | ||
|
|
349fbc3a08 | ||
|
|
0f7d9290e0 | ||
|
|
b79092cf97 | ||
|
|
d6e56d98f9 | ||
|
|
e5a250d774 | ||
|
|
3945640247 | ||
|
|
e25aed10bb | ||
|
|
a82e97baf4 | ||
|
|
6ce2e0a652 | ||
|
|
71648fbe9e | ||
|
|
fb3f186aed | ||
|
|
f9e2bbe193 | ||
|
|
68a629d380 | ||
|
|
e247ccc794 | ||
|
|
9a705d69b5 | ||
|
|
0689f69ea7 | ||
|
|
d1256ec941 | ||
|
|
c59b83692d | ||
|
|
1df7a964fc | ||
|
|
c219bfbd0d | ||
|
|
9c64253b1f | ||
|
|
f474987827 | ||
|
|
d0de4a7497 | ||
|
|
5b6a6a301b | ||
|
|
72bb027767 | ||
|
|
3df8d9f358 | ||
|
|
8f24d9804b | ||
|
|
fdaeed4d7e | ||
|
|
d5af4213c3 | ||
|
|
23533893bb | ||
|
|
37e1f3c297 | ||
|
|
6210384d3a | ||
|
|
481d1f255b | ||
|
|
9b8dcc25ce | ||
|
|
f8f1c6d378 | ||
|
|
a72428a00f | ||
|
|
72373ba68d | ||
|
|
656bc8b5c2 | ||
|
|
3fffe7e2dd | ||
|
|
12000b46d1 | ||
|
|
03c3690d54 | ||
|
|
819bc52745 | ||
|
|
b52a70b1b2 | ||
|
|
2f4fe5fa8b | ||
|
|
c0b3e4ad08 | ||
|
|
a770eb5103 | ||
|
|
19f06be6c1 | ||
|
|
9bba3000f3 | ||
|
|
f1e4ab1cf6 | ||
|
|
b89a65fde6 | ||
|
|
e2c3cea042 | ||
|
|
286f2b668d | ||
|
|
9b81842090 | ||
|
|
81387d0f3b | ||
|
|
7a9f3489a5 | ||
|
|
cec7d05651 | ||
|
|
82df41e671 | ||
|
|
8a21bf5e96 | ||
|
|
09df0bbf36 | ||
|
|
717a07ddfb | ||
|
|
8004bb98f0 | ||
|
|
d7d22ca67f | ||
|
|
8bdd78064a | ||
|
|
bda5a8f6ef | ||
|
|
a1a8e7cc34 | ||
|
|
b337ee639e | ||
|
|
8abe614271 | ||
|
|
49bf651e32 | ||
|
|
668ef8d467 | ||
|
|
131dfe71a7 | ||
|
|
583fdbaf0c | ||
|
|
5b50f6029e | ||
|
|
440c3c69ae | ||
|
|
41ca769fcb | ||
|
|
167eded5f1 | ||
|
|
e76e49e6a3 | ||
|
|
c0c6228ebb | ||
|
|
74bb7b4401 | ||
|
|
93d9d0ea13 | ||
|
|
3ae5fbdf1a | ||
|
|
2ce0acced1 | ||
|
|
da20b45a04 | ||
|
|
a5a7afdfa4 | ||
|
|
a2b916a896 | ||
|
|
1a19c5c4c1 | ||
|
|
367df6cadd | ||
|
|
a1379ef084 | ||
|
|
b53a3fd575 | ||
|
|
55ab8a82d0 | ||
|
|
bf18ae74cb | ||
|
|
ea5abba84d | ||
|
|
8614f0baf7 | ||
|
|
9afc8a160d | ||
|
|
600a4a99a5 | ||
|
|
6a550f59f6 | ||
|
|
b6702196b8 | ||
|
|
f6aff0182c | ||
|
|
ed0b905767 | ||
|
|
28726acaaf | ||
|
|
7bacccf562 | ||
|
|
29c4673ad1 | ||
|
|
a8240f5549 | ||
|
|
5792e83bc6 | ||
|
|
678d8fa5b3 | ||
|
|
b2d9d1ac90 | ||
|
|
6ffddedfbf | ||
|
|
146b9b4ff8 | ||
|
|
1d0a40592b |
@@ -2,4 +2,4 @@
|
||||
|
||||
Novox Mesh — delivery: the parts that build, check and deliver a change by watching and writing keys on the bus (ADR 0429).
|
||||
|
||||
Made by the mesh from the gitea module's config value `repositories` (novox/hq ADR 0428). Main takes no push: a change reaches it by a pull request whose `mesh/repo-check` (this repository's `merge-check.sh`) and `mesh/merge-gate` passed.
|
||||
Made by the mesh from the gitea module's config value `repositories` (novox/hq ADR 0428). Main takes no push: a change reaches it by a pull request, which the checker judges. The forge's branch protection of main requires no status today (read from the forge on 2026-11-25: no required check, no status on the pull request read); this repository holds no `merge-check.sh`.
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||
)
|
||||
|
||||
// assignmentDropTool drops one assignment key of a module no manifest names any more by hand (design 47 H2 H-A-509): a
|
||||
// module key `<node>.<module>` of a retired module, as the clean state of the pass drops it, the act written in the
|
||||
// hand-act log first.
|
||||
const assignmentDropTool = "assigner_assignment_drop"
|
||||
|
||||
// assignmentLeft is why a module key `<node>.<module>` is not dropped, "" when it may be (H-A-509 and its second
|
||||
// addendum, and the lead's answer of review round 1): only when no watched branch's catalog half holds the module (trunk, as
|
||||
// world.trunk is) and the node key does not name it, since the node key is the commit of a write and a hand act never leaves
|
||||
// one node's keys disagreeing; nothing while no half holds any module.
|
||||
func assignmentLeft(node, module string, trunk map[string]bool, nodeRaw []byte, nodeFound bool) string {
|
||||
switch {
|
||||
case len(trunk) == 0:
|
||||
return "no watched branch's catalog half holds a module yet, so no module is known to be retired"
|
||||
case trunk[module]:
|
||||
return "a watched branch's catalog half holds " + module
|
||||
case !nodeFound:
|
||||
return ""
|
||||
}
|
||||
n, err := mmac.DecodeNode(nodeRaw)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("the node key of %s does not read, so whether it names %s is not known: %v", node, module, err)
|
||||
}
|
||||
if slices.ContainsFunc(n.Modules, func(r mma.AssignmentsByNodeNodeValueModulesItem) bool { return r.Module == module }) {
|
||||
return "the node key of " + node + " still names " + module + ", so it stays placed there"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// dropAssignment deletes the module key of module on node, the act first recorded through the seat mesh-hand-acts; trunk
|
||||
// answers every module a watched branch's catalog half holds.
|
||||
func dropAssignment(st seatStore, ask func(string, any) (json.RawMessage, error), trunk func() (map[string]bool, error), node, module, why, by string) (any, error) {
|
||||
switch {
|
||||
case node == "" || module == "":
|
||||
return nil, errors.New("name the node and the module whose assignment key is dropped")
|
||||
case why == "":
|
||||
return nil, errors.New("an assignment key dropped by hand says why")
|
||||
case by == "" || by == stdio.Unproven:
|
||||
return nil, errors.New("an assignment key dropped by hand names who drops it, and the runtime proved no caller")
|
||||
}
|
||||
key, err := mmac.ModuleKey(node, module)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodeKey, err := mmac.NodeKey(node)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, _, found, err := st.get(mma.StateAssignments, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("the assigner holds no assignment key %s", key)
|
||||
}
|
||||
modules, err := trunk()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the watched branches' modules cannot be read, so %s stays: %w", key, err)
|
||||
}
|
||||
nodeRaw, _, nodeFound, err := st.get(mma.StateAssignments, nodeKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if left := assignmentLeft(node, module, modules, nodeRaw, nodeFound); left != "" {
|
||||
return nil, fmt.Errorf("the assignment key %s stays: %s", key, left)
|
||||
}
|
||||
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: assignmentDropTool + " " + key, Why: why + " (" + by + ")", Cause: "assignment-drop"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the drop of %s is not recorded, so the key stays: %w", key, err)
|
||||
}
|
||||
if err := st.del(mma.StateAssignments, key); err != nil {
|
||||
return nil, fmt.Errorf("the assignment key %s is not dropped: %w", key, err)
|
||||
}
|
||||
return map[string]any{"key": key, "dropped": json.RawMessage(raw), "by": by, "hand-act": taken.Log}, nil
|
||||
}
|
||||
|
||||
// watchedModules is every module any watched branch's catalog half holds, as the pass's world.trunk is (design 47 H2 H-A-509,
|
||||
// the lead's answer of review round 1): the watched branches of the seat mesh-catalog's registrations, each branch's revision
|
||||
// read whole through the verb revision, page by page; a branch with none yet holds none.
|
||||
func watchedModules(call mcc.Call) func() (map[string]bool, error) {
|
||||
return func() (map[string]bool, error) {
|
||||
raw, err := call(mcc.RegistrationsVerb, meshcatalog.RegistrationsInput{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
answer, said, ok := buscalls.Unwrap(raw)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s answered: %s", mcc.RegistrationsVerb, said)
|
||||
}
|
||||
var regs meshcatalog.RegistrationsAnswer
|
||||
if err := json.Unmarshal(answer, ®s); err != nil || regs.Registrations == nil {
|
||||
return nil, fmt.Errorf("%s answered no registrations: %v", mcc.RegistrationsVerb, err)
|
||||
}
|
||||
branches := map[string]bool{}
|
||||
for _, reg := range regs.Registrations {
|
||||
for _, b := range reg.Branches {
|
||||
branches[b] = true
|
||||
}
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, branch := range slices.Sorted(maps.Keys(branches)) {
|
||||
for after := ""; ; {
|
||||
a, err := askCandidatePage(call, meshcatalog.RevisionInput{Branch: branch, After: after})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the catalog half of %s cannot be read: %w", branch, err)
|
||||
}
|
||||
if a.NoneYet {
|
||||
break
|
||||
}
|
||||
for _, e := range a.Entries {
|
||||
out[e.Module] = true
|
||||
}
|
||||
if a.Next == "" {
|
||||
break
|
||||
}
|
||||
after = a.Next
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
// assignmentDropTools is the tool over the runtime's states.
|
||||
func assignmentDropTools(st seatStore, ask func(string, any) (json.RawMessage, error), trunk func() (map[string]bool, error)) []stdio.Tool {
|
||||
return []stdio.Tool{{Name: assignmentDropTool, Description: "Drop one assignment key by hand (design 47 H2 H-A-509): the module " +
|
||||
"key <node>.<module> of the seat mesh-module-assigner's assignments, for a module no watched branch's catalog half holds any more " +
|
||||
"(a retired module's key, which may predate the value's version), as the clean state of the pass drops it. Refused while a " +
|
||||
"watched branch's catalog half holds the module, while the node key <node>.node still names it, or with no key there. Recorded as a " +
|
||||
"hand act first.",
|
||||
Input: schema(map[string]string{"node": "the node's name", "module": "the module's name", "why": "why the key is dropped"},
|
||||
[]string{"node", "module", "why"}),
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return dropAssignment(st, ask, trunk, arg(a, "node"), arg(a, "module"), arg(a, "why"), stdio.CallerOf(a))
|
||||
}}}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
|
||||
plc "mesh-delivery-assigner/internal/assignment"
|
||||
)
|
||||
|
||||
// H-A-509 and its second addendum: a module key of a module no manifest of the trunk names, that the node key does not name,
|
||||
// is dropped, by hand through assigner_assignment_drop (recorded as a hand act first) and at the pass's clean state (named in
|
||||
// the journal); a key a manifest of the trunk still names, or the node key still names, stays; nothing goes while the trunk
|
||||
// is empty.
|
||||
func TestARetiredModulesAssignmentKeyIsDropped(t *testing.T) {
|
||||
// novox places web; the key of the retired checker predates the value's version; the key of the retired old is still
|
||||
// named by the node key.
|
||||
values, err := mmac.AssignmentsValues(mma.Assignments{V: mmac.Version, Node: "novox", Modules: []mma.PlacedModule{{Module: "web"}, {Module: "old"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values["novox.checker"] = []byte(`{"node":"novox"}`)
|
||||
checker, web, old := "novox.checker", "novox.web", "novox.old"
|
||||
trunkOf := func(names ...string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, n := range names {
|
||||
out[n] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
copyOf := func() map[string][]byte {
|
||||
out := map[string][]byte{}
|
||||
for k, v := range values {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
t.Run("by hand", func(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, module string
|
||||
trunk map[string]bool
|
||||
refuse error
|
||||
dropped bool
|
||||
}{
|
||||
{"a retired module's key", "checker", trunkOf("web"), nil, true},
|
||||
{"a manifest of the trunk names it", "web", trunkOf("web"), nil, false},
|
||||
{"the node key still names it", "old", trunkOf("web"), nil, false},
|
||||
{"the trunk is empty", "checker", trunkOf(), nil, false},
|
||||
{"no key there", "gone", trunkOf("web"), nil, false},
|
||||
{"not recorded", "checker", trunkOf("web"), errors.New("no responders"), false},
|
||||
} {
|
||||
st := memStore{mma.StateAssignments: &memKV{values: copyOf()}}
|
||||
var asked []string
|
||||
ask := func(verb string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
asked = append(asked, verb+" "+string(raw))
|
||||
return json.RawMessage(`{}`), c.refuse
|
||||
}
|
||||
trunk := func() (map[string]bool, error) { return c.trunk, nil }
|
||||
out, err := dropAssignment(st, ask, trunk, "novox", c.module, "retired", "person.jochen")
|
||||
key := "novox." + c.module
|
||||
_, there := st[mma.StateAssignments].values[key]
|
||||
switch {
|
||||
case c.dropped && (err != nil || there || len(asked) != 1 || !strings.Contains(asked[0], assignmentDropTool+" "+key)):
|
||||
t.Errorf("%s: %v, %v; the key left %v, asked %v", c.name, out, err, there, asked)
|
||||
case !c.dropped && err == nil:
|
||||
t.Errorf("%s: %v, want it refused", c.name, out)
|
||||
case len(st[mma.StateAssignments].values) != len(values)-btoi(c.dropped):
|
||||
t.Errorf("%s: %d keys left, want %d", c.name, len(st[mma.StateAssignments].values), len(values)-btoi(c.dropped))
|
||||
}
|
||||
}
|
||||
if _, err := dropAssignment(memStore{mma.StateAssignments: &memKV{values: copyOf()}}, nil, func() (map[string]bool, error) { return trunkOf("web"), nil },
|
||||
"novox", "checker", "", "person.jochen"); err == nil {
|
||||
t.Error("a drop with no why is not refused")
|
||||
}
|
||||
})
|
||||
|
||||
// The tool judges against every watched branch's half, as the pass does (the lead's answer of review round 1): the branches
|
||||
// of the registrations, each read page by page; a branch with none yet holds none.
|
||||
t.Run("every watched branch", func(t *testing.T) {
|
||||
call := func(verb string, body any) (json.RawMessage, error) {
|
||||
switch verb {
|
||||
case meshcatalogclient.RegistrationsVerb:
|
||||
return json.Marshal(meshcatalog.RegistrationsAnswer{Registrations: []meshcatalog.Registration{{Module: "web", Branches: []string{"main", "feature"}}, {Module: "db", Branches: []string{"fresh"}}}})
|
||||
case meshcatalogclient.RevisionVerb:
|
||||
in := body.(meshcatalog.RevisionInput)
|
||||
switch {
|
||||
case in.Branch == "main" && in.After == "":
|
||||
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "web"}}, Next: "web"})
|
||||
case in.Branch == "main":
|
||||
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "db"}}})
|
||||
case in.Branch == "feature":
|
||||
return json.Marshal(meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{}, Entries: []meshcatalog.CatalogEntry{{Module: "new"}}})
|
||||
}
|
||||
return json.Marshal(meshcatalog.RevisionAnswer{NoneYet: true})
|
||||
}
|
||||
return nil, errors.New("no such verb " + verb)
|
||||
}
|
||||
got, err := watchedModules(call)()
|
||||
if err != nil || len(got) != 3 || !got["web"] || !got["db"] || !got["new"] {
|
||||
t.Errorf("watchedModules = %v, %v; want web, db and new", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("at the pass", func(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
trunk []string
|
||||
gone []string
|
||||
}{
|
||||
{"a retired module's key goes, one the node key names stays", []string{"web"}, []string{checker}},
|
||||
{"the trunk is empty", nil, nil},
|
||||
} {
|
||||
kv := &memKV{values: copyOf()}
|
||||
p := newPasser(kvSet{plc.AssignmentsBucket(): kv}, time.Now())
|
||||
var said []string
|
||||
p.logf = func(f string, a ...any) { said = append(said, f) }
|
||||
for k, v := range kv.values {
|
||||
p.w.put(plc.AssignmentsBucket(), k, v)
|
||||
}
|
||||
// web is held by a watched branch that is not the trunk's first: the pass judges against every watched branch's half.
|
||||
for _, n := range c.trunk {
|
||||
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fpTest, Repository: "novox/" + n, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
|
||||
putModuleRaw(p.w, "feature", n, mod)
|
||||
}
|
||||
for range 2 {
|
||||
p.wants(context.Background())
|
||||
}
|
||||
for _, key := range []string{checker, web, old, "novox.node"} {
|
||||
_, there := kv.values[key]
|
||||
if want := !contains(c.gone, key); there != want {
|
||||
t.Errorf("%s: %s left = %v, want %v", c.name, key, there, want)
|
||||
}
|
||||
}
|
||||
if dropped, left := countSaid(said, "is dropped"), countSaid(said, "is left"); len(c.gone) > 0 && (dropped != 1 || left != 1) {
|
||||
t.Errorf("%s: said dropped %d and left %d times, want once each: %v", c.name, dropped, left, said)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func btoi(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func contains(list []string, s string) bool {
|
||||
for _, x := range list {
|
||||
if x == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func countSaid(said []string, words string) int {
|
||||
n := 0
|
||||
for _, s := range said {
|
||||
if strings.Contains(s, words) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -60,6 +61,20 @@ func (b *builtEnds) endOf(module, fp string) (builds.BuildEnded, bool) {
|
||||
return e, ok
|
||||
}
|
||||
|
||||
// doneStarting is the done builds of module the assigner hears whose fingerprint starts with prefix, in fingerprint order.
|
||||
func (b *builtEnds) doneStarting(module, prefix string) []builds.BuildEnded {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
var out []builds.BuildEnded
|
||||
for _, e := range b.ends {
|
||||
if e.Module == module && e.Outcome == builds.BuildDone && strings.HasPrefix(e.Fingerprint, prefix) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Fingerprint < out[j].Fingerprint })
|
||||
return out
|
||||
}
|
||||
|
||||
// partsOf is the parts of module's build at fp as its end names them (each artifact's digest by `<module>:<artifact>`), with the
|
||||
// node that keeps it, for a kept build or a build of another watched branch; false for a build of the trunk not kept, whose
|
||||
// parts the version's release says (releasedVersions).
|
||||
|
||||
@@ -44,7 +44,12 @@ func dropOver(call func(key string, body any) (json.RawMessage, error)) func(ask
|
||||
}
|
||||
}
|
||||
|
||||
// waitOf is a reader's wait for a build node to take its run's ask (A-469y).
|
||||
// waitOnPublish begins what a composition run's waiting reader waits on while the run waits for a package's publish, the
|
||||
// package's path after it (design 47 H2 H-A-630 (5)).
|
||||
const waitOnPublish = "publish of package "
|
||||
|
||||
// waitOf is a reader's wait for a build node to take its run's ask (A-469y); while the run's value holds `waits`, its wait for
|
||||
// that package's publish before the ask is put, naming the package and the entry, never a build node (H-A-630 (5)).
|
||||
func waitOf(run meshwants.CompositionRun, reader meshwants.CompositionReader) meshwants.Wait {
|
||||
w := meshwants.Wait{Step: "pipeline", Owner: meshwants.Seat, Module: reader.Module, Node: run.Machine, On: waitOnBuildNode, Fp: reader.Fingerprint,
|
||||
Words: fmt.Sprintf("the composition step of %s waits for a build node to take the composition run %s of %s (ask %s)", reader.Pipeline,
|
||||
@@ -52,23 +57,75 @@ func waitOf(run meshwants.CompositionRun, reader meshwants.CompositionReader) me
|
||||
if run.Started != nil {
|
||||
w.Since = *run.Started
|
||||
}
|
||||
if run.Waits != nil {
|
||||
w.On, w.Since = waitOnPublish+run.Waits.Package, run.Waits.Since
|
||||
w.Words = fmt.Sprintf("the composition step of %s waits for the publish of package %s, named with no version in %s, before the composition run %s of %s is asked (ask %s)",
|
||||
reader.Pipeline, run.Waits.Package, run.Waits.Entry, runKeyOf(run.Candidate, run.Machine), run.Machine, run.Ask)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// sayWaits says, for each reader, its wait held or ended (how: ran, superseded); a wait that cannot be said is journaled.
|
||||
func (r *compositionRuns) sayWaits(run meshwants.CompositionRun, readers []meshwants.CompositionReader, how string) {
|
||||
if r.say == nil {
|
||||
r.sayWaitsOf(run, readers, how, "")
|
||||
}
|
||||
|
||||
// sayWaitsAtPut says, at the put of the run ask of a run whose wait for a package's publish ended, its readers' wait-held for a
|
||||
// build node again, under their held id with .put added, so the bus's duplicate window does not take it for the first one's
|
||||
// (design 47 H2 H-A-632).
|
||||
func (r *compositionRuns) sayWaitsAtPut(run meshwants.CompositionRun) {
|
||||
r.sayWaitsOf(run, run.Readers, "", ".put")
|
||||
}
|
||||
|
||||
// sayWaitsOf is sayWaits, each held id with after added.
|
||||
func (r *compositionRuns) sayWaitsOf(run meshwants.CompositionRun, readers []meshwants.CompositionReader, how, after string) {
|
||||
if r.owe == nil {
|
||||
return
|
||||
}
|
||||
for _, c := range readers {
|
||||
w := waitOf(run, c)
|
||||
event, id := meshwants.EventWaitHeld, "composition."+runKeyOf(run.Candidate, run.Machine)+"."+run.Ask+"."+c.ID+".held"
|
||||
if run.Waits != nil && how == "" { // a wait-held of its own, so the bus's duplicate window does not take it for the first one's
|
||||
id += "." + run.Waits.Package
|
||||
}
|
||||
id += after
|
||||
if how != "" {
|
||||
w.How, event, id = how, meshwants.EventWaitEnded, strings.TrimSuffix(id, ".held")+".ended"
|
||||
}
|
||||
if err := r.say(event, w, id); err != nil {
|
||||
r.logf("the %s of %s on the composition run of %s is not said: %v", event, c.Pipeline, run.Machine, err)
|
||||
// Owed in the order of its `<node>.<module>`, said again until the bus takes it (design 47 H2b §832 1., H-A-873).
|
||||
r.owe(compositionWaitOrder(run.Machine, c.Module), event, w, id)
|
||||
}
|
||||
}
|
||||
|
||||
// compositionWaitOrder is the order the events of a composition run's reader wait are said in: its `<node>.<module>` (H-A-873).
|
||||
func compositionWaitOrder(node, module string) string {
|
||||
return "composition-wait." + node + "." + module
|
||||
}
|
||||
|
||||
// sayWaitsAgain says again, at the assigner's start, the wait-held of each reader of a run with no `ended` that still waits (its
|
||||
// ask untaken, or its wait for a package's publish standing), under the id first said, from the kept runs alone (design 47 H2b
|
||||
// §832 4., H-A-873).
|
||||
func (r *compositionRuns) sayWaitsAgain() {
|
||||
all, err := r.keys()
|
||||
if err != nil {
|
||||
r.logf("composition-runs: the runs standing at the start are not read, so their waits are not said again: %v", err)
|
||||
return
|
||||
}
|
||||
for _, key := range all {
|
||||
if !isRunKey(key) {
|
||||
continue
|
||||
}
|
||||
run, _, ok, err := r.read(key)
|
||||
if err != nil || !ok || run.Ended != nil || (run.Waits == nil && !r.untaken(key, run.Ask)) {
|
||||
continue
|
||||
}
|
||||
var waiting []meshwants.CompositionReader
|
||||
for _, c := range run.Readers {
|
||||
if c.Ended == nil {
|
||||
waiting = append(waiting, c)
|
||||
}
|
||||
}
|
||||
r.sayWaits(run, waiting, "")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +250,10 @@ func (r *compositionRuns) expired(boundKey string) {
|
||||
if err != nil || !ok || run.Ended != nil {
|
||||
return
|
||||
}
|
||||
if setting == "composition-step-bound" && run.Waits != nil { // the bound a wait for a package's publish armed (H-A-628 (4))
|
||||
r.waitExpired(boundKey, key, run)
|
||||
return
|
||||
}
|
||||
// The marker of an expiry holds no value (A-470o): the run ends only while its bound is still absent when read again, and
|
||||
// the run is taken for bound., untaken for untaken., so an expiry heard after a bound was armed again, or of a run replaced
|
||||
// since, ends nothing.
|
||||
@@ -229,6 +290,25 @@ func (r *compositionRuns) expired(boundKey string) {
|
||||
}
|
||||
}
|
||||
|
||||
// waitExpired ends a run whose wait for a package's publish passed its bound, the expiry of the bound key bound.<run key> the
|
||||
// wait armed (design 47 H2 H-A-628 (3), (4)): could not run naming the package, the entry and the bound, read from the run's value
|
||||
// (H-A-629 (1), H-A-631). Its run ask is not put yet, so none is dropped; a bound armed again since (the marker holds no value,
|
||||
// A-470o) ends nothing.
|
||||
func (r *compositionRuns) waitExpired(boundKey, key string, run meshwants.CompositionRun) {
|
||||
_, _, armed, err := r.boundOf(boundKey)
|
||||
if err != nil {
|
||||
r.logf("the bound %s is not read again, so its expiry ends nothing: %v", boundKey, err)
|
||||
return
|
||||
}
|
||||
if armed {
|
||||
r.logf("the expiry of %s ends nothing: the bound is armed again (A-470o)", boundKey)
|
||||
return
|
||||
}
|
||||
if _, err := r.endRun(key, run.Ask, meshwants.CompositionRunOutcomeCouldNotRun, r.pastWaitSaid(run.Machine, *run.Waits), nil); err != nil {
|
||||
r.logf("the composition run %s past its wait for package %s is not ended: %v", key, run.Waits.Package, err)
|
||||
}
|
||||
}
|
||||
|
||||
// endRun ends a run (end) and clears its bounds: the untaken key's readers said superseded, both bound keys deleted.
|
||||
func (r *compositionRuns) endRun(key, ask, outcome, said string, verdict map[string]any) (bool, error) {
|
||||
return r.endRunOf(key, ask, outcome, said, verdict, r.untaken(key, ask))
|
||||
@@ -377,4 +457,6 @@ func (c *compositionSteps) takeUp(ctx context.Context, r *compositionRuns) {
|
||||
}
|
||||
go c.say1(ctx, reader.ID, stepRunOf(reader.CompositionReader), how, again)
|
||||
}
|
||||
// the waits of the open runs are said again once the readers are taken up: the runs' ends race the take-up, and a say must not delay it
|
||||
r.sayWaitsAgain()
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ func TestAStepsInputsAreAskedOfEachMachine(t *testing.T) {
|
||||
t.Errorf("ace: %+v", got[0])
|
||||
}
|
||||
// Design 47 H2 §775, H-A-405: each machine is asked as a kept call under the step's ask with the node, until compose-ask-bound.
|
||||
if asks["ace"] != (process.KeptAsk{ID: "step-1.ace", Bound: time.Second}) || asks["g14"].ID != "step-1.g14" {
|
||||
if asks["ace"].ID != "step-1.ace" || asks["ace"].Bound != time.Second || asks["g14"].ID != "step-1.g14" {
|
||||
t.Errorf("the kept asks %+v", asks)
|
||||
}
|
||||
if !strings.Contains(got[1].Why, "no responders") || !strings.Contains(got[2].Why, "unready") || got[1].Body != nil || got[2].Body != nil {
|
||||
|
||||
@@ -4,29 +4,69 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
mccond "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
)
|
||||
|
||||
// The reads of a composition step (design 47 G §354, A-252, A-261): the entries of one catalog revision are read once and shared by
|
||||
// every composition step of that revision, since an entry is content-addressed and a revision never changes; a read that times out
|
||||
// or fails in transport is made again with a growing wait for a bounded time, said in the journal, and only then ends the step as
|
||||
// could not run.
|
||||
// every composition step of that revision, since an entry is content-addressed and a revision never changes. Every read of the
|
||||
// seats mesh-catalog and mesh-builds is a kept call (§775), paced by the form, and all of one run's reads stop at one deadline: its
|
||||
// first read's time plus the setting reads-bound (design 47 H2 H-A-708 (3)); past it the run ends could not run with every call's
|
||||
// time and words.
|
||||
|
||||
const (
|
||||
// readsBound is how long a read is made again before the step could not run.
|
||||
readsBound = 3 * time.Minute
|
||||
// readsFirstWait and readsMaxWait bound the wait between two tries.
|
||||
readsFirstWait = time.Second
|
||||
readsMaxWait = 15 * time.Second
|
||||
// defaultReadsBound is the setting reads-bound's default, 8 minutes: it spans the six minutes a seat went unanswered on
|
||||
// 2026-11-23 and stays below the runner's ask-unanswered-bound (10 minutes, counted from the pull), so the step ends with the
|
||||
// assigner's words.
|
||||
defaultReadsBound = 8 * time.Minute
|
||||
// readsKept is how many catalog revisions' halves are kept; the oldest read goes first.
|
||||
readsKept = 8
|
||||
)
|
||||
|
||||
// readsBoundSetting is the setting reads-bound, in minutes, read at the start from the file the manifest declares with the content
|
||||
// ${config:reads-bound}; its default for a file missing or empty.
|
||||
func readsBoundSetting(getenv func(string) string) (time.Duration, error) {
|
||||
minutes, err := settingFile(getenv("MESH_ASSIGNER_READS_BOUND_FILE"))
|
||||
if err != nil || minutes == 0 {
|
||||
return defaultReadsBound, err
|
||||
}
|
||||
return time.Duration(minutes) * time.Minute, nil
|
||||
}
|
||||
|
||||
// readsClock is the deadline of one run's reads: it begins at the run's first read.
|
||||
type readsClock struct {
|
||||
mu sync.Mutex
|
||||
first time.Time
|
||||
last string
|
||||
}
|
||||
|
||||
type readsClockKey struct{}
|
||||
|
||||
// withReadsClock gives ctx the clock of one run's reads; a ctx that has one keeps it.
|
||||
func withReadsClock(ctx context.Context) context.Context {
|
||||
if ctx.Value(readsClockKey{}) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, readsClockKey{}, &readsClock{})
|
||||
}
|
||||
|
||||
// readsClockOf is the clock of the run ctx belongs to, or a clock of its own for a read made outside a run.
|
||||
func readsClockOf(ctx context.Context) *readsClock {
|
||||
if c, ok := ctx.Value(readsClockKey{}).(*readsClock); ok {
|
||||
return c
|
||||
}
|
||||
return &readsClock{}
|
||||
}
|
||||
|
||||
// readKey names one revision of one watched branch.
|
||||
type readKey struct {
|
||||
branch string
|
||||
@@ -48,65 +88,71 @@ type compositionReads struct {
|
||||
seats map[string]json.RawMessage // by seat and digest: the definition, raw
|
||||
}
|
||||
|
||||
// transient says whether a read's fault is of the transport or a timeout, so that it is worth reading again.
|
||||
func transient(err error, said string) bool {
|
||||
text := said
|
||||
// callRead calls the seat verb key as a kept call that stops at the run's deadline (design 47 H2 H-A-708 (3)); it answers the body
|
||||
// of a good answer, or the holder's own words of an answer that is none, or the fault naming the holder, its machine and every
|
||||
// call of the form.
|
||||
func (r *compositionRun) callRead(ctx context.Context, key string, body any) (json.RawMessage, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
clock := readsClockOf(ctx)
|
||||
left, bound, first := r.readsLeft(clock)
|
||||
if left <= 0 {
|
||||
clock.mu.Lock()
|
||||
last := clock.last
|
||||
clock.mu.Unlock()
|
||||
return nil, "", fmt.Errorf("%s is not read: the run's reads passed their deadline of %s (the setting reads-bound) counted from its first read at %s%s",
|
||||
key, bound, first.UTC().Format(time.RFC3339), last)
|
||||
}
|
||||
id := readFindingID(key)
|
||||
r.waiting(id, +1)
|
||||
raw, err := r.call(process.KeptAsk{Bound: left, Hook: r.readHook}, key, body)
|
||||
r.waiting(id, -1)
|
||||
if err != nil {
|
||||
text = err.Error() + " " + said
|
||||
words := fmt.Errorf("%s%s: %w", key, r.holderWords(key), err)
|
||||
clock.mu.Lock()
|
||||
clock.last = "; the last read said: " + words.Error()
|
||||
clock.mu.Unlock()
|
||||
return nil, "", words
|
||||
}
|
||||
text = strings.ToLower(text)
|
||||
for _, w := range []string{"deadline exceeded", "timeout", "timed out", "no responders", "connection", "i/o", "eof", "broken pipe", "unavailable"} {
|
||||
if strings.Contains(text, w) {
|
||||
return true
|
||||
}
|
||||
inner, said, ok := buscalls.Unwrap(raw)
|
||||
if ok {
|
||||
return inner, "", nil
|
||||
}
|
||||
return false
|
||||
return nil, said, nil
|
||||
}
|
||||
|
||||
// callRetry calls the seat verb key, again with a growing wait while its fault is transient, for readsBound; it answers the body of
|
||||
// a good answer, or the last fault.
|
||||
func (r *compositionRun) callRetry(ctx context.Context, key string, body any) (json.RawMessage, string, error) {
|
||||
start := r.now()
|
||||
wait := readsFirstWait
|
||||
for try := 1; ; try++ {
|
||||
raw, err := r.call(key, body)
|
||||
var inner json.RawMessage
|
||||
var said string
|
||||
if err == nil {
|
||||
var ok bool
|
||||
if inner, said, ok = buscalls.Unwrap(raw); ok {
|
||||
return inner, "", nil
|
||||
}
|
||||
}
|
||||
if !transient(err, said) {
|
||||
return nil, said, err
|
||||
}
|
||||
if r.now().Sub(start)+wait > readsBound {
|
||||
return nil, said, err
|
||||
}
|
||||
r.logf("composition step: %s is not read (try %d, %v %s), read again in %s", key, try, err, said, wait)
|
||||
if serr := r.waitFor(ctx, wait); serr != nil {
|
||||
return nil, said, serr
|
||||
}
|
||||
if wait *= 2; wait > readsMaxWait {
|
||||
wait = readsMaxWait
|
||||
}
|
||||
// readsLeft is what stays of the run's reads' deadline, with the deadline's length and its first read's time; the first read
|
||||
// begins it.
|
||||
func (r *compositionRun) readsLeft(clock *readsClock) (left, bound time.Duration, first time.Time) {
|
||||
bound = r.readsBound
|
||||
if bound <= 0 {
|
||||
bound = defaultReadsBound
|
||||
}
|
||||
now := r.now()
|
||||
clock.mu.Lock()
|
||||
defer clock.mu.Unlock()
|
||||
if clock.first.IsZero() {
|
||||
clock.first = now
|
||||
}
|
||||
return bound - now.Sub(clock.first), bound, clock.first
|
||||
}
|
||||
|
||||
// waitFor waits d, or until ctx ends.
|
||||
func (r *compositionRun) waitFor(ctx context.Context, d time.Duration) error {
|
||||
if r.sleep != nil {
|
||||
return r.sleep(ctx, d)
|
||||
// holderWords name the module that holds the seat of key and the machines it runs on, as the seat list names them (design 47 H2
|
||||
// H-A-708 (3)); nothing where they are not read.
|
||||
func (r *compositionRun) holderWords(key string) string {
|
||||
seat, _, _ := strings.Cut(strings.TrimPrefix(key, "seat:"), ".")
|
||||
if r.holder == nil || seat == "" {
|
||||
return ""
|
||||
}
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
return nil
|
||||
module, nodes := r.holder(seat)
|
||||
if module == "" {
|
||||
return ""
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return " (its holder " + module + ")"
|
||||
}
|
||||
return " (its holder " + module + " on " + strings.Join(nodes, ", ") + ")"
|
||||
}
|
||||
|
||||
// half is the revision's half, read once for every step of it: a step that finds it being read waits for that read, and a read that
|
||||
@@ -179,3 +225,89 @@ func unreadErr(what string, err error, said string) error {
|
||||
}
|
||||
return fmt.Errorf("%s: %s", what, said)
|
||||
}
|
||||
|
||||
// readFindingID is the id of the finding call-unanswered of a read of key: `<seat>.<verb>`.
|
||||
func readFindingID(key string) string { return strings.TrimPrefix(key, "seat:") }
|
||||
|
||||
// readKey is the key of the finding call-unanswered of a read: one per seat verb.
|
||||
func readFindingKey(id string) string {
|
||||
return mccond.Key(mccond.ScopeCall, assign.KeyID(id), mccond.KindCallUnanswered)
|
||||
}
|
||||
|
||||
// readHook is the kept-call form's hook (design 47 H2 H-A-708 (4), H-A-731): told when a read has waited five minutes, it writes the
|
||||
// finding call-unanswered of its seat verb naming its holder, its machine, the last fault and since when; told of the answer, it
|
||||
// clears it.
|
||||
func (r *compositionRun) readHook(w busretry.Waited) {
|
||||
id := w.Seat + "." + w.Verb
|
||||
if w.Answered {
|
||||
r.clearRead(id, true)
|
||||
return
|
||||
}
|
||||
if r.findings.Put == nil {
|
||||
return
|
||||
}
|
||||
holder, nodes := "", []string(nil)
|
||||
if r.holder != nil {
|
||||
holder, nodes = r.holder(w.Seat)
|
||||
}
|
||||
f := assign.ReadUnanswered(w.Seat, w.Verb, holder, nodes, w.Last, w.Since).Finding(r.now())
|
||||
if err := r.findings.Put(f); err != nil {
|
||||
r.logf("the finding %s is not written: %v", readFindingKey(id), err)
|
||||
return
|
||||
}
|
||||
r.readMu.Lock()
|
||||
if r.raised == nil {
|
||||
r.raised = map[string]bool{}
|
||||
}
|
||||
r.raised[id] = true
|
||||
r.readMu.Unlock()
|
||||
}
|
||||
|
||||
// waiting counts the reads of one seat verb now waiting for an answer; when the last one ends, the finding it raised is cleared:
|
||||
// no run waits on it any more, and each run's could-not-run says it (design 47 H2 H-A-708 (4)).
|
||||
func (r *compositionRun) waiting(id string, d int) {
|
||||
r.readMu.Lock()
|
||||
if r.inflight == nil {
|
||||
r.inflight = map[string]int{}
|
||||
}
|
||||
r.inflight[id] += d
|
||||
none := r.inflight[id] <= 0
|
||||
if none {
|
||||
delete(r.inflight, id)
|
||||
}
|
||||
r.readMu.Unlock()
|
||||
if d < 0 && none {
|
||||
r.clearRead(id, false)
|
||||
}
|
||||
}
|
||||
|
||||
// clearRead clears the finding of a read's seat verb: at the verb's answer (answered), or once no read waits on it. The finding is
|
||||
// read from the findings bucket's keys, never from what this process raised, so one written before a restart is cleared as well
|
||||
// (design 47 H2 H-A-708 (4), H-A-722).
|
||||
func (r *compositionRun) clearRead(id string, answered bool) {
|
||||
r.readMu.Lock()
|
||||
was := r.raised[id]
|
||||
clear := answered || r.inflight[id] <= 0
|
||||
if clear {
|
||||
delete(r.raised, id)
|
||||
}
|
||||
r.readMu.Unlock()
|
||||
if !clear || r.findings.Delete == nil {
|
||||
return
|
||||
}
|
||||
key := readFindingKey(id)
|
||||
if r.findings.Keys != nil {
|
||||
ks, err := r.findings.Keys()
|
||||
if err != nil {
|
||||
r.logf("the finding %s is not cleared, the findings are not read: %v", key, err)
|
||||
return
|
||||
}
|
||||
was = slices.Contains(ks, key)
|
||||
}
|
||||
if !was {
|
||||
return
|
||||
}
|
||||
if err := r.findings.Delete(key); err != nil {
|
||||
r.logf("the finding %s is not cleared: %v", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
@@ -46,6 +47,9 @@ const (
|
||||
// entryVerbKey and seatDefinitionsKey are the mesh-catalog seat verbs the step reads.
|
||||
entryVerbKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbEntry
|
||||
seatDefinitionsKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbSeatDefinitions
|
||||
// publishedVerbKey is the build seat's read of whether a package built at a fingerprint is published, what fills a run's
|
||||
// empty pin (design 47 H-A-328, H2 H-A-628 (2)).
|
||||
publishedVerbKey = "seat:" + builds.Seat + "." + builds.VerbPublished
|
||||
)
|
||||
|
||||
// compositionRun runs a composition step.
|
||||
@@ -54,8 +58,20 @@ type compositionRun struct {
|
||||
runs *compositionRuns
|
||||
inputs *compositionInputs
|
||||
keeper *inputKeeper
|
||||
// call asks a seat verb held once for the mesh (process.Conn.CallKept).
|
||||
call func(key string, body any) (json.RawMessage, error)
|
||||
// call asks a seat verb held once for the mesh as a kept call that stops at the ask's bound (process.Conn.CallKeptAsk).
|
||||
call func(ask process.KeptAsk, key string, body any) (json.RawMessage, error)
|
||||
// readsBound is the setting reads-bound: the run's reads stop at its first read's time plus it (H-A-708 (3)); zero: its default.
|
||||
readsBound time.Duration
|
||||
// holder is the module holding a seat and the machines it runs on, for the words of a read that met a fault; nil: none named.
|
||||
holder func(seat string) (module string, nodes []string)
|
||||
// engineReads is what each node's engine states it reads (the state engine-reads), for the validate run's refusal of a node-engine
|
||||
// that needs what none states (design 47 H2 H-A-682 (5)); nil: none is judged.
|
||||
engineReads *engineReadsKept
|
||||
// readMu guards inflight, the reads now waiting by seat verb, and raised, the seat verbs whose finding call-unanswered this
|
||||
// process wrote (H-A-708 (4)).
|
||||
readMu sync.Mutex
|
||||
inflight map[string]int
|
||||
raised map[string]bool
|
||||
// callFile asks a seat verb held once for the mesh whose answer comes in chunks, as a kept call (process.Conn.CallFileKept),
|
||||
// answering the verb's answer with the bytes received as its member `file`, base64: the validate step's seat-list (H-A-443).
|
||||
callFile func(ask process.KeptAsk, key string, body any) (json.RawMessage, error)
|
||||
@@ -80,9 +96,11 @@ type compositionRun struct {
|
||||
away func(machine string) bool
|
||||
// put puts a run ask on the build seat's check queue under the assigner's name.
|
||||
put func(ctx context.Context, a buildstep.StepAsk) error
|
||||
// reads shares the catalog reads among steps (compositionreads.go); sleep waits between two tries of a read (nil: a timer).
|
||||
// own is the assigner's own context: a run's start, and its wait for a package's publish, run on it as the take-up's do, never
|
||||
// on the starting step's, which a supersede or a drop ends while other steps share the run (design 47 H2 H-A-630 (3)).
|
||||
own context.Context
|
||||
// reads shares the catalog reads among steps (compositionreads.go).
|
||||
reads *compositionReads
|
||||
sleep func(ctx context.Context, d time.Duration) error
|
||||
// ask asks a seat verb on one node, for the run's answer kept as the build seat's object (buildstep.StepEnded.ReadOutput).
|
||||
ask buildstep.AskVerb
|
||||
now func() time.Time
|
||||
@@ -130,7 +148,7 @@ func (r *compositionRun) run(ctx context.Context, id string, step meshwants.Step
|
||||
continue
|
||||
}
|
||||
if j.started {
|
||||
go r.start(ctx, j.key, j.run, prep, id)
|
||||
go r.start(r.own, j.key, j.run, prep, id) // on the assigner's own context (H-A-630 (3))
|
||||
}
|
||||
keys = append(keys, j.key)
|
||||
}
|
||||
@@ -138,11 +156,10 @@ func (r *compositionRun) run(ctx context.Context, id string, step meshwants.Step
|
||||
}
|
||||
|
||||
// read waits for the end of each run of keys and judges the step of module from them, naming in its progress and its end the
|
||||
// runs it reads and their asks (§723, §729).
|
||||
// runs it reads and their asks (§723, §729); while a run it reads waits for a package's publish its phase is fetch (H-A-629 (2)).
|
||||
func (r *compositionRun) read(ctx context.Context, module string, keys []string, ends []machineEnd) stepOutcome {
|
||||
setShared(ctx, r.runs.sharedOf(keys, nil))
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseRun)
|
||||
runs := r.runs.await(ctx, keys)
|
||||
runs := r.runs.awaitEach(ctx, keys, r.sayingWaits(ctx, "the composition step of "+module))
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseReport)
|
||||
for _, key := range keys {
|
||||
ends = append(ends, judgeRun(module, runs[key]))
|
||||
@@ -221,7 +238,10 @@ type runPrep struct {
|
||||
manifests map[string]composer.Manifest
|
||||
none map[string]string
|
||||
programOf func(node string) (buildstep.RunProgram, string, map[string]string, error)
|
||||
err error
|
||||
// publishers are the publishers of each package in the step's catalog revision, what an empty pin is filled from
|
||||
// (H-A-628 (2)).
|
||||
publishers map[string]packagePublisher
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *runPrep) get(ctx context.Context) error {
|
||||
@@ -231,6 +251,7 @@ func (p *runPrep) get(ctx context.Context) error {
|
||||
p.err = errors.New("the step's catalog revision is not read: " + err.Error())
|
||||
return
|
||||
}
|
||||
p.publishers = publishersOf(half.Entries) // the step's own revision, before any branch's entry is laid over it
|
||||
if p.r.newest != nil && p.r.watched != nil {
|
||||
half = acrossBranches(p.step, half, p.r.newest(), p.r.watched)
|
||||
}
|
||||
@@ -248,6 +269,7 @@ func (p *runPrep) get(ctx context.Context) error {
|
||||
// start composes the machine of the run the step asked under stepAsk started (§718): the node's input of this moment, its request kept once in `inputs`,
|
||||
// the composer program chosen and recorded with the request's digest, and one run ask put. A fault ends the run could not run.
|
||||
func (r *compositionRun) start(ctx context.Context, key string, run meshwants.CompositionRun, prep *runPrep, stepAsk string) {
|
||||
ctx = withReadsClock(ctx) // all the run's reads stop at one deadline (design 47 H2 H-A-708 (3))
|
||||
node, ask := run.Machine, run.Ask
|
||||
end := func(said string) {
|
||||
if _, err := r.runs.endRun(key, ask, meshwants.CompositionRunOutcomeCouldNotRun, said, nil); err != nil {
|
||||
@@ -283,6 +305,13 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
|
||||
end(node + ": " + err.Error())
|
||||
return
|
||||
}
|
||||
pins, said, ok := r.awaitPins(ctx, key, ask, "the node-engine's entry "+engineFp, pins, prep.publishers)
|
||||
if !ok {
|
||||
if said != "" { // else the run ended or was replaced while it waited, or the step's wait ended
|
||||
end(node + ": " + said)
|
||||
}
|
||||
return
|
||||
}
|
||||
cs := composer.Case{Name: changeCase, Manifests: prep.manifests, None: prep.none}
|
||||
if left, err := r.leftOut(node, unlisted); err != nil {
|
||||
end(node + ": " + err.Error())
|
||||
@@ -309,20 +338,27 @@ func (r *compositionRun) start(ctx context.Context, key string, run meshwants.Co
|
||||
end(node + ": " + err.Error())
|
||||
return
|
||||
}
|
||||
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
waited := false
|
||||
written, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
waited = false
|
||||
if c.Ask != ask || c.Ended != nil {
|
||||
return false
|
||||
}
|
||||
c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: engineFp}
|
||||
c.Input = digest
|
||||
waited, c.Waits = c.Waits != nil, nil // its wait ends as its run ask is put (H-A-629 (1))
|
||||
return true
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
end(node + ": the run's program and input are not written: " + err.Error())
|
||||
return
|
||||
}
|
||||
if waited { // its readers wait for a build node again, no longer for the package's publish (H-A-632)
|
||||
r.runs.sayWaitsAtPut(written)
|
||||
}
|
||||
a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(),
|
||||
Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the composition of " + node + " by the node-engine at " + program.Commit},
|
||||
Packages: pins} // the composer is built against its entry's pins, as every build (H-A-203, H-A-192)
|
||||
Packages: pins} // the composer is built against its entry's pins, each empty one filled (H-A-203, H-A-192, H-A-628 (2))
|
||||
if err := r.put(ctx, a); err != nil {
|
||||
end(node + ": its run ask " + ask + " is not put: " + err.Error())
|
||||
}
|
||||
@@ -453,7 +489,7 @@ func (r *compositionRun) readRevision(ctx context.Context, run meshwants.StepRun
|
||||
half := mcc.Half{Entries: map[string]meshcatalog.CatalogEntry{}}
|
||||
in := meshcatalog.RevisionInput{Branch: keys.EscapeName(run.Branch), Revision: run.Revision}
|
||||
for {
|
||||
body, said, err := r.callRetry(ctx, mcc.RevisionVerb, in)
|
||||
body, said, err := r.callRead(ctx, mcc.RevisionVerb, in)
|
||||
if err != nil {
|
||||
return mcc.Half{}, err
|
||||
}
|
||||
@@ -502,7 +538,7 @@ func (r *compositionRun) seats(ctx context.Context, defs []meshcatalog.CatalogRe
|
||||
// trunkSeats are the definitions of every seat of the trunk's seat list (seat-definitions with no seat names them with their digests).
|
||||
func (r *compositionRun) trunkSeats(ctx context.Context) ([]json.RawMessage, error) {
|
||||
what := "the trunk's seat list is not read"
|
||||
body, said, err := r.callRetry(ctx, seatDefinitionsKey, meshcatalog.SeatDefinitionsInput{})
|
||||
body, said, err := r.callRead(ctx, seatDefinitionsKey, meshcatalog.SeatDefinitionsInput{})
|
||||
if err != nil || body == nil {
|
||||
return nil, unreadErr(what, err, said)
|
||||
}
|
||||
@@ -530,7 +566,7 @@ func (r *compositionRun) seatAt(ctx context.Context, seat, digest string) (json.
|
||||
return def, nil
|
||||
}
|
||||
what := "the definition of the seat " + seat + " is not read"
|
||||
body, said, err := r.callRetry(ctx, seatDefinitionsKey, meshcatalog.SeatDefinitionsInput{Seat: seat})
|
||||
body, said, err := r.callRead(ctx, seatDefinitionsKey, meshcatalog.SeatDefinitionsInput{Seat: seat})
|
||||
if err != nil || body == nil {
|
||||
return nil, unreadErr(what, err, said)
|
||||
}
|
||||
@@ -737,22 +773,260 @@ func programOfEntry(e meshcatalog.CatalogEntry) (buildstep.RunProgram, error) {
|
||||
return buildstep.RunProgram{Repository: e.Repository, Commit: e.Commit, Dir: dir, Package: composer.Package}, nil
|
||||
}
|
||||
|
||||
// pinsOfEntry are the mesh packages' versions an entry pins, the ones it names with a version (H-A-203, H-A-183): the pins
|
||||
// a run's program is built against, in the form the entry keeps and the builder sends. nil when it pins none.
|
||||
// pinsOfEntry are the mesh packages' versions an entry names (H-A-203, H-A-183, H-A-204): the pins a run's program is built
|
||||
// against, in the form the entry keeps and the builder sends, a package it names with no version kept with an empty one,
|
||||
// never left out, for filledPins to fill (H-A-628 (5)). nil when it names none.
|
||||
func pinsOfEntry(e meshcatalog.CatalogEntry) map[string]string {
|
||||
var out map[string]string
|
||||
for path, version := range e.Packages {
|
||||
if version == "" {
|
||||
continue
|
||||
if len(e.Packages) == 0 {
|
||||
return nil
|
||||
}
|
||||
return maps.Clone(e.Packages)
|
||||
}
|
||||
|
||||
// packagePublisher is the build of a catalog revision that publishes a package: its module, the package's artifact reference
|
||||
// (<module>:<artifact>) and the build's fingerprint, what the seat mesh-builds' published is asked of (H-A-328, H-A-628 (2)).
|
||||
type packagePublisher struct {
|
||||
module, artifact, fingerprint string
|
||||
}
|
||||
|
||||
// publishersOf are the publishers of each package the entries of a catalog revision publish, by package name.
|
||||
func publishersOf(entries map[string]meshcatalog.CatalogEntry) map[string]packagePublisher {
|
||||
out := map[string]packagePublisher{}
|
||||
for _, e := range entries {
|
||||
for _, a := range e.Artifacts {
|
||||
if a.Package != nil && a.Package.Name != "" && e.Fp != "" {
|
||||
out[a.Package.Name] = packagePublisher{module: e.Module, artifact: a.Ref, fingerprint: e.Fp}
|
||||
}
|
||||
}
|
||||
if out == nil {
|
||||
out = map[string]string{}
|
||||
}
|
||||
out[path] = version
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// unpublished is a package an entry names with no version whose publisher's build in the step's revision is not published.
|
||||
type unpublished struct {
|
||||
path string
|
||||
by packagePublisher
|
||||
}
|
||||
|
||||
// unpublishedSaid names each package of waiting and the build it waits for.
|
||||
func unpublishedSaid(waiting []unpublished) string {
|
||||
var said []string
|
||||
for _, u := range waiting {
|
||||
said = append(said, fmt.Sprintf("package %s has no published version: the build of %s at %s (%s) is not published", u.path, u.by.module, u.by.fingerprint, u.by.artifact))
|
||||
}
|
||||
return strings.Join(said, "; ")
|
||||
}
|
||||
|
||||
// filledPins fills each empty pin of pins, which the entry what names, from the seat mesh-builds' verb published, asked of the
|
||||
// package's publisher in the step's catalog revision: the version it answers is the pin, never one the assigner computes
|
||||
// (design 47 H2 H-A-628 (2), H-A-328, H-A-192). It answers the pins with every one it could fill, the packages whose
|
||||
// publisher's build is not published yet, or an error naming the package, the entry and why it has no version (H-A-628 (5)).
|
||||
// pins itself is left as it is: one entry's pins serve every machine's run.
|
||||
func (r *compositionRun) filledPins(ctx context.Context, what string, pins map[string]string, publishers map[string]packagePublisher) (map[string]string, []unpublished, error) {
|
||||
pins = maps.Clone(pins)
|
||||
var waiting []unpublished
|
||||
for _, path := range slices.Sorted(maps.Keys(pins)) {
|
||||
if pins[path] != "" {
|
||||
continue
|
||||
}
|
||||
by, ok := publishers[path]
|
||||
if !ok {
|
||||
return nil, nil, fmt.Errorf("package %s has no version in %s, and no build of the step's catalog revision publishes it", path, what)
|
||||
}
|
||||
v, published, err := r.publishedOf(ctx, by)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("package %s has no version in %s, and whether the build of %s at %s publishes it is not read: %w", path, what, by.module, by.fingerprint, err)
|
||||
}
|
||||
if !published {
|
||||
waiting = append(waiting, unpublished{path: path, by: by})
|
||||
continue
|
||||
}
|
||||
pins[path] = v
|
||||
r.logf("package %s, named with no version in %s, is pinned at %s: the build of %s at %s published it (mesh-builds' published, H-A-628)", path, what, v, by.module, by.fingerprint)
|
||||
}
|
||||
return pins, waiting, nil
|
||||
}
|
||||
|
||||
// awaitPins fills the empty pins of the entry what names for the run of ask under key (filledPins) and, while a package's
|
||||
// publisher's build is not published, waits for it (design 47 H2 H-A-628 (3), (4); H-A-629 (1), (3)): the run's value names the
|
||||
// package in `waits`, the time its wait began kept across a start taken up again; the run's bound key bound.<run key> is armed
|
||||
// for what is left of package-wait-minutes from that time, never in full again; published is read first and again at each
|
||||
// package-published heard (H-A-326), and the run's end is heard through its own state, its bound's expiry among them. It answers
|
||||
// the pins, every one filled, the bound key deleted again (an ask in the queue has no clock, §720), and true; else false and why the
|
||||
// run could not run, or no words when the run ended or was replaced meanwhile, or ctx ended.
|
||||
func (r *compositionRun) awaitPins(ctx context.Context, key, ask, what string, pins map[string]string, publishers map[string]packagePublisher) (map[string]string, string, bool) {
|
||||
armed, said := false, ""
|
||||
for {
|
||||
// The wake of each empty pin's publisher, taken before the read, so a publish heard meanwhile wakes the next one; the run
|
||||
// waits on the one of the package its `waits` names alone (H-A-630 (1)).
|
||||
wakes := map[string]<-chan struct{}{}
|
||||
for path, v := range pins {
|
||||
if by, ok := publishers[path]; ok && v == "" {
|
||||
wakes[path] = r.runs.publishWake(by.artifact)
|
||||
}
|
||||
}
|
||||
filled, waiting, err := r.filledPins(ctx, what, pins, publishers)
|
||||
if err != nil {
|
||||
return nil, err.Error(), false
|
||||
}
|
||||
if len(waiting) == 0 {
|
||||
if armed {
|
||||
if err := r.runs.clearBounds(key, ask, runBoundPrefix); err != nil {
|
||||
r.logf("the bound of the composition run %s's wait is not deleted: %v", key, err)
|
||||
}
|
||||
r.logf("the composition run %s waits no more: every package %s names is published", key, what)
|
||||
}
|
||||
return filled, "", true
|
||||
}
|
||||
path := waiting[0].path
|
||||
published := wakes[path]
|
||||
since, held, err := r.runs.waitFor(key, ask, path, what)
|
||||
if err != nil {
|
||||
return nil, "its wait for package " + path + " is not written: " + err.Error(), false
|
||||
}
|
||||
if !held {
|
||||
return nil, "", false
|
||||
}
|
||||
left := since.Add(r.runs.set.packageWait).Sub(r.now())
|
||||
if left <= 0 {
|
||||
return nil, r.runs.pastWaitSaid("", meshwants.CompositionRunWaits{Package: path, Entry: what}), false
|
||||
}
|
||||
if !armed {
|
||||
stands, err := r.runs.armBound(runBoundPrefix, key, ask, wholeSeconds(left))
|
||||
if err != nil {
|
||||
return nil, "the bound of its wait for package " + path + " is not armed: " + err.Error(), false
|
||||
}
|
||||
if !stands {
|
||||
return nil, "", false
|
||||
}
|
||||
armed = true
|
||||
}
|
||||
if path != said {
|
||||
said = path
|
||||
r.logf("the composition run %s waits for package %s, named with no version in %s: %s; %s ends its wait at %s", key, path, what,
|
||||
unpublishedSaid(waiting), packageWaitSetting, since.Add(r.runs.set.packageWait).Format(time.RFC3339))
|
||||
// Its readers are said waiting for that package's publish, naming it, no longer for a build node (H-A-630 (5)).
|
||||
if run, _, ok, err := r.runs.read(key); err == nil && ok && run.Ended == nil && run.Ask == ask && run.Waits != nil {
|
||||
r.runs.sayWaits(run, run.Readers, "")
|
||||
}
|
||||
}
|
||||
for woke := false; !woke; {
|
||||
changed := r.runs.wake()
|
||||
run, _, ok, err := r.runs.read(key)
|
||||
if err == nil && (!ok || run.Ended != nil || run.Ask != ask) {
|
||||
return nil, "", false
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, "", false
|
||||
case <-published:
|
||||
woke = true
|
||||
case <-changed:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// wholeSeconds is d rounded up to a whole second, the bus's least step of a key's time to live: what is left of a wait's bound
|
||||
// is never refused as a time to live below a second.
|
||||
func wholeSeconds(d time.Duration) time.Duration {
|
||||
if w := d.Truncate(time.Second); w < d {
|
||||
return w + time.Second
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// sayingWaits is what a step reading runs says of them at each read (design 47 H2 H-A-629 (2)): the phase fetch while a run it
|
||||
// reads holds `waits`, its journal naming the package, and run once none does.
|
||||
func (r *compositionRun) sayingWaits(ctx context.Context, what string) func(map[string]meshwants.CompositionRun) {
|
||||
said := ""
|
||||
return func(runs map[string]meshwants.CompositionRun) {
|
||||
waits, of := "", ""
|
||||
for _, key := range slices.Sorted(maps.Keys(runs)) {
|
||||
if run := runs[key]; run.Ended == nil && run.Waits != nil {
|
||||
waits, of = run.Waits.Package, key
|
||||
break
|
||||
}
|
||||
}
|
||||
if waits == "" {
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseRun)
|
||||
} else {
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseFetch)
|
||||
}
|
||||
if waits != said {
|
||||
if waits != "" {
|
||||
r.logf("%s says fetch: the composition run %s waits for package %s", what, of, waits)
|
||||
} else {
|
||||
r.logf("%s says run: no composition run it reads waits for a package", what)
|
||||
}
|
||||
said = waits
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// takeUpWaits takes up, at the assigner's start, each run still waiting for a package's publish, its value holding `waits` and
|
||||
// no program (design 47 H2 H-A-629 (3)): past the time its wait began plus package-wait-minutes it ends could not run naming the
|
||||
// package; before it, its bound key is armed again for what is left and its whole start runs again, a compose-candidate ask of the
|
||||
// node and its kept request, which reads published first, as its first reader's step.
|
||||
func (r *compositionRun) takeUpWaits(ctx context.Context) {
|
||||
all, err := r.runs.keys()
|
||||
if err != nil {
|
||||
r.logf("composition-runs: the runs standing at the start are not read, so no run waiting for a package is taken up: %v", err)
|
||||
return
|
||||
}
|
||||
for _, key := range all {
|
||||
if !isRunKey(key) {
|
||||
continue
|
||||
}
|
||||
run, _, ok, err := r.runs.read(key)
|
||||
if err != nil || !ok || run.Ended != nil || run.Waits == nil || run.Program != nil {
|
||||
continue
|
||||
}
|
||||
left := run.Waits.Since.Add(r.runs.set.packageWait).Sub(r.now())
|
||||
if left <= 0 {
|
||||
if _, err := r.runs.endRun(key, run.Ask, meshwants.CompositionRunOutcomeCouldNotRun, r.runs.pastWaitSaid(run.Machine, *run.Waits), nil); err != nil {
|
||||
r.logf("the composition run %s past its wait for package %s is not ended: %v", key, run.Waits.Package, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := r.runs.armBound(runBoundPrefix, key, run.Ask, wholeSeconds(left)); err != nil {
|
||||
r.logf("the bound of the composition run %s's wait is not armed again: %v", key, err)
|
||||
}
|
||||
if len(run.Readers) == 0 {
|
||||
r.logf("the composition run %s waiting for package %s has no reader, so its start does not run again; its bound ends it", key, run.Waits.Package)
|
||||
continue
|
||||
}
|
||||
first := run.Readers[0]
|
||||
r.logf("the composition run %s, waiting for package %s since %s, is taken up again: its start runs again (H-A-629 (3))", key, run.Waits.Package,
|
||||
run.Waits.Since.Format(time.RFC3339))
|
||||
if isValidateRun(run) {
|
||||
go r.startValidate(ctx, key, run, stepRunOf(first))
|
||||
} else {
|
||||
go r.start(ctx, key, run, &runPrep{r: r, step: stepRunOf(first)}, first.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// publishedOf asks the seat mesh-builds' verb published whether by's build is published, answering the pin it is published at
|
||||
// (vMAJOR.MINOR.PATCH, spec S9) when it is.
|
||||
func (r *compositionRun) publishedOf(ctx context.Context, by packagePublisher) (string, bool, error) {
|
||||
body, said, err := r.callRead(ctx, publishedVerbKey, builds.PublishedInput{Module: by.module, Artifact: by.artifact, Fingerprint: by.fingerprint})
|
||||
if err != nil || body == nil {
|
||||
return "", false, unreadErr(builds.VerbPublished+" did not answer", err, said)
|
||||
}
|
||||
a, _, err := builds.DecodePublishedAnswer(body)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("%s answered what does not read: %w", builds.VerbPublished, err)
|
||||
}
|
||||
if !a.Published {
|
||||
return "", false, nil
|
||||
}
|
||||
if a.Version == "" {
|
||||
return "", false, fmt.Errorf("%s answered published with no version", builds.VerbPublished)
|
||||
}
|
||||
return "v" + a.Version, true, nil
|
||||
}
|
||||
|
||||
// programs answers, per machine, the composer its run builds and the node-engine fingerprint it was chosen from (A-226, A-243,
|
||||
// A-252, §719): where the revision's node-engine entry differs from the trunk's, that build for every machine; else the build the
|
||||
// machine's node-engine runs, as its `running` says, its entry read through mesh-catalog's `entry`; a machine whose node-engine's
|
||||
@@ -790,7 +1064,7 @@ func (r *compositionRun) programs(ctx context.Context, half mcc.Half) (func(node
|
||||
return b.program, fp, b.pins, nil
|
||||
}
|
||||
what := "the entry of the node-engine's build " + fp + " is not read"
|
||||
body, said, err := r.callRetry(ctx, entryVerbKey, meshcatalog.EntryInput{Fingerprint: fp})
|
||||
body, said, err := r.callRead(ctx, entryVerbKey, meshcatalog.EntryInput{Fingerprint: fp})
|
||||
if err != nil || body == nil {
|
||||
return buildstep.RunProgram{}, fp, nil, unreadErr(what, err, said)
|
||||
}
|
||||
|
||||
@@ -4,7 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -15,13 +18,16 @@ import (
|
||||
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
mccond "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
)
|
||||
|
||||
@@ -48,10 +54,81 @@ type runStand struct {
|
||||
listFault error
|
||||
// verdict, when set, is the composer's verdict of a machine (by node), else the stand's own.
|
||||
verdict func(node string) (composer.Machine, bool)
|
||||
// publishedAt is the version mesh-builds' published answers for a build fingerprint, none (not published) when absent;
|
||||
// published are the asks it was given (H-A-628 (2)).
|
||||
publishedAt map[string]string
|
||||
published []builds.PublishedInput
|
||||
// noPublisher: the revision holds no build publishing x/go.
|
||||
noPublisher bool
|
||||
}
|
||||
|
||||
// logLines is a journal a test awaits lines of: each write wakes the waiter, no sleep stands in for it.
|
||||
type logLines struct {
|
||||
mu sync.Mutex
|
||||
text []string
|
||||
grew chan struct{}
|
||||
}
|
||||
|
||||
func newLogLines() *logLines { return &logLines{grew: make(chan struct{})} }
|
||||
|
||||
func (l *logLines) logf(format string, a ...any) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.text = append(l.text, fmt.Sprintf(format, a...))
|
||||
close(l.grew)
|
||||
l.grew = make(chan struct{})
|
||||
}
|
||||
|
||||
// await returns once n lines hold words, and fails the test when they did not come within 10 s.
|
||||
func (l *logLines) await(t *testing.T, words string, n int) {
|
||||
t.Helper()
|
||||
deadline := time.After(10 * time.Second)
|
||||
for {
|
||||
l.mu.Lock()
|
||||
count, grew := 0, l.grew
|
||||
for _, line := range l.text {
|
||||
if strings.Contains(line, words) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
text := strings.Join(l.text, "\n")
|
||||
l.mu.Unlock()
|
||||
if count >= n {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-grew:
|
||||
case <-deadline:
|
||||
t.Fatalf("no %d lines %q in the journal within 10 s:\n%s", n, words, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// eventsOf is the assigner's hub as a test hands it events: each handler by its subject, each bind's hearer.
|
||||
type eventsOf struct {
|
||||
handle map[string]func(jetstream.Msg)
|
||||
bound []func(time.Time)
|
||||
}
|
||||
|
||||
func (h *eventsOf) Handle(subject string, f func(jetstream.Msg)) error {
|
||||
h.handle[subject] = f
|
||||
return nil
|
||||
}
|
||||
func (h *eventsOf) OnBound(f func(time.Time)) { h.bound = append(h.bound, f) }
|
||||
|
||||
// say hands the handler of subject the event ev, and fails the test when it is not acknowledged.
|
||||
func (h *eventsOf) say(t *testing.T, subject string, ev any) {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(ev)
|
||||
m := &heardMsg{data: raw, subject: subject}
|
||||
h.handle[subject](m)
|
||||
if !m.acked {
|
||||
t.Errorf("the event %s on %s is not acknowledged", raw, subject)
|
||||
}
|
||||
}
|
||||
|
||||
func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *runStand {
|
||||
s := &runStand{asks: map[string]buildstep.StepAsk{}, requests: map[string]composer.Request{}}
|
||||
s := &runStand{asks: map[string]buildstep.StepAsk{}, requests: map[string]composer.Request{}, publishedAt: map[string]string{"src2:x1": "0.1.9"}}
|
||||
engine := func(fp, commit string) meshcatalog.CatalogEntry {
|
||||
return meshcatalog.CatalogEntry{Module: "engine", Fp: fp, Repository: "novox/mesh-host", Commit: commit, Path: ".", Serves: []string{ne.Seat + ".composition"},
|
||||
Manifest: map[string]any{"module": "engine"}, Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": "v0.1.25-" + fp, "git.novox.be/novox/x/go": ""}}
|
||||
@@ -65,7 +142,9 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
|
||||
Entries: []meshcatalog.CatalogEntry{engine(revisionEngine, revisionCommit), {Module: "bad", Verdict: mcc.VerdictRefused, Inputs: &meshcatalog.EntryInputs{Problems: []string{"no seat x"}},
|
||||
Manifest: map[string]any{"module": "bad"}}}, Next: "bad"},
|
||||
"bad": {Revision: &meshcatalog.CatalogRevision{Revision: 7}, Entries: []meshcatalog.CatalogEntry{{Module: "m", Verdict: mcc.VerdictAccepted, Manifest: map[string]any{"module": "m"}},
|
||||
{Module: "lidarr", None: "builders disagree: node", Manifest: map[string]any{"module": "lidarr"}}}}, // no fingerprint (A-470j)
|
||||
{Module: "lidarr", None: "builders disagree: node", Manifest: map[string]any{"module": "lidarr"}}, // no fingerprint (A-470j)
|
||||
// x publishes the package the node-engine names with no version (H-A-628 (2)); no manifest, so the case holds none of it.
|
||||
{Module: "x", Fp: "src2:x1", Artifacts: []meshcatalog.Artifact{{Ref: "x:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "git.novox.be/novox/x/go"}}}}}},
|
||||
}
|
||||
call := func(key string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
@@ -77,6 +156,9 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
|
||||
return nil, errors.New("asked another revision")
|
||||
}
|
||||
page := pages[in.After]
|
||||
if s.noPublisher {
|
||||
page.Entries = slices.DeleteFunc(slices.Clone(page.Entries), func(e meshcatalog.CatalogEntry) bool { return e.Module == "x" })
|
||||
}
|
||||
if s.noDefinitions && page.Revision != nil {
|
||||
rev := *page.Revision
|
||||
rev.Definitions = nil
|
||||
@@ -101,6 +183,14 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
|
||||
s.mu.Unlock()
|
||||
commit := map[string]string{"src2:e1": commitE1, "src2:e2": commitE2}[in.Fingerprint]
|
||||
return json.Marshal(meshcatalog.EntryAnswer{Entry: engine(in.Fingerprint, commit)})
|
||||
case publishedVerbKey:
|
||||
var in builds.PublishedInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
s.mu.Lock()
|
||||
s.published = append(s.published, in)
|
||||
v, ok := s.publishedAt[in.Fingerprint]
|
||||
s.mu.Unlock()
|
||||
return json.Marshal(builds.PublishedAnswer{Published: ok, Version: v})
|
||||
}
|
||||
return nil, errors.New("no such verb " + key)
|
||||
}
|
||||
@@ -114,7 +204,7 @@ func newRunStand(t *testing.T, revisionEngine, trunkEngine, seatDigest string) *
|
||||
s.runs = newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf)
|
||||
s.r = &compositionRun{runs: s.runs,
|
||||
inputs: &compositionInputs{machines: func(string, string) []string { return []string{"ace", "g14", "shanks"} }, callFile: engines, bound: time.Second},
|
||||
keeper: keeper, reads: &compositionReads{}, call: call, away: away, now: time.Now, logf: t.Logf,
|
||||
keeper: keeper, reads: &compositionReads{}, call: asKept(call), away: away, own: context.Background(), now: time.Now, logf: t.Logf,
|
||||
trunk: func() (mcc.Half, bool) {
|
||||
return mcc.Half{Entries: map[string]meshcatalog.CatalogEntry{"engine": engine(trunkEngine, commitE1)}}, true
|
||||
},
|
||||
@@ -187,11 +277,202 @@ func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
|
||||
if s.asks["g14"].Run.Program.Commit != commitE2 {
|
||||
t.Errorf("g14's composer is built at %s, want the build its node-engine runs", s.asks["g14"].Run.Program.Commit)
|
||||
}
|
||||
// Each composer is built against the pins of the node-engine entry it is built from, a pin with no version left out
|
||||
// (H-A-203, H-A-192).
|
||||
// Each composer is built against the pins of the node-engine entry it is built from (H-A-203, H-A-192); 1984/AC9: the one
|
||||
// it names with no version is filled from mesh-builds' published of its publisher's build in the step's revision, at the
|
||||
// version that answers, never left out (H-A-628 (2), (5)).
|
||||
for node, fp := range map[string]string{"ace": "src2:e1", "g14": "src2:e2"} {
|
||||
if got := s.asks[node].Packages; len(got) != 1 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.25-"+fp {
|
||||
t.Errorf("%s's composer is built against the pins %v; want its entry's", node, got)
|
||||
if got := s.asks[node].Packages; len(got) != 2 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.25-"+fp || got["git.novox.be/novox/x/go"] != "v0.1.9" {
|
||||
t.Errorf("%s's composer is built against the pins %v; want its entry's, x/go at v0.1.9 from published", node, got)
|
||||
}
|
||||
}
|
||||
if len(s.published) == 0 || s.published[0] != (builds.PublishedInput{Module: "x", Artifact: "x:go", Fingerprint: "src2:x1"}) {
|
||||
t.Errorf("published was asked %+v, want x's build of x:go at src2:x1 in the step's revision", s.published)
|
||||
}
|
||||
// 1984/AC9: no run ask is put with a pin left out: no build of the revision publishing x/go ends the run could not run at once,
|
||||
// naming the package and the entry, never the builder (H-A-628 (5)).
|
||||
for name, c := range map[string]struct {
|
||||
stand func(*runStand)
|
||||
said string
|
||||
}{
|
||||
"no publisher": {func(s *runStand) { s.publishedAt = nil; s.noPublisher = true }, "package git.novox.be/novox/x/go has no version in the node-engine's entry src2:e1, and no build of the step's catalog revision publishes it"},
|
||||
} {
|
||||
u := newRunStand(t, "src2:e1", "src2:e1", "d1")
|
||||
c.stand(u)
|
||||
if out := u.r.run(context.Background(), "ask-step", step); out.Outcome != meshwants.StepEndedOutcomeCouldNotRun || !strings.Contains(out.Said, c.said) ||
|
||||
strings.Contains(out.Said, "the builder pins or waits") || len(u.asks) != 0 {
|
||||
t.Errorf("%s: the step came to %+v with %d run asks put, want could not run saying %q and none put", name, out, len(u.asks), c.said)
|
||||
}
|
||||
}
|
||||
// 1984/AC9; H-A-628 (3), (4); H-A-629 (1), (2): x's build not published yet: each run waits, its value naming x/go in `waits`
|
||||
// with the time its wait began, its bound bound.<run key> armed for package-wait-minutes, the step saying fetch naming the
|
||||
// package; at the publish heard each reads published again and puts its run ask with the pin, `waits` and the bound gone, the
|
||||
// step saying run; past the bound each ends could not run naming the package and the bound, no run ask put. H-A-630 (2): a
|
||||
// bind of the consumer, the publish said while it was not bound, wakes each to read it published. H-A-630 (3): the starting
|
||||
// step superseded leaves the runs another step shares waiting, and that step reads them composed after the publish. H-A-630 (4),
|
||||
// H-A-631: past the bound, by the bound's expiry or at a take-up, the words name the package, the entry and the bound.
|
||||
for _, how := range []string{"published", "bind", "superseded", "past its bound", "past its bound at a take-up"} {
|
||||
publish := !strings.HasPrefix(how, "past its bound")
|
||||
u := newRunStand(t, "src2:e1", "src2:e1", "d1")
|
||||
u.publishedAt = nil
|
||||
journal := newLogLines()
|
||||
u.r.logf = journal.logf
|
||||
atPut := map[string]string{} // by run key: what stood of its wait as its run ask was put
|
||||
put := u.r.put
|
||||
u.r.put = func(ctx context.Context, a buildstep.StepAsk) error {
|
||||
key, run, _ := u.runs.keyOfAsk(a.ID)
|
||||
bound, _, _ := u.runs.kv.get(runBoundPrefix + key)
|
||||
u.mu.Lock()
|
||||
atPut[key] = fmt.Sprintf("waits %v, bound %s", run.Waits, bound)
|
||||
u.mu.Unlock()
|
||||
return put(ctx, a)
|
||||
}
|
||||
lastHeld := map[string]string{} // by machine: what its newest wait-held waits on, and its id
|
||||
u.runs.owe = func(_, event string, body any, id string) {
|
||||
w := body.(meshwants.Wait)
|
||||
journal.logf("said %s on %s: %s (%s)", event, w.On, w.Words, id)
|
||||
if event == meshwants.EventWaitHeld {
|
||||
u.mu.Lock()
|
||||
lastHeld[w.Node] = w.On + " (" + id + ")"
|
||||
u.mu.Unlock()
|
||||
}
|
||||
}
|
||||
phase := &stepPhase{}
|
||||
done := make(chan stepOutcome, 1)
|
||||
first, supersede := context.WithCancel(context.WithValue(context.Background(), phaseKey{}, phase))
|
||||
defer supersede()
|
||||
go func() { done <- u.r.run(first, "ask-step", step) }()
|
||||
journal.await(t, "waits for package git.novox.be/novox/x/go, named with no version in the node-engine's entry src2:e", 2)
|
||||
journal.await(t, "the composition step of m says fetch: the composition run", 1)
|
||||
// H-A-630 (5): each reader's wait-held says it waits for x/go's publish, naming the package and the entry.
|
||||
journal.await(t, "said wait-held on "+waitOnPublish+"git.novox.be/novox/x/go: the composition step of waits for the publish of package git.novox.be/novox/x/go, named with no version in the node-engine's entry src2:e", 2)
|
||||
if got := phase.get(); got != meshwants.StepProgressEventPhaseFetch {
|
||||
t.Errorf("waiting, the step says the phase %q, want fetch", got)
|
||||
}
|
||||
kv := u.runs.kv.(*runsMem)
|
||||
var keys []string
|
||||
all, _ := u.runs.keys()
|
||||
for _, key := range all {
|
||||
if isRunKey(key) {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
run, _, _, _ := u.runs.read(key)
|
||||
kv.mu.Lock()
|
||||
ttl := kv.ttl[runBoundPrefix+key]
|
||||
kv.mu.Unlock()
|
||||
if len(keys) != 2 || run.Waits == nil || run.Waits.Package != "git.novox.be/novox/x/go" || !strings.HasPrefix(run.Waits.Entry, "the node-engine's entry src2:e") ||
|
||||
run.Waits.Since.IsZero() || ttl <= 9*time.Minute || ttl > 10*time.Minute {
|
||||
t.Errorf("the waiting run %s of %v holds %+v, its bound %s; want x/go and its entry in waits and package-wait-minutes' bound", key, keys, run.Waits, ttl)
|
||||
}
|
||||
}
|
||||
switch how {
|
||||
case "past its bound":
|
||||
for _, key := range keys {
|
||||
kv.expire(runBoundPrefix + key)
|
||||
u.runs.expired(runBoundPrefix + key)
|
||||
}
|
||||
case "past its bound at a take-up": // the wait began longer ago than package-wait-minutes, as if the assigner were down
|
||||
for _, key := range keys {
|
||||
if _, _, err := u.runs.change(key, func(c *meshwants.CompositionRun) bool { c.Waits.Since = c.Waits.Since.Add(-time.Hour); return true }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
u.r.takeUpWaits(context.Background())
|
||||
case "superseded":
|
||||
second := make(chan stepOutcome, 1)
|
||||
go func() {
|
||||
second <- u.r.run(context.WithValue(context.Background(), phaseKey{}, &stepPhase{}), "ask-step-2", step)
|
||||
}()
|
||||
journal.await(t, "the composition step of m says fetch: the composition run", 2) // the second step reads the waiting runs
|
||||
supersede()
|
||||
<-done
|
||||
for _, key := range keys {
|
||||
if run, _, _, _ := u.runs.read(key); run.Ended != nil || run.Waits == nil || len(run.Readers) != 2 {
|
||||
t.Errorf("the starting step superseded, the run %s holds ended %v, waits %+v, readers %d; want it waiting for its two readers", key, run.Ended, run.Waits, len(run.Readers))
|
||||
}
|
||||
}
|
||||
done = second
|
||||
u.mu.Lock()
|
||||
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
|
||||
u.mu.Unlock()
|
||||
u.runs.heardPublished("x:go")
|
||||
case "bind":
|
||||
hub := &eventsOf{handle: map[string]func(jetstream.Msg){}}
|
||||
if err := hearPublished(hub, u.runs, t.Logf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
|
||||
u.mu.Unlock()
|
||||
for _, bound := range hub.bound {
|
||||
bound(time.Now())
|
||||
}
|
||||
default:
|
||||
// H-A-630 (1): a package-published of another package wakes no run waiting for x/go, so it asks no published; x's own
|
||||
// wakes each.
|
||||
hub := &eventsOf{handle: map[string]func(jetstream.Msg){}}
|
||||
if err := hearPublished(hub, u.runs, t.Logf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.mu.Lock()
|
||||
asked := len(u.published)
|
||||
u.mu.Unlock()
|
||||
hub.say(t, builds.SubjectPackagePublished, builds.PackagePublished{Module: "y", Artifact: "y:go", Branch: "main", Source: 7, Version: "0.2.0", V: 1})
|
||||
u.runs.mu.Lock()
|
||||
_, open := u.runs.published["x:go"]
|
||||
u.runs.mu.Unlock()
|
||||
u.mu.Lock()
|
||||
after := len(u.published)
|
||||
u.publishedAt = map[string]string{"src2:x1": "0.1.9"}
|
||||
u.mu.Unlock()
|
||||
if !open || after != asked {
|
||||
t.Errorf("a publish of y:go woke the runs waiting for x/go (their wake standing %v) or asked published %d times more", open, after-asked)
|
||||
}
|
||||
hub.say(t, builds.SubjectPackagePublished, builds.PackagePublished{Module: "x", Artifact: "x:go", Branch: "main", Source: 7, Version: "0.1.9", V: 1})
|
||||
}
|
||||
var out stepOutcome
|
||||
select {
|
||||
case out = <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("%s: the waiting step said no end", how)
|
||||
}
|
||||
journal.await(t, "the composition step of m says run", 1)
|
||||
if !publish {
|
||||
for _, key := range keys {
|
||||
if run, _, _, _ := u.runs.read(key); run.Ended == nil || run.Waits != nil {
|
||||
t.Errorf("%s: the run %s holds ended %v, waits %+v; want it ended and its wait gone", how, key, run.Ended, run.Waits)
|
||||
}
|
||||
}
|
||||
for node, fp := range map[string]string{"ace": "src2:e1", "g14": "src2:e2"} {
|
||||
if want := node + ": package git.novox.be/novox/x/go has no published version within 10m0s (package-wait-minutes), named with no version in the node-engine's entry " + fp; out.Outcome != meshwants.StepEndedOutcomeCouldNotRun ||
|
||||
!strings.Contains(out.Said, want) || strings.Contains(out.Said, "the builder pins or waits") || len(u.asks) != 0 {
|
||||
t.Errorf("%s: the step came to %+v with %d run asks put, want could not run saying %q", how, out, len(u.asks), want)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if out.Outcome != meshwants.StepEndedOutcomeFailed || !strings.Contains(out.Said, "g14 does not compose") || len(u.asks) != 2 {
|
||||
t.Errorf("after the publish the step came to %+v with %d run asks", out, len(u.asks))
|
||||
}
|
||||
for node, a := range u.asks {
|
||||
if a.Packages["git.novox.be/novox/x/go"] != "v0.1.9" {
|
||||
t.Errorf("after the publish %s's composer is built against %v, want x/go at v0.1.9", node, a.Packages)
|
||||
}
|
||||
}
|
||||
// H-A-632: at the put each reader's newest wait-held is for a build node again, under its held id with .put added.
|
||||
for _, node := range []string{"ace", "g14"} {
|
||||
u.mu.Lock()
|
||||
got := lastHeld[node]
|
||||
u.mu.Unlock()
|
||||
if !strings.HasPrefix(got, waitOnBuildNode+" (") || !strings.HasSuffix(got, ".held.put)") {
|
||||
t.Errorf("%s: after the put the newest wait-held of %s waits on %s, want a build node under its held id with .put", how, node, got)
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
if got := atPut[key]; got != "waits <nil>, bound " {
|
||||
t.Errorf("as the run ask of %s was put its wait stood: %s; want waits and the bound gone (§720: an ask in the queue has no clock)", key, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
if req.Depth != composer.DepthCompose || req.BlameTries != 20 || len(req.Machines) != 1 || req.Machines[0] != "ace" || len(req.Cases) != 1 || req.Cases[0].Name != changeCase ||
|
||||
@@ -384,51 +665,40 @@ func TestTheCompositionStepRunsOneAskPerMachine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G §354, A-252: the entries of one catalog revision are read once for every step of it, and a read that times out is
|
||||
// made again with a growing wait for a bounded time, said in the journal, before the step could not run.
|
||||
func TestTheCompositionStepReadsTheRevisionOnceAndAgainOnATimeout(t *testing.T) {
|
||||
// asKept is a fake seat call as the kept call the run makes: the bound and the hook are the call's own, a fake answers at once.
|
||||
func asKept(call func(key string, body any) (json.RawMessage, error)) func(process.KeptAsk, string, any) (json.RawMessage, error) {
|
||||
return func(_ process.KeptAsk, key string, body any) (json.RawMessage, error) { return call(key, body) }
|
||||
}
|
||||
|
||||
// Design 47 G §354, A-252: the entries of one catalog revision are read once for every step of it, and a fault of the holder's own
|
||||
// answer is not read again.
|
||||
func TestTheCompositionStepReadsTheRevisionOnce(t *testing.T) {
|
||||
step := meshwants.StepRun{Module: "m", Branch: "main", Revision: 7, Step: meshwants.StepRunStepComposition}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
faults int // consecutive faults of the `revision` read before it answers
|
||||
fault error // the fault
|
||||
fault error // the fault of the `revision` read, none: it answers
|
||||
steps int
|
||||
want string // the outcome of the last step
|
||||
revisionCalls int
|
||||
waits int
|
||||
}{
|
||||
{"two steps of one revision read it once", 0, nil, 2, meshwants.StepEndedOutcomeFailed, 2, 0},
|
||||
{"a timeout is read again", 3, errors.New("context deadline exceeded"), 1, meshwants.StepEndedOutcomeFailed, 5, 3},
|
||||
{"a fault that stays ends could not run", 1000, errors.New("nats: timeout"), 1, meshwants.StepEndedOutcomeCouldNotRun, -1, -1},
|
||||
{"a fault of the answer is not read again", 1, errors.New("no such revision"), 1, meshwants.StepEndedOutcomeCouldNotRun, 1, 0},
|
||||
{"two steps of one revision read it once", nil, 2, meshwants.StepEndedOutcomeFailed, 2},
|
||||
{"a fault of the answer is not read again", errors.New("no such revision"), 1, meshwants.StepEndedOutcomeCouldNotRun, 1},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := newRunStand(t, "src2:e1", "src2:e1", "d1")
|
||||
inner := s.r.call
|
||||
var mu sync.Mutex
|
||||
calls, faults := 0, tc.faults
|
||||
s.r.call = func(key string, body any) (json.RawMessage, error) {
|
||||
calls := 0
|
||||
s.r.call = func(ask process.KeptAsk, key string, body any) (json.RawMessage, error) {
|
||||
if key == mcc.RevisionVerb {
|
||||
mu.Lock()
|
||||
calls++
|
||||
f := faults > 0
|
||||
faults--
|
||||
mu.Unlock()
|
||||
if f {
|
||||
if tc.fault != nil {
|
||||
return nil, tc.fault
|
||||
}
|
||||
}
|
||||
return inner(key, body)
|
||||
}
|
||||
clock := time.Unix(1000, 0)
|
||||
var waits []time.Duration
|
||||
s.r.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock }
|
||||
s.r.sleep = func(_ context.Context, d time.Duration) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
waits = append(waits, d)
|
||||
clock = clock.Add(d)
|
||||
return nil
|
||||
return inner(ask, key, body)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
outs := make([]stepOutcome, tc.steps)
|
||||
@@ -442,29 +712,127 @@ func TestTheCompositionStepReadsTheRevisionOnceAndAgainOnATimeout(t *testing.T)
|
||||
t.Fatalf("a step came to %+v, want %s", o, tc.want)
|
||||
}
|
||||
}
|
||||
if tc.waits == -1 { // never answers: bounded, growing waits
|
||||
if len(waits) < 3 || waits[0] != readsFirstWait || waits[1] != 2*readsFirstWait || waits[len(waits)-1] != readsMaxWait {
|
||||
t.Errorf("the waits %v do not grow to %s", waits, readsMaxWait)
|
||||
}
|
||||
var total time.Duration
|
||||
for _, w := range waits {
|
||||
total += w
|
||||
}
|
||||
if total > readsBound {
|
||||
t.Errorf("read again for %s, bound %s", total, readsBound)
|
||||
}
|
||||
if !strings.Contains(outs[0].Said, "catalog revision is not read") || !strings.Contains(outs[0].Said, "timeout") {
|
||||
t.Errorf("the step said %q", outs[0].Said)
|
||||
}
|
||||
return
|
||||
}
|
||||
if calls != tc.revisionCalls || len(waits) != tc.waits {
|
||||
t.Errorf("`revision` asked %d times with %d waits, want %d and %d", calls, len(waits), tc.revisionCalls, tc.waits)
|
||||
if calls != tc.revisionCalls {
|
||||
t.Errorf("`revision` asked %d times, want %d", calls, tc.revisionCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-708 (3), AC-A6: every read of a run is a kept call that stops at one deadline, the run's first read's time plus
|
||||
// reads-bound (default 8 minutes): two reads each unanswered in turn end the run could not run with the assigner's words before
|
||||
// the runner's bound of 10 minutes, naming the holder and its machine, the last fault and the calls; a read answered after a
|
||||
// fault of two minutes composes.
|
||||
func TestARunsReadsShareOneDeadline(t *testing.T) {
|
||||
step := meshwants.StepRun{Module: "m", Branch: "main", Revision: 7, Step: meshwants.StepRunStepComposition}
|
||||
away := &busretry.Away{Part: "the trunk's revision 512", Words: "not read yet since 23:35:40"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
answer func(clock *time.Time, ask process.KeptAsk, key string) error // a fault of the read, none: it answers
|
||||
want string
|
||||
bounds []time.Duration // the bound each kept call was given, in order
|
||||
}{
|
||||
{"seat-definitions met by no responders for two minutes and then answered composes", func(clock *time.Time, ask process.KeptAsk, key string) error {
|
||||
if key == seatDefinitionsKey && clock.Before(time.Unix(1000, 0).Add(2*time.Minute)) {
|
||||
*clock = clock.Add(2 * time.Minute) // the form met no responders for two minutes, then the holder answered
|
||||
}
|
||||
return nil
|
||||
}, meshwants.StepEndedOutcomeFailed, nil},
|
||||
{"two reads each unanswered in turn end the run at the shared deadline", func(clock *time.Time, ask process.KeptAsk, key string) error {
|
||||
if key == mcc.RevisionVerb || key == seatDefinitionsKey {
|
||||
*clock = clock.Add(ask.Bound) // the form asks again until the bound it is given
|
||||
return &busretry.Unanswered{Seat: "mesh-catalog", Verb: "x", Bound: ask.Bound, Tries: []busretry.Try{{At: *clock, Words: away.Error()}}, Last: away}
|
||||
}
|
||||
return nil
|
||||
}, meshwants.StepEndedOutcomeCouldNotRun, []time.Duration{8 * time.Minute}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := newRunStand(t, "src2:e1", "src2:e1", "d1")
|
||||
inner := s.r.call
|
||||
clock := time.Unix(1000, 0)
|
||||
var mu sync.Mutex
|
||||
var bounds []time.Duration
|
||||
s.r.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock }
|
||||
s.r.holder = func(seat string) (string, []string) { return "mesh-delivery-indexer", []string{"novox"} }
|
||||
s.r.call = func(ask process.KeptAsk, key string, body any) (json.RawMessage, error) {
|
||||
mu.Lock()
|
||||
bounds = append(bounds, ask.Bound)
|
||||
err := tc.answer(&clock, ask, key)
|
||||
mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return inner(ask, key, body)
|
||||
}
|
||||
out := s.r.run(context.Background(), "ask-step", step)
|
||||
if out.Outcome != tc.want {
|
||||
t.Fatalf("the step came to %+v, want %s", out, tc.want)
|
||||
}
|
||||
if tc.bounds == nil {
|
||||
return
|
||||
}
|
||||
total := clock.Sub(time.Unix(1000, 0))
|
||||
if total > 9*time.Minute || bounds[0] != 8*time.Minute {
|
||||
t.Errorf("the reads took %s with bounds %v, want the first at 8m and all before the runner's 10m", total, bounds)
|
||||
}
|
||||
for _, w := range []string{"mesh-delivery-indexer on novox", "not read yet since 23:35:40", "mesh-catalog"} {
|
||||
if !strings.Contains(out.Said, w) {
|
||||
t.Errorf("the step said %q, which does not name %q", out.Said, w)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-708 (4), H-A-731, AC-A7: a read that waited five minutes writes the finding call-unanswered, id `<seat>.<verb>`,
|
||||
// naming its holder and machine, the last fault and since when; the verb's answer clears it, and so does the end of the last read
|
||||
// waiting on it past its bound; a finding written before a restart, which no process of this run raised, is cleared the same way
|
||||
// (H-A-722: the clear reads the findings bucket's keys).
|
||||
func TestAReadUnansweredForFiveMinutesIsTheFindingCallUnanswered(t *testing.T) {
|
||||
step := meshwants.StepRun{Module: "m", Branch: "main", Revision: 7, Step: meshwants.StepRunStepComposition}
|
||||
for _, c := range []struct{ answered, restarted bool }{{true, false}, {false, false}, {true, true}, {false, true}} {
|
||||
answered, restarted := c.answered, c.restarted
|
||||
s := newRunStand(t, "src2:e1", "src2:e1", "d1")
|
||||
inner := s.r.call
|
||||
findings := map[string]mcseat.Finding{}
|
||||
s.r.findings = assign.Findings{Put: func(f mcseat.Finding) error { findings[views.FindingKey(f.Scope, f.ID, f.Kind)] = f; return nil },
|
||||
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(findings)), nil },
|
||||
Delete: func(key string) error { delete(findings, key); return nil }}
|
||||
s.r.holder = func(string) (string, []string) { return "mesh-delivery-indexer", []string{"novox"} }
|
||||
since := time.Unix(500, 0)
|
||||
key := mccond.Key(mccond.ScopeCall, "mesh-catalog.revision", mccond.KindCallUnanswered)
|
||||
if restarted { // written before a restart: this process raised nothing
|
||||
findings[key] = mcseat.Finding{}
|
||||
}
|
||||
s.r.call = func(ask process.KeptAsk, k string, body any) (json.RawMessage, error) {
|
||||
if k != mcc.RevisionVerb {
|
||||
return inner(ask, k, body)
|
||||
}
|
||||
if !restarted {
|
||||
ask.Hook(busretry.Waited{Seat: "mesh-catalog", Verb: "revision", Since: since, Last: "away: the trunk's revision 512 not read yet"})
|
||||
}
|
||||
if f, ok := findings[key]; !restarted && (!ok || !strings.Contains(f.Summary, "mesh-delivery-indexer on novox") || !strings.Contains(f.Summary, "the trunk's revision 512") ||
|
||||
!strings.Contains(f.Summary, since.UTC().Format(time.RFC3339))) {
|
||||
t.Errorf("at five minutes the findings are %+v", findings)
|
||||
}
|
||||
if answered {
|
||||
ask.Hook(busretry.Waited{Seat: "mesh-catalog", Verb: "revision", Since: since, Answered: true})
|
||||
if _, ok := findings[key]; ok {
|
||||
t.Error("the answer left the finding")
|
||||
}
|
||||
return inner(ask, k, body)
|
||||
}
|
||||
return nil, &busretry.Unanswered{Seat: "mesh-catalog", Verb: "revision", Bound: ask.Bound}
|
||||
}
|
||||
if out := s.r.run(context.Background(), "ask-step", step); answered == (out.Outcome == meshwants.StepEndedOutcomeCouldNotRun) {
|
||||
t.Errorf("answered %v: the step came to %+v", answered, out)
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("answered %v: the findings stand after the read: %+v", answered, findings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G §718, §719, §720: three composition steps of one revision on two machines start two runs, one request and one run
|
||||
// ask per machine, and each step reads both verdicts; the run records its program with the node-engine fingerprint it was chosen
|
||||
// from and the digest of its kept request, which names no module of the asking pipeline; a step of another candidate starts its
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
meshbuilds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
@@ -60,16 +61,35 @@ type runSettings struct {
|
||||
kept, stepBound, untaken time.Duration
|
||||
// blameTries is blame-tries, carried in each run's request (§721).
|
||||
blameTries int
|
||||
// packageWait is package-wait-minutes: how long a run waits for the publish of a package its entry names with no version
|
||||
// before it ends could not run naming the package, counted from the time its wait began (design 47 H2 H-A-628 (3), H-A-629 (3)).
|
||||
packageWait time.Duration
|
||||
}
|
||||
|
||||
// defaultRunSettings are the settings' defaults, as the manifest gives them.
|
||||
var defaultRunSettings = runSettings{capBytes: 16 << 20, kept: 24 * time.Hour, stepBound: 30 * time.Minute, untaken: 24 * time.Hour, blameTries: 20}
|
||||
var defaultRunSettings = runSettings{capBytes: 16 << 20, kept: 24 * time.Hour, stepBound: 30 * time.Minute, untaken: 24 * time.Hour, blameTries: 20,
|
||||
packageWait: 10 * time.Minute}
|
||||
|
||||
// packageWaitUnit is the unit of the setting package-wait-minutes, a minute; the whole test sets a shorter one, so a run's wait
|
||||
// passes its bound within the test (as tierBoundUnit).
|
||||
var packageWaitUnit = time.Minute
|
||||
|
||||
// packageWaitSetting names the setting package-wait-minutes in a run's words.
|
||||
const packageWaitSetting = "package-wait-minutes"
|
||||
|
||||
// runSettingsOf reads the settings composition-runs-cap-mib, composition-runs-kept, composition-step-bound,
|
||||
// run-untaken-bound and blame-tries from the files the environment names (A-469x, as outsideSettings): a missing or empty
|
||||
// file is its default; a content that is no positive whole number or Go duration is an error naming the file.
|
||||
// run-untaken-bound, blame-tries and package-wait-minutes from the files the environment names (A-469x, as outsideSettings): a
|
||||
// missing or empty file is its default; a content that is no positive whole number or Go duration is an error naming the file.
|
||||
func runSettingsOf(getenv func(string) string) (runSettings, error) {
|
||||
s := defaultRunSettings
|
||||
s.packageWait = 10 * packageWaitUnit
|
||||
minutes, err := settingFile(getenv("MESH_ASSIGNER_PACKAGE_WAIT_FILE"))
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
if minutes > 0 {
|
||||
s.packageWait = time.Duration(minutes) * packageWaitUnit
|
||||
}
|
||||
mib, err := settingFile(getenv("MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE"))
|
||||
if err != nil {
|
||||
return s, err
|
||||
@@ -255,12 +275,16 @@ type compositionRuns struct {
|
||||
mu sync.Mutex
|
||||
// changed is closed and replaced at each change of the state heard (heard): a step waiting on a run reads its key again.
|
||||
changed chan struct{}
|
||||
// published holds, by the artifact of a package's publisher (<module>:<artifact>), what is closed and deleted at the seat
|
||||
// mesh-builds' package-published of that artifact heard (heardPublished), and at each bind of the consumer: a run waiting for
|
||||
// the package that artifact publishes asks published again (design 47 H2 H-A-628 (3), H-A-630 (1); H-A-326).
|
||||
published map[string]chan struct{}
|
||||
// seen are the keys the state's watch handed and has not seen deleted: a listing of the bucket misses a key that is
|
||||
// being written at that moment, so every lookup takes these beside it (keys).
|
||||
seen map[string]bool
|
||||
// say says an event of the seat mesh-wants (a reader's wait, A-469y); drop asks the build seat's drop of a run ask (§119);
|
||||
// nil says or drops nothing.
|
||||
say publisher
|
||||
// owe owes an event of the seat mesh-wants (a reader's wait, A-469y) in the order given, as the passer owes every event it says
|
||||
// (design 47 H2b §832 1., H-A-873); drop asks the build seat's drop of a run ask (§119); nil owes or drops nothing.
|
||||
owe func(order, event string, body any, id string)
|
||||
drop func(ask, why string) error
|
||||
// moved is told each run that ended, for the readers a rerun carried to say their end again (compositionSteps.move).
|
||||
// Set once the steps are served, after the hub starts.
|
||||
@@ -268,7 +292,98 @@ type compositionRuns struct {
|
||||
}
|
||||
|
||||
func newCompositionRuns(kv runsKV, set runSettings, now func() time.Time, logf func(string, ...any)) *compositionRuns {
|
||||
return &compositionRuns{kv: kv, set: set, now: now, logf: logf, changed: make(chan struct{})}
|
||||
return &compositionRuns{kv: kv, set: set, now: now, logf: logf, changed: make(chan struct{}), published: map[string]chan struct{}{}}
|
||||
}
|
||||
|
||||
// heardPublished wakes the runs waiting for the package artifact publishes, at the seat mesh-builds' package-published of that
|
||||
// artifact heard: each reads published again, the event only its second path; a publish of another package wakes none, so it asks
|
||||
// no published (design 47 H2 H-A-628 (3), H-A-630 (1); H-A-326, H-A-328).
|
||||
func (r *compositionRuns) heardPublished(artifact string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if w, ok := r.published[artifact]; ok {
|
||||
close(w)
|
||||
delete(r.published, artifact)
|
||||
}
|
||||
}
|
||||
|
||||
// heardBind wakes every run waiting for a package's publish, at each bind of the assigner's consumer of package-published, which
|
||||
// hears no event said before it was made: each reads published again.
|
||||
func (r *compositionRuns) heardBind() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for artifact, w := range r.published {
|
||||
close(w)
|
||||
delete(r.published, artifact)
|
||||
}
|
||||
}
|
||||
|
||||
// publishWake is closed at the next package-published of artifact heard, or the consumer's next bind.
|
||||
func (r *compositionRuns) publishWake(artifact string) <-chan struct{} {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
w, ok := r.published[artifact]
|
||||
if !ok {
|
||||
w = make(chan struct{})
|
||||
r.published[artifact] = w
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// hearPublished hears the seat mesh-builds' package-published on the assigner's durable consumer: the runs waiting for the
|
||||
// package its artifact publishes are woken (heardPublished, design 47 H2 H-A-630 (1)); one that does not read wakes none and is
|
||||
// journaled. Each bind of the consumer wakes every waiting run (heardBind, H-A-630 (2)): an event said while it was not bound is
|
||||
// never heard, so no run waits until its bound alone ends it while its package stands published.
|
||||
func hearPublished(hub interface {
|
||||
Handle(string, func(jetstream.Msg)) error
|
||||
OnBound(func(time.Time))
|
||||
}, r *compositionRuns, logf func(string, ...any)) error {
|
||||
hub.OnBound(func(time.Time) { r.heardBind() })
|
||||
return hub.Handle(meshbuilds.SubjectPackagePublished, func(m jetstream.Msg) {
|
||||
ev, _, err := meshbuilds.DecodePackagePublishedEvent(m.Data())
|
||||
if err != nil || ev.Artifact == "" {
|
||||
logf("%s holds what is no package-published naming its artifact, so it wakes no composition run: %v", m.Subject(), err)
|
||||
_ = m.Ack()
|
||||
return
|
||||
}
|
||||
r.heardPublished(ev.Artifact)
|
||||
_ = m.Ack()
|
||||
})
|
||||
}
|
||||
|
||||
// waitFor writes on the run of ask the package it waits for, `waits` (design 47 H2 H-A-629 (1)), with the words of the entry
|
||||
// that names it with no version (H-A-631), by compare-and-set: the time its wait began is kept where the run holds one already (a
|
||||
// start taken up again, H-A-629 (3)), else it is now. It answers that time, and false when the key holds another run, or the run
|
||||
// ended or has its program.
|
||||
func (r *compositionRuns) waitFor(key, ask, path, entry string) (time.Time, bool, error) {
|
||||
var since time.Time
|
||||
held := false
|
||||
_, _, err := r.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
if held = c.Ask == ask && c.Ended == nil && c.Program == nil; !held {
|
||||
return false
|
||||
}
|
||||
since = r.now().UTC()
|
||||
if c.Waits != nil {
|
||||
since = c.Waits.Since
|
||||
if c.Waits.Package == path && c.Waits.Entry == entry {
|
||||
return false
|
||||
}
|
||||
}
|
||||
c.Waits = &meshwants.CompositionRunWaits{Package: path, Entry: entry, Since: since}
|
||||
return true
|
||||
})
|
||||
return since, held, err
|
||||
}
|
||||
|
||||
// pastWaitSaid is the end of a run of machine whose wait for the publish of the package path, which the entry names with no
|
||||
// version, passed package-wait-minutes: it names the package, the entry and the bound on every path that ends it, the waiting
|
||||
// start's, the bound's expiry and the take-up's, each from `waits` (design 47 H2 H-A-628 (3), (5); H-A-630 (4); H-A-631).
|
||||
func (r *compositionRuns) pastWaitSaid(machine string, w meshwants.CompositionRunWaits) string {
|
||||
said := fmt.Sprintf("package %s has no published version within %s (%s), named with no version in %s", w.Package, r.set.packageWait, packageWaitSetting, w.Entry)
|
||||
if machine != "" {
|
||||
said = machine + ": " + said
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
// heard takes a change of the state from its watch (a module watches its own state, principle 1).
|
||||
@@ -642,6 +757,7 @@ func (r *compositionRuns) end(key, ask, outcome, said string, verdict map[string
|
||||
}
|
||||
at := r.now().UTC()
|
||||
c.Ended, c.Outcome, c.Said, c.Verdict = &at, outcome, said, verdict
|
||||
c.Waits = nil // a run's wait ends with it (H-A-629 (1))
|
||||
ended = true
|
||||
return true
|
||||
})
|
||||
@@ -702,6 +818,11 @@ func (r *compositionRuns) heardEnd(e buildstep.StepEnded, read func(buildstep.St
|
||||
// await waits until each run of keys has ended, through the state's changes heard, or ctx ends: it answers each run as it
|
||||
// stands then; a key gone could not run.
|
||||
func (r *compositionRuns) await(ctx context.Context, keys []string) map[string]meshwants.CompositionRun {
|
||||
return r.awaitEach(ctx, keys, nil)
|
||||
}
|
||||
|
||||
// awaitEach is await, handing each read of the runs, as they stand, to each before it waits again; nil hands none.
|
||||
func (r *compositionRuns) awaitEach(ctx context.Context, keys []string, each func(map[string]meshwants.CompositionRun)) map[string]meshwants.CompositionRun {
|
||||
out := map[string]meshwants.CompositionRun{}
|
||||
for {
|
||||
wake := r.wake()
|
||||
@@ -722,6 +843,9 @@ func (r *compositionRuns) await(ctx context.Context, keys []string) map[string]m
|
||||
}
|
||||
out[key] = run
|
||||
}
|
||||
if each != nil {
|
||||
each(out)
|
||||
}
|
||||
if !open {
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -324,7 +324,8 @@ func TestACompositionRunIsOneKeyPerCandidateAndMachine(t *testing.T) {
|
||||
t.Run("settings", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
files := map[string]string{"MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE": "8", "MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "2h",
|
||||
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "2s", "MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "", "MESH_ASSIGNER_BLAME_TRIES_FILE": "5"}
|
||||
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "2s", "MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "", "MESH_ASSIGNER_BLAME_TRIES_FILE": "5",
|
||||
"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "3"} // package-wait-minutes in minutes (design 47 H2 H-A-628 (3))
|
||||
env := map[string]string{}
|
||||
for name, content := range files {
|
||||
p := filepath.Join(dir, name)
|
||||
@@ -334,7 +335,8 @@ func TestACompositionRunIsOneKeyPerCandidateAndMachine(t *testing.T) {
|
||||
env[name] = p
|
||||
}
|
||||
s, err := runSettingsOf(func(k string) string { return env[k] })
|
||||
if err != nil || s.capBytes != 8<<20 || s.kept != 2*time.Hour || s.stepBound != 2*time.Second || s.untaken != 24*time.Hour || s.blameTries != 5 {
|
||||
if err != nil || s.capBytes != 8<<20 || s.kept != 2*time.Hour || s.stepBound != 2*time.Second || s.untaken != 24*time.Hour || s.blameTries != 5 ||
|
||||
s.packageWait != 3*time.Minute {
|
||||
t.Errorf("settings %+v %v", s, err)
|
||||
}
|
||||
_ = os.WriteFile(env["MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE"], []byte("30"), 0o600)
|
||||
@@ -372,13 +374,12 @@ func TestACompositionRunsBoundTimesOwedProgress(t *testing.T) {
|
||||
journal = append(journal, fmt.Sprintf(f, a...))
|
||||
mu.Unlock()
|
||||
})
|
||||
r.say = func(event string, body any, _ string) error {
|
||||
r.owe = func(_, event string, body any, _ string) {
|
||||
w := body.(meshwants.Wait)
|
||||
if w.On != waitOnBuildNode || w.Step != "pipeline" || w.Owner != meshwants.Seat || w.Node == "" {
|
||||
t.Errorf("the wait said %+v", w)
|
||||
}
|
||||
saids = append(saids, said{event, w.How, w.Module})
|
||||
return nil
|
||||
}
|
||||
r.drop = func(ask, why string) error { drops = append(drops, ask+": "+why); return nil }
|
||||
return kv, r, &saids, &drops, &journal
|
||||
@@ -449,6 +450,56 @@ func TestACompositionRunsBoundTimesOwedProgress(t *testing.T) {
|
||||
t.Errorf("an ended run is dropped again: %v", *drops)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 1., 2., 4. (H-A-873, review r1 finding 4): a reader's wait-held and wait-ended are owed as every event is, in the order
|
||||
// of their `<node>.<module>`, said again under their ids once the bus takes them, and a start says the waits of an open run again.
|
||||
t.Run("a refused wait event is owed in order and said again; a start says the waits of an open run again", func(t *testing.T) {
|
||||
kv := newRunsMem()
|
||||
r := newCompositionRuns(kv, defaultRunSettings, func() time.Time { return now }, t.Logf)
|
||||
p := newPasser(kvSet{}, now)
|
||||
var said []string
|
||||
refuse := true
|
||||
p.publishWants = func(event string, _ any, id string) error {
|
||||
if refuse {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
said = append(said, event+" "+id)
|
||||
return nil
|
||||
}
|
||||
r.owe = func(order, event string, body any, id string) { p.wantsOwe(order, event, body, id, nil) }
|
||||
if _, err := r.join(reader("a"), "main.3", "n1", "run-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held := p.owedAll()
|
||||
if len(held) != 1 || !strings.HasSuffix(held[0].ID, ".a.held") {
|
||||
t.Fatalf("the refused wait-held is not owed: %+v", held)
|
||||
}
|
||||
// A restart: a new passer and runs over the kept state say the open run's waits again under the same id.
|
||||
p = newPasser(kvSet{}, now)
|
||||
p.publishWants = func(event string, _ any, id string) error { said = append(said, event+" "+id); return nil }
|
||||
r = newCompositionRuns(kv, defaultRunSettings, func() time.Time { return now }, t.Logf)
|
||||
r.owe = func(order, event string, body any, id string) { p.wantsOwe(order, event, body, id, nil) }
|
||||
r.sayWaitsAgain()
|
||||
if len(said) != 1 || said[0] != meshwants.EventWaitHeld+" "+held[0].ID {
|
||||
t.Fatalf("the start said %v, want the wait-held under %s", said, held[0].ID)
|
||||
}
|
||||
// The end made while the held is owed is said after it.
|
||||
refuse, said = true, nil
|
||||
p.publishWants = func(event string, _ any, id string) error {
|
||||
if refuse {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
said = append(said, event+" "+id)
|
||||
return nil
|
||||
}
|
||||
kv.expire(runUntakenPrefix + key)
|
||||
r.expired(runUntakenPrefix + key)
|
||||
refuse = false
|
||||
p.owed.list[0].next = p.clock()
|
||||
p.sayOwed()
|
||||
if len(said) != 1 || !strings.HasPrefix(said[0], meshwants.EventWaitEnded+" ") || len(p.owedAll()) != 0 {
|
||||
t.Errorf("the owed wait-ended said %v, still owed %v", said, p.owedAll())
|
||||
}
|
||||
})
|
||||
// A-470n, A-470o: a bound holds its run's ask, armed for it alone; a late signal of a run replaced moves nothing and is
|
||||
// journaled; an expiry ends the run only while its bound is still absent and the run taken (bound.) or untaken (untaken.).
|
||||
rerun := func(kv *runsMem, r *compositionRuns) func() { // a rerun replaces run-1 by run-2, its bounds gone, run-2's untaken armed
|
||||
|
||||
@@ -104,9 +104,9 @@ func (c *compositionSteps) drop(r *compositionRuns, record func(meshhandactsclie
|
||||
return answer, err
|
||||
}
|
||||
|
||||
// compositionVerbs are the process's handlers of the seat mesh-wants' verbs compositions and compositions-drop.
|
||||
func compositionVerbs(r *compositionRuns, c *compositionSteps, record func(meshhandactsclient.Request) error) map[string]process.SeatHandler {
|
||||
return map[string]process.SeatHandler{
|
||||
// compositionVerbs are the process's handlers of the seat mesh-wants' verbs compositions, compositions-drop and validate.
|
||||
func compositionVerbs(r *compositionRuns, c *compositionSteps, record func(meshhandactsclient.Request) error, validate *compositionRun) map[string]process.SeatHandler {
|
||||
verbs := map[string]process.SeatHandler{
|
||||
meshwants.VerbCompositions: func(_ string, raw json.RawMessage) (any, error) {
|
||||
var in meshwants.CompositionsInput
|
||||
if len(raw) > 0 {
|
||||
@@ -124,6 +124,17 @@ func compositionVerbs(r *compositionRuns, c *compositionSteps, record func(meshh
|
||||
return c.drop(r, record, caller, in)
|
||||
},
|
||||
}
|
||||
if validate != nil {
|
||||
// The seat's verb validate (design 47 H2 H-A-727): the tool assigner_validate reaches the process, which keeps the runs.
|
||||
verbs[meshwants.VerbValidate] = func(caller string, raw json.RawMessage) (any, error) {
|
||||
var in meshwants.ValidateInput
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
return nil, fmt.Errorf("the arguments are not JSON: %w", err)
|
||||
}
|
||||
return validate.validateOnRequest(validate.own, record, caller, in)
|
||||
}
|
||||
}
|
||||
return verbs
|
||||
}
|
||||
|
||||
// compositionsTools are the module's tools of §728's names, each calling its verb (A-469f).
|
||||
|
||||
+2
-2
@@ -45,14 +45,14 @@ func TestTheCompositionRunsAreReadAndDroppedByTheirVerbs(t *testing.T) {
|
||||
})
|
||||
var recorded []meshhandactsclient.Request
|
||||
record := func(q meshhandactsclient.Request) error { recorded = append(recorded, q); return nil }
|
||||
verbs := compositionVerbs(r, c, record)
|
||||
verbs := compositionVerbs(r, c, record, nil)
|
||||
out, err := verbs[meshwants.VerbCompositions]("op", json.RawMessage(`{"machine":"n2"}`))
|
||||
read, _ := out.(meshwants.CompositionsAnswer)
|
||||
if err != nil || len(read.Runs) != 1 || read.Runs[0].Key != runKeyOf("main.3", "n2") || read.Runs[0].Ask != "run-n2" || len(read.Runs[0].Readers) != 3 ||
|
||||
read.Fill.Store != "composition-runs" || read.Fill.Cap != 16<<20 || read.Fill.Bytes == 0 {
|
||||
t.Fatalf("compositions = %+v %v", out, err)
|
||||
}
|
||||
refuse := compositionVerbs(r, c, func(meshhandactsclient.Request) error { return errors.New("no holder") })
|
||||
refuse := compositionVerbs(r, c, func(meshhandactsclient.Request) error { return errors.New("no holder") }, nil)
|
||||
if _, err := refuse[meshwants.VerbCompositionsDrop]("op", json.RawMessage(`{"candidate":"main.3","machine":"n2","why":"stuck"}`)); err == nil ||
|
||||
!strings.Contains(err.Error(), "nothing was dropped") || len(drops) != 0 {
|
||||
t.Fatalf("a drop not recorded: %v, drops %v", err, drops)
|
||||
|
||||
+173
-10
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient/enginereads"
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshwatchdogs"
|
||||
meshbuilds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
@@ -31,8 +33,25 @@ import (
|
||||
// machine on the Go build seat's check queue under its name, its program the node-engine build each machine runs; the stand-in
|
||||
// build seat reads each request by the seat mesh-wants' verb input in chunks and says its step-ended with the composer's verdict;
|
||||
// the step's step-ended fails naming the machine that does not compose, warns of the machine away, and no input stays kept.
|
||||
// 1984/AC11 (design 47 H2 H-A-628 (2) to (5), H-A-629): the node-engine's entry names the package x/go with no version, and x's
|
||||
// build in the step's revision publishes it: each run waits while the seat mesh-builds' published answers not published, and
|
||||
// puts its run ask with x/go at the version published once the package-published is heard; a restart during the wait takes the
|
||||
// runs up, the one past package-wait-minutes ending could not run naming the package, the other's start run again composing
|
||||
// after a publish heard while the assigner was down; a run whose wait passes its bound ends could not run naming the package
|
||||
// and the bound, never "no pin … the builder pins or waits", with no run ask put.
|
||||
func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T) {
|
||||
b := startBed(t, "")
|
||||
t.Cleanup(func() {
|
||||
if t.Failed() {
|
||||
b.journal.mu.Lock()
|
||||
t.Log(b.journal.text.String())
|
||||
b.journal.mu.Unlock()
|
||||
}
|
||||
})
|
||||
packageWaitUnit = time.Second // package-wait-minutes in seconds at the test's unit
|
||||
t.Cleanup(func() { packageWaitUnit = time.Minute })
|
||||
b.settings = map[string]string{"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "30"}
|
||||
const pkg = "git.novox.be/novox/x/go"
|
||||
nc, err := nats.Connect(b.srv.ClientURL())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -43,7 +62,7 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
// machine-back, as the grants part derives them from its consumes; what each node runs it hears on its kept stream (the bed's).
|
||||
if _, err := b.js.CreateOrUpdateConsumer(b.ctx, "EVENTS", jetstream.ConsumerConfig{Durable: "n1_mesh-delivery-assigner",
|
||||
FilterSubjects: []string{enginereads.SubjectPrefix + "*", "mesh.mod." + buckets.IndexerModule + ".event.views.>", meshcatalog.SubjectCatalogRevisionAll,
|
||||
nodebuildgo.SubjectStepEndedAll, meshwatchdogs.SubjectMachineAwayAll, meshwatchdogs.SubjectMachineBackAll}, AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
|
||||
nodebuildgo.SubjectStepEndedAll, meshwatchdogs.SubjectMachineAwayAll, meshwatchdogs.SubjectMachineBackAll, meshbuilds.SubjectPackagePublished}, AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, node := range []string{"n1", "n2"} {
|
||||
@@ -59,10 +78,12 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
}
|
||||
// The trunk's catalog half holds the module and the node-engine, the module claiming the seat node-engine.
|
||||
engine := meshcatalog.CatalogEntry{Module: "engine", Fp: "src2:e1", Repository: "novox/mesh-host", Commit: engineCommit, Path: ".",
|
||||
Serves: []string{nodeengine.Seat + ".composition"}, Manifest: map[string]any{"module": "engine", "version": "0.1"}}
|
||||
Serves: []string{nodeengine.Seat + ".composition"}, Manifest: map[string]any{"module": "engine", "version": "0.1"}, Packages: map[string]string{pkg: ""}}
|
||||
b.cat.mu.Lock()
|
||||
b.cat.entries[trunkBranch] = map[string]meshcatalog.CatalogEntry{"engine": engine,
|
||||
"m": {Module: "m", Fp: "src2:m1", Repository: "novox/m", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "m", "version": "0.1"}}}
|
||||
"m": {Module: "m", Fp: "src2:m1", Repository: "novox/m", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "m", "version": "0.1"}},
|
||||
"x": {Module: "x", Fp: "src2:x1", Repository: "novox/x", Commit: engineCommit, Path: ".", Manifest: map[string]any{"module": "x", "version": "0.1"},
|
||||
Artifacts: []meshcatalog.Artifact{{Ref: "x:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: pkg}}}}}
|
||||
b.cat.rev[trunkBranch] = 3
|
||||
b.cat.mu.Unlock()
|
||||
for _, node := range []string{"n1", "n2", "n3"} {
|
||||
@@ -72,7 +93,10 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
asked := make(chan string, 8)
|
||||
engines, err := nc.Subscribe("mesh.seat.node-engine.call.compose-candidate.*.*", func(m *nats.Msg) {
|
||||
node := strings.Split(m.Subject, ".")[5]
|
||||
asked <- node
|
||||
select { // the first step's asks are read; a later step's runs ask again
|
||||
case asked <- node:
|
||||
default:
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"result": map[string]any{"candidate": "main.3", "node": node, "verdict": "composed", "input": map[string]any{"node": node},
|
||||
"modules": []any{}, "own": map[string]any{}, "took": 1, "v": 1}, "node": node})
|
||||
_ = m.Respond(raw)
|
||||
@@ -90,9 +114,23 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = entries.Unsubscribe() })
|
||||
// The seat mesh-builds' published answers x's build published at 0.1.9 once pub is set (H-A-328).
|
||||
var pub atomic.Bool
|
||||
publishedAsks, err := nc.Subscribe("mesh.seat.mesh-builds.call.published.*", func(m *nats.Msg) {
|
||||
a := meshbuilds.PublishedAnswer{}
|
||||
if pub.Load() {
|
||||
a = meshbuilds.PublishedAnswer{Published: true, Version: "0.1.9"}
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"result": a, "node": "n0"})
|
||||
_ = m.Respond(raw)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = publishedAsks.Unsubscribe() })
|
||||
subscribed(t, nc)
|
||||
// The runner hears the step's end.
|
||||
ended := make(chan meshwants.StepEnded, 1)
|
||||
ended := make(chan meshwants.StepEnded, 8)
|
||||
ends, err := nc.Subscribe("mesh.seat.mesh-wants.event.step-ended.n1", func(m *nats.Msg) {
|
||||
var e meshwants.StepEnded
|
||||
_ = json.Unmarshal(m.Data, &e)
|
||||
@@ -105,7 +143,7 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
subscribed(t, nc)
|
||||
|
||||
from := b.journal.mark()
|
||||
b.start(t)
|
||||
_, stop := b.startStoppable(t)
|
||||
b.journal.await(t, from, "the composition step is pulled from", "the composition step served", 30*time.Second)
|
||||
b.journal.await(t, from, "n3 is away (machine-away)", "the machine-away of n3 heard", 30*time.Second)
|
||||
|
||||
@@ -114,8 +152,31 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the assigner did not read the seat list within 30 s")
|
||||
}
|
||||
// H2 H-A-708 (3), AC-A6b: the seat mesh-catalog's holder is stopped while the composition reads its entry: the read is a kept
|
||||
// call, the journal says the seat does not answer, and the step goes on and passes once the holder answers again.
|
||||
b.cat.stop()
|
||||
outage := b.journal.mark()
|
||||
putStep(b.ctx, t, b.js, "step-ask-1", meshwants.StepRun{Pipeline: "main.3.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
|
||||
Revision: 3, Commit: engineCommit, Fingerprint: "src2:m1"})
|
||||
select { // the read met the stopped holder, and the step has gone no further
|
||||
case <-b.cat.met:
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("no read reached the stopped seat mesh-catalog")
|
||||
}
|
||||
if b.journal.has(outage, "the composition step of m says fetch") {
|
||||
t.Fatal("the step went on while the seat mesh-catalog's holder was stopped")
|
||||
}
|
||||
b.cat.serve()
|
||||
// Each machine's run waits for x/go's publish, the step saying fetch; the publish heard, each puts its run ask (1984/AC11).
|
||||
for _, node := range []string{"n1", "n2"} {
|
||||
b.journal.await(t, from, "the composition run main=2e3."+node+" waits for package "+pkg, "the run of "+node+" waits", 30*time.Second)
|
||||
}
|
||||
b.journal.await(t, from, "the composition step of m says fetch", "the step says fetch", 30*time.Second)
|
||||
pub.Store(true)
|
||||
published, _ := json.Marshal(meshbuilds.PackagePublished{V: 1, Module: "x", Artifact: "x:go", Version: "0.1.9", Digest: "sha256:x", Branch: trunkBranch, Source: 3})
|
||||
if _, err := b.js.Publish(b.ctx, meshbuilds.SubjectPackagePublished, published); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The stand-in Go build seat takes the run asks put under the assigner's name, reads each request by the verb input and says
|
||||
// its end with the composer's verdict: n1 composes, n2 does not.
|
||||
@@ -146,6 +207,9 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
}
|
||||
node := req.Machines[0]
|
||||
programs[node] = a.Run.Program.Commit
|
||||
if a.Packages[pkg] != "v0.1.9" {
|
||||
t.Errorf("the composer of %s is built against %v, want x/go at v0.1.9 from published", node, a.Packages)
|
||||
}
|
||||
m := composer.Machine{Composes: true}
|
||||
if node == "n2" {
|
||||
m = composer.Machine{Reason: "two modules own one path", Problems: []string{"/etc/x"}}
|
||||
@@ -170,10 +234,14 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
if programs["n1"] != engineCommit || programs["n2"] != engineCommit {
|
||||
t.Errorf("the composers were built at %v, want the node-engine build each machine runs", programs)
|
||||
}
|
||||
close(asked)
|
||||
for node := range asked {
|
||||
if node == "n3" {
|
||||
t.Error("the machine away was asked for its input")
|
||||
for drained := false; !drained; {
|
||||
select {
|
||||
case node := <-asked:
|
||||
if node == "n3" {
|
||||
t.Error("the machine away was asked for its input")
|
||||
}
|
||||
default:
|
||||
drained = true
|
||||
}
|
||||
}
|
||||
// The run's end comes before the input's delete (A-470o, A-470p): the inputs go after the step's end, heard by their watch.
|
||||
@@ -196,6 +264,101 @@ func TestTheCompositionStepComposesEachMachineThroughTheBuildSeat(t *testing.T)
|
||||
}
|
||||
}
|
||||
queueEmpty(b.ctx, t, b.js) // the step's ask acknowledged at its end (design 47 H2 §777)
|
||||
|
||||
// A restart during the wait (H-A-629 (3)): the runs of the next revision wait, the assigner stops, n2's wait is aged past
|
||||
// package-wait-minutes as if the assigner were down that long, and x/go is published with no event heard. The start takes
|
||||
// both up: n2's ends could not run naming the package; n1's start runs again, reads published first and composes.
|
||||
revision := func(n int64) {
|
||||
b.cat.mu.Lock()
|
||||
b.cat.rev[trunkBranch] = n
|
||||
b.cat.mu.Unlock()
|
||||
}
|
||||
stepEnd := func(id string) meshwants.StepEnded {
|
||||
t.Helper()
|
||||
for {
|
||||
select {
|
||||
case e := <-ended:
|
||||
if e.ID == id {
|
||||
return e
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatalf("the step %s said no end within 30 s", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub.Store(false)
|
||||
revision(4)
|
||||
from = b.journal.mark()
|
||||
putStep(b.ctx, t, b.js, "step-ask-2", meshwants.StepRun{Pipeline: "main.4.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
|
||||
Revision: 4, Commit: engineCommit, Fingerprint: "src2:m1"})
|
||||
for _, node := range []string{"n1", "n2"} {
|
||||
b.journal.await(t, from, "the composition run main=2e4."+node+" waits for package "+pkg, "the run of "+node+" waits", 30*time.Second)
|
||||
}
|
||||
stop()
|
||||
runs := b.buckets[buckets.CompositionRuns()]
|
||||
e2, err := runs.Get(b.ctx, "main=2e4.n2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var waiting meshwants.CompositionRun
|
||||
if err := json.Unmarshal(e2.Value(), &waiting); err != nil || waiting.Waits == nil || waiting.Waits.Package != pkg ||
|
||||
waiting.Waits.Entry != "the node-engine's entry src2:e1" || waiting.Program != nil {
|
||||
t.Fatalf("the waiting run of n2 holds %s (%v), want waits naming x/go and its entry, and no program", e2.Value(), err)
|
||||
}
|
||||
waiting.Waits.Since = waiting.Waits.Since.Add(-time.Hour)
|
||||
aged, _ := json.Marshal(waiting)
|
||||
if _, err := runs.Update(b.ctx, "main=2e4.n2", aged, e2.Revision()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub.Store(true)
|
||||
from = b.journal.mark()
|
||||
_, stop = b.startStoppable(t)
|
||||
b.journal.await(t, from, "the composition run main=2e4.n1, waiting for package "+pkg, "the run of n1 taken up", 30*time.Second)
|
||||
got, err := worker.Next(jetstream.FetchMaxWait(30 * time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("no run ask is put after the restart: %v", err)
|
||||
}
|
||||
_ = got.Ack()
|
||||
a, err := buildstep.DecodeStepAsk(got.Data())
|
||||
if err != nil || a.Run == nil || a.Packages[pkg] != "v0.1.9" {
|
||||
t.Fatalf("the run ask after the restart %+v (%v), want x/go at v0.1.9", a, err)
|
||||
}
|
||||
if req, err := composer.Decode(readInput(t, nc, a.Run.Input)); err != nil || len(req.Machines) != 1 || req.Machines[0] != "n1" {
|
||||
t.Fatalf("the run ask after the restart composes %+v (%v), want n1", req.Machines, err)
|
||||
}
|
||||
v, _ := json.Marshal(composer.Verdict{V: composer.Version, Cases: []composer.CaseVerdict{{Name: changeCase, Machines: map[string]composer.Machine{"n1": {Composes: true}}}}})
|
||||
end, _ := json.Marshal(buildstep.StepEnded{V: 1, ID: a.ID, Ask: a.ID, Asker: runAsker, Node: "b1", Outcome: buildstep.OutcomePassed, Output: string(v), At: time.Now().UTC()})
|
||||
if _, err := b.js.Publish(b.ctx, nodebuildgo.SubjectStepEnded("b1"), end); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e := stepEnd("step-ask-2"); e.Outcome != meshwants.StepEndedOutcomeCouldNotRun || strings.Contains(e.Said, "the builder pins or waits") ||
|
||||
!strings.Contains(e.Said, "n2: package "+pkg+" has no published version within 30s (package-wait-minutes), named with no version in the node-engine's entry src2:e1") ||
|
||||
strings.Contains(e.Said, "n1") {
|
||||
t.Fatalf("the step taken up ended %+v, want could not run naming n2's package past its bound alone", e)
|
||||
}
|
||||
|
||||
// Past the bound while running (H-A-628 (3), (4)): with package-wait-minutes at one, nothing is published, the bound's expiry
|
||||
// ends each run could not run naming the package, the entry and the bound (H-A-630 (4), H-A-631), and no run ask is put.
|
||||
stop()
|
||||
b.settings["MESH_ASSIGNER_PACKAGE_WAIT_FILE"] = "1"
|
||||
pub.Store(false)
|
||||
revision(5)
|
||||
from = b.journal.mark()
|
||||
_, stop = b.startStoppable(t)
|
||||
b.journal.await(t, from, "the composition step is pulled from", "the composition step served again", 30*time.Second)
|
||||
putStep(b.ctx, t, b.js, "step-ask-3", meshwants.StepRun{Pipeline: "main.5.m", Step: meshwants.StepRunStepComposition, Module: "m", Branch: trunkBranch,
|
||||
Revision: 5, Commit: engineCommit, Fingerprint: "src2:m1"})
|
||||
e3 := stepEnd("step-ask-3")
|
||||
for _, node := range []string{"n1", "n2"} {
|
||||
if want := node + ": package " + pkg + " has no published version within 1s (package-wait-minutes), named with no version in the node-engine's entry src2:e1"; e3.Outcome != meshwants.StepEndedOutcomeCouldNotRun ||
|
||||
!strings.Contains(e3.Said, want) || strings.Contains(e3.Said, "the builder pins or waits") {
|
||||
t.Fatalf("the step past its bound ended %+v, want could not run saying %q", e3, want)
|
||||
}
|
||||
}
|
||||
if info, err := worker.Info(b.ctx); err != nil || info.NumPending != 0 || info.NumAckPending != 0 {
|
||||
t.Errorf("run asks were put past the bound: %+v %v", info, err)
|
||||
}
|
||||
stop()
|
||||
}
|
||||
|
||||
// readInput reads a run's input as a build seat does: the seat mesh-wants' verb input answers its digest and chunk count, then its
|
||||
|
||||
@@ -365,8 +365,10 @@ func (p *passer) capabilityDigests() []meshwants.AssignmentRevisionCapabilitiesI
|
||||
}
|
||||
|
||||
// sayWanted says `wanted` for a want written or removed now, from the revision the pass keeps (A-61, A-67); with none kept, it is
|
||||
// said in the log that it was not said. fp is the want's, and for a removal the fingerprint last wanted there.
|
||||
func (p *passer) sayWanted(node, module, fp, pipeline string, removed bool) {
|
||||
// said in the log that it was not said. fp is the want's, and for a removal the fingerprint last wanted there. at is the want key's
|
||||
// write time when the event is said again after a restart (design 47 H2b H-A-859), zero for a say made with the write; taken runs
|
||||
// once the bus has taken it (a removal's mark goes then, §832 4.).
|
||||
func (p *passer) sayWanted(node, module, fp, pipeline string, removed bool, wantRevision uint64, at time.Time, taken func()) {
|
||||
if p.publishWants == nil {
|
||||
return
|
||||
}
|
||||
@@ -381,13 +383,14 @@ func (p *passer) sayWanted(node, module, fp, pipeline string, removed bool) {
|
||||
p.logf("the want of %s on %s is written, but no assignment graph revision is kept, so wanted is not said", module, node)
|
||||
return
|
||||
}
|
||||
at := p.clock().UTC()
|
||||
body := meshwants.WantedEvent{V: keys.Version, Node: node, Module: module, Fp: fp, Pipeline: pipeline, Removed: removed, Revision: kept.Revision, Source: source, At: &at}
|
||||
event := strings.TrimPrefix(meshwants.SubjectWanted(keys.EscapeName(node), keys.EscapeName(module)), "mesh.seat."+meshwants.Seat+".event.")
|
||||
id := fmt.Sprintf("wanted.%s.%s.%s.%t.%d.%s", keys.EscapeName(node), keys.EscapeName(module), fp, removed, kept.Revision, at.Format(time.RFC3339Nano))
|
||||
if err := p.wantsSay(event, body, id); err != nil {
|
||||
p.logf("wanted of %s on %s is not said: %v", module, node, err)
|
||||
if at.IsZero() {
|
||||
at = p.clock()
|
||||
}
|
||||
at = at.UTC()
|
||||
body := meshwants.WantedEvent{V: keys.Version, Node: node, Module: module, Fp: fp, Pipeline: pipeline, Removed: removed, Revision: kept.Revision, Source: source, At: &at, WantRevision: int64(wantRevision)}
|
||||
event := strings.TrimPrefix(meshwants.SubjectWanted(keys.EscapeName(node), keys.EscapeName(module)), "mesh.seat."+meshwants.Seat+".event.")
|
||||
id := fmt.Sprintf("wanted.%s.%s.%s.%t.%d", keys.EscapeName(node), keys.EscapeName(module), fp, removed, wantRevision)
|
||||
p.wantsOwe("want."+keys.EscapeName(node)+"."+keys.EscapeName(module), event, body, id, taken)
|
||||
}
|
||||
|
||||
// namedBuild answers what a want of module at fp names of its build (design 47 G §379, §526, A-96): a kept build's or another watched
|
||||
|
||||
@@ -5,7 +5,10 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -96,33 +99,215 @@ func TestTheWantsAreSaidWantedFromTheKeptAssignmentGraphRevision(t *testing.T) {
|
||||
if err := json.Unmarshal(events[len(events)-1].body, &w); err != nil || len(events) != 3 || !w.Removed || w.Fp != fpTest {
|
||||
t.Errorf("a removing want said %+v (%v), %d events", w, err, len(events))
|
||||
}
|
||||
// Design 47 H2 §813 (1), H-A-416: a want carries its run, its pipeline's source in decimal, or the newest source held for a
|
||||
// want of no pipeline; it is written by compare-and-set refusing a lower run, and one that differs only by its run stands.
|
||||
// Design 47 H2 §813 (1), H-A-504 corrected, its addendum and its third addendum: a want of a pipeline carries its run, the
|
||||
// pipeline's sequence the want rule set, as information; a want of no pipeline the newest source held. The order is the bus's:
|
||||
// a want is written by compare-and-set on the key's revision the pass read, whatever its run, and one that differs only by its
|
||||
// run stands; a pass whose read the key has moved past writes nothing, says so once, and the next pass writes it.
|
||||
// Design 47 H §832 3. (H-A-830, H-A-832): the id of `wanted` names the want's key revision, never the say's time or the graph
|
||||
// revision, so puts of F1, F0 and F1 say three under three ids, and a removal is the id of the write it removes.
|
||||
t.Run("a want's ids name its key revision", func(t *testing.T) {
|
||||
fp0 := fpTest[:len(fpTest)-1] + "0"
|
||||
events = nil
|
||||
for _, f := range []string{fpTest, fp0, fpTest} {
|
||||
p.putWant(ctx, "ace", "owed", mwc.Want{Fp: f, Self: true})
|
||||
}
|
||||
p.putWant(ctx, "ace", "owed", mwc.Want{Removed: true})
|
||||
ids := map[string]bool{}
|
||||
for _, e := range events {
|
||||
ids[e.id] = true
|
||||
}
|
||||
var last meshwants.WantedEvent
|
||||
_ = json.Unmarshal(events[len(events)-1].body, &last)
|
||||
if len(events) != 4 || len(ids) != 4 || !strings.Contains(events[0].id, "wanted.ace.owed."+fpTest+".false.") || strings.Contains(events[0].id, "T") {
|
||||
t.Errorf("ids %v", events)
|
||||
}
|
||||
if !last.Removed || last.WantRevision == 0 || !strings.HasSuffix(events[3].id, ".true."+strconv.FormatInt(last.WantRevision, 10)) {
|
||||
t.Errorf("the removal said %+v under %s", last, events[3].id)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 3. (H-A-832, 1984/AC-832q): a `wanted` the bus refused and said again carries the body first said, its `at`
|
||||
// included, under the id first made.
|
||||
t.Run("a wanted owed and said again carries the body first said, at included (AC-832q)", func(t *testing.T) {
|
||||
first := time.Date(2026, 11, 27, 6, 0, 0, 0, time.UTC)
|
||||
clock, refuse := first, true
|
||||
p.now = func() time.Time { return clock }
|
||||
defer func() { p.now = func() time.Time { return at } }()
|
||||
p.publishWants = func(event string, body any, id string) error {
|
||||
if refuse {
|
||||
return errors.New("the bus refuses")
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
events = append(events, said{event, id, raw})
|
||||
return nil
|
||||
}
|
||||
events = nil
|
||||
p.putWant(ctx, "ace", "late", mwc.Want{Fp: fpTest, Self: true})
|
||||
owed := p.owedAll()
|
||||
if len(owed) != 1 || len(events) != 0 {
|
||||
t.Fatalf("the refused wanted is owed %+v, said %d", owed, len(events))
|
||||
}
|
||||
clock, refuse = first.Add(10*time.Minute), false
|
||||
p.owed.list[0].next = clock
|
||||
if !p.sayOwed() || len(events) != 1 {
|
||||
t.Fatalf("the owed wanted is not said again: %d events", len(events))
|
||||
}
|
||||
var b meshwants.WantedEvent
|
||||
_ = json.Unmarshal(events[0].body, &b)
|
||||
if events[0].id != owed[0].ID || b.At == nil || !b.At.Equal(first) {
|
||||
t.Errorf("said again under %s with at %v, want %s and the first said's %v", events[0].id, b.At, owed[0].ID, first)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 4. (H-A-843, H-A-859; 1984/AC-832e, AC-832f, AC-832r, AC-832w): a start says again what the kept state implies
|
||||
// under the same ids; a removal is marked before it is written and said, and the mark is said from at a start; a `wanted` said
|
||||
// again carries the want key's write time as its `at`.
|
||||
t.Run("a start says again the wants written and the removals marked, under the same ids", func(t *testing.T) {
|
||||
first := time.Date(2026, 11, 27, 5, 0, 0, 0, time.UTC)
|
||||
build := func(kv *memKV, ends *memEnds, now time.Time) (*passer, *[]said) {
|
||||
q := newPasser(kvSet{buckets.Wants(): kv}, now)
|
||||
q.now = func() time.Time { return now }
|
||||
q.logf = t.Logf
|
||||
var out []said
|
||||
q.publishWants = func(event string, body any, id string) error {
|
||||
raw, _ := json.Marshal(body)
|
||||
out = append(out, said{event, id, raw})
|
||||
return nil
|
||||
}
|
||||
q.graph = &graphKeeper{objects: memObjects{}, halves: func() map[string]mcc.Half { return map[string]mcc.Half{trunkBranch: half} }}
|
||||
q.ends = newPipelineEnds(ends, func() {}, t.Logf)
|
||||
q.keepGraph(ctx)
|
||||
out = nil
|
||||
return q, &out
|
||||
}
|
||||
// the process before the restart: the want written, said, then a removal the bus refuses
|
||||
kv, ends := &memKV{values: map[string][]byte{}}, newMemEnds()
|
||||
q, out := build(kv, ends, first)
|
||||
q.putWant(ctx, "ace", "web", mwc.Want{Fp: fpTest, Self: true})
|
||||
q.putWant(ctx, "ace", "keep", mwc.Want{Fp: fpTest, Self: true})
|
||||
keepID := (*out)[1].id
|
||||
q.publishWants = func(string, any, string) error { return errors.New("the bus refuses") }
|
||||
q.putWant(ctx, "ace", "web", mwc.Want{Removed: true})
|
||||
if raw, _, _ := ends.get(removalKey("ace", "web")); raw == nil {
|
||||
t.Fatal("AC-832f: the removal has no mark")
|
||||
}
|
||||
// AC-832r: assigner_written answers the mark
|
||||
written := writtenTools(memStore{writtenState: &memKV{values: map[string][]byte{removalKey("ace", "web"): ends.vals[removalKey("ace", "web")]}}})
|
||||
if got, err := written[0].Run(map[string]any{}); err != nil || got.(map[string]any)[removalKey("ace", "web")] == nil {
|
||||
t.Errorf("AC-832r: assigner_written answered %v (%v)", got, err)
|
||||
}
|
||||
// the restart: the kept state is the want keys and the mark
|
||||
restart := func(now time.Time) (*passer, *[]said) {
|
||||
r, out := build(kv, ends, now)
|
||||
for k, v := range kv.values {
|
||||
r.w.putEntry(buckets.Wants(), k, v, kv.revision(k), first)
|
||||
}
|
||||
return r, out
|
||||
}
|
||||
r, out2 := restart(first.Add(time.Hour))
|
||||
r.startSays(ctx)
|
||||
var removal, again *said
|
||||
for i, e := range *out2 {
|
||||
var b meshwants.WantedEvent
|
||||
_ = json.Unmarshal(e.body, &b)
|
||||
switch {
|
||||
case b.Module == "web" && b.Removed:
|
||||
removal = &(*out2)[i]
|
||||
case b.Module == "keep":
|
||||
again = &(*out2)[i]
|
||||
}
|
||||
}
|
||||
if removal == nil || (*out2)[len(*out2)-1].event == "" || again == nil {
|
||||
t.Fatalf("AC-832e: the start said %v", *out2)
|
||||
}
|
||||
var b meshwants.WantedEvent
|
||||
_ = json.Unmarshal(again.body, &b)
|
||||
if again.id != keepID || b.At == nil || !b.At.Equal(first) || b.WantRevision == 0 {
|
||||
t.Errorf("AC-832w: the want said again is %s %+v, want the key's write time %v as its at", again.id, b, first)
|
||||
}
|
||||
if raw, _, _ := ends.get(removalKey("ace", "web")); raw != nil {
|
||||
t.Errorf("AC-832f: the mark stands once the removal was taken")
|
||||
}
|
||||
webKey, _ := mwc.WantKey("ace", "web")
|
||||
if w, _ := mwc.DecodeWant(kv.values[webKey]); !w.Removed {
|
||||
t.Errorf("AC-832f: the want's key holds %+v, want the removing want", w)
|
||||
}
|
||||
// the same ids again at the next start; the removal's mark is gone, so only the want written is said
|
||||
r2, out3 := restart(first.Add(2 * time.Hour))
|
||||
r2.startSays(ctx)
|
||||
ids := map[string]bool{}
|
||||
for _, e := range *out3 {
|
||||
ids[e.id] = true
|
||||
}
|
||||
if !ids[again.id] || len(*out3) != 1 {
|
||||
t.Errorf("AC-832e: the second start said %v, want the want written under %s", *out3, again.id)
|
||||
}
|
||||
// a crash between the mark and the removing want: the key still holds the revision the mark names, so the start writes it first
|
||||
kv2, ends2 := &memKV{values: map[string][]byte{}}, newMemEnds()
|
||||
c, _ := build(kv2, ends2, first)
|
||||
c.putWant(ctx, "ace", "web", mwc.Want{Fp: fpTest, Self: true})
|
||||
cKey, _ := mwc.WantKey("ace", "web")
|
||||
mark, _ := json.Marshal(removalMark{Node: "ace", Module: "web", Fp: fpTest, WantRevision: kv2.revision(cKey)})
|
||||
ends2.vals[removalKey("ace", "web")], ends2.revs[removalKey("ace", "web")] = mark, 1
|
||||
d, out4 := build(kv2, ends2, first.Add(time.Hour))
|
||||
for k, v := range kv2.values {
|
||||
d.w.putEntry(buckets.Wants(), k, v, kv2.revision(k), first)
|
||||
}
|
||||
d.startSays(ctx)
|
||||
if w, _ := mwc.DecodeWant(kv2.values[cKey]); !w.Removed || len(*out4) != 1 || !strings.HasSuffix((*out4)[0].id, ".true."+strconv.FormatUint(kv2.revision(cKey)-1, 10)) {
|
||||
t.Errorf("AC-832f: a mark whose want still stands left %+v and said %v", w, *out4)
|
||||
}
|
||||
})
|
||||
t.Run("a want's run", func(t *testing.T) {
|
||||
wkey, _ := mwc.WantKey("g14", "db")
|
||||
stored := func() mwc.Want { w, _ := mwc.DecodeWant(kv.values[wkey]); return w }
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1})
|
||||
if w := stored(); w.Run != "12" || w.Pipeline != "main.12" {
|
||||
t.Fatalf("the want of pipeline main.12 is %+v, want run 12", w)
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1, Run: "212"})
|
||||
if w := stored(); w.Run != "212" || w.Pipeline != "main.12" {
|
||||
t.Fatalf("the want of pipeline main.12 is %+v, want run 212", w)
|
||||
}
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1, Run: "211"})
|
||||
if w := stored(); w.Run != "211" || w.Version != "0.1.1" {
|
||||
t.Errorf("a want of a lower run left %+v, want it written: the run is no gate", w)
|
||||
}
|
||||
puts := kv.puts
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1})
|
||||
if w := stored(); w.Run != "12" || w.Version != "0.1.2" || kv.puts != puts {
|
||||
t.Errorf("a want of a lower run replaced %+v (%d writes)", w, kv.puts-puts)
|
||||
}
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1})
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.1", Pipeline: "main.11", Rank: 1, Run: "211"})
|
||||
if kv.puts != puts {
|
||||
t.Error("a want that stands was written again")
|
||||
}
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.2", Pipeline: "main.12", Rank: 1, Run: "212"})
|
||||
skey, _ := mwc.WantKey("shanks", "db")
|
||||
p.putWant(ctx, "shanks", "db", mwc.Want{Fp: fpTest, Put: true, Words: "put: by hand"})
|
||||
if w, _ := mwc.DecodeWant(kv.values[skey]); w.Run != "9" {
|
||||
t.Errorf("a put's want is %+v, want the newest source held, 9", w)
|
||||
}
|
||||
// a placement's build after the delivery of run 12: the newest source held for it is the want's own, never refused
|
||||
// a placement's build after the delivery of run 212: the newest source held for it is the want's own
|
||||
p.putWant(ctx, "g14", "db", mwc.Want{Fp: fpTest, Version: "0.1.0"})
|
||||
if w := stored(); w.Run != "12" || w.Version != "0.1.0" {
|
||||
t.Errorf("a placement's want after run 12 is %+v, want it written at run 12", w)
|
||||
if w := stored(); w.Run != "212" || w.Version != "0.1.0" {
|
||||
t.Errorf("a placement's want after run 212 is %+v, want it written at run 212", w)
|
||||
}
|
||||
// Wants written before the sequence carry a revision number (322) as their run: a want of a lower sequence is written.
|
||||
nkey, _ := mwc.WantKey("novox", "node-tools")
|
||||
atNovox := func() mwc.Want { w, _ := mwc.DecodeWant(kv.values[nkey]); return w }
|
||||
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.96", Pipeline: "main.265.again.2", Rank: 1, Run: "322"})
|
||||
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.115", Pipeline: "main.320.again.1", Rank: 1, Run: "312"})
|
||||
if w := atNovox(); w.Run != "312" || w.Version != "0.1.115" {
|
||||
t.Errorf("seq 312 after run 322 left %+v, want 0.1.115 at run 312", w)
|
||||
}
|
||||
// A stale pass: another write moved the key past the revision this pass read; it loses, says so once, writes nothing.
|
||||
var lines []string
|
||||
p.logf = func(f string, a ...any) { lines = append(lines, fmt.Sprintf(f, a...)) }
|
||||
defer func() { p.logf = t.Logf }()
|
||||
newer, _ := mwc.EncodeWant(mwc.Want{Fp: fpTest, Version: "0.1.116", Pipeline: "main.321", Rank: 1, Run: "313"})
|
||||
if _, err := kv.Update(ctx, nkey, newer, kv.revision(nkey)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
puts = kv.puts
|
||||
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.114", Pipeline: "main.319", Rank: 1, Run: "311"})
|
||||
if w := atNovox(); w.Version != "0.1.116" || kv.puts != puts || len(lines) != 1 || !strings.Contains(lines[0], "the newer write stands") {
|
||||
t.Errorf("a stale pass left %+v (%d writes), said %q", w, kv.puts-puts, lines)
|
||||
}
|
||||
p.w.putEntry(buckets.Wants(), nkey, newer, kv.revision(nkey), at) // the watch hands the newer write
|
||||
p.putWant(ctx, "novox", "node-tools", mwc.Want{Fp: fpTest, Version: "0.1.117", Pipeline: "main.322", Rank: 1, Run: "314"})
|
||||
if w := atNovox(); w.Version != "0.1.117" || len(lines) != 1 {
|
||||
t.Errorf("the next pass left %+v, said %q", w, lines)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -378,6 +563,109 @@ func TestAPassWritesWantsWhileAKeepingIsBlocked(t *testing.T) {
|
||||
t.Errorf("assigner_keep_now: %v, asked %v", err, asked)
|
||||
}
|
||||
})
|
||||
// 1984/AC13 (design 47 H2 H-A-635): a pass still running after pass-stall-seconds says in the journal which phase it is in, and again at each
|
||||
// further bound until it ends; one that ends within the bound says none, and its end line stays as it was. The bound is the setting
|
||||
// read from its file (the unit a millisecond), so a row that blocks a phase waits only for its bounds.
|
||||
t.Run("a pass past pass-stall-seconds says its phase", func(t *testing.T) {
|
||||
was := passStallUnit
|
||||
passStallUnit = time.Millisecond
|
||||
t.Cleanup(func() { passStallUnit = was })
|
||||
file := filepath.Join(t.TempDir(), "pass-stall-seconds")
|
||||
if err := os.WriteFile(file, []byte("20"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stall, err := passStallSetting(func(string) string { return file })
|
||||
if none, noneErr := passStallSetting(func(string) string { return "" }); err != nil || stall != 20*time.Millisecond || noneErr != nil || none != 0 ||
|
||||
(&passer{}).passStallOf() != time.Minute || (&passer{passStall: stall}).passStallOf() != stall {
|
||||
t.Fatalf("the setting reads %v (%v), none set %v (%v), the default %v; want 20 units, none set the default of a minute", stall, err, none, noneErr, (&passer{}).passStallOf())
|
||||
}
|
||||
for _, row := range []struct {
|
||||
name, phase string
|
||||
block func(p *passer, gate chan struct{}) // blocks the phase until the gate closes
|
||||
}{
|
||||
{"the kept graph", phaseKeptGraph, func(p *passer, gate chan struct{}) {
|
||||
p.graph = &graphKeeper{objects: &blockedObjects{memObjects: memObjects{}}, background: func(f func()) { f() }, wake: func() {},
|
||||
halves: func() map[string]mcc.Half { <-gate; return nil }}
|
||||
}},
|
||||
{"the node wants", phaseNodeWants, func(p *passer, gate chan struct{}) {
|
||||
p.kvs[buckets.Wants()] = &gatedKV{memKV: &memKV{values: map[string][]byte{}}, gate: gate}
|
||||
}},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var journal []string
|
||||
stalled := make(chan string, 64)
|
||||
p := newPasser(kvSet{buckets.Wants(): &memKV{values: map[string][]byte{}}, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
|
||||
p.passStall = stall
|
||||
p.logf = func(f string, a ...any) {
|
||||
line := fmt.Sprintf(f, a...)
|
||||
mu.Lock()
|
||||
journal = append(journal, line)
|
||||
mu.Unlock()
|
||||
if strings.Contains(line, "the pass started at ") {
|
||||
stalled <- line
|
||||
}
|
||||
}
|
||||
placeOn(t, p.w, "ace", "web")
|
||||
gate := make(chan struct{})
|
||||
row.block(p, gate)
|
||||
done := make(chan struct{})
|
||||
go func() { p.pass(context.Background()); close(done) }()
|
||||
var earlier time.Duration
|
||||
for range 2 { // the first bound and the next
|
||||
select {
|
||||
case line := <-stalled:
|
||||
_, after, _ := strings.Cut(line, " is in "+row.phase+" for ")
|
||||
spent, err := time.ParseDuration(after)
|
||||
if after == "" || err != nil || spent < earlier {
|
||||
t.Fatalf("the journal says %q, want the pass in %q for a time that grows", line, row.phase)
|
||||
}
|
||||
earlier = spent
|
||||
case <-time.After(bound):
|
||||
t.Fatalf("a pass blocked in %s says nothing within %v", row.phase, bound)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("the pass ended while its phase was blocked")
|
||||
default:
|
||||
}
|
||||
close(gate)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(bound):
|
||||
t.Fatal("the pass does not end when its phase is opened")
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if last := journal[len(journal)-1]; !strings.HasPrefix(last, "the pass took ") {
|
||||
t.Errorf("the journal ends %q, want the end line of the pass as before", last)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A pass that ends within the bound says none: the bound is armed once, disarmed at the end, and a bound that still fires
|
||||
// after the end (as a late timer) says nothing.
|
||||
var armed []func()
|
||||
var stopped int
|
||||
var journal []string
|
||||
p := newPasser(kvSet{buckets.Wants(): &memKV{values: map[string][]byte{}}, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
|
||||
p.logf = func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }
|
||||
p.stallAfter = func(d time.Duration, f func()) func() {
|
||||
if d != time.Minute {
|
||||
t.Errorf("the bound armed is %v, want the default of a minute", d)
|
||||
}
|
||||
armed = append(armed, f)
|
||||
return func() { stopped++ }
|
||||
}
|
||||
p.pass(context.Background())
|
||||
if len(armed) != 1 || stopped != 1 {
|
||||
t.Fatalf("the bound was armed %d times and disarmed %d times, want once each", len(armed), stopped)
|
||||
}
|
||||
armed[0]()
|
||||
if len(armed) != 1 || len(journal) != 1 || !strings.HasPrefix(journal[0], "the pass took ") {
|
||||
t.Errorf("a pass that ended within the bound: journal %q, armed %d; want only its end line", journal, len(armed))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// failingObjects refuses the next fail puts, then is objects.
|
||||
@@ -393,3 +681,14 @@ func (f *failingObjects) Put(ctx context.Context, name string, data []byte) erro
|
||||
}
|
||||
return f.blockedObjects.Put(ctx, name, data)
|
||||
}
|
||||
|
||||
// gatedKV is a bucket whose put waits until the gate closes.
|
||||
type gatedKV struct {
|
||||
*memKV
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func (g *gatedKV) Put(ctx context.Context, key string, value []byte) (uint64, error) {
|
||||
<-g.gate
|
||||
return g.memKV.Put(ctx, key, value)
|
||||
}
|
||||
|
||||
@@ -54,6 +54,15 @@ func (h *halves) follow() error {
|
||||
h.changed(branch, module, entry, deleted)
|
||||
}
|
||||
b.Adopted = h.adopted
|
||||
// An entry read by fingerprint never changes: each catalog revision taken in releases only the entries that no want and no
|
||||
// `running` the assigner holds names any more (design 47 H2 H-A-757, amending H-A-682 (2)).
|
||||
b.Held = func(string, meshcatalog.CatalogRevision) {
|
||||
for _, r := range b.Entries.Rows() {
|
||||
if !h.w.namesFingerprint(r.Fingerprint) {
|
||||
b.Entries.Release(r.Fingerprint)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The one handler of registration-changed is the follower's (H-A-270 (3)): the pipeline ends are told each change from it,
|
||||
// never from a second handler on the hub.
|
||||
reconcile := b.Registrations.Follower.Changed
|
||||
|
||||
@@ -4,7 +4,14 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -105,3 +112,107 @@ func TestAModulesWatchedBranchesAreItsRegistrations(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-682 (2): the entries read by fingerprint are kept until the next catalog revision the assigner takes in, and each revision
|
||||
// held releases those no want or running names (H-A-757).
|
||||
func TestACatalogRevisionTakenInReleasesTheEntriesKept(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
call := func(key string, _ any) (json.RawMessage, error) {
|
||||
if key == mcc.EntryVerb {
|
||||
return json.Marshal(seat.EntryAnswer{Entry: seat.CatalogEntry{Module: "m", Needs: []string{"x"}}})
|
||||
}
|
||||
return nil, errors.New("not answered here")
|
||||
}
|
||||
reader := &views.ProcessReader{Module: "mesh-delivery-assigner", Call: call, Logf: t.Logf}
|
||||
h := &halves{w: newWorld(), call: call, reader: reader, wake: func() {}, logf: t.Logf, ctx: ctx}
|
||||
if err := h.follow(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answered := make(chan struct{}, 1)
|
||||
h.branches.Entries.Changed = func(mcc.EntryRow) { answered <- struct{}{} }
|
||||
old := mcc.SourcePrefix2 + strings.Repeat("a", 64)
|
||||
for _, fp := range []string{old, "src2:unnamed"} {
|
||||
h.branches.Entries.Need(ctx, fp)
|
||||
select {
|
||||
case <-answered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the entry is never answered")
|
||||
}
|
||||
}
|
||||
raw, _ := mwc.EncodeWant(mwc.Want{Fp: old, Version: "1.0.0", Pipeline: trunkBranch + ".5", Rank: 1, Run: "205", Self: true})
|
||||
key, _ := mwc.WantKey("g14", "web")
|
||||
h.w.putEntry(buckets.Wants(), key, raw, 1, time.Now())
|
||||
// A pass over the want at the older fingerprint: the module's trunk entry names a newer one, so its needs come from the entry
|
||||
// read by fingerprint. The want stands as the pass writes it, so a revision taken in and a pass after it write nothing.
|
||||
writes := 0
|
||||
wantsKV := &writeCountingKV{memKV: memKV{values: map[string][]byte{}}, writes: &writes, key: key}
|
||||
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
|
||||
p.w, p.entries = h.w, h.branches.Entries
|
||||
p.w.setTrunk(trunkBranch)
|
||||
p.publishWants = func(string, any, string) error { return nil }
|
||||
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
|
||||
p.ends.trunk = p.w.trunkName
|
||||
p.reads = &engineReadsKept{} // g14 states want:version and the capability the entry needs
|
||||
words, _ := json.Marshal(engineWords{Words: []string{nodeengine.ManifestReadWordWantVersion, "x"}, At: time.Now()})
|
||||
if err := p.reads.take("g14", words, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := strings.Repeat("4", 64)
|
||||
mod, _ := mcc.EncodeModule(seat.ModulesByModuleValue{Fp2: mcc.SourcePrefix2 + strings.Repeat("b", 64), Manifest: digest, Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: mcc.RootPath})
|
||||
putModuleRaw(p.w, trunkBranch, "web", mod)
|
||||
p.w.manifests[digest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web"}}
|
||||
placeOn(t, p.w, "g14", "web")
|
||||
p.w.mu.Lock()
|
||||
p.w.runningHeard = true
|
||||
p.w.mu.Unlock()
|
||||
runningRaw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "web", Fingerprint: old})
|
||||
if err := p.w.hearRunning("running.g14.web", runningRaw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The pipeline that passed names the older fingerprint: it is the want's target, its entry the one read by fingerprint.
|
||||
e := ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("web", old, "1.0.0", 1, mpr.StepResultOutcomePassed))
|
||||
e.Source, e.Pipeline = 4, trunkBranch+".5"
|
||||
if _, err := p.ends.take(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.wants(ctx)
|
||||
p.wants(ctx)
|
||||
settled := writes
|
||||
h.branches.Held("main", seat.CatalogRevision{Branch: "main", Revision: 2})
|
||||
if rows := h.branches.Entries.Rows(); len(rows) != 1 || rows[0].Fingerprint != old {
|
||||
t.Errorf("a catalog revision taken in keeps %+v, want the entry a want names and releases the one nothing names", rows)
|
||||
}
|
||||
p.wants(ctx)
|
||||
if writes != settled {
|
||||
t.Errorf("a pass after a revision taken in wrote %d wants: the want at the older fingerprint is rewritten", writes-settled)
|
||||
}
|
||||
}
|
||||
|
||||
// writeCountingKV counts every write of one key of the wants bucket, a create or an update as a put.
|
||||
type writeCountingKV struct {
|
||||
memKV
|
||||
writes *int
|
||||
key string
|
||||
}
|
||||
|
||||
func (c *writeCountingKV) count(key string) {
|
||||
if key == c.key {
|
||||
*c.writes++
|
||||
}
|
||||
}
|
||||
|
||||
func (c *writeCountingKV) Put(ctx context.Context, key string, value []byte) (uint64, error) {
|
||||
c.count(key)
|
||||
return c.memKV.Put(ctx, key, value)
|
||||
}
|
||||
|
||||
func (c *writeCountingKV) Create(ctx context.Context, key string, value []byte, o ...jetstream.KVCreateOpt) (uint64, error) {
|
||||
c.count(key)
|
||||
return c.memKV.Create(ctx, key, value, o...)
|
||||
}
|
||||
|
||||
func (c *writeCountingKV) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
|
||||
c.count(key)
|
||||
return c.memKV.Update(ctx, key, value, revision)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -98,6 +99,10 @@ type catalogBed struct {
|
||||
// at is, by branch and revision, a revision's entries a test keeps whole: the verb revision answers a revision asked by its
|
||||
// number from here, and the current one otherwise.
|
||||
at map[string]map[int64][]meshcatalog.CatalogEntry
|
||||
// stop makes the seat's holder unheard, as a holder stopped is (no responders); serve makes it heard again (serveCatalog).
|
||||
stop, serve func()
|
||||
// met says a call reached the holder while it was stopped.
|
||||
met chan struct{}
|
||||
}
|
||||
|
||||
// journal is a program's journal as the bed hears it: a test awaits a line in it (await) where the line is the only sign
|
||||
@@ -124,6 +129,13 @@ func (j *journal) mark() int {
|
||||
return j.text.Len()
|
||||
}
|
||||
|
||||
// has says whether the journal holds, after from (mark), a line with words.
|
||||
func (j *journal) has(from int, words string) bool {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return strings.Contains(j.text.String()[from:], words)
|
||||
}
|
||||
|
||||
// await returns once the journal holds, after from (mark), a line with words, and fails the test when none came within
|
||||
// bound.
|
||||
func (j *journal) await(t *testing.T, from int, words, what string, bound time.Duration) {
|
||||
@@ -599,7 +611,7 @@ func (b *bed) ended(t *testing.T, source int64, outcome string, movers ...moverA
|
||||
if outcome != mpr.PipelineEndedOutcomePassed {
|
||||
step.Outcome = mpr.StepResultOutcomeFailed
|
||||
}
|
||||
e := mpr.PipelineEnded{V: 1, Pipeline: pipeline, Branch: trunkBranch, Source: source, Outcome: outcome}
|
||||
e := mpr.PipelineEnded{V: 1, Pipeline: pipeline, Branch: trunkBranch, Source: source, Seq: 200 + source, Outcome: outcome}
|
||||
for _, m := range movers {
|
||||
e.Movers = append(e.Movers, mpr.MoverEnded{Module: m.module, Fingerprint: m.fp, Version: m.version, Tier: m.tier, Steps: []mpr.StepResult{step}})
|
||||
}
|
||||
@@ -885,7 +897,7 @@ func TestWantsAreWrittenAndNoDifferenceIs(t *testing.T) {
|
||||
t.Error("the state engine-reads holds a key of shanks, whose engine said nothing")
|
||||
}
|
||||
// H-A-270 (3): registration-changed has one handler, the catalog half's follower, so the start's hub refuses no overlap.
|
||||
b.journal.await(t, 0, "the kept seat events heard", "the hub started", time.Second)
|
||||
b.journal.await(t, 0, "the hub started: the events and the kept seat events", "the hub started", time.Second)
|
||||
b.journal.mu.Lock()
|
||||
overlap := strings.Contains(b.journal.text.String(), "a message has one taker")
|
||||
b.journal.mu.Unlock()
|
||||
@@ -1831,13 +1843,6 @@ func serveCatalog(t *testing.T, b *bed, nc *nats.Conn) {
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
for _, subject := range []string{"mesh.seat.mesh-catalog.tool.revision", "mesh.seat.mesh-catalog.call.revision.*", "mesh.seat.mesh-catalog.tool.revision.*"} {
|
||||
sub, err := nc.Subscribe(subject, answer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
// The verb entry answers an entry by its fingerprint from every branch's half, and a fingerprint no half holds as not found,
|
||||
// as the seat's holder does: an entry the assigner asks for a form change is answered, never left asked (orderwaits.go).
|
||||
entry := func(m *nats.Msg) {
|
||||
@@ -1856,8 +1861,24 @@ func serveCatalog(t *testing.T, b *bed, nc *nats.Conn) {
|
||||
}
|
||||
_ = m.Respond([]byte(`{"error":"no catalog entry has the fingerprint ` + in.Fingerprint + `","node":"n0"}`))
|
||||
}
|
||||
for _, subject := range []string{"mesh.seat.mesh-catalog.tool.entry", "mesh.seat.mesh-catalog.call.entry.*"} {
|
||||
sub, err := nc.Subscribe(subject, entry)
|
||||
// A holder stopped answers each call as the bus does a subject nobody serves, no responders, and says it met one (b.cat.met).
|
||||
var down atomic.Bool
|
||||
b.cat.met = make(chan struct{}, 16)
|
||||
b.cat.stop = func() { down.Store(true) }
|
||||
b.cat.serve = func() { down.Store(false) }
|
||||
for subject, handler := range map[string]nats.MsgHandler{"mesh.seat.mesh-catalog.tool.revision": answer, "mesh.seat.mesh-catalog.call.revision.*": answer,
|
||||
"mesh.seat.mesh-catalog.tool.revision.*": answer, "mesh.seat.mesh-catalog.tool.entry": entry, "mesh.seat.mesh-catalog.call.entry.*": entry} {
|
||||
sub, err := nc.Subscribe(subject, func(m *nats.Msg) {
|
||||
if down.Load() {
|
||||
select {
|
||||
case b.cat.met <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
_ = m.RespondMsg(&nats.Msg{Header: nats.Header{"Status": []string{"503"}}})
|
||||
return
|
||||
}
|
||||
handler(m)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient/heard"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
@@ -324,6 +327,17 @@ func findingsOf(ctx context.Context, account process.Account, conn *nats.Conn, j
|
||||
return w.Clear(ctx, scope, rest[:i], rest[i+1:], "the assigner no longer observes it")
|
||||
}
|
||||
f.Keys = state.Keys
|
||||
f.Get = func(key string) (mcseat.Finding, bool, error) {
|
||||
entry, err := state.Get(key)
|
||||
if err != nil || entry == nil {
|
||||
return mcseat.Finding{}, false, err
|
||||
}
|
||||
var found mcseat.Finding
|
||||
if err := json.Unmarshal(entry.Value, &found); err != nil {
|
||||
return mcseat.Finding{}, false, fmt.Errorf("the finding %s does not read: %w", key, err)
|
||||
}
|
||||
return found, true, nil
|
||||
}
|
||||
return f, w
|
||||
}
|
||||
|
||||
@@ -506,9 +520,6 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
return err
|
||||
}
|
||||
runs = newCompositionRuns(busRuns{ctx, js, kv}, set, time.Now, logger.Printf)
|
||||
if js != nil {
|
||||
runs.say = wantsPublisher(ctx, js, thisNode)
|
||||
}
|
||||
if bus != nil {
|
||||
runs.drop = dropOver(bus.CallKept)
|
||||
}
|
||||
@@ -516,6 +527,12 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
if err := hearRunBounds(hub, runs, logger.Printf); err != nil {
|
||||
logger.Printf("the build seats' ask-taken and step-progress are not heard, so a composition run is ended by no bound: %v", err)
|
||||
}
|
||||
// The seat mesh-builds' package-published wakes the runs waiting for the package its artifact publishes, which read published
|
||||
// again; each bind of the consumer, which hears no event said before it was made, wakes every waiting run (design 47 H2
|
||||
// H-A-628 (3), H-A-630 (1), (2); H-A-326, H-A-328).
|
||||
if err := hearPublished(hub, runs, logger.Printf); err != nil {
|
||||
logger.Printf("the seat mesh-builds' package-published is not heard, so a composition run waiting for a package reads published only at its start and at each bind: %v", err)
|
||||
}
|
||||
}
|
||||
if inputs != nil {
|
||||
var runEnded func(buildstep.StepEnded) error
|
||||
@@ -592,7 +609,17 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.tierBound, p.tierWake = tierBound, wake
|
||||
p.tierBound, p.wake = tierBound, wake
|
||||
if p.owed.first, p.owed.last, err = owedSetting(getenv); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.owed.unsaid, err = durationFile(getenv("MESH_ASSIGNER_EVENT_UNSAID_AFTER_FILE")); err != nil { // design 47 H2b §832 6.
|
||||
return err
|
||||
}
|
||||
// The setting pass-stall-seconds: a pass still running after it says which phase it is in (design 47 H2 H-A-635).
|
||||
if p.passStall, err = passStallSetting(getenv); err != nil {
|
||||
return err
|
||||
}
|
||||
// The wait on an outside cause (outside.go, design 47 G §706): the keeper's three events say when to judge again, and the
|
||||
// seat mesh-wants' wait-held and wait-ended are said; registered before the hub starts.
|
||||
if bus != nil && kvs[buckets.Waits()] != nil {
|
||||
@@ -680,8 +707,12 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
run := &compositionRun{runs: runs, inputs: &compositionInputs{machines: w.machinesOf, callFile: bus.CallFileKept, bound: askBound}, keeper: inputs, reads: &compositionReads{}, call: bus.CallKept, callFile: bus.CallFileKept,
|
||||
trunk: trunkOf(iv, w.trunkName), newest: iv.newestOf(), watched: iv.watchedOf, assigned: w.assignedOn, assignment: w.assignmentOf, findings: findings, running: w.runningOf, away: func(machine string) bool { return w.awayNow()[machine] }, put: runAskPublisher(js), ask: bus.CallFile, now: time.Now, logf: logger.Printf}
|
||||
readsBound, err := readsBoundSetting(getenv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
run := &compositionRun{runs: runs, inputs: &compositionInputs{machines: w.machinesOf, callFile: bus.CallFileKept, bound: askBound}, keeper: inputs, reads: &compositionReads{}, call: bus.CallKeptAsk, callFile: bus.CallFileKept, readsBound: readsBound, holder: holderOf(bus, w), engineReads: reads,
|
||||
trunk: trunkOf(iv, w.trunkName), newest: iv.newestOf(), watched: iv.watchedOf, assigned: w.assignedOn, assignment: w.assignmentOf, findings: findings, running: w.runningOf, away: func(machine string) bool { return w.awayNow()[machine] }, put: runAskPublisher(js), own: ctx, ask: bus.CallFile, now: time.Now, logf: logger.Printf}
|
||||
// The seat's work queue (design 47 H2 §777): pulled through its one worker, each ask taken once in the state taken.
|
||||
takenBound, err := askTakenBound()
|
||||
if err != nil {
|
||||
@@ -689,6 +720,7 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
}
|
||||
var ackWait atomic.Int64 // the worker's ack wait, read when it is bound
|
||||
ackWait.Store(int64(buscompose.SeatQueueDefaultAckWait))
|
||||
runs.owe = func(order, event string, body any, id string) { p.wantsOwe(order, event, body, id, nil) } // owed as every event is (H-A-873)
|
||||
steps := &compositionSteps{node: thisNode, say: p.publishWants, run: run.run, resume: run.resume,
|
||||
validate: run.validate, resumeValidate: run.resumeValidate, ended: runs.stepEnded, now: time.Now, logf: logger.Printf,
|
||||
takenBound: takenBound, inProgress: inProgressOf(seatlist.Definition(gate.Reader, meshwants.Seat), func() time.Duration { return time.Duration(ackWait.Load()) })}
|
||||
@@ -699,7 +731,8 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
runs.moved.Store(&move)
|
||||
// The state's watch wakes the steps waiting on a run and hears a bound's expiry; the runs standing at the start are taken up
|
||||
// once the values that stand are read (§719, §720).
|
||||
if err := watchRuns(ctx, kvs[buckets.CompositionRuns()], runs, runs.expired, func() { steps.takeUp(ctx, runs) }); err != nil {
|
||||
// A run still waiting for a package's publish has its start run again (H-A-629 (3)).
|
||||
if err := watchRuns(ctx, kvs[buckets.CompositionRuns()], runs, runs.expired, func() { steps.takeUp(ctx, runs); run.takeUpWaits(ctx) }); err != nil {
|
||||
return fmt.Errorf("the state %s is not watched: %w", buckets.CompositionRunsState, err)
|
||||
}
|
||||
// The runs' read and drop, the seat mesh-wants' verbs compositions and compositions-drop (§728, A-469f), answered here
|
||||
@@ -709,8 +742,9 @@ func follow(ctx context.Context, js jetstream.JetStream, nc process.Subscriber,
|
||||
_, err := meshhandactsclient.Recorder{Ask: bus.Call}.Record(q)
|
||||
return err
|
||||
}
|
||||
verbs := compositionVerbs(runs, steps, record)
|
||||
maps.Copy(verbs, dropVerb(steps)) // the seat's act drop (§778, H-A-404)
|
||||
verbs := compositionVerbs(runs, steps, record, run)
|
||||
maps.Copy(verbs, dropVerb(steps)) // the seat's act drop (§778, H-A-404)
|
||||
maps.Copy(verbs, owedVerbs(p, record)) // the owed events' read, say and drop (§832 6., H-A-847)
|
||||
if p.graph != nil {
|
||||
maps.Copy(verbs, keepNowVerb(ctx, p)) // the keeping by hand (§813 (2), H-A-417)
|
||||
}
|
||||
@@ -830,6 +864,10 @@ func hearReadsChanged(ctx context.Context, js jetstream.JetStream, hub *process.
|
||||
account := process.Account{Node: thisNode, Module: assignment.Module()}
|
||||
w := notHeardWriter(findings, logf)
|
||||
handle := readsChangedHandler(reads, logf)
|
||||
// Start answers nil while a durable is not yet bound (mesh-sdk S1): what waits on live events is done where the hub says it
|
||||
// hears every pattern, and a pattern it does not hear is said through its unheard hook (design 47 H2b §836 1., 4.).
|
||||
hub.OnAllHeard(readsLive(live, logf))
|
||||
hub.OnUnheard(readsUnheard(w, logf))
|
||||
err := hub.Handle(enginereads.SubjectPrefix+"*", handle)
|
||||
if err == nil {
|
||||
err = hub.Start(ctx, js, account)
|
||||
@@ -838,19 +876,56 @@ func hearReadsChanged(ctx context.Context, js jetstream.JetStream, hub *process.
|
||||
w.NotHeard(process.EventsStream, enginereads.Event+" is not heard until the assigner starts again, so no node's new words are kept", err)
|
||||
return
|
||||
}
|
||||
w.Heard(process.EventsStream)
|
||||
// The build seats' step-ended is a kept seat event, on its own stream and never on EVENTS: bound here, or no composition
|
||||
// run's end is heard and every composition step waits for ever (design 47 G §354, A-240; mesh-sdk EventHub.StartKept).
|
||||
logf("the kept seat events heard: %d streams bound", hub.StartKept(ctx, js, account))
|
||||
if live != nil {
|
||||
live() // the seat list, unread while the seat was silent, is read now (seatlist.Part.EventsLive)
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
hub.Stop()
|
||||
}()
|
||||
}
|
||||
|
||||
// readsLive is what the hub's OnAllHeard does: the seat list, unread while the seat was silent, is read now
|
||||
// (seatlist.Part.EventsLive), once every registered pattern is heard (design 47 H2b §836 1.).
|
||||
func readsLive(live func(), logf func(string, ...any)) func() {
|
||||
return func() {
|
||||
logf("the hub started: the events and the kept seat events are bound by Start")
|
||||
if live != nil {
|
||||
live()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readsUnheard is what the hub's OnUnheard does: the finding of the reads' family is written while the hub does not hear the
|
||||
// node-engine seat's manifest-reads-changed, and deleted once it does (design 47 H2b §836 4.).
|
||||
func readsUnheard(w heard.Writer, logf func(string, ...any)) func([]process.Unheard) {
|
||||
return func(unheard []process.Unheard) {
|
||||
for _, u := range unheard {
|
||||
if u.Pattern == enginereads.SubjectPrefix+"*" {
|
||||
w.NotHeard(process.EventsStream, enginereads.Event+" is not heard until the hub binds it, so no node's new words are kept", errors.New(u.Why))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Heard(process.EventsStream)
|
||||
}
|
||||
}
|
||||
|
||||
// holderOf names the module holding a seat, asked of the seat that places modules (seatlist.HolderOf), and the machines whose
|
||||
// assignments place it, for the words of a read that met a fault (design 47 H2 H-A-708 (3)).
|
||||
func holderOf(bus caller, w *world) func(seat string) (string, []string) {
|
||||
return func(seat string) (string, []string) {
|
||||
module, err := seatlist.HolderOf(bus.Call, seat)
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
var nodes []string
|
||||
for node, modules := range w.assigned() {
|
||||
if slices.Contains(modules, module) {
|
||||
nodes = append(nodes, node)
|
||||
}
|
||||
}
|
||||
slices.Sort(nodes)
|
||||
return module, nodes
|
||||
}
|
||||
}
|
||||
|
||||
// entriesOf are the catalog entries the passer asks by fingerprint: the followed branches' own, so each catalog-revision asks
|
||||
// again an entry whose ask failed to reach the holder, at most asks times (the setting entry-asks, 0 its default), and the
|
||||
// assigner's finding writer writes entry-not-found and entry-unanswered of them (design 47 H, H-A-60). Each change wakes a pass.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -21,6 +23,7 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
@@ -69,17 +72,80 @@ type outsideActs struct {
|
||||
// bound and settle are the settings outside-wait-minutes and outside-settle-seconds.
|
||||
bound, settle time.Duration
|
||||
// reading is a read in flight by machine, answered the answers it brought, not yet judged by.
|
||||
reading map[string]bool
|
||||
answered map[string][]outside.Cond
|
||||
// dirty is a machine whose waits are judged again, cleared a wait's key whose cause's clearing was heard.
|
||||
dirty map[string]bool
|
||||
cleared map[string]bool
|
||||
reading map[string]bool
|
||||
// answered is, by machine, the newest answer of the conditions and when it was received, kept for the pass that first takes it
|
||||
// and replaced by each new one (design 47 H2b §829 1.); condAt is the time of the last condition event naming the machine.
|
||||
answered map[string]*machineAnswer
|
||||
condAt map[string]time.Time
|
||||
// dirty is a machine whose waits are judged again, cleared a wait's key whose cause's clearing was heard; each is read by every
|
||||
// judging of one pass alike (marks).
|
||||
dirty marks
|
||||
cleared marks
|
||||
// pass is the number of the pass judging now; clock is the passer's, nil for the wall clock.
|
||||
pass int64
|
||||
clock func() time.Time
|
||||
// sigs is each check's last signature, by node.module.
|
||||
sigs map[string]string
|
||||
// causes is, by condition key, the nodes whose waits stand on it, as the last pass kept them.
|
||||
causes map[string][]string
|
||||
// started says the first pass judged every wait again.
|
||||
started bool
|
||||
// started says a pass began before this one, so the first pass judges every wait again.
|
||||
started, first bool
|
||||
}
|
||||
|
||||
// machineAnswer is one answer of the keeper's `conditions` for a machine, the pass that first took it (zero: none yet).
|
||||
type machineAnswer struct {
|
||||
conds []outside.Cond
|
||||
at time.Time
|
||||
takenIn int64
|
||||
}
|
||||
|
||||
// marks are the machines (or keys) whose waits are judged again, read alike by every judging of one pass: a mark is cleared at the
|
||||
// next pass's start only when the pass saw it, so an event heard after a judging is judged by the next (§829 2.).
|
||||
type marks struct {
|
||||
n uint64
|
||||
at, done, seen map[string]uint64
|
||||
}
|
||||
|
||||
func (m *marks) set(k string) {
|
||||
if m.at == nil {
|
||||
m.at, m.done, m.seen = map[string]uint64{}, map[string]uint64{}, map[string]uint64{}
|
||||
}
|
||||
m.n++
|
||||
m.at[k] = m.n
|
||||
}
|
||||
|
||||
func (m *marks) is(k string) bool {
|
||||
v := m.at[k]
|
||||
if v <= m.done[k] {
|
||||
return false
|
||||
}
|
||||
m.seen[k] = max(m.seen[k], v)
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *marks) next() {
|
||||
for k, v := range m.seen {
|
||||
m.done[k] = v
|
||||
delete(m.seen, k)
|
||||
}
|
||||
}
|
||||
|
||||
// beginPass starts a pass of the judgings: what the last pass judged by is spent, and the first pass judges every wait again.
|
||||
func (o *outsideActs) beginPass(now func() time.Time) {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
o.clock = now
|
||||
o.pass++
|
||||
o.dirty.next()
|
||||
o.cleared.next()
|
||||
o.first, o.started = !o.started, true
|
||||
}
|
||||
|
||||
func (o *outsideActs) now() time.Time {
|
||||
if o.clock != nil {
|
||||
return o.clock()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func newOutsideActs(call func(string, any) (json.RawMessage, error), wake func(), logf func(string, ...any), bound, settle time.Duration) *outsideActs {
|
||||
@@ -89,8 +155,7 @@ func newOutsideActs(call func(string, any) (json.RawMessage, error), wake func()
|
||||
if settle <= 0 {
|
||||
settle = outside.DefaultSettle
|
||||
}
|
||||
return &outsideActs{call: call, wake: wake, logf: logf, bound: bound, settle: settle, reading: map[string]bool{}, answered: map[string][]outside.Cond{},
|
||||
dirty: map[string]bool{}, cleared: map[string]bool{}, sigs: map[string]string{}, causes: map[string][]string{}}
|
||||
return &outsideActs{call: call, wake: wake, logf: logf, bound: bound, settle: settle, reading: map[string]bool{}, answered: map[string]*machineAnswer{}, condAt: map[string]time.Time{}, sigs: map[string]string{}, causes: map[string][]string{}}
|
||||
}
|
||||
|
||||
// outsideSettings are the bounds of the wait, the settings outside-wait-minutes and outside-settle-seconds (design 47 G §633, §706),
|
||||
@@ -142,29 +207,44 @@ func (o *outsideActs) Heard(subject string, body []byte) {
|
||||
}
|
||||
cleared := strings.HasSuffix(subject, "."+mcseat.EventConditionCleared)
|
||||
o.mu.Lock()
|
||||
at := o.now()
|
||||
if cleared {
|
||||
for _, node := range o.causes[e.Key] {
|
||||
o.dirty[node] = true
|
||||
o.cleared[node+"|"+e.Key] = true
|
||||
o.dirty.set(node)
|
||||
o.cleared.set(node + "|" + e.Key)
|
||||
o.condAt[node] = at
|
||||
}
|
||||
} else if e.Subject != nil {
|
||||
o.dirty[e.Subject.Machine] = true
|
||||
}
|
||||
if e.Subject != nil {
|
||||
if !cleared {
|
||||
o.dirty.set(e.Subject.Machine)
|
||||
}
|
||||
o.condAt[e.Subject.Machine] = at
|
||||
for _, m := range e.Subject.Also {
|
||||
o.dirty[m] = true
|
||||
if !cleared {
|
||||
o.dirty.set(m)
|
||||
}
|
||||
o.condAt[m] = at
|
||||
}
|
||||
}
|
||||
o.mu.Unlock()
|
||||
o.wake()
|
||||
}
|
||||
|
||||
// take is the conditions read for machine, consumed (one answer is one judging), or false while the kept call is unanswered,
|
||||
// which it starts when none is in flight.
|
||||
func (o *outsideActs) take(machine string) ([]outside.Cond, bool) {
|
||||
// take is the conditions read for machine, or false while the kept call is unanswered, which it starts when none is in flight
|
||||
// (design 47 H2b §829). The answer is kept for the whole pass that first takes it, so every wait judged on the machine in that pass
|
||||
// is judged by it; a later pass reads again, but at a settle's end (settleEnd, the failing check at since) the newest answer serves
|
||||
// when it was received after the failing check and no condition event naming the machine came after it.
|
||||
func (o *outsideActs) take(machine string, since time.Time, settleEnd bool) ([]outside.Cond, bool) {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
if c, ok := o.answered[machine]; ok {
|
||||
delete(o.answered, machine)
|
||||
return c, true
|
||||
if a := o.answered[machine]; a != nil {
|
||||
if a.takenIn == 0 {
|
||||
a.takenIn = o.pass
|
||||
}
|
||||
if a.takenIn == o.pass || (settleEnd && !a.at.Before(since) && !o.condAt[machine].After(a.at)) {
|
||||
return a.conds, true
|
||||
}
|
||||
}
|
||||
if o.reading[machine] {
|
||||
return nil, false
|
||||
@@ -179,10 +259,10 @@ func (o *outsideActs) take(machine string) ([]outside.Cond, bool) {
|
||||
o.mu.Lock()
|
||||
o.reading[machine] = false
|
||||
if err != nil {
|
||||
o.logf("the conditions of %s are not read (%v): the move waits on %s", machine, err, outside.OnUnread)
|
||||
o.logf("the conditions of %s are not read (%v): its waits stand on %s until a judging on an input reads again", machine, err, outside.OnUnread)
|
||||
} else {
|
||||
o.answered[machine] = conds
|
||||
o.dirty[machine] = true // the kept call answered: the move is judged by it
|
||||
o.answered[machine] = &machineAnswer{conds: conds, at: o.now()}
|
||||
o.dirty.set(machine) // the kept call answered: every wait on the machine is judged by it
|
||||
}
|
||||
o.mu.Unlock()
|
||||
if err == nil {
|
||||
@@ -209,8 +289,16 @@ func (p *passer) outsideReview(ctx context.Context, module, fp string, nodes []s
|
||||
override := map[string]string{}
|
||||
// A wait of another fingerprint of this module is replaced by the newer want.
|
||||
for key, raw := range kept {
|
||||
if w, err := outside.Decode(raw); err == nil && w.Module == module && w.FP != fp {
|
||||
w, err := outside.Decode(raw)
|
||||
switch {
|
||||
case err != nil || w.Module != module:
|
||||
case w.Ending != "":
|
||||
// an end written and not said stands until its say finishes it, whatever the want names now (§831)
|
||||
case w.FP != fp:
|
||||
p.outsideEnd(ctx, key, w, outside.HowReplaced, now)
|
||||
case w.Decided != "" && !slices.Contains(nodes, w.Node):
|
||||
// a decided record of a module no longer placed on its machine goes, with no event (§830 2.)
|
||||
p.outsideEnd(ctx, key, w, "", now)
|
||||
}
|
||||
}
|
||||
for _, node := range nodes {
|
||||
@@ -222,13 +310,15 @@ func (p *passer) outsideReview(ctx context.Context, module, fp string, nodes []s
|
||||
}
|
||||
}
|
||||
h, ok := n.Haves[node][module]
|
||||
sig := fmt.Sprintf("%s|%s|%s", h.Fp, h.Phase, h.Health)
|
||||
run, runs := n.Running[node][module]
|
||||
running := runs && run.Fingerprint == fp && !run.Stopped // §827: the node-engine seat's last running names the wait's fingerprint
|
||||
sig := fmt.Sprintf("%s|%s|%s|%t", h.Fp, h.Phase, h.Health, running)
|
||||
o.mu.Lock()
|
||||
first := !o.started
|
||||
first := o.first
|
||||
changed := o.sigs[node+"."+module] != sig
|
||||
o.sigs[node+"."+module] = sig
|
||||
dirty := o.dirty[node]
|
||||
cleared := prev != nil && prev.Cause != "" && o.cleared[node+"|"+prev.Cause]
|
||||
dirty := o.dirty.is(node)
|
||||
cleared := prev != nil && prev.Cause != "" && o.cleared.is(node+"|"+prev.Cause)
|
||||
o.mu.Unlock()
|
||||
failing, healthy := ok && h.Fp == fp && assign.Failed(h), n.RunsHealthy(node, module, fp)
|
||||
if !failing && !healthy && prev == nil {
|
||||
@@ -239,26 +329,33 @@ func (p *passer) outsideReview(ctx context.Context, module, fp string, nodes []s
|
||||
}
|
||||
due := prev != nil && (prev.Release != "" || (prev.Settling && !now.Before(prev.SettleEnds)))
|
||||
var d outside.Decision
|
||||
if prev != nil && !(first || changed || dirty || due) {
|
||||
if prev != nil && prev.Ending != "" {
|
||||
// An end written and not said: it is said again under its id until the bus takes it, and that finishes the wait (§831).
|
||||
d = outside.Judge(prev, node, module, fp, outside.Facts{})
|
||||
p.outsideEnd(ctx, key, *prev, prev.Ending, now)
|
||||
} else if prev != nil && !(first || changed || dirty || due) {
|
||||
// nothing to judge by: the wait stands as kept; the bound's ask is made when it has run
|
||||
d = outside.Decision{Wait: prev, Waiting: prev.Standing() || prev.Settling, Own: prev.Decided == outside.HowFailed || prev.Decided == outside.HowOwnFailure,
|
||||
Counted: prev.Decided == outside.HowGoOn}
|
||||
if prev.Standing() && !now.Before(prev.ClockFrom.Add(o.bound)) {
|
||||
if prev.Standing() && running && prev.Ask != "" {
|
||||
w := *prev
|
||||
w.Ask = ""
|
||||
d.Withdraw, d.Wait = true, &w
|
||||
} else if prev.Standing() && !running && !now.Before(prev.ClockFrom.Add(o.bound)) {
|
||||
d.Ask = true
|
||||
}
|
||||
} else {
|
||||
f := outside.Facts{Now: now, Failing: failing, Healthy: healthy, Node: node, KeeperSelf: keeperSelf, Bound: o.bound, Settle: o.settle,
|
||||
Moved: func(owner string) bool { return moved(owner, node) }, CauseCleared: cleared}
|
||||
if failing && !keeperSelf {
|
||||
f.Conds, f.Read = o.take(node)
|
||||
Moved: func(owner string) bool { return moved(owner, node) }, CauseCleared: cleared, Running: running}
|
||||
if failing && !keeperSelf && (prev == nil || prev.Decided == "") { // a decided record reads nothing (§829 3.)
|
||||
settleEnd := prev != nil && prev.Settling && !now.Before(prev.SettleEnds)
|
||||
since := now
|
||||
if prev != nil {
|
||||
since = prev.Since
|
||||
}
|
||||
f.Conds, f.Read = o.take(node, since, settleEnd)
|
||||
}
|
||||
d = outside.Judge(prev, node, module, fp, f)
|
||||
o.mu.Lock()
|
||||
delete(o.dirty, node)
|
||||
if prev != nil {
|
||||
delete(o.cleared, node+"|"+prev.Cause)
|
||||
}
|
||||
o.mu.Unlock()
|
||||
}
|
||||
switch {
|
||||
case d.Waiting:
|
||||
@@ -266,11 +363,8 @@ func (p *passer) outsideReview(ctx context.Context, module, fp string, nodes []s
|
||||
case d.Counted:
|
||||
override[node] = nodeengineclient.HealthOK
|
||||
}
|
||||
p.outsideApply(ctx, key, hex, node, module, fp, prev, d, now)
|
||||
p.outsideApply(ctx, key, hex, node, module, fp, prev, d, now, running)
|
||||
}
|
||||
o.mu.Lock()
|
||||
o.started = true
|
||||
o.mu.Unlock()
|
||||
if len(override) == 0 {
|
||||
return n
|
||||
}
|
||||
@@ -313,14 +407,14 @@ func (p *passer) outsideAnswered(w *outside.Wait, node, module, fp string) bool
|
||||
}
|
||||
|
||||
// outsideApply keeps what a judging came to: the wait's record, its events, its finding and its ask.
|
||||
func (p *passer) outsideApply(ctx context.Context, key, hex, node, module, fp string, prev *outside.Wait, d outside.Decision, now time.Time) {
|
||||
func (p *passer) outsideApply(ctx context.Context, key, hex, node, module, fp string, prev *outside.Wait, d outside.Decision, now time.Time, running bool) {
|
||||
o := p.outside
|
||||
read := p.w.metaOf(buckets.Waits(), key).revision
|
||||
switch {
|
||||
case prev != nil && prev.Ending != "":
|
||||
return // its end is owed, and its say finishes it (outsideReview)
|
||||
case d.End != "":
|
||||
p.outsideEnd(ctx, key, *prev, d.End, now)
|
||||
if d.Wait != nil {
|
||||
p.keepWait(ctx, key, *d.Wait)
|
||||
}
|
||||
return
|
||||
case d.Wait == nil:
|
||||
if prev != nil {
|
||||
@@ -330,14 +424,24 @@ func (p *passer) outsideApply(ctx context.Context, key, hex, node, module, fp st
|
||||
}
|
||||
w := *d.Wait
|
||||
if d.Held {
|
||||
body := p.outsideBody(w)
|
||||
if err := p.wantsSay(meshwants.EventWaitHeld, body, key+"."+w.On+"."+w.ClockFrom.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
p.logf("the wait of %s on %s is not said, and is said at the next pass: %v", module, node, err)
|
||||
// The record is written with `held-said` raised first, by compare-and-set on the revision the judging read, and the event
|
||||
// is owed under the id it names only once that write took (§832 3.); a lost race is judged again at the next pass.
|
||||
w.HeldSaid++
|
||||
if !p.keepWaitAt(ctx, key, w, read) {
|
||||
p.logf("the wait of %s on %s at %s is not written, so its wait-held is not owed yet", module, node, fp)
|
||||
return
|
||||
}
|
||||
p.wantsOwe(waitOrder(key, w.ClockFrom), meshwants.EventWaitHeld, p.outsideBody(w), waitEventID(node, module, hex, "held."+strconv.Itoa(w.HeldSaid), w.ClockFrom), nil)
|
||||
p.outsideFinding(w, true)
|
||||
}
|
||||
if d.Withdraw {
|
||||
if ask, err := asks.OutsideAskKey(node, module, fp); err == nil {
|
||||
p.remove(ctx, buckets.Asks(), ask)
|
||||
}
|
||||
p.logf("the ask about %s on %s at %s is withdrawn: the module runs its wanted build, and the wait stands on %s", module, node, fp, w.On)
|
||||
}
|
||||
if d.Ask && w.Ask == "" {
|
||||
p.logf("the operator is asked about %s on %s at %s: its wait on %s is past %s and the module does not run its wanted build", module, node, fp, w.On, o.bound)
|
||||
if id := p.outsideAsk(ctx, node, module, fp, w, now); id != "" {
|
||||
w.Ask = id
|
||||
}
|
||||
@@ -350,11 +454,16 @@ func (p *passer) outsideApply(ctx context.Context, key, hex, node, module, fp st
|
||||
}
|
||||
}
|
||||
o.mu.Unlock()
|
||||
if w.Settling {
|
||||
p.wakeAt(w.SettleEnds, now)
|
||||
} else if w.Standing() {
|
||||
p.wakeAt(w.ClockFrom.Add(o.bound), now)
|
||||
// The one deadline timer is armed at a settle's end or a wait's bound only while that time is still to come, and the bound
|
||||
// only while the module does not run its wanted build (design 47 H2b §828): past it nothing is armed, and the wait is judged
|
||||
// again only on an input.
|
||||
var at time.Time
|
||||
if w.Settling && now.Before(w.SettleEnds) {
|
||||
at = w.SettleEnds
|
||||
} else if w.Standing() && !running && now.Before(w.ClockFrom.Add(o.bound)) {
|
||||
at = w.ClockFrom.Add(o.bound)
|
||||
}
|
||||
p.wakeSet("wait."+key, at)
|
||||
p.keepWait(ctx, key, w)
|
||||
}
|
||||
}
|
||||
@@ -370,7 +479,37 @@ func containsString(l []string, s string) bool {
|
||||
|
||||
// keepWait writes the wait's record.
|
||||
func (p *passer) keepWait(ctx context.Context, key string, w outside.Wait) {
|
||||
p.put(ctx, buckets.Waits(), key, func() ([]byte, error) { return outside.Encode(w) })
|
||||
p.keepWaitAt(ctx, key, w, p.w.metaOf(buckets.Waits(), key).revision)
|
||||
}
|
||||
|
||||
// keepWaitAt writes the wait's record by compare-and-set on revision, the one read (0: the key is new), and says whether it took: a
|
||||
// record that moved past it (a hand act, another write) is not overwritten, and its newer value stands (design 47 H2b §832 3.).
|
||||
func (p *passer) keepWaitAt(ctx context.Context, key string, w outside.Wait, revision uint64) bool {
|
||||
value, err := outside.Encode(w)
|
||||
if err != nil {
|
||||
p.logf("%s %s is not written: %v", buckets.Waits(), key, err)
|
||||
return false
|
||||
}
|
||||
raw := p.w.value(buckets.Waits(), key)
|
||||
if raw != nil && bytes.Equal(raw, value) {
|
||||
return true // it stands as it is to be
|
||||
}
|
||||
kv := p.kvs[buckets.Waits()]
|
||||
if raw == nil || revision == 0 {
|
||||
revision, err = kv.Create(ctx, key, value)
|
||||
} else {
|
||||
revision, err = kv.Update(ctx, key, value, revision)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, jetstream.ErrKeyExists) || errors.Is(err, jetstream.ErrKeyRevisionMismatch) || isWrongSequence(err) {
|
||||
p.logf("the wait %s is not written: its record moved past the revision this pass read; the next pass judges it again", key)
|
||||
} else if !errors.Is(err, context.Canceled) {
|
||||
p.logf("%s %s could not be written: %v", buckets.Waits(), key, err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
p.w.putEntry(buckets.Waits(), key, value, revision, p.clock())
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *passer) outsideBody(w outside.Wait) meshwants.Wait {
|
||||
@@ -380,17 +519,47 @@ func (p *passer) outsideBody(w outside.Wait) meshwants.Wait {
|
||||
Words: fmt.Sprintf("%s on %s waits on %s", w.Module, w.Node, w.On)}
|
||||
}
|
||||
|
||||
// outsideEnd ends a wait: its wait-ended with how (none for a settle, which was never said), its finding and ask taken away, and
|
||||
// its record deleted unless the end decided it (the caller keeps that record).
|
||||
// outsideEnd ends a wait (design 47 H2b §831): a standing wait's end, `how`, is written into its record (`ending`) before it is said,
|
||||
// and said before anything of the wait goes; only once the bus has taken `wait-ended` are its ask and finding taken away and the
|
||||
// record written decided or deleted (outside.EndedAs). While the say is owed the record, its ask and its finding stand. A wait that
|
||||
// was never said (a settle, a decided one) and a `how` of "" end at once and delete the record.
|
||||
func (p *passer) outsideEnd(ctx context.Context, key string, w outside.Wait, how string, now time.Time) {
|
||||
if w.Standing() && how != "" {
|
||||
body := p.outsideBody(w)
|
||||
body.How = how
|
||||
if err := p.wantsSay(meshwants.EventWaitEnded, body, key+"."+how+"."+now.UTC().Format(time.RFC3339Nano)); err != nil {
|
||||
p.logf("the end of the wait of %s on %s is not said, and is said at the next pass: %v", w.Module, w.Node, err)
|
||||
if how == "" || !(w.Standing() || w.Ending != "") {
|
||||
p.outsideEnded(ctx, key, w, nil)
|
||||
return
|
||||
}
|
||||
if w.Ending == "" {
|
||||
w.Ending = how
|
||||
if !p.keepWaitAt(ctx, key, w, p.w.metaOf(buckets.Waits(), key).revision) {
|
||||
p.logf("the end of %s on %s (%s) is not written, so it is not said", w.Module, w.Node, how)
|
||||
return
|
||||
}
|
||||
}
|
||||
body := p.outsideBody(w)
|
||||
body.How = how
|
||||
done := context.WithoutCancel(ctx)
|
||||
hex := key[strings.LastIndex(key, ".")+1:]
|
||||
p.wantsOwe(waitOrder(key, w.ClockFrom), meshwants.EventWaitEnded, body, waitEventID(w.Node, w.Module, hex, "ended."+how, w.ClockFrom), func() {
|
||||
p.outsideEnded(done, key, w, outside.EndedAs(w, how))
|
||||
})
|
||||
if w.Ending != "" && p.waitEndingKept(key) {
|
||||
p.logf("the end of %s on %s (%s) is not said yet: its ask, its finding and its record stand", w.Module, w.Node, how)
|
||||
}
|
||||
}
|
||||
|
||||
// waitEndingKept says the record under key still holds an end not yet finished.
|
||||
func (p *passer) waitEndingKept(key string) bool {
|
||||
raw := p.w.value(buckets.Waits(), key)
|
||||
if raw == nil {
|
||||
return false
|
||||
}
|
||||
w, err := outside.Decode(raw)
|
||||
return err == nil && w.Ending != ""
|
||||
}
|
||||
|
||||
// outsideEnded is what the bus taking a wait's end lets go: its finding, its ask and its timer, and the record, written decided or
|
||||
// deleted.
|
||||
func (p *passer) outsideEnded(ctx context.Context, key string, w outside.Wait, decided *outside.Wait) {
|
||||
p.outsideFinding(w, false)
|
||||
if ask, err := asks.OutsideAskKey(w.Node, w.Module, w.FP); err == nil {
|
||||
p.remove(ctx, buckets.Asks(), ask)
|
||||
@@ -400,6 +569,11 @@ func (p *passer) outsideEnd(ctx context.Context, key string, w outside.Wait, how
|
||||
p.outside.causes[w.Cause] = removeString(p.outside.causes[w.Cause], w.Node)
|
||||
p.outside.mu.Unlock()
|
||||
}
|
||||
p.wakeSet("wait."+key, time.Time{}) // a wait that ended arms nothing
|
||||
if decided != nil {
|
||||
p.keepWait(ctx, key, *decided)
|
||||
return
|
||||
}
|
||||
p.remove(ctx, buckets.Waits(), key)
|
||||
}
|
||||
|
||||
@@ -451,10 +625,13 @@ func (p *passer) outsideAsk(ctx context.Context, node, module, fp string, w outs
|
||||
return ""
|
||||
}
|
||||
|
||||
// wakeAt makes a pass when t comes: the settle's end and the bound are the waits' own times, the one wake (no polling).
|
||||
func (p *passer) wakeAt(t, now time.Time) {
|
||||
if p.outside == nil || p.outside.wake == nil {
|
||||
return
|
||||
}
|
||||
time.AfterFunc(max(t.Sub(now), 0)+time.Millisecond, p.outside.wake)
|
||||
// waitOrder is the order the events of one wait are said in: its key `<node>.<module>.<fingerprint>` and its clock-from (§832 1.).
|
||||
func waitOrder(key string, clockFrom time.Time) string {
|
||||
return "wait." + key + "." + clockFrom.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
// waitEventID is the message id of a wait's event: `<node>.<module>.<fingerprint>.<what>.<clock-from>`, the fingerprint the 64 hex
|
||||
// its record's key holds, the names escaped by keys.EscapeName, the time RFC 3339 with nanoseconds in UTC (§832 3.; H-A-831).
|
||||
func waitEventID(node, module, hex, what string, clockFrom time.Time) string {
|
||||
return keys.EscapeName(node) + "." + keys.EscapeName(module) + "." + hex + "." + what + "." + clockFrom.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -15,6 +17,8 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
||||
mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-teller/tellerevents"
|
||||
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
@@ -31,9 +35,19 @@ type outsideRig struct {
|
||||
unread bool
|
||||
events []string
|
||||
bodies []meshwants.Wait
|
||||
ids []string
|
||||
// refuse makes the bus refuse the next n says, as a publish it does not take.
|
||||
refuse int
|
||||
found map[string]bool
|
||||
woke chan struct{}
|
||||
health string
|
||||
// notRunning: the node-engine seat's last running does not name the module at the fingerprint (it is not running its wanted build).
|
||||
notRunning bool
|
||||
// reads counts the conditions reads a judging started.
|
||||
reads int
|
||||
// gate, when set, holds each read unanswered until the test sends one token: a read answers only when the test lets it, so no
|
||||
// answer arrives in the middle of a pass the test is still judging.
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func newOutsideRig(t *testing.T) *outsideRig {
|
||||
@@ -42,12 +56,21 @@ func newOutsideRig(t *testing.T) *outsideRig {
|
||||
r.p.now = func() time.Time { return r.now }
|
||||
r.p.w.put(buckets.Asks(), "x", nil)
|
||||
r.p.outside = newOutsideActs(func(key string, body any) (json.RawMessage, error) {
|
||||
if r.gate != nil {
|
||||
<-r.gate
|
||||
}
|
||||
r.reads++
|
||||
if r.unread {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
return json.Marshal(map[string]any{"conditions": r.conds})
|
||||
}, func() { r.woke <- struct{}{} }, func(string, ...any) {}, 30*time.Minute, 90*time.Second)
|
||||
r.p.publishWants = func(event string, body any, id string) error {
|
||||
if r.refuse > 0 {
|
||||
r.refuse--
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
r.ids = append(r.ids, id)
|
||||
r.events = append(r.events, event)
|
||||
r.bodies = append(r.bodies, body.(meshwants.Wait))
|
||||
return nil
|
||||
@@ -68,12 +91,17 @@ func (r *outsideRig) review(keeperSelf bool, moved func(string, string) bool) as
|
||||
"ace": {"nats": {Fp: fpTest, Phase: nodeengineclient.PhaseRunning, Health: r.health}}}}
|
||||
healthy := r.health == nodeengineclient.HealthOK
|
||||
n.Running = map[string]map[string]nodeengine.Running{"ace": {"nats": {Node: "ace", Module: "nats", Fingerprint: fpTest, Healthy: &healthy}}}
|
||||
if r.notRunning {
|
||||
n.Running = nil
|
||||
}
|
||||
if moved == nil {
|
||||
moved = func(string, string) bool { return false }
|
||||
}
|
||||
r.p.outside.beginPass(r.p.clock)
|
||||
out := r.p.outsideReview(context.Background(), "nats", fpTest, []string{"ace"}, n, keeperSelf, moved)
|
||||
select {
|
||||
case <-r.woke: // the read was answered: the next pass judges by it
|
||||
r.p.outside.beginPass(r.p.clock)
|
||||
out = r.p.outsideReview(context.Background(), "nats", fpTest, []string{"ace"}, n, keeperSelf, moved)
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
@@ -165,9 +193,197 @@ func TestTheWaitOnAnOutsideCause(t *testing.T) {
|
||||
t.Errorf("the keeper's own failing check waits: %s %v", healthOf(n), r2.events)
|
||||
}
|
||||
})
|
||||
t.Run("the operator is asked only while the module does not run its wanted build: kept with no ask when it runs, withdrawn when it comes to run, raised at once when it stops (§827)", func(t *testing.T) {
|
||||
key, _ := asks.OutsideAskKey("ace", "nats", fpTest)
|
||||
for _, unread := range []bool{false, true} {
|
||||
r := newOutsideRig(t)
|
||||
r.unread = unread
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
if unread {
|
||||
r.now = r.now.Add(90 * time.Second)
|
||||
r.review(false, nil)
|
||||
}
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(`{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
if r.p.w.value(buckets.Asks(), key) != nil || len(r.found) != 1 || r.wait().Ask != "" || !r.wait().Standing() {
|
||||
t.Fatalf("unread %v: running past the bound is asked or loses its finding: ask %v findings %v wait %+v", unread, r.p.w.value(buckets.Asks(), key) != nil, r.found, r.wait())
|
||||
}
|
||||
}
|
||||
r := newOutsideRig(t)
|
||||
r.notRunning = true
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(`{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
if r.p.w.value(buckets.Asks(), key) == nil || r.wait().Ask == "" {
|
||||
t.Fatalf("a module not running its wanted build past the bound is not asked: %+v", r.wait())
|
||||
}
|
||||
events := len(r.events)
|
||||
r.notRunning, r.now = false, r.now.Add(time.Minute) // it comes to run
|
||||
r.review(false, nil)
|
||||
if r.p.w.value(buckets.Asks(), key) != nil || r.wait().Ask != "" || len(r.events) != events || len(r.found) != 1 {
|
||||
t.Fatalf("the ask stands after the module came to run, or the wait ended: events %v wait %+v", r.events, r.wait())
|
||||
}
|
||||
r.notRunning, r.now = true, r.now.Add(time.Minute) // it stops again, past the bound
|
||||
r.review(false, nil)
|
||||
if r.p.w.value(buckets.Asks(), key) == nil || r.wait().Ask == "" {
|
||||
t.Fatalf("the ask is not raised at once when the module stops running past the bound: %+v", r.wait())
|
||||
}
|
||||
})
|
||||
t.Run("the bound is armed once, only while to come and the module does not run; past it a wait is judged again only on an input (§828)", func(t *testing.T) {
|
||||
armed := func(r *outsideRig) bool {
|
||||
r.p.wakes.mu.Lock()
|
||||
defer r.p.wakes.mu.Unlock()
|
||||
for k := range r.p.wakes.at {
|
||||
if strings.HasPrefix(k, "wait.") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
input := func(r *outsideRig) {
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(`{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
}
|
||||
for _, notRunning := range []bool{false, true} {
|
||||
r := newOutsideRig(t)
|
||||
r.notRunning = notRunning
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
if armed(r) != notRunning { // a running module's bound is no deadline; a module not running has its bound to come
|
||||
t.Fatalf("notRunning %v: the bound's timer armed = %v before the bound", notRunning, armed(r))
|
||||
}
|
||||
// AC-828c (H-A-872): the rig counts the reads it answers; passes while nothing changes make none
|
||||
standing := r.reads
|
||||
for range 3 {
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.review(false, nil)
|
||||
}
|
||||
if r.reads != standing {
|
||||
t.Errorf("notRunning %v: three passes with nothing changed made %d reads", notRunning, r.reads-standing)
|
||||
}
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
input(r)
|
||||
r.review(false, nil)
|
||||
if armed(r) {
|
||||
t.Fatalf("notRunning %v: a timer stands past the bound", notRunning)
|
||||
}
|
||||
reads := r.reads
|
||||
r.review(false, nil) // nothing changed: not judged again
|
||||
if r.reads != reads {
|
||||
t.Errorf("notRunning %v: a wait past its bound was judged again with no input (%d reads, then %d)", notRunning, reads, r.reads)
|
||||
}
|
||||
if notRunning {
|
||||
// AC-828b: the ask is raised and nothing is armed; its lapse, heard on the teller's ask-ended, raises it again under a new asking
|
||||
key, _ := asks.OutsideAskKey("ace", "nats", fpTest)
|
||||
raw := r.p.w.value(buckets.Asks(), key)
|
||||
_, ask, err := assign.DecodeAsk(key, raw)
|
||||
if err != nil || raw == nil {
|
||||
t.Fatalf("AC-828b: no ask stands past the bound: %v", err)
|
||||
}
|
||||
value, why := assign.AskedAgain(tellerevents.Ended{Key: key, Ask: ask.ID, Outcome: "expired"}, raw, nil, r.now)
|
||||
_, again, derr := assign.DecodeAsk(key, value)
|
||||
if why != "" || derr != nil || again.ID == ask.ID {
|
||||
t.Errorf("AC-828b: the lapse of %s wrote %q (%v), new ask %q", ask.ID, why, derr, again.ID)
|
||||
}
|
||||
}
|
||||
input(r) // a condition raised on M judges it again
|
||||
r.review(false, nil)
|
||||
if r.reads == reads {
|
||||
t.Errorf("notRunning %v: a condition event on the machine did not judge the wait again", notRunning)
|
||||
}
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §828 (H-A-846, AC-828d): a tier's deadline, a wait's bound and an owed event's next are each a time the pass is to
|
||||
// wake at; one timer stands, armed at the earliest, and a later one arms nothing.
|
||||
t.Run("a tier's deadline, a wait's bound and an owed event's next stand on one timer, armed at the earliest (AC-828d)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
var arms []time.Duration
|
||||
stopped := 0
|
||||
r.p.after = func(d time.Duration, _ func()) func() bool {
|
||||
arms = append(arms, d)
|
||||
return func() bool { stopped++; return true }
|
||||
}
|
||||
r.p.wake = func() {}
|
||||
r.p.wakeSet("wait.ace.nats", r.now.Add(30*time.Minute))
|
||||
r.p.wakeSet("tiers", r.now.Add(10*time.Minute))
|
||||
r.p.wakeSet("owed", r.now.Add(20*time.Minute))
|
||||
if len(arms) != 2 || arms[1] != 10*time.Minute+time.Millisecond || stopped != 1 {
|
||||
t.Fatalf("armed %v, stopped %d: the timer is not armed at the earliest of the three, one standing", arms, stopped)
|
||||
}
|
||||
r.p.wakeSet("wait.ace.nats", r.now.Add(40*time.Minute)) // a later time moves nothing
|
||||
if len(arms) != 2 || stopped != 1 {
|
||||
t.Errorf("a later time armed again: %v, stopped %d", arms, stopped)
|
||||
}
|
||||
r.p.wakeSet("tiers", time.Time{}) // the earliest goes: the timer is armed at the next earliest
|
||||
if len(arms) != 3 || arms[2] != 20*time.Minute+time.Millisecond || stopped != 2 {
|
||||
t.Errorf("after the earliest went: armed %v, stopped %d", arms, stopped)
|
||||
}
|
||||
})
|
||||
t.Run("one read of a machine's conditions serves every wait judged on it in one pass, a decided one reads nothing, a settle's end uses the newest answer (§829)", func(t *testing.T) {
|
||||
both := func(r *outsideRig) assign.Nodes {
|
||||
n := assign.Nodes{Online: map[string]bool{"ace": true}, Haves: map[string]map[string]nodeengine.HaveByNodeModuleValue{"ace": {}}}
|
||||
for _, m := range []string{"nats", "web", "db"} {
|
||||
n.Haves["ace"][m] = nodeengine.HaveByNodeModuleValue{Fp: fpTest, Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthFailed}
|
||||
}
|
||||
return n
|
||||
}
|
||||
judge := func(r *outsideRig, modules ...string) {
|
||||
r.p.outside.beginPass(r.p.clock)
|
||||
for _, m := range modules {
|
||||
r.p.outsideReview(context.Background(), m, fpTest, []string{"ace"}, both(r), false, func(string, string) bool { return false })
|
||||
}
|
||||
}
|
||||
r := newOutsideRig(t)
|
||||
r.gate = make(chan struct{}, 4)
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
hex, _ := catalogkey.KeyPart(fpTest)
|
||||
decided, _ := outside.Encode(outside.Wait{Node: "ace", Module: "db", FP: fpTest, Since: r.now, ClockFrom: r.now, Decided: outside.HowGoOn})
|
||||
r.p.w.put(buckets.Waits(), outside.Key("ace", "db", hex), decided)
|
||||
judge(r, "nats", "web", "db") // the first judgings start the one read
|
||||
r.gate <- struct{}{} // the read is answered only now
|
||||
<-r.woke
|
||||
judge(r, "nats", "web", "db") // the pass the answer wakes: every wait on the machine is judged by it
|
||||
if r.reads != 1 || len(r.events) != 2 || r.bodies[0].On != "unreachable:hub" || r.bodies[1].On != "unreachable:hub" {
|
||||
t.Fatalf("two waits and a decided one, one pass: %d reads, events %v bodies %+v", r.reads, r.events, r.bodies)
|
||||
}
|
||||
// a settle's end: no cause open, the answer read in it ends own-failure, never on conditions-unread
|
||||
r2 := newOutsideRig(t)
|
||||
r2.gate = make(chan struct{}, 4)
|
||||
judge(r2, "nats") // settle starts, read starts
|
||||
r2.gate <- struct{}{}
|
||||
<-r2.woke
|
||||
judge(r2, "nats") // the answer: no cause open, a settle
|
||||
r2.now = r2.now.Add(91 * time.Second)
|
||||
judge(r2, "nats") // the settle's end: the answer read before it was received after the failing check and no condition came since
|
||||
if r2.reads != 1 || r2.wait().Decided != outside.HowOwnFailure {
|
||||
t.Fatalf("the settle's end read again (%d reads) or did not end own-failure: %+v", r2.reads, r2.wait())
|
||||
}
|
||||
// a restart: the answer is gone, a settle's end starts a read
|
||||
r3 := newOutsideRig(t)
|
||||
r3.gate = make(chan struct{}, 4)
|
||||
judge(r3, "nats")
|
||||
r3.gate <- struct{}{}
|
||||
<-r3.woke
|
||||
judge(r3, "nats")
|
||||
r3.p.outside = newOutsideActs(r3.p.outside.call, r3.p.outside.wake, func(string, ...any) {}, 30*time.Minute, 90*time.Second)
|
||||
r3.now = r3.now.Add(91 * time.Second)
|
||||
judge(r3, "nats")
|
||||
r3.gate <- struct{}{}
|
||||
<-r3.woke // the read it started is answered
|
||||
if r3.reads != 2 {
|
||||
t.Errorf("a settle's end after a restart did not start a read: %d reads", r3.reads)
|
||||
}
|
||||
})
|
||||
t.Run("past the bound the operator is asked; Go on counts it healthy and Count as failed holds it, each said ended", func(t *testing.T) {
|
||||
for how, want := range map[string]string{assign.OptionGoOn: nodeengineclient.HealthOK, assign.OptionFailed: nodeengineclient.HealthFailed} {
|
||||
r := newOutsideRig(t)
|
||||
r.notRunning = true
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
@@ -203,6 +419,190 @@ func TestTheWaitOnAnOutsideCause(t *testing.T) {
|
||||
}
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §831 (1984/AC-831a to AC-831d): an end is written into the record before it is said, and nothing of the wait goes
|
||||
// before the bus took it.
|
||||
t.Run("an end is written before it is said: the record stays ending with its ask and finding while the say is owed, then is decided; a restart says it again, no wait-held (§831)", func(t *testing.T) {
|
||||
askKey, _ := asks.OutsideAskKey("ace", "nats", fpTest)
|
||||
waitKey := outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:"))
|
||||
ended := func(r *outsideRig) (n int) {
|
||||
for _, e := range r.events {
|
||||
if e == meshwants.EventWaitEnded {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
// asked at the bound, then the operator's Go on, the say of the end refused once
|
||||
start := func() *outsideRig {
|
||||
r := newOutsideRig(t)
|
||||
r.notRunning = true
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(`{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
_, ask, err := assign.DecodeAsk(askKey, r.p.w.value(buckets.Asks(), askKey))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, _ := mdc.EncodeAnswer(mdc.Answer{Option: assign.OptionGoOn, Warrant: ask.ID + "@2026-11-11T10:32:00Z", Words: "the operator"})
|
||||
r.p.w.put(buckets.Answers, askKey, v)
|
||||
r.refuse = 1
|
||||
r.review(false, nil)
|
||||
return r
|
||||
}
|
||||
r := start()
|
||||
if w := r.wait(); w.Ending != outside.HowGoOn || w.Decided != "" || outside.StateOf(w) != "ending:go-on" || r.p.w.value(buckets.Asks(), askKey) == nil || len(r.found) != 1 || ended(r) != 0 {
|
||||
t.Fatalf("AC-831a: with the say refused the record is %+v (%s), ask %v findings %v, ended %d", w, outside.StateOf(r.wait()), r.p.w.value(buckets.Asks(), askKey) != nil, r.found, ended(r))
|
||||
}
|
||||
r.now = r.p.owedNext()
|
||||
r.p.sayOwed()
|
||||
if w := r.wait(); w.Decided != outside.HowGoOn || w.Ending != "" || r.p.w.value(buckets.Asks(), askKey) != nil || len(r.found) != 0 || ended(r) != 1 {
|
||||
t.Errorf("AC-831b: once said the record is %+v, ask %v, findings %v, ended %d", w, r.p.w.value(buckets.Asks(), askKey) != nil, r.found, ended(r))
|
||||
}
|
||||
// AC-831c: a restart between the two (the owed events are lost with the process) says the end again under its id
|
||||
r = start()
|
||||
held := len(r.ids)
|
||||
r.p.owed.list = nil
|
||||
r.p.outside.started = false
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.review(false, nil)
|
||||
if w := r.wait(); w.Decided != outside.HowGoOn || ended(r) != 1 || len(r.ids) != held+1 || !strings.Contains(r.ids[len(r.ids)-1], ".ended.go-on.") || r.events[len(r.events)-1] != meshwants.EventWaitEnded {
|
||||
t.Errorf("AC-831c: after a restart the record is %+v, events %v", w, r.events)
|
||||
}
|
||||
// AC-831d: the bus took the end and the process went before the record's write: the end is said again, then the rest is done
|
||||
w := r.wait()
|
||||
w.Decided, w.Ending = "", outside.HowGoOn
|
||||
raw, _ := outside.Encode(w)
|
||||
r.p.w.put(buckets.Waits(), waitKey, raw)
|
||||
r.p.w.put(buckets.Asks(), askKey, []byte(`{}`))
|
||||
r.p.outside.started = false
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.review(false, nil)
|
||||
if w := r.wait(); w.Decided != outside.HowGoOn || w.Ending != "" || r.p.w.value(buckets.Asks(), askKey) != nil || ended(r) != 2 {
|
||||
t.Errorf("AC-831d: after the restart the record is %+v, ask %v, ended %d", w, r.p.w.value(buckets.Asks(), askKey) != nil, ended(r))
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 4. (1984/AC-832e): a start says `wait-held` again for every standing wait under its held-said, and no
|
||||
// `wait-held` for a settle or a record with `ending`.
|
||||
t.Run("a start says wait-held again for a standing wait under the id first said (§832 4.)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
r.review(false, nil)
|
||||
if len(r.ids) != 1 {
|
||||
t.Fatalf("ids %v", r.ids)
|
||||
}
|
||||
r.p.owed.list = nil // the memory of the process is gone
|
||||
r.p.startWaitsSaid = false
|
||||
r.p.startSays(context.Background())
|
||||
if len(r.ids) != 2 || r.ids[1] != r.ids[0] || r.events[1] != meshwants.EventWaitHeld {
|
||||
t.Errorf("AC-832e: the start said %v %v, want wait-held again under %s", r.events, r.ids, r.ids[0])
|
||||
}
|
||||
r.p.startWaitsSaid = false
|
||||
w := r.wait()
|
||||
w.Ending = outside.HowHealthy
|
||||
r.p.keepWait(context.Background(), outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")), w)
|
||||
r.p.startSays(context.Background())
|
||||
if r.events[len(r.events)-1] != meshwants.EventWaitEnded || len(r.ids) != 3 {
|
||||
t.Errorf("AC-832e: a record with ending said %v, want only its end", r.events)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 6. (1984/AC-832h, AC-832i, AC-832j, AC-832k, AC-832s): past event-unsaid-after an owed event is a finding, cleared
|
||||
// when said; assigner_owed_say says one now; assigner_owed_drop of a wait-ended does the rest of the wait's end; the tools call the
|
||||
// seat's verbs and say so when the program is stopped.
|
||||
t.Run("an owed event is the finding event-unsaid past event-unsaid-after, said by hand or dropped with what waited on it; the tools call the verbs (§832 6.)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
r.p.wake = func() {}
|
||||
r.p.owed.unsaid = 5 * time.Minute
|
||||
r.p.findings.Keys = func() ([]string, error) {
|
||||
var ks []string
|
||||
for k := range r.found {
|
||||
ks = append(ks, k)
|
||||
}
|
||||
return ks, nil
|
||||
}
|
||||
r.notRunning = true
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.refuse = 100
|
||||
r.review(false, nil)
|
||||
owed := r.p.owedAll()
|
||||
if len(owed) != 1 || len(r.found) != 1 {
|
||||
t.Fatalf("owed %+v findings %v", owed, r.found)
|
||||
}
|
||||
r.now = r.now.Add(6 * time.Minute)
|
||||
r.p.owedFindings()
|
||||
key := unsaidKey(owed[0].ID)
|
||||
if !r.found[strings.TrimPrefix(key, "")] || strings.Contains(key, "src2:") || strings.Contains(key, "T") {
|
||||
t.Fatalf("AC-832h: findings %v, want %s (the id with times as Unix nanoseconds)", r.found, key)
|
||||
}
|
||||
// AC-832k: a pass that would make the id owed already makes nothing
|
||||
r.review(false, nil)
|
||||
if got := r.p.owedAll(); len(got) != 1 {
|
||||
t.Errorf("AC-832k: owed %+v after another pass", got)
|
||||
}
|
||||
// AC-832i: said by hand at once; the finding is cleared with it (AC-832h)
|
||||
r.refuse = 0
|
||||
said, err := r.p.owedSay(owed[0].ID)
|
||||
if err != nil || said.ID != owed[0].ID || len(r.p.owedAll()) != 0 || r.found[key] || len(r.events) != 1 || r.events[0] != meshwants.EventWaitHeld {
|
||||
t.Fatalf("AC-832i: said %+v (%v), owed %d, events %v, findings %v", said, err, len(r.p.owedAll()), r.events, r.found)
|
||||
}
|
||||
// AC-832h: a restart no longer owes it, so the first pass clears what the bucket holds
|
||||
r.found[key] = true
|
||||
r.p.owedFindings()
|
||||
if r.found[key] {
|
||||
t.Error("AC-832h: a finding of an event no longer owed stands")
|
||||
}
|
||||
// AC-832j: the drop of the wait-held owed before a wait-ended drops both, and the wait is decided go-on, its ask and finding gone
|
||||
askKey, _ := asks.OutsideAskKey("ace", "nats", fpTest)
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(`{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
_, ask, err := assign.DecodeAsk(askKey, r.p.w.value(buckets.Asks(), askKey))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.refuse = 100
|
||||
w := r.wait()
|
||||
w.HeldSaid++ // a new wait-held the bus refuses, then the end
|
||||
r.p.keepWait(context.Background(), outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")), w)
|
||||
r.p.wantsOwe(waitOrder(outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")), w.ClockFrom), meshwants.EventWaitHeld, r.p.outsideBody(w),
|
||||
waitEventID("ace", "nats", strings.TrimPrefix(fpTest, "src2:"), "held."+strconv.Itoa(w.HeldSaid), w.ClockFrom), nil)
|
||||
v, _ := mdc.EncodeAnswer(mdc.Answer{Option: assign.OptionGoOn, Warrant: ask.ID + "@2026-11-11T10:32:00Z", Words: "the operator"})
|
||||
r.p.w.put(buckets.Answers, askKey, v)
|
||||
r.review(false, nil)
|
||||
owed = r.p.owedAll()
|
||||
if len(owed) != 2 || r.wait().Ending != outside.HowGoOn {
|
||||
t.Fatalf("AC-832j: owed %+v, wait %+v", owed, r.wait())
|
||||
}
|
||||
dropped, err := r.p.owedDrop(owed[0].ID)
|
||||
if err != nil || len(dropped) != 2 || r.wait().Decided != outside.HowGoOn || r.p.w.value(buckets.Asks(), askKey) != nil || len(r.p.owedAll()) != 0 {
|
||||
t.Errorf("AC-832j: the drop answered %+v (%v); wait %+v, ask %v", dropped, err, r.wait(), r.p.w.value(buckets.Asks(), askKey) != nil)
|
||||
}
|
||||
if _, err := r.p.owedDrop("no such id"); err == nil {
|
||||
t.Error("AC-832j: an id not owed was dropped")
|
||||
}
|
||||
// AC-832s: each tool answers through its verb; with the program stopped each says the verb is unanswered
|
||||
var verbs []string
|
||||
tools := owedTools(func(verb string, in any) (json.RawMessage, error) {
|
||||
verbs = append(verbs, verb)
|
||||
return json.RawMessage(`{"events":[]}`), nil
|
||||
})
|
||||
for _, tool := range tools {
|
||||
if _, err := tool.Run(map[string]any{"id": "x", "why": "y"}); err != nil {
|
||||
t.Errorf("AC-832s: %s: %v", tool.Name, err)
|
||||
}
|
||||
}
|
||||
if len(verbs) != 3 || !strings.HasSuffix(verbs[0], "."+meshwants.VerbOwed) || !strings.HasSuffix(verbs[1], "."+meshwants.VerbOwedSay) || !strings.HasSuffix(verbs[2], "."+meshwants.VerbOwedDrop) {
|
||||
t.Errorf("AC-832s: the tools called %v", verbs)
|
||||
}
|
||||
for _, tool := range owedTools(func(string, any) (json.RawMessage, error) { return nil, errors.New("no answer") }) {
|
||||
if _, err := tool.Run(map[string]any{"id": "x", "why": "y"}); err == nil || !strings.Contains(err.Error(), "does not answer the verb") {
|
||||
t.Errorf("AC-832s: %s with the program stopped answered %v", tool.Name, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a newer want ends the wait replaced, and a restart judges it again", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
@@ -213,6 +613,93 @@ func TestTheWaitOnAnOutsideCause(t *testing.T) {
|
||||
t.Errorf("events %v", r.events)
|
||||
}
|
||||
})
|
||||
t.Run("an event the bus refuses is owed under one id and said again in order, at 2s, 4s, doubling to the pace's end (§832 1., 2.)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
var armed []time.Duration
|
||||
r.p.wake = func() {}
|
||||
r.p.after = func(d time.Duration, f func()) func() bool {
|
||||
armed = append(armed, d)
|
||||
return func() bool { return true }
|
||||
}
|
||||
r.p.owed.last = 8 * time.Second
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
r.refuse = 3 // the wait-held is refused now, and at its first two says again
|
||||
r.review(false, nil)
|
||||
if len(r.events) != 0 {
|
||||
t.Fatalf("a refused event was said: %v", r.events)
|
||||
}
|
||||
// the wait ends while its wait-held is owed: the end is owed behind it, never tried before it
|
||||
r.conds, r.health, r.now = nil, nodeengineclient.HealthOK, r.now.Add(time.Minute)
|
||||
r.review(false, nil)
|
||||
if len(r.events) != 0 || len(r.p.owed.list) != 2 {
|
||||
t.Fatalf("events %v owed %d, want the held and the end owed in order", r.events, len(r.p.owed.list))
|
||||
}
|
||||
heldID, endID := r.p.owed.list[0].id, r.p.owed.list[1].id
|
||||
for _, want := range []struct {
|
||||
tries int
|
||||
delay time.Duration
|
||||
}{{1, 4 * time.Second}, {2, 8 * time.Second}} {
|
||||
r.now = r.p.owedNext()
|
||||
if r.p.sayOwed() || r.p.owed.list[0].tries != want.tries || r.p.owed.list[0].next.Sub(r.now) != want.delay {
|
||||
t.Fatalf("try %d: said %v owed %+v, want the next delay %v", want.tries, r.events, r.p.owed.list[0], want.delay)
|
||||
}
|
||||
}
|
||||
if d := r.p.owed.list[0].next.Sub(r.now); d != 8*time.Second {
|
||||
t.Errorf("the third delay %v, want 8s (the pace's end)", d)
|
||||
}
|
||||
r.now = r.p.owedNext()
|
||||
if !r.p.sayOwed() {
|
||||
t.Fatal("the bus took nothing")
|
||||
}
|
||||
if len(r.events) != 2 || r.events[0] != meshwants.EventWaitHeld || r.events[1] != meshwants.EventWaitEnded || r.ids[0] != heldID || r.ids[1] != endID || len(r.p.owed.list) != 0 {
|
||||
t.Errorf("events %v ids %v, owed %d: want held then ended under the ids first owed (%s, %s)", r.events, r.ids, len(r.p.owed.list), heldID, endID)
|
||||
}
|
||||
if !strings.Contains(heldID, ".held.1.") || !strings.Contains(endID, ".ended.healthy.") || len(armed) == 0 {
|
||||
t.Errorf("ids %s %s, armed %v", heldID, endID, armed)
|
||||
}
|
||||
})
|
||||
t.Run("an on going from A to B and back to A says three wait-held under three ids; a name with a dot is escaped (§832 3.; H-A-831)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
r.review(false, nil)
|
||||
for _, key := range []string{"machine.hub.network", "machine.hub.unreachable"} {
|
||||
r.conds = nil
|
||||
r.cond(key, "ace")
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-raised", []byte(`{"key":"`+key+`","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range r.ids {
|
||||
seen[id] = true
|
||||
}
|
||||
if len(r.ids) != 3 || len(seen) != 3 {
|
||||
t.Errorf("wait-held ids %v, want three different", r.ids)
|
||||
}
|
||||
if id := waitEventID("a.b", "m.x", "00ff", "held.1", r.now); !strings.HasPrefix(id, "a=2eb.m=2ex.00ff.held.1.") {
|
||||
t.Errorf("id %q holds a dot unescaped", id)
|
||||
}
|
||||
})
|
||||
t.Run("held-said and ending are written by compare-and-set: a record that moved past the read is not overwritten and owes no event (§832 3., review r1 finding 2)", func(t *testing.T) {
|
||||
r := newOutsideRig(t)
|
||||
r.cond("machine.hub.unreachable", "ace")
|
||||
r.review(false, nil)
|
||||
kv := r.p.kvs[buckets.Waits()].(*memKV)
|
||||
for key := range kv.values {
|
||||
kv.revs[key] += 100 // a rival write: the world still holds the revision it read
|
||||
}
|
||||
before := len(r.ids)
|
||||
r.conds = nil
|
||||
r.cond("machine.hub.network", "ace")
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-raised", []byte(`{"key":"machine.hub.network","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
if len(r.ids) != before || r.wait().HeldSaid != 1 {
|
||||
t.Errorf("a held write that lost the race owed %v and left held-said %d", r.ids[before:], r.wait().HeldSaid)
|
||||
}
|
||||
})
|
||||
t.Run("its bounds are read at the start from the files the manifest declares (A-112)", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, content string) string {
|
||||
@@ -279,4 +766,128 @@ func TestTheToolsReadAndReleaseAnOutsideWait(t *testing.T) {
|
||||
if r.bodies[len(r.bodies)-1].How != "go-on" || n.Haves["ace"]["nats"].Health != nodeengineclient.HealthOK {
|
||||
t.Errorf("last %+v health %s", r.bodies[len(r.bodies)-1], n.Haves["ace"]["nats"].Health)
|
||||
}
|
||||
// Design 47 H2b §830 (1984/AC-830a to AC-830c): the state is derived from the record, a decided record lives until its fingerprint
|
||||
// runs healthy or is replaced, and assigner_wait_drop drops it by hand.
|
||||
t.Run("assigner_waits derives the states; a decided record goes when healthy or replaced, with no second end; assigner_wait_drop drops it (§830)", func(t *testing.T) {
|
||||
stateOf := func(r *outsideRig) (states []string) {
|
||||
s := newPutTools(memStore{waitsState: &memKV{values: map[string][]byte{}}}, func(string, any) (json.RawMessage, error) { return nil, nil })
|
||||
for k, v := range r.p.w.read(buckets.Waits()) {
|
||||
s.st.put(waitsState, k, v)
|
||||
}
|
||||
got, err := s.doWaits(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, w := range got.(map[string]any)["waits"].([]any) {
|
||||
states = append(states, w.(waitSaid).State)
|
||||
}
|
||||
return states
|
||||
}
|
||||
askKey, _ := asks.OutsideAskKey("ace", "nats", fpTest)
|
||||
heard := `{"key":"machine.hub.silent","subject":{"id":"hub","scope":"machine","machine":"hub","also":["ace"]}}`
|
||||
// a settle, then own-failure
|
||||
r := newOutsideRig(t)
|
||||
r.review(false, nil)
|
||||
if got := stateOf(r); len(got) != 1 || got[0] != "settling" {
|
||||
t.Fatalf("AC-830a: a settle is %v", got)
|
||||
}
|
||||
r.now = r.now.Add(2 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-raised", []byte(heard))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
if got := stateOf(r); len(got) != 1 || got[0] != "decided:own-failure" {
|
||||
t.Errorf("AC-830a: a settle's end is %v", got)
|
||||
}
|
||||
// waiting, asked past the bound, decided go-on
|
||||
r = newOutsideRig(t)
|
||||
r.notRunning = true
|
||||
r.cond("machine.hub.silent", "ace")
|
||||
r.review(false, nil)
|
||||
if got := stateOf(r); len(got) != 1 || got[0] != "waiting" {
|
||||
t.Fatalf("AC-830a: a standing wait is %v", got)
|
||||
}
|
||||
r.now = r.now.Add(31 * time.Minute)
|
||||
r.p.outside.Heard("mesh.seat.mesh-conditions.event.condition-changed", []byte(heard))
|
||||
<-r.woke
|
||||
r.review(false, nil)
|
||||
if got := stateOf(r); len(got) != 1 || got[0] != "asked" {
|
||||
t.Fatalf("AC-830a: a wait past its bound is %v", got)
|
||||
}
|
||||
_, ask, _ := assign.DecodeAsk(askKey, r.p.w.value(buckets.Asks(), askKey))
|
||||
v, _ := mdc.EncodeAnswer(mdc.Answer{Option: assign.OptionGoOn, Warrant: ask.ID + "@2026-11-11T10:32:00Z", Words: "the operator"})
|
||||
r.p.w.put(buckets.Answers, askKey, v)
|
||||
r.review(false, nil)
|
||||
if got := stateOf(r); len(got) != 1 || got[0] != "decided:go-on" || r.wait().On != "silent:hub" || r.wait().Since.IsZero() {
|
||||
t.Fatalf("AC-830a: a Go on is %v, record %+v", got, r.wait())
|
||||
}
|
||||
// AC-830b: a want naming another fingerprint deletes it, with no second end; a healthy module deletes it too
|
||||
ended := func() (n int) {
|
||||
for _, e := range r.events {
|
||||
if e == meshwants.EventWaitEnded {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
before := ended()
|
||||
n := assign.Nodes{Online: map[string]bool{"ace": true}, Haves: map[string]map[string]nodeengine.HaveByNodeModuleValue{}}
|
||||
saved := r.p.w.value(buckets.Waits(), outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")))
|
||||
r.p.outsideReview(context.Background(), "nats", "src2:"+strings.Repeat("c", 64), []string{"ace"}, n, false, func(string, string) bool { return false })
|
||||
if len(r.p.w.read(buckets.Waits())) != 0 || ended() != before {
|
||||
t.Errorf("AC-830b: a decided record of another fingerprint stands (%v) or ends again (%d)", stateOf(r), ended()-before)
|
||||
}
|
||||
restore := func() {
|
||||
_, _ = r.p.kvs[buckets.Waits()].Put(context.Background(), outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")), saved)
|
||||
r.p.w.put(buckets.Waits(), outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:")), saved)
|
||||
}
|
||||
restore()
|
||||
r.notRunning, r.health = false, nodeengineclient.HealthOK
|
||||
r.review(false, nil)
|
||||
if len(r.p.w.read(buckets.Waits())) != 0 || ended() != before {
|
||||
t.Errorf("AC-830b: a decided record of a module running healthy stands (%v) or ends again", stateOf(r))
|
||||
}
|
||||
restore()
|
||||
r.notRunning, r.health = true, nodeengineclient.HealthFailed
|
||||
r.p.outsideReview(context.Background(), "nats", fpTest, nil, n, false, func(string, string) bool { return false })
|
||||
if len(r.p.w.read(buckets.Waits())) != 0 {
|
||||
t.Errorf("AC-830b: a decided record of a module no longer placed on its machine stands (%v)", stateOf(r))
|
||||
}
|
||||
// AC-830c: assigner_wait_drop drops a decided record, and the next failing check there is a new wait
|
||||
key := outside.Key("ace", "nats", strings.TrimPrefix(fpTest, "src2:"))
|
||||
st := memStore{waitsState: &memKV{values: map[string][]byte{key: saved}}}
|
||||
var acts []string
|
||||
act := func(verb string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
acts = append(acts, string(raw))
|
||||
return json.RawMessage(`{"ok":true,"log":"logged"}`), nil
|
||||
}
|
||||
if _, err := dropWait(st, act, key, "", "person.jochen"); err == nil {
|
||||
t.Error("AC-830c: a drop with no why is taken")
|
||||
}
|
||||
if _, err := dropWait(st, act, key, "the hub is back", "person.jochen"); err != nil || len(st[waitsState].values) != 0 || len(acts) != 1 || !strings.Contains(acts[0], waitDropTool+" "+key) {
|
||||
t.Fatalf("AC-830c: the drop answered %v, left %d, acts %v", err, len(st[waitsState].values), acts)
|
||||
}
|
||||
standing, _ := outside.Encode(outside.Wait{Node: "ace", Module: "nats", FP: fpTest, Since: r.now, ClockFrom: r.now})
|
||||
st[waitsState].values[key] = standing
|
||||
if _, err := dropWait(st, act, key, "x", "person.jochen"); err == nil || len(st[waitsState].values) != 1 {
|
||||
t.Error("AC-830c: a wait that stands is dropped")
|
||||
}
|
||||
// the record gone, the next failing check there is held as a new wait
|
||||
held := 0
|
||||
for _, e := range r.events {
|
||||
if e == meshwants.EventWaitHeld {
|
||||
held++
|
||||
}
|
||||
}
|
||||
r.review(false, nil)
|
||||
after := 0
|
||||
for _, e := range r.events {
|
||||
if e == meshwants.EventWaitHeld {
|
||||
after++
|
||||
}
|
||||
}
|
||||
if after != held+1 || r.wait().Decided != "" {
|
||||
t.Errorf("AC-830c: after the drop the next failing check is not held as a new wait: held %d then %d, %+v", held, after, r.wait())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ const waitsState = buckets.WaitsState
|
||||
type waitSaid struct {
|
||||
Key string `json:"key"`
|
||||
outside.Wait
|
||||
// State is derived from the record at the read (design 47 H2b §830 1.): settling, waiting, asked, ending:<how> or decided:<how>.
|
||||
State string `json:"state"`
|
||||
// Settling's end is in the record; Ends is when the bound runs from clock-from, empty for a settle.
|
||||
BoundEnds string `json:"bound-ends,omitempty"`
|
||||
}
|
||||
@@ -50,7 +52,7 @@ func (s *putTools) doWaits(args map[string]any) (any, error) {
|
||||
if err != nil || (arg(args, "node") != "" && w.Node != arg(args, "node")) || (arg(args, "module") != "" && w.Module != arg(args, "module")) {
|
||||
continue
|
||||
}
|
||||
said := waitSaid{Key: key, Wait: w}
|
||||
said := waitSaid{Key: key, Wait: w, State: outside.StateOf(w)}
|
||||
if w.Standing() {
|
||||
if d, err := time.ParseDuration(w.Bound); err == nil {
|
||||
said.BoundEnds = w.ClockFrom.Add(d).UTC().Format("2006-01-02T15:04:05Z")
|
||||
@@ -86,7 +88,7 @@ func (s *putTools) doReleaseWait(args map[string]any, by string) (any, error) {
|
||||
if err != nil || !found {
|
||||
continue
|
||||
}
|
||||
if c, err := outside.Decode(raw); err == nil && c.Decided == "" {
|
||||
if c, err := outside.Decode(raw); err == nil && c.Decided == "" && c.Ending == "" {
|
||||
key, w = k, c
|
||||
}
|
||||
}
|
||||
@@ -114,7 +116,9 @@ func (s *putTools) doReleaseWait(args map[string]any, by string) (any, error) {
|
||||
func (s *putTools) waitsTool() stdio.Tool {
|
||||
return stdio.Tool{Name: toolWaits, Description: "Every wait of the delivery and where it stands: a moved module's failing health check on a " +
|
||||
"machine whose open conditions name a cause outside the delivery (design 47 G §706), with its module, machine, fingerprint, the " +
|
||||
"condition's key, what it stands `on`, its clock-from, bound, its ask and its state; a settle shows as settling with its end. Narrowed by " +
|
||||
"condition's key, what it stands `on`, its clock-from, bound, its ask and its state, derived from the record: settling (with its end), " +
|
||||
"waiting, asked, ending:<how> (an end not said yet) or decided:<how> (a decided record lives until its fingerprint runs healthy, " +
|
||||
"a want names another one or the module is no longer placed there, and answers its last `on` and `since`). Narrowed by " +
|
||||
"machine or module. Read-only.",
|
||||
Input: schema(map[string]string{"node": "one machine", "module": "one module"}, nil), Run: s.doWaits}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// An event the bus refuses is owed in order and said again, never dropped (design 47 H §832 1., 2.; H-A-777, H-A-801): the
|
||||
// events the assigner says on the seat mesh-wants (`wanted`, `pipeline-wanted`, `wait-held`, `wait-ended`) are kept in its memory
|
||||
// when the bus refuses them or does not acknowledge them, in the order they were made within one wait, one pipeline or one want,
|
||||
// and the first of each order is said again on the one deadline timer under the message id fixed when it was first owed.
|
||||
|
||||
// The defaults of the settings say-again-pace-first and say-again-pace-max (design 47 H §832 2.).
|
||||
const (
|
||||
defaultSayAgainFirst = 2 * time.Second
|
||||
defaultSayAgainMax = time.Minute
|
||||
)
|
||||
|
||||
// owedEvent is one event owed: what the bus was to be told, and where its saying again stands.
|
||||
type owedEvent struct {
|
||||
order, event string
|
||||
body any
|
||||
id string
|
||||
firstOwed time.Time
|
||||
tries int
|
||||
next time.Time
|
||||
// taken is what waited on the bus taking it (a record kept until then); nil for none. It runs once, at the say or at a drop.
|
||||
taken func()
|
||||
}
|
||||
|
||||
// owedKept is the events owed, in the order they were made; the memory of the process, never the bus that refused them.
|
||||
type owedKept struct {
|
||||
mu sync.Mutex
|
||||
list []*owedEvent
|
||||
first, last time.Duration // the setting's pace; zero: the defaults
|
||||
unsaid time.Duration // the setting event-unsaid-after; zero: its default
|
||||
}
|
||||
|
||||
func (o *owedKept) pace() (first, max time.Duration) {
|
||||
first, max = o.first, o.last
|
||||
if first <= 0 {
|
||||
first = defaultSayAgainFirst
|
||||
}
|
||||
if max <= 0 {
|
||||
max = defaultSayAgainMax
|
||||
}
|
||||
return first, max
|
||||
}
|
||||
|
||||
func (o *owedKept) has(id string) bool {
|
||||
return slices.ContainsFunc(o.list, func(e *owedEvent) bool { return e.id == id })
|
||||
}
|
||||
|
||||
func (o *owedKept) ordered(order string) bool {
|
||||
return slices.ContainsFunc(o.list, func(e *owedEvent) bool { return e.order == order })
|
||||
}
|
||||
|
||||
// owedSetting is a setting kept as a Go duration, read at the start from the file the manifest declares; zero, its default,
|
||||
// for a file missing or empty.
|
||||
func owedSetting(getenv func(string) string) (first, max time.Duration, err error) {
|
||||
if first, err = durationFile(getenv("MESH_ASSIGNER_SAY_AGAIN_PACE_FIRST_FILE")); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
max, err = durationFile(getenv("MESH_ASSIGNER_SAY_AGAIN_PACE_MAX_FILE"))
|
||||
return first, max, err
|
||||
}
|
||||
|
||||
// wantsOwe says one event of the seat mesh-wants, and owes it when the bus does not take it: an id already owed makes nothing, an
|
||||
// event whose order has an earlier one owed is owed behind it and not tried, and one the bus refuses is kept with `first-owed`,
|
||||
// `tries` and `next`. taken runs once the bus has taken the event (at once when it takes it now). With no bus, nothing is said.
|
||||
func (p *passer) wantsOwe(order, event string, body any, id string, taken func()) {
|
||||
if p.publishWants == nil {
|
||||
if taken != nil {
|
||||
taken()
|
||||
}
|
||||
return
|
||||
}
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
if o.has(id) {
|
||||
return
|
||||
}
|
||||
first, _ := o.pace()
|
||||
now := p.clock().UTC()
|
||||
e := &owedEvent{order: order, event: event, body: body, id: id, firstOwed: now, next: now.Add(first), taken: taken}
|
||||
if o.ordered(order) {
|
||||
o.list = append(o.list, e)
|
||||
p.logf("%s %s is owed behind an earlier event of its order %s", event, id, order)
|
||||
return
|
||||
}
|
||||
if err := p.publishWants(event, body, id); err != nil {
|
||||
o.list = append(o.list, e)
|
||||
p.logf("%s %s is not said and is owed, said again from %s: %v", event, id, e.next.Format(time.RFC3339Nano), err)
|
||||
return
|
||||
}
|
||||
if taken != nil {
|
||||
taken()
|
||||
}
|
||||
}
|
||||
|
||||
// sayOwed says again each owed event whose time has come, the first of each order and then the next of that order once it is taken
|
||||
// (§832 2.): a refusal doubles the delay up to say-again-pace-max. It answers whether the bus took any.
|
||||
func (p *passer) sayOwed() bool {
|
||||
if p.publishWants == nil {
|
||||
return false
|
||||
}
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
now := p.clock().UTC()
|
||||
first, max := o.pace()
|
||||
said, blocked, freed := false, map[string]bool{}, map[string]bool{}
|
||||
for i := 0; i < len(o.list); {
|
||||
e := o.list[i]
|
||||
if blocked[e.order] {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if e.next.After(now) && !freed[e.order] { // the next of an order is said once the one before it is taken
|
||||
blocked[e.order] = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if err := p.publishWants(e.event, e.body, e.id); err != nil {
|
||||
e.tries++
|
||||
delay := first
|
||||
for n := 0; n < e.tries && delay < max; n++ {
|
||||
delay *= 2
|
||||
}
|
||||
e.next = now.Add(min(delay, max))
|
||||
p.logf("%s %s is not said again (try %d), said again from %s: %v", e.event, e.id, e.tries, e.next.Format(time.RFC3339Nano), err)
|
||||
blocked[e.order] = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
p.logf("%s %s is said again (try %d)", e.event, e.id, e.tries+1)
|
||||
o.list = slices.Delete(o.list, i, i+1)
|
||||
if e.taken != nil {
|
||||
e.taken()
|
||||
}
|
||||
said, freed[e.order] = true, true
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
// owedNext is the earliest time an owed event is to be said again, the first of its order only; zero for none.
|
||||
func (p *passer) owedNext() time.Time {
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
var next time.Time
|
||||
seen := map[string]bool{}
|
||||
for _, e := range o.list {
|
||||
if seen[e.order] {
|
||||
continue
|
||||
}
|
||||
seen[e.order] = true
|
||||
if next.IsZero() || e.next.Before(next) {
|
||||
next = e.next
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
// wakes are the times a pass is to be made at by itself, by source: the tiers' earliest deadline, each wait's bound or settle end,
|
||||
// and the owed events' earliest `next`. One timer stands, armed at the earliest (H-A-846; principle 7).
|
||||
type wakes struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
stop func() bool
|
||||
armed time.Time
|
||||
}
|
||||
|
||||
// wakeSet records the time source is to wake the pass at (zero: none) and arms the one timer at the earliest recorded.
|
||||
func (p *passer) wakeSet(source string, at time.Time) {
|
||||
wake := p.wake
|
||||
if wake == nil && p.outside != nil {
|
||||
wake = p.outside.wake
|
||||
}
|
||||
if wake == nil {
|
||||
return
|
||||
}
|
||||
w := &p.wakes
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.at == nil {
|
||||
w.at = map[string]time.Time{}
|
||||
}
|
||||
if at.IsZero() {
|
||||
delete(w.at, source)
|
||||
} else {
|
||||
w.at[source] = at
|
||||
}
|
||||
var earliest time.Time
|
||||
for _, t := range w.at {
|
||||
if earliest.IsZero() || t.Before(earliest) {
|
||||
earliest = t
|
||||
}
|
||||
}
|
||||
if earliest.Equal(w.armed) && w.stop != nil {
|
||||
return
|
||||
}
|
||||
if w.stop != nil {
|
||||
w.stop()
|
||||
w.stop = nil
|
||||
}
|
||||
w.armed = earliest
|
||||
if earliest.IsZero() {
|
||||
return
|
||||
}
|
||||
d := max(earliest.Sub(p.clock()), 0) + time.Millisecond
|
||||
fire := func() {
|
||||
w.mu.Lock()
|
||||
for k, t := range w.at {
|
||||
if !t.After(earliest) {
|
||||
delete(w.at, k) // heard: a pass that still needs it sets it again
|
||||
}
|
||||
}
|
||||
w.armed, w.stop = time.Time{}, nil
|
||||
w.mu.Unlock()
|
||||
wake()
|
||||
}
|
||||
if p.after != nil {
|
||||
w.stop = p.after(d, fire)
|
||||
return
|
||||
}
|
||||
t := time.AfterFunc(d, fire)
|
||||
w.stop = t.Stop
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
)
|
||||
|
||||
// The owed events' reading and steering (design 47 H2b §832 6., H-A-847, H-A-869): the seat mesh-wants' verbs `owed`, `owed-say` and
|
||||
// `owed-drop` are answered by the assigner's program, which keeps the owed events in its memory, and the tools assigner_owed,
|
||||
// assigner_owed_say and assigner_owed_drop call them. Past `event-unsaid-after` an owed event is the finding `event-unsaid`.
|
||||
|
||||
const (
|
||||
owedTool = "assigner_owed"
|
||||
owedSayTool = "assigner_owed_say"
|
||||
owedDropTool = "assigner_owed_drop"
|
||||
// kindEventUnsaid is the finding of an event owed for event-unsaid-after, scope delivery, id the message id made a key.
|
||||
kindEventUnsaid = "event-unsaid"
|
||||
// defaultEventUnsaidAfter is the setting event-unsaid-after's default.
|
||||
defaultEventUnsaidAfter = 5 * time.Minute
|
||||
)
|
||||
|
||||
func (o *owedKept) unsaidFor() time.Duration {
|
||||
if o.unsaid > 0 {
|
||||
return o.unsaid
|
||||
}
|
||||
return defaultEventUnsaidAfter
|
||||
}
|
||||
|
||||
// owedSeen is e as the seat's verbs answer it.
|
||||
func owedSeen(e *owedEvent) meshwants.OwedEvent {
|
||||
return meshwants.OwedEvent{ID: e.id, FirstOwed: e.firstOwed, Next: e.next, Tries: int64(e.tries)}
|
||||
}
|
||||
|
||||
// owedAll is every owed event, in the order they were made.
|
||||
func (p *passer) owedAll() []meshwants.OwedEvent {
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
out := make([]meshwants.OwedEvent, 0, len(o.list))
|
||||
for _, e := range o.list {
|
||||
out = append(out, owedSeen(e))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// owedSay says the first owed event of id's order now, its delay set back to say-again-pace-first; it answers the event said, or the
|
||||
// refusal of the bus (the event stays owed, said again from say-again-pace-first on).
|
||||
func (p *passer) owedSay(id string) (meshwants.OwedEvent, error) {
|
||||
if p.publishWants == nil {
|
||||
return meshwants.OwedEvent{}, errors.New("the assigner has no bus to say it on")
|
||||
}
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
at := slicesIndex(o.list, id)
|
||||
if at < 0 {
|
||||
o.mu.Unlock()
|
||||
return meshwants.OwedEvent{}, fmt.Errorf("no event is owed under %q: assigner_owed lists them", id)
|
||||
}
|
||||
var e *owedEvent
|
||||
for _, c := range o.list {
|
||||
if c.order == o.list[at].order {
|
||||
e = c
|
||||
break
|
||||
}
|
||||
}
|
||||
first, _ := o.pace()
|
||||
now := p.clock().UTC()
|
||||
if err := p.publishWants(e.event, e.body, e.id); err != nil {
|
||||
e.tries, e.next = 0, now.Add(first)
|
||||
o.mu.Unlock()
|
||||
return owedSeen(e), fmt.Errorf("the bus did not take %s %s: %w; it stays owed, said again from %s", e.event, e.id, err, e.next.Format(time.RFC3339))
|
||||
}
|
||||
seen := owedSeen(e)
|
||||
o.list = slicesDelete(o.list, e)
|
||||
o.mu.Unlock()
|
||||
p.logf("%s %s is said by hand", e.event, e.id)
|
||||
if e.taken != nil {
|
||||
e.taken()
|
||||
}
|
||||
p.owedFindings()
|
||||
if p.wake != nil {
|
||||
p.wake()
|
||||
}
|
||||
return seen, nil
|
||||
}
|
||||
|
||||
// owedDrop drops the owed event id and every event owed behind it in its order, doing for each what the bus taking it would have
|
||||
// done (its taken), then clears their findings; it answers the events dropped, the named one first.
|
||||
func (p *passer) owedDrop(id string) ([]meshwants.OwedEvent, error) {
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
at := slicesIndex(o.list, id)
|
||||
if at < 0 {
|
||||
o.mu.Unlock()
|
||||
return nil, fmt.Errorf("no event is owed under %q: assigner_owed lists them", id)
|
||||
}
|
||||
order := o.list[at].order
|
||||
var dropped []*owedEvent
|
||||
var kept []*owedEvent
|
||||
for i, e := range o.list {
|
||||
if e.order == order && i >= at {
|
||||
dropped = append(dropped, e)
|
||||
continue
|
||||
}
|
||||
kept = append(kept, e)
|
||||
}
|
||||
o.list = kept
|
||||
o.mu.Unlock()
|
||||
seen := make([]meshwants.OwedEvent, 0, len(dropped))
|
||||
for _, e := range dropped {
|
||||
seen = append(seen, owedSeen(e))
|
||||
p.logf("%s %s is dropped by hand, with what waited on it done", e.event, e.id)
|
||||
if e.taken != nil {
|
||||
e.taken()
|
||||
}
|
||||
}
|
||||
p.owedFindings()
|
||||
if p.wake != nil {
|
||||
p.wake()
|
||||
}
|
||||
return seen, nil
|
||||
}
|
||||
|
||||
func slicesIndex(list []*owedEvent, id string) int {
|
||||
for i, e := range list {
|
||||
if e.id == id {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func slicesDelete(list []*owedEvent, e *owedEvent) []*owedEvent {
|
||||
out := list[:0:0]
|
||||
for _, c := range list {
|
||||
if c != e {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var (
|
||||
unsaidFp = regexp.MustCompile(`src2:([0-9a-f]{64})`)
|
||||
unsaidTime = regexp.MustCompile(`\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z`)
|
||||
)
|
||||
|
||||
// unsaidID is a message id as the finding's id: each fingerprint as its 64 hex digits without `src2:` and each time as Unix
|
||||
// nanoseconds (design 47 H2b §832 6.); assign.KeyID makes it a key.
|
||||
func unsaidID(id string) string {
|
||||
id = unsaidFp.ReplaceAllString(id, "$1")
|
||||
return unsaidTime.ReplaceAllStringFunc(id, func(s string) string {
|
||||
t, err := time.Parse(time.RFC3339Nano, s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return strconv.FormatInt(t.UnixNano(), 10)
|
||||
})
|
||||
}
|
||||
|
||||
func unsaidKey(id string) string {
|
||||
return views.FindingKey(mcc.ScopeDelivery, assign.KeyID(unsaidID(id)), kindEventUnsaid)
|
||||
}
|
||||
|
||||
// owedFindings writes the finding `event-unsaid` of each event owed for event-unsaid-after, and clears, from the bucket's keys read
|
||||
// now, every one of an event no longer owed: said, dropped, or not owed again after a restart (H-A-722).
|
||||
func (p *passer) owedFindings() {
|
||||
have, ok := p.findingKeys("the finding event-unsaid")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
o := &p.owed
|
||||
o.mu.Lock()
|
||||
now, after := p.clock().UTC(), o.unsaidFor()
|
||||
owed := map[string]bool{}
|
||||
var raise []*owedEvent
|
||||
for _, e := range o.list {
|
||||
if now.Sub(e.firstOwed) < after {
|
||||
continue
|
||||
}
|
||||
owed[unsaidKey(e.id)] = true
|
||||
raise = append(raise, e)
|
||||
}
|
||||
o.mu.Unlock()
|
||||
for _, e := range raise {
|
||||
key := unsaidKey(e.id)
|
||||
if have[key] {
|
||||
continue
|
||||
}
|
||||
summary := fmt.Sprintf("%s %s has been owed since %s and the bus does not take it", e.event, e.id, e.firstOwed.Format(time.RFC3339))
|
||||
f := assign.Observed{Scope: mcc.ScopeDelivery, ID: unsaidID(e.id), Kind: kindEventUnsaid, Severity: mcseat.FindingSeverityWarning,
|
||||
Summary: summary, Headline: "An event of the delivery is not said",
|
||||
Explanation: summary + ". The assigner says it again on its own pace; assigner_owed lists what is owed, assigner_owed_say says one now and assigner_owed_drop drops one the bus will never take.",
|
||||
Needs: "Nothing, unless the bus keeps refusing it.", Source: "assigner." + kindEventUnsaid}
|
||||
if err := p.findings.Put(f.Finding(now)); err != nil {
|
||||
p.logf("the finding %s is not written: %v", key, err)
|
||||
}
|
||||
}
|
||||
var gone []string
|
||||
for key := range have {
|
||||
if strings.HasPrefix(key, mcc.ScopeDelivery+".") && strings.HasSuffix(key, "."+kindEventUnsaid) && !owed[key] {
|
||||
gone = append(gone, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(gone)
|
||||
for _, key := range gone {
|
||||
if err := p.findings.Delete(key); err != nil {
|
||||
p.logf("the finding %s is not cleared: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// owedVerbs are the process's handlers of the seat mesh-wants' verbs owed, owed-say and owed-drop; record writes the hand act of a
|
||||
// drop in the log first.
|
||||
func owedVerbs(p *passer, record func(meshhandactsclient.Request) error) map[string]process.SeatHandler {
|
||||
return map[string]process.SeatHandler{
|
||||
meshwants.VerbOwed: func(string, json.RawMessage) (any, error) {
|
||||
return meshwants.OwedAnswer{Events: p.owedAll()}, nil
|
||||
},
|
||||
meshwants.VerbOwedSay: func(_ string, raw json.RawMessage) (any, error) {
|
||||
var in meshwants.OwedSayInput
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
return nil, fmt.Errorf("the arguments are not JSON: %w", err)
|
||||
}
|
||||
e, err := p.owedSay(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meshwants.OwedSayAnswer{Event: e}, nil
|
||||
},
|
||||
meshwants.VerbOwedDrop: func(caller string, raw json.RawMessage) (any, error) {
|
||||
var in meshwants.OwedDropInput
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
return nil, fmt.Errorf("the arguments are not JSON: %w", err)
|
||||
}
|
||||
if in.ID == "" || strings.TrimSpace(in.Why) == "" {
|
||||
return nil, errors.New("name the owed event's id and why it is dropped")
|
||||
}
|
||||
if err := record(meshhandactsclient.Request{What: owedDropTool + " " + in.ID, Why: in.Why + " (" + caller + ")", Cause: "owed-event-drop"}); err != nil {
|
||||
return nil, fmt.Errorf("the hand act is not recorded, so nothing is dropped: %w", err)
|
||||
}
|
||||
dropped, err := p.owedDrop(in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meshwants.OwedDropAnswer{Dropped: dropped}, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// owedTools are the module's tools of the owed events, each calling its verb of the seat mesh-wants; with the program stopped each
|
||||
// says the verb is unanswered.
|
||||
func owedTools(ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
|
||||
call := func(verb string, in any) (any, error) {
|
||||
raw, err := ask("seat:"+meshwants.Seat+"."+verb, in)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the assigner's program does not answer the verb %s of the seat %s (it is stopped or starting): %w", verb, meshwants.Seat, err)
|
||||
}
|
||||
var out any
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("%s answered what is not JSON: %w", verb, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
return []stdio.Tool{
|
||||
{Name: owedTool, Description: "The events the assigner says on the seat mesh-wants that the bus refused or did not acknowledge, owed in order and said " +
|
||||
"again under the same id (design 47 H2b §832): each with its id, when it was first owed, how many times it was said again and when it is said next; past " +
|
||||
"event-unsaid-after each is the finding event-unsaid. Read-only.",
|
||||
Input: schema(map[string]string{}, nil),
|
||||
Run: func(map[string]any) (any, error) { return call(meshwants.VerbOwed, meshwants.OwedInput{}) }},
|
||||
{Name: owedSayTool, Description: "Say the first owed event of an id's order now (design 47 H2b §832 6.), its delay set back to say-again-pace-first; answers the event said, " +
|
||||
"or the bus's refusal, the event staying owed.",
|
||||
Input: schema(map[string]string{"id": "an owed event's message id, as assigner_owed lists it"}, []string{"id"}),
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return call(meshwants.VerbOwedSay, meshwants.OwedSayInput{ID: arg(a, "id")})
|
||||
}},
|
||||
{Name: owedDropTool, Description: "Drop an owed event the bus will never take, with every event owed behind it in its order (design 47 H2b §832 6.), doing for each what " +
|
||||
"the bus taking it would have done: a tier-late writes tier-late-said, a running deletes the progress key, a wait-ended does the rest of the wait's end, a removal " +
|
||||
"deletes its mark; then its finding is cleared. Written in the hand-act log first.",
|
||||
Input: schema(map[string]string{"id": "an owed event's message id", "why": "why it is dropped"}, []string{"id", "why"}),
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return call(meshwants.VerbOwedDrop, meshwants.OwedDropInput{ID: arg(a, "id"), Why: arg(a, "why")})
|
||||
}},
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"maps"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
"reflect"
|
||||
"slices"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mmac "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
|
||||
mma "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
||||
@@ -29,6 +31,7 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
|
||||
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
@@ -58,8 +61,6 @@ type passer struct {
|
||||
whys map[string]string
|
||||
// findings is the assigner's findings bucket (its said conditions, ADR 0564 §2).
|
||||
findings assign.Findings
|
||||
// unplaced are the nodes whose unplaced finding this process wrote.
|
||||
unplaced map[string]bool
|
||||
// listed says whether a module's watched branches list it (catalogViews.listed), for the clear of assignment-unlisted.
|
||||
listed func(module string) bool
|
||||
// answeredAt is, by the id of a backup ask, how many values the have had when its answer was written into the want.
|
||||
@@ -79,6 +80,8 @@ type passer struct {
|
||||
// nodeFailed is, by node and module, the words of the condition last raised for a failure that is the node's own (ADR 0557
|
||||
// §1, issue 1496): raised once per words, cleared once when it ends.
|
||||
nodeFailed map[string]string
|
||||
// startSaid says the start's saying again was made (startsays.go).
|
||||
startSaid, startWaitsSaid bool
|
||||
// callsCleared says the first pass cleared the conditions of refused controller calls a previous process raised
|
||||
// (clearStaleCalls): the assigner makes no such call now (issue 774).
|
||||
callsCleared bool
|
||||
@@ -97,6 +100,9 @@ type passer struct {
|
||||
// saidWaits is the last said of the seat's wait for its states (sayWaits).
|
||||
saidWaits string
|
||||
intended map[string]map[string]map[string]bool
|
||||
// assignmentLeftSaid is, by assignment key, the why last said that the clean state leaves a retired module's key (H-A-509),
|
||||
// so each is said once per why.
|
||||
assignmentLeftSaid map[string]string
|
||||
// laidHere are the proposals whose candidates this process wrote (design 47 G A-317), by id.
|
||||
laidHere map[string]bool
|
||||
// reads is the assigner's state engine-reads, what each node's engine said it reads (enginewords.go, design 47 H-A-104);
|
||||
@@ -111,11 +117,25 @@ type passer struct {
|
||||
// entries are the catalog entries by fingerprint asked of the seat mesh-catalog's verb `entry` (design 47 G §614, A-217): a
|
||||
// held revert's running entry and its want's (revert.go); nil: no revert is asked about.
|
||||
entries *meshcatalogclient.Entries
|
||||
// tierBound is the setting tier-bound (design 47 H §751; zero: its default), and tierTimer the one timer that wakes the pass at
|
||||
// the earliest tier's deadline (tiers.go), made with tierWake; nil tierWake sets no timer.
|
||||
// tierBound is the setting tier-bound (design 47 H §751; zero: its default). wake makes a pass; wakes are the times the one
|
||||
// timer wakes it at, armed at the earliest (owed.go, H-A-846), made with after (nil: time.AfterFunc; a test's seam); nil wake
|
||||
// sets no timer.
|
||||
tierBound time.Duration
|
||||
tierWake func()
|
||||
tierTimer *time.Timer
|
||||
wake func()
|
||||
wakes wakes
|
||||
after func(time.Duration, func()) func() bool
|
||||
// tierHolds are, by pipeline, what holds its tier progress at its tier, read by the last pass (tiers.go, why.go).
|
||||
tierHolds map[string]tierHold
|
||||
// owed are the events of the seat mesh-wants the bus refused, owed in order and said again (owed.go, design 47 H §832).
|
||||
owed owedKept
|
||||
// putHeld is the put waits whose wait-held is owed and not yet taken, by put key: their record is written once it is taken, and
|
||||
// a put that ends meanwhile still owes its wait-ended behind it (design 47 H2b §832 1., 4.).
|
||||
putHeld putHeldOwed
|
||||
// passStall is the setting pass-stall-seconds (passstall.go; zero: its default): a pass still running after it says which phase
|
||||
// it is in (design 47 H2 H-A-635).
|
||||
passStall time.Duration
|
||||
// stallAfter arms a bound of the pass's watch in the place of a timer, returning what disarms it; nil: a timer (a test's seam).
|
||||
stallAfter func(time.Duration, func()) func()
|
||||
}
|
||||
|
||||
// wantsSay says one event of the seat mesh-wants; with no bus to say it on, nothing is said.
|
||||
@@ -146,16 +166,36 @@ func (p *passer) clock() time.Time {
|
||||
|
||||
func (p *passer) pass(ctx context.Context) {
|
||||
start := time.Now()
|
||||
defer func() { p.logf("the pass took %s", time.Since(start).Round(time.Millisecond)) }() // design 47 H-A-259
|
||||
watch := p.watchPass(start) // a pass past pass-stall-seconds says which phase it is in (design 47 H2 H-A-635)
|
||||
defer func() {
|
||||
watch.end()
|
||||
p.wakeSet("owed", p.owedNext())
|
||||
p.logf("the pass took %s", time.Since(start).Round(time.Millisecond)) // design 47 H-A-259
|
||||
}()
|
||||
if p.outside != nil {
|
||||
p.outside.beginPass(p.clock)
|
||||
}
|
||||
p.sayOwed()
|
||||
p.owedFindings() // an event owed for event-unsaid-after is raised, one no longer owed is cleared (§832 6.)
|
||||
watch.in(phaseAssignmentsSeat)
|
||||
p.assignmentsSeat(ctx)
|
||||
if held := p.keepGraph(ctx); held == "" {
|
||||
watch.in(phaseKeptGraph)
|
||||
held := p.keepGraph(ctx)
|
||||
p.startSays(ctx)
|
||||
if held == "" {
|
||||
watch.in(phaseWants)
|
||||
p.wants(ctx)
|
||||
watch.in(phasePassSaid)
|
||||
p.sayPass(ctx, "judged")
|
||||
} else {
|
||||
watch.in(phasePassSaid)
|
||||
p.sayPass(ctx, held) // a full store keeps the last revision (design 47 G §181); none kept yet writes no want (H-A-261)
|
||||
}
|
||||
watch.in(phasePuts)
|
||||
p.puts(ctx)
|
||||
watch.in(phaseNodeWants)
|
||||
p.nodeWants(ctx)
|
||||
watch.in(phaseBackups)
|
||||
p.backups(ctx, p.reverts(ctx))
|
||||
}
|
||||
|
||||
@@ -222,6 +262,7 @@ func (p *passer) wants(ctx context.Context) {
|
||||
puts := p.putsByModule()
|
||||
builds := placementBuilds(p.w.assignments())
|
||||
p.staleAsks(ctx, trunk)
|
||||
p.retiredAssignments(ctx, trunk)
|
||||
names := map[string]bool{}
|
||||
for name := range trunk {
|
||||
names[name] = true
|
||||
@@ -229,6 +270,7 @@ func (p *passer) wants(ctx context.Context) {
|
||||
for name := range wanted {
|
||||
names[name] = true
|
||||
}
|
||||
unversioned := map[string]unversionedWant{}
|
||||
for name := range names {
|
||||
groups := p.groups(name, nodesOf[name], assignedBranches[name])
|
||||
for gi, g := range groups {
|
||||
@@ -241,6 +283,10 @@ func (p *passer) wants(ctx context.Context) {
|
||||
ReadsVersion: func(node string) bool {
|
||||
return slices.Contains(nodes.Reads[node], nodeengine.ManifestReadWordWantVersion)
|
||||
},
|
||||
// H-A-682 (2), H-A-698: a want's needs are those of its entry, the node's missing ones the want held for.
|
||||
MissingNeeds: func(node, fp string) ([]string, bool) {
|
||||
return p.missingNeeds(ctx, bv.trunk[name], nodes.Reads[node], fp)
|
||||
},
|
||||
// H §750, H-A-5, H-A-99: a placement's build is read before the rule and names the want's version.
|
||||
Target: func(node string) (assign.Target, bool) {
|
||||
if build := builds[node][name]; build != "" {
|
||||
@@ -256,7 +302,14 @@ func (p *passer) wants(ctx context.Context) {
|
||||
p.outsideReview(ctx, name, target.Fp, m.Nodes, bv.nodes, bv.manifests[name].ClaimsSeat(mcseat.Seat), p.movedTo(wanted, bv.nodes))
|
||||
}
|
||||
out := assign.Wants(m, wantedOf)
|
||||
p.sayWhy(ctx, name, m.Nodes, wantWhy{Branch: g.branch, Fp: target.Fp, Version: target.Version, Pipeline: target.Pipeline, Step: whyStep(ok)}, wantedOf, &out)
|
||||
for node, fp := range out.Unversioned {
|
||||
unversioned[assign.UnversionedKey(name, node)] = unversionedWant{module: name, node: node, fp: fp}
|
||||
}
|
||||
why := wantWhy{Branch: g.branch, Fp: target.Fp, Version: target.Version, Pipeline: target.Pipeline, Step: whyStep(ok)}
|
||||
if !ok {
|
||||
why, _ = p.heldByTier(name, g.branch, why)
|
||||
}
|
||||
p.sayWhy(ctx, name, m.Nodes, why, wantedOf, &out)
|
||||
if ok {
|
||||
p.yeses(ctx, name, m, wantedOf, &out)
|
||||
}
|
||||
@@ -265,6 +318,31 @@ func (p *passer) wants(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
p.unversionedFindings(unversioned, trunk)
|
||||
}
|
||||
|
||||
// missingNeeds reads what a want at fp lacks of its node's words (design 47 H2 H-A-682 (2), H-A-698): the needs of the entry at fp,
|
||||
// those of the module's held entry when it names fp, else the seat `mesh-catalog`'s `entry` for it, asked once and kept; read is
|
||||
// false while that ask stands out, is not found or is unanswered, and the answer wakes a pass. The pass never waits on it.
|
||||
func (p *passer) missingNeeds(ctx context.Context, held meshcatalog.ModulesByModuleValue, words []string, fp string) (missing []string, read bool) {
|
||||
needs := held.Needs
|
||||
if held.Fp2 != fp {
|
||||
if p.entries == nil {
|
||||
return nil, true
|
||||
}
|
||||
e, state := p.entries.Need(ctx, fp)
|
||||
if state != meshcatalogclient.EntryAnswered {
|
||||
return nil, false
|
||||
}
|
||||
needs = e.Needs
|
||||
}
|
||||
for _, need := range needs {
|
||||
if !slices.Contains(words, need) {
|
||||
missing = append(missing, need)
|
||||
}
|
||||
}
|
||||
slices.Sort(missing)
|
||||
return slices.Compact(missing), true
|
||||
}
|
||||
|
||||
// put writes one key of the assigner's own bucket; a write that fails is said and made again at the next pass.
|
||||
@@ -307,20 +385,34 @@ func (p *passer) putWant(ctx context.Context, node, module string, want mwc.Want
|
||||
fp = before.Fp
|
||||
}
|
||||
}
|
||||
// The want-revision `wanted` says is the revision of the want's key it says; for a removal, of the write it removes (§832 3.).
|
||||
removes := p.w.metaOf(buckets.Wants(), key).revision
|
||||
// A removal is written before it is said (§832 4., H-A-843): its mark, the fingerprint and the want-revision of the write it
|
||||
// removes, is kept in the state `written` before the removing want is written, and goes once the bus has taken the event.
|
||||
var taken func()
|
||||
if want.Removed && removes != 0 && p.ends != nil {
|
||||
if !p.markRemoval(node, module, fp, removes) {
|
||||
return
|
||||
}
|
||||
taken = func() { p.dropRemovalMark(node, module) }
|
||||
}
|
||||
if p.wantWritten(ctx, node, module, key, want) {
|
||||
p.sayWanted(node, module, fp, want.Pipeline, want.Removed)
|
||||
revision := removes
|
||||
if !want.Removed {
|
||||
revision = p.w.metaOf(buckets.Wants(), key).revision
|
||||
}
|
||||
p.sayWanted(node, module, fp, want.Pipeline, want.Removed, revision, time.Time{}, taken)
|
||||
}
|
||||
}
|
||||
|
||||
// runOf is the run a want carries (design 47 H2 §813 (1); H-A-355 (1), H-A-416): the source revision of the pipeline that
|
||||
// released it, `<branch>.<source>`, in decimal; for a want of no pipeline (a put, a placement's build, a removal) the newest
|
||||
// source the assigner holds for it: the trunk's source of its kept assignment graph revision, or the run of the want written
|
||||
// (held) when that is newer, so a person's put or placement after a delivery is never refused as older; "" when it holds none.
|
||||
// runOf is the run a want carries (design 47 H2 §813 (1); H-A-355 (1), H-A-504 corrected and its addendum): the sequence of
|
||||
// the pipeline that released it, as its pipeline-ended said it, set on the want by the want rule; for a want of no pipeline (a
|
||||
// put, a placement's build, a removal) the newest source the assigner holds for it: the trunk's source of its kept assignment
|
||||
// graph revision, or the run of the want written (held) when that is newer, so a person's put or placement after a delivery is
|
||||
// never refused as older; "" when it holds none.
|
||||
func (p *passer) runOf(want mwc.Want, held *mwc.Want) string {
|
||||
if i := strings.LastIndexByte(want.Pipeline, '.'); i >= 0 {
|
||||
if n, err := strconv.ParseInt(want.Pipeline[i+1:], 10, 64); err == nil && n > 0 {
|
||||
return strconv.FormatInt(n, 10)
|
||||
}
|
||||
if want.Run != "" {
|
||||
return want.Run
|
||||
}
|
||||
var newest int64
|
||||
if p.graph != nil {
|
||||
@@ -343,12 +435,16 @@ func runNumber(run string) int64 {
|
||||
return n
|
||||
}
|
||||
|
||||
// wantWritten writes the want of module on node under key by compare-and-set, carrying its run (design 47 H2 §813 (1)): a want
|
||||
// that differs from the one written only by its run is not written again (its run stays, so a node never composes again for
|
||||
// it), and one whose run is lower than the run written is refused, said in the journal. It answers whether it wrote.
|
||||
// wantWritten writes the want of module on node under key, carrying its run as information (design 47 H2 §813 (1), H-A-504
|
||||
// third addendum): the order is the bus's own, a compare-and-set on the key's revision this pass read, so a stale pass loses to
|
||||
// the newer write, said once in the journal, and the next pass judges the key again from what it then reads. The run is the
|
||||
// pipeline's sequence for the why and the tools, never a gate. A want that differs from the one written only by its run is
|
||||
// not written again (its run stays, so a node never composes again for it). It answers whether it wrote.
|
||||
func (p *passer) wantWritten(ctx context.Context, node, module, key string, want mwc.Want) bool {
|
||||
raw := p.w.value(buckets.Wants(), key)
|
||||
read := p.w.metaOf(buckets.Wants(), key).revision
|
||||
var held *mwc.Want
|
||||
if raw := p.w.value(buckets.Wants(), key); raw != nil {
|
||||
if raw != nil {
|
||||
if h, err := mwc.DecodeWant(raw); err == nil {
|
||||
held = &h
|
||||
}
|
||||
@@ -359,9 +455,6 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
|
||||
same.Run = want.Run
|
||||
if reflect.DeepEqual(same, want) {
|
||||
want.Run = held.Run // it stands: nothing is written
|
||||
} else if runNumber(held.Run) > runNumber(want.Run) {
|
||||
p.logf("the want of %s on %s is not written: its run %q is lower than the run %q written (§813 (1))", module, node, want.Run, held.Run)
|
||||
return false
|
||||
}
|
||||
}
|
||||
value, err := mwc.EncodeWant(want)
|
||||
@@ -369,20 +462,19 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
|
||||
p.logf("%s %s is not written: %v", buckets.Wants(), key, err)
|
||||
return false
|
||||
}
|
||||
if held := p.w.value(buckets.Wants(), key); held != nil && bytes.Equal(held, value) {
|
||||
if raw != nil && bytes.Equal(raw, value) {
|
||||
return false
|
||||
}
|
||||
kv := p.kvs[buckets.Wants()]
|
||||
entry, err := kv.Get(ctx, key)
|
||||
switch {
|
||||
case errors.Is(err, jetstream.ErrKeyNotFound):
|
||||
_, err = kv.Create(ctx, key, value)
|
||||
case err == nil:
|
||||
if h, derr := mwc.DecodeWant(entry.Value()); derr == nil && runNumber(h.Run) > runNumber(want.Run) {
|
||||
p.logf("the want of %s on %s is not written: its run %q is lower than the run %q written (§813 (1))", module, node, want.Run, h.Run)
|
||||
return false
|
||||
}
|
||||
_, err = kv.Update(ctx, key, value, entry.Revision())
|
||||
var revision uint64
|
||||
if raw == nil {
|
||||
revision, err = kv.Create(ctx, key, value)
|
||||
} else {
|
||||
revision, err = kv.Update(ctx, key, value, read)
|
||||
}
|
||||
if errors.Is(err, jetstream.ErrKeyExists) || errors.Is(err, jetstream.ErrKeyRevisionMismatch) || (err != nil && isWrongSequence(err)) {
|
||||
p.logf("the want of %s on %s (run %q) is not written: its key moved past revision %d this pass read, and the newer write stands (§813 (1), H-A-504 third addendum); the next pass judges it again", module, node, want.Run, read)
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
@@ -390,7 +482,7 @@ func (p *passer) wantWritten(ctx context.Context, node, module, key string, want
|
||||
}
|
||||
return false
|
||||
}
|
||||
p.w.put(buckets.Wants(), key, value)
|
||||
p.w.putEntry(buckets.Wants(), key, value, revision, p.clock())
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -529,6 +621,42 @@ func (p *passer) staleAsks(ctx context.Context, trunk map[string]meshcatalog.Mod
|
||||
}
|
||||
}
|
||||
|
||||
// retiredAssignments is the clean state of the assignments at the pass (design 47 H2 H-A-509 and its second addendum): each
|
||||
// module key `<node>.<module>` of a module no manifest the trunk holds names, that the node key does not name, is deleted and
|
||||
// named in the journal, whether its value reads or not; one the node key still names is left, said once per why. Nothing goes
|
||||
// while the trunk is empty, or with no assignments bucket open.
|
||||
func (p *passer) retiredAssignments(ctx context.Context, trunk map[string]meshcatalog.ModulesByModuleValue) {
|
||||
if len(trunk) == 0 || p.kvs[plc.AssignmentsBucket()] == nil {
|
||||
return
|
||||
}
|
||||
names := make(map[string]bool, len(trunk))
|
||||
for name := range trunk {
|
||||
names[name] = true
|
||||
}
|
||||
held := p.w.read(plc.AssignmentsBucket())
|
||||
for _, key := range slices.Sorted(maps.Keys(held)) {
|
||||
node, module, kind, err := mmac.ParseKey(key)
|
||||
if err != nil || kind != mmac.ModuleKind || names[module] {
|
||||
continue
|
||||
}
|
||||
nodeKey, _ := mmac.NodeKey(node)
|
||||
nodeRaw, nodeFound := held[nodeKey]
|
||||
if left := assignmentLeft(node, module, names, nodeRaw, nodeFound); left != "" {
|
||||
if p.assignmentLeftSaid[key] != left {
|
||||
if p.assignmentLeftSaid == nil {
|
||||
p.assignmentLeftSaid = map[string]string{}
|
||||
}
|
||||
p.assignmentLeftSaid[key] = left
|
||||
p.logf("the assignment key %s is of a module no manifest of the trunk names, and is left: %s", key, left)
|
||||
}
|
||||
continue
|
||||
}
|
||||
delete(p.assignmentLeftSaid, key)
|
||||
p.logf("the assignment key %s is of a module no manifest of the trunk names, and is dropped", key)
|
||||
p.remove(ctx, plc.AssignmentsBucket(), key)
|
||||
}
|
||||
}
|
||||
|
||||
// remove deletes one key of the assigner's own bucket when it holds it; a delete that fails is said and made again at the next
|
||||
// pass.
|
||||
func (p *passer) remove(ctx context.Context, bucket, key string) {
|
||||
@@ -709,17 +837,37 @@ func chosenOf(chosen map[string]catalogue.PersonPolicy, module string) *catalogu
|
||||
return nil
|
||||
}
|
||||
|
||||
// findingKeys is the keys the assigner's findings bucket holds now; false when it cannot be read (no bucket, or a read that
|
||||
// failed, said), so that nothing is written or cleared from what was not read (H-A-722: a finding is cleared from what the bucket
|
||||
// holds, never from what a process remembers).
|
||||
func (p *passer) findingKeys(what string) (map[string]bool, bool) {
|
||||
if p.findings.Keys == nil || p.findings.Put == nil || p.findings.Delete == nil {
|
||||
return nil, false
|
||||
}
|
||||
ks, err := p.findings.Keys()
|
||||
if err != nil {
|
||||
p.logf("the findings are not read, so %s is not written or cleared in this pass: %v", what, err)
|
||||
return nil, false
|
||||
}
|
||||
have := make(map[string]bool, len(ks))
|
||||
for _, k := range ks {
|
||||
have[k] = true
|
||||
}
|
||||
return have, true
|
||||
}
|
||||
|
||||
// unplacedFindings writes, from the lease write, the finding `machine.<node>.unplaced` for each node that runs but no
|
||||
// assignments names, which gets no want (ADR 0571 §6), and deletes it once the node is placed.
|
||||
// assignments names, which gets no want (ADR 0571 §6), and deletes it at the pass that finds the node placed or gone: the
|
||||
// findings' keys are read from the bucket at each pass (H-A-722).
|
||||
func (p *passer) unplacedFindings() {
|
||||
if p.findings.Put == nil {
|
||||
have, ok := p.findingKeys("the finding unplaced")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
now := []string(p.w.unplacedNodes())
|
||||
is := map[string]bool{}
|
||||
for _, node := range now {
|
||||
for _, node := range p.w.unplacedNodes() {
|
||||
is[node] = true
|
||||
if p.unplaced[node] {
|
||||
if have[assign.UnplacedKey(node)] {
|
||||
continue
|
||||
}
|
||||
f, err := assign.UnplacedFinding(node, p.clock())
|
||||
@@ -728,23 +876,71 @@ func (p *passer) unplacedFindings() {
|
||||
}
|
||||
if err != nil {
|
||||
p.logf("the unplaced node %s is not said: %v", node, err)
|
||||
continue
|
||||
}
|
||||
if p.unplaced == nil {
|
||||
p.unplaced = map[string]bool{}
|
||||
}
|
||||
p.unplaced[node] = true
|
||||
}
|
||||
for node := range p.unplaced {
|
||||
if is[node] {
|
||||
for key := range have {
|
||||
node, found := unplacedOfKey(key)
|
||||
if !found || is[node] {
|
||||
continue
|
||||
}
|
||||
if err := p.findings.Delete(assign.UnplacedKey(node)); err == nil {
|
||||
delete(p.unplaced, node)
|
||||
if err := p.findings.Delete(key); err != nil {
|
||||
p.logf("the finding %s is not cleared: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unplacedOfKey is the node of an unplaced finding's key `machine.<node>.unplaced`, or false for another finding's.
|
||||
func unplacedOfKey(key string) (string, bool) {
|
||||
rest, ok := strings.CutPrefix(key, mcc.ScopeMachine+".")
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
node, ok := strings.CutSuffix(rest, "."+assign.KindUnplaced)
|
||||
return node, ok && node != "" && assign.UnplacedKey(node) == key
|
||||
}
|
||||
|
||||
// unversionedWant is a want of no version for which no target is held, as a pass finds it (design 47 H2 H-A-673, H-A-706).
|
||||
type unversionedWant struct{ module, node, fp string }
|
||||
|
||||
// unversionedFindings writes the finding want-unversioned (id `<module>.<node>`) of each want a pass found with no version and no
|
||||
// target, naming its fingerprint and why no target is held, and clears, at the pass that finds its cause gone, each one the
|
||||
// bucket holds that the pass did not find: the want names a version, the module is no longer assigned to the node, or the node
|
||||
// is gone (H-A-722). Nothing is cleared while the trunk is unread.
|
||||
func (p *passer) unversionedFindings(found map[string]unversionedWant, trunk map[string]meshcatalog.ModulesByModuleValue) {
|
||||
have, ok := p.findingKeys("the finding want-unversioned")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for key, u := range found {
|
||||
if have[key] {
|
||||
continue
|
||||
}
|
||||
f, err := assign.UnversionedFinding(u.module, u.node, u.fp, "no version of it released on its branch has a passed pipeline whose tier is written, and no placement names a build", p.clock())
|
||||
if err == nil {
|
||||
err = p.findings.Put(f)
|
||||
}
|
||||
if err != nil {
|
||||
p.logf("the finding want-unversioned of %s on %s is not written: %v", u.module, u.node, err)
|
||||
}
|
||||
}
|
||||
if len(trunk) == 0 {
|
||||
return
|
||||
}
|
||||
for key := range have {
|
||||
if _, _, is := assign.UnversionedOfKey(key); !is {
|
||||
continue
|
||||
}
|
||||
if _, still := found[key]; still {
|
||||
continue
|
||||
}
|
||||
if err := p.findings.Delete(key); err != nil {
|
||||
p.logf("the finding %s is not cleared: %v", key, err)
|
||||
continue
|
||||
}
|
||||
p.logf("the finding %s is cleared: its want names a version, or its module or its node is gone", key)
|
||||
}
|
||||
}
|
||||
|
||||
// clearUnlisted clears, in the pass over the assignments, each finding assignment-unlisted whose assignment is gone or whose module
|
||||
// one of its watched branches lists again, so the clear never waits for the next composition step on that machine (H-A-149).
|
||||
func (p *passer) clearUnlisted() {
|
||||
|
||||
@@ -6,12 +6,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient/heard"
|
||||
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
"mesh-delivery-assigner/internal/puts"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -46,19 +49,39 @@ import (
|
||||
type memKV struct {
|
||||
jetstream.KeyValue
|
||||
values map[string][]byte
|
||||
puts int // how many puts reached the bucket
|
||||
puts int // how many puts reached the bucket
|
||||
revs map[string]uint64 // each key's revision, as the bus numbers its writes (a key set by hand has none: its length stands in)
|
||||
seq uint64
|
||||
}
|
||||
|
||||
// written gives key the bucket's next revision, as a write on the bus does.
|
||||
func (m *memKV) written(key string) uint64 {
|
||||
if m.revs == nil {
|
||||
m.revs = map[string]uint64{}
|
||||
}
|
||||
m.seq++
|
||||
m.revs[key] = m.seq
|
||||
return m.seq
|
||||
}
|
||||
|
||||
// revision is key's revision as the bucket holds it.
|
||||
func (m *memKV) revision(key string) uint64 {
|
||||
if r, ok := m.revs[key]; ok {
|
||||
return r
|
||||
}
|
||||
return uint64(len(m.values[key]))
|
||||
}
|
||||
|
||||
func (m *memKV) Put(_ context.Context, key string, value []byte) (uint64, error) {
|
||||
m.values[key] = value
|
||||
m.puts++
|
||||
return uint64(len(m.values)), nil
|
||||
return m.written(key), nil
|
||||
}
|
||||
|
||||
func (m *memKV) Create(_ context.Context, key string, value []byte, _ ...jetstream.KVCreateOpt) (uint64, error) {
|
||||
m.values[key] = value
|
||||
m.puts++ // a write that reaches the bucket (the wants' compare-and-set, design 47 H2 §813 (1))
|
||||
return uint64(len(m.values)), nil
|
||||
return m.written(key), nil
|
||||
}
|
||||
|
||||
func (m *memKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
|
||||
@@ -213,6 +236,26 @@ func TestAnAnswerCountsOnlyForTheAskingItAnswered(t *testing.T) {
|
||||
if _, err := readEngineReads(memStore{engineReadsState: &memKV{values: state}}, "g14"); err == nil {
|
||||
t.Error("assigner_engine_reads answers a node it holds no key of")
|
||||
}
|
||||
// Design 47 H2b §836 1., 4. (review r1, part 1 finding 7): a Start that answers nil with a durable not bound says nothing
|
||||
// is heard; what waits on live events is done by the hub's OnAllHeard, and the reads' finding stands while its pattern is
|
||||
// unheard and goes once the hub's list holds it no more.
|
||||
lives := 0
|
||||
readsLive(func() { lives++ }, t.Logf)()
|
||||
if lives != 1 {
|
||||
t.Errorf("OnAllHeard made the seat list live %d times, want 1", lives)
|
||||
}
|
||||
finds := map[string]bool{}
|
||||
unheard := readsUnheard(heard.Writer{Observer: "assigner", Logf: t.Logf,
|
||||
Put: func(key string, _ []byte) error { finds[key] = true; return nil },
|
||||
Delete: func(key string) error { delete(finds, key); return nil }}, t.Logf)
|
||||
unheard([]process.Unheard{{Pattern: enginereads.SubjectPrefix + "*", Stream: process.EventsStream, Why: "not composed"}})
|
||||
if len(finds) != 1 {
|
||||
t.Errorf("the reads' pattern unheard wrote %v, want one finding", finds)
|
||||
}
|
||||
unheard([]process.Unheard{{Pattern: "mesh.seat.other.event.x", Stream: "SEAT_other_x", Why: "no stream carries it"}})
|
||||
if len(finds) != 0 {
|
||||
t.Errorf("a list without the reads' pattern left %v", finds)
|
||||
}
|
||||
// The event's node is its subject's last token, and what does not hold is no event.
|
||||
now := time.Now().Format(time.RFC3339Nano)
|
||||
for _, row := range []struct {
|
||||
@@ -247,15 +290,15 @@ func (m *memKV) Get(_ context.Context, key string) (jetstream.KeyValueEntry, err
|
||||
if !ok {
|
||||
return nil, jetstream.ErrKeyNotFound
|
||||
}
|
||||
return memEntry{value: v, revision: uint64(len(v))}, nil
|
||||
return memEntry{value: v, revision: m.revision(key)}, nil
|
||||
}
|
||||
func (m *memKV) Update(_ context.Context, key string, value []byte, revision uint64) (uint64, error) {
|
||||
if uint64(len(m.values[key])) != revision {
|
||||
return 0, errors.New("wrong last sequence")
|
||||
if m.revision(key) != revision {
|
||||
return 0, fmt.Errorf("wrong last sequence: %w", jetstream.ErrKeyRevisionMismatch)
|
||||
}
|
||||
m.values[key] = value
|
||||
m.puts++
|
||||
return uint64(len(value)), nil
|
||||
return m.written(key), nil
|
||||
}
|
||||
|
||||
// memStore is the runtime's states for the put's tools, over the same memKVs a pass writes.
|
||||
@@ -266,7 +309,7 @@ func (s memStore) get(state, key string) ([]byte, uint64, bool, error) {
|
||||
return nil, 0, false, nil
|
||||
}
|
||||
v, ok := s[state].values[key]
|
||||
return v, uint64(len(v)), ok, nil
|
||||
return v, s[state].revision(key), ok, nil
|
||||
}
|
||||
func (s memStore) put(state, key string, value []byte) error {
|
||||
s[state].values[key] = value
|
||||
@@ -297,6 +340,9 @@ func (b *fakeBus) CallOn(node, key string, body any) (json.RawMessage, error) {
|
||||
return b.Call(node+"/"+key, body)
|
||||
}
|
||||
func (b *fakeBus) CallKept(key string, body any) (json.RawMessage, error) { return b.Call(key, body) }
|
||||
func (b *fakeBus) CallKeptAsk(_ process.KeptAsk, key string, body any) (json.RawMessage, error) {
|
||||
return b.Call(key, body)
|
||||
}
|
||||
func (b *fakeBus) CallFile(key string, body any) (json.RawMessage, error) { return b.Call(key, body) }
|
||||
func (b *fakeBus) CallFileKept(_ process.KeptAsk, key string, body any) (json.RawMessage, error) {
|
||||
return b.Call(key, body)
|
||||
@@ -419,7 +465,8 @@ func putOfTheBus(t *testing.T) {
|
||||
before, _ := nodeengineclient.EncodeHave(nodeengine.HaveByNodeModuleValue{Fp: meshcatalogclient.SourcePrefix2 + strings.Repeat("a", 64), Phase: nodeengineclient.PhaseRunning, Health: nodeengineclient.HealthOK})
|
||||
world(buckets.Have, hkey, before)
|
||||
|
||||
// Issue 1966: newest is asked of the indexer's first view of modules, never read from its bus state.
|
||||
// The tool asks nobody for newest (design 47 H2b §833): the program resolves it. The indexer's view is asked only for the
|
||||
// older-than-newest of the puts listed (issue 1966).
|
||||
indexer := &fakeIndexer{views: map[string]map[string][]byte{"mesh-delivery-indexer.modules": {"mesh-catalog": mod, "nats": mod}}}
|
||||
s := newPutTools(memStore{putsState: putsKV}, func(key string, body any) (json.RawMessage, error) {
|
||||
if raw, ok, err := indexer.answer(key, body); ok {
|
||||
@@ -431,19 +478,19 @@ func putOfTheBus(t *testing.T) {
|
||||
was := answerWithin
|
||||
answerWithin = 0
|
||||
defer func() { answerWithin = was }()
|
||||
if _, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": "fd497ab8ffff", "why": "x"}, "shanks.node-tools"); err == nil {
|
||||
t.Error("a prefix of a fingerprint was taken: a put names the whole fingerprint (A-181)")
|
||||
// Design 47 H2b §833, §834: the tool reads nothing; it takes newest, a whole fingerprint, or its first 12 hex digits as asked.
|
||||
prefix := meshcatalogclient.SourcePrefix2 + "fd497ab80000"
|
||||
for _, ok := range []string{"newest", fp, prefix, strings.ToUpper(prefix)} {
|
||||
if _, err := s.version("nats", ok); err != nil {
|
||||
t.Errorf("%q is a version: %v", ok, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.version("nats", "fd497ab80000"); err == nil {
|
||||
t.Error("the prefix of the fingerprint built was read: a put names the whole fingerprint (A-181)")
|
||||
for _, bad := range []string{"fd497ab80000", meshcatalogclient.SourcePrefix2 + "fd497ab800", "main", ""} {
|
||||
if _, err := s.version("nats", bad); err == nil {
|
||||
t.Errorf("%q was taken as a version", bad)
|
||||
}
|
||||
}
|
||||
if got, err := s.version("nats", "newest"); err != nil || got != fp || indexer.asks["mesh-delivery-indexer.modules"] != 2 {
|
||||
t.Errorf("newest reads %q, %v, asking %d pages of the indexer's first view (want its 2)", got, err, indexer.asks["mesh-delivery-indexer.modules"])
|
||||
}
|
||||
if _, err := s.version("ghost", "newest"); err == nil || !strings.Contains(err.Error(), "holds no module ghost") {
|
||||
t.Errorf("newest of a module the indexer does not hold: %v", err)
|
||||
}
|
||||
ans, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": fp, "hold": "true", "why": "the bus's user list"}, "shanks.node-tools")
|
||||
ans, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": prefix, "hold": "true", "why": "the bus's user list"}, "shanks.node-tools")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -461,8 +508,8 @@ func putOfTheBus(t *testing.T) {
|
||||
}
|
||||
return got
|
||||
}
|
||||
if got := step(); got.Step != puts.Compose || !strings.Contains(got.Words, "no composition") {
|
||||
t.Fatalf("the first pass left the put at %s: %s", got.Step, got.Words)
|
||||
if got := step(); got.Step != puts.Compose || !strings.Contains(got.Words, "no composition") || got.FP != fp {
|
||||
t.Fatalf("the first pass left the put at %s (%s) at %q: it resolves the prefix to the whole fingerprint %s", got.Step, got.Words, got.FP, fp)
|
||||
}
|
||||
select {
|
||||
case call := <-bus.calls:
|
||||
@@ -569,6 +616,45 @@ func putOfTheBus(t *testing.T) {
|
||||
if string(wantsKV.values["want.novox.nats"]) != string(oldWant) {
|
||||
t.Errorf("a want was written for a put released meanwhile: %s", wantsKV.values["want.novox.nats"])
|
||||
}
|
||||
// §833, H-A-862: newest is the end kept for the node's branch, whatever newer build the trunk has; none kept is refused
|
||||
// naming the branch and the words of the tool's description. §834: a prefix two builds share is refused naming both.
|
||||
trunkNewer := meshcatalogclient.SourcePrefix2 + strings.Repeat("9", 64)
|
||||
// AC-833: the trunk's newest build of nats, which passed no pipeline, is placed in the world beside the end kept below.
|
||||
newer, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: trunkNewer, Repository: "novox/mesh-catalog", Commit: strings.Repeat("d", 40)})
|
||||
putModuleRaw(p.w, trunkBranch, "nats", newer)
|
||||
newerBuilt, _ := json.Marshal(builds.BuildEnded{Module: "nats", Fingerprint: trunkNewer, Outcome: builds.BuildDone})
|
||||
if p.w.ends.put(newerBuilt) != nil {
|
||||
t.Fatal("the newer build is not heard")
|
||||
}
|
||||
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
|
||||
p.ends.trunk = p.w.trunkName
|
||||
if _, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": "newest", "why": "the newest that passed"}, "shanks.node-tools"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := step(); got.Step != puts.Refused || !strings.Contains(got.Words, "no version of nats passed a pipeline: name a fingerprint, or read assigner_written") || !strings.Contains(got.Words, trunkBranch) {
|
||||
t.Fatalf("newest with no end kept stands at %s: %s", got.Step, got.Words)
|
||||
}
|
||||
end, _ := json.Marshal(End{Pipeline: "main.7", Source: 7, Seq: 1, Fp: fp, Version: "2.10.1", Rank: 1})
|
||||
p.ends.st.(*memEnds).vals[endKey("nats", trunkBranch)] = end
|
||||
p.w.put(buckets.Puts(), pkey, putsKV.values[pkey])
|
||||
if _, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": "newest", "why": "again"}, "shanks.node-tools"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := step(); got.FP != fp || got.FP == trunkNewer || !strings.Contains(got.Steps[0].Words+got.Steps[1].Words, "which newest resolves to") {
|
||||
t.Fatalf("newest with an end kept at %s stands at %s at %q: %s (the trunk's %s passed no pipeline)", fp, got.Step, got.FP, got.Words, trunkNewer)
|
||||
}
|
||||
for _, other := range []string{"1", "2"} {
|
||||
two, _ := json.Marshal(builds.BuildEnded{Module: "nats", Fingerprint: fp[:len(fp)-1] + other, Outcome: builds.BuildDone})
|
||||
if p.w.ends.put(two) != nil {
|
||||
t.Fatal("a build is not heard")
|
||||
}
|
||||
}
|
||||
if _, err := s.doPut(map[string]any{"node": "novox", "module": "nats", "version": meshcatalogclient.SourcePrefix2 + "fd497ab80000", "why": "shared prefix"}, "shanks.node-tools"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := step(); got.Step != puts.Refused || strings.Count(got.Words, "fd497ab80000") < 3 {
|
||||
t.Fatalf("a prefix three builds share stands at %s: %s", got.Step, got.Words)
|
||||
}
|
||||
}
|
||||
|
||||
// 1906 note 28: an ask outlives its fingerprint. Each pass takes away the hold, restore and record asks of a module whose
|
||||
@@ -745,12 +831,12 @@ func aPlacedNodesWantsNameTheBuildAloneAndItsYesComesFromItsHave(t *testing.T) {
|
||||
wkey, _ := mwc.WantKey("g14", "web")
|
||||
want, _ := mwc.EncodeWant(mwc.Want{Fp: fpOld, Version: "0.1.1", Pipeline: trunkBranch + ".1", Rank: 1})
|
||||
wantsKV.values[wkey] = want
|
||||
put(buckets.Wants(), wkey, want)
|
||||
sync := func() {
|
||||
sync := func() { // as the watch hands the wants, with their revisions
|
||||
for k, v := range wantsKV.values {
|
||||
put(buckets.Wants(), k, v)
|
||||
p.w.putEntry(buckets.Wants(), k, v, wantsKV.revision(k), time.Now())
|
||||
}
|
||||
}
|
||||
sync()
|
||||
|
||||
p.wants(context.Background())
|
||||
p.nodeWants(context.Background())
|
||||
@@ -1018,3 +1104,87 @@ func TestAnActingPartsNewVersionHoldsNoWant(t *testing.T) {
|
||||
t.Errorf("an acting part's version held the want: kept %v, said %v", waits.values, said)
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-682 (2), H-A-698 (1), (2): the needs of a want are those of the module's held entry when it names the fingerprint, else those
|
||||
// the seat `mesh-catalog`'s `entry` answers; the pass never waits on that ask, the entry is not read while it is out, not found or
|
||||
// unanswered, and the answer wakes a pass.
|
||||
func TestAWantsNeedsAreReadFromItsEntryAndNeverWaitedFor(t *testing.T) {
|
||||
const held, older, gone, lost = "src2:held", "src2:older", "src2:gone", "src2:lost"
|
||||
words := []string{"want:version", "approval-mark/1"}
|
||||
answered := make(chan struct{}, 8)
|
||||
p := &passer{}
|
||||
p.entries = meshcatalogclient.NewEntries(func(_ string, body any) (json.RawMessage, error) {
|
||||
switch fp := body.(meshcatalog.EntryInput).Fingerprint; fp {
|
||||
case gone:
|
||||
return nil, &busretry.Answered{Words: "no entry"}
|
||||
case lost:
|
||||
return nil, errors.New("no responders")
|
||||
default:
|
||||
return json.Marshal(meshcatalog.EntryAnswer{Entry: meshcatalog.CatalogEntry{Module: "m", Fp: fp, Needs: []string{"directory-contents-owner", "approval-mark/1"}}})
|
||||
}
|
||||
})
|
||||
p.entries.Changed = func(meshcatalogclient.EntryRow) { answered <- struct{}{} }
|
||||
value := meshcatalog.ModulesByModuleValue{Fp2: held, Needs: []string{"want:version", "zeta", "approval-mark/1"}}
|
||||
ctx := context.Background()
|
||||
for _, c := range []struct {
|
||||
fp string
|
||||
missing []string
|
||||
read bool
|
||||
asked bool
|
||||
}{
|
||||
{held, []string{"zeta"}, true, false},
|
||||
{older, nil, false, true}, // asked: not read yet
|
||||
{older, []string{"directory-contents-owner"}, true, false}, // answered, and kept
|
||||
{gone, nil, false, true},
|
||||
{lost, nil, false, false}, // out and failed in transport: asked again at the next revision, its answer awaited by no pass
|
||||
} {
|
||||
missing, read := p.missingNeeds(ctx, value, words, c.fp)
|
||||
if !slices.Equal(missing, c.missing) || read != c.read {
|
||||
t.Errorf("%s: missing %v read %v, want %v %v", c.fp, missing, read, c.missing, c.read)
|
||||
}
|
||||
if c.asked {
|
||||
select {
|
||||
case <-answered:
|
||||
case <-time.After(10 * time.Second): // a bound on a failure only
|
||||
t.Fatalf("%s: the ask is never answered", c.fp)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, read := p.missingNeeds(ctx, value, words, gone); read {
|
||||
t.Error("an entry not found is read")
|
||||
}
|
||||
// Design 47 H §872 (1984/AC-872b): a need `word:<path>` of a word the take-in set aside (the indexer's, in the form of the manifest
|
||||
// reads) holds the want on a machine whose node-engine's words lack it, and lets it be written on one whose words hold it.
|
||||
const need = "word:build.artifacts.race"
|
||||
racing := meshcatalog.ModulesByModuleValue{Fp2: held, Needs: []string{"want:version", need}}
|
||||
if missing, read := p.missingNeeds(ctx, racing, words, held); !read || !slices.Equal(missing, []string{need}) {
|
||||
t.Errorf("AC-872b: a node-engine whose words lack %s: missing %v (read %v), want the want held for it", need, missing, read)
|
||||
}
|
||||
if missing, read := p.missingNeeds(ctx, racing, append([]string{need}, words...), held); !read || len(missing) != 0 {
|
||||
t.Errorf("AC-872b: a node-engine whose words hold %s: missing %v (read %v), want the want written", need, missing, read)
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-698 (2): the why of a want held awaiting its entry names the ask: its state, how often it was asked again and its last failure.
|
||||
func TestTheWhyOfAWantAwaitingItsEntryNamesTheAsk(t *testing.T) {
|
||||
const fp = "src2:lost"
|
||||
kv := &memKV{values: map[string][]byte{}}
|
||||
p := &passer{kvs: map[string]jetstream.KeyValue{writtenBucket(): kv}}
|
||||
p.entries = meshcatalogclient.NewEntries(func(string, any) (json.RawMessage, error) { return nil, errors.New("no responders") })
|
||||
p.entries.Need(context.Background(), fp)
|
||||
deadline := time.Now().Add(10 * time.Second) // a bound on a failure only
|
||||
for len(p.entries.Rows()) == 0 || p.entries.Rows()[0].Detail == "" {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the ask never failed")
|
||||
}
|
||||
runtime.Gosched() // the ask runs on its own goroutine
|
||||
}
|
||||
held := mwc.Want{Fp: fp, Hold: true, Words: mwc.HoldAwaitsEntryPrefix + fp}
|
||||
p.sayWhy(context.Background(), "m", []string{"ace"}, wantWhy{Branch: "main", Fp: fp, Step: whyPassed}, nil, &assign.Outcome{Wants: map[string]mwc.Want{"ace": held}})
|
||||
raw, ok := kv.values[whyKey("ace", "m")]
|
||||
var got wantWhy
|
||||
if !ok || json.Unmarshal(raw, &got) != nil || got.Entry == nil || got.Entry.Fingerprint != fp || got.Entry.State != meshcatalogclient.EntryAsked ||
|
||||
!strings.Contains(got.Entry.Detail, "no responders") {
|
||||
t.Errorf("the why = %s, want the ask of %s named with its state and last failure", raw, fp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The phases of a pass, each named as it starts so a pass that stands still can say where (design 47 H2 H-A-635).
|
||||
const (
|
||||
phaseAssignmentsSeat = "the assignments seat"
|
||||
phaseKeptGraph = "the kept graph"
|
||||
phaseWants = "the wants"
|
||||
phasePassSaid = "the pass said"
|
||||
phasePuts = "the puts"
|
||||
phaseNodeWants = "the node wants"
|
||||
phaseBackups = "the backups and reverts"
|
||||
)
|
||||
|
||||
// defaultPassStall is the setting pass-stall-seconds' default, 60 seconds (design 47 H2 H-A-635).
|
||||
const defaultPassStall = 60 * time.Second
|
||||
|
||||
// passStallUnit is the unit of the setting pass-stall-seconds, a second; the whole test sets a shorter one, so a pass passes its
|
||||
// bound without a test waiting seconds (as tierBoundUnit).
|
||||
var passStallUnit = time.Second
|
||||
|
||||
// passStallSetting is the setting pass-stall-seconds, read at the start from the file the manifest declares with the content
|
||||
// ${config:pass-stall-seconds}; zero, its default, for a file missing or empty (design 47 H2 H-A-635, principle 11).
|
||||
func passStallSetting(getenv func(string) string) (time.Duration, error) {
|
||||
seconds, err := settingFile(getenv("MESH_ASSIGNER_PASS_STALL_FILE"))
|
||||
return time.Duration(seconds) * passStallUnit, err
|
||||
}
|
||||
|
||||
// passStallOf is the setting pass-stall-seconds; zero or less is its default.
|
||||
func (p *passer) passStallOf() time.Duration {
|
||||
if p.passStall > 0 {
|
||||
return p.passStall
|
||||
}
|
||||
return defaultPassStall
|
||||
}
|
||||
|
||||
// passWatch is what one running pass keeps of where it stands, in the passer's own memory: its start, the phase it is in and
|
||||
// since when. A pass still running at the bound says in the journal which phase it is in, and again at each further bound until
|
||||
// it ends; nothing is said for a pass that ends within the bound, and the end line stays as it was (design 47 H2 H-A-635 on
|
||||
// H-A-259; principle 3, a part that waits says where; principle 7, a journal line, no new key or event).
|
||||
type passWatch struct {
|
||||
logf func(string, ...any)
|
||||
after func(time.Duration, func()) func()
|
||||
bound time.Duration
|
||||
start time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
phase string
|
||||
since time.Time
|
||||
stop func()
|
||||
ended bool
|
||||
}
|
||||
|
||||
// watchPass starts the watch of the pass that began at start; stallAfter, when set, arms the bound in the place of a timer.
|
||||
func (p *passer) watchPass(start time.Time) *passWatch {
|
||||
w := &passWatch{logf: p.logf, after: p.stallAfter, bound: p.passStallOf(), start: start, since: start}
|
||||
if w.after == nil {
|
||||
w.after = func(d time.Duration, f func()) func() {
|
||||
t := time.AfterFunc(d, f)
|
||||
return func() { t.Stop() }
|
||||
}
|
||||
}
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.stop = w.after(w.bound, w.say)
|
||||
return w
|
||||
}
|
||||
|
||||
// in says the pass is in phase now.
|
||||
func (w *passWatch) in(phase string) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.phase, w.since = phase, time.Now()
|
||||
}
|
||||
|
||||
// say is one bound passed with the pass still running: the journal line, and the next bound armed. The line is said under the
|
||||
// watch's lock, so none is said after the pass's end has returned.
|
||||
func (w *passWatch) say() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.ended {
|
||||
return
|
||||
}
|
||||
w.stop = w.after(w.bound, w.say)
|
||||
w.logf("the pass started at %s is in %s for %s", w.start.Format(time.RFC3339), w.phase, time.Since(w.since).Round(time.Millisecond))
|
||||
}
|
||||
|
||||
// end is the pass's end: the bound is disarmed and no further line is said.
|
||||
func (w *passWatch) end() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.ended = true
|
||||
w.stop()
|
||||
}
|
||||
@@ -44,8 +44,11 @@ const pipelineEndedSubject = "mesh.seat." + mpr.Seat + ".event." + mpr.EventPipe
|
||||
type End struct {
|
||||
Pipeline string `json:"pipeline"`
|
||||
Source int64 `json:"source"`
|
||||
Fp string `json:"fp"`
|
||||
Version string `json:"version"`
|
||||
// Seq is the pipeline's sequence its pipeline-ended said, written as the run of its wants (design 47 H2 §813 (1), H-A-504
|
||||
// addendum).
|
||||
Seq int64 `json:"seq,omitempty"`
|
||||
Fp string `json:"fp"`
|
||||
Version string `json:"version"`
|
||||
// Rank is the mover's tier in the pipeline's delivery order, from 1 (§746, §750).
|
||||
Rank int64 `json:"rank"`
|
||||
}
|
||||
@@ -141,6 +144,8 @@ type pipelineEnds struct {
|
||||
// firsts is, by module, the first watched branch of its registration, the branch of a placement that names none (design
|
||||
// 47 G §14).
|
||||
firsts map[string]string
|
||||
// noSeq is, by module and pipeline, the ends kept without a sequence already said (H-A-504 second addendum).
|
||||
noSeq map[string]bool
|
||||
// runEnded is told a run on request's pipeline-ended, its group `run-<id>`, to drop the run's candidate (A-235, H-A-58); nil
|
||||
// drops nothing.
|
||||
runEnded func(group string) error
|
||||
@@ -178,11 +183,18 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
|
||||
e.logf("the pipeline-ended of %s is refused, and none of its movers' versions is kept: %v", p.Pipeline, err)
|
||||
return false, nil
|
||||
}
|
||||
// Its sequence is its wants' run (design 47 H2 §813 (1), H-A-504 addendum): an end without one, of an older runner, is
|
||||
// refused loudly and writes no want.
|
||||
if p.Seq <= 0 {
|
||||
e.logf("the pipeline-ended of %s is refused, and none of its movers' versions is kept: it carries no seq, the run its "+
|
||||
"wants would carry (a runner older than H-A-504's addendum); the runner's end-again of %s, once it says seq, keeps them", p.Pipeline, p.Pipeline)
|
||||
return false, nil
|
||||
}
|
||||
changed := false
|
||||
var kept []tierMover
|
||||
versioned := map[string]bool{}
|
||||
defer func() {
|
||||
if err := e.startTiers(p.Pipeline, p.Source, kept, versioned); err != nil {
|
||||
if err := e.startTiers(p.Pipeline, p.Source, p.Seq, kept, versioned); err != nil {
|
||||
e.logf("the tier progress of %s is not written: %v", p.Pipeline, err)
|
||||
}
|
||||
}()
|
||||
@@ -198,6 +210,13 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
|
||||
m.Version = v
|
||||
}
|
||||
}
|
||||
if v, ok := e.releasedAt(m.Module, m.Fingerprint); m.Version != "" && ok && v != m.Version {
|
||||
// A version released from another build is no version of this mover (design 47 H2b §835 2.): it is not kept, the mover
|
||||
// is held `no-version` for the pass to find the version released at its own fingerprint (§826 1.).
|
||||
e.logf("%s: %s at %s names version %s, released from another build; the version released at its own fingerprint is %s: taken at the next pass",
|
||||
p.Pipeline, m.Module, m.Fingerprint, m.Version, v)
|
||||
m.Version = ""
|
||||
}
|
||||
if m.Version == "" {
|
||||
// The runner writes a mover's version at its release's version-released, and says this end again once it does
|
||||
// (H-A-270 (1), (2)): the skip is said, never silent.
|
||||
@@ -207,35 +226,95 @@ func (e *pipelineEnds) take(p mpr.PipelineEnded) (bool, error) {
|
||||
continue
|
||||
}
|
||||
versioned[m.Module] = true
|
||||
key := endKey(m.Module, p.Branch)
|
||||
for {
|
||||
raw, rev, err := e.st.get(key)
|
||||
if err != nil {
|
||||
return changed, err
|
||||
}
|
||||
if raw != nil {
|
||||
var kept End
|
||||
if err := json.Unmarshal(raw, &kept); err == nil && compareVersion(m.Version, kept.Version) <= 0 {
|
||||
break // an older version, or this one again
|
||||
}
|
||||
}
|
||||
value, err := json.Marshal(End{Pipeline: p.Pipeline, Source: p.Source, Fp: m.Fingerprint, Version: m.Version, Rank: max(m.Tier, 1)})
|
||||
if err != nil {
|
||||
return changed, err
|
||||
}
|
||||
if err := e.st.swap(key, value, rev); errors.Is(err, errSwapped) {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return changed, err
|
||||
}
|
||||
did, err := e.keepEnd(p.Pipeline, p.Branch, p.Source, p.Seq, m.Module, m.Fingerprint, m.Version, max(m.Tier, 1))
|
||||
if err != nil {
|
||||
return changed, err
|
||||
}
|
||||
if did {
|
||||
changed = true
|
||||
kept = append(kept, tierMover{Module: m.Module, Fp: m.Fingerprint, Tier: max(m.Tier, 1)})
|
||||
break
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// releasedAt is releasedOf, false when no lookup is set.
|
||||
func (e *pipelineEnds) releasedAt(module, fp string) (string, bool) {
|
||||
if e.releasedOf == nil {
|
||||
return "", false
|
||||
}
|
||||
return e.releasedOf(module, fp)
|
||||
}
|
||||
|
||||
// keepEnd keeps the end of a passed mover, version and all, as the newest of its module on branch, by compare-and-set: an older
|
||||
// version, or the same one again, writes nothing, the same one from another pipeline whose want was never written excepted
|
||||
// (design 47 H2b §825 2.). It says whether the key changed. The pipeline's end (take) and a pass that finds a `no-version`
|
||||
// mover's version released (§826 1.) keep it so.
|
||||
func (e *pipelineEnds) keepEnd(pipeline, branch string, source, seq int64, module, fp, version string, rank int64) (bool, error) {
|
||||
key := endKey(module, branch)
|
||||
for {
|
||||
raw, rev, err := e.st.get(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if raw != nil {
|
||||
var kept End
|
||||
if err := json.Unmarshal(raw, &kept); err == nil {
|
||||
c := compareVersion(version, kept.Version)
|
||||
if c < 0 || (c == 0 && !e.stranded(kept, pipeline, fp)) {
|
||||
return false, nil // an older version, or this one again
|
||||
}
|
||||
if c == 0 {
|
||||
e.logf("%s: %s at %s is kept again from %s: the want of %s, whose progress is at tier %d of %d, was never written",
|
||||
pipeline, module, version, pipeline, kept.Pipeline, e.tierOf(kept.Pipeline), kept.Rank)
|
||||
}
|
||||
}
|
||||
}
|
||||
value, err := json.Marshal(End{Pipeline: pipeline, Source: source, Seq: seq, Fp: fp, Version: version, Rank: rank})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := e.st.swap(key, value, rev); errors.Is(err, errSwapped) {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// stranded says the end kept at the same fingerprint and version, from another pipeline, never had its want written: that
|
||||
// pipeline's progress still stands below the end's rank (design 47 H2b §825 2.). The pipeline now ended carries the mover again.
|
||||
func (e *pipelineEnds) stranded(kept End, pipeline, fp string) bool {
|
||||
if kept.Pipeline == "" || kept.Pipeline == pipeline || kept.Fp != fp {
|
||||
return false
|
||||
}
|
||||
t, _, ok := e.tiersOf(kept.Pipeline)
|
||||
return ok && t.Tier < kept.Rank
|
||||
}
|
||||
|
||||
// tierOf is the tier a pipeline's progress stands at, 0 when it has none.
|
||||
func (e *pipelineEnds) tierOf(pipeline string) int64 {
|
||||
t, _, _ := e.tiersOf(pipeline)
|
||||
return t.Tier
|
||||
}
|
||||
|
||||
// noSeqOnce says, once per module and pipeline, that the end kept for module from pipeline carries no sequence and writes
|
||||
// no want, naming the recovery (H-A-504 second addendum).
|
||||
func (e *pipelineEnds) noSeqOnce(module, pipeline string) {
|
||||
e.mu.Lock()
|
||||
if e.noSeq == nil {
|
||||
e.noSeq = map[string]bool{}
|
||||
}
|
||||
said := e.noSeq[module+" "+pipeline]
|
||||
e.noSeq[module+" "+pipeline] = true
|
||||
e.mu.Unlock()
|
||||
if !said && e.logf != nil {
|
||||
e.logf("no want of %s is written: its end kept from %s carries no seq, the run its want would carry (kept before "+
|
||||
"H-A-504's addendum); the runner's end-again of %s, or %s's next pipeline, writes it", module, pipeline, pipeline, module)
|
||||
}
|
||||
}
|
||||
|
||||
// endOf is the end kept for module on branch: the newest version released there whose pipeline passed.
|
||||
func (e *pipelineEnds) endOf(module, branch string) (End, bool) {
|
||||
if e == nil {
|
||||
@@ -257,7 +336,13 @@ func (e *pipelineEnds) target(module, branch string) (assign.Target, bool) {
|
||||
if !ok || !e.tierWritten(end) {
|
||||
return assign.Target{}, false
|
||||
}
|
||||
return assign.Target{Fp: end.Fp, Version: end.Version, Pipeline: end.Pipeline, Rank: end.Rank}, true
|
||||
if end.Seq <= 0 {
|
||||
// An end kept before pipeline-ended carried its sequence has no run for its wants (design 47 H2 §813 (1), H-A-504
|
||||
// second addendum): it writes no want, said once.
|
||||
e.noSeqOnce(module, end.Pipeline)
|
||||
return assign.Target{}, false
|
||||
}
|
||||
return assign.Target{Fp: end.Fp, Version: end.Version, Pipeline: end.Pipeline, Rank: end.Rank, Seq: end.Seq}, true
|
||||
}
|
||||
|
||||
// hearPipeline takes a pipeline-ended: a passed one's released versions are kept (take), and a run on request's drops the
|
||||
@@ -326,7 +411,7 @@ func (e *pipelineEnds) branchOf(module, placed string) string {
|
||||
|
||||
// writtenTools is the tool assigner_written: every key of the state written, with its end.
|
||||
func writtenTools(st store) []stdio.Tool {
|
||||
return []stdio.Tool{{Name: writtenTool, Description: "the pipeline ends the assigner's wants follow: per module and watched branch, the newest version released whose pipeline passed, with its pipeline and rank; per pipeline whose wants are written tier by tier, its tier progress (tier, since, movers); with why, why each want is what it is (as assigner_why).",
|
||||
return []stdio.Tool{{Name: writtenTool, Description: "the pipeline ends the assigner's wants follow: per module and watched branch, the newest version released whose pipeline passed, with its pipeline and rank; per pipeline whose wants are written tier by tier, its tier progress (tier, since, movers, and clock-from and paused-from: the time tier-bound counts from, and when a pause of the count by an ask of the operator began; tier-late-at, the time any tier was first found past tier-bound, and tier-late-said, the time the bus took pipeline-wanted tier-late: a key with the first and not the second holds a tier-late still to be said); per removal written and not yet said (removal.<node>.<module>), its mark: node, module, the fingerprint and the want-revision of the write it removes; with why, why each want is what it is (as assigner_why).",
|
||||
Input: schema(map[string]string{"why": "true: why each want is what it is", "module": "with why: a module's name", "node": "with why: a node's name"}, nil, "why"),
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
if args["why"] == true || args["why"] == "true" {
|
||||
@@ -353,6 +438,13 @@ func writtenTools(st store) []stdio.Tool {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(k, removalPrefix) { // a removal written and not said, its mark (startsays.go)
|
||||
var m removalMark
|
||||
if json.Unmarshal(raw, &m) == nil {
|
||||
out[k] = m
|
||||
}
|
||||
continue
|
||||
}
|
||||
var e End
|
||||
if json.Unmarshal(raw, &e) == nil {
|
||||
out[k] = e
|
||||
@@ -383,7 +475,7 @@ func (e *pipelineEnds) registered(reg mpcat.Registration, gone bool) {
|
||||
prefix := keys.EscapeName(reg.Module) + "."
|
||||
for _, k := range kept {
|
||||
rest, ok := strings.CutPrefix(k, prefix)
|
||||
if !ok || isTierKey(k) || strings.HasPrefix(k, whyPrefix) {
|
||||
if !ok || isTierKey(k) || strings.HasPrefix(k, whyPrefix) || strings.HasPrefix(k, removalPrefix) {
|
||||
continue
|
||||
}
|
||||
branch, err := keys.UnescapeName(rest)
|
||||
|
||||
@@ -68,9 +68,9 @@ func mover(module, fp, version string, tier int64, outcome string) mpr.MoverEnde
|
||||
Steps: []mpr.StepResult{{Step: "unit", Status: mpr.StepResultStatusRequired, Outcome: outcome, Module: module}}}
|
||||
}
|
||||
|
||||
// ended is the pipeline-ended of the take-in of source on branch, its movers given.
|
||||
// ended is the pipeline-ended of the take-in of source on branch, its movers given, its sequence 200 + source.
|
||||
func ended(branch string, source int64, outcome string, movers ...mpr.MoverEnded) mpr.PipelineEnded {
|
||||
return mpr.PipelineEnded{V: 1, Branch: branch, Source: source, EndCount: 1, Outcome: outcome, Movers: movers,
|
||||
return mpr.PipelineEnded{V: 1, Branch: branch, Source: source, Seq: 200 + source, EndCount: 1, Outcome: outcome, Movers: movers,
|
||||
Pipeline: fmt.Sprintf("%s.%d", branch, source)}
|
||||
}
|
||||
|
||||
@@ -86,28 +86,42 @@ func TestThePassedVersionIsKept(t *testing.T) {
|
||||
want *End // nil: none kept for web on main
|
||||
}{
|
||||
{"a passed pipeline keeps its version", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))},
|
||||
&End{Pipeline: "main.5", Source: 5, Fp: "fp1", Version: "0.1.2", Rank: 2}},
|
||||
&End{Pipeline: "main.5", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 2}},
|
||||
{"nothing to run counts as passed", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, nothing))},
|
||||
&End{Pipeline: "main.5", Source: 5, Fp: "fp1", Version: "0.1.2", Rank: 1}},
|
||||
&End{Pipeline: "main.5", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 1}},
|
||||
{"a failed pipeline keeps nothing, a passed mover in it neither", []mpr.PipelineEnded{ended("main", 5, fail, mover("web", "fp1", "0.1.2", 1, ok),
|
||||
mover("db", "fp9", "0.3.0", 1, failed))}, nil},
|
||||
{"a mover whose required step failed keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, failed))}, nil},
|
||||
{"no version released keeps nothing", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "", 1, ok))}, nil},
|
||||
{"an older end heard after a newer one keeps the newer", []mpr.PipelineEnded{ended("main", 6, pass, mover("web", "fp2", "0.1.3", 1, ok)),
|
||||
ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Fp: "fp2", Version: "0.1.3", Rank: 1}},
|
||||
ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Seq: 206, Fp: "fp2", Version: "0.1.3", Rank: 1}},
|
||||
{"a newer version replaces", []mpr.PipelineEnded{ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok)),
|
||||
ended("main", 6, pass, mover("web", "fp2", "0.1.10", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Fp: "fp2", Version: "0.1.10", Rank: 1}},
|
||||
ended("main", 6, pass, mover("web", "fp2", "0.1.10", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Seq: 206, Fp: "fp2", Version: "0.1.10", Rank: 1}},
|
||||
// Design 47 H2b §825: the same version again, from a later pipeline, is kept when the earlier pipeline's progress never
|
||||
// reached the mover's tier (its want was never written), and otherwise nothing is written.
|
||||
{"a later pipeline carrying a stranded mover at its kept version keeps it again", []mpr.PipelineEnded{
|
||||
ended("main", 5, pass, mover("db", "fp9", "0.3.0", 1, ok), mover("web", "fp1", "0.1.2", 2, ok)),
|
||||
ended("main", 6, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.6", Source: 6, Seq: 206, Fp: "fp1", Version: "0.1.2", Rank: 1}},
|
||||
{"one whose earlier pipeline's progress reached the tier writes nothing", []mpr.PipelineEnded{
|
||||
ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok)),
|
||||
ended("main", 6, pass, mover("web", "fp1", "0.1.2", 1, ok))}, &End{Pipeline: "main.5", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 1}},
|
||||
// H-A-485: an again pipeline's end is kept as a take-in's; a key of no form the runner's seat defines is refused, nothing kept.
|
||||
{"an again pipeline keeps its version", []mpr.PipelineEnded{func() mpr.PipelineEnded {
|
||||
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))
|
||||
p.Pipeline = "main.5.again.2"
|
||||
return p
|
||||
}()}, &End{Pipeline: "main.5.again.2", Source: 5, Fp: "fp1", Version: "0.1.2", Rank: 2}},
|
||||
}()}, &End{Pipeline: "main.5.again.2", Source: 5, Seq: 205, Fp: "fp1", Version: "0.1.2", Rank: 2}},
|
||||
{"a key of no form is refused", []mpr.PipelineEnded{func() mpr.PipelineEnded {
|
||||
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 2, ok))
|
||||
p.Pipeline = "main.5.later.2"
|
||||
return p
|
||||
}()}, nil},
|
||||
// H-A-504 addendum: an end without its sequence, of an older runner, is refused and keeps nothing.
|
||||
{"an end without seq keeps nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded {
|
||||
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))
|
||||
p.Seq = 0
|
||||
return p
|
||||
}()}, nil},
|
||||
{"a run on request keeps nothing", []mpr.PipelineEnded{func() mpr.PipelineEnded {
|
||||
p := ended("main", 5, pass, mover("web", "fp1", "0.1.2", 1, ok))
|
||||
p.Run = "r1"
|
||||
@@ -206,7 +220,7 @@ func TestAPassWritesTheWantOfThePassedVersion(t *testing.T) {
|
||||
if !passed {
|
||||
continue
|
||||
}
|
||||
if w, err := mwc.DecodeWant(raw); err != nil || w.Fp != fp || w.Version != "0.1.2" || w.Pipeline != trunkBranch+".5" || w.Rank != 2 {
|
||||
if w, err := mwc.DecodeWant(raw); err != nil || w.Fp != fp || w.Version != "0.1.2" || w.Pipeline != trunkBranch+".5" || w.Rank != 2 || w.Run != "205" {
|
||||
t.Errorf("%s: the want on %s = %+v (%v)", c.name, node, w, err)
|
||||
}
|
||||
}
|
||||
@@ -235,8 +249,25 @@ func TestARegistrationNamesTheDefaultBranch(t *testing.T) {
|
||||
if woken == 0 || endsKept() != 1 || e.branchOf("web", "") != "beta" || e.branchOf("other", "") != trunkBranch {
|
||||
t.Errorf("ends kept %d, default branch %q: an unwatched branch's end stayed, or the default is wrong", endsKept(), e.branchOf("web", ""))
|
||||
}
|
||||
if tg, ok := e.target("web", ""); !ok || tg.Fp != "fp2" {
|
||||
t.Errorf("the default branch's target = %+v %v", tg, ok)
|
||||
if tg, ok := e.target("web", ""); !ok || tg.Fp != "fp2" || tg.Seq != 205 {
|
||||
t.Errorf("the default branch's target = %+v %v, want fp2 at seq 205", tg, ok)
|
||||
}
|
||||
// H-A-504 second addendum: an end kept without a sequence (before pipeline-ended said it) writes no want, said once.
|
||||
raw, rev, _ := st.get(endKey("web", "beta"))
|
||||
var old End
|
||||
_ = json.Unmarshal(raw, &old)
|
||||
old.Seq = 0
|
||||
raw, _ = json.Marshal(old)
|
||||
_ = st.swap(endKey("web", "beta"), raw, rev)
|
||||
var said []string
|
||||
e.logf = func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }
|
||||
for range 2 {
|
||||
if tg, ok := e.target("web", ""); ok {
|
||||
t.Errorf("an end kept without seq is the target %+v", tg)
|
||||
}
|
||||
}
|
||||
if len(said) != 1 || !strings.Contains(said[0], "beta.5") || !strings.Contains(said[0], "end-again") {
|
||||
t.Errorf("an end kept without seq said %q, want once, naming the pipeline and end-again", said)
|
||||
}
|
||||
e.registered(mpcat.Registration{Module: "web"}, true)
|
||||
if endsKept() != 0 {
|
||||
|
||||
@@ -98,8 +98,8 @@ func newOrderFixture(t *testing.T, mods []orderMod, history ...map[string]string
|
||||
_, _ = p.ends.take(ended(trunkBranch, 1, mpr.PipelineEndedOutcomePassed, mover(m.name, m.trunk, "0.1.1", 1, mpr.StepResultOutcomePassed)))
|
||||
wkey, _ := mwc.WantKey("ace", m.name)
|
||||
old, _ := mwc.EncodeWant(mwc.Want{Fp: m.run, Self: true})
|
||||
p.w.put(buckets.Wants(), wkey, old)
|
||||
f.wants.values[wkey] = old
|
||||
p.w.putEntry(buckets.Wants(), wkey, old, f.wants.revision(wkey), time.Now()) // as the watch hands it, with its revision
|
||||
}
|
||||
composes(t, p.w, "ace", digest)
|
||||
values, err := mmac.AssignmentsValues(pl)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// progressDropTool drops one pipeline's tier progress by hand (design 47 H2b §824 7.): a key whose tier never runs (a version that
|
||||
// never comes) stands, said by `tier-late`, until a later pipeline carries its movers or a person drops it. The act is recorded in
|
||||
// the hand-act log first; the key is deleted, and the pass that finds its pipeline no longer followed clears its `tier-late`
|
||||
// from the findings bucket (H-A-722). Nothing is said on the seat `mesh-wants`: the gate's record ended failed at `tier-late`.
|
||||
const progressDropTool = "assigner_progress_drop"
|
||||
|
||||
// dropProgress deletes the tier progress of pipeline, the act first recorded through the seat mesh-hand-acts.
|
||||
func dropProgress(st seatStore, ask func(string, any) (json.RawMessage, error), pipeline, why, by string) (any, error) {
|
||||
switch {
|
||||
case pipeline == "":
|
||||
return nil, errors.New("name the pipeline whose tier progress is dropped")
|
||||
case !isTierKey(tierKey(pipeline)):
|
||||
return nil, fmt.Errorf("%q is no pipeline's key of a form the seat defines", pipeline)
|
||||
case why == "":
|
||||
return nil, errors.New("a tier progress dropped by hand says why")
|
||||
case by == "" || by == stdio.Unproven:
|
||||
return nil, errors.New("a tier progress dropped by hand names who drops it, and the runtime proved no caller")
|
||||
}
|
||||
key := tierKey(pipeline)
|
||||
raw, _, found, err := st.get(writtenState, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("the assigner holds no tier progress under %s: assigner_written lists them", key)
|
||||
}
|
||||
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: progressDropTool + " " + key, Why: why + " (" + by + ")", Cause: "tier-progress-drop"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the drop of %s is not recorded, so the progress stays: %w", key, err)
|
||||
}
|
||||
if err := st.del(writtenState, key); err != nil {
|
||||
return nil, fmt.Errorf("the tier progress %s is not dropped: %w", key, err)
|
||||
}
|
||||
return map[string]any{"key": key, "dropped": json.RawMessage(raw), "by": by, "hand-act": taken.Log}, nil
|
||||
}
|
||||
|
||||
// progressDropTools is the tool over the runtime's states.
|
||||
func progressDropTools(st seatStore, ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
|
||||
return []stdio.Tool{{Name: progressDropTool, Description: "Drop one pipeline's tier progress by hand (design 47 H2b §824 7.): the key pipeline.<pipeline> of the state written " +
|
||||
"is deleted, for a progress whose tier never runs (a version that never comes) and no later pipeline carries; the finding tier-late of that pipeline is cleared by the next pass, and nothing " +
|
||||
"is said on the seat mesh-wants. Recorded as a hand act first; refused with no progress under the key.",
|
||||
Input: schema(map[string]string{"pipeline": "the pipeline's key, <branch>.<revision> or its again form", "why": "why the progress is dropped"}, []string{"pipeline", "why"}),
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return dropProgress(st, ask, arg(a, "pipeline"), arg(a, "why"), stdio.CallerOf(a))
|
||||
}}}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ type caller interface {
|
||||
CallOn(node, key string, body any) (json.RawMessage, error)
|
||||
// CallKept is Call for a kept call, safe to call again (process.Conn.CallKept; ADR 0668).
|
||||
CallKept(key string, body any) (json.RawMessage, error)
|
||||
// CallKeptAsk is CallKept stopping at its caller's bound and carrying the ask's id and hook (process.Conn.CallKeptAsk; H2 §775).
|
||||
CallKeptAsk(ask process.KeptAsk, key string, body any) (json.RawMessage, error)
|
||||
// CallFile is Call of a verb marked chunks, its answer read whole (process.Conn.CallFile; design 47 G A-291).
|
||||
CallFile(key string, body any) (json.RawMessage, error)
|
||||
// CallFileKept is CallFile as a kept call carrying its ask's id, until its bound (process.Conn.CallFileKept; H2 §775).
|
||||
@@ -136,6 +138,12 @@ func (p *passer) puts(ctx context.Context) {
|
||||
world := p.putWorld(node, module, put, manifest, assigned[node])
|
||||
world.Snapshot, world.Snapshotting, world.SnapshotFailed = p.acts.state(id)
|
||||
next := assign.StepPut(world)
|
||||
if puts.Unresolved(put.FP) && puts.Whole(next.Put.FP) {
|
||||
// The first step resolved the version (H-A-848, H-A-862): the rest is read at the fingerprint it named.
|
||||
world = p.putWorld(node, module, next.Put, manifest, assigned[node])
|
||||
world.Snapshot, world.Snapshotting, world.SnapshotFailed = p.acts.state(id)
|
||||
next = assign.StepPut(world)
|
||||
}
|
||||
// The bus's want is written only for the act the operator's yes bound (ADR 0546 clause 8).
|
||||
if next.Put.Step == puts.Wanted && put.Step != puts.Wanted && world.Bus && next.Put.Ask != "" {
|
||||
if err := p.performs(next.Put.Ask, assign.PutAct(node, module, next.Put.FP, next.Put.Composed)); err != nil {
|
||||
@@ -181,6 +189,19 @@ func (p *passer) putWorld(node, module string, put puts.Put, manifest catalogue.
|
||||
if e, ok := p.w.ends.endOf(module, put.FP); ok { // the build's end heard (A-181): none heard, no state
|
||||
w.Build, w.BuildWords = e.Outcome, e.Error
|
||||
}
|
||||
if puts.Unresolved(put.FP) {
|
||||
for _, e := range p.w.ends.doneStarting(module, put.FP) {
|
||||
v, _ := p.w.releasedOf(module, e.Fingerprint)
|
||||
w.Matches = append(w.Matches, assign.PutMatch{FP: e.Fingerprint, Version: v})
|
||||
}
|
||||
w.Branch = p.w.trunkName()
|
||||
if p.ends.following() {
|
||||
w.Branch = p.ends.branchOf(module, p.w.placedBranches()[module][node])
|
||||
}
|
||||
if end, ok := p.ends.endOf(module, w.Branch); ok {
|
||||
w.BranchEnd = end.Fp
|
||||
}
|
||||
}
|
||||
w.Version, _ = p.w.releasedOf(module, put.FP) // matched by its build's parts, as the pass matches a mover's (H-A-490 addendum)
|
||||
w.Composed, w.Granted = p.composedFor(node, module, put.FP)
|
||||
if d := w.Composed; d != nil {
|
||||
@@ -276,7 +297,7 @@ func (p *passer) performs(key string, act occ.Act) error {
|
||||
|
||||
// samePut says two puts say the same: their step, words and what they found.
|
||||
func samePut(a, b puts.Put) bool {
|
||||
return a.Step == b.Step && a.Words == b.Words && a.Composed == b.Composed && a.Ask == b.Ask && a.Snapshot == b.Snapshot
|
||||
return a.FP == b.FP && a.Step == b.Step && a.Words == b.Words && a.Composed == b.Composed && a.Ask == b.Ask && a.Snapshot == b.Snapshot
|
||||
}
|
||||
|
||||
// writePut writes a put's next value over the one the pass read, by compare-and-set, unless the tool has put again or
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
@@ -48,6 +49,29 @@ type putWaiting struct {
|
||||
Put puts.Put `json:"put"`
|
||||
}
|
||||
|
||||
// putHeldOwed is the put waits whose wait-held is owed, by put key (in memory: a restart owes what the kept state implies).
|
||||
type putHeldOwed struct {
|
||||
mu sync.Mutex
|
||||
m map[string]putWaiting
|
||||
}
|
||||
|
||||
func (h *putHeldOwed) set(key string, w putWaiting) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.m == nil {
|
||||
h.m = map[string]putWaiting{}
|
||||
}
|
||||
h.m[key] = w
|
||||
}
|
||||
|
||||
func (h *putHeldOwed) drop(key, id string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.m[key].ID == id {
|
||||
delete(h.m, key)
|
||||
}
|
||||
}
|
||||
|
||||
// saidPutWaits is every put wait the state put-waits holds, by key; a value that does not decode is said and left.
|
||||
func (p *passer) saidPutWaits() map[string]putWaiting {
|
||||
out := map[string]putWaiting{}
|
||||
@@ -59,6 +83,13 @@ func (p *passer) saidPutWaits() map[string]putWaiting {
|
||||
}
|
||||
out[key] = w
|
||||
}
|
||||
p.putHeld.mu.Lock()
|
||||
for key, w := range p.putHeld.m {
|
||||
if _, kept := out[key]; !kept {
|
||||
out[key] = w // its wait-held is owed: its end is owed behind it
|
||||
}
|
||||
}
|
||||
p.putHeld.mu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -88,11 +119,11 @@ func (p *passer) putWaits(ctx context.Context, all map[string]map[string]puts.Pu
|
||||
}
|
||||
body := putWaitBody(node, module, was.Put)
|
||||
body.How = how
|
||||
if err := p.wantsSay(meshwants.EventWaitEnded, body, was.ID+".put."+how); err != nil {
|
||||
p.logf("the end of the put %s's wait is not said, and is said at the next pass: %v", key, err)
|
||||
continue
|
||||
}
|
||||
p.remove(ctx, buckets.PutWaits(), key)
|
||||
// The kept record stays until the bus has taken the end, so a restart says it again (§832 4.; H-A-830).
|
||||
p.wantsOwe(putWaitOrder(node, module), meshwants.EventWaitEnded, body, was.ID+".put."+how, func() {
|
||||
p.putHeld.drop(key, was.ID)
|
||||
p.remove(ctx, buckets.PutWaits(), key)
|
||||
})
|
||||
delete(waiting, key)
|
||||
}
|
||||
for module, byNode := range all {
|
||||
@@ -105,12 +136,17 @@ func (p *passer) putWaits(ctx context.Context, all map[string]map[string]puts.Pu
|
||||
if w, said := waiting[key]; said && w.ID == id {
|
||||
continue
|
||||
}
|
||||
if err := p.wantsSay(meshwants.EventWaitHeld, putWaitBody(node, module, put), id+".put"); err != nil {
|
||||
p.logf("the put %s's wait is not said, and is said at the next pass: %v", key, err)
|
||||
continue
|
||||
}
|
||||
kept := putWaiting{ID: id, Put: put}
|
||||
p.put(ctx, buckets.PutWaits(), key, func() ([]byte, error) { return json.Marshal(kept) })
|
||||
// The record is written once the bus has taken the wait-held, never while it is only owed: after a restart a record
|
||||
// that stands reads as said (§832 4., 1.; H-A-830).
|
||||
kept, done := putWaiting{ID: id, Put: put}, context.WithoutCancel(ctx)
|
||||
p.putHeld.set(key, kept)
|
||||
p.wantsOwe(putWaitOrder(node, module), meshwants.EventWaitHeld, putWaitBody(node, module, put), id+".put", func() {
|
||||
p.putHeld.drop(key, id)
|
||||
p.put(done, buckets.PutWaits(), key, func() ([]byte, error) { return json.Marshal(kept) })
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// putWaitOrder is the order the events of a put's wait are said in: its `<node>.<module>` (design 47 H §832 1.; H-A-830).
|
||||
func putWaitOrder(node, module string) string { return "put-wait." + node + "." + module }
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -89,4 +90,29 @@ func TestAPutWithoutHoldIsSaidAsAWait(t *testing.T) {
|
||||
if a := answerOf("ace", "web", held); !a.Since.Equal(at.Add(time.Minute)) || a.Bound != "" {
|
||||
t.Errorf("a held put answers since %v, bound %q", a.Since, a.Bound)
|
||||
}
|
||||
// Design 47 H §832 (H-A-830): the bus refuses the wait-held once, then the put ends; the end is owed behind the held, and the kept
|
||||
// record stays until the bus took the end. Both are said after, in that order, under main's ids.
|
||||
refused := true
|
||||
events, bodies = nil, nil
|
||||
var ids []string
|
||||
p.publishWants = func(event string, body any, id string) error {
|
||||
if refused {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
events, bodies, ids = append(events, event), append(bodies, body.(meshwants.Wait)), append(ids, id)
|
||||
return nil
|
||||
}
|
||||
fresh := puts.Put{FP: fpTest, Why: "a try again", At: at.Add(3 * time.Hour)}.Said(at.Add(3*time.Hour), puts.Wanted, "the want is written")
|
||||
p.putWaits(ctx, map[string]map[string]puts.Put{"db": {"g14": fresh}})
|
||||
p.putWaits(ctx, map[string]map[string]puts.Put{"db": {"g14": fresh.Said(at.Add(4*time.Hour), puts.Done, "runs")}})
|
||||
if len(events) != 0 || kept.values["g14.db"] != nil {
|
||||
t.Fatalf("a refused say was kept as said: %v, record %q (the record is written once the bus took the wait-held, review r1 finding 3)", events, kept.values["g14.db"])
|
||||
}
|
||||
refused = false
|
||||
p.after = nil
|
||||
p.owed.list[0].next = p.clock()
|
||||
if !p.sayOwed() || len(events) != 2 || events[0] != meshwants.EventWaitHeld || events[1] != meshwants.EventWaitEnded ||
|
||||
!strings.HasSuffix(ids[0], ".put") || !strings.HasSuffix(ids[1], ".put."+putWaitRan) || kept.values["g14.db"] != nil {
|
||||
t.Errorf("the owed said %v under %v, record %q", events, ids, kept.values["g14.db"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
@@ -287,17 +288,68 @@ func TestTheSeatsVerbs(t *testing.T) {
|
||||
findings := map[string][]byte{}
|
||||
p := &passer{w: w, logf: func(string, ...any) {}, findings: assign.Findings{
|
||||
Put: putInto(findings),
|
||||
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(findings)), nil },
|
||||
Delete: func(k string) error { delete(findings, k); return nil }}}
|
||||
p.unplacedFindings()
|
||||
if _, ok := findings[assign.UnplacedKey("g14")]; !ok || len(findings) != 1 {
|
||||
t.Fatalf("findings = %v", findings)
|
||||
}
|
||||
putAssignments(w, mma.Assignments{V: keys.Version, Node: "g14", Modules: []mma.PlacedModule{{Module: "web"}}})
|
||||
p.unplacedFindings()
|
||||
// A process that starts again knows nothing of what the first said: it clears the finding from the bucket (H-A-722).
|
||||
restarted := &passer{w: w, logf: func(string, ...any) {}, findings: p.findings}
|
||||
restarted.unplacedFindings()
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("placed again: findings %v", findings)
|
||||
}
|
||||
})
|
||||
t.Run("H-A-673, H-A-706, H-A-722: want-unversioned is written, and cleared from the bucket by a pass after a restart", func(t *testing.T) {
|
||||
fp := meshcatalogclient.SourcePrefix2 + strings.Repeat("3", 64)
|
||||
wantsKV := &memKV{values: map[string][]byte{}}
|
||||
findings := map[string][]byte{}
|
||||
pass := func(version string, assigned ...string) *passer {
|
||||
p := newPasser(kvSet{buckets.Wants(): wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, time.Now())
|
||||
p.publishWants = func(string, any, string) error { return nil }
|
||||
p.findings = assign.Findings{Put: putInto(findings), Keys: func() ([]string, error) { return slices.Collect(maps.Keys(findings)), nil },
|
||||
Delete: func(k string) error { delete(findings, k); return nil }}
|
||||
digest := strings.Repeat("4", 64)
|
||||
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: fp, Manifest: digest, Repository: "novox/web", Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
|
||||
putModuleRaw(p.w, trunkBranch, "web", mod)
|
||||
p.w.manifests[digest] = parsed{module: "web", manifest: catalogue.Manifest{Module: "web"}}
|
||||
if len(assigned) > 0 { // none: the node is gone, no assignments name it
|
||||
placeOn(t, p.w, "g14", assigned...)
|
||||
}
|
||||
raw, _ := mwc.EncodeWant(mwc.Want{Fp: fp, Version: version})
|
||||
key, _ := mwc.WantKey("g14", "web")
|
||||
wantsKV.values[key] = raw
|
||||
p.w.putEntry(buckets.Wants(), key, raw, 1, time.Now())
|
||||
return p
|
||||
}
|
||||
key := assign.UnversionedKey("web", "g14")
|
||||
pass("", "web").wants(context.Background())
|
||||
if _, ok := findings[key]; !ok || len(findings) != 1 {
|
||||
t.Fatalf("a want of no version and no target: findings %v", findings)
|
||||
}
|
||||
pass("", "web").wants(context.Background()) // a process that starts again: written once, and it stands
|
||||
if _, ok := findings[key]; !ok || len(findings) != 1 {
|
||||
t.Fatalf("a restarted pass changed the finding: %v", findings)
|
||||
}
|
||||
pass("1.0.0", "web").wants(context.Background()) // the want names a version now
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("the want names a version: findings %v", findings)
|
||||
}
|
||||
pass("", "web").wants(context.Background())
|
||||
pass("", "other").wants(context.Background()) // the module is no longer assigned to the node
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("the module is no longer assigned to the node: findings %v", findings)
|
||||
}
|
||||
if pass("", "web").wants(context.Background()); len(findings) != 1 {
|
||||
t.Fatalf("a want of no version again: findings %v", findings)
|
||||
}
|
||||
pass("").wants(context.Background()) // the node is gone: no assignments name it
|
||||
if len(findings) != 0 {
|
||||
t.Errorf("the node is gone: findings %v", findings)
|
||||
}
|
||||
})
|
||||
t.Run("1955/L7 (ADR 0571 §4): seat-holders is written from assignments, only the keys a change moves, and answered by assignments seats", func(t *testing.T) {
|
||||
writes := 0
|
||||
kv := &countingKV{memKV: memKV{values: map[string][]byte{}}, writes: &writes}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
"mesh-delivery-assigner/internal/outside"
|
||||
)
|
||||
|
||||
// A start says again what its kept state implies (design 47 H2b §832 4., H-A-843, H-A-859): what was owed in memory is gone after a
|
||||
// restart, so the first pass that has an assignment graph revision kept says again, under the same ids and in each order's order,
|
||||
// `wait-ended` for a record with `ending` (§831), `wait-held` for every standing wait under its `held-said`, and per node and module
|
||||
// the removal its mark holds, then `wanted` for the want written. `pipeline-wanted` `tier-late` and `running` are said again by the
|
||||
// tier progress's own pass (§824), which owes them whenever its keys say so.
|
||||
|
||||
// removalPrefix is the prefix of a removal's mark in the state `written`: `removal.<node>.<module>`.
|
||||
const removalPrefix = "removal."
|
||||
|
||||
// removalMark is a removal written before it is said: the fingerprint and the want-revision of the write it removes. A mark holds
|
||||
// the newest removal of its node and module, the one a consumer needs.
|
||||
type removalMark struct {
|
||||
Node string `json:"node"`
|
||||
Module string `json:"module"`
|
||||
Fp string `json:"fp"`
|
||||
WantRevision uint64 `json:"want-revision"`
|
||||
}
|
||||
|
||||
func removalKey(node, module string) string {
|
||||
return removalPrefix + keys.EscapeName(node) + "." + keys.EscapeName(module)
|
||||
}
|
||||
|
||||
// markRemoval keeps the mark of the removal of the want of module on node, which stands at revision, before the removing want is
|
||||
// written; false (said in the journal) when it could not be kept, so the removal is not made.
|
||||
func (p *passer) markRemoval(node, module, fp string, revision uint64) bool {
|
||||
raw, err := json.Marshal(removalMark{Node: node, Module: module, Fp: fp, WantRevision: revision})
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
key := removalKey(node, module)
|
||||
for range 2 {
|
||||
held, rev, err := p.ends.st.get(key)
|
||||
if err != nil {
|
||||
p.logf("the mark of the removal of %s on %s cannot be read, so the removal waits: %v", module, node, err)
|
||||
return false
|
||||
}
|
||||
if held != nil && string(held) == string(raw) {
|
||||
return true
|
||||
}
|
||||
switch err = p.ends.st.swap(key, raw, rev); err {
|
||||
case nil:
|
||||
return true
|
||||
case errSwapped:
|
||||
continue
|
||||
}
|
||||
p.logf("the mark of the removal of %s on %s is not written, so the removal waits: %v", module, node, err)
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// dropRemovalMark deletes the mark of a removal the bus has taken.
|
||||
func (p *passer) dropRemovalMark(node, module string) {
|
||||
if err := p.ends.st.drop(removalKey(node, module)); err != nil {
|
||||
p.logf("the mark of the removal of %s on %s is not deleted: %v", module, node, err)
|
||||
}
|
||||
}
|
||||
|
||||
// startSays is the start pass's saying again: the waits' events at the first pass, and the wants' at the first pass that keeps an
|
||||
// assignment graph revision, each once.
|
||||
func (p *passer) startSays(ctx context.Context) {
|
||||
if !p.startWaitsSaid {
|
||||
p.startWaitsSaid = true
|
||||
p.sayWaitsAgain(ctx)
|
||||
}
|
||||
if p.startSaid {
|
||||
return
|
||||
}
|
||||
if _, _, ok := p.graphKept(); !ok {
|
||||
return
|
||||
}
|
||||
p.startSaid = true
|
||||
p.sayWantsAgain(ctx)
|
||||
}
|
||||
|
||||
// sayWaitsAgain says `wait-ended` again for a record with `ending` (the rest of the end is done once the bus takes it), and
|
||||
// `wait-held` for every standing wait under its `held-said`.
|
||||
func (p *passer) sayWaitsAgain(ctx context.Context) {
|
||||
if p.kvs[buckets.Waits()] == nil {
|
||||
return
|
||||
}
|
||||
kept := p.w.read(buckets.Waits())
|
||||
for _, key := range slices.Sorted(mapKeys(kept)) {
|
||||
w, err := outside.Decode(kept[key])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
hex := key[strings.LastIndex(key, ".")+1:]
|
||||
switch {
|
||||
case w.Ending != "":
|
||||
p.outsideEnd(ctx, key, w, w.Ending, p.clock())
|
||||
case w.Standing():
|
||||
p.wantsOwe(waitOrder(key, w.ClockFrom), meshwants.EventWaitHeld, p.outsideBody(w), waitEventID(w.Node, w.Module, hex, "held."+strconv.Itoa(w.HeldSaid), w.ClockFrom), nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mapKeys[M ~map[string]V, V any](m M) func(func(string) bool) {
|
||||
return func(yield func(string) bool) {
|
||||
for k := range m {
|
||||
if !yield(k) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sayWantsAgain says, per node and module, the removal its mark holds (the removing want written first when the want's key still
|
||||
// holds the revision the mark names), then `wanted` for the want written, carrying the key's write time as its `at`.
|
||||
func (p *passer) sayWantsAgain(ctx context.Context) {
|
||||
marks := map[string]removalMark{}
|
||||
if p.ends != nil {
|
||||
ks, err := p.ends.st.keys()
|
||||
if err != nil {
|
||||
p.logf("the removal marks cannot be listed: %v", err)
|
||||
}
|
||||
sort.Strings(ks)
|
||||
for _, k := range ks {
|
||||
if !strings.HasPrefix(k, removalPrefix) {
|
||||
continue
|
||||
}
|
||||
raw, _, err := p.ends.st.get(k)
|
||||
var m removalMark
|
||||
if err != nil || raw == nil || json.Unmarshal(raw, &m) != nil {
|
||||
continue
|
||||
}
|
||||
if key, err := mwc.WantKey(m.Node, m.Module); err == nil {
|
||||
marks[key] = m
|
||||
}
|
||||
}
|
||||
}
|
||||
wants := p.w.read(buckets.Wants())
|
||||
seen := map[string]bool{}
|
||||
keysOf := slices.Sorted(mapKeys(wants))
|
||||
for k := range marks {
|
||||
if _, ok := wants[k]; !ok {
|
||||
keysOf = append(keysOf, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(keysOf)
|
||||
for _, key := range keysOf {
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
node, module, err := mwc.ParseWantKey(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if m, ok := marks[key]; ok {
|
||||
if meta := p.w.metaOf(buckets.Wants(), key); wants[key] != nil && meta.revision == m.WantRevision {
|
||||
p.wantWritten(ctx, node, module, key, mwc.Want{Removed: true, Words: "the removal is written from its mark, at a start (design 47 H2b §832 4.)"})
|
||||
}
|
||||
p.sayWanted(node, module, m.Fp, "", true, m.WantRevision, p.w.metaOf(buckets.Wants(), key).at, func() { p.dropRemovalMark(node, module) })
|
||||
}
|
||||
raw := p.w.value(buckets.Wants(), key)
|
||||
if raw == nil {
|
||||
continue
|
||||
}
|
||||
want, err := mwc.DecodeWant(raw)
|
||||
if err != nil || want.Removed {
|
||||
continue
|
||||
}
|
||||
meta := p.w.metaOf(buckets.Wants(), key)
|
||||
p.sayWanted(node, module, want.Fp, want.Pipeline, false, meta.revision, meta.at, nil)
|
||||
}
|
||||
}
|
||||
@@ -17,17 +17,20 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
)
|
||||
|
||||
// One pipeline's wants are written tier by tier (design 47 H §751, H-A-10, H-A-56): on a passed pipeline-ended the assigner
|
||||
// writes the wants of its first tier's movers; once each of them runs at the mover's fingerprint (the node-engine seat's
|
||||
// `running`, H-A-40) on every present placing machine, it writes the next tier's, and so on. The tier progress is the key
|
||||
// `pipeline.<branch>.<source>` of the state written, `{tier, since, movers}`; a tier counts placed movers only, and a machine away
|
||||
// is not waited for. A tier whose movers do not all run within `tier-bound` ends the delivery loudly: no later tier is written,
|
||||
// the finding `tier-late` (scope delivery, id the pipeline) is raised naming the movers and machines not running, and
|
||||
// `pipeline-wanted` says outcome tier-late; once every tier runs it says outcome running and the key goes (H-A-75). tier-late
|
||||
// clears when the late movers run or a later passed pipeline moves them (H-A-56).
|
||||
// is not waited for. A tier whose movers do not all run within `tier-bound` is found late: the finding `tier-late` (scope delivery, id
|
||||
// the pipeline) is raised naming the movers and machines not running, and `pipeline-wanted` says outcome tier-late, on which the
|
||||
// delivery record ends failed; the next tier is written once the late tier runs (design 47 H2b §824), and once every tier runs
|
||||
// `pipeline-wanted` says outcome running and the key goes (H-A-75). tier-late clears when the late movers run or a later passed
|
||||
// pipeline moves them (H-A-56).
|
||||
|
||||
// tierPrefix starts the key of a pipeline's tier progress in the state written.
|
||||
const tierPrefix = "pipeline."
|
||||
@@ -55,6 +58,28 @@ type tierProgress struct {
|
||||
Since time.Time `json:"since"`
|
||||
Movers []tierMover `json:"movers"`
|
||||
Source int64 `json:"source,omitempty"`
|
||||
// Seq is the sequence of the pipeline-ended the progress was written from, the run of the wants of a `no-version` mover the pass
|
||||
// finds released (design 47 H2b §826 1., H-A-845); zero in a progress kept before the field.
|
||||
Seq int64 `json:"seq,omitempty"`
|
||||
// ClockFrom is the time tier-bound counts from, in Since's form: Since when the progress starts, moved later by each
|
||||
// pause; absent reads as Since (design 47 H2 H-A-627).
|
||||
ClockFrom time.Time `json:"clock-from,omitzero"`
|
||||
// PausedFrom is the time the standing pause began: a key of the state asks names a mover of the tier that is not running,
|
||||
// and the count stands still. Absent while the bound counts (H-A-627).
|
||||
PausedFrom time.Time `json:"paused-from,omitzero"`
|
||||
// TierLateAt is the time any tier of the pipeline was first found past tier-bound, written before the finding is raised and
|
||||
// `pipeline-wanted` `tier-late` said; TierLateSaid the time the bus took that event. A key with the first and not the second
|
||||
// holds a `tier-late` still to be said. Both go into every later tier's progress (design 47 H2b §824 2.).
|
||||
TierLateAt time.Time `json:"tier-late-at,omitzero"`
|
||||
TierLateSaid time.Time `json:"tier-late-said,omitzero"`
|
||||
}
|
||||
|
||||
// clockFrom is the time tier-bound counts from; Since in a progress kept before the field.
|
||||
func (t tierProgress) clockFrom() time.Time {
|
||||
if t.ClockFrom.IsZero() {
|
||||
return t.Since
|
||||
}
|
||||
return t.ClockFrom
|
||||
}
|
||||
|
||||
// tierKey is the key of pipeline's tier progress; pipeline is the runner's key `<branch>.<source>`, its branch escaped.
|
||||
@@ -76,7 +101,7 @@ func isTierKey(key string) bool {
|
||||
// lowest of theirs, since now (H-A-277 (1)). A pipeline heard again adds to the progress that stands each mover it does not hold,
|
||||
// at the mover's tier, and marks versioned each held mover whose version is now written (H-A-270, H-A-273): its want is written
|
||||
// when the progress reaches its tier, or at once when that tier ran already, never out of tier order.
|
||||
func (e *pipelineEnds) startTiers(pipeline string, source int64, movers []tierMover, versioned map[string]bool) error {
|
||||
func (e *pipelineEnds) startTiers(pipeline string, source, seq int64, movers []tierMover, versioned map[string]bool) error {
|
||||
for {
|
||||
t, rev, ok := e.tiersOf(pipeline)
|
||||
if !ok {
|
||||
@@ -87,9 +112,13 @@ func (e *pipelineEnds) startTiers(pipeline string, source int64, movers []tierMo
|
||||
for _, m := range movers {
|
||||
first = min(first, m.Tier)
|
||||
}
|
||||
t = tierProgress{Tier: first, Since: e.clock().UTC(), Source: source}
|
||||
at := e.clock().UTC()
|
||||
t = tierProgress{Tier: first, Since: at, ClockFrom: at, Source: source, Seq: seq}
|
||||
}
|
||||
moved := false
|
||||
if t.Seq == 0 && seq > 0 {
|
||||
t.Seq, moved = seq, true
|
||||
}
|
||||
for i := range t.Movers {
|
||||
if t.Movers[i].NoVersion && versioned[t.Movers[i].Module] {
|
||||
t.Movers[i].NoVersion, moved = false, true
|
||||
@@ -169,6 +198,16 @@ func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []st
|
||||
now := p.clock().UTC()
|
||||
bound := p.tierBoundOf()
|
||||
var next time.Time
|
||||
standing := p.w.read(buckets.Asks())
|
||||
followed := map[string]bool{}
|
||||
for _, key := range ks {
|
||||
if isTierKey(key) {
|
||||
followed[assign.KeyID(strings.TrimPrefix(key, tierPrefix))] = true
|
||||
}
|
||||
}
|
||||
defer p.clearTierLate(followed)
|
||||
have, readable := p.findingKeys("the finding tier-late")
|
||||
p.tierHolds = map[string]tierHold{}
|
||||
for _, key := range ks {
|
||||
if !isTierKey(key) {
|
||||
continue
|
||||
@@ -179,24 +218,102 @@ func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []st
|
||||
continue
|
||||
}
|
||||
branch, number := pk.Branch, strconv.FormatInt(pk.Revision, 10)
|
||||
findingKey := views.FindingKey(mcc.ScopeDelivery, assign.KeyID(pipeline), kindTierLate)
|
||||
for {
|
||||
t, rev, ok := p.ends.tiersOf(pipeline)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
notRunning := p.notRunning(n, placedOn, pipeline, branch, t, t.Tier)
|
||||
late := !now.Before(t.Since.Add(bound))
|
||||
if late {
|
||||
p.tierLate(pipeline, branch, number, t, notRunning)
|
||||
// A key the earlier rule left holds neither field: it counts as said when the findings bucket holds a tier-late of its
|
||||
// pipeline, and both fields are written from that finding's time (H-A-722, H-A-828).
|
||||
if t.TierLateAt.IsZero() && readable && have[findingKey] {
|
||||
at := p.tierLateSince(findingKey, now)
|
||||
t.TierLateAt, t.TierLateSaid = at, at
|
||||
err := p.writeTier(key, t, rev, "tier-late-at")
|
||||
if err == nil || errors.Is(err, errSwapped) {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(notRunning) > 0 {
|
||||
if d := t.Since.Add(bound); next.IsZero() || d.Before(next) {
|
||||
if p.takeReleased(key, pipeline, branch, t, rev) {
|
||||
continue // a version found released: its end is kept and the mark gone, read the progress again
|
||||
}
|
||||
notRunning := p.notRunning(n, placedOn, pipeline, branch, t, t.Tier)
|
||||
// The count stands still while an ask of the operator names a mover of the tier that is not running (H-A-627): the first
|
||||
// pass that finds one writes paused-from, the first that finds none moves clock-from later by the time it stood still.
|
||||
clock := t.clockFrom()
|
||||
paused := pausedBy(standing, t, notRunning)
|
||||
if paused && t.PausedFrom.IsZero() && now.Before(clock.Add(bound)) && len(notRunning) > 0 {
|
||||
t.PausedFrom = now
|
||||
if now.Before(t.Since) {
|
||||
t.PausedFrom = t.Since // never earlier than the progress's own start
|
||||
}
|
||||
err := p.writeTier(key, t, rev, "paused-from")
|
||||
if err == nil {
|
||||
p.logf("pipeline %s: tier %d's count of tier-bound stands still: %s", pipeline, t.Tier, pauseNamed(standing, t, notRunning))
|
||||
}
|
||||
if err == nil || errors.Is(err, errSwapped) {
|
||||
continue // written, or a lost race: read the progress again
|
||||
}
|
||||
break // refused (said): reading it again would spin the pass
|
||||
}
|
||||
if !paused && !t.PausedFrom.IsZero() {
|
||||
held := now.Sub(t.PausedFrom)
|
||||
t.ClockFrom, t.PausedFrom = clock.Add(held), time.Time{}
|
||||
err := p.writeTier(key, t, rev, "clock-from")
|
||||
if err == nil {
|
||||
p.logf("pipeline %s: tier %d's count of tier-bound stood still for %s and goes on; the tier is late at %s", pipeline, t.Tier, held.Round(time.Second), t.ClockFrom.Add(bound).Format(time.RFC3339))
|
||||
}
|
||||
if err == nil || errors.Is(err, errSwapped) {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
runs := len(notRunning) == 0
|
||||
if !runs {
|
||||
p.tierHolds[pipeline] = tierHold{tier: t.Tier, mover: notRunning[0].Module, late: !t.TierLateAt.IsZero(), pipeline: pipeline}
|
||||
}
|
||||
late := !runs && t.PausedFrom.IsZero() && !now.Before(clock.Add(bound))
|
||||
if !runs && !t.PausedFrom.IsZero() {
|
||||
if !t.TierLateAt.IsZero() && t.TierLateSaid.IsZero() {
|
||||
p.sayTierLate(key, pipeline, branch, number, t, notRunning) // owed still: said while the tier is paused too (§824 2., §832 4.)
|
||||
}
|
||||
break // paused: no lateness, and no timer armed
|
||||
}
|
||||
if late {
|
||||
// Lateness is written before it is said: the field, the finding, the event (§824 2.).
|
||||
if t.TierLateAt.IsZero() {
|
||||
t.TierLateAt = now
|
||||
if err := p.writeTier(key, t, rev, "tier-late-at"); err == nil || errors.Is(err, errSwapped) {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
p.raiseTierLate(pipeline, t, notRunning, have, readable)
|
||||
if t.TierLateSaid.IsZero() {
|
||||
p.sayTierLate(key, pipeline, branch, number, t, notRunning)
|
||||
}
|
||||
break
|
||||
}
|
||||
if !t.TierLateAt.IsZero() && t.TierLateSaid.IsZero() {
|
||||
p.sayTierLate(key, pipeline, branch, number, t, notRunning) // owed still: said before any running of this pipeline
|
||||
}
|
||||
if !runs {
|
||||
if d := clock.Add(bound); next.IsZero() || d.Before(next) {
|
||||
next = d
|
||||
}
|
||||
break
|
||||
}
|
||||
// The tier runs: the next tier's wants are written, or every tier ran.
|
||||
// The tier runs, whether or not it was found late: the finding is cleared, and the next tier's wants are written, or
|
||||
// every tier ran.
|
||||
if readable && have[findingKey] {
|
||||
if err := p.findings.Delete(findingKey); err != nil {
|
||||
p.logf("the finding %s is not cleared, so the next tier of %s is not written yet: %v", findingKey, pipeline, err)
|
||||
break
|
||||
}
|
||||
delete(have, findingKey)
|
||||
p.logf("the finding %s is cleared: tier %d runs", findingKey, t.Tier)
|
||||
}
|
||||
later := int64(0)
|
||||
for _, m := range t.Movers {
|
||||
if m.Tier > t.Tier && (later == 0 || m.Tier < later) {
|
||||
@@ -204,14 +321,17 @@ func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []st
|
||||
}
|
||||
}
|
||||
if later == 0 {
|
||||
if err := p.ends.st.drop(key); err != nil {
|
||||
p.logf("the tier progress %s is not deleted: %v", key, err)
|
||||
break
|
||||
}
|
||||
p.sayPipelineWanted(pipeline, branch, number, t.Source, meshwants.PipelineWantedOutcomeRunning, nil)
|
||||
// The last tier runs: `running` is said, and the key goes once the bus has taken it, never before (§824 1.).
|
||||
p.sayPipelineWantedTaken(pipeline, branch, number, t.Source, meshwants.PipelineWantedOutcomeRunning, nil, func() {
|
||||
if err := p.ends.st.drop(key); err != nil {
|
||||
p.logf("the tier progress %s is not deleted: %v", key, err)
|
||||
}
|
||||
})
|
||||
break
|
||||
}
|
||||
value, err := json.Marshal(tierProgress{Tier: later, Since: now, Movers: t.Movers, Source: t.Source})
|
||||
moved := t
|
||||
moved.Tier, moved.Since, moved.ClockFrom, moved.PausedFrom = later, now, now, time.Time{}
|
||||
value, err := json.Marshal(moved)
|
||||
if err == nil {
|
||||
err = p.ends.st.swap(key, value, rev)
|
||||
}
|
||||
@@ -228,6 +348,46 @@ func (p *passer) tiers(n assign.Nodes, placedOn func(module, branch string) []st
|
||||
return next
|
||||
}
|
||||
|
||||
// takeReleased looks up, for each mover of t marked `no-version`, the version released of its module's build at its fingerprint,
|
||||
// whichever pipeline or source released it, matched by the build's parts, from what the assigner hears and with no call (design 47
|
||||
// H2b §826 1.). One found is kept as a passed mover's end naming this pipeline, with its source and the progress's seq (H-A-845),
|
||||
// and its mark goes; one whose kept end names another fingerprint is left to notRunning (§826 2.). It says whether the progress
|
||||
// was written, for the caller to read it again; a mover whose version is not found stays held, and a progress with no seq
|
||||
// (kept before the field) says why it cannot be taken.
|
||||
func (p *passer) takeReleased(key, pipeline, branch string, t tierProgress, rev uint64) bool {
|
||||
if p.ends.releasedOf == nil {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
for i, m := range t.Movers {
|
||||
if !m.NoVersion {
|
||||
continue
|
||||
}
|
||||
v, ok := p.ends.releasedOf(m.Module, m.Fp)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if end, kept := p.ends.endOf(m.Module, branch); kept && end.Fp != m.Fp {
|
||||
continue // a later pipeline moved it on
|
||||
}
|
||||
if t.Seq <= 0 {
|
||||
p.logf("pipeline %s: %s at %s has its version %s released, and is not taken: the progress carries no seq, the run its want would carry; the runner's end-again of %s writes it", pipeline, m.Module, m.Fp, v, pipeline)
|
||||
continue
|
||||
}
|
||||
if _, err := p.ends.keepEnd(pipeline, branch, t.Source, t.Seq, m.Module, m.Fp, v, max(m.Tier, 1)); err != nil {
|
||||
p.logf("pipeline %s: the end of %s at %s is not kept: %v", pipeline, m.Module, m.Fp, err)
|
||||
continue
|
||||
}
|
||||
t.Movers[i].NoVersion, changed = false, true
|
||||
p.logf("pipeline %s: %s at %s has its version %s released: taken at this pass", pipeline, m.Module, m.Fp, v)
|
||||
}
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
err := p.writeTier(key, t, rev, "no-version")
|
||||
return err == nil || errors.Is(err, errSwapped)
|
||||
}
|
||||
|
||||
// notRunning is, of tier's movers in t whose kept end still names pipeline, those not running at their fingerprint on a present
|
||||
// placing machine, with those machines. A mover a later pipeline moved counts as run; one placed nowhere counts as run.
|
||||
func (p *passer) notRunning(n assign.Nodes, placedOn func(module, branch string) []string, pipeline, branch string, t tierProgress, tier int64) []meshwants.NotRunning {
|
||||
@@ -236,6 +396,9 @@ func (p *passer) notRunning(n assign.Nodes, placedOn func(module, branch string)
|
||||
if m.Tier != tier {
|
||||
continue
|
||||
}
|
||||
if end, ok := p.ends.endOf(m.Module, branch); m.NoVersion && ok && end.Fp != m.Fp {
|
||||
continue // a later pipeline moved a mover with no version on to another fingerprint: it counts as run (§826 2.)
|
||||
}
|
||||
if m.NoVersion {
|
||||
// A mover whose version is not yet written holds its tier, under the tier bound (H-A-277 (1)).
|
||||
machines := []string{}
|
||||
@@ -248,8 +411,8 @@ func (p *passer) notRunning(n assign.Nodes, placedOn func(module, branch string)
|
||||
out = append(out, meshwants.NotRunning{Module: m.Module, Machines: machines})
|
||||
continue
|
||||
}
|
||||
if end, ok := p.ends.endOf(m.Module, branch); !ok || end.Pipeline != pipeline {
|
||||
continue // a later pipeline moved it
|
||||
if end, ok := p.ends.endOf(m.Module, branch); !ok || end.Fp != m.Fp {
|
||||
continue // a later pipeline moved it on to another fingerprint; one kept at its own, by whichever pipeline, is counted by its running (§824 1., §825)
|
||||
}
|
||||
var machines []string
|
||||
for _, node := range placedOn(m.Module, branch) {
|
||||
@@ -269,92 +432,94 @@ func (p *passer) notRunning(n assign.Nodes, placedOn func(module, branch string)
|
||||
return out
|
||||
}
|
||||
|
||||
// tierLate ends a pipeline's delivery at a tier past tier-bound: the finding tier-late is raised and pipeline-wanted says tier-late,
|
||||
// once each; the finding clears once the late movers run or a later pipeline moved them. The progress stays, so no later tier is
|
||||
// written, until no later tier's mover is kept at this pipeline any more.
|
||||
func (p *passer) tierLate(pipeline, branch, number string, t tierProgress, notRunning []meshwants.NotRunning) {
|
||||
o := tierLateFinding(pipeline, t.Tier, notRunning)
|
||||
// raiseTierLate raises the finding tier-late of pipeline naming the late tier, when the findings bucket holds none of the pipeline
|
||||
// (read from the bucket, never from what the process said, H-A-722); a bucket not read raises nothing.
|
||||
func (p *passer) raiseTierLate(pipeline string, t tierProgress, notRunning []meshwants.NotRunning, have map[string]bool, readable bool) {
|
||||
o := tierLateFinding(pipeline, t, notRunning)
|
||||
key := views.FindingKey(o.Scope, assign.KeyID(o.ID), o.Kind)
|
||||
if len(notRunning) > 0 {
|
||||
if !p.said[key+".raised"] {
|
||||
if p.findings.Put != nil {
|
||||
if err := p.findings.Put(o.Finding(p.clock())); err != nil {
|
||||
p.logf("the finding %s is not written: %v", key, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
p.said[key+".raised"] = true
|
||||
delete(p.said, key+".cleared")
|
||||
p.logf("pipeline %s: tier %d is late (tier-bound %s): %s; no later tier is written", pipeline, t.Tier, p.tierBoundOf(), o.Summary)
|
||||
p.sayPipelineWanted(pipeline, branch, number, t.Source, meshwants.PipelineWantedOutcomeTierLate, notRunning)
|
||||
}
|
||||
} else if !p.said[key+".cleared"] {
|
||||
if p.findings.Delete != nil {
|
||||
if err := p.findings.Delete(key); err != nil {
|
||||
p.logf("the finding %s is not deleted: %v", key, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
p.said[key+".cleared"] = true
|
||||
delete(p.said, key+".raised")
|
||||
if !readable || have[key] {
|
||||
return
|
||||
}
|
||||
for _, m := range t.Movers {
|
||||
if m.Tier <= t.Tier {
|
||||
continue
|
||||
}
|
||||
if end, ok := p.ends.endOf(m.Module, branch); ok && end.Pipeline == pipeline {
|
||||
return // a later tier's mover still kept at this pipeline: its want stays unwritten
|
||||
}
|
||||
if err := p.findings.Put(o.Finding(p.clock())); err != nil {
|
||||
p.logf("the finding %s is not written: %v", key, err)
|
||||
return
|
||||
}
|
||||
if len(notRunning) == 0 {
|
||||
if err := p.ends.st.drop(tierKey(pipeline)); err != nil {
|
||||
p.logf("the tier progress of %s is not deleted: %v", pipeline, err)
|
||||
have[key] = true
|
||||
p.logf("pipeline %s: tier %d is late (tier-bound %s): %s; the next tier is written once it runs", pipeline, t.Tier, p.tierBoundOf(), o.Summary)
|
||||
}
|
||||
|
||||
// sayTierLate owes `pipeline-wanted` `tier-late` of pipeline once, under its id; once the bus has taken it, the progress's
|
||||
// `tier-late-said` is written (§824 2.). A refused say is owed and said again (§832).
|
||||
func (p *passer) sayTierLate(key, pipeline, branch, number string, t tierProgress, notRunning []meshwants.NotRunning) {
|
||||
p.sayPipelineWantedTaken(pipeline, branch, number, t.Source, meshwants.PipelineWantedOutcomeTierLate, notRunning, func() { p.markTierLateSaid(key, pipeline) })
|
||||
}
|
||||
|
||||
// markTierLateSaid writes `tier-late-said`, the time the bus took the event, by compare-and-set on the key.
|
||||
func (p *passer) markTierLateSaid(key, pipeline string) {
|
||||
for {
|
||||
t, rev, ok := p.ends.tiersOf(pipeline)
|
||||
if !ok || !t.TierLateSaid.IsZero() {
|
||||
return
|
||||
}
|
||||
t.TierLateSaid = p.clock().UTC()
|
||||
if err := p.writeTier(key, t, rev, "tier-late-said"); !errors.Is(err, errSwapped) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tierLateFinding is the finding tier-late of pipeline's tier, naming the movers and machines not running (design 47 H §751).
|
||||
func tierLateFinding(pipeline string, tier int64, notRunning []meshwants.NotRunning) assign.Observed {
|
||||
// tierLateSince is the time of the finding tier-late a key of the earlier rule stands with, as the findings bucket holds it; now
|
||||
// when it cannot be read (H-A-828).
|
||||
func (p *passer) tierLateSince(findingKey string, now time.Time) time.Time {
|
||||
if p.findings.Get != nil {
|
||||
if f, ok, err := p.findings.Get(findingKey); err == nil && ok && !f.Since.IsZero() {
|
||||
return f.Since.UTC()
|
||||
}
|
||||
}
|
||||
return now
|
||||
}
|
||||
|
||||
// tierLateFinding is the finding tier-late of pipeline's tier, naming the movers and machines not running (design 47 H §751, §824
|
||||
// 3.); a mover with no version is named in §826's words.
|
||||
func tierLateFinding(pipeline string, t tierProgress, notRunning []meshwants.NotRunning) assign.Observed {
|
||||
var named []string
|
||||
for _, nr := range notRunning {
|
||||
if i := slices.IndexFunc(t.Movers, func(m tierMover) bool { return m.Module == nr.Module && m.NoVersion }); i >= 0 {
|
||||
named = append(named, fmt.Sprintf("%s: no version released at %s", nr.Module, t.Movers[i].Fp))
|
||||
continue
|
||||
}
|
||||
named = append(named, fmt.Sprintf("%s on %s", nr.Module, strings.Join(nr.Machines, ", ")))
|
||||
}
|
||||
summary := fmt.Sprintf("pipeline %s: tier %d does not run within tier-bound: %s", pipeline, tier, strings.Join(named, "; "))
|
||||
summary := fmt.Sprintf("pipeline %s: tier %d does not run within tier-bound: %s", pipeline, t.Tier, strings.Join(named, "; "))
|
||||
return assign.Observed{Scope: mcc.ScopeDelivery, ID: pipeline, Kind: kindTierLate, Severity: mcseat.FindingSeverityWarning,
|
||||
Summary: summary, Headline: "A delivery's tier does not run in time",
|
||||
Explanation: summary + ". The assigner writes no later tier of this pipeline; the delivery ends here.",
|
||||
Explanation: summary + ". The delivery record ends failed. The assigner writes the next tier once this tier runs on every present placing machine.",
|
||||
Source: "assigner." + kindTierLate}
|
||||
}
|
||||
|
||||
// sayPipelineWanted says the seat mesh-wants' pipeline-wanted of pipeline, once (its id the pipeline and the outcome): its
|
||||
// revision the number of the pipeline's key `<branch>.<revision>`, its source the one the pipeline-ended named (design 47
|
||||
// H-A-214, H-A-216), the key's number for a progress kept before it held one.
|
||||
// sayPipelineWanted says the seat mesh-wants' pipeline-wanted of pipeline (see sayPipelineWantedTaken), with nothing to do once the
|
||||
// bus has taken it.
|
||||
func (p *passer) sayPipelineWanted(pipeline, branch, number string, source int64, outcome string, notRunning []meshwants.NotRunning) {
|
||||
p.sayPipelineWantedTaken(pipeline, branch, number, source, outcome, notRunning, nil)
|
||||
}
|
||||
|
||||
// sayPipelineWantedTaken owes the seat mesh-wants' pipeline-wanted of pipeline once (its id the pipeline and the outcome): its
|
||||
// revision the number of the pipeline's key `<branch>.<revision>`, its source the one the pipeline-ended named (design 47
|
||||
// H-A-214, H-A-216), the key's number for a progress kept before it held one. It is said on the subject of its branch and revision
|
||||
// whatever the pipeline's form, its body naming the pipeline whole (H-A-839); taken runs once the bus has taken it.
|
||||
func (p *passer) sayPipelineWantedTaken(pipeline, branch, number string, source int64, outcome string, notRunning []meshwants.NotRunning, taken func()) {
|
||||
var revision int64
|
||||
_, _ = fmt.Sscan(number, &revision)
|
||||
if source <= 0 {
|
||||
source = revision
|
||||
}
|
||||
body := meshwants.PipelineWantedEvent{V: keys.Version, Pipeline: pipeline, Branch: branch, Source: source, Revision: revision, Outcome: outcome, NotRunning: notRunning}
|
||||
event := meshwants.EventPipelineWanted + "." + pipeline
|
||||
if err := p.wantsSay(event, body, "pipeline-wanted."+pipeline+"."+outcome); err != nil {
|
||||
p.logf("pipeline-wanted of %s is not said: %v", pipeline, err)
|
||||
}
|
||||
event := meshwants.EventPipelineWanted + "." + keys.EscapeName(branch) + "." + number
|
||||
p.wantsOwe("pipeline."+pipeline, event, body, "pipeline-wanted."+pipeline+"."+outcome, taken)
|
||||
}
|
||||
|
||||
// tierDeadline sets the one timer that wakes the pass at the earliest tier's deadline (H-A-56); zero stops it.
|
||||
func (p *passer) tierDeadline(at time.Time) {
|
||||
if p.tierWake == nil {
|
||||
return
|
||||
}
|
||||
if p.tierTimer != nil {
|
||||
p.tierTimer.Stop()
|
||||
}
|
||||
if at.IsZero() {
|
||||
return
|
||||
}
|
||||
p.tierTimer = time.AfterFunc(max(at.Sub(p.clock()), 0), p.tierWake)
|
||||
}
|
||||
// tierDeadline sets the earliest tier's deadline the one timer wakes the pass at (H-A-56, H-A-846); zero for none.
|
||||
func (p *passer) tierDeadline(at time.Time) { p.wakeSet("tiers", at) }
|
||||
|
||||
// tierBoundSetting is the setting tier-bound in minutes (design 47 H §751), read at the start from the file the manifest declares
|
||||
// with the content ${config:tier-bound}; zero, its default, for a file missing or empty.
|
||||
@@ -366,3 +531,85 @@ func tierBoundSetting(getenv func(string) string) (time.Duration, error) {
|
||||
// tierBoundUnit is the unit of the setting tier-bound, a minute; the whole test sets a shorter one, so a tier passes its bound
|
||||
// without a test waiting minutes.
|
||||
var tierBoundUnit = time.Minute
|
||||
|
||||
// writeTier swaps the tier progress at key by compare-and-set at rev; its error when it was not written: errSwapped for a lost race
|
||||
// (the caller reads the progress again), any other said (what field the write was for names it) and the caller goes on.
|
||||
func (p *passer) writeTier(key string, t tierProgress, rev uint64, field string) error {
|
||||
value, err := json.Marshal(t)
|
||||
if err == nil {
|
||||
err = p.ends.st.swap(key, value, rev)
|
||||
}
|
||||
if err != nil && !errors.Is(err, errSwapped) {
|
||||
p.logf("the tier progress %s is not written (%s): %v", key, field, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// pausingAsks are the keys of asks (the assigner's state asks, G §717) that pause the count of tier t of its pipeline: a key of
|
||||
// any kind but assignments that names a mover of the tier by its module, by the mover's fingerprint where the kind's key names
|
||||
// one (every kind but record, whose key names the composition), and, where it names a machine (every kind but hold), one of
|
||||
// the machines on which the mover is not running (H-A-627 (1)); sorted.
|
||||
func pausingAsks(standing map[string][]byte, t tierProgress, notRunning []meshwants.NotRunning) []string {
|
||||
var out []string
|
||||
for key := range standing {
|
||||
k, err := asks.ParseAnyAskKey(key)
|
||||
if err != nil || k.Kind == asks.AskKindAssignments || k.Module == "" {
|
||||
continue
|
||||
}
|
||||
for _, m := range t.Movers {
|
||||
if m.Tier != t.Tier || m.Module != k.Module || (k.Kind != asks.AskKindRecord && m.Fp != k.FP) {
|
||||
continue
|
||||
}
|
||||
if k.Kind == asks.AskKindHold || notRunningOn(notRunning, m.Module, k.Node) {
|
||||
out = append(out, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func notRunningOn(notRunning []meshwants.NotRunning, module, node string) bool {
|
||||
return slices.ContainsFunc(notRunning, func(nr meshwants.NotRunning) bool { return nr.Module == module && slices.Contains(nr.Machines, node) })
|
||||
}
|
||||
|
||||
// pausedBy says whether an ask of the operator pauses tier t's count (pausingAsks).
|
||||
func pausedBy(standing map[string][]byte, t tierProgress, notRunning []meshwants.NotRunning) bool {
|
||||
return len(pausingAsks(standing, t, notRunning)) > 0
|
||||
}
|
||||
|
||||
// pauseNamed names the ask that pauses the count, for the journal: its key and the movers of the tier it names.
|
||||
func pauseNamed(standing map[string][]byte, t tierProgress, notRunning []meshwants.NotRunning) string {
|
||||
var named []string
|
||||
for _, key := range pausingAsks(standing, t, notRunning) {
|
||||
k, _ := asks.ParseAnyAskKey(key)
|
||||
named = append(named, fmt.Sprintf("the ask %s about %s on %s", key, k.Module, k.Node))
|
||||
}
|
||||
return strings.Join(named, "; ")
|
||||
}
|
||||
|
||||
// clearTierLate clears, at the pass that finds its pipeline no longer followed (no tier progress stands for it), each finding
|
||||
// tier-late the findings bucket holds, read from the bucket, never from what a process said (H-A-722). followed are the
|
||||
// pipelines' ids as a finding's key holds them.
|
||||
func (p *passer) clearTierLate(followed map[string]bool) {
|
||||
have, ok := p.findingKeys("the finding tier-late")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for key := range have {
|
||||
rest, is := strings.CutPrefix(key, mcc.ScopeDelivery+".")
|
||||
if !is {
|
||||
continue
|
||||
}
|
||||
id, is := strings.CutSuffix(rest, "."+kindTierLate)
|
||||
if !is || followed[id] {
|
||||
continue
|
||||
}
|
||||
if err := p.findings.Delete(key); err != nil {
|
||||
p.logf("the finding %s is not cleared: %v", key, err)
|
||||
continue
|
||||
}
|
||||
delete(p.said, key+".raised")
|
||||
p.logf("the finding %s is cleared: its pipeline is no longer followed", key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,18 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
mcc "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
@@ -18,6 +23,7 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
||||
"mesh-delivery-assigner/internal/assign"
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
)
|
||||
@@ -32,7 +38,10 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
runs bool
|
||||
pipeline string
|
||||
}{{true, trunkBranch + ".5"}, {false, trunkBranch + ".5"}, {true, trunkBranch + ".5.again.2"}, {false, trunkBranch + ".5.again.2"}} {
|
||||
paused bool // H-A-627: the provider's record ask stands in asks from minute 5 to minute 45, and the count stands still
|
||||
held bool // H-A-682 (2), (4): the provider's entry needs a capability g14's node-engine does not state, so its want there is held
|
||||
}{{true, trunkBranch + ".5", false, false}, {false, trunkBranch + ".5", false, false}, {true, trunkBranch + ".5.again.2", false, false}, {false, trunkBranch + ".5.again.2", false, false},
|
||||
{true, trunkBranch + ".5", true, false}, {false, trunkBranch + ".5", true, false}, {false, trunkBranch + ".5", false, true}} {
|
||||
runs, pipeline := c.runs, c.pipeline
|
||||
start := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC)
|
||||
now := start
|
||||
@@ -42,11 +51,14 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
p.say = func(oc.Condition) error { return nil }
|
||||
findings := map[string]mcseat.Finding{}
|
||||
p.findings = assign.Findings{Put: func(f mcseat.Finding) error { findings[views.FindingKey(f.Scope, f.ID, f.Kind)] = f; return nil },
|
||||
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(findings)), nil },
|
||||
Delete: func(key string) error { delete(findings, key); return nil }}
|
||||
// H-A-722: a tier-late of a pipeline no longer followed, written before a restart, is cleared at the first pass.
|
||||
findings["delivery.main.3.tier-late"] = mcseat.Finding{Scope: "delivery", ID: "main.3", Kind: kindTierLate}
|
||||
var said []meshwants.PipelineWanted
|
||||
p.publishWants = func(event string, body any, _ string) error {
|
||||
if b, ok := body.(meshwants.PipelineWantedEvent); ok {
|
||||
if event != "pipeline-wanted."+pipeline {
|
||||
if event != "pipeline-wanted."+trunkBranch+".5" { // H-A-839: the subject of its branch and revision, an again pipeline's too
|
||||
t.Errorf("pipeline-wanted said as %s", event)
|
||||
}
|
||||
said = append(said, b)
|
||||
@@ -55,13 +67,26 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
}
|
||||
for i, m := range []struct{ name, fp string }{{"db", db}, {"web", web}} {
|
||||
digest := strings.Repeat(string(rune('e'+i)), 64)
|
||||
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: m.fp, Manifest: digest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
|
||||
value := meshcatalog.ModulesByModuleValue{Fp2: m.fp, Manifest: digest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath}
|
||||
if c.held && m.name == "db" {
|
||||
value.Needs = []string{"directory-contents-owner"}
|
||||
}
|
||||
mod, _ := meshcatalogclient.EncodeModule(value)
|
||||
putModuleRaw(p.w, trunkBranch, m.name, mod)
|
||||
p.w.manifests[digest] = parsed{module: m.name, manifest: catalogue.Manifest{Module: m.name}}
|
||||
}
|
||||
placeOn(t, p.w, "g14", "db", "web")
|
||||
placeOn(t, p.w, "ace", "db", "web")
|
||||
p.w.heardPresence("ace", true, start) // away: not waited for
|
||||
if c.held { // both engines state want:version; neither states the capability db needs
|
||||
p.reads = &engineReadsKept{}
|
||||
for _, node := range []string{"g14", "ace"} {
|
||||
raw, _ := json.Marshal(engineWords{Words: []string{nodeengine.ManifestReadWordWantVersion}, At: start})
|
||||
if err := p.reads.take(node, raw, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
p.w.mu.Lock()
|
||||
p.w.runningHeard = true
|
||||
p.w.mu.Unlock()
|
||||
@@ -80,15 +105,49 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
return ok
|
||||
}
|
||||
p.wants(context.Background())
|
||||
if _, old := findings["delivery.main.3.tier-late"]; old {
|
||||
t.Errorf("%s: a tier-late of a pipeline no longer followed stands after a pass: %v", pipeline, findings)
|
||||
}
|
||||
if !wanted("g14", "db") || !wanted("ace", "db") || wanted("g14", "web") || wanted("ace", "web") {
|
||||
t.Fatalf("%s runs %v: tier 1 alone is not what is wanted first: %v", pipeline, runs, wantsKV.values)
|
||||
}
|
||||
if c.held {
|
||||
key, _ := mwc.WantKey("g14", "db")
|
||||
if w, err := mwc.DecodeWant(wantsKV.values[key]); err != nil || !w.Hold || w.Words != mwc.HoldAwaitsReadsPrefix+"directory-contents-owner" {
|
||||
t.Fatalf("%s: db's want on g14 is not held awaiting its reads: %+v (%v)", pipeline, w, err)
|
||||
}
|
||||
}
|
||||
runAt, lateBefore, lateAt := time.Minute, 29*time.Minute, 30*time.Minute
|
||||
if c.paused {
|
||||
runAt, lateBefore, lateAt = 50*time.Minute, 69*time.Minute, 70*time.Minute
|
||||
akey, err := asks.RecordAskKey("g14", "db", "sha256:"+strings.Repeat("a", 64))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = start.Add(5 * time.Minute)
|
||||
p.w.put(buckets.Asks(), akey, []byte(`{}`))
|
||||
p.wants(context.Background())
|
||||
now = start.Add(30 * time.Minute) // past tier-bound had the count not stood still
|
||||
p.wants(context.Background())
|
||||
if len(findings) != 0 || len(said) != 0 {
|
||||
t.Fatalf("%s: late at minute 30 while its provider's ask stands: %v, %+v", pipeline, findings, said)
|
||||
}
|
||||
if prog, _, _ := p.ends.tiersOf(pipeline); prog.PausedFrom.IsZero() || !prog.PausedFrom.Equal(start.Add(5*time.Minute)) {
|
||||
t.Fatalf("%s: the pause's start is not kept: %+v", pipeline, prog)
|
||||
}
|
||||
now = start.Add(45 * time.Minute)
|
||||
p.w.put(buckets.Asks(), akey, nil)
|
||||
p.wants(context.Background())
|
||||
if prog, _, _ := p.ends.tiersOf(pipeline); !prog.PausedFrom.IsZero() || !prog.ClockFrom.Equal(start.Add(40*time.Minute)) {
|
||||
t.Fatalf("%s: the pause's end does not move clock-from to minute 40: %+v", pipeline, prog)
|
||||
}
|
||||
}
|
||||
if runs {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db})
|
||||
if err := p.w.hearRunning("running.g14.db", raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = start.Add(time.Minute)
|
||||
now = start.Add(runAt)
|
||||
p.wants(context.Background())
|
||||
if !wanted("g14", "web") || !wanted("ace", "web") {
|
||||
t.Fatalf("%s: the consumer's want is not written once its provider runs: %v", pipeline, wantsKV.values)
|
||||
@@ -104,12 +163,12 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
now = start.Add(29 * time.Minute)
|
||||
now = start.Add(lateBefore)
|
||||
p.wants(context.Background())
|
||||
if len(findings) != 0 || len(said) != 0 {
|
||||
t.Fatalf("late before tier-bound: %v, %+v", findings, said)
|
||||
}
|
||||
now = start.Add(30 * time.Minute)
|
||||
now = start.Add(lateAt)
|
||||
p.wants(context.Background())
|
||||
p.wants(context.Background())
|
||||
f, ok := findings["delivery."+assign.KeyID(pipeline)+".tier-late"]
|
||||
@@ -129,6 +188,281 @@ func TestAPipelinesWantsAreWrittenTierByTier(t *testing.T) {
|
||||
t.Error("a consumer's want is written after its provider's tier was late")
|
||||
}
|
||||
}
|
||||
// Design 47 H2b §824 (H-A-828, H-A-858): a delivery whose tier passed tier-bound goes on once that tier runs.
|
||||
t.Run("a late tier goes on once it runs", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
wanted := func(module string) bool {
|
||||
key, _ := mwc.WantKey("g14", module)
|
||||
_, ok := r.wantsKV.values[key]
|
||||
return ok
|
||||
}
|
||||
run := func(module, fp string) {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: module, Fingerprint: fp})
|
||||
if err := r.p.w.hearRunning("running.g14."+module, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r.pass(30 * time.Minute)
|
||||
prog, _, _ := r.p.ends.tiersOf(pipeline)
|
||||
if len(r.said) != 1 || r.said[0].Outcome != meshwants.PipelineWantedOutcomeTierLate || len(r.findings) != 1 || prog.TierLateAt.IsZero() || prog.TierLateSaid.IsZero() {
|
||||
t.Fatalf("AC-824a: at minute 30 said %+v findings %v progress %+v", r.said, r.findings, prog)
|
||||
}
|
||||
// AC-824c: a restart between the two keeps both fields
|
||||
r.restart()
|
||||
if prog, _, _ := r.p.ends.tiersOf(pipeline); prog.TierLateAt.IsZero() || prog.TierLateSaid.IsZero() {
|
||||
t.Fatalf("AC-824c: a restart lost the fields: %+v", prog)
|
||||
}
|
||||
run("db", db)
|
||||
r.pass(45 * time.Minute)
|
||||
if !wanted("web") || len(r.findings) != 0 {
|
||||
t.Fatalf("AC-824a: at minute 45 the consumer's want is %v, findings %v", wanted("web"), r.findings)
|
||||
}
|
||||
// AC-824b: a second tier found late raises the finding naming it and says no second pipeline-wanted
|
||||
r.pass(76 * time.Minute)
|
||||
f := r.findings["delivery."+assign.KeyID(pipeline)+".tier-late"]
|
||||
if len(r.said) != 1 || !strings.Contains(f.Summary, "tier 2 does not run") {
|
||||
t.Errorf("AC-824b: said %+v, finding %+v", r.said, f)
|
||||
}
|
||||
run("web", web)
|
||||
r.pass(77 * time.Minute)
|
||||
if len(r.said) != 2 || r.said[1].Outcome != meshwants.PipelineWantedOutcomeRunning || len(r.findings) != 0 {
|
||||
t.Errorf("AC-824a: running said %+v, findings %v", r.said, r.findings)
|
||||
}
|
||||
if _, _, ok := r.p.ends.tiersOf(pipeline); ok {
|
||||
t.Error("the key stands after running was taken")
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §825, §824 1. (review r1 finding 1, AC-825a): a mover a later pipeline carries at its own fingerprint is kept
|
||||
// again under that pipeline, and the earlier progress goes on once it runs, never before.
|
||||
t.Run("a mover kept again by a later pipeline at its own fingerprint is counted by its running", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
later := ended(trunkBranch, 6, mpr.PipelineEndedOutcomePassed, mover("web", web, "0.1.2", 1, mpr.StepResultOutcomePassed))
|
||||
if _, err := r.p.ends.take(later); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if end, ok := r.p.ends.endOf("web", trunkBranch); !ok || end.Pipeline != trunkBranch+".6" || end.Fp != web {
|
||||
t.Fatalf("AC-825a: web's end = %+v (%v), want kept again by main.6", end, ok)
|
||||
}
|
||||
run := func(module, fp string) {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: module, Fingerprint: fp})
|
||||
if err := r.p.w.hearRunning("running.g14."+module, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
saidOf := func(revision int64) (n int) {
|
||||
for _, b := range r.said {
|
||||
if b.Revision == revision && b.Outcome == meshwants.PipelineWantedOutcomeRunning {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
r.pass(30 * time.Second)
|
||||
// AC-825a, first half: web's want is written in main.6's own tier, naming main.6 and rank 1
|
||||
wkey, _ := mwc.WantKey("g14", "web")
|
||||
if w, err := mwc.DecodeWant(r.wantsKV.values[wkey]); err != nil || w.Pipeline != trunkBranch+".6" || w.Rank != 1 || w.Fp != web {
|
||||
t.Fatalf("AC-825a: web's want is %+v (%v), want it written by main.6 at rank 1", w, err)
|
||||
}
|
||||
run("db", db)
|
||||
r.pass(time.Minute)
|
||||
r.pass(2 * time.Minute)
|
||||
if prog, _, ok := r.p.ends.tiersOf(pipeline); !ok || prog.Tier != 2 || saidOf(5) != 0 {
|
||||
t.Fatalf("AC-825a: main.5 says running while web does not run: progress %+v (%v), said %+v", prog, ok, r.said)
|
||||
}
|
||||
run("web", web)
|
||||
r.pass(3 * time.Minute)
|
||||
if saidOf(5) != 1 {
|
||||
t.Errorf("AC-825a: main.5 does not say running once web runs: %+v", r.said)
|
||||
}
|
||||
})
|
||||
t.Run("an end naming a rebuild's version is kept no-version, then takes the version released at its own fingerprint (§835 2.)", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
r := &tierRig{t: t, start: time.Date(2026, 11, 27, 4, 0, 0, 0, time.UTC), findings: map[string]mcseat.Finding{}, ends: newMemEnds(), db: db, web: web}
|
||||
r.now = r.start
|
||||
r.build()
|
||||
r.p.ends.releasedOf = r.p.w.releasedOf
|
||||
release := func(source int64, version, digest string) {
|
||||
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "db", Source: source, Version: version, Artifacts: []meshcatalog.VersionArtifact{{Artifact: "db:image", Digest: digest}}})
|
||||
if err := r.p.w.released.put(rel); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
built, _ := json.Marshal(builds.BuildEnded{Module: "db", Fingerprint: db, Outcome: builds.BuildDone, Made: map[string]string{"image": "sha256:7"}})
|
||||
if err := r.p.w.ends.put(built); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release(4, "0.2.0", "sha256:7") // the build at db's fingerprint
|
||||
release(5, "0.2.1", "sha256:8") // a rebuild of the same source
|
||||
e := ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("db", db, "0.2.1", 1, mpr.StepResultOutcomePassed))
|
||||
e.Source = 4
|
||||
if _, err := r.p.ends.take(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prog, _, _ := r.p.ends.tiersOf(trunkBranch + ".5")
|
||||
if _, ok := r.p.ends.endOf("db", trunkBranch); ok || len(prog.Movers) != 1 || !prog.Movers[0].NoVersion {
|
||||
t.Fatalf("the rebuild's version was kept: end %v progress %+v", ok, prog)
|
||||
}
|
||||
r.pass(time.Minute)
|
||||
if end, ok := r.p.ends.endOf("db", trunkBranch); !ok || end.Version != "0.2.0" || end.Fp != db || end.Seq != 205 {
|
||||
t.Fatalf("the end kept after the pass = %+v (%v)", end, ok)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §832 6. (1984/AC-832j): dropping an owed tier-late writes tier-late-said, and an owed running deletes the progress key.
|
||||
t.Run("assigner_owed_drop of an owed tier-late writes tier-late-said, and of an owed running deletes the progress key", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
r.refuse = true
|
||||
r.pass(30 * time.Minute)
|
||||
owed := r.p.owedAll()
|
||||
if len(owed) != 1 || !strings.HasPrefix(owed[0].ID, "pipeline-wanted."+pipeline+".tier-late") {
|
||||
t.Fatalf("AC-832j: owed %+v", owed)
|
||||
}
|
||||
dropped, err := r.p.owedDrop(owed[0].ID)
|
||||
prog, _, _ := r.p.ends.tiersOf(pipeline)
|
||||
if err != nil || len(dropped) != 1 || prog.TierLateSaid.IsZero() || len(r.p.owedAll()) != 0 {
|
||||
t.Fatalf("AC-832j: the drop of tier-late answered %+v (%v), progress %+v", dropped, err, prog)
|
||||
}
|
||||
for i, m := range []struct{ module, fp string }{{"db", db}, {"web", web}} {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: m.module, Fingerprint: m.fp})
|
||||
_ = r.p.w.hearRunning("running.g14."+m.module, raw)
|
||||
r.pass(time.Duration(31+i) * time.Minute)
|
||||
}
|
||||
owed = r.p.owedAll()
|
||||
if len(owed) != 1 || !strings.HasSuffix(owed[0].ID, ".running") {
|
||||
t.Fatalf("AC-832j: owed %+v, want running", owed)
|
||||
}
|
||||
if _, err := r.p.owedDrop(owed[0].ID); err != nil || r.ends.vals[tierKey(pipeline)] != nil {
|
||||
t.Errorf("AC-832j: the drop of running left the progress key %v (%v)", r.ends.vals[tierKey(pipeline)] != nil, err)
|
||||
}
|
||||
})
|
||||
t.Run("a tier-late the bus refuses is said again after a restart, before running, and the key stands until running is taken", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
r.refuse = true
|
||||
r.pass(30 * time.Minute)
|
||||
prog, _, _ := r.p.ends.tiersOf(pipeline)
|
||||
if len(r.said) != 0 || prog.TierLateAt.IsZero() || !prog.TierLateSaid.IsZero() {
|
||||
t.Fatalf("AC-824d: a refused say was taken: said %+v progress %+v", r.said, prog)
|
||||
}
|
||||
r.restart()
|
||||
r.refuse = false
|
||||
for _, m := range []struct{ module, fp string }{{"db", db}, {"web", web}} {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: m.module, Fingerprint: m.fp})
|
||||
_ = r.p.w.hearRunning("running.g14."+m.module, raw)
|
||||
}
|
||||
r.pass(31 * time.Minute)
|
||||
r.pass(32 * time.Minute)
|
||||
if len(r.said) != 2 || r.said[0].Outcome != meshwants.PipelineWantedOutcomeTierLate || r.said[1].Outcome != meshwants.PipelineWantedOutcomeRunning {
|
||||
t.Errorf("AC-824d: said %+v, want tier-late then running", r.said)
|
||||
}
|
||||
if want := []string{"pipeline-wanted." + pipeline + ".tier-late", "pipeline-wanted." + pipeline + ".running"}; !slices.Equal(r.ids, want) {
|
||||
t.Errorf("AC-824d: said under %v, want the ids %v", r.ids, want)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §824 2., §832 4. (review r1 finding 5): a tier-late owed and lost to a restart is said at the start pass even
|
||||
// while the tier its key stands at is paused.
|
||||
t.Run("a tier-late owed is said at a start while the tier is paused", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
r.refuse = true
|
||||
r.pass(30 * time.Minute) // tier 1 late: tier-late-at written, the say refused
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db})
|
||||
_ = r.p.w.hearRunning("running.g14.db", raw)
|
||||
r.pass(31 * time.Minute) // tier 1 runs: tier 2's progress carries the fields
|
||||
akey, _ := asks.RecordAskKey("g14", "web", "sha256:"+strings.Repeat("a", 64))
|
||||
r.p.w.put(buckets.Asks(), akey, []byte(`{}`))
|
||||
r.pass(32 * time.Minute)
|
||||
prog, _, _ := r.p.ends.tiersOf(pipeline)
|
||||
if prog.Tier != 2 || prog.PausedFrom.IsZero() || prog.TierLateAt.IsZero() || !prog.TierLateSaid.IsZero() {
|
||||
t.Fatalf("tier 2 is not paused holding an owed tier-late: %+v", prog)
|
||||
}
|
||||
r.restart()
|
||||
r.refuse = false
|
||||
r.p.w.put(buckets.Asks(), akey, []byte(`{}`))
|
||||
r.pass(33 * time.Minute)
|
||||
if len(r.said) != 1 || r.said[0].Outcome != meshwants.PipelineWantedOutcomeTierLate {
|
||||
t.Errorf("a start pass says %+v while its tier is paused, want the owed tier-late", r.said)
|
||||
}
|
||||
})
|
||||
t.Run("a key of the earlier rule with a tier-late in the bucket says no second one; a tier past its bound pauses for no later ask; a refused clear holds the next tier", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
since := r.start.Add(-time.Hour)
|
||||
r.findings["delivery."+assign.KeyID(pipeline)+".tier-late"] = mcseat.Finding{Scope: "delivery", ID: pipeline, Kind: kindTierLate, Since: since}
|
||||
r.pass(31 * time.Minute)
|
||||
prog, _, _ := r.p.ends.tiersOf(pipeline)
|
||||
if len(r.said) != 0 || !prog.TierLateAt.Equal(since) || !prog.TierLateSaid.Equal(since) {
|
||||
t.Fatalf("AC-824e: said %+v progress %+v, want both fields at the finding's since", r.said, prog)
|
||||
}
|
||||
// AC-824h: the tier is past its bound, so a later ask pauses nothing
|
||||
akey, _ := asks.RecordAskKey("g14", "db", "sha256:"+strings.Repeat("a", 64))
|
||||
r.p.w.put(buckets.Asks(), akey, []byte(`{}`))
|
||||
r.pass(32 * time.Minute)
|
||||
if prog, _, _ := r.p.ends.tiersOf(pipeline); !prog.PausedFrom.IsZero() {
|
||||
t.Errorf("AC-824h: a paused-from after the bound: %+v", prog)
|
||||
}
|
||||
// AC-824n: the clear refused once holds the next tier's progress
|
||||
r.deleteRefused = 1
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: "db", Fingerprint: db})
|
||||
_ = r.p.w.hearRunning("running.g14.db", raw)
|
||||
r.pass(33 * time.Minute)
|
||||
if prog, _, _ := r.p.ends.tiersOf(pipeline); prog.Tier != 1 {
|
||||
t.Fatalf("AC-824n: tier 2's progress is written while the clear is refused: %+v", prog)
|
||||
}
|
||||
r.pass(34 * time.Minute)
|
||||
if prog, _, _ := r.p.ends.tiersOf(pipeline); prog.Tier != 2 || prog.TierLateAt.IsZero() {
|
||||
t.Errorf("AC-824n: the next pass, with the clear taken, writes tier 2 and carries the fields: %+v", prog)
|
||||
}
|
||||
})
|
||||
// Design 47 H2b §824 6., 7. (H-A-844): a want waiting on its tier says held-by-tier, naming the pipeline, the tier and the mover that
|
||||
// holds it; assigner_progress_drop deletes a progress whose version never comes, in the hand-act log.
|
||||
t.Run("a want waiting on its tier says held-by-tier, and a progress is dropped by hand", func(t *testing.T) {
|
||||
db, web := meshcatalogclient.SourcePrefix2+strings.Repeat("d", 64), meshcatalogclient.SourcePrefix2+strings.Repeat("c", 64)
|
||||
pipeline := trunkBranch + ".5"
|
||||
r := newTierRig(t, db, web, pipeline)
|
||||
r.pass(31 * time.Minute)
|
||||
why, ok := r.p.heldByTier("web", trunkBranch, wantWhy{})
|
||||
if !ok || why.Step != whyHeldByTier || why.Pipeline != pipeline || why.Tier != 1 || why.Holder != "db" || !why.TierLate {
|
||||
t.Errorf("AC-824l: the why of web is %+v (%v), want held-by-tier naming %s, tier 1, db, late", why, ok, pipeline)
|
||||
}
|
||||
if _, ok := r.p.heldByTier("nothing", trunkBranch, wantWhy{}); ok {
|
||||
t.Error("AC-824l: a module with no kept end is held by a tier")
|
||||
}
|
||||
key := tierKey(pipeline)
|
||||
st := memStore{writtenState: &memKV{values: map[string][]byte{key: r.ends.vals[key]}}}
|
||||
var asked []string
|
||||
ask := func(verb string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
asked = append(asked, string(raw))
|
||||
return json.RawMessage(`{}`), nil
|
||||
}
|
||||
if _, err := dropProgress(st, ask, pipeline, "its version never comes", "person.jochen"); err != nil || len(st[writtenState].values) != 0 || len(asked) != 1 ||
|
||||
!strings.Contains(asked[0], progressDropTool+" "+key) {
|
||||
t.Errorf("AC-824g: the drop answered %v, left %v, asked %v", err, st[writtenState].values, asked)
|
||||
}
|
||||
if _, err := dropProgress(st, ask, pipeline, "again", "person.jochen"); err == nil {
|
||||
t.Error("a progress no longer there was dropped")
|
||||
}
|
||||
// the pass that finds the pipeline no longer followed clears its tier-late
|
||||
delete(r.ends.vals, key)
|
||||
r.pass(32 * time.Minute)
|
||||
if len(r.findings) != 0 || len(r.said) != 1 {
|
||||
t.Errorf("AC-824g: findings %v, said %+v after the drop", r.findings, r.said)
|
||||
}
|
||||
prog := tierProgress{TierLateAt: r.start, TierLateSaid: r.start.Add(time.Minute)}
|
||||
raw, _ := json.Marshal(prog)
|
||||
if !strings.Contains(string(raw), `"tier-late-at"`) || !strings.Contains(string(raw), `"tier-late-said"`) {
|
||||
t.Errorf("AC-824j: the progress holds %s", raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// H-A-270, H-A-273, H-A-277 (1): a pipeline's tier progress holds every passed mover, versioned or not, and a tier with a mover
|
||||
@@ -139,11 +473,27 @@ func TestALateMoverHoldsItsTier(t *testing.T) {
|
||||
versions map[string]string // a pipeline-ended taken, each mover's version ("": none yet)
|
||||
runs string // or: this module runs on g14
|
||||
wanted string // then: the modules wanted, in order of the list
|
||||
released string // or: the version of db's build released under another source (heard, no pipeline names it)
|
||||
later bool // or: a later pipeline moves db on to another fingerprint
|
||||
late bool // or: tier-bound passes with the findings read
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
steps []step
|
||||
}{
|
||||
{"a version released under another source is taken at the next pass (H-A-845: its end carries the seq)", []step{
|
||||
{versions: map[string]string{"db": "", "web": "0.1.2", "api": "0.3.0"}, wanted: ""},
|
||||
{released: "0.2.0", wanted: "db"},
|
||||
{runs: "db", wanted: "db,web"},
|
||||
}},
|
||||
{"a mover a later pipeline moved on counts as run", []step{
|
||||
{versions: map[string]string{"db": "", "web": "0.1.2", "api": "0.3.0"}, wanted: ""},
|
||||
{later: true, wanted: "db,web"},
|
||||
}},
|
||||
{"a version that never comes holds the tier, named with its fingerprint, and writes no later want", []step{
|
||||
{versions: map[string]string{"db": "", "web": "0.1.2", "api": "0.3.0"}, wanted: ""},
|
||||
{late: true, wanted: ""},
|
||||
}},
|
||||
{"the lowest tier's version comes last", []step{
|
||||
{versions: map[string]string{"db": "", "web": "0.1.2", "api": "0.3.0"}, wanted: ""},
|
||||
{versions: map[string]string{"db": "0.2.0", "web": "0.1.2", "api": "0.3.0"}, wanted: "db"},
|
||||
@@ -182,7 +532,44 @@ func TestALateMoverHoldsItsTier(t *testing.T) {
|
||||
p.w.mu.Unlock()
|
||||
p.ends = newPipelineEnds(newMemEnds(), func() {}, t.Logf)
|
||||
p.ends.trunk, p.ends.now = p.w.trunkName, func() time.Time { return now }
|
||||
p.ends.releasedOf = p.w.releasedOf
|
||||
found := map[string]mcseat.Finding{}
|
||||
p.findings = assign.Findings{Put: func(f mcseat.Finding) error { found[views.FindingKey(f.Scope, f.ID, f.Kind)] = f; return nil },
|
||||
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(found)), nil },
|
||||
Get: func(key string) (mcseat.Finding, bool, error) { f, ok := found[key]; return f, ok, nil },
|
||||
Delete: func(key string) error { delete(found, key); return nil }}
|
||||
for i, s := range c.steps {
|
||||
switch {
|
||||
case s.released != "":
|
||||
rel, _ := json.Marshal(meshcatalog.VersionReleasedEvent{Module: "db", Source: 9, Version: s.released, Artifacts: []meshcatalog.VersionArtifact{{Artifact: "db:image", Digest: "sha256:7"}}})
|
||||
built, _ := json.Marshal(builds.BuildEnded{Module: "db", Fingerprint: fps["db"], Outcome: builds.BuildDone, Made: map[string]string{"image": "sha256:7"}})
|
||||
if err := p.w.released.put(rel); err != nil || p.w.ends.put(built) != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case s.later:
|
||||
other := meshcatalogclient.SourcePrefix2 + strings.Repeat("9", 64)
|
||||
e := ended(trunkBranch, 6, mpr.PipelineEndedOutcomePassed, mover("db", other, "0.2.1", 1, mpr.StepResultOutcomePassed))
|
||||
if _, err := p.ends.take(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case s.late:
|
||||
now = now.Add(time.Hour)
|
||||
}
|
||||
if s.late {
|
||||
now = now.Add(time.Minute)
|
||||
p.wants(context.Background())
|
||||
f, ok := found[views.FindingKey(mcc.ScopeDelivery, assign.KeyID(trunkBranch+".5"), kindTierLate)]
|
||||
if !ok || !strings.Contains(f.Summary, "db: no version released at "+fps["db"]) {
|
||||
t.Fatalf("step %d: the finding tier-late = %+v (%v)", i+1, f, ok)
|
||||
}
|
||||
}
|
||||
if s.released != "" {
|
||||
now = now.Add(time.Minute)
|
||||
p.wants(context.Background())
|
||||
if end, ok := p.ends.endOf("db", trunkBranch); !ok || end.Pipeline != trunkBranch+".5" || end.Seq != 205 || end.Version != s.released {
|
||||
t.Fatalf("step %d: the end kept for db = %+v (%v)", i+1, end, ok)
|
||||
}
|
||||
}
|
||||
if s.versions != nil {
|
||||
var movers []mpr.MoverEnded
|
||||
for _, m := range []string{"db", "web", "api"} {
|
||||
@@ -191,7 +578,7 @@ func TestALateMoverHoldsItsTier(t *testing.T) {
|
||||
if _, err := p.ends.take(ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, movers...)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
} else if s.runs != "" {
|
||||
raw, _ := json.Marshal(nodeengine.Running{Node: "g14", Module: s.runs, Fingerprint: fps[s.runs]})
|
||||
if err := p.w.hearRunning("running.g14."+s.runs, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -213,3 +600,123 @@ func TestALateMoverHoldsItsTier(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-627 (2): a write of the tier progress that is refused (a full bucket), not lost to another writer, is said and not read
|
||||
// again within the pass: the pass would spin on the same progress for ever.
|
||||
func TestARefusedTierWriteDoesNotSpinThePass(t *testing.T) {
|
||||
start := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC)
|
||||
for _, field := range []string{"paused-from", "clock-from"} {
|
||||
st := &refusingEnds{memEnds: newMemEnds(), t: t}
|
||||
p := newPasser(kvSet{buckets.Asks(): &memKV{values: map[string][]byte{}}}, start.Add(5*time.Minute))
|
||||
p.ends = newPipelineEnds(st, func() {}, func(string, ...any) {})
|
||||
prog := tierProgress{Tier: 1, Since: start, ClockFrom: start, Movers: []tierMover{{Module: "db", Fp: "fp", Tier: 1, NoVersion: true}}}
|
||||
if field == "clock-from" {
|
||||
prog.PausedFrom = start.Add(time.Minute) // the ask is gone: the pause ends
|
||||
} else if akey, err := asks.RecordAskKey("g14", "db", "sha256:"+strings.Repeat("a", 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
} else {
|
||||
p.w.put(buckets.Asks(), akey, []byte(`{}`))
|
||||
}
|
||||
raw, _ := json.Marshal(prog)
|
||||
st.vals[tierKey(trunkBranch+".5")], st.revs[tierKey(trunkBranch+".5")] = raw, 1
|
||||
p.tiers(assign.Nodes{Online: map[string]bool{}}, func(string, string) []string { return []string{"g14"} })
|
||||
if st.swaps != 1 {
|
||||
t.Errorf("%s: the refused write was made %d times in one pass", field, st.swaps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// refusingEnds is memEnds whose every swap is refused for a cause other than a lost race; it fails the test on the third.
|
||||
type refusingEnds struct {
|
||||
*memEnds
|
||||
t *testing.T
|
||||
swaps int
|
||||
}
|
||||
|
||||
func (r *refusingEnds) swap(string, []byte, uint64) error {
|
||||
r.swaps++
|
||||
if r.swaps > 2 {
|
||||
r.t.Fatal("the pass reads the refused progress again and writes it again")
|
||||
}
|
||||
return errors.New("the bucket is full")
|
||||
}
|
||||
|
||||
// tierRig is one pass loop of a pipeline of db (tier 1) and web (tier 2) on g14 with the findings of a bucket the test reads, and a
|
||||
// restart that makes a new passer on the same kept progress (the process's memory gone).
|
||||
type tierRig struct {
|
||||
t *testing.T
|
||||
p *passer
|
||||
start time.Time
|
||||
now time.Time
|
||||
wantsKV *memKV
|
||||
findings map[string]mcseat.Finding
|
||||
said []meshwants.PipelineWanted
|
||||
ids []string // the message id of each pipeline-wanted taken, beside said
|
||||
refuse bool
|
||||
deleteRefused int
|
||||
ends *memEnds
|
||||
db, web string
|
||||
}
|
||||
|
||||
func newTierRig(t *testing.T, db, web, pipeline string) *tierRig {
|
||||
r := &tierRig{t: t, start: time.Date(2026, 11, 27, 4, 0, 0, 0, time.UTC), findings: map[string]mcseat.Finding{}, ends: newMemEnds(), db: db, web: web}
|
||||
r.now = r.start
|
||||
r.build()
|
||||
e := ended(trunkBranch, 5, mpr.PipelineEndedOutcomePassed, mover("db", db, "0.2.0", 1, mpr.StepResultOutcomePassed), mover("web", web, "0.1.2", 2, mpr.StepResultOutcomePassed))
|
||||
e.Source, e.Pipeline = 4, pipeline
|
||||
if _, err := r.p.ends.take(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.pass(0)
|
||||
return r
|
||||
}
|
||||
|
||||
// build makes the passer over the kept state: a start of the process.
|
||||
func (r *tierRig) build() {
|
||||
t := r.t
|
||||
r.wantsKV = &memKV{values: map[string][]byte{}}
|
||||
p := newPasser(kvSet{buckets.Wants(): r.wantsKV, buckets.Asks(): &memKV{values: map[string][]byte{}}}, r.start)
|
||||
p.now = func() time.Time { return r.now }
|
||||
p.say = func(oc.Condition) error { return nil }
|
||||
p.findings = assign.Findings{Put: func(f mcseat.Finding) error { r.findings[views.FindingKey(f.Scope, f.ID, f.Kind)] = f; return nil },
|
||||
Keys: func() ([]string, error) { return slices.Collect(maps.Keys(r.findings)), nil },
|
||||
Get: func(key string) (mcseat.Finding, bool, error) { f, ok := r.findings[key]; return f, ok, nil },
|
||||
Delete: func(key string) error {
|
||||
if r.deleteRefused > 0 {
|
||||
r.deleteRefused--
|
||||
return errors.New("the bucket is full")
|
||||
}
|
||||
delete(r.findings, key)
|
||||
return nil
|
||||
}}
|
||||
p.publishWants = func(event string, body any, id string) error {
|
||||
if r.refuse {
|
||||
return errors.New("the bus refuses")
|
||||
}
|
||||
if b, ok := body.(meshwants.PipelineWantedEvent); ok {
|
||||
r.said, r.ids = append(r.said, b), append(r.ids, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for i, m := range []struct{ name, fp string }{{"db", r.db}, {"web", r.web}} {
|
||||
digest := strings.Repeat(string(rune('e'+i)), 64)
|
||||
mod, _ := meshcatalogclient.EncodeModule(meshcatalog.ModulesByModuleValue{Fp2: m.fp, Manifest: digest, Repository: "novox/" + m.name, Commit: strings.Repeat("1", 40), Path: meshcatalogclient.RootPath})
|
||||
putModuleRaw(p.w, trunkBranch, m.name, mod)
|
||||
p.w.manifests[digest] = parsed{module: m.name, manifest: catalogue.Manifest{Module: m.name}}
|
||||
}
|
||||
placeOn(t, p.w, "g14", "db", "web")
|
||||
p.w.mu.Lock()
|
||||
p.w.runningHeard = true
|
||||
p.w.mu.Unlock()
|
||||
p.ends = newPipelineEnds(r.ends, func() {}, t.Logf)
|
||||
p.ends.trunk, p.ends.now = p.w.trunkName, func() time.Time { return r.now }
|
||||
r.p = p
|
||||
}
|
||||
|
||||
func (r *tierRig) restart() { r.build() }
|
||||
|
||||
// pass makes one pass at minutes after the start.
|
||||
func (r *tierRig) pass(minutes time.Duration) {
|
||||
r.now = r.start.Add(minutes)
|
||||
r.p.wants(context.Background())
|
||||
}
|
||||
|
||||
@@ -74,33 +74,18 @@ func (s *putTools) hear(key string, value []byte) {
|
||||
// fullFP is a fingerprint of the new form, whole.
|
||||
var fullFP = regexp.MustCompile(`^src2:[0-9a-f]{64}$`)
|
||||
|
||||
// version reads the version a put names: newest (the indexer's fingerprint at the trunk) or a whole fingerprint (design 47 G A-181:
|
||||
// a put names the whole fingerprint, the builder's builds being no bucket to list).
|
||||
// prefixFP is a fingerprint's first 12 to 63 hex digits behind src2:.
|
||||
var prefixFP = regexp.MustCompile(`^src2:[0-9a-f]{12,64}$`)
|
||||
|
||||
// version reads the version a put names: newest, or a fingerprint whole or by its first 12 hex digits. The tool reads nothing:
|
||||
// the program resolves newest to the end kept for the node's branch, and a prefix among the builds it hears, at the put's first
|
||||
// step (design 47 H2b §833, §834; H-A-848, H-A-862).
|
||||
func (s *putTools) version(module, version string) (string, error) {
|
||||
v := strings.ToLower(strings.TrimSpace(version))
|
||||
switch {
|
||||
case v == "newest":
|
||||
// Asked of the indexer's first view of modules, never read from its bus state (ADR 0596, ADR 0621; issue 1966).
|
||||
mods, err := indexerView(s.ask, indexerModules)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the indexer's modules cannot be read: %w", err)
|
||||
}
|
||||
raw, found := mods[module]
|
||||
if !found {
|
||||
return "", fmt.Errorf("the indexer holds no module %s at the trunk", module)
|
||||
}
|
||||
m, err := meshcatalogclient.DecodeModule(raw)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the indexer's %s cannot be read: %w", module, err)
|
||||
}
|
||||
if m.Fp2 == "" {
|
||||
return "", fmt.Errorf("the indexer holds no fingerprint of the new form for %s: %s", module, m.None2)
|
||||
}
|
||||
return m.Fp2, nil
|
||||
case fullFP.MatchString(v):
|
||||
if v == puts.Newest || fullFP.MatchString(v) || prefixFP.MatchString(v) {
|
||||
return v, nil
|
||||
}
|
||||
return "", fmt.Errorf("%q is no version: newest, a fingerprint (src2: and 64 hex digits) whole", version)
|
||||
return "", fmt.Errorf("%q is no version of %s: newest (the version whose pipeline passed), or a fingerprint (src2: and 64 hex digits, or at least its first 12)", version, module)
|
||||
}
|
||||
|
||||
// putAnswer is what assigner_put and assigner_puts answer of one put.
|
||||
@@ -155,7 +140,7 @@ func (s *putTools) doPut(args map[string]any, by string) (any, error) {
|
||||
return nil, fmt.Errorf("the put of %s on %s cannot be read: %w", module, node, err)
|
||||
} else if found {
|
||||
if before, err := puts.Decode(raw); err == nil && !puts.Ended(before.Step) {
|
||||
if before.FP == fp && before.Hold == hold {
|
||||
if (before.FP == fp || (puts.Unresolved(fp) && fp != puts.Newest && strings.HasPrefix(before.FP, fp))) && before.Hold == hold {
|
||||
a := answerOf(node, module, before)
|
||||
a.Follow = followPut(node, module)
|
||||
return a, nil
|
||||
@@ -332,7 +317,7 @@ func (s *putTools) tools() []stdio.Tool {
|
||||
Input: schema(map[string]string{
|
||||
"node": "the machine, where the module is assigned",
|
||||
"module": "the module",
|
||||
"version": "newest, a fingerprint (src2: and 64 hex digits), or at least its first 12 hex digits",
|
||||
"version": "newest (the version of the node's branch whose pipeline passed), a fingerprint (src2: and 64 hex digits), or at least its first 12 hex digits",
|
||||
"hold": "\"true\": the want stays at this version until released; \"false\" (the default): the rules move it again once it runs",
|
||||
"why": "why, kept with the put and said in any ask",
|
||||
}, []string{"node", "module", "version", "why"}, "hold"),
|
||||
@@ -409,14 +394,19 @@ func serveTools() error {
|
||||
tools = append(tools, wants.tools()...)
|
||||
keeper := &inputKeeper{vals: stateobjects.ForState(buckets.InputsState), now: time.Now, logf: func(string, ...any) {}}
|
||||
tools = append(tools, inputsRead(keeper), inputsDrop(keeper, stdio.Ask))
|
||||
tools = append(tools, validateTools(stdio.Ask)...) // judge a pipeline's candidate on request, through the seat mesh-wants' verb validate (H-A-727)
|
||||
tools = append(tools, owedTools(stdio.Ask)...) // the owed events, through the seat mesh-wants' verbs (§832 6.)
|
||||
tools = append(tools, compositionsTools(stdio.Ask)...) // the composition runs' read and drop, through their verbs (§728)
|
||||
tools = append(tools, viewTools(os.Getenv, keptSource, time.Now)...)
|
||||
// What each node's engine reads, as the assigner uses it: its own state engine-reads (design 47 H-A-104).
|
||||
tools = append(tools, engineReadsTools(runtimeStore{})...)
|
||||
tools = append(tools, writtenTools(runtimeStore{})...)
|
||||
tools = append(tools, progressDropTools(runtimeStore{}, stdio.Ask)...) // a tier progress whose tier never runs (§824 7.)
|
||||
tools = append(tools, waitDropTools(runtimeStore{}, stdio.Ask)...) // a decided wait record (§830 2.)
|
||||
tools = append(tools, whyTools(runtimeStore{})...)
|
||||
tools = append(tools, askAgainTools(runtimeStore{}, stdio.Ask, time.Now)...)
|
||||
tools = append(tools, wantDropTools(runtimeStore{}, stdio.Ask)...)
|
||||
tools = append(tools, assignmentDropTools(runtimeStore{}, stdio.Ask, watchedModules(stdio.Ask))...) // a retired module's assignment key (H-A-509)
|
||||
tools = append(tools, asksTools(stdio.QueueWaiting, stdio.State(process.TakenState), stdio.Ask)...) // the seat's work queue (§777)
|
||||
tools = append(tools, keepNowTools(stdio.Ask)...)
|
||||
tools = append(tools, validateBeforeTools(runtimeStore{})...) // what a validate step did not count (§814) // the keeping by hand (§813 (2))
|
||||
|
||||
@@ -13,13 +13,17 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
ne "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/graph"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"mesh-delivery-assigner/internal/buckets"
|
||||
@@ -75,7 +79,7 @@ func (r *compositionRun) validate(ctx context.Context, id string, step meshwants
|
||||
return couldNotRun("the validate run " + key + " is not joined: " + err.Error())
|
||||
}
|
||||
if j.started {
|
||||
go r.startValidate(ctx, key, j.run, step)
|
||||
go r.startValidate(r.own, key, j.run, step) // on the assigner's own context (H-A-630 (3))
|
||||
}
|
||||
return r.readValidate(ctx, key, step)
|
||||
}
|
||||
@@ -92,8 +96,7 @@ func (r *compositionRun) resumeValidate(ctx context.Context, _ string, step mesh
|
||||
// readValidate waits for the end of the validate run of key and judges the step from it.
|
||||
func (r *compositionRun) readValidate(ctx context.Context, key string, step meshwants.StepRun) stepOutcome {
|
||||
setShared(ctx, r.runs.sharedOf([]string{key}, nil))
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseRun)
|
||||
run := r.runs.await(ctx, []string{key})[key]
|
||||
run := r.runs.awaitEach(ctx, []string{key}, r.sayingWaits(ctx, "the validate step of "+step.Module))[key]
|
||||
setPhase(ctx, meshwants.StepProgressEventPhaseReport)
|
||||
out := r.judgeValidate(ctx, step, run)
|
||||
out.Shared = r.runs.sharedOf([]string{key}, map[string]meshwants.CompositionRun{key: run})
|
||||
@@ -125,7 +128,13 @@ func (r *compositionRun) judgeValidate(ctx context.Context, step meshwants.StepR
|
||||
if half.Revision.Base <= 0 {
|
||||
empty = emptyBeforeWords
|
||||
}
|
||||
if problems := causedProblems(v.Change, v.Before); len(problems) > 0 {
|
||||
// H-A-682 (5): the node-engine's own build is refused, never held; the run adds the problem to its verdict, for the mover's
|
||||
// manifest, so the run kept in composition-runs holds it and every step reads it as it reads the validator's.
|
||||
if needs := r.engineNeedProblems(half)[step.Module]; len(needs) > 0 {
|
||||
v = r.keepEngineNeeds(step, v, needs)
|
||||
}
|
||||
problems := causedProblems(v.Change, v.Before)
|
||||
if len(problems) > 0 {
|
||||
said := reasonManifestRefused + ": " + strings.Join(problems, "; ")
|
||||
if empty != "" {
|
||||
said += " (" + empty + ")"
|
||||
@@ -135,6 +144,105 @@ func (r *compositionRun) judgeValidate(ctx context.Context, step meshwants.StepR
|
||||
return stepOutcome{Outcome: meshwants.StepEndedOutcomePassed, Said: empty}
|
||||
}
|
||||
|
||||
// keepEngineNeeds adds needs, the problems of step's module, to the verdict the validate run of its revision keeps, as the refusal of
|
||||
// that module's manifest in the change case (none the verdict holds already), and answers the verdict as it is then; where the run
|
||||
// cannot be written, the verdict it was read as with them added, said in the journal.
|
||||
func (r *compositionRun) keepEngineNeeds(step meshwants.StepRun, read validateVerdict, needs []string) validateVerdict {
|
||||
add := func(v *validateVerdict) bool {
|
||||
m := v.Change.Manifests[step.Module]
|
||||
held := strings.Split(m.Refused, "\n")
|
||||
changed := false
|
||||
for _, p := range needs {
|
||||
if !slices.Contains(held, p) {
|
||||
held, changed = append(held, p), true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
m.Accepted, m.Refused = false, strings.Join(slices.DeleteFunc(held, func(p string) bool { return p == "" }), "\n")
|
||||
if v.Change.Manifests == nil {
|
||||
v.Change.Manifests = map[string]composer.ManifestRead{}
|
||||
}
|
||||
v.Change.Manifests[step.Module] = m
|
||||
return true
|
||||
}
|
||||
if !add(&read) {
|
||||
return read
|
||||
}
|
||||
key, err := validateKeyOf(step)
|
||||
if err == nil {
|
||||
_, _, err = r.runs.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
var v validateVerdict
|
||||
if raw, e := json.Marshal(c.Verdict); e != nil || json.Unmarshal(raw, &v) != nil || !add(&v) {
|
||||
return false
|
||||
}
|
||||
verdict, e := v.asVerdict()
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
c.Verdict = verdict
|
||||
return true
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
r.logf("the validate run's verdict is not written with the problems of %s: %v", step.Module, err)
|
||||
}
|
||||
return read
|
||||
}
|
||||
|
||||
// engineNeedProblems are, by module, the problems of the revision's entries that claim the seat node-engine and need a reader capability
|
||||
// that no node's words in the state engine-reads hold: such an engine would be held on every machine and none could state it, so its
|
||||
// validate run refuses it (design 47 H2 H-A-682 (5)), counted as a new problem. None while no node's words are held.
|
||||
func (r *compositionRun) engineNeedProblems(half mcc.Half) map[string][]string {
|
||||
if r.engineReads == nil {
|
||||
return nil
|
||||
}
|
||||
var stated []string
|
||||
nodes := r.engineReads.nodes()
|
||||
for _, node := range nodes {
|
||||
words, _ := r.engineReads.words(node)
|
||||
stated = append(stated, words...)
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := map[string][]string{}
|
||||
for module, e := range half.Entries {
|
||||
if !claimsSeat(e.Manifest, ne.Seat) {
|
||||
continue
|
||||
}
|
||||
for _, need := range e.Needs {
|
||||
if !slices.Contains(stated, need) {
|
||||
out[module] = append(out[module], "needs "+need+", which no node-engine states")
|
||||
}
|
||||
}
|
||||
slices.Sort(out[module])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// claimsSeat says whether a manifest, as the catalog entry keeps it, claims the seat.
|
||||
func claimsSeat(manifest map[string]any, seat string) bool {
|
||||
raw, err := json.Marshal(manifest)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var m struct {
|
||||
Claims []struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"claims"`
|
||||
}
|
||||
if json.Unmarshal(raw, &m) != nil {
|
||||
return false
|
||||
}
|
||||
return slices.ContainsFunc(m.Claims, func(c struct {
|
||||
Name string `json:"name"`
|
||||
}) bool {
|
||||
return c.Name == seat
|
||||
})
|
||||
}
|
||||
|
||||
// emptyBeforeWords say, in a validate step's end, that its revision names no base: the branch's first take-in, judged against
|
||||
// an empty case before (H-A-151, H-A-154).
|
||||
const emptyBeforeWords = "the case before is empty: the revision names no base, the branch's first take-in"
|
||||
@@ -251,6 +359,7 @@ func manifestsOf(half mcc.Half) (map[string]composer.Manifest, error) {
|
||||
// is kept once in `inputs`, its program and input recorded on the run, and one run ask put on the Go build seat. A fault ends
|
||||
// the run could not run.
|
||||
func (r *compositionRun) startValidate(ctx context.Context, key string, run meshwants.CompositionRun, step meshwants.StepRun) {
|
||||
ctx = withReadsClock(ctx) // all the run's reads stop at one deadline (design 47 H2 H-A-708 (3))
|
||||
ask := run.Ask
|
||||
end := func(outcome, said string, verdict map[string]any) {
|
||||
if _, err := r.runs.endRun(key, ask, outcome, said, verdict); err != nil {
|
||||
@@ -288,6 +397,13 @@ func (r *compositionRun) startValidate(ctx context.Context, key string, run mesh
|
||||
return
|
||||
}
|
||||
program.Package = validatorPackage
|
||||
pins, said, ok := r.awaitPins(ctx, key, ask, "the manifest validator's entry "+entry.Fp, pinsOfEntry(entry), publishersOf(half.Entries))
|
||||
if !ok {
|
||||
if said != "" { // else the run ended or was replaced while it waited, or the step's wait ended
|
||||
couldNot(said)
|
||||
}
|
||||
return
|
||||
}
|
||||
seats, list, err := r.validateSeats(ctx, ask, half.Revision.Definitions)
|
||||
if err != nil {
|
||||
couldNot(err.Error())
|
||||
@@ -321,20 +437,27 @@ func (r *compositionRun) startValidate(ctx context.Context, key string, run mesh
|
||||
couldNot(err.Error())
|
||||
return
|
||||
}
|
||||
if _, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
waited := false
|
||||
written, _, err := r.runs.change(key, func(c *meshwants.CompositionRun) bool {
|
||||
waited = false
|
||||
if c.Ask != ask || c.Ended != nil {
|
||||
return false
|
||||
}
|
||||
c.Program = &meshwants.CompositionRunProgram{Repository: program.Repository, Commit: program.Commit, Directory: program.Dir, Fingerprint: entry.Fp}
|
||||
c.Input = digest
|
||||
waited, c.Waits = c.Waits != nil, nil // its wait ends as its run ask is put (H-A-629 (1))
|
||||
return true
|
||||
}); err != nil {
|
||||
})
|
||||
if err != nil {
|
||||
couldNot("the run's program and input are not written: " + err.Error())
|
||||
return
|
||||
}
|
||||
if waited { // its readers wait for a build node again, no longer for the package's publish (H-A-632)
|
||||
r.runs.sayWaitsAtPut(written)
|
||||
}
|
||||
a := buildstep.StepAsk{ID: ask, Kind: buildstep.AskCheck, Language: buildstep.AskGo, Asker: runAsker, At: r.now().UTC(),
|
||||
Run: &buildstep.RunJob{Program: program, Heads: []buildstep.RunHead{}, Input: ref, Reader: "the manifest validator of " + step.Pipeline + " at " + program.Commit},
|
||||
Packages: pinsOfEntry(entry)} // the validator is built against its entry's pins at the step's revision (H-A-203, H-A-192, H-A-205)
|
||||
Packages: pins} // the validator is built against its entry's pins at the step's revision, each empty one filled (H-A-203, H-A-192, H-A-205, H-A-628 (2))
|
||||
if err := r.put(ctx, a); err != nil {
|
||||
couldNot("its run ask " + ask + " is not put: " + err.Error())
|
||||
}
|
||||
@@ -425,7 +548,7 @@ const seatListKey = "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbSeatList
|
||||
// seat-list hands, asked as a kept call under the run's ask.
|
||||
func (r *compositionRun) validateSeats(ctx context.Context, ask string, defs []meshcatalog.CatalogRevisionDefinitionsItem) ([]json.RawMessage, string, error) {
|
||||
if len(defs) == 0 {
|
||||
return r.seatList(ask)
|
||||
return r.seatList(ctx, ask)
|
||||
}
|
||||
sorted := slices.Clone(defs)
|
||||
slices.SortStableFunc(sorted, func(a, b meshcatalog.CatalogRevisionDefinitionsItem) int { return strings.Compare(a.Seat, b.Seat) })
|
||||
@@ -453,8 +576,12 @@ func seatListDigest(raw []byte) string {
|
||||
// seatList is the trunk's seat list as the verb seat-list hands it (H-A-443): its digest and size, then the object's bytes in
|
||||
// chunks; bytes whose size or sha256 is not the answer's, or that are no JSON array, are refused, so every run of one digest
|
||||
// judges the same bytes.
|
||||
func (r *compositionRun) seatList(ask string) ([]json.RawMessage, string, error) {
|
||||
func (r *compositionRun) seatList(ctx context.Context, ask string) ([]json.RawMessage, string, error) {
|
||||
what := "the trunk's seat list is not read through " + seatListKey
|
||||
left, bound, _ := r.readsLeft(readsClockOf(ctx))
|
||||
if left <= 0 {
|
||||
return nil, "", errors.New(what + ": the run's reads passed their deadline of " + bound.String() + " (the setting reads-bound)")
|
||||
}
|
||||
if r.callFile == nil {
|
||||
return nil, "", errors.New(what + ": the assigner holds no chunked call")
|
||||
}
|
||||
@@ -462,8 +589,11 @@ func (r *compositionRun) seatList(ask string) ([]json.RawMessage, string, error)
|
||||
if _, err := rand.Read(bits[:]); err != nil {
|
||||
return nil, "", fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
raw, err := r.callFile(process.KeptAsk{ID: ask + "." + meshcatalog.VerbSeatList, Bound: readsBound}, seatListKey,
|
||||
id := readFindingID(seatListKey)
|
||||
r.waiting(id, +1)
|
||||
raw, err := r.callFile(process.KeptAsk{ID: ask + "." + meshcatalog.VerbSeatList, Bound: left, Hook: r.readHook}, seatListKey,
|
||||
meshcatalog.SeatListInput{Call: hex.EncodeToString(bits[:])})
|
||||
r.waiting(id, -1)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
@@ -491,3 +621,203 @@ func (r *compositionRun) seatList(ask string) ([]json.RawMessage, string, error)
|
||||
}
|
||||
return list, a.Digest, nil
|
||||
}
|
||||
|
||||
// validateTool is the tool that judges a pipeline's candidate on request (design 47 H2 H-A-684, H-A-702, H-A-727).
|
||||
const validateTool = "assigner_validate"
|
||||
|
||||
// showKey is the seat mesh-pipeline-runner's verb show, which names a pipeline's candidate (H-A-684 (1), H-A-739).
|
||||
const showKey = "seat:" + mpr.Seat + "." + mpr.VerbShow
|
||||
|
||||
// validateVerbKey is the seat mesh-wants' verb validate, answered by the assigner's process, which keeps the runs (H-A-727).
|
||||
const validateVerbKey = "seat:" + meshwants.Seat + "." + meshwants.VerbValidate
|
||||
|
||||
// validateOnRequest is the process's answer of the seat mesh-wants' verb validate: it reads the pipeline's candidate from the runner's
|
||||
// `show` (H-A-739), answers at once, starting nothing, a pipeline the runner does not know and a candidate the indexer does not
|
||||
// hold; for a run that has ended it answers its verdict, narrowed by the module; otherwise it records the hand act through the seat
|
||||
// mesh-hand-acts with its why (H-A-702) and joins or starts the run `<pipeline>.validate` as the step does (H-A-684 (1), H-A-727),
|
||||
// and answers the run as it stands.
|
||||
func (r *compositionRun) validateOnRequest(ctx context.Context, record func(meshhandactsclient.Request) error, caller string, in meshwants.ValidateInput) (meshwants.ValidateAnswer, error) {
|
||||
why, pipeline := strings.TrimSpace(in.Why), strings.TrimSpace(in.Pipeline)
|
||||
if pipeline == "" || why == "" {
|
||||
return meshwants.ValidateAnswer{}, errors.New("name the pipeline and why its candidate is judged")
|
||||
}
|
||||
couldNot := func(words string) (meshwants.ValidateAnswer, error) {
|
||||
return meshwants.ValidateAnswer{Outcome: meshwants.ValidateAnswerOutcomeCouldNotRun, Why: words}, nil
|
||||
}
|
||||
body, said, err := r.callRead(withReadsClock(ctx), showKey, mpr.ShowInput{Pipeline: pipeline, Bound: 4096})
|
||||
if err != nil {
|
||||
return couldNot("the runner's show of " + pipeline + " is not read: " + err.Error())
|
||||
}
|
||||
if body == nil {
|
||||
return couldNot("the runner knows no pipeline " + pipeline + ": " + said)
|
||||
}
|
||||
var shown mpr.ShowAnswer
|
||||
if err := json.Unmarshal(body, &shown); err != nil || shown.Pipeline.Pipeline == "" {
|
||||
return couldNot("the runner's show of " + pipeline + " names no pipeline")
|
||||
}
|
||||
p := shown.Pipeline
|
||||
step := meshwants.StepRun{Pipeline: pipeline, Branch: p.Branch, Revision: p.Revision, Run: p.Run, Source: p.Source, Module: strings.TrimSpace(in.Module),
|
||||
Step: meshwants.StepRunStepValidate}
|
||||
candidate, err := candidateKeyOf(step)
|
||||
if err != nil {
|
||||
return couldNot("the pipeline " + pipeline + " names no candidate: " + err.Error())
|
||||
}
|
||||
if in.Candidate != "" && in.Candidate != candidate {
|
||||
return couldNot(fmt.Sprintf("the candidate %s is not the pipeline %s's, %s", in.Candidate, pipeline, candidate))
|
||||
}
|
||||
half, err := r.revision(withReadsClock(ctx), step)
|
||||
if err != nil {
|
||||
return couldNot(fmt.Sprintf("the indexer holds no candidate %s of the pipeline %s: %v", candidate, pipeline, err))
|
||||
}
|
||||
key, err := validateKeyOf(step)
|
||||
if err != nil {
|
||||
return couldNot(err.Error())
|
||||
}
|
||||
run, _, ok, err := r.runs.read(key)
|
||||
if err != nil {
|
||||
return meshwants.ValidateAnswer{}, err
|
||||
}
|
||||
if !ok || run.Ended == nil {
|
||||
if err := record(meshhandactsclient.Request{What: meshwants.VerbValidate + " " + key, Why: why + " (" + caller + ")", Cause: "validate"}); err != nil {
|
||||
return meshwants.ValidateAnswer{}, fmt.Errorf("the hand act was not recorded, so no run was started: %w", err)
|
||||
}
|
||||
now := r.now().UTC()
|
||||
reader := readerOf("validate."+buildstep.NewID(), step)
|
||||
reader.Ended = &now // a reader of a hand act owes no step end; the run's later steps join it
|
||||
j, err := r.runs.joinAt(key, reader, candidate, "", buildstep.NewID())
|
||||
if err != nil {
|
||||
return meshwants.ValidateAnswer{}, fmt.Errorf("the validate run %s is not joined: %w", key, err)
|
||||
}
|
||||
if j.started {
|
||||
go r.startValidate(r.own, key, j.run, step)
|
||||
}
|
||||
if run, _, ok, err = r.runs.read(key); err != nil || !ok {
|
||||
run = j.run
|
||||
}
|
||||
}
|
||||
run.Key = key
|
||||
return validateAnswerOf(run, step.Module, r.engineNeedProblems(half))
|
||||
}
|
||||
|
||||
// validateAnswerOf is the validate run as it stands: running with its start, or its end: passed, failed `cycle` naming the
|
||||
// cycle, failed `manifest-refused` with every problem per manifest (those the case before holds too marked), or could not run with
|
||||
// why; the problems narrowed to module when one is named (H-A-684 (1)).
|
||||
func validateAnswerOf(run meshwants.CompositionRun, module string, engine map[string][]string) (meshwants.ValidateAnswer, error) {
|
||||
out := meshwants.ValidateAnswer{Run: &run}
|
||||
if run.Ended == nil {
|
||||
out.Outcome, out.Started = meshwants.ValidateAnswerOutcomeRunning, run.Started
|
||||
return out, nil
|
||||
}
|
||||
if run.Outcome != meshwants.CompositionRunOutcomePassed {
|
||||
out.Outcome, out.Why = meshwants.ValidateAnswerOutcomeCouldNotRun, run.Said
|
||||
return out, nil
|
||||
}
|
||||
var v validateVerdict
|
||||
if raw, err := json.Marshal(run.Verdict); err != nil || json.Unmarshal(raw, &v) != nil {
|
||||
out.Outcome, out.Why = meshwants.ValidateAnswerOutcomeCouldNotRun, "the validate run's verdict does not read"
|
||||
return out, nil
|
||||
}
|
||||
if len(v.Cycle) > 0 {
|
||||
out.Outcome, out.Reason = meshwants.ValidateAnswerOutcomeFailed, meshwants.ValidateAnswerReasonCycle
|
||||
for _, a := range v.Cycle {
|
||||
out.Cycle = append(out.Cycle, string(a))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
counted := false
|
||||
for _, name := range slices.Sorted(maps.Keys(v.Change.Manifests)) {
|
||||
read := v.Change.Manifests[name]
|
||||
if read.Accepted || read.Refused == "" || (module != "" && name != module) {
|
||||
continue
|
||||
}
|
||||
held := map[string]bool{}
|
||||
for _, p := range strings.Split(v.Before.Manifests[name].Refused, "\n") {
|
||||
held[p] = true
|
||||
}
|
||||
for _, p := range strings.Split(read.Refused, "\n") {
|
||||
if p != "" {
|
||||
out.Problems = append(out.Problems, meshwants.ValidateAnswerProblemsItem{Module: name, Problem: p, Before: held[p]})
|
||||
counted = counted || !held[p]
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, name := range slices.Sorted(maps.Keys(engine)) { // H-A-682 (5): a node-engine's needs no node-engine states
|
||||
if module != "" && name != module {
|
||||
continue
|
||||
}
|
||||
for _, p := range engine[name] {
|
||||
if slices.ContainsFunc(out.Problems, func(q meshwants.ValidateAnswerProblemsItem) bool { return q.Module == name && q.Problem == p }) {
|
||||
continue // the run's verdict holds it already
|
||||
}
|
||||
out.Problems = append(out.Problems, meshwants.ValidateAnswerProblemsItem{Module: name, Problem: p})
|
||||
counted = true
|
||||
}
|
||||
}
|
||||
out.Outcome = meshwants.ValidateAnswerOutcomePassed
|
||||
if counted {
|
||||
out.Outcome, out.Reason = meshwants.ValidateAnswerOutcomeFailed, meshwants.ValidateAnswerReasonManifestRefused
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// validateTools is the module's tool assigner_validate: it reads the pipeline's candidate from the seat mesh-pipeline-runner's `show`
|
||||
// (answering a pipeline the runner does not know, starting nothing), then calls the seat mesh-wants' verb validate, which the
|
||||
// process answers; it writes no state and answers what the verb answers (H-A-727).
|
||||
func validateTools(ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
|
||||
return []stdio.Tool{{Name: validateTool, Description: "Judge a manifest on request (design 47 H2 H-A-684, H-A-702): the manifest validator's verdict " +
|
||||
"on a pipeline's candidate, a delivering pipeline's or a run on request's, the one revision's manifests together. It joins or starts the " +
|
||||
"validate run `<pipeline>.validate` as the step does, so the pipeline's own validate step joins it, recorded as a hand act with why, " +
|
||||
"and answers at once the run as it stands: running, passed, failed (cycle, or manifest-refused with every problem per manifest, those " +
|
||||
"the case before holds too marked) or could-not-run. A pipeline the runner does not know, or a candidate the indexer does not hold, " +
|
||||
"is answered so and starts nothing; a run on request's later steps run until its cancel.",
|
||||
Input: schema(map[string]string{"pipeline": "the pipeline's key as the runner names it", "module": "narrows the answer to one module's manifest", "why": "why the candidate is judged, kept in the hand act"},
|
||||
[]string{"pipeline", "why"}),
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
pipeline, why := strings.TrimSpace(arg(args, "pipeline")), strings.TrimSpace(arg(args, "why"))
|
||||
if pipeline == "" || why == "" {
|
||||
return nil, errors.New("name the pipeline and why its candidate is judged")
|
||||
}
|
||||
body, said, err := unwrapAnswer(ask(showKey, mpr.ShowInput{Pipeline: pipeline, Bound: 4096}))
|
||||
if err != nil || body == nil {
|
||||
return meshwants.ValidateAnswer{Outcome: meshwants.ValidateAnswerOutcomeCouldNotRun, Why: "the runner knows no pipeline " + pipeline + ": " + orWords(said, err)}, nil
|
||||
}
|
||||
var shown mpr.ShowAnswer
|
||||
if err := json.Unmarshal(body, &shown); err != nil || shown.Pipeline.Pipeline == "" {
|
||||
return meshwants.ValidateAnswer{Outcome: meshwants.ValidateAnswerOutcomeCouldNotRun, Why: "the runner's show of " + pipeline + " names no pipeline"}, nil
|
||||
}
|
||||
p := shown.Pipeline
|
||||
candidate, err := candidateKeyOf(meshwants.StepRun{Branch: p.Branch, Revision: p.Revision, Run: p.Run})
|
||||
if err != nil {
|
||||
return meshwants.ValidateAnswer{Outcome: meshwants.ValidateAnswerOutcomeCouldNotRun, Why: "the pipeline " + pipeline + " names no candidate: " + err.Error()}, nil
|
||||
}
|
||||
raw, err := ask(validateVerbKey, meshwants.ValidateInput{Pipeline: pipeline, Candidate: candidate, Module: strings.TrimSpace(arg(args, "module")), Why: why})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out any
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("validate answered what is not JSON: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}}}
|
||||
}
|
||||
|
||||
// unwrapAnswer reads a verb's answer as a tool call gave it: the body of a good answer, else the holder's words; err when the call
|
||||
// failed.
|
||||
func unwrapAnswer(raw json.RawMessage, err error) (json.RawMessage, string, error) {
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
body, said, ok := buscalls.Unwrap(raw)
|
||||
if !ok {
|
||||
return nil, said, nil
|
||||
}
|
||||
return body, "", nil
|
||||
}
|
||||
|
||||
func orWords(said string, err error) string {
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
@@ -11,8 +11,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
mcc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
builds "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
mpr "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
|
||||
@@ -32,6 +35,8 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
indexer := meshcatalog.CatalogEntry{Module: "indexer", Repository: "novox/mesh-delivery", Commit: commitE3, Path: "modules/mesh-delivery-indexer",
|
||||
Fp: "src2:ix", Serves: []string{"seat:" + meshcatalog.Seat + ".revision"}, Manifest: map[string]any{"module": "indexer"}, ManifestDigest: "d-ix",
|
||||
Packages: map[string]string{"git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient": "v0.1.4"}}
|
||||
unpinned := indexer
|
||||
unpinned.Packages = map[string]string{"git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient": "v0.1.4", "git.novox.be/novox/mesh-sdk/go": ""}
|
||||
entry := func(module, digest string, edges ...meshcatalog.Edge) meshcatalog.CatalogEntry {
|
||||
return meshcatalog.CatalogEntry{Module: module, Manifest: map[string]any{"module": module, "d": digest}, ManifestDigest: digest, Edges: edges}
|
||||
}
|
||||
@@ -41,7 +46,13 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
9: {indexer, entry("a", "d-a", meshcatalog.Edge{From: "a:x", To: "b:y", Kind: 3}, meshcatalog.Edge{From: "b:y", To: "a:x", Kind: 3}), entry("b", "d-b")},
|
||||
3: {indexer},
|
||||
12: {indexer, entry("web", "d-web-2"), entry("db", "d-db")},
|
||||
// 1984/AC10: the validator's entry names mesh-sdk/go with no version, and mesh-sdk's build in the revision publishes it.
|
||||
13: {unpinned, entry("web", "d-web-2"), entry("db", "d-db"), {Module: "mesh-sdk", Fp: "src2:sdk1",
|
||||
Artifacts: []meshcatalog.Artifact{{Ref: "mesh-sdk:go", Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "git.novox.be/novox/mesh-sdk/go"}}}}},
|
||||
}
|
||||
revisions[14] = revisions[13] // H-A-630 (3): its validate run waits for mesh-sdk's publish
|
||||
var sdkMu sync.Mutex
|
||||
sdkUnpublished := false
|
||||
// base is the newest kept revision below n, as the take-in names it; none below the first. Revision 12 names 7 with 8 to 11
|
||||
// never kept, so a case before read as the number minus one could not run (H-A-154).
|
||||
base := func(n int64) (b int64) {
|
||||
@@ -55,9 +66,24 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
}
|
||||
return b
|
||||
}
|
||||
// The runner's show of each pipeline it knows (H-A-739): a delivering pipeline's, a run on request's, and one whose candidate the
|
||||
// indexer holds not.
|
||||
shown := map[string]mpr.Pipeline{
|
||||
"main.12": {Pipeline: "main.12", Branch: "main", Revision: 12, Source: 12},
|
||||
"main.run.r1": {Pipeline: "main.run.r1", Branch: "main", Revision: 7, Run: "r1"},
|
||||
"main.50": {Pipeline: "main.50", Branch: "main", Revision: 50, Source: 50},
|
||||
}
|
||||
call := func(key string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
switch key {
|
||||
case showKey:
|
||||
var in mpr.ShowInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
p, ok := shown[in.Pipeline]
|
||||
if !ok {
|
||||
return json.Marshal(map[string]string{"error": "no pipeline " + in.Pipeline})
|
||||
}
|
||||
return json.Marshal(mpr.ShowAnswer{Pipeline: p})
|
||||
case mcc.RevisionVerb:
|
||||
var in meshcatalog.RevisionInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
@@ -74,6 +100,18 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
Definitions: defs}, Entries: entries})
|
||||
case seatDefinitionsKey:
|
||||
return json.Marshal(meshcatalog.SeatDefinitionsAnswer{Found: true, Entry: &meshcatalog.SeatDefinitionsAnswerEntry{Seat: "s1", Digest: "sd", Definition: map[string]any{"seat": "s1"}}})
|
||||
case publishedVerbKey:
|
||||
var in builds.PublishedInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
if in != (builds.PublishedInput{Module: "mesh-sdk", Artifact: "mesh-sdk:go", Fingerprint: "src2:sdk1"}) {
|
||||
return nil, errors.New("published asked of another build")
|
||||
}
|
||||
sdkMu.Lock()
|
||||
defer sdkMu.Unlock()
|
||||
if sdkUnpublished {
|
||||
return json.Marshal(builds.PublishedAnswer{})
|
||||
}
|
||||
return json.Marshal(builds.PublishedAnswer{Published: true, Version: "0.1.36"})
|
||||
}
|
||||
return nil, errors.New("no such verb " + key)
|
||||
}
|
||||
@@ -98,7 +136,15 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
var requests []composer.Request
|
||||
keeper := testKeeper(&objectsMem{objs: map[string][]byte{}}, time.Now)
|
||||
runs := newCompositionRuns(newRunsMem(), defaultRunSettings, time.Now, t.Logf)
|
||||
r := &compositionRun{runs: runs, keeper: keeper, reads: &compositionReads{}, call: call, callFile: callFile, now: time.Now, logf: t.Logf,
|
||||
var held []string // the wait-helds of the reader ask-left said, what each waits on and its id (H-A-630 (5), H-A-632)
|
||||
runs.owe = func(_, event string, body any, id string) {
|
||||
if w := body.(meshwants.Wait); event == meshwants.EventWaitHeld && strings.Contains(id, ".ask-left.") {
|
||||
mu.Lock()
|
||||
held = append(held, w.On+" ("+id+")")
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
r := &compositionRun{runs: runs, keeper: keeper, reads: &compositionReads{}, call: asKept(call), callFile: callFile, own: context.Background(), now: time.Now, logf: t.Logf,
|
||||
put: func(_ context.Context, a buildstep.StepAsk) error {
|
||||
body, err := keeper.body(a.Run.Input.Digest)
|
||||
if err != nil {
|
||||
@@ -204,7 +250,7 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
{"an empty list", listAnswer([]byte(`[]`), seatListDigest([]byte(`[]`)), 2)},
|
||||
} {
|
||||
listed = row.answer
|
||||
if seats, digest, err := r.seatList("ask-row"); err == nil || !strings.Contains(err.Error(), seatListKey) {
|
||||
if seats, digest, err := r.seatList(context.Background(), "ask-row"); err == nil || !strings.Contains(err.Error(), seatListKey) {
|
||||
t.Errorf("%s: the seat list read %s %s, %v; want it refused, naming the verb", row.name, digest, seats, err)
|
||||
}
|
||||
}
|
||||
@@ -217,4 +263,160 @@ func TestTheValidateStepRefusesAManifestProblemAndACycle(t *testing.T) {
|
||||
} else if web := requests[2].Cases[1].Manifests["web"]; len(requests[2].Cases[1].Manifests) != 3 || !strings.Contains(string(web.Raw), "d-web-2") {
|
||||
t.Errorf("the case before of revision 12 is %+v, want base 7's manifests", requests[2].Cases[1].Manifests)
|
||||
}
|
||||
// 1984/AC10 (H-A-628 (2), (5)): the validator's pin with no version is filled from mesh-builds' published of its publisher's
|
||||
// build in the step's revision, never left out.
|
||||
if o := r.validate(ctx, "ask-unpinned", step("web", 13)); o.Outcome != meshwants.StepEndedOutcomeFailed || len(asks) != 4 {
|
||||
t.Errorf("a validator entry with an empty pin ended %+v (%d validator asks), want it judged", o, len(asks))
|
||||
} else if got := asks[3].Packages; len(got) != 2 || got["git.novox.be/novox/mesh-sdk/go"] != "v0.1.36" || got["git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"] != "v0.1.4" {
|
||||
t.Errorf("the validator is built against the pins %v; want mesh-sdk/go at v0.1.36 from published beside its entry's", got)
|
||||
}
|
||||
// H-A-630 (3): the validate run waits for mesh-sdk's publish on the assigner's own context, so the step that started it, ended
|
||||
// meanwhile, leaves it waiting: at the publish it is put and ends passed for the movers that read it.
|
||||
sdkMu.Lock()
|
||||
sdkUnpublished = true
|
||||
sdkMu.Unlock()
|
||||
journal := newLogLines()
|
||||
r.logf = journal.logf
|
||||
starting, stop := context.WithCancel(ctx)
|
||||
left := make(chan stepOutcome, 1)
|
||||
go func() { left <- r.validate(starting, "ask-left", step("web", 14)) }()
|
||||
journal.await(t, "waits for package git.novox.be/novox/mesh-sdk/go", 1)
|
||||
stop()
|
||||
if o := <-left; o.Outcome != meshwants.StepEndedOutcomeCouldNotRun {
|
||||
t.Errorf("the starting step stopped ended %+v", o)
|
||||
}
|
||||
sdkMu.Lock()
|
||||
sdkUnpublished = false
|
||||
sdkMu.Unlock()
|
||||
runs.heardPublished("mesh-sdk:go")
|
||||
key, _ := validateKeyOf(step("web", 14))
|
||||
run := runs.awaitEach(ctx, []string{key}, nil)[key]
|
||||
mu.Lock()
|
||||
if run.Ended == nil || run.Outcome != meshwants.CompositionRunOutcomePassed || len(asks) != 5 || asks[4].Packages["git.novox.be/novox/mesh-sdk/go"] != "v0.1.36" {
|
||||
t.Errorf("the validate run its starting step left ended %v %s %q with %d validator asks, want it put after the publish and passed", run.Ended, run.Outcome, run.Said, len(asks))
|
||||
}
|
||||
mu.Unlock()
|
||||
if len(held) < 2 || !strings.HasPrefix(held[len(held)-2], waitOnPublish+"git.novox.be/novox/mesh-sdk/go (") ||
|
||||
!strings.HasPrefix(held[len(held)-1], waitOnBuildNode+" (") || !strings.HasSuffix(held[len(held)-1], ".held.put)") {
|
||||
t.Errorf("the validate run's reader was said waiting %v; want mesh-sdk's publish, then a build node again at the put (H-A-632)", held)
|
||||
}
|
||||
|
||||
// H2 H-A-682 (5) (A4): a mover claiming the seat node-engine whose entry needs a capability no node's words hold ends
|
||||
// manifest-refused naming it, counted as new; one that a node states is not refused for it; the verb's answer lists it.
|
||||
engine := meshcatalog.CatalogEntry{Module: "engine", Fp: "src2:eng", Needs: []string{"directory-contents-owner"}, ManifestDigest: "d-eng",
|
||||
Manifest: map[string]any{"module": "engine", "claims": []any{map[string]any{"name": "node-engine"}}}}
|
||||
revisions[15], revisions[16] = []meshcatalog.CatalogEntry{indexer, engine}, []meshcatalog.CatalogEntry{indexer, engine}
|
||||
engineStep := func(revision int64) meshwants.StepRun {
|
||||
return meshwants.StepRun{Step: meshwants.StepRunStepValidate, Pipeline: "main." + string(rune('0'+revision)), Branch: "main", Module: "engine", Revision: revision, Source: revision}
|
||||
}
|
||||
r.engineReads = &engineReadsKept{by: map[string]engineWords{"ace": {Words: []string{"want:version"}}}}
|
||||
if o := r.validate(ctx, "ask-engine", engineStep(15)); o.Outcome != meshwants.StepEndedOutcomeFailed || !strings.HasPrefix(o.Said, reasonManifestRefused+": ") ||
|
||||
!strings.Contains(o.Said, "engine: needs directory-contents-owner, which no node-engine states") {
|
||||
t.Errorf("a node-engine needing what no node states ended %+v", o)
|
||||
}
|
||||
// The run kept in composition-runs holds the problem in its verdict, for the mover's manifest (H-A-682 (5)).
|
||||
if k, _ := validateKeyOf(engineStep(15)); true {
|
||||
kept, _, _, _ := r.runs.read(k)
|
||||
var v validateVerdict
|
||||
raw, _ := json.Marshal(kept.Verdict)
|
||||
if json.Unmarshal(raw, &v) != nil || v.Change.Manifests["engine"].Accepted || !strings.Contains(v.Change.Manifests["engine"].Refused, "needs directory-contents-owner, which no node-engine states") {
|
||||
t.Errorf("the kept validate run's verdict is %+v, want the engine's manifest refused for its need", kept.Verdict)
|
||||
}
|
||||
}
|
||||
r.engineReads = &engineReadsKept{by: map[string]engineWords{"ace": {Words: []string{"want:version"}}, "g14": {Words: []string{"directory-contents-owner"}}}}
|
||||
if o := r.validate(ctx, "ask-engine-2", engineStep(16)); strings.Contains(o.Said, "which no node-engine states") {
|
||||
t.Errorf("a node-engine needing what g14 states ended %+v", o)
|
||||
}
|
||||
ended := time.Now()
|
||||
passed := meshwants.CompositionRun{Started: &ended, Ended: &ended, Outcome: meshwants.CompositionRunOutcomePassed, Verdict: map[string]any{}}
|
||||
if a, _ := validateAnswerOf(passed, "", map[string][]string{"engine": {"needs directory-contents-owner, which no node-engine states"}}); a.Outcome != meshwants.ValidateAnswerOutcomeFailed ||
|
||||
len(a.Problems) != 1 || a.Problems[0].Before || a.Problems[0].Module != "engine" {
|
||||
t.Errorf("the verb's answer for a node-engine needing what none states is %+v", a)
|
||||
}
|
||||
// H2 H-A-684, H-A-702, H-A-727, H-A-739 (A5): the verb validate, which the tool assigner_validate calls, joins or starts the run.
|
||||
var acts []meshhandactsclient.Request
|
||||
record := func(q meshhandactsclient.Request) error { acts = append(acts, q); return nil }
|
||||
onRequest := func(pipeline, module, why string) meshwants.ValidateAnswer {
|
||||
t.Helper()
|
||||
a, err := r.validateOnRequest(ctx, record, "op@shanks", meshwants.ValidateInput{Pipeline: pipeline, Module: module, Why: why})
|
||||
if err != nil {
|
||||
t.Fatalf("validate of %s: %v", pipeline, err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
if _, err := r.validateOnRequest(ctx, record, "op", meshwants.ValidateInput{Pipeline: "main.12"}); err == nil || len(acts) != 0 {
|
||||
t.Errorf("a call with no why is not refused (%v), or recorded %d hand acts", err, len(acts))
|
||||
}
|
||||
mu.Lock()
|
||||
asked := len(asks)
|
||||
mu.Unlock()
|
||||
if a := onRequest("main.12", "", "judge the fix before its merge"); a.Outcome != meshwants.ValidateAnswerOutcomeRunning || a.Started == nil || len(acts) != 1 ||
|
||||
!strings.Contains(acts[0].What, "main.12"+validateKeySuffix) || !strings.Contains(acts[0].Why, "judge the fix before its merge (op@shanks)") {
|
||||
t.Errorf("a pipeline with no validate run answered %+v after %d hand acts %+v", a, len(acts), acts)
|
||||
}
|
||||
// The pipeline's own validate step joins that run: no second manifest validator is asked.
|
||||
if o := r.validate(ctx, "ask-web-12", meshwants.StepRun{Step: meshwants.StepRunStepValidate, Pipeline: "main.12", Branch: "main", Module: "web", Revision: 12, Source: 12}); o.Outcome != meshwants.StepEndedOutcomeFailed || len(asks) != asked+1 {
|
||||
t.Errorf("the step after the call ended %+v with %d validator asks, want one for the call and the step", o, len(asks)-asked)
|
||||
}
|
||||
// On an ended run it starts nothing, records none and answers its verdict, narrowed by the module.
|
||||
got := onRequest("main.12", "web", "again")
|
||||
if got.Outcome != meshwants.ValidateAnswerOutcomeFailed || got.Reason != meshwants.ValidateAnswerReasonManifestRefused || len(acts) != 1 || len(asks) != asked+1 ||
|
||||
len(got.Problems) != 2 || got.Problems[0].Module != "web" || got.Problems[0].Before || got.Problems[1].Problem != "an inherited problem" || !got.Problems[1].Before {
|
||||
t.Errorf("an ended run answered %+v after %d hand acts and %d asks", got, len(acts), len(asks)-asked)
|
||||
}
|
||||
// An unknown pipeline and a candidate the indexer does not hold are answered so, and start nothing.
|
||||
for _, pipeline := range []string{"main.99", "main.50"} {
|
||||
if a := onRequest(pipeline, "", "why"); a.Outcome != meshwants.ValidateAnswerOutcomeCouldNotRun || a.Why == "" || len(acts) != 1 || len(asks) != asked+1 {
|
||||
t.Errorf("%s answered %+v after %d hand acts, %d asks", pipeline, a, len(acts), len(asks)-asked)
|
||||
}
|
||||
}
|
||||
// H-A-739: a run on request's candidate (run-r1) is judged at the revision show names, 7.
|
||||
if a := onRequest("main.run.r1", "", "judge the run's members"); a.Outcome != meshwants.ValidateAnswerOutcomeRunning || len(acts) != 2 {
|
||||
t.Errorf("a run on request answered %+v after %d hand acts", a, len(acts))
|
||||
}
|
||||
if run, _, ok, _ := runs.read("main.run.r1" + validateKeySuffix); !ok || run.Candidate != "run-r1" {
|
||||
t.Errorf("the run on request's validate run is %+v (kept %v), want its candidate run-r1", run, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-684 (1), H-A-727, H-A-739: the tool reads the runner's show for the candidate and calls the seat mesh-wants' verb validate with
|
||||
// it, answering what the verb answers; a pipeline the runner does not know is answered so with no verb called, and a call with no
|
||||
// why is refused.
|
||||
func TestTheToolValidateReadsTheCandidateAndCallsTheVerb(t *testing.T) {
|
||||
var verbs []meshwants.ValidateInput
|
||||
ask := func(key string, body any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(body)
|
||||
switch key {
|
||||
case showKey:
|
||||
var in mpr.ShowInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
if in.Pipeline == "main.12" {
|
||||
return json.Marshal(mpr.ShowAnswer{Pipeline: mpr.Pipeline{Pipeline: "main.12", Branch: "main", Revision: 12}})
|
||||
}
|
||||
return json.Marshal(map[string]string{"error": "no pipeline " + in.Pipeline})
|
||||
case validateVerbKey:
|
||||
var in meshwants.ValidateInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
verbs = append(verbs, in)
|
||||
return json.Marshal(meshwants.ValidateAnswer{Outcome: meshwants.ValidateAnswerOutcomePassed})
|
||||
}
|
||||
return nil, errors.New("no such verb " + key)
|
||||
}
|
||||
tool := validateTools(ask)[0]
|
||||
if d := strings.ToLower(tool.Description); tool.Name != validateTool || !strings.Contains(d, "judge a manifest on request") || !strings.Contains(d, "the manifest validator's verdict") ||
|
||||
!strings.Contains(d, "validate") {
|
||||
t.Errorf("the tool %s says %q", tool.Name, tool.Description)
|
||||
}
|
||||
out, err := tool.Run(map[string]any{"pipeline": "main.12", "module": "web", "why": "before the merge"})
|
||||
if b, _ := json.Marshal(out); err != nil || !strings.Contains(string(b), `"outcome":"passed"`) || len(verbs) != 1 ||
|
||||
verbs[0] != (meshwants.ValidateInput{Pipeline: "main.12", Candidate: "main.12", Module: "web", Why: "before the merge"}) {
|
||||
t.Errorf("a known pipeline answered %s, %v and called the verb with %+v", out, err, verbs)
|
||||
}
|
||||
out, err = tool.Run(map[string]any{"pipeline": "main.99", "why": "why"})
|
||||
if a, _ := out.(meshwants.ValidateAnswer); err != nil || a.Outcome != meshwants.ValidateAnswerOutcomeCouldNotRun || len(verbs) != 1 {
|
||||
t.Errorf("an unknown pipeline answered %+v, %v and called the verb %d times", out, err, len(verbs))
|
||||
}
|
||||
if _, err := tool.Run(map[string]any{"pipeline": "main.12"}); err == nil || len(verbs) != 1 {
|
||||
t.Errorf("a call with no why answered %v and called the verb", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"mesh-delivery-assigner/internal/outside"
|
||||
)
|
||||
|
||||
// waitDropTool drops one decided wait record by hand (design 47 H2b §830 2.): a wait that ended `go-on`, `failed` or `own-failure`
|
||||
// keeps its record in the state `waits` until its fingerprint runs healthy, so a check that goes on failing there is not held again;
|
||||
// dropping it makes the next failing check there a new wait. The act is recorded in the hand-act log first; only a decided record is
|
||||
// dropped (a wait that stands is released by assigner_release).
|
||||
const waitDropTool = "assigner_wait_drop"
|
||||
|
||||
// dropWait deletes the decided record under key, the act first recorded through the seat mesh-hand-acts.
|
||||
func dropWait(st seatStore, ask func(string, any) (json.RawMessage, error), key, why, by string) (any, error) {
|
||||
switch {
|
||||
case key == "":
|
||||
return nil, errors.New("name the wait's key, <node>.<module>.<fingerprint>: assigner_waits lists them")
|
||||
case why == "":
|
||||
return nil, errors.New("a wait dropped by hand says why")
|
||||
case by == "" || by == stdio.Unproven:
|
||||
return nil, errors.New("a wait dropped by hand names who drops it, and the runtime proved no caller")
|
||||
}
|
||||
raw, _, found, err := st.get(waitsState, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("the assigner holds no wait under %s: assigner_waits lists them", key)
|
||||
}
|
||||
w, err := outside.Decode(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s holds no wait on an outside cause: %w", key, err)
|
||||
}
|
||||
if w.Decided == "" {
|
||||
return nil, fmt.Errorf("the wait %s is %s, not decided: assigner_release takes a wait that stands, and an end not said is said by the assigner (assigner_owed)", key, outside.StateOf(w))
|
||||
}
|
||||
taken, err := meshhandactsclient.Recorder{Ask: ask}.Record(meshhandactsclient.Request{What: waitDropTool + " " + key, Why: why + " (" + by + ")", Cause: "outside-wait-drop"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the drop of %s is not recorded, so the wait stays: %w", key, err)
|
||||
}
|
||||
if err := st.del(waitsState, key); err != nil {
|
||||
return nil, fmt.Errorf("the wait %s is not dropped: %w", key, err)
|
||||
}
|
||||
return map[string]any{"key": key, "dropped": json.RawMessage(raw), "by": by, "hand-act": taken.Log}, nil
|
||||
}
|
||||
|
||||
// waitDropTools is the tool over the runtime's states.
|
||||
func waitDropTools(st seatStore, ask func(string, any) (json.RawMessage, error)) []stdio.Tool {
|
||||
return []stdio.Tool{{Name: waitDropTool, Description: "Drop one decided wait record by hand (design 47 H2b §830 2.): the key <node>.<module>.<fingerprint> of the state waits, " +
|
||||
"of a wait that ended go-on, failed or own-failure, so the next failing check of that module there is held as a new wait. Recorded as a hand act first; " +
|
||||
"refused for a wait that stands or whose end is not said (assigner_release takes the first).",
|
||||
Input: schema(map[string]string{"key": "the wait's key as assigner_waits answers it", "why": "why the record is dropped"}, []string{"key", "why"}),
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return dropWait(st, ask, arg(a, "key"), arg(a, "why"), stdio.CallerOf(a))
|
||||
}}}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
@@ -28,6 +29,9 @@ const whyTool = "assigner_why"
|
||||
const (
|
||||
whyNoPipeline = "no-passed-pipeline" // no version of the module released on the branch passed its pipeline: the want written stays
|
||||
whyPassed = "passed-pipeline" // the want names the newest version released on the branch whose pipeline passed (design 47 H §750)
|
||||
// whyHeldByTier: the module's end is kept, and its pipeline's tier progress has not reached its rank; the why names the
|
||||
// pipeline, the tier that runs and the mover that holds it, and whether that tier was found late (§824 6., H-A-507, H-A-844).
|
||||
whyHeldByTier = "held-by-tier"
|
||||
)
|
||||
|
||||
// whyStep is the step that decided a want: a passed pipeline's version, or none yet.
|
||||
@@ -38,6 +42,32 @@ func whyStep(passed bool) string {
|
||||
return whyNoPipeline
|
||||
}
|
||||
|
||||
// heldByTier is the why of module's want on branch when its end is kept and its pipeline's tier progress has not reached its rank;
|
||||
// false when no end is kept (then the step is no-passed-pipeline, H-A-507) or the tier is written.
|
||||
func (p *passer) heldByTier(module, branch string, w wantWhy) (wantWhy, bool) {
|
||||
if p.ends == nil {
|
||||
return w, false
|
||||
}
|
||||
end, ok := p.ends.endOf(module, p.ends.branchOf(module, branch))
|
||||
if !ok || p.ends.tierWritten(end) {
|
||||
return w, false
|
||||
}
|
||||
w.Step, w.Pipeline, w.Fp, w.Version = whyHeldByTier, end.Pipeline, end.Fp, end.Version
|
||||
if h, ok := p.tierHolds[end.Pipeline]; ok {
|
||||
w.Tier, w.Holder, w.TierLate = h.tier, h.mover, h.late
|
||||
}
|
||||
return w, true
|
||||
}
|
||||
|
||||
// tierHold is what holds a pipeline's tier progress at its tier: the first mover of that tier not running, and whether the tier was
|
||||
// found late; kept by the pass that read it, for the whys of the wants that wait on the tier.
|
||||
type tierHold struct {
|
||||
tier int64
|
||||
mover string
|
||||
late bool
|
||||
pipeline string
|
||||
}
|
||||
|
||||
// wantWhy is one key's value.
|
||||
type wantWhy struct {
|
||||
At time.Time `json:"at"`
|
||||
@@ -47,9 +77,36 @@ type wantWhy struct {
|
||||
Version string `json:"version,omitempty"`
|
||||
Pipeline string `json:"pipeline,omitempty"`
|
||||
Step string `json:"step"`
|
||||
// Tier, Holder and TierLate say, for held-by-tier, the tier that runs, the mover that holds it and whether that tier was found
|
||||
// late (design 47 H2b §824 6.).
|
||||
Tier int64 `json:"tier,omitempty"`
|
||||
Holder string `json:"holder,omitempty"`
|
||||
TierLate bool `json:"tier-late,omitempty"`
|
||||
// Before is the want that stood before the pass, After the one the pass wrote (none: it kept Before).
|
||||
Before *mwc.Want `json:"before,omitempty"`
|
||||
After *mwc.Want `json:"after,omitempty"`
|
||||
// Entry is the ask of the catalog entry a want held awaiting its entry waits on: its state, how often it was asked again and its
|
||||
// last failure (design 47 H2 H-A-698 (2)).
|
||||
Entry *entryAsk `json:"entry,omitempty"`
|
||||
}
|
||||
|
||||
// entryAsk is where the ask of one catalog entry stands.
|
||||
type entryAsk struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
State meshcatalogclient.EntryState `json:"state"`
|
||||
Asks int `json:"asks"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// heldWant is the want a why says stands after the pass: the one written, else the one before.
|
||||
func heldWant(w wantWhy) mwc.Want {
|
||||
switch {
|
||||
case w.After != nil:
|
||||
return *w.After
|
||||
case w.Before != nil:
|
||||
return *w.Before
|
||||
}
|
||||
return mwc.Want{}
|
||||
}
|
||||
|
||||
func whyKey(node, module string) string { return whyPrefix + node + "." + module }
|
||||
@@ -74,6 +131,14 @@ func (p *passer) sayWhy(ctx context.Context, module string, nodes []string, w wa
|
||||
one.After = &a
|
||||
}
|
||||
}
|
||||
if held := heldWant(one); p.entries != nil && strings.HasPrefix(held.Words, mwc.HoldAwaitsEntryPrefix) {
|
||||
fp := strings.TrimPrefix(held.Words, mwc.HoldAwaitsEntryPrefix)
|
||||
for _, row := range p.entries.Rows() {
|
||||
if row.Fingerprint == fp {
|
||||
one.Entry = &entryAsk{Fingerprint: fp, State: row.State, Asks: row.Asks, Detail: row.Detail}
|
||||
}
|
||||
}
|
||||
}
|
||||
same := one
|
||||
same.At = time.Time{}
|
||||
cmp, _ := json.Marshal(same)
|
||||
|
||||
@@ -362,6 +362,26 @@ func (w *world) online() map[string]bool {
|
||||
return out
|
||||
}
|
||||
|
||||
// namesFingerprint says whether a want the assigner wrote or a `running` it holds names fp: the entry at fp is still read by it
|
||||
// (design 47 H2 H-A-757).
|
||||
func (w *world) namesFingerprint(fp string) bool {
|
||||
for _, nodes := range w.wantsOf() {
|
||||
for _, want := range nodes {
|
||||
if want.Fp == fp {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
for _, r := range w.running {
|
||||
if r.Fingerprint == fp {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// wantsOf is the wants the assigner wrote, by module then node.
|
||||
func (w *world) wantsOf() map[string]map[string]mwc.Want {
|
||||
out := map[string]map[string]mwc.Want{}
|
||||
|
||||
@@ -8,6 +8,7 @@ require (
|
||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
github.com/nats-io/nats-server/v2 v2.11.17
|
||||
|
||||
@@ -3,6 +3,7 @@ package assign
|
||||
import (
|
||||
"fmt"
|
||||
"mesh-delivery-assigner/internal/assignment"
|
||||
"mesh-delivery-assigner/internal/outside"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -52,13 +53,18 @@ func OutsideAsk(key, about, node, module, fp, cause string, since time.Time, ask
|
||||
// id `<node>.<module>`, severity warning, naming the module, the machine and the cause by its condition's key, and needing
|
||||
// nothing, so it is sent to no one: the operator's one message is the ask at the bound.
|
||||
func WaitsOutsideFinding(node, module, causeKey, on string, at time.Time) Observed {
|
||||
needs := "Nothing for you to do."
|
||||
if on == outside.OnUnread {
|
||||
// A read that failed leaves the wait standing until an input judges it again (design 47 H2b §829 5.): the way through is named.
|
||||
needs = "The conditions of " + node + " could not be read: ask assigner_release for " + module + " on " + node + " with how rejudge to judge it again now."
|
||||
}
|
||||
return Observed{Scope: "delivery", ID: node + "." + module, Kind: "delivery-waits-outside", Machine: node,
|
||||
Severity: "warning",
|
||||
Summary: fmt.Sprintf("%s on %s waits on %s (the condition %s)", module, node, on, causeKey),
|
||||
Headline: fmt.Sprintf("%s on %s waits on an outside cause", module, node),
|
||||
Explanation: fmt.Sprintf("The health check of %s fails on %s while %s is open, which is outside the delivery. The delivery "+
|
||||
"waits, judges again when it clears and goes on by itself.", module, node, causeKey),
|
||||
Needs: "Nothing for you to do.", Source: "assigner.delivery-waits-outside"}
|
||||
Needs: needs, Source: "assigner.delivery-waits-outside"}
|
||||
}
|
||||
|
||||
// The options of the record ask (ADR 0539 §14) and of the backup ask (§16).
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-teller/tellerevents"
|
||||
"mesh-delivery-assigner/internal/assignment"
|
||||
"mesh-delivery-assigner/internal/outside"
|
||||
"mesh-delivery-assigner/internal/puts"
|
||||
"regexp"
|
||||
"slices"
|
||||
@@ -217,6 +218,16 @@ func theBackupAskIsValid(t *testing.T) {
|
||||
// 1952/WM6: the assigner's conditions are findings.
|
||||
func TestTheAssignersConditions(t *testing.T) {
|
||||
t.Run("1952/WM6: each said condition is a finding, its clear deletes it, said straight only with no findings bucket", saidConditionsAreFindings)
|
||||
// Design 47 H2b §829 5. (review r1 finding 6): a wait on conditions-unread names the way through; any other wait needs nothing.
|
||||
t.Run("the finding of a wait on conditions-unread names assigner_release with rejudge", func(t *testing.T) {
|
||||
at := time.Date(2026, 11, 27, 4, 0, 0, 0, time.UTC)
|
||||
if o := WaitsOutsideFinding("ace", "nats", "", outside.OnUnread, at); !strings.Contains(o.Needs, "assigner_release") || !strings.Contains(o.Needs, "rejudge") {
|
||||
t.Errorf("a wait on conditions-unread needs %q", o.Needs)
|
||||
}
|
||||
if o := WaitsOutsideFinding("ace", "nats", "machine.hub.unreachable", "unreachable:hub", at); o.Needs != "Nothing for you to do." {
|
||||
t.Errorf("a wait on a cause needs %q", o.Needs)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 1952/WM6 (ADR 0564 §2, issue 1952 note 16): every condition the assigner says is a finding in its own bucket, under
|
||||
|
||||
@@ -75,6 +75,27 @@ func CallUnanswered(id, callee, machine, fault, source string, since time.Time)
|
||||
Source: source}
|
||||
}
|
||||
|
||||
// ReadUnanswered is the observation of a seat verb a run's read waited five minutes on (design 47 H2 H-A-708 (4), ADR 0668 §3): id
|
||||
// `<seat>.<verb>`, the summary naming its holder, the machines it runs on, the last fault and since when; the id is one finding per
|
||||
// seat verb.
|
||||
func ReadUnanswered(seat, verb, holder string, machines []string, fault string, since time.Time) Observed {
|
||||
who := "its holder is not read"
|
||||
if holder != "" {
|
||||
who = "its holder " + holder
|
||||
if len(machines) > 0 {
|
||||
who += " on " + strings.Join(machines, ", ")
|
||||
}
|
||||
}
|
||||
callee := seat + "." + verb
|
||||
return Observed{Scope: mcc.ScopeCall, ID: callee, Kind: mcc.KindCallUnanswered, Severity: mcseat.FindingSeverityWarning,
|
||||
Summary: fmt.Sprintf("%s is unanswered since %s (%s); the last fault: %s", callee, since.UTC().Format(time.RFC3339), who, fault),
|
||||
Said: fault, Headline: "A read of a run is not answered",
|
||||
Explanation: fmt.Sprintf("A composition or validate run's read of %s is asked again at the kept-call pace and has not been answered since %s; %s. "+
|
||||
"The last fault: %s.", callee, since.UTC().Format(time.RFC3339), who, fault),
|
||||
Needs: "the holder of the seat " + seat + " to answer",
|
||||
Source: "assigner." + mcc.KindCallUnanswered}
|
||||
}
|
||||
|
||||
// FindingOf is a said condition as a finding: from the condition's own key `mesh-delivery-assigner.<kind>.<id…>` (the
|
||||
// subject's id when the key names none), its words unchanged but the resolved ones. raised is false for a clear, whose
|
||||
// finding names only its scope, id and kind.
|
||||
@@ -115,7 +136,9 @@ type Findings struct {
|
||||
Put func(f mcseat.Finding) error
|
||||
Delete func(key string) error
|
||||
Keys func() ([]string, error)
|
||||
Now func() time.Time
|
||||
// Get reads one finding's value by its key, false when none stands (design 47 H2b H-A-828); nil reads none.
|
||||
Get func(key string) (mcseat.Finding, bool, error)
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Say is say with each condition written as a finding (or its finding deleted), which the condition keeper carries, the
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
|
||||
mwc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshwantsclient"
|
||||
"mesh-delivery-assigner/internal/puts"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||
@@ -56,6 +57,43 @@ type PutWorld struct {
|
||||
// ends on it, never on the have.
|
||||
Running *nodeengine.Running
|
||||
Now time.Time
|
||||
// Matches are the done builds of the module the assigner hears whose fingerprint starts with the put's prefix, with the
|
||||
// version released at each ("" none); Branch is the watched branch the pass uses for the module on the node and
|
||||
// BranchEnd the fingerprint of the end kept there ("" when none is kept). They resolve a put's version at its first
|
||||
// step (design 47 H2b §833, §834; H-A-848, H-A-862).
|
||||
Matches []PutMatch
|
||||
Branch string
|
||||
BranchEnd string
|
||||
}
|
||||
|
||||
// PutMatch is one done build that starts with a put's prefix.
|
||||
type PutMatch struct{ FP, Version string }
|
||||
|
||||
// resolvePut is the put with its version resolved to the whole fingerprint, or the words that refuse it (design 47 H2b §833,
|
||||
// §834): newest is the end kept for the node's branch, a prefix the one done build that starts with it.
|
||||
func resolvePut(w PutWorld) (puts.Put, string) {
|
||||
p := w.Put
|
||||
asked := p.FP
|
||||
if asked == puts.Newest {
|
||||
if w.BranchEnd == "" {
|
||||
return p, fmt.Sprintf("no version of %s passed a pipeline: name a fingerprint, or read assigner_written (the end of branch %s is the one read)", w.Module, w.Branch)
|
||||
}
|
||||
p.FP = w.BranchEnd
|
||||
} else {
|
||||
switch len(w.Matches) {
|
||||
case 0:
|
||||
return p, fmt.Sprintf("no build of %s that the assigner hears is done at a fingerprint starting %s: name another fingerprint", w.Module, asked)
|
||||
case 1:
|
||||
p.FP = w.Matches[0].FP
|
||||
default:
|
||||
var each []string
|
||||
for _, m := range w.Matches {
|
||||
each = append(each, fmt.Sprintf("%s (%s)", short(m.FP), m.Version))
|
||||
}
|
||||
return p, fmt.Sprintf("%s names more than one build of %s: %s; name more of the fingerprint", asked, w.Module, strings.Join(each, ", "))
|
||||
}
|
||||
}
|
||||
return p.Said(w.Now, p.Step, fmt.Sprintf("the put of %s names %s, which %s resolves to", w.Module, p.FP, asked)), ""
|
||||
}
|
||||
|
||||
// PutNext is what a step decides: the put as it stands after it, and the acts the pass does for it.
|
||||
@@ -78,6 +116,13 @@ func StepPut(w PutWorld) PutNext {
|
||||
say := func(step, format string, args ...any) PutNext {
|
||||
return PutNext{Put: p.Said(w.Now, step, fmt.Sprintf(format, args...))}
|
||||
}
|
||||
if puts.Unresolved(p.FP) {
|
||||
resolved, refused := resolvePut(w)
|
||||
if refused != "" {
|
||||
return PutNext{Put: p.Said(w.Now, puts.Refused, refused)}
|
||||
}
|
||||
p = resolved
|
||||
}
|
||||
fp := short(p.FP)
|
||||
if !w.Assigned {
|
||||
return say(puts.Refused, "%s is not assigned to %s: a put moves a module where it stands assigned (propose its assignments first)", w.Module, w.Node)
|
||||
|
||||
@@ -44,3 +44,35 @@ func UnlistedFinding(node, module string, at time.Time) (mcseat.Finding, error)
|
||||
"Take it off, or register the module on a watched branch.",
|
||||
Source: "assigner." + KindAssignmentUnlisted}, at)
|
||||
}
|
||||
|
||||
// KindWantUnversioned is a want that names no version, for a module whose target no release gives (design 47 H2 H-A-673,
|
||||
// H-A-706 on DQ-40): scope delivery, id `<module>.<node>`, severity warning.
|
||||
const KindWantUnversioned = "want-unversioned"
|
||||
|
||||
// UnversionedKey is its finding's key, `delivery.<module>.<node>.want-unversioned`.
|
||||
func UnversionedKey(module, node string) string {
|
||||
return views.FindingKey(ScopeAssignmentUnlisted, KeyID(module+"."+node), KindWantUnversioned)
|
||||
}
|
||||
|
||||
// UnversionedOfKey is the module and node of a want-unversioned finding's key, or false for another finding's.
|
||||
func UnversionedOfKey(key string) (module, node string, ok bool) {
|
||||
rest, ok := strings.CutPrefix(key, ScopeAssignmentUnlisted+".")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
if rest, ok = strings.CutSuffix(rest, "."+KindWantUnversioned); !ok {
|
||||
return "", "", false
|
||||
}
|
||||
module, node, ok = strings.Cut(rest, ".")
|
||||
return module, node, ok && module != "" && node != "" && !strings.Contains(node, ".")
|
||||
}
|
||||
|
||||
// UnversionedFinding is the finding of the want of module on node that names fingerprint fp and no version, while no target is
|
||||
// held (why).
|
||||
func UnversionedFinding(module, node, fp, why string, at time.Time) (mcseat.Finding, error) {
|
||||
summary := fmt.Sprintf("the want of %s on %s names %s and no version, and no target is held for it: %s", module, node, short(fp), why)
|
||||
return encode(Observed{Scope: ScopeAssignmentUnlisted, ID: module + "." + node, Kind: KindWantUnversioned, Machine: node,
|
||||
Severity: mcseat.FindingSeverityWarning, Summary: summary, Headline: clipHeadline(module + " on " + node + " is wanted with no version"),
|
||||
Explanation: summary + ". The want stands as written, so the node composes nothing new for it; it clears once the want names a version.",
|
||||
Source: "assigner." + KindWantUnversioned}, at)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package assign
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
|
||||
@@ -16,7 +17,7 @@ import (
|
||||
|
||||
// A want names the newest released version whose pipeline passed (design 47 H §750): for every node whose assignment places
|
||||
// a module on a watched branch, the want names the version, the pipeline and the mover's rank in it, written tier by tier
|
||||
// (§751). It is held for nothing else: the rules of ADR 0429 §6 (the build done, not held, the canary and step, every
|
||||
// (§751). It is held for nothing else than a reader capability its node-engine does not state (ADR 0614 §4, §772 being its first case, H-A-682); the rules of ADR 0429 §6 (the build done, not held, the canary and step, every
|
||||
// provider healthy, the grant, the composition and the reader capabilities, the provisions, the served verbs and the bus
|
||||
// state), the network hold and A-428's exceptions end (H-A-55). A put owns its node's want as before (ADR 0546), and the
|
||||
// operator's yes on a module of policy record is the node-engine's have and the asker's (the pass's yeses).
|
||||
@@ -28,6 +29,9 @@ type Target struct {
|
||||
Version string
|
||||
Pipeline string
|
||||
Rank int64
|
||||
// Seq is the pipeline's sequence, the want's run in decimal (design 47 H2 §813 (1), H-A-504 addendum); 0 for a placement's
|
||||
// build.
|
||||
Seq int64
|
||||
}
|
||||
|
||||
// Module is what the want rule reads of one module: the nodes it is assigned to, the build each node's want names, the puts
|
||||
@@ -54,6 +58,10 @@ type Module struct {
|
||||
// node-engine, design 47 H §772, H-A-45); a node whose engine does not is written its want held, awaiting its hand placement
|
||||
// (H-A-73). Nil: every node does.
|
||||
ReadsVersion func(node string) bool
|
||||
// MissingNeeds says what the want of node at fp lacks of its node-engine's words: the reader capabilities the entry at fp
|
||||
// needs that the node's words in `engine-reads` do not hold, sorted; read false while the entry's needs are not read yet
|
||||
// (design 47 H2 H-A-682 (2), H-A-698 (2)). Nil: no want needs more than want:version.
|
||||
MissingNeeds func(node, fp string) (missing []string, read bool)
|
||||
}
|
||||
|
||||
func (m Module) selfOn(node string) bool { return m.Self != nil && m.Self(node) }
|
||||
@@ -92,13 +100,16 @@ func (n Nodes) RunsHealthy(node, module, fp string) bool {
|
||||
// Outcome is what one module's pass decides: each node's want to write (only those that change).
|
||||
type Outcome struct {
|
||||
Wants map[string]mwc.Want
|
||||
// Unversioned is, by node, the fingerprint of a want that names no version and for which Target answers none: the want
|
||||
// stands as written, and the pass says it with the finding want-unversioned (design 47 H2 H-A-673, H-A-706 on DQ-40).
|
||||
Unversioned map[string]string
|
||||
}
|
||||
|
||||
// Wants is the pass of one module m: for each of its nodes, the want naming its Target, starting from the want written before
|
||||
// (wants, by node). A put that owns a node's want writes the put's; a node with no target keeps the want written. A node that
|
||||
// wants m but is no longer among its nodes gets its want written removed, never deleted (ADR 0408 §4).
|
||||
func Wants(m Module, wants map[string]mwc.Want) Outcome {
|
||||
out := Outcome{Wants: map[string]mwc.Want{}}
|
||||
out := Outcome{Wants: map[string]mwc.Want{}, Unversioned: map[string]string{}}
|
||||
for _, node := range m.Nodes {
|
||||
before, had := wants[node]
|
||||
p, put := m.Puts[node]
|
||||
@@ -120,9 +131,15 @@ func Wants(m Module, wants map[string]mwc.Want) Outcome {
|
||||
t, ok = m.Target(node)
|
||||
}
|
||||
if !ok || t.Fp == "" {
|
||||
if had && !before.Removed && !before.Put && before.Version == "" && before.Fp != "" {
|
||||
out.Unversioned[node] = before.Fp
|
||||
}
|
||||
continue
|
||||
}
|
||||
next := mwc.Want{Fp: t.Fp, Version: t.Version, Pipeline: t.Pipeline, Rank: t.Rank, Self: m.selfOn(node)}
|
||||
if t.Seq > 0 {
|
||||
next.Run = strconv.FormatInt(t.Seq, 10)
|
||||
}
|
||||
if had && !before.Removed && !before.Put && before.Fp == t.Fp {
|
||||
// The answers the want carries stay while its build does: a failed backup's (ADR 0539 §16), a held revert's, the yes.
|
||||
next.Backup, next.Words, next.Revert, next.Yes, next.Release = before.Backup, before.Words, before.Revert, before.Yes, before.Release
|
||||
@@ -130,6 +147,19 @@ func Wants(m Module, wants map[string]mwc.Want) Outcome {
|
||||
if m.ReadsVersion != nil && !m.ReadsVersion(node) {
|
||||
// A node-engine that cannot read a want by version is placed by hand when its machine is back (design 47 H §772).
|
||||
next.Hold, next.Words, next.Backup, next.Revert = true, mwc.HoldAwaitsHandPlacement, "", ""
|
||||
} else if m.MissingNeeds != nil {
|
||||
// A node-engine whose words lack a reader capability the entry needs reads the want no better (ADR 0614 §4): the want is
|
||||
// held, saying which, or saying the entry is not read yet (design 47 H2 H-A-682 (2), H-A-698 (2)).
|
||||
missing, read := m.MissingNeeds(node, t.Fp)
|
||||
switch {
|
||||
case !read:
|
||||
next.Hold, next.Words, next.Backup, next.Revert = true, mwc.HoldAwaitsEntryPrefix+t.Fp, "", ""
|
||||
case len(missing) > 0:
|
||||
next.Hold, next.Words, next.Backup, next.Revert = true, mwc.HoldAwaitsReadsPrefix+strings.Join(missing, ","), "", ""
|
||||
}
|
||||
}
|
||||
if !next.Hold && holdWords(next.Words) {
|
||||
next.Words = "" // the hold ended: its words with it
|
||||
}
|
||||
if !had || !mwc.SameWant(normal(before), normal(next)) {
|
||||
out.Wants[node] = next
|
||||
@@ -143,6 +173,11 @@ func Wants(m Module, wants map[string]mwc.Want) Outcome {
|
||||
return out
|
||||
}
|
||||
|
||||
// holdWords says whether words are those of a want the assigner holds for what its node-engine does not read.
|
||||
func holdWords(words string) bool {
|
||||
return words == mwc.HoldAwaitsHandPlacement || strings.HasPrefix(words, mwc.HoldAwaitsReadsPrefix) || strings.HasPrefix(words, mwc.HoldAwaitsEntryPrefix)
|
||||
}
|
||||
|
||||
// failed says whether a have's health check failed once the node is done moving: phase running or failed (never removed, held, or
|
||||
// moving).
|
||||
func failed(h nodeengine.HaveByNodeModuleValue) bool {
|
||||
|
||||
@@ -69,6 +69,34 @@ func TestAWantNamesTheNewestPassedVersion(t *testing.T) {
|
||||
m.ReadsVersion = func(node string) bool { return node == "ace" }
|
||||
return m
|
||||
}, nil, map[string]mwc.Want{"ace": want, "g14": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsHandPlacement}}},
|
||||
{"A3a (H-A-682 (2)): a node whose words lack a need of the entry is held, awaiting its reads; one whose words hold it is not", func() Module {
|
||||
m := released()
|
||||
m.MissingNeeds = func(node, fp string) ([]string, bool) {
|
||||
if node == "ace" {
|
||||
return []string{"directory-contents-owner", "approval-mark/1"}, true
|
||||
}
|
||||
return nil, true
|
||||
}
|
||||
return m
|
||||
}, nil, map[string]mwc.Want{"ace": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsReadsPrefix + "directory-contents-owner,approval-mark/1"}, "g14": want}},
|
||||
{"A3a: a node without want:version keeps awaiting its hand placement, whatever its needs", func() Module {
|
||||
m := released()
|
||||
m.ReadsVersion = func(node string) bool { return node == "g14" }
|
||||
m.MissingNeeds = func(string, string) ([]string, bool) { return []string{"directory-contents-owner"}, true }
|
||||
return m
|
||||
}, nil, map[string]mwc.Want{"ace": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsHandPlacement},
|
||||
"g14": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsReadsPrefix + "directory-contents-owner"}}},
|
||||
{"A3a: the node's next manifest-reads-changed naming the need writes the want with no hold", func() Module {
|
||||
m := released()
|
||||
m.MissingNeeds = func(string, string) ([]string, bool) { return nil, true }
|
||||
return m
|
||||
}, map[string]mwc.Want{"ace": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsReadsPrefix + "directory-contents-owner"}, "g14": want},
|
||||
map[string]mwc.Want{"ace": want}},
|
||||
{"A3b (H-A-698 (2)): a want whose entry is not read yet is held awaiting its entry", func() Module {
|
||||
m := released()
|
||||
m.MissingNeeds = func(node, fp string) ([]string, bool) { return nil, node != "ace" }
|
||||
return m
|
||||
}, wantedOld(), map[string]mwc.Want{"ace": {Fp: fNew, Version: "1.2.3", Pipeline: "main.12", Rank: 2, Hold: true, Words: mwc.HoldAwaitsEntryPrefix + fNew}, "g14": want}},
|
||||
{"a node no longer assigned is removed", func() Module {
|
||||
m := released()
|
||||
m.Nodes = []string{"ace"}
|
||||
@@ -86,6 +114,28 @@ func TestAWantNamesTheNewestPassedVersion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// H-A-673, H-A-706 (DQ-40): a node whose want names no version and for which Target answers none is named in the outcome
|
||||
// beside the wants, with the fingerprint; one whose want names a version, one with a target (rewritten) and one removed are not.
|
||||
none := func() Module {
|
||||
m := released()
|
||||
m.Target = func(string) (Target, bool) { return Target{}, false }
|
||||
return m
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
module func() Module
|
||||
before map[string]mwc.Want
|
||||
named map[string]string
|
||||
}{
|
||||
{"no version and no target", none, map[string]mwc.Want{"ace": {Fp: fOld}, "g14": {Fp: fOld, Version: "1.2.2"}}, map[string]string{"ace": fOld}},
|
||||
{"a target rewrites the want", released, map[string]mwc.Want{"ace": {Fp: fOld}}, map[string]string{}},
|
||||
{"a removed want", none, map[string]mwc.Want{"ace": {Removed: true}}, map[string]string{}},
|
||||
} {
|
||||
got := Wants(c.module(), c.before).Unversioned
|
||||
if len(got) != len(c.named) || (len(got) > 0 && got["ace"] != c.named["ace"]) {
|
||||
t.Errorf("%s: unversioned = %v, want %v", c.name, got, c.named)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ADR 0546: a put owns the node's want from its asking until it ends; while it waits the rule writes nothing there, once wanted its
|
||||
|
||||
@@ -105,14 +105,19 @@ type Wait struct {
|
||||
// Settling: no outside cause was open at the failing check; the judgement is held until SettleEnds.
|
||||
Settling bool `json:"settling,omitempty"`
|
||||
SettleEnds time.Time `json:"settle-ends,omitempty"`
|
||||
// Ask is the id of the asking made at the bound, and State where the wait stands in words (settling, waiting, asked).
|
||||
Ask string `json:"ask,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
// Ask is the id of the asking made at the bound. Where the wait stands in words is derived at the read, never kept (StateOf).
|
||||
Ask string `json:"ask,omitempty"`
|
||||
// Release is a release by hand not taken up yet: go-on, failed or rejudge, by By and why Why.
|
||||
Release string `json:"release,omitempty"`
|
||||
By string `json:"by,omitempty"`
|
||||
Why string `json:"why,omitempty"`
|
||||
// Decided is `go-on` or `failed` once the wait ended so.
|
||||
// HeldSaid counts the wait-held the wait was the record of, raised by one in the write that makes a new one, so an `on` back at
|
||||
// an earlier cause makes a new message id (design 47 H §832 3.).
|
||||
HeldSaid int `json:"held-said,omitempty"`
|
||||
// Ending is the `how` of an end written and not yet said (design 47 H2b §831): the record stands with its ask and finding until the
|
||||
// bus has taken `wait-ended`, and is judged no more.
|
||||
Ending string `json:"ending,omitempty"`
|
||||
// Decided is `go-on`, `failed` or `own-failure` once the wait ended so and its end was said.
|
||||
Decided string `json:"decided,omitempty"`
|
||||
}
|
||||
|
||||
@@ -135,7 +140,43 @@ func Decode(raw []byte) (Wait, error) {
|
||||
}
|
||||
|
||||
// Standing says a wait is said (`wait-held`) and not only settling, nor decided.
|
||||
func (w Wait) Standing() bool { return !w.Settling && w.Decided == "" }
|
||||
func (w Wait) Standing() bool { return !w.Settling && w.Decided == "" && w.Ending == "" }
|
||||
|
||||
// The states of a wait as `assigner_waits` says them, derived from the record (design 47 H2b §830 1.).
|
||||
const (
|
||||
StateSettling = "settling"
|
||||
StateWaiting = "waiting"
|
||||
StateAsked = "asked"
|
||||
StateEnding = "ending:"
|
||||
StateDecided = "decided:"
|
||||
)
|
||||
|
||||
// StateOf derives where a wait stands from its record: `settling`, `waiting` (standing, no ask), `asked` (standing, with its ask),
|
||||
// `ending:<how>` (an end not yet said) or `decided:<how>`.
|
||||
func StateOf(w Wait) string {
|
||||
switch {
|
||||
case w.Decided != "":
|
||||
return StateDecided + w.Decided
|
||||
case w.Ending != "":
|
||||
return StateEnding + w.Ending
|
||||
case w.Settling:
|
||||
return StateSettling
|
||||
case w.Ask != "":
|
||||
return StateAsked
|
||||
}
|
||||
return StateWaiting
|
||||
}
|
||||
|
||||
// EndedAs is the record a wait's end leaves once `wait-ended` was said (design 47 H2b §831): the wait decided for `go-on`, `failed` and
|
||||
// `own-failure`, nil (the record is deleted) for `healthy`, `cleared` and `replaced`.
|
||||
func EndedAs(w Wait, how string) *Wait {
|
||||
switch how {
|
||||
case HowGoOn, HowFailed, HowOwnFailure:
|
||||
w.Release, w.Ask, w.Ending, w.Settling, w.SettleEnds, w.Decided = "", "", "", false, time.Time{}, how
|
||||
return &w
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Facts are what a judging reads: the module's check on the node at the wait's fingerprint (Failing, Healthy), the keeper's
|
||||
// conditions as read now (Read false: the kept call is unanswered), whether the module holds the seat mesh-conditions itself,
|
||||
@@ -153,8 +194,11 @@ type Facts struct {
|
||||
CauseCleared bool
|
||||
// KeeperSelf: the module holds the seat mesh-conditions, which cannot answer for its own failing check.
|
||||
KeeperSelf bool
|
||||
Bound time.Duration
|
||||
Settle time.Duration
|
||||
// Running: the node-engine seat's last `running` for the module on the node names the wait's fingerprint and does not say it
|
||||
// stopped, whatever its health says (design 47 H2b §827): the operator is asked only while it is false.
|
||||
Running bool
|
||||
Bound time.Duration
|
||||
Settle time.Duration
|
||||
}
|
||||
|
||||
// Decision is what a judging comes to.
|
||||
@@ -169,12 +213,18 @@ type Decision struct {
|
||||
Own, Counted, Waiting bool
|
||||
// Ask: the bound has run from clock-from, so the operator is asked.
|
||||
Ask bool
|
||||
// Withdraw: the module runs its wanted build while its ask stands, so the ask is withdrawn and the wait's Ask written empty (§827 2.).
|
||||
Withdraw bool
|
||||
// Due is when the judging is due again by itself (the settle's end); zero for none.
|
||||
Due time.Time
|
||||
}
|
||||
|
||||
// Judge is one judging of the check at the node (§706). prev is the kept wait of that module at that fingerprint, nil for none.
|
||||
func Judge(prev *Wait, node, module, fp string, f Facts) Decision {
|
||||
if prev != nil && prev.Ending != "" {
|
||||
// An end written and not yet said: the record is judged no more and makes no wait-held (§831); the end's say finishes it.
|
||||
return Decision{Wait: prev, Own: prev.Ending == HowFailed || prev.Ending == HowOwnFailure, Counted: prev.Ending == HowGoOn}
|
||||
}
|
||||
if prev != nil && prev.Decided != "" {
|
||||
// Decided by the operator: it holds for this fingerprint until the module runs healthy.
|
||||
if f.Healthy {
|
||||
@@ -236,14 +286,14 @@ func Judge(prev *Wait, node, module, fp string, f Facts) Decision {
|
||||
if prev != nil && prev.Settling {
|
||||
next = *prev
|
||||
} else {
|
||||
next.Settling, next.SettleEnds, next.State = true, f.Now.Add(f.Settle), "settling"
|
||||
next.Settling, next.SettleEnds = true, f.Now.Add(f.Settle)
|
||||
}
|
||||
if f.Now.Before(next.SettleEnds) {
|
||||
return Decision{Wait: &next, Waiting: true, Due: next.SettleEnds}
|
||||
}
|
||||
next.Settling, next.SettleEnds = false, time.Time{}
|
||||
}
|
||||
next.On, next.Cause, next.Settling, next.State = OnUnread, "", false, "waiting"
|
||||
next.On, next.Cause, next.Settling = OnUnread, "", false
|
||||
return stand(prev, next, f)
|
||||
}
|
||||
causes := Causes(f.Conds, node, f.Moved)
|
||||
@@ -256,7 +306,7 @@ func Judge(prev *Wait, node, module, fp string, f Facts) Decision {
|
||||
}
|
||||
}
|
||||
}
|
||||
next.On, next.Cause, next.Settling, next.SettleEnds, next.State = c.On, c.Key, false, time.Time{}, "waiting"
|
||||
next.On, next.Cause, next.Settling, next.SettleEnds = c.On, c.Key, false, time.Time{}
|
||||
return stand(prev, next, f)
|
||||
}
|
||||
if standing {
|
||||
@@ -274,7 +324,7 @@ func Judge(prev *Wait, node, module, fp string, f Facts) Decision {
|
||||
}
|
||||
return Decision{Wait: prev, Waiting: true, Due: prev.SettleEnds}
|
||||
}
|
||||
next.Settling, next.SettleEnds, next.State, next.On, next.Cause = true, f.Now.Add(f.Settle), "settling", "", ""
|
||||
next.Settling, next.SettleEnds, next.On, next.Cause = true, f.Now.Add(f.Settle), "", ""
|
||||
return Decision{Wait: &next, Waiting: true, Due: next.SettleEnds}
|
||||
}
|
||||
|
||||
@@ -287,9 +337,14 @@ func stand(prev *Wait, next Wait, f Facts) Decision {
|
||||
if prev != nil && prev.Standing() {
|
||||
next.Ask = prev.Ask
|
||||
}
|
||||
if f.Bound > 0 && !f.Now.Before(next.ClockFrom.Add(f.Bound)) {
|
||||
switch {
|
||||
case f.Running:
|
||||
// §827: a module that runs its wanted build is asked about nothing; an ask that stands is withdrawn, the wait stands.
|
||||
if prev != nil && prev.Standing() && prev.Ask != "" {
|
||||
d.Withdraw, next.Ask = true, ""
|
||||
}
|
||||
case f.Bound > 0 && !f.Now.Before(next.ClockFrom.Add(f.Bound)):
|
||||
d.Ask = true
|
||||
next.State = "asked"
|
||||
}
|
||||
d.Wait = &next
|
||||
return d
|
||||
|
||||
@@ -138,6 +138,30 @@ func TestJudge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}},
|
||||
{"a module running its wanted build past the bound has no ask; one that came to run has its ask withdrawn; its end carries none (§827)", func(t *testing.T) {
|
||||
_, w := step(nil, facts(t0, hub))
|
||||
f := facts(t0.Add(30*time.Minute), hub)
|
||||
f.Running = true
|
||||
if d, _ := step(w, f); d.Ask || d.Withdraw || d.End != "" {
|
||||
t.Fatalf("running past the bound: %+v", d)
|
||||
}
|
||||
d, asked := step(w, facts(t0.Add(30*time.Minute), hub))
|
||||
if !d.Ask {
|
||||
t.Fatalf("not running past the bound: %+v", d)
|
||||
}
|
||||
asked.Ask = "the-ask"
|
||||
if d, kept := step(asked, f); d.Ask || !d.Withdraw || kept.Ask != "" || !kept.Standing() || d.End != "" {
|
||||
t.Errorf("withdrawn: %+v %+v", d, kept)
|
||||
}
|
||||
f.Conds = nil
|
||||
if d, _ := step(asked, f); d.End != HowOwnFailure || d.Ask {
|
||||
t.Errorf("no cause open: %+v", d)
|
||||
}
|
||||
f.Failing, f.Healthy = false, true
|
||||
if d, _ := step(asked, f); d.End != HowCleared || d.Ask || d.Withdraw {
|
||||
t.Errorf("cleared: %+v", d)
|
||||
}
|
||||
}},
|
||||
{"a release to judge again changes nothing by itself", func(t *testing.T) {
|
||||
_, w := step(nil, facts(t0, hub))
|
||||
w.Release = HowRejudge
|
||||
|
||||
@@ -112,9 +112,28 @@ func (p Put) StandsSince() time.Time {
|
||||
|
||||
var digestForm = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
|
||||
|
||||
// Newest is the version a put names to take the newest version whose pipeline passed on the node's branch (design 47 H2b
|
||||
// §833); the program resolves it at the put's first step (H-A-862), as it resolves a prefix of a fingerprint (§834, H-A-848).
|
||||
const Newest = "newest"
|
||||
|
||||
var prefixForm = regexp.MustCompile(`^src2:[0-9a-f]{12,64}$`)
|
||||
|
||||
// Whole says fp is a whole fingerprint of the new form.
|
||||
func Whole(fp string) bool {
|
||||
_, err := catalogkey.KeyPart(fp)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Unresolved says fp is what a put names before its first step resolves it: Newest, or src2: and 12 to 63 hex digits.
|
||||
func Unresolved(fp string) bool {
|
||||
return fp == Newest || (prefixForm.MatchString(fp) && !Whole(fp))
|
||||
}
|
||||
|
||||
func (p Put) check() error {
|
||||
if _, err := catalogkey.KeyPart(p.FP); err != nil {
|
||||
return fmt.Errorf("puts: a put's fingerprint: %w", err)
|
||||
if !Unresolved(p.FP) {
|
||||
if _, err := catalogkey.KeyPart(p.FP); err != nil {
|
||||
return fmt.Errorf("puts: a put's fingerprint: %w", err)
|
||||
}
|
||||
}
|
||||
if p.Why == "" {
|
||||
return fmt.Errorf("puts: a put says why")
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestManifest(t *testing.T) {
|
||||
// revision, entry and difference from its revisions kept as objects in the old section, form 1, capped at 512 MiB.
|
||||
if len(m.Claims) != 2 || m.Claims[0].Name != meshmoduleassigner.Seat || m.Claims[0].At() != catalogue.ScopeMesh ||
|
||||
!slices.Equal(m.Claims[0].Serves, []string{"assignments", "proposals", "propose", "withdraw", "again", "placement"}) ||
|
||||
m.Claims[1].Name != meshwants.Seat || m.Claims[1].At() != catalogue.ScopeMesh || !slices.Equal(m.Claims[1].Serves, []string{"upgrade", "bus", "revision", "entry", "difference", "input", "compositions", "compositions-drop", "keep-now", "drop"}) {
|
||||
m.Claims[1].Name != meshwants.Seat || m.Claims[1].At() != catalogue.ScopeMesh || !slices.Equal(m.Claims[1].Serves, []string{"upgrade", "bus", "revision", "entry", "difference", "input", "compositions", "compositions-drop", "validate", "keep-now", "drop", "owed", "owed-say", "owed-drop"}) {
|
||||
t.Errorf("the assigner claims %+v, want mesh-module-assigner with its five verbs and mesh-wants with its five", m.Claims)
|
||||
}
|
||||
if len(m.Objects) != 1 || m.Objects[0].Name != "assignment-revisions" || m.Objects[0].MaxMiB != 512 || m.Objects[0].Form != 1 {
|
||||
@@ -116,8 +116,8 @@ func TestManifest(t *testing.T) {
|
||||
// which lists and asks again what each node's engine reads.
|
||||
if !slices.Equal(m.Tools, []string{"assigner_put", "assigner_release", "assigner_puts", "assigner_waits", "assigner_inputs", "assigner_inputs_drop", "assigner_compositions", "assigner_compositions_drop", "assignments", "seat-holders", "wants", "asks",
|
||||
"assigner_read_assignments", "assigner_read_seat_holders", "assigner_read_wants", "assigner_read_findings", "assigner_read_differences", "assigner_read_copies",
|
||||
"assigner_first_views", "assigner_first_view_again", "assigner_engine_reads", "assigner_seat_list", "assigner_seat_list_again", "assigner_ask_again", "assigner_written", "assigner_why", "assigner_want_drop", "assigner_asks", "assigner_ask_drop", "assigner_keep_now", "assigner_validate_before"}) {
|
||||
t.Errorf("the assigner serves tools %v, want its three put tools, three first views, six read tools, assigner_engine_reads, the seat list's two (ADR 0636 §7) assigner_ask_again (ADR 0668 §5) and assigner_why (design 47 G A-439)", m.Tools)
|
||||
"assigner_first_views", "assigner_first_view_again", "assigner_engine_reads", "assigner_seat_list", "assigner_seat_list_again", "assigner_ask_again", "assigner_written", "assigner_progress_drop", "assigner_wait_drop", "assigner_owed", "assigner_owed_say", "assigner_owed_drop", "assigner_why", "assigner_want_drop", "assigner_assignment_drop", "assigner_asks", "assigner_ask_drop", "assigner_keep_now", "assigner_validate_before", "assigner_validate"}) {
|
||||
t.Errorf("the assigner serves tools %v, want its three put tools, three first views, six read tools, assigner_engine_reads, the seat list's two (ADR 0636 §7) assigner_ask_again (ADR 0668 §5), assigner_why (design 47 G A-439) and assigner_assignment_drop after assigner_want_drop (design 47 H2 H-A-509)", m.Tools)
|
||||
}
|
||||
if m.RunsAs != m.Module || m.SecretsOwner != m.RunsAs {
|
||||
t.Errorf("runs-as = %q: the bundle runs on the assigner's own account (ADR 0621 §1)", m.RunsAs)
|
||||
@@ -153,16 +153,18 @@ func TestManifest(t *testing.T) {
|
||||
// issue 1966 note 151: and the teller's ask-ended, its subject the one the assigner hears; §389: the watchman's machine-away
|
||||
// and machine-back, read whole at its start. A1/AC1 (design 47 H §750, §764): no version-delivered, delivery-waits,
|
||||
// delivered-again or assigner_delivered_again: a want waits on no dependency's delivery.
|
||||
if !slices.Equal(m.Consumes, []string{"mesh-conditions.findings-asked", "mesh-conditions.condition-raised", "mesh-conditions.condition-changed", "mesh-conditions.condition-cleared", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-catalog.version-released", "mesh-watchdogs.machine-away", "mesh-watchdogs.machine-back", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", builds.BuilderModule + "." + builds.BuildsStreamEvents, buckets.TellerModule + "." + tellerevents.AskEnded, buckets.TellerModule + ".views." + buckets.AnswersState, "mesh-pipeline-runner.pipeline-ended", "node-build-go.step-ended", "node-build-go.ask-taken", "node-build-go.step-progress", "node-engine.manifest-reads-changed", "node-engine.running"}) {
|
||||
if !slices.Equal(m.Consumes, []string{"mesh-conditions.findings-asked", "mesh-conditions.condition-raised", "mesh-conditions.condition-changed", "mesh-conditions.condition-cleared", "mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "mesh-catalog.version-released", "mesh-watchdogs.machine-away", "mesh-watchdogs.machine-back", "mesh-catalog.seat-definition-changed", "mesh-catalog.seat-definition-removed", builds.BuilderModule + "." + builds.BuildsStreamEvents, "mesh-builds.package-published", buckets.TellerModule + "." + tellerevents.AskEnded, buckets.TellerModule + ".views." + buckets.AnswersState, "mesh-pipeline-runner.pipeline-ended", "node-build-go.step-ended", "node-build-go.ask-taken", "node-build-go.step-progress", "node-engine.manifest-reads-changed", "node-engine.running"}) {
|
||||
t.Errorf("consumes = %v, want the catalog half's revisions (design 47 G §195), the teller's ask-ended, the engines' reads changed and what they run", m.Consumes)
|
||||
}
|
||||
if want := []string{"mesh-delivery-indexer.manifests", "mesh-delivery-indexer.modules",
|
||||
buckets.TellerModule + "." + buckets.AnswersReadTool, // A-175, A-178: the teller's answers' first view
|
||||
"seat:mesh-builds.published", // design 47 H2 H-A-628 (2), H-A-328: a run's empty pin filled from its publisher's build (1984/AC9, AC10)
|
||||
"seat:mesh-catalog.entry", "seat:mesh-catalog.registrations", "seat:mesh-catalog.revision", "seat:mesh-catalog.seat-definitions", // ADR 0636 §4: the seat list
|
||||
"seat:mesh-catalog.seat-list", // design 47 H2 H-A-443: the validate step's trunk seat list, in chunks
|
||||
"seat:mesh-conditions.conditions", // design 47 G §706: the conditions read at each judging of an outside wait
|
||||
"seat:mesh-delivery.source", // §507: the branches the gate keeps a source revision of, before the first registrations
|
||||
"seat:mesh-hand-acts.hand-act", "seat:mesh-hand-acts.hand-acts", "seat:mesh-hand-acts.warranted", // ADR 0565 §9, §11: the seat alone
|
||||
"seat:mesh-pipeline-runner.show", // design 47 H2 H-A-684 (1), H-A-739: the candidate of the pipeline assigner_validate judges
|
||||
"seat:node-backup.backed-up", "seat:node-backup.now",
|
||||
"seat:node-build-go.accept.check", // A-231
|
||||
"seat:node-build-go.answer", // A-254, H-A-412: a composition run's answer over the inline bound, read through the build seat's verb answer
|
||||
@@ -184,11 +186,19 @@ func TestManifest(t *testing.T) {
|
||||
}
|
||||
file, _ := os.ReadFile("module.json")
|
||||
if err := json.Unmarshal(file, &raw); err != nil || raw.Config["outside-wait-minutes"].Default != float64(30) || raw.Config["outside-settle-seconds"].Default != float64(90) ||
|
||||
raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 15 || raw.Config["tier-bound"].Default != float64(30) || raw.Config["entry-asks"].Default != float64(5) ||
|
||||
raw.Config["ask-operator-for"].Default != "take-off,remove-node,stops" || len(raw.Config) != 21 || raw.Config["tier-bound"].Default != float64(30) || raw.Config["entry-asks"].Default != float64(5) || raw.Config["reads-bound"].Default != float64(8) ||
|
||||
raw.Config["composition-runs-cap-mib"].Default != float64(16) || raw.Config["composition-runs-kept"].Default != "24h" ||
|
||||
raw.Config["composition-step-bound"].Default != "30m" || raw.Config["run-untaken-bound"].Default != "24h" || raw.Config["blame-tries"].Default != float64(20) ||
|
||||
// design 47 H2 H-A-628 (3): the bound of a run's wait for a package's publish, the builder's default
|
||||
raw.Config["package-wait-minutes"].Default != float64(10) ||
|
||||
// design 47 H2 H-A-635: the bound a pass runs before it says which phase it is in
|
||||
raw.Config["pass-stall-seconds"].Default != float64(60) ||
|
||||
// design 47 H2 §775, H-A-381 (2): the taken key's bound and the kept-call pace, runtime settings
|
||||
raw.Config["ask-taken-bound"].Default != "10m" || raw.Config["kept-call-pace-first"].Default != "1s" || raw.Config["kept-call-pace-max"].Default != "30s" || raw.Config["compose-ask-bound"].Default != "10s" || raw.Config["keeping-retry"].Default != "30s" {
|
||||
raw.Config["ask-taken-bound"].Default != "10m" || raw.Config["kept-call-pace-first"].Default != "1s" || raw.Config["kept-call-pace-max"].Default != "30s" || raw.Config["compose-ask-bound"].Default != "10s" || raw.Config["keeping-retry"].Default != "30s" ||
|
||||
// design 47 H §832 2.: the pace an owed event is said again at
|
||||
raw.Config["say-again-pace-first"].Default != "2s" || raw.Config["say-again-pace-max"].Default != "1m" ||
|
||||
// design 47 H2b §832 6.: how long an event may stay owed before it is the finding event-unsaid
|
||||
raw.Config["event-unsaid-after"].Default != "5m" {
|
||||
t.Errorf("config = %+v (%v), want outside-wait-minutes of 30, outside-settle-seconds of 90 and ask-operator-for of take-off,remove-node,stops (A-425a)", raw.Config, err)
|
||||
}
|
||||
for _, f := range []struct{ env, path, key string }{
|
||||
@@ -201,14 +211,24 @@ func TestManifest(t *testing.T) {
|
||||
{"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE", "${dir:state}/composition-step-bound", "composition-step-bound"},
|
||||
{"MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE", "${dir:state}/run-untaken-bound", "run-untaken-bound"},
|
||||
{"MESH_ASSIGNER_BLAME_TRIES_FILE", "${dir:state}/blame-tries", "blame-tries"},
|
||||
{"MESH_ASSIGNER_TIER_BOUND_FILE", "${dir:state}/tier-bound", "tier-bound"}, // design 47 H §751
|
||||
{"MESH_ASSIGNER_ENTRY_ASKS_FILE", "${dir:state}/entry-asks", "entry-asks"}, // design 47 H H-A-60
|
||||
{"MESH_ASSIGNER_PACKAGE_WAIT_FILE", "${dir:state}/package-wait-minutes", "package-wait-minutes"}, // design 47 H2 H-A-628 (3)
|
||||
{"MESH_ASSIGNER_PASS_STALL_FILE", "${dir:state}/pass-stall-seconds", "pass-stall-seconds"}, // design 47 H2 H-A-635
|
||||
{"MESH_ASSIGNER_TIER_BOUND_FILE", "${dir:state}/tier-bound", "tier-bound"}, // design 47 H §751
|
||||
{"MESH_ASSIGNER_ENTRY_ASKS_FILE", "${dir:state}/entry-asks", "entry-asks"}, // design 47 H H-A-60
|
||||
{"MESH_ASSIGNER_READS_BOUND_FILE", "${dir:state}/reads-bound", "reads-bound"}, // design 47 H2 H-A-708 (3)
|
||||
{"MESH_ASSIGNER_SAY_AGAIN_PACE_FIRST_FILE", "${dir:state}/say-again-pace-first", "say-again-pace-first"}, // design 47 H §832 2.
|
||||
{"MESH_ASSIGNER_SAY_AGAIN_PACE_MAX_FILE", "${dir:state}/say-again-pace-max", "say-again-pace-max"},
|
||||
{"MESH_ASSIGNER_EVENT_UNSAID_AFTER_FILE", "${dir:state}/event-unsaid-after", "event-unsaid-after"}, // design 47 H2b §832 6.
|
||||
} {
|
||||
if !strings.Contains(string(file), `"`+f.env+`": "`+f.path+`"`) || !strings.Contains(string(file), `"path": "`+f.path+`"`) ||
|
||||
!strings.Contains(string(file), `"content": "${config:`+f.key+`}"`) {
|
||||
t.Errorf("the setting %s is not a file %s the env names as %s", f.key, f.path, f.env)
|
||||
}
|
||||
}
|
||||
// design 47 H2b §824 (review r1 finding 7): the setting's words say what a late tier does now, not the rule §824 replaces
|
||||
if strings.Contains(string(file), "writes no later tier") || !strings.Contains(string(file), "writes the next tier once that tier runs") {
|
||||
t.Errorf("the description of tier-bound states the rule design 47 H2b section 824 replaces")
|
||||
}
|
||||
if strings.Contains(string(file), `": "${config:outside-`) && strings.Contains(string(file), `"MESH_ASSIGNER_OUTSIDE_WAIT_MINUTES"`) {
|
||||
t.Errorf("the process's env still carries a setting")
|
||||
}
|
||||
|
||||
@@ -29,8 +29,12 @@
|
||||
"input",
|
||||
"compositions",
|
||||
"compositions-drop",
|
||||
"validate",
|
||||
"keep-now",
|
||||
"drop"
|
||||
"drop",
|
||||
"owed",
|
||||
"owed-say",
|
||||
"owed-drop"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -56,6 +60,7 @@
|
||||
"mesh-catalog.seat-definition-changed",
|
||||
"mesh-catalog.seat-definition-removed",
|
||||
"mesh-delivery-builder.build.ended.**",
|
||||
"mesh-builds.package-published",
|
||||
"mesh-delivery-teller.ask-ended",
|
||||
"mesh-delivery-teller.views.answers",
|
||||
"mesh-pipeline-runner.pipeline-ended",
|
||||
@@ -69,6 +74,7 @@
|
||||
"mesh-delivery-indexer.manifests",
|
||||
"mesh-delivery-indexer.modules",
|
||||
"mesh-delivery-teller.teller_read_answers",
|
||||
"seat:mesh-builds.published",
|
||||
"seat:mesh-catalog.entry",
|
||||
"seat:mesh-catalog.registrations",
|
||||
{"verb": "seat:mesh-catalog.revision", "fields": ["none-yet"]},
|
||||
@@ -79,6 +85,7 @@
|
||||
"seat:mesh-hand-acts.hand-act",
|
||||
"seat:mesh-hand-acts.hand-acts",
|
||||
"seat:mesh-hand-acts.warranted",
|
||||
"seat:mesh-pipeline-runner.show",
|
||||
"seat:node-backup.backed-up",
|
||||
"seat:node-backup.now",
|
||||
"seat:node-build-go.answer",
|
||||
@@ -132,12 +139,19 @@
|
||||
"assigner_seat_list_again",
|
||||
"assigner_ask_again",
|
||||
"assigner_written",
|
||||
"assigner_progress_drop",
|
||||
"assigner_wait_drop",
|
||||
"assigner_owed",
|
||||
"assigner_owed_say",
|
||||
"assigner_owed_drop",
|
||||
"assigner_why",
|
||||
"assigner_want_drop",
|
||||
"assigner_assignment_drop",
|
||||
"assigner_asks",
|
||||
"assigner_ask_drop",
|
||||
"assigner_keep_now",
|
||||
"assigner_validate_before"
|
||||
"assigner_validate_before",
|
||||
"assigner_validate"
|
||||
],
|
||||
"state": [
|
||||
{ "name": "assignments", "history": 64, "max-mib": 8 },
|
||||
@@ -188,12 +202,20 @@
|
||||
},
|
||||
"tier-bound": {
|
||||
"type": "number",
|
||||
"description": "minutes each tier of a pipeline's movers has to run on every present placing machine before the assigner writes the next tier's wants; a tier that does not run within it ends the delivery with the finding tier-late and writes no later tier (design 47 H section 751).",
|
||||
"description": "minutes each tier of a pipeline's movers has to run on every present placing machine before the assigner writes the next tier's wants; a tier that does not run within it is found late: the finding tier-late is raised and pipeline-wanted says tier-late, on which the delivery record ends failed, and the assigner writes the next tier once that tier runs (design 47 H2b section 824).",
|
||||
"minimum": 1,
|
||||
"maximum": 10080,
|
||||
"trusted": false,
|
||||
"default": 30
|
||||
},
|
||||
"reads-bound": {
|
||||
"type": "number",
|
||||
"description": "minutes a composition or validate run's reads of the seats mesh-catalog and mesh-builds may take in all, counted from the run's first read: the reads are kept calls paced by the form, and past it the run ends could not run with every call's time and words. Kept below the runner's ask-unanswered-bound (default 10 minutes, counted from the pull), so the step ends with the assigner's words; one set above it has the runner's bound end the step with its own (design 47 H2 H-A-708 (3)).",
|
||||
"minimum": 1,
|
||||
"maximum": 9,
|
||||
"trusted": false,
|
||||
"default": 8
|
||||
},
|
||||
"entry-asks": {
|
||||
"type": "number",
|
||||
"description": "how often the assigner asks a catalog entry again, on each catalog-revision and when its link to the bus opens again, after its ask failed to reach the holder of the seat mesh-catalog; one more failure leaves it unanswered, with the finding entry-unanswered (design 47 H, H-A-60).",
|
||||
@@ -228,6 +250,40 @@
|
||||
"trusted": false,
|
||||
"default": "24h"
|
||||
},
|
||||
"package-wait-minutes": {
|
||||
"type": "number",
|
||||
"description": "minutes a composition or validate run waits for the publish of a mesh package its entry names with no version, counted from the time its wait began, before it ends could not run naming the package (design 47 H2 H-A-628 (3), H-A-629 (3)); the builder's range and default.",
|
||||
"minimum": 1,
|
||||
"maximum": 120,
|
||||
"trusted": false,
|
||||
"default": 10
|
||||
},
|
||||
"say-again-pace-first": {
|
||||
"type": "string",
|
||||
"description": "the first wait before the assigner says again an event of the seat mesh-wants that the bus refused or did not acknowledge, under the same message id, doubling at each try to say-again-pace-max, a Go duration (design 47 H section 832 2.).",
|
||||
"trusted": false,
|
||||
"default": "2s"
|
||||
},
|
||||
"say-again-pace-max": {
|
||||
"type": "string",
|
||||
"description": "the longest wait between two says again of an owed event, a Go duration (design 47 H section 832 2.).",
|
||||
"trusted": false,
|
||||
"default": "1m"
|
||||
},
|
||||
"event-unsaid-after": {
|
||||
"type": "string",
|
||||
"description": "how long an event of the seat mesh-wants may stay owed before it is the finding event-unsaid, a Go duration (design 47 H2b section 832 6.).",
|
||||
"trusted": false,
|
||||
"default": "5m"
|
||||
},
|
||||
"pass-stall-seconds": {
|
||||
"type": "number",
|
||||
"description": "seconds a pass of the assigner may run before it says in the journal which phase it is in, and again at each further bound until it ends (design 47 H2 H-A-635).",
|
||||
"minimum": 10,
|
||||
"maximum": 600,
|
||||
"trusted": false,
|
||||
"default": 60
|
||||
},
|
||||
"blame-tries": {
|
||||
"type": "number",
|
||||
"description": "the most compositions a machine's composer makes to find the modules it blames, carried in the run's request as blame_tries (design 47 G section 721, A-466r).",
|
||||
@@ -327,6 +383,14 @@
|
||||
"mode": "0600",
|
||||
"content": "${config:tier-bound}"
|
||||
},
|
||||
{
|
||||
"id": "reads-bound",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/reads-bound",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:reads-bound}"
|
||||
},
|
||||
{
|
||||
"id": "entry-asks",
|
||||
"type": "file",
|
||||
@@ -367,6 +431,46 @@
|
||||
"mode": "0600",
|
||||
"content": "${config:run-untaken-bound}"
|
||||
},
|
||||
{
|
||||
"id": "package-wait-minutes",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/package-wait-minutes",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:package-wait-minutes}"
|
||||
},
|
||||
{
|
||||
"id": "say-again-pace-first",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/say-again-pace-first",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:say-again-pace-first}"
|
||||
},
|
||||
{
|
||||
"id": "say-again-pace-max",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/say-again-pace-max",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:say-again-pace-max}"
|
||||
},
|
||||
{
|
||||
"id": "event-unsaid-after",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/event-unsaid-after",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:event-unsaid-after}"
|
||||
},
|
||||
{
|
||||
"id": "pass-stall-seconds",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/pass-stall-seconds",
|
||||
"owner": "mesh-delivery-assigner",
|
||||
"mode": "0600",
|
||||
"content": "${config:pass-stall-seconds}"
|
||||
},
|
||||
{
|
||||
"id": "blame-tries",
|
||||
"type": "file",
|
||||
@@ -390,11 +494,17 @@
|
||||
"MESH_ASSIGNER_ASK_OPERATOR_FOR_FILE": "${dir:state}/ask-operator-for",
|
||||
"MESH_ASSIGNER_TIER_BOUND_FILE": "${dir:state}/tier-bound",
|
||||
"MESH_ASSIGNER_ENTRY_ASKS_FILE": "${dir:state}/entry-asks",
|
||||
"MESH_ASSIGNER_READS_BOUND_FILE": "${dir:state}/reads-bound",
|
||||
"MESH_ASSIGNER_COMPOSITION_RUNS_CAP_MIB_FILE": "${dir:state}/composition-runs-cap-mib",
|
||||
"MESH_ASSIGNER_COMPOSITION_RUNS_KEPT_FILE": "${dir:state}/composition-runs-kept",
|
||||
"MESH_ASSIGNER_COMPOSITION_STEP_BOUND_FILE": "${dir:state}/composition-step-bound",
|
||||
"MESH_ASSIGNER_RUN_UNTAKEN_BOUND_FILE": "${dir:state}/run-untaken-bound",
|
||||
"MESH_ASSIGNER_BLAME_TRIES_FILE": "${dir:state}/blame-tries"
|
||||
"MESH_ASSIGNER_BLAME_TRIES_FILE": "${dir:state}/blame-tries",
|
||||
"MESH_ASSIGNER_PACKAGE_WAIT_FILE": "${dir:state}/package-wait-minutes",
|
||||
"MESH_ASSIGNER_PASS_STALL_FILE": "${dir:state}/pass-stall-seconds",
|
||||
"MESH_ASSIGNER_SAY_AGAIN_PACE_FIRST_FILE": "${dir:state}/say-again-pace-first",
|
||||
"MESH_ASSIGNER_SAY_AGAIN_PACE_MAX_FILE": "${dir:state}/say-again-pace-max",
|
||||
"MESH_ASSIGNER_EVENT_UNSAID_AFTER_FILE": "${dir:state}/event-unsaid-after"
|
||||
},
|
||||
"user": "mesh-delivery-assigner",
|
||||
"health": {
|
||||
|
||||
@@ -19,7 +19,6 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/catalogkey"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/kept"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
@@ -240,9 +239,6 @@ type BuilderBuild struct {
|
||||
// its id (novox/hq ADR 0525 §1; issue 1887 A4b): a builder that takes the key over at its start waits for those asks'
|
||||
// steps and never puts them again. A reader that does not know the field reads the key as before.
|
||||
Asks map[string]string `json:"asks,omitempty"`
|
||||
// Imports are, on a done key, the mesh packages the built programs import, as the build module answered them
|
||||
// (BuildAnswer.Imports; novox/hq ADR 0593 §2): the builder carries them onto the build's end (BuildLogEntry.Imports).
|
||||
Imports []string `json:"imports,omitempty"`
|
||||
// Packages are, on a done key only, the mesh packages' versions its Go build was built with, by module path, the ones
|
||||
// the registry gave a package the entry named with none included (H-A-207): the build step's end reports them, so the
|
||||
// runner asks the steps that waited for the pins with what the build was built against. A reader that does not know
|
||||
@@ -272,9 +268,6 @@ func (b BuilderBuild) check() error {
|
||||
if b.KeptOn != "" && b.State != BuildDone {
|
||||
return fmt.Errorf("builds: a build is kept on a done key alone, this one is %s", b.State)
|
||||
}
|
||||
if err := trunk.CheckImports(b.Imports); err != nil {
|
||||
return err
|
||||
}
|
||||
switch b.State {
|
||||
case BuildQueued, BuildBuilding, BuildDone, BuildFailed:
|
||||
default:
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
@@ -70,10 +69,6 @@ type BuildLogEntry struct {
|
||||
// KeptOn is, at the end of a kept build, the build node that keeps it, once for the build (design 47 G §671): every
|
||||
// artifact in Made is kept there, with its digest. A build not kept carries none.
|
||||
KeptOn string `json:"kept-on,omitempty"`
|
||||
// Imports are, at a build's end, the mesh packages (import paths) the built programs import, their tests left out,
|
||||
// sorted and each once, as the build module answered them (BuildAnswer.Imports; novox/hq ADR 0593 §2): the indexer
|
||||
// keeps them on the module (KeptInputs2.Imports) when the build's fingerprint is the module's.
|
||||
Imports []string `json:"imports,omitempty"`
|
||||
// OutOfStep are, at a build's end, the generated files its test step found out of step with what their generator
|
||||
// writes, as the build module answered them (its test step's `out-of-step`): the indexer raises a finding naming them
|
||||
// for a trunk build, and only a clean build of the same module clears it. A start or a narration names none.
|
||||
@@ -132,9 +127,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
|
||||
switch {
|
||||
case e.Module == "" || e.FP == "" || e.At.IsZero() || e.Line == "":
|
||||
return nil, fmt.Errorf("builds: a build's narration names its module, fingerprint, line and time")
|
||||
case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 || len(e.OutOfStep) > 0 ||
|
||||
case e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.OutOfStep) > 0 ||
|
||||
e.Error != "" || e.Step != "":
|
||||
return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, import, file out of step, error or step")
|
||||
return nil, fmt.Errorf("builds: a build's narration names no outcome, manifest, base, artifact, file out of step, error or step")
|
||||
}
|
||||
return json.Marshal(e)
|
||||
case e.Event != BuildStartedEvent && e.Event != BuildEndedEvent:
|
||||
@@ -145,12 +140,9 @@ func EncodeBuildLogEntry(e BuildLogEntry) ([]byte, error) {
|
||||
return nil, fmt.Errorf("builds: a build log entry names its module, fingerprint, repository, commit, node and time")
|
||||
case e.Event == BuildEndedEvent && e.Outcome == "":
|
||||
return nil, fmt.Errorf("builds: a build's end names its outcome")
|
||||
case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 || len(e.Imports) > 0 ||
|
||||
case e.Event == BuildStartedEvent && (e.Outcome != "" || len(e.Made) > 0 || e.Manifest != "" || len(e.Against) > 0 ||
|
||||
len(e.OutOfStep) > 0 || e.Error != "" || e.Step != ""):
|
||||
return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, import, file out of step, error or step")
|
||||
}
|
||||
if err := trunk.CheckImports(e.Imports); err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("builds: a build's start names no outcome, manifest, base, artifact, file out of step, error or step")
|
||||
}
|
||||
return json.Marshal(e)
|
||||
}
|
||||
|
||||
@@ -41,10 +41,10 @@ type queueAsker func(key string, value []byte) (json.RawMessage, error)
|
||||
// Tools are the builder's tools: stuck reads, askAgain writes the reasks value, queue writes a queues value and waits for
|
||||
// the builder's read, buildAgain writes a reasks value of mode build and waits for the builder's answer.
|
||||
//
|
||||
// builder_versions, asked by a name, answers also what the verb reserved answers for it (reserve; design 47 G §572): the
|
||||
// bundle calls the seat mesh-builds through its invokes, as any caller does. Nil answers none.
|
||||
func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time, vs versions.Reader,
|
||||
fw, of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool {
|
||||
// builder_versions answers from the reservations alone, what the verb reserved answers for a name (reserve; design 47 G §572,
|
||||
// H §756): the bundle calls the seat mesh-builds through its invokes, as any caller does.
|
||||
func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, queue, buildAgain queueAsker, since build.LogSince, now func() time.Time,
|
||||
of versions.Reader, reserve func(name, version string) (meshbuilds.ReservedAnswer, error)) []stdio.Tool {
|
||||
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
|
||||
// handAct writes a reasks value of a versions hand act and answers the builder's answer, or its refusal as an error.
|
||||
handAct := func(key string, value []byte, err error) (any, error) {
|
||||
@@ -65,13 +65,6 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
|
||||
return map[string]any{"key": key, "name": a.Name, "answer": a.Answer}, nil
|
||||
}
|
||||
return []stdio.Tool{
|
||||
{Name: versions.FloorAgainTool, Description: versions.FloorAgainDescription,
|
||||
Input: map[string]any{"type": "object", "required": []string{"name", "why"}, "properties": map[string]any{
|
||||
"name": map[string]any{"type": "string", "description": "the numbered name, <module>/<artifact>"},
|
||||
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
return handAct(build.NewFloorAgain(str(args, "name"), str(args, "why"), stdio.CallerOf(args), now()))
|
||||
}},
|
||||
{Name: versions.OldFormTool, Description: versions.OldFormDescription,
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{
|
||||
"drop": map[string]any{"type": "string", "description": "a retired node to drop from the count by hand"},
|
||||
@@ -82,25 +75,13 @@ func Tools(r build.StuckReader, askAgain func(key string, value []byte) error, q
|
||||
}
|
||||
return versions.AnswerOldForm(of)
|
||||
}},
|
||||
{Name: versions.FloorWaitsTool, Description: versions.FloorWaitsDescription,
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{}},
|
||||
Run: func(map[string]any) (any, error) { return versions.AnswerFloorWaits(fw) }},
|
||||
{Name: versions.VersionsTool, Description: versions.VersionsDescription,
|
||||
Input: map[string]any{"type": "object", "required": []string{"name"}, "properties": map[string]any{
|
||||
"name": map[string]any{"type": "string", "description": "the package, image, bundle or archive name"},
|
||||
"version": map[string]any{"type": "string", "description": "one version, to ask whether it is recorded"},
|
||||
"digest": map[string]any{"type": "string", "description": "with version: the digest the holder received"}}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
out, err := versions.AnswerVersions(context.Background(), vs, str(args, "name"), str(args, "version"), str(args, "digest"))
|
||||
if err != nil || reserve == nil {
|
||||
return out, err
|
||||
}
|
||||
ra, err := reserve(out.Name, str(args, "version"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the seat mesh-builds' reserved did not answer for %s: %w", out.Name, err)
|
||||
}
|
||||
out.Reserved = &ra
|
||||
return out, nil
|
||||
return versions.AnswerVersions(str(args, "name"), str(args, "version"), str(args, "digest"), reserve)
|
||||
}},
|
||||
{Name: build.StuckTool,
|
||||
Description: "Every build key that waits (building or queued), oldest first: its module, fingerprint, step words and since when, and each ask it " +
|
||||
@@ -348,7 +329,7 @@ const (
|
||||
|
||||
func main() {
|
||||
reasks := stdio.State(build.ReAsksState)
|
||||
r := build.StuckReader{Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-builder-tools] "+f+"\n", a...) }, Builds: read(stdio.State("builds")), ReAsks: read(reasks), StepsOf: stepsOfHolder(func(seat string) (string, error) { return seatlist.HolderOf(stdio.Ask, seat) }, func(name string) build.StateRead { return read(stdio.State(name)) }),
|
||||
r := build.StuckReader{Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, "[mesh-delivery-builder-tools] "+f+"\n", a...) }, Builds: read(stdio.State("builds")), ReAsks: read(reasks), Waits: read(stdio.State(build.WaitsState)), StepsOf: stepsOfHolder(func(seat string) (string, error) { return seatlist.HolderOf(stdio.Ask, seat) }, func(name string) build.StateRead { return read(stdio.State(name)) }),
|
||||
Hearing: read(stdio.State(buildrun.HearingState))}
|
||||
put := func(key string, value []byte) error {
|
||||
_, err := reasks.Put(key, json.RawMessage(value))
|
||||
@@ -358,22 +339,6 @@ func main() {
|
||||
a, err := build.DecodeReAsk(v)
|
||||
return err == nil && !a.Answered.IsZero()
|
||||
})
|
||||
vs := stdio.State(versions.State)
|
||||
vr := versions.Reader{Keys: vs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
|
||||
e, err := vs.Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return e.Value, true, nil
|
||||
}}
|
||||
fs := stdio.State(versions.FloorWaitsState)
|
||||
fr := versions.Reader{Keys: fs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
|
||||
e, err := fs.Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return e.Value, true, nil
|
||||
}}
|
||||
ofs := stdio.State(versions.OldFormState)
|
||||
ofr := versions.Reader{Keys: ofs.Keys, Get: func(key string) (json.RawMessage, bool, error) {
|
||||
e, err := ofs.Get(key)
|
||||
@@ -429,13 +394,13 @@ func main() {
|
||||
var a meshbuilds.ReservedAnswer
|
||||
return a, json.Unmarshal(raw, &a)
|
||||
}
|
||||
tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, vr, fr, ofr, reserve)
|
||||
tools := Tools(r, put, askQueue(stdio.State(build.QueuesState), 25*time.Second), buildAgain, stdio.Log(builds.BuilderLog).Since, time.Now, ofr, reserve)
|
||||
tools = append(tools, buildTool(&build.BuildReader{Builds: read(stdio.State("builds")), Entry: entryOf(stdio.State("builds").Get), Asked: read(stdio.State("asked")),
|
||||
Newest: newestVia(stdio.Ask), Steps: r}))
|
||||
tools = append(tools, reservedTools(rr, buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
as := stdio.State(versions.ActedState)
|
||||
tools = append(tools, publishActTools(buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
tools = append(tools, republishTools(publishQueueVia(stdio.Ask), readerOf(as), readerOf(reasks), buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
tools = append(tools, republishTools(publishQueueVia(stdio.Ask), readerOf(as), buildAgain, time.Now, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
ws := stdio.State(build.WaitsState)
|
||||
wr := versions.Reader{Keys: ws.Keys, Get: func(key string) (json.RawMessage, bool, error) {
|
||||
e, err := ws.Get(key)
|
||||
|
||||
@@ -114,7 +114,7 @@ func publishActTools(ask queueAsker, now func() time.Time, acts meshhandactsclie
|
||||
// republishTools are builder_publish_again and builder_publish_queue (design 47 G §588). The publish again is a hand act:
|
||||
// it is recorded in the hand-act log first, then written to reasks for the builder, which owns the queue, to answer
|
||||
// with the versions it queued.
|
||||
func republishTools(queue func(module, version string) (meshbuilds.PublishQueueAnswer, error), acted, reasks versions.Reader, ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool {
|
||||
func republishTools(queue func(module, version string) (meshbuilds.PublishQueueAnswer, error), acted versions.Reader, ask queueAsker, now func() time.Time, acts meshhandactsclient.Recorder) []stdio.Tool {
|
||||
str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) }
|
||||
return []stdio.Tool{
|
||||
{Name: versions.PublishAgainTool, Description: versions.PublishAgainDescription,
|
||||
@@ -153,7 +153,7 @@ func republishTools(queue func(module, version string) (meshbuilds.PublishQueueA
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return versions.AnswerQueue(q, acted, reasks)
|
||||
return versions.AnswerQueue(q, acted)
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestAStateIsReadInOnePage(t *testing.T) {
|
||||
Queue: []meshbuilds.PublishQueueAnswerQueueItem{{Holder: "oci", Module: "m", Version: "0.1.0", Class: versions.PublishClassStart}}})
|
||||
}
|
||||
none := versions.Reader{Keys: func() ([]string, error) { return nil, nil }}
|
||||
tools := republishTools(publishQueueVia(ask), none, none, nil, time.Now, meshhandactsclient.Recorder{})
|
||||
tools := republishTools(publishQueueVia(ask), none, nil, time.Now, meshhandactsclient.Recorder{})
|
||||
raw, err := tools[1].Run(map[string]any{"module": "m"})
|
||||
a, _ := raw.(versions.Queued)
|
||||
if err != nil || fmt.Sprint(asked) != "[seat:mesh-builds.publish-queue m]" || a.Total != 9000 || len(a.Queue) != 1 || a.Queue[0].Module != "m" ||
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// reservedTools are builder_reserved, builder_reserved_drop and builder_reserve_done (A-455) (design 47 G section 369), served as tools of the bundle. The drop is a hand act: it is recorded in the hand-act log first, then written to
|
||||
// reservedTools are builder_reserved and builder_reserved_drop (design 47 G section 369), served as tools of the bundle. The drop is a hand act: it is recorded in the hand-act log first, then written to
|
||||
// reasks for the builder, which owns the reservations, to answer.
|
||||
//
|
||||
// The seat's verb reserved is the builder's process's (design 47 G A-115, A-127), not the bundle's.
|
||||
@@ -25,16 +25,17 @@ func reservedTools(rr versions.Reader, ask queueAsker, now func() time.Time, act
|
||||
"module": map[string]any{"type": "string", "description": "only this module's reservations"}}},
|
||||
Run: func(args map[string]any) (any, error) { return versions.AnswerReserved(rr, str(args, "module")) }},
|
||||
{Name: versions.ReservedDropTool, Description: versions.ReservedDropDescription,
|
||||
Input: map[string]any{"type": "object", "required": []string{"module", "series", "why"}, "properties": map[string]any{
|
||||
"module": map[string]any{"type": "string", "description": "the module"},
|
||||
"series": map[string]any{"type": "string", "description": "its MAJOR.MINOR"},
|
||||
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
|
||||
Input: map[string]any{"type": "object", "required": []string{"module", "series", "version", "why"}, "properties": map[string]any{
|
||||
"module": map[string]any{"type": "string", "description": "the module"},
|
||||
"series": map[string]any{"type": "string", "description": "its MAJOR.MINOR"},
|
||||
"version": map[string]any{"type": "string", "description": "the MAJOR.MINOR.PATCH the reservation stands at, as builder_reserved shows it: a newer one is never dropped"},
|
||||
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
key, value, err := build.NewReservedDrop(str(args, "module"), str(args, "series"), str(args, "why"), stdio.CallerOf(args), now())
|
||||
key, value, err := build.NewReservedDrop(str(args, "module"), str(args, "series"), str(args, "version"), str(args, "why"), stdio.CallerOf(args), now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("dropped the reservation of %s %s by hand", str(args, "module"), str(args, "series")),
|
||||
if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("dropped the reservation of %s %s by hand", str(args, "module"), str(args, "version")),
|
||||
Why: str(args, "why"), Cause: versions.ReservedDropTool, Verb: "reserved-drop"}); err != nil {
|
||||
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was dropped: %w", err)
|
||||
}
|
||||
@@ -51,32 +52,5 @@ func reservedTools(rr versions.Reader, ask queueAsker, now func() time.Time, act
|
||||
}
|
||||
return map[string]any{"key": key, "answer": a.Answer}, nil
|
||||
}},
|
||||
{Name: versions.ReserveDoneTool, Description: versions.ReserveDoneDescription,
|
||||
Input: map[string]any{"type": "object", "required": []string{"module", "fp", "why"}, "properties": map[string]any{
|
||||
"module": map[string]any{"type": "string", "description": "the module"},
|
||||
"fp": map[string]any{"type": "string", "description": "the fingerprint of its done trunk build"},
|
||||
"why": map[string]any{"type": "string", "description": "why, in plain words"}}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
key, value, err := build.NewReserveDone(str(args, "module"), str(args, "fp"), str(args, "why"), stdio.CallerOf(args), now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("reserved a version for the done build of %s at %s by hand", str(args, "module"), str(args, "fp")),
|
||||
Why: str(args, "why"), Cause: versions.ReserveDoneTool, Verb: "reserve-done"}); err != nil {
|
||||
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was reserved: %w", err)
|
||||
}
|
||||
raw, err := ask(key, value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, err := build.DecodeReAsk(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if a.Refused {
|
||||
return nil, errors.New(a.Answer)
|
||||
}
|
||||
return map[string]any{"key": key, "answer": a.Answer}, nil
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestBuilderVersionsByNameCallsReserved(t *testing.T) {
|
||||
called = append(called, name+"@"+version)
|
||||
return want, nil
|
||||
}
|
||||
tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, none, none, reserve)
|
||||
tools := Tools(build.StuckReader{}, nil, nil, nil, nil, time.Now, none, reserve)
|
||||
for _, tl := range tools {
|
||||
if tl.Name == versions.VersionsTool {
|
||||
out, err := tl.Run(map[string]any{"name": "@novox/mesh-sdk", "version": "0.1.2"})
|
||||
|
||||
@@ -23,7 +23,7 @@ func waitsTools(rr versions.Reader, ask queueAsker, now func() time.Time, acts m
|
||||
return []stdio.Tool{
|
||||
{Name: build.WaitsTool,
|
||||
Description: "The builder's toolchain waits: each entry held because its fingerprint names a toolchain version of its language other than the " +
|
||||
"agreed one, with its module, fingerprint, what it waits on (toolchain:<language>@<version>) and since when. It ends when the agreed toolchain " +
|
||||
"agreed one, and each build waiting for a package's blank pin (package:<path>, with its publisher, the catalog revision it holds and until when), with its module, fingerprint, what it waits on (toolchain:<language>@<version>) and since when. It ends when the agreed toolchain " +
|
||||
"names that version (ran) or when " + build.ReleaseTool + " builds it with the running build module (released). Read-only.",
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{}},
|
||||
Run: func(map[string]any) (any, error) {
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -45,56 +44,3 @@ func TestWaitsToolsListTheWaitsAndReleaseAfterTheHandAct(t *testing.T) {
|
||||
t.Fatalf("release: %v, %d recorded, asked %+v", err, recorded, asked)
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G A-455: builder_reserve_done records the hand act first and only then asks the builder through reasks; the builder's
|
||||
// answer (the version and its queued publish) is the tool's answer, its refusal the tool's error, and an act that was not
|
||||
// recorded asks nothing.
|
||||
func TestReserveDoneRecordsTheHandActFirstAndAnswersTheBuilders(t *testing.T) {
|
||||
var order []string
|
||||
var asked []build.ReAsk
|
||||
reply := func(refuse bool) func(string, []byte) (json.RawMessage, error) {
|
||||
return func(key string, value []byte) (json.RawMessage, error) {
|
||||
order = append(order, "asked")
|
||||
a, _ := build.DecodeReAsk(value)
|
||||
asked = append(asked, a)
|
||||
a.Answered, a.Answer, a.Refused = time.Now(), "reserved 0.1.13 for node-tools and queued 1 versions to publish: node-tools@0.1.13", refuse
|
||||
if refuse {
|
||||
a.Answer = "the build key is not done"
|
||||
}
|
||||
return json.Marshal(a)
|
||||
}
|
||||
}
|
||||
record := func(fail bool) meshhandactsclient.Recorder {
|
||||
return meshhandactsclient.Recorder{Ask: func(string, any) (json.RawMessage, error) {
|
||||
order = append(order, "recorded")
|
||||
if fail {
|
||||
return nil, errors.New("no responders")
|
||||
}
|
||||
return json.RawMessage(`{}`), nil
|
||||
}}
|
||||
}
|
||||
run := func(ask func(string, []byte) (json.RawMessage, error), acts meshhandactsclient.Recorder, args map[string]any) (any, error) {
|
||||
for _, tl := range reservedTools(versions.Reader{}, ask, time.Now, acts) {
|
||||
if tl.Name == versions.ReserveDoneTool {
|
||||
return tl.Run(args)
|
||||
}
|
||||
}
|
||||
t.Fatal("the bundle serves no builder_reserve_done")
|
||||
return nil, nil
|
||||
}
|
||||
args := map[string]any{"module": "node-tools", "fp": "src2:7df8", "why": "its build ended done with no version"}
|
||||
out, err := run(reply(false), record(false), args)
|
||||
if err != nil || len(order) != 2 || order[0] != "recorded" || order[1] != "asked" || asked[0].Mode != build.ModeReserveDone || asked[0].Name != "node-tools" || asked[0].FP != "src2:7df8" {
|
||||
t.Fatalf("answer %v, %v; order %v, asked %+v", out, err, order, asked)
|
||||
}
|
||||
if ans := out.(map[string]any)["answer"].(string); !strings.Contains(ans, "reserved 0.1.13") || !strings.Contains(ans, "queued 1 versions") {
|
||||
t.Errorf("the answer %q names no version and queued publish", ans)
|
||||
}
|
||||
if _, err := run(reply(true), record(false), args); err == nil || !strings.Contains(err.Error(), "not done") {
|
||||
t.Errorf("the builder's refusal is not the tool's error: %v", err)
|
||||
}
|
||||
order = nil
|
||||
if _, err := run(reply(false), record(true), args); err == nil || len(order) != 1 || order[0] != "recorded" {
|
||||
t.Errorf("an unrecorded act was asked of the builder: %v, %v", err, order)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// Design 47 H2 H-A-720 (1), H-A-741: a mark is updated by one publish carrying its lifetime and the expected last sequence of its
|
||||
// key: the update at the right revision succeeds and the key keeps its lifetime; one at a stale revision is a conflict.
|
||||
func TestAMarkIsUpdatedWithItsLifetimeInOnePublish(t *testing.T) {
|
||||
b := startBed(t)
|
||||
kv, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: "acted-test", LimitMarkerTTL: time.Minute})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := versions.ActedKey("retake:x")
|
||||
rev, err := kv.Create(b.ctx, key, []byte("1"), jetstream.KeyTTL(time.Hour))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := updateWithLifetime(b.ctx, b.js, "acted-test", key, []byte("2"), rev, 2*time.Hour)
|
||||
if err != nil || next <= rev {
|
||||
t.Fatalf("update at the key's revision: %d, %v", next, err)
|
||||
}
|
||||
if e, err := kv.Get(b.ctx, key); err != nil || string(e.Value()) != "2" || e.Revision() != next {
|
||||
t.Fatalf("the key holds %v, %v after the update", e, err)
|
||||
}
|
||||
if _, err := updateWithLifetime(b.ctx, b.js, "acted-test", key, []byte("3"), rev, time.Hour); !errors.Is(err, versions.ErrConflict) {
|
||||
t.Fatalf("update at a stale revision: %v, want a conflict", err)
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,12 @@ import (
|
||||
// ownBuckets are the buckets of the builder's own states, each `<module>_<state>` of the module its credential names, never
|
||||
// a constant (design 47 G A-296, §428).
|
||||
type ownBuckets struct {
|
||||
versions, bounds, reserved, queue, acted, toolchainsHeard, instances string
|
||||
bounds, reserved, queue, acted, toolchainsHeard, instances string
|
||||
}
|
||||
|
||||
func ownBucketsOf(module string) ownBuckets {
|
||||
return ownBuckets{
|
||||
versions: builds.StateBucket(module, versions.State), bounds: builds.StateBucket(module, versions.BoundsState),
|
||||
bounds: builds.StateBucket(module, versions.BoundsState),
|
||||
reserved: builds.StateBucket(module, versions.ReservedState), queue: builds.StateBucket(module, versions.PublishQueueState),
|
||||
acted: builds.StateBucket(module, versions.ActedState), toolchainsHeard: builds.StateBucket(module, buildrun.ToolchainsHeardState),
|
||||
instances: builds.StateBucket(module, instancesState),
|
||||
|
||||
@@ -75,8 +75,6 @@ type catalogHalf struct {
|
||||
halves map[string]*views.Follower
|
||||
once sync.Once
|
||||
ctx context.Context
|
||||
// floor is told each entry change: a floor whose tags or requirements were silent is asked again (design 47 G A-119).
|
||||
floor func(context.Context)
|
||||
// holders is told each entry change: a claim of a build seat may have moved (design 47 G A-82).
|
||||
holders func()
|
||||
}
|
||||
@@ -112,9 +110,6 @@ func (c *catalogHalf) Changed(ctx context.Context) func(branch, module string, e
|
||||
c.logf("%v", err)
|
||||
}
|
||||
c.b.Entry(ctx, origin, e)
|
||||
if c.floor != nil {
|
||||
defer c.floor(ctx)
|
||||
}
|
||||
c.mu.Lock()
|
||||
was := c.named[module]
|
||||
now := namesOf(e)
|
||||
@@ -183,6 +178,20 @@ func (w sweepWiring) Adopt(f *views.Follower, seatName, event string, hear func(
|
||||
return nil
|
||||
}
|
||||
|
||||
// AdoptEvent registers a seat's event on the wrapped reader before its Start, as the branch follower asks of a wiring that has a hub
|
||||
// to refuse a pattern registered after it (design 47 H2b §836 3., H-A-854): without it the first branch followed after Start
|
||||
// registers catalog-revision too late.
|
||||
func (w sweepWiring) AdoptEvent(seat, event string, hear func(context.Context, []byte) error) error {
|
||||
ew, ok := w.Wiring.(interface {
|
||||
AdoptEvent(seat, event string, hear func(context.Context, []byte) error) error
|
||||
})
|
||||
if !ok {
|
||||
// Said, not passed over: the event would be registered by none, so it would be heard by none (design 47 H2b §836 3.).
|
||||
return fmt.Errorf("the events %q of the seat %s are not registered: the builder's reader cannot adopt an event before its start", event, seat)
|
||||
}
|
||||
return ew.AdoptEvent(seat, event, hear)
|
||||
}
|
||||
|
||||
// Follow follows a plain view through the wrapped wiring (meshcatalogclient's SeatHolders, A-298).
|
||||
func (w sweepWiring) Follow(owner, state, tool string) (func() map[string]json.RawMessage, error) {
|
||||
f, ok := w.Wiring.(interface {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
// handlers is where a part of the builder registers its handler of the events it hears: the event hub, or agedHub over it.
|
||||
type handlers interface {
|
||||
Handle(pattern string, handle func(jetstream.Msg)) error
|
||||
HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error
|
||||
}
|
||||
|
||||
// ledgers are the builder's durable consumers' ledgers, one per consumer as a message's metadata names it (the events consumer
|
||||
@@ -56,7 +57,16 @@ type agedHub struct {
|
||||
}
|
||||
|
||||
func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error {
|
||||
return a.hub.Handle(pattern, func(m jetstream.Msg) {
|
||||
return a.hub.Handle(pattern, a.aged(handle))
|
||||
}
|
||||
|
||||
// HandleByKey registers handle held by key, each message noted as Handle's are.
|
||||
func (a agedHub) HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error {
|
||||
return a.hub.HandleByKey(pattern, key, a.aged(handle))
|
||||
}
|
||||
|
||||
func (a agedHub) aged(handle func(jetstream.Msg)) func(jetstream.Msg) {
|
||||
return func(m jetstream.Msg) {
|
||||
led := a.ledgers.of(m)
|
||||
if led == nil {
|
||||
handle(m)
|
||||
@@ -64,7 +74,7 @@ func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error {
|
||||
}
|
||||
led.Delivered(m)
|
||||
handle(&agedMsg{Msg: m, ledger: led})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// agedMsg is a message whose acknowledgement or end is noted applied on its consumer's ledger, once.
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// slowEventSetting is the setting slow-event (design 47 H2 §794; H-A-461 (2), P11): how long the handling of one heard event
|
||||
@@ -53,3 +59,30 @@ func takeEvent(m jetstream.Msg, takers []eventTaker, rest eventTaker, slow time.
|
||||
logf("the event %s took %s to handle, over %s: %s took it", m.Subject(), took.Round(time.Millisecond), slow, part)
|
||||
}
|
||||
}
|
||||
|
||||
// eventKey is the key the hub holds a builder's event under (design 47 H2 H-A-683 (1), H-A-737 (1)): a registry seat's outcome's
|
||||
// name, a version-released's module, the node the subject of the seat node-engine's running and manifest-reads-changed names,
|
||||
// else "" (the events naming none share one key). One key's events are handled one at a time in the order heard, the keys side by
|
||||
// side, so a slow handling of one node's event holds back no other node's.
|
||||
func eventKey(subject string, data []byte) string {
|
||||
if _, ok := seatEvents[subject]; ok {
|
||||
var o versions.Outcome
|
||||
if json.Unmarshal(data, &o) == nil {
|
||||
return "name " + o.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if subject == meshcatalog.SubjectVersionReleased {
|
||||
var ev meshcatalog.VersionReleasedEvent
|
||||
if json.Unmarshal(data, &ev) == nil {
|
||||
return "module " + ev.Module
|
||||
}
|
||||
return ""
|
||||
}
|
||||
// mesh.seat.node-engine.event.running.<node>.<module> and mesh.seat.node-engine.event.manifest-reads-changed.<node>
|
||||
if t := strings.Split(subject, "."); len(t) >= 6 && t[2] == "node-engine" && t[3] == "event" &&
|
||||
(t[4] == nodeengine.EventRunning || t[4] == nodeengine.EventManifestReadsChanged) {
|
||||
return "node " + t[5]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
)
|
||||
|
||||
// lastKept reads whether the stream keeps a message on a subject: found false when the stream or the message is not there.
|
||||
type lastKept func(ctx context.Context, subject string) (found bool, err error)
|
||||
|
||||
// lastKeptOf reads the seat event's own kept stream (the contract's StreamVersionsFilled, kept by age) the way any kept event
|
||||
// is heard (design 47 G A-411, A-233): the SDK's hearing of it from its first message, whose start read hands every message
|
||||
// kept to the handler; the reading is stopped once the read ended, the hub's own hearing following the durable. Nothing of
|
||||
// EVENTS is read.
|
||||
func lastKeptOf(js jetstream.JetStream, acct process.Account, logf func(string, ...any)) lastKept {
|
||||
return func(ctx context.Context, subject string) (bool, error) {
|
||||
var found atomic.Bool
|
||||
cc, err := acct.HearSeatEvents(ctx, js, meshcatalog.StreamVersionsFilled, func(m jetstream.Msg) {
|
||||
if m.Subject() == subject {
|
||||
found.Store(true)
|
||||
}
|
||||
_ = m.Ack() // a message of the durable is taken as the hub takes it; an ordered read's has nothing to acknowledge
|
||||
}, logf, process.FromFirst())
|
||||
if err != nil {
|
||||
if errors.Is(err, jetstream.ErrStreamNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
cc.Stop()
|
||||
return found.Load(), nil
|
||||
}
|
||||
}
|
||||
|
||||
// readFilled reads at the builder's start the last versions-filled the stream keeps (design 47 G §369, §372, A-411) and takes it as heard; the event heard later sets it as before. Nothing found leaves it unset, said; a
|
||||
// read that failed is said and tried again in the background with backoff, never holding the start.
|
||||
func (rv *reservations) readFilled(ctx context.Context, read lastKept, wait func(context.Context, time.Duration) bool) {
|
||||
const first, most = time.Second, time.Minute
|
||||
try := func() (done bool, err error) {
|
||||
found, err := read(ctx, meshcatalog.SubjectVersionsFilled)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !found {
|
||||
rv.logf("the stream keeps no versions-filled yet (read at start): versions are reserved once the catalog says it")
|
||||
return true, nil
|
||||
}
|
||||
rv.filled.Store(true)
|
||||
rv.logf("the catalog said versions-filled (read at start): versions are reserved from now on")
|
||||
if rv.wake != nil {
|
||||
rv.wake(ctx)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if done, err := try(); done {
|
||||
return
|
||||
} else {
|
||||
rv.logf("the last versions-filled is not read at start: %v; read again in the background", err)
|
||||
}
|
||||
go func() {
|
||||
for d := first; ; d = min(d*2, most) {
|
||||
if !wait(ctx, d) {
|
||||
return
|
||||
}
|
||||
done, err := try()
|
||||
if done {
|
||||
return
|
||||
}
|
||||
rv.logf("the last versions-filled is not read: %v; read again in %s", err, min(d*2, most))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// sleeps waits d, as a context's bound (ADR 0437 §8: the builder holds no timer); false when ctx ended first.
|
||||
func sleeps(ctx context.Context, d time.Duration) bool {
|
||||
bound, cancel := context.WithTimeout(ctx, d)
|
||||
defer cancel()
|
||||
<-bound.Done()
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTheLastVersionsFilledIsReadAtStart(t *testing.T) {
|
||||
boom := errors.New("bus down")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
results []error // per read: nil found, boom fails
|
||||
notFound bool
|
||||
wantFilled bool
|
||||
wantReads int
|
||||
waits []time.Duration
|
||||
}{
|
||||
{"kept", []error{nil}, false, true, 1, nil},
|
||||
{"none kept", []error{nil}, true, false, 1, nil},
|
||||
{"read fails then kept", []error{boom, boom, nil}, false, true, 3, []time.Duration{time.Second, 2 * time.Second}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rv := newReservations(nil, nil, nil, nil, nil, t.Logf)
|
||||
var mu sync.Mutex
|
||||
woke := make(chan struct{}, 1)
|
||||
rv.wake = func(context.Context) { woke <- struct{}{} }
|
||||
reads := 0
|
||||
read := func(_ context.Context, subject string) (bool, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
err := tc.results[reads]
|
||||
reads++
|
||||
return !tc.notFound, err
|
||||
}
|
||||
var waits []time.Duration
|
||||
wait := func(_ context.Context, d time.Duration) bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
waits = append(waits, d)
|
||||
return true
|
||||
}
|
||||
rv.readFilled(context.Background(), read, wait)
|
||||
if tc.wantFilled {
|
||||
select {
|
||||
case <-woke:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the read did not take the fill")
|
||||
}
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if rv.Filled() != tc.wantFilled || reads != tc.wantReads {
|
||||
t.Fatalf("filled %v reads %d", rv.Filled(), reads)
|
||||
}
|
||||
if !reflect.DeepEqual(waits, tc.waits) {
|
||||
t.Fatalf("backoff %v, want %v", waits, tc.waits)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -13,18 +13,21 @@ import (
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// heldWriter is the builder's finding writer: its findings are raised as they happen, so the writer holds them (design 47 G
|
||||
// A-29); its `findings-asked` subject is the seat's, from the generated contract (A-17).
|
||||
type heldWriter = views.HeldWriter[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent]
|
||||
|
||||
// findingWriter is the part of the held writer the builder's findings use.
|
||||
// retiredFindingKinds are kinds no code of the builder raises any more, which its writer clears once at its start (design 47 H2
|
||||
// H-A-578 (1), H-A-247 (3)): floor-silent went with the version floor.
|
||||
var retiredFindingKinds = []views.RetiredKind{{Kind: "floor-silent"}}
|
||||
|
||||
// findingWriter is the part of the held writer the builder's findings use; Held answers the findings it holds (design 47 G A-38).
|
||||
type findingWriter interface {
|
||||
Write(ctx context.Context, f mcseat.Finding) error
|
||||
Clear(ctx context.Context, scope, id, kind, why string) error
|
||||
Held() []mcseat.Finding
|
||||
}
|
||||
|
||||
// findings writes the builder's findings through its held finding writer (design 47 G §689, A-29): a finding written before the
|
||||
@@ -115,6 +118,19 @@ func (f *findings) raise(ctx context.Context, fd finding) {
|
||||
}
|
||||
}
|
||||
|
||||
// stands says whether the writer holds the finding of kind about scope and id (design 47 G A-38): it is raised and not cleared.
|
||||
func (f *findings) stands(kind, scope, id string) bool {
|
||||
if f.w == nil {
|
||||
return false
|
||||
}
|
||||
for _, x := range f.w.Held() {
|
||||
if x.Kind == kind && x.Scope == scope && x.ID == keyID(id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// clear clears the finding of kind about scope and id; one not there is nothing to clear.
|
||||
func (f *findings) clear(ctx context.Context, kind, scope, id string) {
|
||||
if f.w == nil {
|
||||
@@ -151,19 +167,3 @@ func (f *findings) notHeard(ctx context.Context) heard.Writer {
|
||||
return f.w.Clear(ctx, scope, rest[:i], rest[i+1:], "the builder hears it")
|
||||
}}
|
||||
}
|
||||
|
||||
// floorSaid is the floor finding (design 51 *Health and conditions*: a floor source silent): raised for a name waiting on
|
||||
// its floor, about that name, cleared once all three sources answered.
|
||||
func (f *findings) floorSaid(ctx context.Context) func(versions.FloorWait, bool) {
|
||||
return func(w versions.FloorWait, raised bool) {
|
||||
if !raised {
|
||||
f.clear(ctx, versions.FloorSilent, mcc.ScopeModule, w.Name)
|
||||
return
|
||||
}
|
||||
f.raise(ctx, finding{kind: versions.FloorSilent, scope: mcc.ScopeModule, id: w.Name, summary: w.Finding(),
|
||||
headline: "A version's floor is not known",
|
||||
explanation: "The builder numbers a name only once its registry seat, the forge bridge's tags and the indexer's requirements all answered; one of them did not.",
|
||||
resolved: "All three answered.",
|
||||
needs: "builder_floor_waits names the silent source; builder_floor_again asks again by hand."})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,6 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
sweep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshartifactsweep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
)
|
||||
|
||||
// A done key whose blob the artifact store no longer holds is built again, by the builder whole against the bus
|
||||
@@ -194,31 +192,3 @@ func artifactsGoneLeadsTheBuilderToBuildTheKeyAgain(t *testing.T) {
|
||||
b.fake.count("mesh-build-go.build_go_build"))
|
||||
}
|
||||
}
|
||||
|
||||
// The last versions-filled is read at the start from the seat event's own kept stream, kept by age, through the SDK's hearing
|
||||
// from the first message (design 47 G A-411), never from EVENTS: a message the stream keeps is found, an empty one is none.
|
||||
func TestTheLastVersionsFilledIsReadFromItsKeptStream(t *testing.T) {
|
||||
b := startBed(t)
|
||||
acct := process.Account{Node: "n1", Module: "mesh-delivery-builder"}
|
||||
if err := b.js.DeleteStream(b.ctx, eventsStream); err != nil { // the bus keeps a kept event off EVENTS: its subject is nowhere else
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.js.CreateOrUpdateStream(b.ctx, jetstream.StreamConfig{Name: meshcatalog.StreamVersionsFilled,
|
||||
Subjects: []string{meshcatalog.SubjectVersionsFilled}, MaxAge: 24 * time.Hour}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.js.CreateOrUpdateConsumer(b.ctx, meshcatalog.StreamVersionsFilled, jetstream.ConsumerConfig{
|
||||
Durable: acct.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy, FilterSubject: meshcatalog.SubjectVersionsFilled}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read := lastKeptOf(b.js, acct, t.Logf)
|
||||
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || found {
|
||||
t.Fatalf("empty stream: found %v, %v", found, err)
|
||||
}
|
||||
if _, err := b.js.Publish(b.ctx, meshcatalog.SubjectVersionsFilled, []byte(`{"v":1}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if found, err := read(b.ctx, meshcatalog.SubjectVersionsFilled); err != nil || !found {
|
||||
t.Fatalf("kept message: found %v, %v", found, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,16 +9,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
mcseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
@@ -31,6 +30,7 @@ import (
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry"
|
||||
@@ -177,6 +177,8 @@ func (f *fakeBuildModules) step(module, name string, args map[string]any) (any,
|
||||
return json.RawMessage(`{"artifact":"` + fmt.Sprint(args["artifact"]) + `","digest":"` + d + `","reference":"registry.example/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@` + d + `","pushed":true}`), nil
|
||||
case tool != "build_image_build" && f.refusePush.Load():
|
||||
return nil, fmt.Errorf("%s%v: the artifact store answered 507 Insufficient Storage", builds.NotStored, args["artifact"])
|
||||
case tool == "build_go_build" && args["seat"] == "go-package-registry": // a Go package under a reserved version: <name>@<version>
|
||||
return json.RawMessage(`{"digest":"` + digestOf(fmt.Sprint(args["artifact"])) + `","reference":"git.novox.be/novox/mesh-catalog/` + fmt.Sprint(args["module"]) + `/` + fmt.Sprint(args["artifact"]) + `@v` + fmt.Sprint(args["version"]) + `"}`), nil
|
||||
case tool != "build_image_build": // a bundle or an archive is pushed and its reference answered (ADR 0498 clause 1)
|
||||
d := digestOf(fmt.Sprint(args["artifact"]))
|
||||
return json.RawMessage(`{"digest":"` + d + `","reference":"artifact-store://` + filepath.Base(fmt.Sprint(args["module"])) + `/` + fmt.Sprint(args["artifact"]) + `/blobs/` + d + `"}`), nil
|
||||
@@ -323,7 +325,7 @@ func startBedWith(t *testing.T, closed bool) *bed {
|
||||
// each have their durable consumer.
|
||||
b.catalog = newCatalogHolder(t, ctx, js, ctl)
|
||||
b.catalog.buildSeats(t, ctl, map[string]string{"node-build-go": testGo, "node-build-node": testNode, "node-build-image": testImage,
|
||||
"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer", // the floor's sources are the holders of git and mesh-catalog
|
||||
"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer",
|
||||
"mesh-builds": builds.BuilderModule}) // the builder's own seat, whose verb reserved it answers once its definition is read (A-115, A-278)
|
||||
readers := []string{"n1_" + builds.BuilderModule, "n2_" + builds.BuilderModule}
|
||||
// Design 47 G §717, A-298: the catalog half names testAssigner the claimant of mesh-module-assigner, and its seat-holders view
|
||||
@@ -571,7 +573,7 @@ func isState(state string) func(builds.BuilderBuild) bool {
|
||||
// the digests of both bundles, both build modules' toolchains, after a fetch and a build on one node (ADR 0478 clause 4).
|
||||
func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
|
||||
b := startBed(t)
|
||||
// The builder's versions, findings and the floor's three sources are on the bus, the seat answering 0.1.4; two merges close
|
||||
// The builder's findings are on the bus, the seat answering 0.1.4; two merges close
|
||||
// together, the first replaced before its claim. The builder numbers neither in its state versions (design 47 H H-A-159,
|
||||
// G §348, §369): the reservation is the one place a version is numbered.
|
||||
reg := b.registry(t, "n1", "0.1.4")
|
||||
@@ -584,12 +586,6 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
|
||||
doneBound := map[string]string{"MESH_BUILDER_STEP_BOUND": testbus.SetupBound(t).String()}
|
||||
b.start(t, "n1", doneBound)
|
||||
v := b.await(t, "netcheck", isState(builds.BuildDone))
|
||||
for _, a := range []string{"tools-go", "tools-typescript"} {
|
||||
es := reg.of(t, "netcheck/"+a)
|
||||
if len(es) != 0 {
|
||||
t.Errorf("versions of netcheck/%s = %+v, want none: the builder numbers nothing of its own (H-A-159)", a, es)
|
||||
}
|
||||
}
|
||||
if v.By != "n1.mesh-delivery-builder" || v.Manifest != digest || len(v.Artifacts) != 2 {
|
||||
t.Fatalf("build = %+v", v)
|
||||
}
|
||||
@@ -622,7 +618,7 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
|
||||
for _, e := range b.logged(t, "netcheck") {
|
||||
if e.Event != builds.BuildSaidEvent {
|
||||
ended = append(ended, e)
|
||||
} else if e.Why == versions.SaidNumbered || e.Why == versions.SaidKept {
|
||||
} else if e.Why == "numbered" || e.Why == "kept" { // the narrations of the numbering from before G (design 47 H §756)
|
||||
t.Errorf("said = %+v, want no version of the builder's own numbered (H-A-159)", e)
|
||||
}
|
||||
}
|
||||
@@ -658,40 +654,6 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
|
||||
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
|
||||
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
|
||||
}
|
||||
// Versions numbered before G, which the state keeps until G §372 removes it: one a holder removes below, one it refuses.
|
||||
kept, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-typescript", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.5", Module: "netcheck",
|
||||
Fingerprint: fp, Digest: digestOf("tools-typescript"), Seat: ociartifactregistry.Seat, State: versions.Published, At: time.Now().UTC()})
|
||||
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-typescript", "0.1.5"), kept); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refusable, _ := json.Marshal(versions.Entry{Name: "netcheck/tools-go", Kind: versions.KindBundle, Series: "0.1", Version: "0.1.6", Module: "netcheck",
|
||||
Fingerprint: "src2:" + strings.Repeat("6", 64), Seat: ociartifactregistry.Seat, State: versions.Numbered, At: time.Now().UTC()})
|
||||
if _, err := reg.versions.Put(b.ctx, versions.Key("netcheck/tools-go", "0.1.6"), refusable); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Running-testing note (review round 1): two claims never get one number on the bus's own compare-and-set, as
|
||||
// the builder's state versions keeps them: eight claims of one name at once, eight versions.
|
||||
store := versions.Versions{Store: awaitedVersions{b: process.AwaitBucket(b.ctx, b.js, nil, builds.StateBucket(builds.BuilderModule, versions.State), "", t.Logf)}}
|
||||
numbers := make(chan string, 8)
|
||||
var claims sync.WaitGroup
|
||||
for i := range 8 {
|
||||
claims.Go(func() {
|
||||
d, _, err := store.Number(b.ctx, versions.Claim{Name: "netcheck/race", Kind: versions.KindBundle, Fingerprint: fmt.Sprintf("f%d", i)})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
numbers <- d.Version
|
||||
})
|
||||
}
|
||||
claims.Wait()
|
||||
close(numbers)
|
||||
got := map[string]bool{}
|
||||
for v := range numbers {
|
||||
got[v] = true
|
||||
}
|
||||
if len(got) != 8 {
|
||||
t.Errorf("eight claims of one name at once were numbered %v, want eight versions", slices.Sorted(maps.Keys(got)))
|
||||
}
|
||||
if got := reg.numberedOf("netcheck/tools-go"); len(got) != 0 {
|
||||
t.Errorf("version.numbered of netcheck/tools-go said %v, want none", got)
|
||||
}
|
||||
@@ -724,20 +686,167 @@ func TestBuilderMakesADoneKeyWithTheDigests(t *testing.T) { // 1607/AC7
|
||||
b.moduleFP(t, "netcheck", netcheck, "modules/netcheck", bothToolchains, "89abcdef0123456789abcdef0123456789abcdef", third, 3) // the entry moves to a later commit, same fingerprint
|
||||
b.awaitFP(t, "netcheck", third, isState(builds.BuildDone))
|
||||
reg.awaitFinding(t, failed, false)
|
||||
// DLV-B4: the seats' refused and removed, heard on the builder's durable consumer, move a numbered version: a retention
|
||||
// removal turns the entry removed with its reason, a refusal refused with the holder's reason and the bytes it refused.
|
||||
reg.outcome(t, ociartifactregistry.SubjectRemoved, versions.Outcome{Name: "netcheck/tools-typescript", Version: "0.1.5", Kind: "bundle", Holder: "distribution", Reason: "retention"})
|
||||
// DLV-B4: a seat's refused, heard on the builder's durable consumer, is the finding publish-refused about the name with the
|
||||
// holder's reason; the numbering from before G, which marked its state versions, is gone (design 47 H §756).
|
||||
reg.outcome(t, ociartifactregistry.SubjectRefused, versions.Outcome{Name: "netcheck/tools-go", Version: "0.1.6", Digest: digestOf("other"), Kind: "bundle", Holder: "distribution", Reason: "the cap"})
|
||||
reg.awaitOf(t, "netcheck/tools-typescript", func(es []versions.Entry) bool {
|
||||
return slices.ContainsFunc(es, func(e versions.Entry) bool {
|
||||
return e.Version == "0.1.5" && e.State == versions.Removed && e.Reason == "retention"
|
||||
})
|
||||
})
|
||||
reg.awaitOf(t, "netcheck/tools-go", func(es []versions.Entry) bool {
|
||||
return slices.ContainsFunc(es, func(e versions.Entry) bool {
|
||||
return e.Version == "0.1.6" && e.State == versions.Refused && e.Reason == "the cap" && e.RefusedDigest == digestOf("other")
|
||||
})
|
||||
})
|
||||
reg.awaitFinding(t, meshconditionsclient.Key(meshconditionsclient.ScopeModule, "netcheck/tools-go", versions.PublishRefused), true)
|
||||
// Issue 721 B4 (design 47 H2 H-A-521, H-A-547 (3), H-A-551): an entry naming a mesh package with no version is built with
|
||||
// the version its publisher reserved at the source revision of the key's own origin, once that reservation's artifact is
|
||||
// published, never the newest version a registry seat said published; once the version is released and the reservation
|
||||
// gone, the next such build takes it from the release record.
|
||||
const pkg = "git.novox.be/novox/mesh-catalog/modules/disk-load/diskreadings"
|
||||
goPublished := func(version, digest string) {
|
||||
t.Helper()
|
||||
reg.outcome(t, gopackageregistry.SubjectPublished, versions.Outcome{Name: pkg, Version: version, Digest: digest, Kind: versions.KindPackage, Holder: "go-registry"})
|
||||
}
|
||||
// The reservations' states, as the controller makes them from the builder's manifest, and the catalog seat's versions, which
|
||||
// a first reservation reads (none released yet).
|
||||
// The state acted is declared key-ttl (design 47 H2 H-A-720 (1)): its marks take a lifetime, so the bucket holds per-message lifetimes.
|
||||
for _, state := range []string{versions.ReservedState, versions.ActedState} { // acted keeps the release record
|
||||
if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: builds.StateBucket(builds.BuilderModule, state), LimitMarkerTTL: time.Second}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
none, _ := json.Marshal(map[string]any{"result": meshcatalog.VersionsAnswer{Module: "disk-load", Versions: []meshcatalog.VersionEntry{}}, "node": "ctl"})
|
||||
if s, err := b.js.Conn().Subscribe("mesh.seat."+meshcatalog.Seat+".call.versions.>", func(m *nats.Msg) { _ = m.Respond(none) }); err != nil {
|
||||
t.Fatal(err)
|
||||
} else {
|
||||
defer s.Unsubscribe()
|
||||
}
|
||||
goPublished("9.9.9", digestOf("elsewhere")) // the newest a registry seat said published: of no reservation at this origin
|
||||
b.awaitSaid(t, "the published of "+pkg+"@9.9.9")
|
||||
const diskLoad = "catalogue-8b8b0f66-disk-load.module.json"
|
||||
raw, err := os.ReadFile(filepath.Join("testdata", diskLoad))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pubFP := "src2:" + strings.Repeat("5", 64)
|
||||
publisher := b.entry("disk-load", "modules/disk-load", commit, pubFP, meshcatalogclient.ManifestDigest(raw), b.manifestOf(t, diskLoad), bothToolchains, 0)
|
||||
publisher.Artifacts = []meshcatalog.Artifact{{Ref: "disk-load:diskreadings", Kind: versions.KindPackage, Language: "go", Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: pkg}}}
|
||||
b.catalog.put(t, publisher)
|
||||
importer := func(fp2 string) {
|
||||
t.Helper()
|
||||
e := b.entry("netcheck", "modules/netcheck", commit, fp2, digest, b.manifestOf(t, netcheck), bothToolchains, 0)
|
||||
e.Packages = map[string]string{pkg: ""}
|
||||
b.catalog.put(t, e)
|
||||
}
|
||||
fourth := "src2:" + strings.Repeat("6", 64)
|
||||
importer(fourth)
|
||||
pub := b.awaitFP(t, "disk-load", pubFP, isState(builds.BuildDone))
|
||||
conn, err := process.Connect(process.Account{URL: b.srvURL, Module: "mesh-delivery-view", User: "ctl", Password: "pw"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
answer, err := conn.Call("seat:mesh-builds.reserved", meshbuilds.ReservedInput{Module: "disk-load"})
|
||||
var reserved meshbuilds.ReservedAnswer
|
||||
if err != nil || json.Unmarshal(answer, &reserved) != nil || reserved.Version == "" {
|
||||
t.Fatalf("reserved of disk-load = %s, %v; want the version its trunk build reserved", answer, err)
|
||||
}
|
||||
pkgDigest := ""
|
||||
for _, a := range pub.Artifacts {
|
||||
if a.Name == "diskreadings" {
|
||||
pkgDigest = a.Digest
|
||||
}
|
||||
}
|
||||
b.awaitSaid(t, "package "+pkg+" has no published version")
|
||||
want := "v" + reserved.Version
|
||||
// Design 47 H2 H-A-707 (3), (4) (B18, whole): the same fingerprint taken in again at a later revision, its entry at a later commit
|
||||
// naming the version, while the earlier build waits on its blank pin: the build takes that pin, said once, with no published
|
||||
// heard, and is one build, its key written done once and never failed.
|
||||
later := b.entry("netcheck", "modules/netcheck", "89abcdef0123456789abcdef0123456789abcdef", fourth, digest, b.manifestOf(t, netcheck), bothToolchains, 0)
|
||||
later.Packages = map[string]string{pkg: want}
|
||||
b.catalog.put(t, later)
|
||||
b.awaitSaid(t, pkg+" takes "+want)
|
||||
if v := b.awaitFP(t, "netcheck", fourth, isState(builds.BuildDone)); v.Packages[pkg] != want {
|
||||
t.Errorf("netcheck built with %v, want %s at %s, its publisher's reservation at the key's origin (H-A-547 (3))", v.Packages, pkg, want)
|
||||
}
|
||||
goPublished(reserved.Version, pkgDigest) // heard after the build: nothing builds again
|
||||
if st, err := b.js.Stream(b.ctx, "BUILDER_BUILDS"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if subject := "mesh.stream.mesh-delivery-builder.event." + builds.BuildEndedEventName("netcheck", fourth); true {
|
||||
info, err := st.Info(b.ctx, jetstream.WithSubjectFilter(subject))
|
||||
if err != nil || info.State.Subjects[subject] != 1 {
|
||||
t.Errorf("netcheck at %s ended %d times (%v), want its one build done, never one failed (H-A-707 (3), (4))", fourth, info.State.Subjects[subject], err)
|
||||
}
|
||||
}
|
||||
released, _ := json.Marshal(meshcatalog.VersionReleasedEvent{V: 1, Module: "disk-load", Version: reserved.Version})
|
||||
msg := nats.NewMsg(meshcatalog.SubjectVersionReleased)
|
||||
msg.Header.Set("x-event-id", "released-disk-load-"+reserved.Version)
|
||||
msg.Data = released
|
||||
if _, err := b.js.PublishMsg(b.ctx, msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The release deletes the reservation (H-A-551): what fills the next build is the release record alone.
|
||||
reservations, err := b.js.KeyValue(b.ctx, builds.StateBucket(builds.BuilderModule, versions.ReservedState))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Watched, never polled: the watch gives the keys standing, then a nil, then each change (the delete of the release).
|
||||
w, err := reservations.WatchFiltered(b.ctx, []string{versions.NameFilter("disk-load")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = w.Stop() }()
|
||||
held, caughtUp := map[string]bool{}, false
|
||||
timeout := time.After(20 * time.Second)
|
||||
for !caughtUp || len(held) > 0 {
|
||||
select {
|
||||
case e := <-w.Updates():
|
||||
switch {
|
||||
case e == nil:
|
||||
caughtUp = true
|
||||
case e.Operation() == jetstream.KeyValuePut:
|
||||
held[e.Key()] = true
|
||||
default:
|
||||
delete(held, e.Key())
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatalf("disk-load holds %v 20 s after its version-released of %s, want none", held, reserved.Version)
|
||||
}
|
||||
}
|
||||
fifth := "src2:" + strings.Repeat("7", 64)
|
||||
importer(fifth)
|
||||
if v := b.awaitFP(t, "netcheck", fifth, isState(builds.BuildDone)); v.Packages[pkg] != want {
|
||||
t.Errorf("netcheck built with %v once disk-load %s was released, want %s at %s from its release record (H-A-551)", v.Packages, reserved.Version, pkg, want)
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-695 (AC-B16c, whole): the manifest-reads-changed of node n2 asks its engine, which never answers (no engine of n2 is
|
||||
// listening); the running of the build module on node n1, stopped, is handled all the same (its toolchain key is deleted), and no event
|
||||
// of the builder's durable is given again or ends in the dead letters (a delivery limit reached is advised on the bus).
|
||||
deadLetters, err := b.js.Conn().SubscribeSync("$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES." + eventsStream + ".*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer deadLetters.Unsubscribe()
|
||||
toolchainKey, _ := sdkstep.ToolchainKey("n1", "go")
|
||||
if _, err := b.heard.Get(b.ctx, toolchainKey); err != nil {
|
||||
t.Fatalf("the builder holds no toolchain of n1 before the events: %v", err)
|
||||
}
|
||||
changed, _ := json.Marshal(nodeengine.ManifestReadsChanged{Node: "n2", Why: "changed", At: time.Now().UTC().Format(time.RFC3339Nano)})
|
||||
if _, err := b.js.Publish(b.ctx, nodeengine.SubjectManifestReadsChanged("n2"), changed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stopped, _ := json.Marshal(nodeengine.Running{Module: testGo, Node: "n1", At: time.Now().UTC()})
|
||||
if _, err := b.js.Publish(b.ctx, nodeengine.SubjectRunning("n1", testGo), stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(20 * time.Millisecond) {
|
||||
if _, err := b.heard.Get(b.ctx, toolchainKey); errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the running of n1 was not handled within 20 s while the manifest-reads-changed of n2 waited on its ask")
|
||||
}
|
||||
}
|
||||
if m, err := deadLetters.NextMsg(10 * time.Millisecond); err == nil {
|
||||
t.Errorf("the bus advised a delivery limit reached: %s", m.Subject)
|
||||
}
|
||||
if c, err := b.js.Consumer(b.ctx, eventsStream, "n1_mesh-delivery-builder"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if info, err := c.Info(b.ctx); err != nil || info.NumRedelivered != 0 {
|
||||
t.Errorf("the builder's durable gave %d events again (%v), want none", info.NumRedelivered, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnArchiveOnlyModuleAndARootModuleAreBuilt: the indexer gives an archive no language, so modules.ca-trust has no
|
||||
@@ -1154,15 +1263,14 @@ func TestARestartedBuilderPutsNoSecondAsk(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// registry is the part of the bed design 51's builder cases need: the builder's states versions, findings, floor-waits and
|
||||
// reasks, EVENTS with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's
|
||||
// own events kept, and the floor's three sources served on the bus as their holders answer through the tool runner
|
||||
// ({result}): the seat's versions, the seat git's tags and the indexer's indexer_requirements.
|
||||
// registry is the part of the bed design 51's builder cases need: the builder's states findings and reasks, EVENTS
|
||||
// with the seat oci-artifact-registry's outcomes and the builder's durable consumer of it, the builder's own events kept, and
|
||||
// the seat's versions served on the bus as its holder answers through the tool runner ({result}).
|
||||
type registry struct {
|
||||
b *bed
|
||||
versions, findings, reasks jetstream.KeyValue
|
||||
mu sync.Mutex
|
||||
numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349
|
||||
b *bed
|
||||
findings, reasks jetstream.KeyValue
|
||||
mu sync.Mutex
|
||||
numbered []string // the bodies said on the subject version.numbered was said on before design 47 G §349
|
||||
}
|
||||
|
||||
func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *registry {
|
||||
@@ -1175,8 +1283,7 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
|
||||
}
|
||||
return kv
|
||||
}
|
||||
r.versions, r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, versions.State)), mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState))
|
||||
mk(builds.StateBucket(builds.BuilderModule, versions.FloorWaitsState))
|
||||
r.findings, r.reasks = mk(builds.StateBucket(builds.BuilderModule, mcseat.StateFindings)), mk(builds.StateBucket(builds.BuilderModule, build.ReAsksState))
|
||||
// EVENTS with two seats' outcomes, and the forge bridge's stream (a branch's end): each with the builder's durable consumer.
|
||||
for stream, subjects := range map[string][]string{
|
||||
eventsStream: {"mesh.mod.*.event.>", "mesh.seat.*.event.>"},
|
||||
@@ -1206,7 +1313,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
|
||||
}
|
||||
for subject, answer := range map[string]any{
|
||||
"mesh.seat." + ociartifactregistry.Seat + ".call.versions.>": map[string]any{"versions": listed},
|
||||
"mesh.seat.git.call.tags.>": map[string]any{"tags": []string{}},
|
||||
} {
|
||||
reply, _ := json.Marshal(map[string]any{"result": answer, "node": "ctl"})
|
||||
s, err := nc.Subscribe(subject, func(m *nats.Msg) { _ = m.Respond(reply) })
|
||||
@@ -1218,42 +1324,6 @@ func (b *bed) registry(t *testing.T, node string, seatVersions ...string) *regis
|
||||
return r
|
||||
}
|
||||
|
||||
// of is every entry versions holds of name.
|
||||
func (r *registry) of(t *testing.T, name string) []versions.Entry {
|
||||
t.Helper()
|
||||
l, err := r.versions.ListKeysFiltered(r.b.ctx, versions.NameFilter(name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = l.Stop() }()
|
||||
var out []versions.Entry
|
||||
for k := range l.Keys() {
|
||||
e, err := r.versions.Get(r.b.ctx, k)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v versions.Entry
|
||||
if err := json.Unmarshal(e.Value(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// awaitOf reads name's entries until pred holds of them, within 20 s.
|
||||
func (r *registry) awaitOf(t *testing.T, name string, pred func([]versions.Entry) bool) []versions.Entry {
|
||||
t.Helper()
|
||||
var es []versions.Entry
|
||||
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
||||
if es = r.of(t, name); pred(es) {
|
||||
return es
|
||||
}
|
||||
}
|
||||
t.Fatalf("versions of %s = %+v within 20 s", name, es)
|
||||
return es
|
||||
}
|
||||
|
||||
// published says the artifact seat's published for name@version, as its holder does.
|
||||
func (r *registry) published(t *testing.T, name, version, digest string) {
|
||||
t.Helper()
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient/heard"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||
sweep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshartifactsweep"
|
||||
@@ -99,7 +100,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
// The builder's findings are raised as they happen, so its one finding writer holds them (design 47 G A-29, §689): it
|
||||
// is started once the state is bound, and what is written before is stated at its start.
|
||||
fw, err := views.NewHeldWriter(views.WriterConfig[mcseat.Finding, mcseat.FindingCleared, mcseat.FindingsStated, mcseat.FindingsAskedEvent]{
|
||||
Module: cred.Module, State: calls.State("findings"), Node: cred.Node, Asked: mcseat.SubjectFindingsAsked, JS: js, Conn: conn, Logf: logger.Printf})
|
||||
Module: cred.Module, State: calls.State("findings"), Node: cred.Node, Asked: mcseat.SubjectFindingsAsked, Retired: retiredFindingKinds, JS: js, Conn: conn, Logf: logger.Printf})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -159,26 +160,12 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
conn.SetReconnectHandler(func(*nats.Conn) { hearing.Again(); heard.Nudge("") })
|
||||
// The builder asks the controller, as its own account, whether the artifact store still holds a done key's blobs
|
||||
// (the seat verb held, novox/hq issue 1937) before it leaves the key done, on its calls connection.
|
||||
// The state versions, kept from before G (design 51 *The versions*) and read through builder_versions until G §372 removes
|
||||
// it, bound once the bus holds it; the builder numbers nothing in it (design 47 H H-A-159).
|
||||
versionsKV := process.AwaitBucket(ctx, js, conn, own.versions, "builder_versions answers nothing of the versions numbered before G", logger.Printf)
|
||||
found := &findings{module: cred.Module, w: fw, logf: logger.Printf, now: time.Now}
|
||||
floorWaits := &versions.FloorWaits{Holder: versions.HolderOf(branches), Logf: logger.Printf, Said: found.floorSaid(context.WithoutCancel(ctx))}
|
||||
// The names waiting on their floor are kept in the state floor-waits (DLV-B4): a restarted builder takes them in, so
|
||||
// their silent sources' events still wake them; until the state is bound they are kept here only.
|
||||
process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, versions.FloorWaitsState), "the names waiting on their floor are kept in memory only, and builder_floor_waits shows none", logger.Printf).
|
||||
Ready(func(kv jetstream.KeyValue) {
|
||||
floorWaits.Keep(kvKeeper{ctx: ctx, kv: kv}, heldFloorWaits(ctx, kv, logger.Printf))
|
||||
})
|
||||
// A package is numbered under its name in its ecosystem, read from the catalog half's entries (design 32, design 47 G §348).
|
||||
numberer := &versions.Numberer{Versions: versions.Versions{Store: awaitedVersions{b: versionsKV}}, Floor: floorVia(calls.Call, versions.RequirementsFrom(versions.EntriesOf(branches))), Waits: floorWaits,
|
||||
Names: versions.NamesFrom(versions.EntriesOf(branches))}
|
||||
// A publish that ends badly is a finding (design 51 *Health and conditions*): a holder's refused, a version no holder
|
||||
// answered within its bound (a key of the state bounds with its own time to live), a seat's outcome that does not read.
|
||||
pubBoundsKV := process.AwaitBucket(ctx, js, conn, own.bounds, "a publish no holder answers, and a node holding the old form seven days, are not raised", logger.Printf)
|
||||
stepReads.bounds, stepReads.findings = func() jetstream.KeyValue { return pubBoundsKV.KV() }, found
|
||||
pubs := &publishes{bounds: pubBoundsKV.KV, versions: numberer.Versions, findings: found, bound: versions.PublishBound, logf: logger.Printf}
|
||||
numberer.Publishing = pubs.arm
|
||||
pubs := &publishes{findings: found}
|
||||
stepExpiry := &buildrun.Expiry{}
|
||||
var b *build.Builder
|
||||
seatsChanged := func(ctx context.Context) {
|
||||
@@ -211,9 +198,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
unput := &unputs{bounds: pubBoundsKV.KV, store: b.Claimer.Store, looking: b.Looking, findings: found,
|
||||
bound: meshconditionsclient.CallUnansweredAfter, now: time.Now, logf: logger.Printf}
|
||||
b.Left, b.Ended = unput.left, unput.ended
|
||||
// The builder numbers nothing of its own (design 47 H H-A-159, G §348, §349, §369): b.Numbers stays nil, so no trunk build
|
||||
// is numbered in the state versions, waits on a floor or arms a publish-unanswered bound of it; the reservation is the one
|
||||
// place a version is numbered. The state, kept from before G, is still read (builder_versions) until G §372 removes it.
|
||||
// The builder numbers nothing of its own and asks no floor (design 47 H §756, H H-A-159, G §348, §349, §369): the
|
||||
// reservation is the one place a version is numbered.
|
||||
// The builder's toolchain waits (design 47 G §672): its state waits, and wait-held and wait-ended on its stream waits; its
|
||||
// bound is its setting toolchain-wait-minutes.
|
||||
waitBound, err := toolchainWaitOf(getenv("MESH_BUILDER_TOOLCHAIN_WAIT_FILE"))
|
||||
@@ -239,8 +225,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
return err
|
||||
}
|
||||
b.RecordBound = time.Duration(recordBound) * time.Second
|
||||
// Before it waits for an unpinned package, the build reads what the Go package registry seat holds of it (H-A-194).
|
||||
b.PublishedVersions = publishedVersionsVia(calls.Call)
|
||||
waitsBucket := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.WaitsState), "the toolchain waits are kept in memory only, and builder_waits shows none", logger.Printf)
|
||||
b.Waits = newWaitsKept(waitsBucket, func(ctx context.Context, event, id string, body any) error {
|
||||
return emitEvent(context.WithoutCancel(ctx), js, cred, event, id, body)
|
||||
@@ -248,10 +232,15 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
waitsBucket.Ready(func(kv jetstream.KeyValue) { b.Waits.(*waitsKept).start(ctx, kv) })
|
||||
// The plans no seat builds (design 47 H2 §795, H-A-425): kept in the state unbuildable, read by builder_unbuildable.
|
||||
b.Unbuildables = unbuildableKept{b: process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.UnbuildableState), "the plans no seat builds are said, and builder_unbuildable lists none", logger.Printf)}
|
||||
// The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's versions-filled
|
||||
// and version-released heard; nothing is reserved before the fill.
|
||||
// The versions a build reserves at its start (design 47 G §369): its state reserved, and the catalog's version-released
|
||||
// heard (design 47 H2 H-A-552: no fill is waited for).
|
||||
reservedKV := process.AwaitBucket(ctx, js, conn, own.reserved, "no version is reserved: builds are made unreserved", logger.Printf)
|
||||
reserved := newReservations(awaitedReserved{awaitedVersions{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, b.Reconsider, logger.Printf)
|
||||
reserved := newReservations(awaitedReserved{awaitedState{b: reservedKV, bucket: own.reserved}}, calls.Call, pubBoundsKV.KV, found, logger.Printf)
|
||||
publishAck, err := numberFile(getenv("MESH_BUILDER_PUBLISH_ACK_FILE"), defaultPublishAckMinutes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reserved.setBound(time.Duration(publishAck) * time.Minute) // the finding version-unreleased is timed by the same setting (H-A-613 (3))
|
||||
// The index by digest and by version beside the reservations is written again once the state is bound (H-A-269 (1), H-A-271).
|
||||
reservedKV.Ready(func(jetstream.KeyValue) { reserved.reindex(ctx) })
|
||||
// Each artifact the holder says published at a reserved version is said as the seat mesh-builds' package-published (design 47 G §52).
|
||||
@@ -264,25 +253,33 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
b.Reserved = reserved
|
||||
// A take-over of a series' reservation by another fingerprint withdraws the older build (H-A-225).
|
||||
reserved.withdraw = b.Withdraw
|
||||
reserved.looking = func(module, fp string) bool {
|
||||
key, err := builds.BuilderBuildKey(module, fp)
|
||||
return err == nil && b.Looking(key)
|
||||
}
|
||||
reserved.recordAgain = b.RecordAgain // a done build's digests its end did not record are recorded at the start (H-A-492)
|
||||
// The last versions-filled the stream keeps is read at the start (design 47 G §369, §372): a restart does not lose it.
|
||||
reserved.readFilled(ctx, lastKeptOf(js, cred, logger.Printf), sleeps)
|
||||
// A state bound later numbers the builds looked at without it.
|
||||
versionsKV.Ready(func(jetstream.KeyValue) { b.Reconsider(ctx) })
|
||||
// The versions' hand acts (builder_publish_again, builder_floor_again) come through reasks, as builder_build_again.
|
||||
acts := versions.Acts{Numberer: numberer, DropReserved: reserved.dropped, Reconsider: b.Reconsider}
|
||||
// The versions' hand acts (builder_publish_again, builder_reserved_drop) come through reasks, as builder_build_again.
|
||||
acts := versions.Acts{DropReserved: reserved.dropped}
|
||||
// A reserved version left unpublished is published again, by the builder on an event or by a person's tool (design 47 G
|
||||
// §588): its items on the work queue publishes, the module's own stream of its old streams section (design 47 H2 §793, H-A-454).
|
||||
actedKV := process.AwaitBucket(ctx, js, conn, own.acted, "no version is published again on an event or by builder_publish_again", logger.Printf)
|
||||
pq := &publishQueue{js: js, logf: logger.Printf, binding: publishesOf(cred.Module)}
|
||||
republish := &versions.Republisher{Reserved: reserved.r, Put: pq.put,
|
||||
Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk),
|
||||
Entry: entryVia(calls.Call), Send: sendVia(calls.CallKeptAsk, publishUnanswered(ctx, found)),
|
||||
Unreleased: reserved.unreleasedWords, Logf: logger.Printf,
|
||||
Holders: holders, // a registry seat's holder from the seat-holders view, from the start (design 47 G A-416, A-416a)
|
||||
Started: time.Now()} // a build ended from now on is of the live class (H-A-290 (1))
|
||||
// A number a registry seat already holds is never reserved (H-A-275): read before reserving, through the seats' verb versions.
|
||||
reserved.r.HeldNumbers = func(ctx context.Context, module, fp string, refs []string) ([]string, error) {
|
||||
return republish.HeldNumbers(ctx, module, fp, refs, registryVersionsVia(calls.Call))
|
||||
reserved.r.HeldRecords = func(ctx context.Context, module, fp string, refs []string) ([]versions.HeldArtifact, error) {
|
||||
return republish.HeldRecords(ctx, module, fp, refs, registryVersionsVia(calls.Call))
|
||||
}
|
||||
reserved.r.MovedFrom = reserved.movedFrom
|
||||
republish.Unstored = reserved.unstoredAgain
|
||||
// An artifact held for this very build is published as held (H-A-738 (1)); a published version the catalog holds no release of is
|
||||
// said again by builder_publish_again (H-A-773 (1)).
|
||||
republish.SayPublished = reserved.sayPublished
|
||||
reserved.judge = func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) {
|
||||
return republish.Held(ctx, v, registryVersionsVia(calls.Call))
|
||||
}
|
||||
// A done build whose number a registry holds elsewhere is built again at the next free number (H-A-279), on the builder's context.
|
||||
reserved.rebuild = func(_ context.Context, module, fp, why string) error {
|
||||
@@ -300,50 +297,62 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
reserved.r.HeldElsewhere = func(ctx context.Context, module string, skipped []string) {
|
||||
reserved.heldElsewhere(ctx, module, "the registries hold "+strings.Join(skipped, ", ")+", so the reserve skipped them")
|
||||
}
|
||||
publishSet, err := publishSettingsOf(getenv)
|
||||
republishMax, err := numberFile(getenv("MESH_BUILDER_REPUBLISH_MAX_FILE"), versions.DefaultRepublishMaxVersions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pq.ackWait = publishSet.PauseMax // a sent item unheard is delivered again after the longest pause (H-A-440 (1))
|
||||
pq.ackWait = time.Duration(publishAck) * time.Minute // a sent item unheard is given again after the publish bound (H-A-613 (3))
|
||||
republish.Bound = pq.ackWait // a send's calls wait that long at most, then the item is given again (H-A-613 (3), H-A-745)
|
||||
actedDays, err := numberFile(getenv("MESH_BUILDER_ACTED_DAYS_FILE"), versions.DefaultActedDays)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if actedDays > 365 {
|
||||
return fmt.Errorf("the setting acted-days is %d, at most 365", actedDays)
|
||||
}
|
||||
releasedKept, err := numberFile(getenv("MESH_BUILDER_RELEASED_KEPT_FILE"), versions.DefaultReleasedKept)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reasksKV := process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, build.ReAsksState), "builder_ask_again is not heard; an ask that can no longer be answered is still asked again by itself", logger.Printf)
|
||||
// A version's publish is the builder's own work until its release is written (design 47 G A-457a): an item of the re-ask state.
|
||||
items := &publishItems{reasks: reasksKV.KV, set: publishSet, now: time.Now, logf: logger.Printf,
|
||||
// A version's publish is the builder's own work until its release is written (design 47 G A-457a); a publish dropped by hand is
|
||||
// kept on its reservation (H-A-746).
|
||||
items := &publishItems{now: time.Now, logf: logger.Printf, unreleased: republish.Unreleased,
|
||||
dropMark: func(ctx context.Context, module, version, by, why string) error {
|
||||
found, err := reserved.r.MarkDropped(ctx, module, version, by, why, time.Now())
|
||||
if err == nil && !found {
|
||||
err = fmt.Errorf("no reservation of %s stands at %s: there is no publish to drop", module, version)
|
||||
}
|
||||
return err
|
||||
},
|
||||
reserved: func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) {
|
||||
return reserved.r.Of(ctx, module, version)
|
||||
},
|
||||
republish: republish.Republish, endedWith: reserved.unreleased,
|
||||
// A publish is asked again only while no published of it may be unheard and the registry's record lacks it (H-A-269 (2), H-A-272).
|
||||
unheard: unheardVia(js, process.EventsStream, cred.EventConsumerName()),
|
||||
republish: republish.Queue, // the build's end's ask queues only; builder_publish_again says a published version again (H-A-773 (1))
|
||||
// A publish is asked again while the registry's record lacks it (H-A-269 (2), H-A-272; H-A-514 addendum: no backlog count).
|
||||
judge: func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) {
|
||||
return republish.Held(ctx, v, registryVersionsVia(calls.Call))
|
||||
},
|
||||
markHeld: reserved.markHeld, moveElsewhere: reserved.movedElsewhere,
|
||||
allDone: func(ctx context.Context) ([]versions.ReservedVersion, error) { return reserved.r.All(ctx) },
|
||||
send: republish.SendQueued,
|
||||
retired: reserved.r.Retired} // only each module's newest done build is asked at the start (H-A-291 (1))
|
||||
send: republish.SendQueued}
|
||||
// A version that never publishes (withdrawn or taken over) has its publish item ended by the queue too (H-A-290 (2)).
|
||||
republish.Ended = items.Ended
|
||||
pq.take = items.take
|
||||
// At the start, a built reservation the catalog holds released is taken in as its version-released would (H-A-484 addendum),
|
||||
// before the publish items of the rest are asked.
|
||||
reasksKV.Ready(func(jetstream.KeyValue) {
|
||||
reasksKV.Ready(func(kv jetstream.KeyValue) {
|
||||
carryDrops(ctx, kv, reserved.r, logger.Printf) // before any event is heard: a drop made before is kept (H-A-749)
|
||||
reserved.releasedAtStart(ctx)
|
||||
items.AskAllDone(ctx)
|
||||
})
|
||||
wirePublishItems(reserved, items, awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}}, releasedKept)
|
||||
wirePublishItems(reserved, items, awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, releasedKept)
|
||||
acts.Republish = republish.Republish
|
||||
acts.PublishDrop = func(ctx context.Context, module, version, by, why string) (string, error) {
|
||||
return pq.drop(ctx, items, module, version, by, why)
|
||||
}
|
||||
// builder_reserve_done: a done trunk build that reserved none is given a version, and its publish queued as publish again does.
|
||||
acts.ReserveDone = reserveDoneAct(b.ReserveDone, republish.Republish, logger.Printf)
|
||||
// The operator is asked once a key's event builds are spent (design 47 G §568): the builder's asker on the seat operator-channel.
|
||||
decided := &decisions{subject: oc.SubjectDecided(cred.Module)}
|
||||
retakeActed := awaitedReserved{awaitedVersions{b: actedKV, bucket: own.acted}}
|
||||
retakeActed := markLifetime{awaitedReserved{awaitedState{b: actedKV, bucket: own.acted}}, actedDays, js}
|
||||
actedKV.Ready(func(kv jetstream.KeyValue) { deleteUnknown(ctx, kv, logger.Printf) })
|
||||
asker := &operatorask.Asker[oc.Warrant]{Module: cred.Module, Call: calls.Call, Record: calls.Ask, Publish: publishVia(ctx, js), Subscribe: decided.hear(logger.Printf),
|
||||
Contract: operatorask.Contract{Seat: oc.Seat, StateAsks: oc.StateAsks},
|
||||
AskSubject: oc.AcceptSubjectAsk, DecidedSubject: oc.SubjectDecided}
|
||||
@@ -353,6 +362,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
if err := operator.Listen(); err != nil {
|
||||
return fmt.Errorf("hearing the operator's answers: %w", err)
|
||||
}
|
||||
again := &publishingAgain{a: &versions.Againer{Republisher: republish, Acted: retakeActed, MaxVersions: republishMax, Nodes: branches.SeatHolderNodes(ctx)}}
|
||||
retake := &retaking{rt: &build.Retaker{Builder: b, Acted: retakeActed, Entry: entryVia(calls.Call), Ask: operator.Ask, Logf: logger.Printf}}
|
||||
// What waits on the work queue is pulled, and the old state's items are put on it once (§793).
|
||||
go func() {
|
||||
@@ -480,11 +490,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
// The seat mesh-artifact-sweep says artifacts-gone when it found a key's blob gone (issue 1937, ADR 0571 §2): the
|
||||
// builder's durable consumer on EVENTS, made by the grants part from the manifest's consumes. Where it is not there yet the builder says
|
||||
// so; it still asks held at its start and at every module value.
|
||||
// The same consumer carries what wakes a floor (design 51 *The floor*): the indexer's take-in.taken (design 47 H H-A-116) and the
|
||||
// condition keeper's condition-cleared.
|
||||
floor := floorWake{b: b, waits: floorWaits, logf: logger.Printf}
|
||||
// And the four registry seats' published, refused and removed (DLV-B4), which move a numbered version.
|
||||
seatHeard := seatHearer{n: numberer, b: b, logf: logger.Printf, pub: pubs, res: reserved}
|
||||
seatHeard := seatHearer{b: b, logf: logger.Printf, pub: pubs, res: reserved}
|
||||
// Each part takes the events it hears in turn; a handling over the setting slow-event is said with the part that took it
|
||||
// (design 47 H2 §794; H-A-461 (2)).
|
||||
slow, err := slowEvent()
|
||||
@@ -494,14 +501,15 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
takers := []eventTaker{
|
||||
{"the operator's answer to an ask about a key", decided.heard}, // §568
|
||||
{"the retake of a key failed on a transport fault", func(m jetstream.Msg) bool { return retake.heard(ctx, m, logger.Printf) }}, // §568
|
||||
{"the publish again of reserved versions", func(m jetstream.Msg) bool { return again.heard(ctx, m, logger.Printf) }}, // ADR 0674 §2
|
||||
{"what a node's engine reads", func(m jetstream.Msg) bool { return reads.heard(m, logger.Printf) }}, // manifest-reads-changed (ADR 0618 §4)
|
||||
{"the toolchains reported", func(m jetstream.Msg) bool { return heardTools.Reported(ctx, m) }},
|
||||
{"the toolchains running", func(m jetstream.Msg) bool { return heardTools.Running(ctx, m) }},
|
||||
{"the floor", func(m jetstream.Msg) bool { return floor.heard(ctx, m) }},
|
||||
{"the reservations", func(m jetstream.Msg) bool { return reserved.heard(ctx, m) }},
|
||||
{"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }},
|
||||
}
|
||||
gone := eventTaker{"the artifacts gone", func(m jetstream.Msg) bool { heardGone(ctx, b, m, logger.Printf); return true }}
|
||||
// The hub holds each event under its key (eventKey), one key's events in order, the keys side by side (H-A-683 (1), H-A-737 (1)).
|
||||
events := func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) }
|
||||
// The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, the indexer's take-in.taken and
|
||||
// manifest-reads-changed and the seat mesh-conditions' condition-cleared: seatEventPatterns); the owners' views events and the
|
||||
@@ -551,7 +559,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
seatGate.Follow(seatlist.ProcessBus(calls.Call, aged), func() { seatsChanged(ctx); b.SayUnbuildable(ctx) }, logger.Printf)
|
||||
half.holders = func() { seatsChanged(ctx) }
|
||||
for _, pattern := range seatEventPatterns {
|
||||
if err := aged.Handle(pattern, events); err != nil {
|
||||
if err := aged.HandleByKey(pattern, eventKey, events); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -572,23 +580,18 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
b.SayUnbuildable(ctx) // at the start, once the first views are in: the plans no seat builds in one line (§795)
|
||||
}
|
||||
branches.Changed = half.Changed(ctx)
|
||||
// A catalog revision the builder hears wakes a floor whose tags or requirements were silent (design 47 G A-119).
|
||||
half.floor = func(ctx context.Context) {
|
||||
(&floorWake{b: b, waits: floorWaits, logf: logger.Printf}).wake(ctx, versions.WakeRevision, "", "")
|
||||
}
|
||||
// All of the catalog half's wiring is set before the reader starts: its views are heard on the reader's goroutines from then.
|
||||
reader.Start(ctx, js, cred, process.AwaitBucket(ctx, js, conn, builds.StateBucket(cred.Module, views.StatusState), "builder_first_views reads nothing and builder_first_view_again is not heard", logger.Printf))
|
||||
// Every part has registered: the hub pulls the module's durable. Where the consumer is not there yet the builder says so
|
||||
// and binds it at a later change (heard.Writer; ADR 0615 §5).
|
||||
_ = notHeard.Bind(eventsStream, sweep.EventArtifactsGone+", what wakes a floor, the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again", func() error {
|
||||
if err := hub.Start(ctx, js, cred); err != nil {
|
||||
return err
|
||||
}
|
||||
// And the kept seat events it handles (the build seats' toolchain-reported, the seat mesh-catalog's versions-filled
|
||||
// and version-released), each on its own stream: the tool runner reads its own twin there (lead answer A-397).
|
||||
hub.StartKept(ctx, js, cred)
|
||||
return nil
|
||||
})
|
||||
// Start's nil says the hub started, never that anything is heard: EVENTS is heard when the hub's unheard list names no EVENTS
|
||||
// entry, else not heard with the hub's reason (design 47 H2b H-A-877). One Start binds every pattern's stream, the kept seat
|
||||
// events' too (the build seats' toolchain-reported, the seat mesh-catalog's version-released) (§836 1.).
|
||||
eventsConsequence := sweep.EventArtifactsGone + ", the registry seats' words, the views and manifest-reads-changed are not heard until the builder starts again"
|
||||
hub.OnUnheard(eventsUnheard(notHeard, eventsConsequence))
|
||||
if err := hub.Start(ctx, js, cred); err != nil {
|
||||
notHeard.NotHeard(eventsStream, eventsConsequence, err)
|
||||
}
|
||||
go func() { <-ctx.Done(); hub.Stop() }()
|
||||
// A person asks a key's build again with builder_ask_again, which writes the reasks state (issue 1945): watched, as
|
||||
// every other input. The builder asks again by itself without it.
|
||||
@@ -632,7 +635,6 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
|
||||
}
|
||||
return
|
||||
}
|
||||
pubs.ended(ctx, e)
|
||||
}
|
||||
watchBounds(ctx, kv, each, found.notHeard(ctx), errs, logger.Printf)
|
||||
})
|
||||
@@ -689,3 +691,17 @@ func toolchainWaitOf(path string) (time.Duration, error) {
|
||||
}
|
||||
return time.Duration(n) * time.Minute, nil
|
||||
}
|
||||
|
||||
// eventsUnheard is the hub's word of what it does not hear, as the builder's finding family-not-heard of EVENTS: heard when the
|
||||
// list names no EVENTS entry, else not heard with the hub's reason (design 47 H2b H-A-877; Start's nil says only that it started).
|
||||
func eventsUnheard(w heard.Writer, consequence string) func([]process.Unheard) {
|
||||
return func(list []process.Unheard) {
|
||||
for _, u := range list {
|
||||
if u.Stream == eventsStream {
|
||||
w.NotHeard(eventsStream, consequence, errors.New(u.Why))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Heard(eventsStream)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
const namedTreePrefix = "named:"
|
||||
|
||||
// seatEventPatterns are the seats' events the builder's own handler takes off its durable consumer (its manifest's `consumes` of
|
||||
// them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, condition-cleared, the node-engine
|
||||
// seat's events, of the seat mesh-catalog, version-released and versions-filled, and the indexer's take-in.taken. The seat mesh-catalog's
|
||||
// them): the registry seats' words, artifacts-gone, the build seats' toolchain-reported, the node-engine
|
||||
// seat's events, of the seat mesh-catalog, version-released. The seat mesh-catalog's
|
||||
// catalog-revision and registration-changed and the seat mesh-delivery's source-moved are the views reader's (the branch
|
||||
// follower's), so no pattern here covers them: a message has one taker.
|
||||
var seatEventPatterns = func() []string {
|
||||
@@ -18,9 +18,8 @@ var seatEventPatterns = func() []string {
|
||||
"mesh-artifact-sweep", "mesh-conditions", "node-engine", "node-build-go", "node-build-image", "node-build-node"} {
|
||||
out = append(out, "mesh.seat."+seat+".event.>")
|
||||
}
|
||||
for _, event := range []string{meshcatalog.EventVersionReleased, meshcatalog.EventVersionsFilled} {
|
||||
for _, event := range []string{meshcatalog.EventVersionReleased} {
|
||||
out = append(out, "mesh.seat."+meshcatalog.Seat+".event."+event, "mesh.seat."+meshcatalog.Seat+".event."+event+".>")
|
||||
}
|
||||
// And the indexer's take-in.taken, which wakes the floor (design 47 H H-A-116).
|
||||
return append(out, takenInSubject)
|
||||
return out
|
||||
}()
|
||||
|
||||
@@ -32,14 +32,11 @@ func TestTheNamesAreTheManifests(t *testing.T) {
|
||||
t.Errorf("the builder reads %s, its manifest's reads are %v", read, m.Reads)
|
||||
}
|
||||
}
|
||||
// The catalog half (design 47 G §348, §614) is followed through the seat, and no state of the indexer is; the indexer's
|
||||
// event take-in.taken wakes the floor (design 47 H H-A-116).
|
||||
if !slices.Contains(m.Consumes, "mesh-delivery-indexer.take-in.taken") {
|
||||
t.Errorf("the builder's floor wakes on no take-in.taken: its manifest consumes %v", m.Consumes)
|
||||
}
|
||||
// The catalog half (design 47 G §348, §614) is followed through the seat, and nothing of the indexer is: with the floor gone
|
||||
// (design 47 H §756) not its take-in.taken either (H-A-116).
|
||||
for _, c := range m.Consumes {
|
||||
if strings.HasPrefix(c, "mesh-delivery-indexer.") && c != "mesh-delivery-indexer.take-in.taken" {
|
||||
t.Errorf("the builder follows %s, an indexer state, its manifest consumes it", c)
|
||||
if strings.HasPrefix(c, "mesh-delivery-indexer.") {
|
||||
t.Errorf("the builder follows %s of the indexer, its manifest consumes it", c)
|
||||
}
|
||||
}
|
||||
for _, view := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved", "seat:mesh-module-assigner.views.assignments"} {
|
||||
@@ -51,7 +48,6 @@ func TestTheNamesAreTheManifests(t *testing.T) {
|
||||
"mesh-build-go_steps": buildrun.StepsBucket("mesh-build-go"),
|
||||
ownBucketsOf("acme-builder").toolchainsHeard: "acme-builder_toolchains-heard",
|
||||
ownBucketsOf("acme-builder").bounds: "acme-builder_bounds",
|
||||
ownBucketsOf("acme-builder").versions: "acme-builder_versions",
|
||||
ownBucketsOf("acme-builder").instances: "acme-builder_instances",
|
||||
} {
|
||||
if want != got {
|
||||
|
||||
@@ -2,9 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
@@ -17,53 +15,15 @@ import (
|
||||
)
|
||||
|
||||
// publishes raises and clears the builder's findings of a publish that ended badly (versions/publish.go): a holder's
|
||||
// refused, a version unanswered past its bound, kept as a key of the state bounds with its own time to live, and a seat's
|
||||
// outcome that does not read.
|
||||
// refused and a seat's outcome that does not read. A reserved version left unpublished is the reservation's bound (design 47
|
||||
// G §369, design 47 H §756: the numbered version's bound goes with the numbering from before G).
|
||||
type publishes struct {
|
||||
bounds func() jetstream.KeyValue
|
||||
versions versions.Versions
|
||||
findings *findings
|
||||
bound time.Duration
|
||||
logf func(string, ...any)
|
||||
}
|
||||
|
||||
// arm writes the version's bound when none stands, so a standing bound keeps its time. A bound that cannot be written
|
||||
// would never end, so the version is publish-unanswered at once (review round 2): the finding says why.
|
||||
func (p *publishes) arm(ctx context.Context, e versions.Entry) {
|
||||
kv := p.bounds()
|
||||
var err error
|
||||
if kv == nil {
|
||||
err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState)
|
||||
} else if _, err = kv.Create(ctx, versions.PublishBoundKey(e.Name, e.Version), versions.EncodeBound("the publish of "+e.Name+"@"+e.Version+" to "+e.Seat, time.Now().Add(p.bound)), jetstream.KeyTTL(p.bound)); errors.Is(err, jetstream.ErrKeyExists) {
|
||||
err = nil
|
||||
}
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
p.logf("the publish bound of %s@%s is not written, so it is raised unanswered now: %v", e.Name, e.Version, err)
|
||||
p.unanswered(ctx, e, fmt.Sprintf("its bound could not be written (%v), so the builder cannot wait on the holder's word", err))
|
||||
}
|
||||
|
||||
// unanswered raises publish-unanswered about e's name, saying why.
|
||||
func (p *publishes) unanswered(ctx context.Context, v versions.Entry, why string) {
|
||||
p.findings.raise(ctx, finding{kind: versions.PublishUnanswered, scope: meshconditionsclient.ScopeModule, id: v.Name,
|
||||
summary: fmt.Sprintf("%s said neither published nor refused of %s@%s: %s", v.Seat, v.Name, v.Version, why),
|
||||
headline: "A registry seat did not answer a publish",
|
||||
explanation: "The builder built and numbered " + v.Name + " " + v.Version + " and asked " + v.Seat + " to publish it; no word of its holder is known, so the build says done while the version may not be in the registry.",
|
||||
resolved: "That version is published, or a later version of " + v.Name + " is.",
|
||||
needs: "a look at the holder of " + v.Seat + " (its health and log); builder_publish_again asks the publish again."})
|
||||
}
|
||||
|
||||
// heard is told each holder's word the numberer took in: published clears the name's findings, refused raises
|
||||
// publish-refused with the holder's reason, and either ends the version's bound.
|
||||
// heard is told each holder's word: published clears the name's findings (publish-unanswered too, raised by a builder of
|
||||
// before the change), refused raises publish-refused with the holder's reason.
|
||||
func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Outcome) {
|
||||
if o.Version != "" {
|
||||
if kv := p.bounds(); kv != nil {
|
||||
if err := kv.Delete(ctx, versions.PublishBoundKey(o.Name, o.Version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||
p.logf("the publish bound of %s@%s is not ended: %v", o.Name, o.Version, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
switch event {
|
||||
case versions.HeardPublished:
|
||||
p.findings.clear(ctx, versions.PublishRefused, meshconditionsclient.ScopeModule, o.Name)
|
||||
@@ -78,7 +38,7 @@ func (p *publishes) heard(ctx context.Context, seat, event string, o versions.Ou
|
||||
headline: "A registry seat refused a publish",
|
||||
explanation: "The builder built and numbered " + o.Name + " " + o.Version + ", and the holder of " + seat + " refused to store it, so that version is not in the registry.",
|
||||
resolved: "That version is published, or a later version of " + o.Name + " is.",
|
||||
needs: "builder_versions shows the version and why; builder_publish_again publishes it again once the cause is mended."})
|
||||
needs: "builder_reserved shows the version and why; builder_publish_again publishes it again once the cause is mended."})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,24 +56,6 @@ func (p *publishes) read(ctx context.Context, seat string) {
|
||||
p.findings.clear(ctx, versions.SeatOutcomeUnread, meshconditionsclient.ScopeModule, seat)
|
||||
}
|
||||
|
||||
// ended is told each change of the state bounds: a bound whose time ended (the bus's marker) on a version still numbered
|
||||
// raises publish-unanswered.
|
||||
func (p *publishes) ended(ctx context.Context, e jetstream.KeyValueEntry) {
|
||||
key, ok := versions.PublishBoundOf(e.Key())
|
||||
if e.Operation() != jetstream.KeyValuePurge || !ok {
|
||||
return
|
||||
}
|
||||
raw, _, found, err := p.versions.Store.Get(ctx, key)
|
||||
if err != nil || !found {
|
||||
return
|
||||
}
|
||||
v, err := versions.Decode(raw)
|
||||
if err != nil || v.State != versions.Numbered {
|
||||
return
|
||||
}
|
||||
p.unanswered(ctx, v, fmt.Sprintf("nothing within %s of its build", p.bound))
|
||||
}
|
||||
|
||||
// watchBounds watches the state bounds, handing each change to each: a watch that cannot start loses every bound's end,
|
||||
// so it is the finding family-not-heard naming the state until a later start watches it (review round 2).
|
||||
func watchBounds(ctx context.Context, kv jetstream.KeyValue, each func(jetstream.KeyValueEntry), w heard.Writer, errs chan<- error, logf func(string, ...any)) {
|
||||
|
||||
+612
-32
@@ -16,12 +16,15 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
"git.novox.be/novox/mesh-sdk/go/seatlist"
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
|
||||
@@ -46,12 +49,11 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// One consumer per holder (H-A-483 and its addenda): the holder's class durables of an earlier release are retired, the item
|
||||
// one of them held unacknowledged reaches the one consumer; no item is lost; a failed send comes back after its pause, and a
|
||||
// live item put while it waits is sent before it returns; a dropped item never comes back.
|
||||
// one of them held unacknowledged reaches the one consumer; no item is lost; a failed send ends its item and is never sent again
|
||||
// on a timer; a dropped item never comes back.
|
||||
t.Run("one consumer", func(t *testing.T) {
|
||||
const holder, pause = "paused", 3 * time.Second // the pause is far longer than a send of an item put now
|
||||
const holder = "paused"
|
||||
bound := testbus.SetupBound(t)
|
||||
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
type send struct {
|
||||
module string
|
||||
at time.Time
|
||||
@@ -59,7 +61,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
published, failed := map[string]bool{}, map[string]bool{}
|
||||
sentCh := make(chan send, 16)
|
||||
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: pause, PauseMax: time.Minute, Tries: 5},
|
||||
items := &publishItems{dropMark: func(context.Context, string, string, string, string) error { return nil },
|
||||
now: time.Now, logf: t.Logf,
|
||||
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
|
||||
mu.Lock()
|
||||
@@ -109,22 +111,20 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
}
|
||||
return send{}
|
||||
}
|
||||
// The two class durables an earlier release made, the live one holding an item given and not acknowledged.
|
||||
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
|
||||
if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder) + "-" + class,
|
||||
FilterSubject: bind.Subject + ".publish." + holder + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Hour}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The one durable an earlier build made, holding an item given and not acknowledged (H-A-700 (2)).
|
||||
if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesOneConsumer(holder),
|
||||
FilterSubject: bind.Subject + ".publish." + holder + ".>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Hour}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put("given", versions.PublishClassLive)
|
||||
old, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder)+"-"+versions.PublishClassLive)
|
||||
old, err := b.js.Consumer(ctx, bind.Stream, publishesOneConsumer(holder))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, err := old.Next(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if md, _ := m.Metadata(); md.NumDelivered != 1 {
|
||||
t.Fatalf("the old live durable gave %+v", md)
|
||||
t.Fatalf("the old durable gave %+v", md)
|
||||
}
|
||||
pq.learn(ctx, holder)
|
||||
stream, err := b.js.Stream(ctx, bind.Stream)
|
||||
@@ -133,38 +133,68 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
}
|
||||
var names []string
|
||||
for n := range stream.ConsumerNames(ctx).Name() {
|
||||
if strings.HasPrefix(n, publishesConsumer(holder)) {
|
||||
if strings.HasPrefix(n, publishesOneConsumer(holder)) {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(names, []string{publishesConsumer(holder)}) {
|
||||
t.Fatalf("the consumers of %s are %v, want only %s: the class durables retired", holder, names, publishesConsumer(holder))
|
||||
want := []string{publishesConsumer(holder, versions.PublishClassLive), publishesConsumer(holder, versions.PublishClassStart)}
|
||||
slices.Sort(names)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(names, want) {
|
||||
t.Fatalf("the consumers of %s are %v, want %v: the one durable removed", holder, names, want)
|
||||
}
|
||||
// H-A-719, H-A-700 (1), H-A-620 (2): each of the two carries the stream's maximum age as its inactive threshold; four live sends
|
||||
// in flight and one again.
|
||||
sinfo, err := stream.Info(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for class, inflight := range map[string]int{versions.PublishClassLive: 4, versions.PublishClassStart: 1} {
|
||||
c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder, class))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := c.Info(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.InactiveThreshold != sinfo.Config.MaxAge || sinfo.Config.MaxAge == 0 || info.Config.MaxAckPending != inflight {
|
||||
t.Fatalf("%s: inactive threshold %s (stream max age %s), %d in flight, want the stream's max age and %d", class, info.Config.InactiveThreshold, sinfo.Config.MaxAge, info.Config.MaxAckPending, inflight)
|
||||
}
|
||||
}
|
||||
if s := next(); s.module != "given" {
|
||||
t.Fatalf("sent %s first, want the item the old durable held unacknowledged", s.module)
|
||||
}
|
||||
put("fail", versions.PublishClassStart)
|
||||
put("dropme", versions.PublishClassStart)
|
||||
var firstFail time.Time
|
||||
for range 2 {
|
||||
if s := next(); s.module == "fail" {
|
||||
firstFail = s.at
|
||||
}
|
||||
for range 2 { // the first send of each fails: its item ends, the version stays reserved, nothing hands it back after a pause (H-A-606)
|
||||
next()
|
||||
}
|
||||
put("live", versions.PublishClassLive) // put while both failed items wait out their pause
|
||||
put("live", versions.PublishClassLive)
|
||||
if s := next(); s.module != "live" {
|
||||
t.Fatalf("sent %s, want the live item put while the failed ones wait their pause", s.module)
|
||||
t.Fatalf("sent %s, want the live item put after the failed ones", s.module)
|
||||
}
|
||||
// design 47 H2 H-A-654, H-A-703: the consumer deleted under a running dispatch and made again, the dispatch binds again on the
|
||||
// bus's created advisory and sends the next item.
|
||||
if err := b.js.DeleteConsumer(ctx, bind.Stream, publishesConsumer(holder, versions.PublishClassLive)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.js.CreateOrUpdateConsumer(ctx, bind.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder, versions.PublishClassLive),
|
||||
FilterSubject: bind.Subject + ".publish." + holder + ".live.>", AckPolicy: jetstream.AckExplicitPolicy, AckWait: time.Minute,
|
||||
MaxAckPending: 4, MaxDeliver: publishesMaxDeliver}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put("rebound", versions.PublishClassLive)
|
||||
if s := next(); s.module != "rebound" {
|
||||
t.Fatalf("sent %s, want the item put after the consumer was made again", s.module)
|
||||
}
|
||||
if answer, err := pq.drop(ctx, items, "dropme", "0.1.0", "op@node", "a test drops it"); err != nil {
|
||||
t.Fatalf("drop: %v", err)
|
||||
} else {
|
||||
t.Log(answer)
|
||||
}
|
||||
if s := next(); s.module != "fail" || s.at.Sub(firstFail) < pause {
|
||||
t.Fatalf("sent %s %s after the failed send, want fail again after its pause %s", s.module, s.at.Sub(firstFail), pause)
|
||||
}
|
||||
// Every item is acknowledged and the dropped one is gone: nothing is left to come back.
|
||||
c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder))
|
||||
c, err := b.js.Consumer(ctx, bind.Stream, publishesConsumer(holder, versions.PublishClassLive))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -197,12 +227,11 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("the queue, the move, tags and backlog", func(t *testing.T) {
|
||||
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
var mu sync.Mutex
|
||||
var sent []string
|
||||
published := map[string]bool{} // the modules whose publish is heard
|
||||
sentCh := make(chan string, 200)
|
||||
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: time.Second, PauseMax: time.Minute, Tries: 5},
|
||||
items := &publishItems{dropMark: func(context.Context, string, string, string, string) error { return nil },
|
||||
now: time.Now, logf: t.Logf,
|
||||
reserved: func(_ context.Context, m, v string) (versions.ReservedVersion, bool, error) {
|
||||
mu.Lock()
|
||||
@@ -248,7 +277,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
if err := pq.learnAll(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 4 { // the items in flight: at most four held unacknowledged, their publish unheard
|
||||
for range 1 { // the again items in flight: at most one held unacknowledged, its publish unheard (H-A-620 (2))
|
||||
select {
|
||||
case <-sentCh:
|
||||
case <-time.After(30 * time.Second):
|
||||
@@ -300,8 +329,7 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
}
|
||||
found := &memFindings{vals: map[string][]byte{}}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
|
||||
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, nil, t.Logf)
|
||||
rv.filled.Store(true)
|
||||
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
type oldItem struct {
|
||||
key string
|
||||
raw []byte
|
||||
@@ -467,4 +495,556 @@ func TestThePublishQueueLosesNoItemAndNeverSendsADroppedItem(t *testing.T) {
|
||||
t.Errorf("the health four minutes in = %+v, want healthy", a)
|
||||
}
|
||||
})
|
||||
// Design 47 H2 H-A-613 (4), H-A-620 (3), H-A-593 (5), H-A-588 to H-A-590 (whole, against the bus and a fake registry holder): the
|
||||
// builder's reserving, its publish items and its work queue as main joins them, the publish a kept call through a process
|
||||
// connection to a holder on the bus, which answers `versions` with each version's digest and kept fingerprint and `publish` as the
|
||||
// seats do (held, other bytes, a refusal). A publish met by no responders is called again and passes once the holder answers; a
|
||||
// refused one is ended and waits for the next running; a build whose two of three artifacts a holder holds for its fingerprint
|
||||
// stores the third and releases the same number; the same with no fingerprint kept withdraws the number, builds again and releases
|
||||
// the next number, clearing version-held-elsewhere; other bytes of another build end the item at once.
|
||||
t.Run("a publish is a kept call and a registry's record is read", func(t *testing.T) {
|
||||
const holder, fpOf = "goreg", "src2:"
|
||||
reg := &fakeRegistry{held: map[string]map[string]heldRecord{}, away: true, firstAway: make(chan struct{}, 1)}
|
||||
reg.listen(t, b.js.Conn())
|
||||
conn, err := process.Connect(process.Account{URL: b.srvURL, Module: "mesh-delivery-builder", User: "ctl", Password: "pw"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
entries := map[string]meshcatalog.CatalogEntry{}
|
||||
entryOf := func(module, fp string, arts ...string) {
|
||||
e := meshcatalog.CatalogEntry{Module: module, Fp: fp}
|
||||
for _, a := range arts {
|
||||
e.Artifacts = append(e.Artifacts, meshcatalog.Artifact{Ref: module + ":" + a, Kind: versions.KindPackage, Language: "go",
|
||||
Package: &meshcatalog.ArtifactPackage{Ecosystem: "go", Name: "x.example/" + module + "/" + a}})
|
||||
}
|
||||
entries[fp] = e
|
||||
}
|
||||
call := func(string, any) (json.RawMessage, error) {
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
|
||||
}
|
||||
found := &memFindings{vals: map[string][]byte{}}
|
||||
rv := newReservations(&lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, call,
|
||||
func() jetstream.KeyValue { return nil },
|
||||
&findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
rv.say = func(context.Context, meshbuilds.PackagePublished) error { return nil }
|
||||
pq := &publishQueue{js: b.js, ackWait: time.Minute, logf: t.Logf, binding: publishesOf("mesh-delivery-builder")}
|
||||
republish := &versions.Republisher{Reserved: rv.r, Put: pq.put, Logf: t.Logf, Started: time.Now(),
|
||||
Entry: func(_ context.Context, fp string) (meshcatalog.CatalogEntry, error) {
|
||||
if e, ok := entries[fp]; ok {
|
||||
return e, nil
|
||||
}
|
||||
return meshcatalog.CatalogEntry{}, fmt.Errorf("no entry %s", fp)
|
||||
},
|
||||
Send: sendVia(conn.CallKeptAsk, publishUnanswered(ctx, &findings{module: builds.BuilderModule, w: found, logf: t.Logf, now: time.Now})),
|
||||
Unreleased: rv.unreleasedWords, Holders: func(string) []string { return []string{holder} }}
|
||||
rv.r.HeldRecords = func(ctx context.Context, module, fp string, refs []string) ([]versions.HeldArtifact, error) {
|
||||
return republish.HeldRecords(ctx, module, fp, refs, registryVersionsVia(conn.Call))
|
||||
}
|
||||
rv.r.MovedFrom = rv.movedFrom
|
||||
republish.Unstored = rv.unstoredAgain
|
||||
republish.SayPublished = rv.sayPublished
|
||||
rv.judge = func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error) {
|
||||
return republish.Held(ctx, v, registryVersionsVia(conn.Call))
|
||||
}
|
||||
rv.r.HeldElsewhere = func(ctx context.Context, module string, skipped []string) {
|
||||
rv.heldElsewhere(ctx, module, "the registries hold "+strings.Join(skipped, ", ")+", so the reserve skipped them")
|
||||
}
|
||||
items := &publishItems{now: time.Now, logf: t.Logf, unreleased: republish.Unreleased, republish: republish.Queue,
|
||||
dropMark: func(context.Context, string, string, string, string) error { return nil },
|
||||
reserved: func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error) {
|
||||
return rv.r.Of(ctx, module, version)
|
||||
},
|
||||
judge: rv.judge, markHeld: rv.markHeld, moveElsewhere: rv.movedElsewhere, send: republish.SendQueued}
|
||||
republish.Ended = items.Ended
|
||||
pq.take = items.take
|
||||
wirePublishItems(rv, items, &lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}}, versions.DefaultReleasedKept)
|
||||
// The publish again hears the node-engine seat's events from the bus, as the builder's events consumer gives them (H-A-606, ADR 0674 §2):
|
||||
// the registry holder's module runs on the node ace, and its catalog entry serves the registry seat.
|
||||
entries[fpOf+holder] = meshcatalog.CatalogEntry{Module: holder, Fp: fpOf + holder, Serves: []string{versions.SeatGoPackages + ".publish"}}
|
||||
againer := &publishingAgain{a: &versions.Againer{Republisher: republish, Acted: &lockedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}},
|
||||
Nodes: func(seat string) []seatlist.HolderNode {
|
||||
if seat == versions.SeatGoPackages {
|
||||
return []seatlist.HolderNode{{Module: holder, Node: "ace"}}
|
||||
}
|
||||
return nil
|
||||
}}}
|
||||
handled := make(chan uint64, 16)
|
||||
engineEvents, err := b.js.CreateOrUpdateConsumer(ctx, eventsStream, jetstream.ConsumerConfig{Durable: "publish-again-test", AckPolicy: jetstream.AckExplicitPolicy,
|
||||
DeliverPolicy: jetstream.DeliverNewPolicy, FilterSubjects: []string{nodeengine.SubjectRunningAll, nodeengine.SubjectManifestReadsChanged("*")}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hearing, err := engineEvents.Consume(func(m jetstream.Msg) {
|
||||
againer.heard(ctx, m, t.Logf)
|
||||
_ = m.Ack()
|
||||
if md, err := m.Metadata(); err == nil {
|
||||
handled <- md.Sequence.Stream
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hearing.Stop()
|
||||
// said puts one event of the node-engine seat on the bus and waits until the publish again has handled it; it answers its stream sequence.
|
||||
said := func(subject string, body any) uint64 {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(body)
|
||||
ack, err := b.js.Publish(ctx, subject, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for bound := time.After(testbus.SetupBound(t)); ; {
|
||||
select {
|
||||
case seq := <-handled:
|
||||
if seq == ack.Sequence {
|
||||
return seq
|
||||
}
|
||||
case <-bound:
|
||||
t.Fatalf("the publish again did not handle %s", subject)
|
||||
}
|
||||
}
|
||||
}
|
||||
returned := func() uint64 {
|
||||
return said(nodeengine.SubjectManifestReadsChanged("ace"), nodeengine.ManifestReadsChanged{Node: "ace", Why: nodeengine.ManifestReadsChangedWhyReturned})
|
||||
}
|
||||
// build is the reserve and the end of a build of module at fp: its digests are built+artifact.
|
||||
build := func(module, fp, built string, arts ...string) versions.ReservedVersion {
|
||||
t.Helper()
|
||||
var refs []string
|
||||
digests := map[string]string{}
|
||||
for _, a := range arts {
|
||||
refs = append(refs, module+":"+a)
|
||||
digests[module+":"+a] = "sha256:" + built + a
|
||||
}
|
||||
res, err := rv.Reserve(ctx, module, "0.1", refs, versions.Source{Fingerprint: fp})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rv.Built(ctx, module, res.Version, digests, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
stored := func(module, version, a string) string { return reg.digest("x.example/"+module+"/"+a, version) }
|
||||
|
||||
// H-A-613 (4): the first call finds no responders; the holder answers, and the publish passes, called again by itself.
|
||||
entryOf("kept", fpOf+"k", "a")
|
||||
build("kept", fpOf+"k", "k", "a")
|
||||
select {
|
||||
case <-reg.firstAway:
|
||||
case <-time.After(testbus.SetupBound(t)):
|
||||
t.Fatal("the publish was not called")
|
||||
}
|
||||
reg.answer()
|
||||
reg.await(t, "x.example/kept/a", "0.1.0")
|
||||
if got := reg.callsOf("x.example/kept/a"); got < 2 {
|
||||
t.Errorf("the publish was called %d times, want it met by no responders and called again", got)
|
||||
}
|
||||
reg.published(t, rv, "x.example/kept/a", "0.1.0") // its publish heard: the item is acknowledged
|
||||
reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "kept", "0.1.0") })
|
||||
|
||||
// H-A-613 (4): an answered refusal ends the send; nothing calls again; the next running puts it again and it passes.
|
||||
entryOf("refused", fpOf+"r", "a")
|
||||
reg.refuse("x.example/refused/a", "the cap")
|
||||
build("refused", fpOf+"r", "r", "a")
|
||||
reg.await(t, "x.example/refused/a", "0.1.0")
|
||||
reg.settle(t, b.js, bind.Stream, holder, nil)
|
||||
if got := reg.callsOf("x.example/refused/a"); got != 1 {
|
||||
t.Errorf("the refused publish was called %d times, want once: it waits for the next running", got)
|
||||
}
|
||||
reg.refuse("x.example/refused/a", "")
|
||||
// The holder's running, heard from the bus, puts it again once, as an item of the class again (H-A-606, H-A-613 (1), H-A-620 (1)).
|
||||
liveBefore, againBefore := delivered(t, b.js, bind.Stream, holder, versions.PublishClassLive), delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart)
|
||||
said(nodeengine.SubjectRunning("ace", holder), nodeengine.Running{Module: holder, Node: "ace", Fingerprint: fpOf + holder})
|
||||
reg.await(t, "x.example/refused/a", "0.1.0")
|
||||
if got := stored("refused", "0.1.0", "a"); got != "sha256:ra" {
|
||||
t.Errorf("the refused publish put again stored %q, want sha256:ra", got)
|
||||
}
|
||||
reg.published(t, rv, "x.example/refused/a", "0.1.0")
|
||||
reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "refused", "0.1.0") })
|
||||
if l, a := delivered(t, b.js, bind.Stream, holder, versions.PublishClassLive), delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart); l != liveBefore || a != againBefore+1 {
|
||||
t.Errorf("the running put %d live and %d again items, want one item of the class again", l-liveBefore, a-againBefore)
|
||||
}
|
||||
|
||||
// H-A-620 (1) (AC-B8a): two returns of one holder queue a version once while its send runs: the holder is away, the first return puts
|
||||
// the version and its send waits at the kept call's pace, the second finds the version held by the work queue and puts nothing.
|
||||
entryOf("twice", fpOf+"t", "a")
|
||||
reg.refuse("x.example/twice/a", "the cap")
|
||||
build("twice", fpOf+"t", "t", "a")
|
||||
reg.await(t, "x.example/twice/a", "0.1.0")
|
||||
reg.settle(t, b.js, bind.Stream, holder, nil)
|
||||
reg.refuse("x.example/twice/a", "")
|
||||
reg.goAway()
|
||||
againBefore = delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart)
|
||||
returned()
|
||||
select {
|
||||
case <-reg.firstAway:
|
||||
case <-time.After(testbus.SetupBound(t)):
|
||||
t.Fatal("the first return did not put the version")
|
||||
}
|
||||
returned()
|
||||
if st, err := b.js.Stream(ctx, bind.Stream); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish."+holder+".again."+versions.EscapeToken("twice")+".>")); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if n := func() (n uint64) {
|
||||
for _, c := range info.State.Subjects {
|
||||
n += c
|
||||
}
|
||||
return
|
||||
}(); n != 1 {
|
||||
t.Errorf("two returns left %d items of twice on the work queue (%v), want one", n, info.State.Subjects)
|
||||
}
|
||||
reg.answer()
|
||||
reg.await(t, "x.example/twice/a", "0.1.0")
|
||||
reg.published(t, rv, "x.example/twice/a", "0.1.0")
|
||||
reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "twice", "0.1.0") })
|
||||
if got := delivered(t, b.js, bind.Stream, holder, versions.PublishClassStart); got != againBefore+1 {
|
||||
t.Errorf("two returns made %d deliveries of again items, want one", got-againBefore)
|
||||
}
|
||||
|
||||
// H-A-593 (5): a build of F publishes two of three artifacts at V and fails on the third (the holder refuses it). Built again, the
|
||||
// two held for F keep their held digests, the third is stored and V is released, with no refusal and no new number.
|
||||
entryOf("three", fpOf+"3", "a", "b", "c")
|
||||
reg.refuse("x.example/three/c", "the cap")
|
||||
res := build("three", fpOf+"3", "first-", "a", "b", "c")
|
||||
reg.await(t, "x.example/three/c", res.Version)
|
||||
reg.settle(t, b.js, bind.Stream, holder, nil)
|
||||
for _, a := range []string{"a", "b"} {
|
||||
if got := stored("three", res.Version, a); got != "sha256:first-"+a {
|
||||
t.Fatalf("%s of three at %s is held at %q, want what the first run stored", a, res.Version, got)
|
||||
}
|
||||
}
|
||||
reg.refuse("x.example/three/c", "")
|
||||
republish.Started = time.Now().Add(time.Hour) // the build again is of a run before the next: its put is of the start class
|
||||
again, err := rv.Reserve(ctx, "three", "0.1", []string{"three:a", "three:b", "three:c"}, versions.Source{Fingerprint: fpOf + "3"})
|
||||
if err != nil || again.Version != res.Version {
|
||||
t.Fatalf("the build of three again reserved %q (%v), want the standing %s", again.Version, err, res.Version)
|
||||
}
|
||||
rv.MarkRegistryHeld(ctx, again) // before a build module is asked again (H-A-588 (4))
|
||||
if err := rv.Built(ctx, "three", res.Version, map[string]string{"three:c": "sha256:again-c"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.await(t, "x.example/three/c", res.Version)
|
||||
reg.published(t, rv, "x.example/three/c", res.Version)
|
||||
reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "three", res.Version) })
|
||||
cur, ok, _ := rv.r.Of(ctx, "three", "")
|
||||
if !ok || cur.Version != res.Version || len(cur.Withdrawn) != 0 || len(cur.Missing()) != 0 || cur.Artifacts["three:a"] != "sha256:first-a" || cur.Artifacts["three:c"] != "sha256:again-c" {
|
||||
t.Errorf("three stands %+v, want %s with every artifact published, the held digests of a and b and the third stored, and no number withdrawn", cur, res.Version)
|
||||
}
|
||||
if got := reg.callsOf("x.example/three/a"); got != 1 {
|
||||
t.Errorf("a of three was published %d times, want once: the second run answered it from the registry's record", got)
|
||||
}
|
||||
|
||||
// H-A-593 (5): the same with no fingerprint kept withdraws V, builds again and releases the next number, clearing
|
||||
// version-held-elsewhere at that release.
|
||||
entryOf("bare", fpOf+"b", "a", "b", "c")
|
||||
rv.rebuild = func(ctx context.Context, module, fp, _ string) error {
|
||||
var refs []string
|
||||
digests := map[string]string{}
|
||||
for _, a := range []string{"a", "b", "c"} {
|
||||
refs = append(refs, module+":"+a)
|
||||
digests[module+":"+a] = "sha256:next-" + a
|
||||
}
|
||||
again, err := rv.Reserve(ctx, module, "0.1", refs, versions.Source{Fingerprint: fp, Rebuild: true})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rv.Built(ctx, module, again.Version, digests, nil)
|
||||
}
|
||||
first := func() versions.ReservedVersion {
|
||||
res, err := rv.Reserve(ctx, "bare", "0.1", []string{"bare:a", "bare:b", "bare:c"}, versions.Source{Fingerprint: fpOf + "b"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return res
|
||||
}()
|
||||
reg.hold("x.example/bare/a", first.Version, "sha256:old-a", "")
|
||||
reg.hold("x.example/bare/b", first.Version, "sha256:old-b", "")
|
||||
if err := rv.Built(ctx, "bare", first.Version, map[string]string{"bare:a": "sha256:mine-a", "bare:b": "sha256:mine-b", "bare:c": "sha256:mine-c"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.await(t, "x.example/bare/c", "0.1.1")
|
||||
raised := func() bool {
|
||||
for k := range found.vals {
|
||||
if strings.Contains(k, versions.VersionHeldElsewhere) && strings.Contains(k, "bare") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !raised() {
|
||||
t.Errorf("no version-held-elsewhere raised about bare: %v", found.vals)
|
||||
}
|
||||
if got := reg.digest("x.example/bare/a", first.Version); got != "sha256:old-a" {
|
||||
t.Errorf("a of bare at %s is held at %q, want what the holder held, never overwritten", first.Version, got)
|
||||
}
|
||||
for _, a := range []string{"a", "b", "c"} {
|
||||
reg.published(t, rv, "x.example/bare/"+a, "0.1.1")
|
||||
}
|
||||
if err := rv.release(ctx, meshcatalog.VersionReleasedEvent{V: 1, Module: "bare", Version: "0.1.1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raised() {
|
||||
t.Errorf("version-held-elsewhere still raised about bare after its release: %v", found.vals)
|
||||
}
|
||||
reg.settle(t, b.js, bind.Stream, holder, func() { items.heard(ctx, "bare", "0.1.1") })
|
||||
|
||||
// H-A-588, H-A-590: a holder answering other bytes of another build ends the item at once, its tries unspent: it is called once.
|
||||
entryOf("other", fpOf+"o", "a")
|
||||
res, err = rv.Reserve(ctx, "other", "0.1", []string{"other:a"}, versions.Source{Fingerprint: fpOf + "o"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.hold("x.example/other/a", res.Version, "sha256:theirs", fpOf+"another")
|
||||
reg.hide("x.example/other/a") // the record is not read, so the item is sent and the holder answers other bytes (H-A-729)
|
||||
if err := rv.Built(ctx, "other", res.Version, map[string]string{"other:a": "sha256:mine"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg.await(t, "x.example/other/a", res.Version)
|
||||
// The item is ended at once, never held for its publish nor left on either durable (H-A-593 (5), H-A-729): the build is of a run
|
||||
// before the last start here, so its item is of the class again, which the settle reads as the live class.
|
||||
reg.settle(t, b.js, bind.Stream, holder, nil)
|
||||
if st, err := b.js.Stream(ctx, bind.Stream); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if info, err := st.Info(ctx, jetstream.WithSubjectFilter(bind.Subject+".publish."+holder+".*.other.>")); err != nil || len(info.State.Subjects) != 0 {
|
||||
t.Errorf("after other bytes the work queue holds %v (%v) of the item, want it terminated", info.State.Subjects, err)
|
||||
}
|
||||
if got := reg.callsOf("x.example/other/a"); got != 1 {
|
||||
t.Errorf("other bytes of another build: called %d times, want once", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// lockedReserve is the unit tests' reservations store, safe for the pull goroutines of a queue and a test at once.
|
||||
type lockedReserve struct {
|
||||
mu sync.Mutex
|
||||
*memReserve
|
||||
}
|
||||
|
||||
func (l *lockedReserve) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.memReserve.Get(ctx, key)
|
||||
}
|
||||
func (l *lockedReserve) Create(ctx context.Context, key string, v []byte) (uint64, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.memReserve.Create(ctx, key, v)
|
||||
}
|
||||
func (l *lockedReserve) Update(ctx context.Context, key string, v []byte, rev uint64) (uint64, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.memReserve.Update(ctx, key, v, rev)
|
||||
}
|
||||
func (l *lockedReserve) KeysOf(ctx context.Context, filter string) ([]string, error) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.memReserve.KeysOf(ctx, filter)
|
||||
}
|
||||
func (l *lockedReserve) Delete(ctx context.Context, key string) error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.memReserve.Delete(ctx, key)
|
||||
}
|
||||
|
||||
// heldRecord is what a fake registry holder keeps of one name at one version: its digest and the fingerprint it keeps (none: "").
|
||||
type heldRecord struct{ digest, fingerprint string }
|
||||
|
||||
// fakeRegistry is a registry seat's holder on the bus (the seat go-package-registry): it answers `versions` with each version's digest
|
||||
// and kept fingerprint, and `publish` as the seats do: stored when it holds nothing there, held for the same digest, other bytes
|
||||
// (with the kept fingerprint) for another digest, or a refusal in words. While away it answers as the bus does when no one is
|
||||
// listening (a 503 status without data), which the caller meets as no responders.
|
||||
type fakeRegistry struct {
|
||||
mu sync.Mutex
|
||||
held map[string]map[string]heldRecord // name -> version -> record
|
||||
away bool
|
||||
firstAway chan struct{}
|
||||
refused map[string]string // name -> the words it is refused in
|
||||
hidden map[string]bool
|
||||
calls map[string]int
|
||||
answered chan string // "<name> <version>" of each publish answered, not away
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) listen(t *testing.T, nc *nats.Conn) {
|
||||
t.Helper()
|
||||
r.answered = make(chan string, 64)
|
||||
sub, err := nc.Subscribe("mesh.seat."+versions.SeatGoPackages+".call.>", func(m *nats.Msg) {
|
||||
reply := func(result any, words string) {
|
||||
data, _ := json.Marshal(map[string]any{"result": result, "error": words, "node": "ctl"})
|
||||
_ = m.Respond(data)
|
||||
}
|
||||
switch strings.Split(m.Subject, ".")[4] {
|
||||
case "versions":
|
||||
var in struct{ Name string }
|
||||
_ = json.Unmarshal(m.Data, &in)
|
||||
r.mu.Lock()
|
||||
list := []map[string]string{}
|
||||
if !r.hidden[in.Name] {
|
||||
for v, rec := range r.held[in.Name] {
|
||||
list = append(list, map[string]string{"version": v, "digest": rec.digest, "fingerprint": rec.fingerprint})
|
||||
}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
reply(map[string]any{"versions": list}, "")
|
||||
case "publish":
|
||||
var in gopackageregistry.PublishInput
|
||||
_ = json.Unmarshal(m.Data, &in)
|
||||
r.mu.Lock()
|
||||
if r.calls == nil {
|
||||
r.calls = map[string]int{}
|
||||
}
|
||||
r.calls[in.Name]++
|
||||
if r.away {
|
||||
r.mu.Unlock()
|
||||
select {
|
||||
case r.firstAway <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
_ = m.RespondMsg(&nats.Msg{Header: nats.Header{"Status": {"503"}}})
|
||||
return
|
||||
}
|
||||
var answer gopackageregistry.PublishAnswer
|
||||
words := r.refused[in.Name]
|
||||
if rec, ok := r.held[in.Name][in.Version]; words == "" && ok {
|
||||
if rec.digest == in.Digest {
|
||||
answer.Held = true
|
||||
} else {
|
||||
answer.OtherBytes = &gopackageregistry.PublishAnswerOtherBytes{Digest: rec.digest, Fingerprint: rec.fingerprint}
|
||||
}
|
||||
} else if words == "" {
|
||||
if r.held[in.Name] == nil {
|
||||
r.held[in.Name] = map[string]heldRecord{}
|
||||
}
|
||||
r.held[in.Name][in.Version] = heldRecord{digest: in.Digest, fingerprint: in.Fingerprint}
|
||||
answer.Transfer = "t"
|
||||
}
|
||||
r.mu.Unlock()
|
||||
reply(answer, words)
|
||||
r.answered <- in.Name + " " + in.Version
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) answer() { r.mu.Lock(); r.away = false; r.mu.Unlock() }
|
||||
|
||||
func (r *fakeRegistry) refuse(name, words string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.refused == nil {
|
||||
r.refused = map[string]string{}
|
||||
}
|
||||
if words == "" {
|
||||
delete(r.refused, name)
|
||||
return
|
||||
}
|
||||
r.refused[name] = words
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) hide(name string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.hidden == nil {
|
||||
r.hidden = map[string]bool{}
|
||||
}
|
||||
r.hidden[name] = true
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) hold(name, version, digest, fingerprint string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.held[name] == nil {
|
||||
r.held[name] = map[string]heldRecord{}
|
||||
}
|
||||
r.held[name][version] = heldRecord{digest: digest, fingerprint: fingerprint}
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) digest(name, version string) string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.held[name][version].digest
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) callsOf(name string) int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.calls[name]
|
||||
}
|
||||
|
||||
// await reads the publishes answered until name's at version, within the level's set-up share.
|
||||
func (r *fakeRegistry) await(t *testing.T, name, version string) {
|
||||
t.Helper()
|
||||
bound := time.After(testbus.SetupBound(t))
|
||||
for {
|
||||
select {
|
||||
case got := <-r.answered:
|
||||
if got == name+" "+version {
|
||||
return
|
||||
}
|
||||
case <-bound:
|
||||
t.Fatalf("no publish of %s %s was answered", name, version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// settle waits until the holder's queue holds nothing sent and unacknowledged on either durable, the live class's and the again
|
||||
// class's: every item taken is ended.
|
||||
func (r *fakeRegistry) settle(t *testing.T, js jetstream.JetStream, stream string, holder string, each func()) {
|
||||
t.Helper()
|
||||
var cs []jetstream.Consumer
|
||||
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
|
||||
c, err := js.Consumer(context.Background(), stream, publishesConsumer(holder, class))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cs = append(cs, c)
|
||||
}
|
||||
for deadline := time.Now().Add(testbus.SetupBound(t)); ; {
|
||||
if each != nil {
|
||||
each()
|
||||
}
|
||||
var ack, pending int
|
||||
for _, c := range cs {
|
||||
info, err := c.Info(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack, pending = ack+info.NumAckPending, pending+int(info.NumPending)
|
||||
}
|
||||
if ack == 0 && pending == 0 {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the queue of %s holds %d unacknowledged and %d pending", holder, ack, pending)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// delivered is how many items the holder's durable of a class has given since it was made.
|
||||
func delivered(t *testing.T, js jetstream.JetStream, stream, holder, class string) uint64 {
|
||||
t.Helper()
|
||||
c, err := js.Consumer(context.Background(), stream, publishesConsumer(holder, class))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := c.Info(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return info.Delivered.Consumer
|
||||
}
|
||||
|
||||
// goAway makes the holder answer as the bus does when no one listens: its publish is met by no responders.
|
||||
func (r *fakeRegistry) goAway() { r.mu.Lock(); r.away = true; r.mu.Unlock() }
|
||||
|
||||
// published says the holder's published of name at version, as it says it after a publish: the reservation marks it from the digest held.
|
||||
func (r *fakeRegistry) published(t *testing.T, rv *reservations, name, version string) {
|
||||
t.Helper()
|
||||
rv.published(context.Background(), versions.Outcome{Name: name, Version: version, Digest: r.digest(name, version), Kind: versions.KindPackage, Holder: "go-registry"}, nil)
|
||||
}
|
||||
|
||||
@@ -17,50 +17,26 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793): each
|
||||
// reservation of a done build is a publish item in the builder's re-ask state, asked when the build ends and at the builder's
|
||||
// start; its try puts the publish on the work queue publishes, and each send counts one try in the item and hands a failed one
|
||||
// back with a longer pause; the release deletes it; after its tries it ends loudly and stays readable in builder_publish_queue.
|
||||
// **A version's publish is the builder's own work until its release is written** (design 47 G A-457a, §588; H2 §793, H-A-606): the
|
||||
// ask at a build's end is the first try, and it puts the publish on the work queue publishes; a publish that is refused or fails stays
|
||||
// reserved, with version-unreleased naming the holder's words, and is put again only on ADR 0674 §2's events (a registry holder's
|
||||
// running, a returned of its node: versions.Againer) or by builder_publish_again. No timer, pause or count of tries stands on this path.
|
||||
|
||||
// publishSettings are the settings publish-pause, publish-pause-max and publish-tries.
|
||||
type publishSettings struct {
|
||||
Pause, PauseMax time.Duration
|
||||
Tries int
|
||||
}
|
||||
|
||||
// defaultPublishSettings are the settings' defaults: 30 s, 30 min and 5 tries (H-A-446 (2)).
|
||||
var defaultPublishSettings = publishSettings{Pause: 30 * time.Second, PauseMax: 30 * time.Minute, Tries: 5}
|
||||
|
||||
// pauseAfter is the pause after the try-th try: the setting doubled per try, up to the maximum.
|
||||
func (s publishSettings) pauseAfter(try int) time.Duration {
|
||||
d := s.Pause
|
||||
for i := 1; i < try && d < s.PauseMax; i++ {
|
||||
d *= 2
|
||||
}
|
||||
return min(d, s.PauseMax)
|
||||
}
|
||||
|
||||
// publishItems asks, tries and ends the publish items.
|
||||
// publishItems asks and takes the publishes of reserved versions.
|
||||
type publishItems struct {
|
||||
reasks func() jetstream.KeyValue // the re-ask state, nil until it is bound
|
||||
// dropMark records on a version's reservation that its publish was dropped by hand, by whom and why (design 47 H2 H-A-746); nil
|
||||
// drops none.
|
||||
dropMark func(ctx context.Context, module, version, by, why string) error
|
||||
now func() time.Time
|
||||
reserved func(ctx context.Context, module, version string) (versions.ReservedVersion, bool, error)
|
||||
republish func(ctx context.Context, module, version string) ([]string, error)
|
||||
endedWith func(ctx context.Context, v versions.ReservedVersion, why string) // raises the finding version-unreleased
|
||||
// allDone are the reservations, done or not: those whose build is done are asked at the start (builtOf).
|
||||
allDone func(ctx context.Context) ([]versions.ReservedVersion, error)
|
||||
// retired are the done builds a newer reservation or release of the same module supersedes, with why (H-A-291 (1)); nil
|
||||
// retires none.
|
||||
retired func(ctx context.Context, all []versions.ReservedVersion) (map[string]string, error)
|
||||
// unheard is how many messages the builder's durable on the events stream holds pending and unacknowledged, read before each
|
||||
// try (design 47 H H-A-269 (2), H-A-272); nil reads none.
|
||||
unheard func(ctx context.Context) (int, error)
|
||||
// judge is what the registries' own record says of a version's missing artifacts (H-A-272, H-A-274, H-A-275); nil judges none.
|
||||
judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error)
|
||||
// markHeld marks the artifacts the registries hold with the built digest published from their record, as their published heard
|
||||
@@ -69,142 +45,52 @@ type publishItems struct {
|
||||
markHeld func(ctx context.Context, v versions.ReservedVersion, held []versions.HeldArtifact)
|
||||
moveElsewhere func(ctx context.Context, v versions.ReservedVersion, j versions.Judged) error
|
||||
// send sends one item pulled from the work queue (Republisher.SendQueued); nil sends none.
|
||||
send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate
|
||||
set publishSettings
|
||||
now func() time.Time
|
||||
after func(time.Duration) <-chan time.Time
|
||||
logf func(string, ...any)
|
||||
send func(ctx context.Context, q versions.QueuedPublish) versions.SendFate
|
||||
// unreleased raises version-unreleased about a version with the words given (Republisher's Unreleased); nil raises none.
|
||||
unreleased func(ctx context.Context, v versions.ReservedVersion, why string)
|
||||
logf func(string, ...any)
|
||||
// progressEvery is the pace the bus is told an item is in progress at while its send's calls wait: the kept call's pace
|
||||
// (busretry.KeptPace's most) when zero (design 47 H2 H-A-613 (3)).
|
||||
progressEvery time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
held map[string][]heldItem // "<module> <version>": the items sent, their publish not yet heard
|
||||
}
|
||||
|
||||
func (p *publishItems) wait(ctx context.Context, d time.Duration) bool {
|
||||
if d <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
after := p.after
|
||||
if after == nil {
|
||||
after = time.After
|
||||
}
|
||||
select {
|
||||
case <-after(d):
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Ask writes the publish item of a version whose build is done, when none stands: its first try is now.
|
||||
// Ask puts the publish of a version whose build is done on the work queue: its first try, at the build's end (A-473).
|
||||
func (p *publishItems) Ask(ctx context.Context, module, version string) error {
|
||||
kv := p.reasks()
|
||||
if kv == nil {
|
||||
return errors.New("the re-ask state is not on the bus yet")
|
||||
}
|
||||
raw, err := json.Marshal(build.ReAsk{V: 1, Why: "the build ended with its version unreleased", By: "the builder", At: p.now().UTC(), Mode: build.ModePublish, Module: module, Version: version, NextTry: p.now().UTC()})
|
||||
queued, err := p.republish(ctx, module, version)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("the publish of %s %s is not put on the work queue %s: %w", module, version, versions.PublishesLocal, err)
|
||||
}
|
||||
if _, err := kv.Create(ctx, versions.PublishItemKey(module, version), raw); err != nil && !errors.Is(err, jetstream.ErrKeyExists) {
|
||||
return fmt.Errorf("the publish item of %s %s cannot be written: %w", module, version, err)
|
||||
if len(queued) == 0 {
|
||||
p.logf("%s %s: the publish is not put on the work queue %s: nothing of it is left to queue", module, version, versions.PublishesLocal)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AskAllDone asks the publish item of every reservation whose build is done and that has no release: at the builder's start, so
|
||||
// what stood before this change moves too, whatever its artifacts.
|
||||
func (p *publishItems) AskAllDone(ctx context.Context) {
|
||||
all, err := p.allDone(ctx)
|
||||
if err != nil {
|
||||
p.logf("the reservations of done builds are not asked to publish at the start: %v", err)
|
||||
return
|
||||
}
|
||||
var retired map[string]string
|
||||
if p.retired != nil {
|
||||
if retired, err = p.retired(ctx, all); err != nil {
|
||||
p.logf("the superseded builds are not retired at the start: %v", err)
|
||||
}
|
||||
}
|
||||
for _, v := range builtOf(all) {
|
||||
if why := retired[v.Module+" "+v.Version]; why != "" { // only each module's newest is asked (H-A-291 (1), H-A-275)
|
||||
p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why)
|
||||
p.Done(ctx, v.Module, v.Version)
|
||||
continue
|
||||
}
|
||||
if why := versions.NotStanding(v, true); why != "" { // withdrawn: it never publishes (H-A-290 (2))
|
||||
p.logf("%s %s is not asked to publish at the start: %s; its publish item is ended", v.Module, v.Version, why)
|
||||
p.Done(ctx, v.Module, v.Version)
|
||||
continue
|
||||
}
|
||||
if err := p.Ask(ctx, v.Module, v.Version); err != nil {
|
||||
p.logf("%v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Done deletes a version's publish item and acknowledges its held items: its release is written.
|
||||
// Done acknowledges a version's held items: its release is written.
|
||||
func (p *publishItems) Done(ctx context.Context, module, version string) {
|
||||
for _, h := range p.settle(module, version, func(heldItem) bool { return true }) {
|
||||
_ = h.m.Ack()
|
||||
}
|
||||
kv := p.reasks()
|
||||
if kv == nil {
|
||||
return
|
||||
}
|
||||
if err := kv.Delete(ctx, versions.PublishItemKey(module, version)); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||
p.logf("the publish item of %s %s is not deleted: %v", module, version, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Try waits for the item's next try, then, while the version is still reserved, puts its publish on the work queue publishes
|
||||
// under its message id (design 47 H2 §793; H-A-448): an item the queue holds already is put once. It counts no try: each send
|
||||
// does, and hands its item back with the pause (take). A put that queued nothing is put again after the pause. A version no
|
||||
// longer reserved (released, dropped or taken over) has its item deleted.
|
||||
func (p *publishItems) Try(ctx context.Context, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk) {
|
||||
if !p.wait(ctx, r.NextTry.Sub(p.now())) {
|
||||
return
|
||||
}
|
||||
cur, err := kv.Get(ctx, e.Key())
|
||||
if err != nil || cur.Revision() != e.Revision() {
|
||||
return // deleted by the release, or written again
|
||||
}
|
||||
v, held, err := p.reserved(ctx, r.Module, r.Version)
|
||||
if err != nil {
|
||||
p.logf("%s %s: its reservation cannot be read, the publish item waits: %v", r.Module, r.Version, err)
|
||||
return
|
||||
}
|
||||
if why := versions.NotStanding(v, held); why != "" { // dropped, taken over, released or withdrawn (A-456b, H-A-290 (2))
|
||||
p.logf("%s %s: the publish item is ended: %s", r.Module, r.Version, why)
|
||||
_ = kv.Delete(ctx, e.Key())
|
||||
return
|
||||
}
|
||||
queued, err := p.republish(ctx, r.Module, r.Version)
|
||||
if err == nil && len(queued) > 0 {
|
||||
return
|
||||
}
|
||||
r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries))
|
||||
p.logf("%s %s: the publish is not on the work queue %s (%v); it is put again after %s", r.Module, r.Version, versions.PublishesLocal, err, p.set.pauseAfter(r.Tries))
|
||||
if data, err := json.Marshal(r); err == nil {
|
||||
if _, err := kv.Update(ctx, e.Key(), data, e.Revision()); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) {
|
||||
p.logf("%s: the publish item could not be written: %v", e.Key(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// itemMsg is what take reads of an item pulled from the work queue (jetstream.Msg).
|
||||
type itemMsg interface {
|
||||
Data() []byte
|
||||
InProgress() error
|
||||
Ack() error
|
||||
NakWithDelay(time.Duration) error
|
||||
Term() error
|
||||
Metadata() (*jetstream.MsgMetadata, error)
|
||||
}
|
||||
|
||||
// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448): an item whose publish item ended (dropped, or
|
||||
// its tries spent) or whose version never publishes is terminated; one whose artifacts are all published is acknowledged; once
|
||||
// publish-tries sends are spent it is terminated and version-unreleased said; while a published of it may be unheard it is handed
|
||||
// back with the pause, and one the registries' record confirms is acknowledged (H-A-274); else it is sent, the try counted in its
|
||||
// publish item, and a send that fails handed back with the pause as its delay, so the queue delivers it again and nothing is put
|
||||
// again. A sent item is acknowledged when its publish is heard (heard, Done) and delivered again after the ack wait, unheard.
|
||||
// take handles one item pulled from the work queue (§793; H-A-440 (2), H-A-448, H-A-606): an item whose version never publishes is
|
||||
// terminated; one whose artifacts are all published is acknowledged; one the registries' record confirms is acknowledged (H-A-274);
|
||||
// else it is sent. A sent item is acknowledged when its publish is heard (heard, Done) and given again after the ack wait, unheard.
|
||||
// A send that fails or is refused ends the item, the version staying reserved with version-unreleased naming the holder's words
|
||||
// (said by the send): it is put again only on the next event of ADR 0674 §2 or by builder_publish_again, never on a timer.
|
||||
func (p *publishItems) take(ctx context.Context, m itemMsg) {
|
||||
var q versions.QueuedPublish
|
||||
if err := json.Unmarshal(m.Data(), &q); err != nil || q.Module == "" || q.Version == "" {
|
||||
@@ -212,44 +98,24 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
kv := p.reasks()
|
||||
if kv == nil {
|
||||
p.logf("%s %s: the re-ask state is not on the bus yet; the item is handed back", q.Module, q.Version)
|
||||
_ = m.NakWithDelay(p.set.Pause)
|
||||
return
|
||||
}
|
||||
key := versions.PublishItemKey(q.Module, q.Version)
|
||||
e, err := kv.Get(ctx, key)
|
||||
if errors.Is(err, jetstream.ErrKeyNotFound) { // put by builder_publish_again or the move: its tries are counted from now
|
||||
if err = p.Ask(ctx, q.Module, q.Version); err == nil {
|
||||
e, err = kv.Get(ctx, key)
|
||||
if md, err := m.Metadata(); err == nil && md.NumDelivered >= publishesMaxDeliver {
|
||||
// The delivery where an item reaches the queue's ten ends it, said, never left dead on the queue (design 47 H2 H-A-653, H-A-703).
|
||||
words := fmt.Sprintf("given up after %d deliveries", publishesMaxDeliver)
|
||||
p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, words)
|
||||
if v, found, err := p.reserved(ctx, q.Module, q.Version); err == nil && found && p.unreleased != nil {
|
||||
p.unreleased(ctx, v, words)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
p.logf("%s %s: its publish item cannot be read (%v); the item is handed back", q.Module, q.Version, err)
|
||||
_ = m.NakWithDelay(p.set.Pause)
|
||||
return
|
||||
}
|
||||
r, err := build.DecodeReAsk(e.Value())
|
||||
if err != nil {
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
if r.Answer != "" {
|
||||
p.logf("%s %s at %s is terminated: its publish item ended: %s", q.Module, q.Version, q.Holder, r.Answer)
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
v, found, err := p.reserved(ctx, q.Module, q.Version)
|
||||
if err != nil {
|
||||
p.logf("%s %s: its reservation cannot be read (%v); the item is handed back", q.Module, q.Version, err)
|
||||
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
|
||||
p.logf("%s %s: its reservation cannot be read (%v); the item is given again after the ack wait", q.Module, q.Version, err)
|
||||
return
|
||||
}
|
||||
if why := versions.NotStanding(v, found); why != "" {
|
||||
p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, why)
|
||||
_ = m.Term()
|
||||
_ = kv.Delete(ctx, key)
|
||||
return
|
||||
}
|
||||
if allPublished(v, q) {
|
||||
@@ -257,17 +123,6 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
|
||||
_ = m.Ack()
|
||||
return
|
||||
}
|
||||
if r.Tries >= p.set.Tries {
|
||||
_ = m.Term()
|
||||
r.Answer = fmt.Sprintf("the publish of %s %s was tried %d times and the version is not released; builder_publish_again tries it again", r.Module, r.Version, r.Tries)
|
||||
r.Answered = p.now().UTC()
|
||||
p.logf("%s: %s", key, r.Answer)
|
||||
if p.endedWith != nil {
|
||||
p.endedWith(ctx, v, "the publish ended after "+fmt.Sprint(r.Tries)+" tries")
|
||||
}
|
||||
p.write(ctx, kv, key, r, e.Revision())
|
||||
return
|
||||
}
|
||||
if why, gone := p.notAgain(ctx, v); gone {
|
||||
_ = m.Term() // moved to another number, whose own item is asked (H-A-275)
|
||||
return
|
||||
@@ -277,39 +132,66 @@ func (p *publishItems) take(ctx context.Context, m itemMsg) {
|
||||
_ = m.Ack()
|
||||
return
|
||||
}
|
||||
p.logf("%s %s: the publish is not sent again: %s; handed back for %s", q.Module, q.Version, why, p.set.pauseAfter(r.Tries))
|
||||
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
|
||||
p.logf("%s %s at %s: the publish is not sent: %s; the item is ended, the version stays reserved", q.Module, q.Version, q.Holder, why)
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
fate := versions.SendFate{Failed: "this builder sends no publish"}
|
||||
if p.send != nil {
|
||||
// The item is marked in progress while its calls wait, so the bus gives it again only when the builder itself stopped
|
||||
// (design 47 H2 H-A-613 (3)).
|
||||
stop := p.inProgress(m)
|
||||
fate = p.send(ctx, q)
|
||||
stop()
|
||||
}
|
||||
if fate.Unread != "" {
|
||||
// A read of the builder's own state that failed is no answer of a holder: the item is left unacknowledged, given again after the
|
||||
// ack wait, and the queue's tenth delivery ends it loud (design 47 H2 H-A-745, H-A-653).
|
||||
p.logf("%s %s at %s: sent no publish: %s; the item is left, given again after the ack wait", q.Module, q.Version, q.Holder, fate.Unread)
|
||||
return
|
||||
}
|
||||
if fate.Ended != "" {
|
||||
p.logf("%s %s at %s is terminated: %s", q.Module, q.Version, q.Holder, fate.Ended)
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
r.Tries++
|
||||
r.NextTry = p.now().UTC().Add(p.set.pauseAfter(r.Tries))
|
||||
p.write(ctx, kv, key, r, e.Revision())
|
||||
if fate.Failed != "" {
|
||||
p.logf("%s %s at %s: try %d sent no publish: %s; handed back for %s", q.Module, q.Version, q.Holder, r.Tries, fate.Failed, p.set.pauseAfter(r.Tries))
|
||||
_ = m.NakWithDelay(p.set.pauseAfter(r.Tries))
|
||||
p.logf("%s %s at %s: sent no publish: %s; the item is ended, the version stays reserved and is put again on the next event of its holder (H-A-606)", q.Module, q.Version, q.Holder, fate.Failed)
|
||||
_ = m.Term()
|
||||
return
|
||||
}
|
||||
p.hold(q, m)
|
||||
// Its publish heard between the send and the hold would be missed by both: read again once held.
|
||||
p.heard(ctx, q.Module, q.Version)
|
||||
}
|
||||
|
||||
// write writes a publish item at its revision; a newer write wins.
|
||||
func (p *publishItems) write(ctx context.Context, kv jetstream.KeyValue, key string, r build.ReAsk, rev uint64) {
|
||||
data, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return
|
||||
// inProgress tells the bus the item is in progress now and at the kept call's pace until the returned function is called.
|
||||
func (p *publishItems) inProgress(m itemMsg) (stop func()) {
|
||||
every := p.progressEvery
|
||||
if every <= 0 {
|
||||
every = busretry.KeptPace().Max
|
||||
}
|
||||
if _, err := kv.Update(ctx, key, data, rev); err != nil && !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) {
|
||||
p.logf("%s: the publish item could not be written: %v", key, err)
|
||||
say := func() {
|
||||
if err := m.InProgress(); err != nil {
|
||||
p.logf("an item in progress is not said to the bus: %v", err)
|
||||
}
|
||||
}
|
||||
done, ended := make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(ended)
|
||||
say()
|
||||
t := time.NewTicker(every)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
say()
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return func() { close(done); <-ended }
|
||||
}
|
||||
|
||||
// allPublished says none of q's artifacts is missing from v: its publish is heard.
|
||||
@@ -386,20 +268,11 @@ func (p *publishItems) Ended(ctx context.Context, module, version string) {
|
||||
}
|
||||
|
||||
// notAgain says why a version's publish is not asked again now, empty when it is (design 47 H H-A-269 (2), H-A-272, H-A-274,
|
||||
// H-A-275): the builder's durable holds UnheardBound messages or more not yet heard, so a published of it may be among them; or the
|
||||
// registries' own record holds every missing artifact at its version with its built digest, which marks them published from that
|
||||
// record; or a registry holds the version at another digest, which moves the build to the next free number (gone: this item is
|
||||
// ended with the old number). A count or a record that cannot be read is said, and does not hold the ask.
|
||||
// H-A-275), judged from what the builder recorded and the registries' record, never from a count of its events unheard (design
|
||||
// 47 H2 H-A-514 addendum): the registries' own record holds every missing artifact at its version with its built digest, which
|
||||
// marks them published from that record; or a registry holds the version at another digest, which moves the build to the next
|
||||
// free number (gone: this item is ended with the old number). A record that cannot be read is said, and does not hold the ask.
|
||||
func (p *publishItems) notAgain(ctx context.Context, v versions.ReservedVersion) (why string, gone bool) {
|
||||
if p.unheard != nil {
|
||||
n, err := p.unheard(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
p.logf("%s %s: the builder's events consumer cannot be read, so the publish is asked again as it stands: %v", v.Module, v.Version, err)
|
||||
case n >= versions.UnheardBound:
|
||||
return fmt.Sprintf("the builder's events consumer holds %d messages not yet heard (the bound is %d), a published of it may be among them", n, versions.UnheardBound), false
|
||||
}
|
||||
}
|
||||
if p.judge == nil {
|
||||
return "", false
|
||||
}
|
||||
@@ -424,22 +297,6 @@ func (p *publishItems) notAgain(ctx context.Context, v versions.ReservedVersion)
|
||||
return "", false
|
||||
}
|
||||
|
||||
// unheardVia reads the builder's durable on the events stream: its messages pending and those given and not yet acknowledged
|
||||
// (design 47 H H-A-272), what it has not yet heard.
|
||||
func unheardVia(js jetstream.JetStream, stream, durable string) func(context.Context) (int, error) {
|
||||
return func(ctx context.Context) (int, error) {
|
||||
c, err := js.Consumer(ctx, stream, durable)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
info, err := c.Info(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(info.NumPending) + info.NumAckPending, nil
|
||||
}
|
||||
}
|
||||
|
||||
// registryVersionsVia asks a registry seat's verb versions for a name (H-A-272): each version it holds with its digest.
|
||||
func registryVersionsVia(call toolCaller) func(context.Context, string, string) ([]versions.HeldVersion, error) {
|
||||
return func(_ context.Context, seat, name string) ([]versions.HeldVersion, error) {
|
||||
@@ -449,8 +306,9 @@ func registryVersionsVia(call toolCaller) func(context.Context, string, string)
|
||||
}
|
||||
var a struct { // the four registry seats answer versions alike: each version with its digest
|
||||
Versions []struct {
|
||||
Version string `json:"version"`
|
||||
Digest string `json:"digest"`
|
||||
Version string `json:"version"`
|
||||
Digest string `json:"digest"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
} `json:"versions"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
@@ -458,7 +316,7 @@ func registryVersionsVia(call toolCaller) func(context.Context, string, string)
|
||||
}
|
||||
out := make([]versions.HeldVersion, 0, len(a.Versions))
|
||||
for _, v := range a.Versions {
|
||||
out = append(out, versions.HeldVersion{Version: v.Version, Digest: v.Digest})
|
||||
out = append(out, versions.HeldVersion{Version: v.Version, Digest: v.Digest, Fingerprint: v.Fingerprint})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -488,24 +346,6 @@ func numberFile(path string, def int) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// publishSettingsOf reads publish-pause (seconds), publish-pause-max (minutes) and publish-tries from their files.
|
||||
func publishSettingsOf(getenv func(string) string) (publishSettings, error) {
|
||||
s := defaultPublishSettings
|
||||
pause, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_FILE"), int(s.Pause/time.Second))
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
pmax, err := numberFile(getenv("MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"), int(s.PauseMax/time.Minute))
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
tries, err := numberFile(getenv("MESH_BUILDER_PUBLISH_TRIES_FILE"), s.Tries)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return publishSettings{Pause: time.Duration(pause) * time.Second, PauseMax: time.Duration(pmax) * time.Minute, Tries: tries}, nil
|
||||
}
|
||||
|
||||
// wirePublishItems joins the reservations to the publish items (design 47 G A-457a, A-456a, A-456b, H2 §793): a done build asks its
|
||||
// item, a release ends it and acknowledges its held items, a drop and a takeover end it and terminate them, a published heard
|
||||
// acknowledges those it publishes, and a release is recorded in releases, the last kept of each module.
|
||||
@@ -554,16 +394,29 @@ func publishesOf(module string) func() (publishesStream, error) {
|
||||
return func() (publishesStream, error) { return b, nil }
|
||||
}
|
||||
|
||||
// The consumer's numbers (H-A-446 (2)): at most four sends in flight per holder, and ten deliveries, the work queue's largest;
|
||||
// the builder ends an item at publish-tries anyway.
|
||||
const (
|
||||
publishesMaxAckPending = versions.PublishSendsAtOnce
|
||||
publishesMaxDeliver = 10
|
||||
)
|
||||
// defaultPublishAckMinutes is the setting publish-ack-minutes' default: G section 369's publish bound (H-A-606 round 3 (3)).
|
||||
const defaultPublishAckMinutes = 10
|
||||
|
||||
// publishesConsumer is the one durable consumer of holder's items (H-A-483 addendum).
|
||||
func publishesConsumer(holder string) string {
|
||||
return versions.PublishesLocal + "-" + holder
|
||||
// The consumers' numbers (H-A-700 (1), H-A-620 (2)): per holder, at most four `live` sends in flight and one `again` send, and ten
|
||||
// deliveries, the work queue's largest.
|
||||
const publishesMaxDeliver = 10
|
||||
|
||||
// publishesConsumer is the durable consumer of holder's items of a class: `publishes-<holder>-live` and `publishes-<holder>-again`
|
||||
// (H-A-700 (1)).
|
||||
func publishesConsumer(holder, class string) string {
|
||||
return versions.PublishesLocal + "-" + holder + "-" + class
|
||||
}
|
||||
|
||||
// publishesOneConsumer is the one durable of holder's items an earlier build made: its filter overlaps both classes', which a work
|
||||
// queue refuses, so a pull deletes it before it makes the two (H-A-700 (2)).
|
||||
func publishesOneConsumer(holder string) string { return versions.PublishesLocal + "-" + holder }
|
||||
|
||||
// inFlight is the sends of a class at once: four `live`, one `again` (ADR 0674 §3, H-A-620 (2)).
|
||||
func inFlight(class string) int {
|
||||
if class == versions.PublishClassStart {
|
||||
return 1
|
||||
}
|
||||
return versions.PublishSendsAtOnce
|
||||
}
|
||||
|
||||
// subject is the item's subject on the bus.
|
||||
@@ -582,7 +435,19 @@ func (pq *publishQueue) put(ctx context.Context, q versions.QueuedPublish) (bool
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ack, err := pq.js.PublishMsg(ctx, &nats.Msg{Subject: pq.subject(b, q), Data: data}, jetstream.WithMsgID(versions.PublishMsgID(q.Holder, q.Class, q.Module, q.Version)))
|
||||
// No form of a manifest's stream refuses a new message while one is held, so the subject's last message is read first: one held
|
||||
// there means the version is queued or being sent, and nothing is put (design 47 H2 H-A-620 (1); ADR 0674 §3).
|
||||
st, err := pq.js.Stream(ctx, b.Stream)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := st.GetLastMsgForSubject(ctx, pq.subject(b, q)); err == nil {
|
||||
pq.learn(ctx, q.Holder)
|
||||
return true, nil
|
||||
} else if !errors.Is(err, jetstream.ErrMsgNotFound) {
|
||||
return false, err
|
||||
}
|
||||
ack, err := pq.js.PublishMsg(ctx, &nats.Msg{Subject: pq.subject(b, q), Data: data}, jetstream.WithMsgID(q.MsgID()))
|
||||
if err != nil {
|
||||
if w := err.Error(); strings.Contains(w, "maximum bytes") || strings.Contains(w, "maximum messages") || errors.Is(err, jetstream.ErrMaxBytesExceeded) {
|
||||
return false, fmt.Errorf("%w: %v", versions.ErrQueueFull, err)
|
||||
@@ -642,72 +507,111 @@ func (pq *publishQueue) learn(ctx context.Context, holder string) {
|
||||
}
|
||||
}
|
||||
|
||||
// pull makes holder's one consumer and dispatches its items (design 47 H2 §793, H-A-483 and its addenda): first it retires the
|
||||
// holder's class durables an earlier release made (`-live`, `-again`), whose filters a work queue refuses beside the one; their
|
||||
// unacknowledged items stay on the queue and reach the one consumer.
|
||||
// pull makes holder's two consumers and dispatches their items (design 47 H2 §793, H-A-700, H-A-719): first it deletes the one
|
||||
// consumer `publishes-<holder>` an earlier build made, whose filter overlaps both and a work queue refuses overlapping filters, not
|
||||
// found ignored and a removal said; its unacknowledged items stay on the queue and reach the two. Each of the two takes the bus's
|
||||
// inactive threshold equal to the stream's own maximum age, so the bus removes the durable of a holder nothing pulled for that long
|
||||
// and no deleter is built here (H-A-719).
|
||||
func (pq *publishQueue) pull(ctx context.Context, holder string) error {
|
||||
b, err := pq.binding()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := pq.js.Stream(ctx, b.Stream)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := st.Info(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
old := publishesOneConsumer(holder)
|
||||
switch err := pq.js.DeleteConsumer(ctx, b.Stream, old); {
|
||||
case err == nil:
|
||||
pq.logf("the consumer %s of an earlier build is removed: the publishes of %s have two, one per class (H-A-700)", old, holder)
|
||||
case !errors.Is(err, jetstream.ErrConsumerNotFound):
|
||||
return fmt.Errorf("the consumer %s of an earlier build is not removed: %w", old, err)
|
||||
}
|
||||
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
|
||||
old := publishesConsumer(holder) + "-" + class
|
||||
err := pq.js.DeleteConsumer(ctx, b.Stream, old)
|
||||
switch {
|
||||
case err == nil:
|
||||
pq.logf("the consumer %s of an earlier release is removed: the publishes of %s have one consumer (H-A-483)", old, holder)
|
||||
case !errors.Is(err, jetstream.ErrConsumerNotFound):
|
||||
return fmt.Errorf("the consumer %s of an earlier release is not removed: %w", old, err)
|
||||
_, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder, class),
|
||||
FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + "." + class + ".>", AckPolicy: jetstream.AckExplicitPolicy,
|
||||
AckWait: pq.ackWait, MaxAckPending: inFlight(class), MaxDeliver: publishesMaxDeliver, InactiveThreshold: info.Config.MaxAge})
|
||||
if err != nil {
|
||||
return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder, class), err)
|
||||
}
|
||||
}
|
||||
c, err := pq.js.CreateOrUpdateConsumer(ctx, b.Stream, jetstream.ConsumerConfig{Durable: publishesConsumer(holder),
|
||||
FilterSubject: b.Subject + ".publish." + versions.EscapeToken(holder) + ".>", AckPolicy: jetstream.AckExplicitPolicy,
|
||||
AckWait: pq.ackWait, MaxAckPending: publishesMaxAckPending, MaxDeliver: publishesMaxDeliver})
|
||||
if err != nil {
|
||||
return fmt.Errorf("the consumer %s: %w", publishesConsumer(holder), err)
|
||||
}
|
||||
pq.logf("pulling the publishes of %s", holder)
|
||||
go pq.dispatch(ctx, holder, c)
|
||||
for _, class := range []string{versions.PublishClassLive, versions.PublishClassStart} {
|
||||
if err := pq.dispatch(ctx, b.Stream, holder, class); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// dispatch runs the items of one holder in the order its one consumer gives them, at most four at once (design 47 H2 §793,
|
||||
// H-A-483): each free slot takes the next item through a pull that waits, so an item put or handed back after its pause is
|
||||
// received the moment the bus gives it; an item handed back reappears only after its pause, so an item put meanwhile goes
|
||||
// before it. A pull the bus refuses ends the dispatch, said; the holder is pulled again when an item of it is put.
|
||||
func (pq *publishQueue) dispatch(ctx context.Context, holder string, c jetstream.Consumer) {
|
||||
sem := make(chan struct{}, versions.PublishSendsAtOnce)
|
||||
for {
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
// dispatch runs the items of one holder's class as the consumer gives them, at most inFlight(class) at once (design 47 H2 §793,
|
||||
// H-A-483, H-A-700, H-A-654): in the step queue's shape (serveSteps), a Consume bound to the durable, which the bus's advisories of
|
||||
// the consumer's creation and deletion bind again, so a pull error never ends it.
|
||||
func (pq *publishQueue) dispatch(ctx context.Context, stream, holder, class string) error {
|
||||
name := publishesConsumer(holder, class)
|
||||
var mu sync.Mutex
|
||||
var pulling jetstream.ConsumeContext
|
||||
bind := func() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if pulling != nil || ctx.Err() != nil {
|
||||
return pulling != nil
|
||||
}
|
||||
var got jetstream.Msg
|
||||
b, err := c.Fetch(1)
|
||||
if err == nil {
|
||||
for m := range b.Messages() {
|
||||
got = m
|
||||
}
|
||||
err = b.Error()
|
||||
c, err := pq.js.Consumer(ctx, stream, name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if err != nil && !errors.Is(err, jetstream.ErrNoMessages) && !errors.Is(err, nats.ErrTimeout) && ctx.Err() == nil {
|
||||
<-sem
|
||||
pq.logf("the publishes of %s are not pulled: %v; they are pulled when an item of it is put", holder, err)
|
||||
pq.mu.Lock()
|
||||
delete(pq.pulling, holder)
|
||||
pq.mu.Unlock()
|
||||
return
|
||||
cc, err := c.Consume(func(m jetstream.Msg) { go pq.take(ctx, m) }, jetstream.PullMaxMessages(inFlight(class)),
|
||||
jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) {
|
||||
pq.logf("the %s publishes of %s: the pull met %v; it goes on", class, holder, err)
|
||||
}))
|
||||
if err != nil {
|
||||
pq.logf("the %s publishes of %s are not pulled: %v; they are pulled when the bus says the consumer was created", class, holder, err)
|
||||
return false
|
||||
}
|
||||
if got == nil {
|
||||
<-sem
|
||||
continue
|
||||
}
|
||||
go func(m jetstream.Msg) {
|
||||
defer func() { <-sem }()
|
||||
pq.take(ctx, m)
|
||||
}(got)
|
||||
pulling = cc
|
||||
return true
|
||||
}
|
||||
release := func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if pulling == nil {
|
||||
return
|
||||
}
|
||||
pulling.Stop()
|
||||
pulling = nil
|
||||
pq.logf("the consumer %s was deleted: its items wait, and it is pulled again when the bus says it was created", name)
|
||||
}
|
||||
conn := pq.js.Conn()
|
||||
created, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.CREATED."+stream+"."+name, func(*nats.Msg) { go bind() })
|
||||
if err != nil {
|
||||
return fmt.Errorf("hearing the creation of the consumer %s: %w", name, err)
|
||||
}
|
||||
deleted, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.DELETED."+stream+"."+name, func(*nats.Msg) {
|
||||
go func() {
|
||||
release()
|
||||
bind() // made again before the deletion was heard
|
||||
}()
|
||||
})
|
||||
if err != nil {
|
||||
_ = created.Unsubscribe()
|
||||
return fmt.Errorf("hearing the deletion of the consumer %s: %w", name, err)
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = created.Unsubscribe()
|
||||
_ = deleted.Unsubscribe()
|
||||
release()
|
||||
}()
|
||||
if !bind() {
|
||||
return fmt.Errorf("the consumer %s is not bound", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// itemsOf are the items the work queue holds of module's version in class (empty for any class), each with its subject.
|
||||
@@ -789,14 +693,17 @@ func (pq *publishQueue) reader(ctx context.Context) versions.Reader {
|
||||
}}
|
||||
}
|
||||
|
||||
// drop is builder_publish_drop (§793): the version's publish item is ended with who dropped it and why, so no item of it is ever
|
||||
// drop is builder_publish_drop (§793): the version's reservation keeps who dropped its publish and why (H-A-746), so no item of it is ever
|
||||
// sent or put again; its items waiting on the work queue are removed, and one held is terminated.
|
||||
func (pq *publishQueue) drop(ctx context.Context, items *publishItems, module, version, by, why string) (string, error) {
|
||||
qs, st, err := pq.itemsOf(ctx, module, version, "")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the work queue %s cannot be read: %w", versions.PublishesLocal, err)
|
||||
}
|
||||
if err := items.endItem(ctx, module, version, fmt.Sprintf("dropped by %s: %s", by, why)); err != nil {
|
||||
if items.dropMark == nil {
|
||||
return "", errors.New("this builder keeps no reservations")
|
||||
}
|
||||
if err := items.dropMark(ctx, module, version, by, why); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for subj := range qs {
|
||||
@@ -810,48 +717,6 @@ func (pq *publishQueue) drop(ctx context.Context, items *publishItems, module, v
|
||||
return fmt.Sprintf("the publish of %s %s is dropped: %d items terminated, and none is sent or put again", module, version, len(qs)), nil
|
||||
}
|
||||
|
||||
// endItem writes the version's publish item ended with answer, made when none stands: Try and take then leave it, and a start
|
||||
// asks it no more.
|
||||
func (p *publishItems) endItem(ctx context.Context, module, version, answer string) error {
|
||||
kv := p.reasks()
|
||||
if kv == nil {
|
||||
return errors.New("the re-ask state is not on the bus yet")
|
||||
}
|
||||
key := versions.PublishItemKey(module, version)
|
||||
for range 5 {
|
||||
r := build.ReAsk{V: 1, Why: "the build ended with its version unreleased", By: "the builder", At: p.now().UTC(), Mode: build.ModePublish, Module: module, Version: version}
|
||||
e, err := kv.Get(ctx, key)
|
||||
var rev uint64
|
||||
switch {
|
||||
case errors.Is(err, jetstream.ErrKeyNotFound):
|
||||
case err != nil:
|
||||
return err
|
||||
default:
|
||||
if r, err = build.DecodeReAsk(e.Value()); err != nil {
|
||||
return err
|
||||
}
|
||||
rev = e.Revision()
|
||||
}
|
||||
r.Answer, r.Answered = answer, p.now().UTC()
|
||||
data, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rev == 0 {
|
||||
_, err = kv.Create(ctx, key, data)
|
||||
} else {
|
||||
_, err = kv.Update(ctx, key, data, rev)
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, jetstream.ErrKeyExists) && !errors.Is(err, jetstream.ErrKeyRevisionMismatch) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return errors.New("the publish item of " + module + " " + version + " changed five times while it was ended")
|
||||
}
|
||||
|
||||
// moveOld puts the items of the old state publish-queue on the work queue once at the start (§793): each under its message id, so
|
||||
// a move run twice puts each once within the duplicates window; then the builder, which made that bucket, removes it itself
|
||||
// (H-A-461 (1): the bus module's keeper holds no entry for it, so its drop refuses it). A builder whose bus holds no such
|
||||
|
||||
@@ -5,20 +5,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
@@ -90,15 +85,48 @@ func (k *itemKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOp
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListKeys lists the keys the state holds, as the bus's key lister does.
|
||||
func (k *itemKV) ListKeys(context.Context, ...jetstream.WatchOpt) (jetstream.KeyLister, error) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
ch := make(chan string, len(k.vals))
|
||||
for key := range k.vals {
|
||||
ch <- key
|
||||
}
|
||||
close(ch)
|
||||
return itemKeys{ch}, nil
|
||||
}
|
||||
|
||||
type itemKeys struct{ ch chan string }
|
||||
|
||||
func (l itemKeys) Keys() <-chan string { return l.ch }
|
||||
func (l itemKeys) Stop() error { return nil }
|
||||
|
||||
// itemMsgFake is an item pulled from the work queue: what take settled it with.
|
||||
type itemMsgFake struct {
|
||||
data []byte
|
||||
settled []string // ack, term, nak <delay>
|
||||
progress atomic.Int64 // InProgress calls
|
||||
onWorking func(n int64) // told the count after each
|
||||
data []byte
|
||||
delivered uint64 // the delivery count Metadata says; 0 says none
|
||||
settled []string // ack, term, nak <delay>
|
||||
}
|
||||
|
||||
func (m *itemMsgFake) Data() []byte { return m.data }
|
||||
func (m *itemMsgFake) Ack() error { m.settled = append(m.settled, "ack"); return nil }
|
||||
func (m *itemMsgFake) Term() error { m.settled = append(m.settled, "term"); return nil }
|
||||
func (m *itemMsgFake) InProgress() error {
|
||||
n := m.progress.Add(1)
|
||||
if m.onWorking != nil {
|
||||
m.onWorking(n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *itemMsgFake) Ack() error { m.settled = append(m.settled, "ack"); return nil }
|
||||
func (m *itemMsgFake) Term() error { m.settled = append(m.settled, "term"); return nil }
|
||||
func (m *itemMsgFake) Metadata() (*jetstream.MsgMetadata, error) {
|
||||
if m.delivered == 0 {
|
||||
return nil, errors.New("no metadata")
|
||||
}
|
||||
return &jetstream.MsgMetadata{NumDelivered: m.delivered}, nil
|
||||
}
|
||||
func (m *itemMsgFake) NakWithDelay(d time.Duration) error {
|
||||
m.settled = append(m.settled, "nak "+d.String())
|
||||
return nil
|
||||
@@ -122,26 +150,19 @@ func decodeItem(t *testing.T, raw []byte) build.ReAsk {
|
||||
return r
|
||||
}
|
||||
|
||||
// TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly: design 47 G A-457a, H2 §793 (H-A-440 (2), H-A-448) — a version's publish
|
||||
// item is asked once; its try puts the publish on the work queue and counts no try; each send counts one and a failed send hands
|
||||
// the item back with the pause doubled up to its maximum; after the setting's tries the item is terminated and ends with its words,
|
||||
// raises the condition and stays; an item whose artifacts are published is acknowledged; the release deletes it; a version no
|
||||
// longer reserved has it deleted.
|
||||
func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) {
|
||||
// TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer: design 47 H2 H-A-606 (A-473) — the ask at a build's end puts the publish on the
|
||||
// work queue once; a send that fails or is refused ends its item, the version stays reserved and nothing hands it back after a pause;
|
||||
// an item whose artifacts are published is acknowledged; a version no longer reserved is terminated; a publish its drop ended is
|
||||
// terminated whatever puts it again.
|
||||
func TestAPublishIsPutOnceAtABuildsEndAndNeverOnATimer(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
now := time.Date(2026, 11, 17, 1, 0, 0, 0, time.UTC)
|
||||
var queued, ended, sent []string
|
||||
var queued, sent []string
|
||||
reserved := true
|
||||
v := versions.ReservedVersion{Module: "m", Version: "0.1.2", Artifacts: map[string]string{"m:a": "sha256:a"}, BuiltAt: now}
|
||||
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: publishSettings{Pause: 30 * time.Second, PauseMax: 2 * time.Minute, Tries: 4},
|
||||
now: func() time.Time { return now }, logf: t.Logf,
|
||||
after: func(d time.Duration) <-chan time.Time {
|
||||
now = now.Add(d)
|
||||
c := make(chan time.Time, 1)
|
||||
c <- now
|
||||
return c
|
||||
},
|
||||
fate := versions.SendFate{Failed: "no holder answers"}
|
||||
p := &publishItems{now: func() time.Time { return now }, logf: t.Logf,
|
||||
reserved: func(_ context.Context, _, ver string) (versions.ReservedVersion, bool, error) {
|
||||
if ver == "0.3.0" { // every artifact published, its release not written yet
|
||||
return versions.ReservedVersion{Module: "m", Version: ver, Artifacts: map[string]string{"m:a": "sha256:a"}, Published: map[string]bool{"m:a": true}, BuiltAt: now}, true, nil
|
||||
@@ -154,290 +175,120 @@ func TestAPublishItemIsTriedWithAGrowingPauseAndEndsLoudly(t *testing.T) {
|
||||
},
|
||||
send: func(_ context.Context, q versions.QueuedPublish) versions.SendFate {
|
||||
sent = append(sent, q.Module+" "+q.Version)
|
||||
return versions.SendFate{Failed: "no holder answers"}
|
||||
},
|
||||
endedWith: func(_ context.Context, v versions.ReservedVersion, why string) {
|
||||
ended = append(ended, v.Version+": "+why)
|
||||
return fate
|
||||
}}
|
||||
key := versions.PublishItemKey("m", "0.1.2")
|
||||
if err := p.Ask(ctx, "m", "0.1.2"); err != nil || p.Ask(ctx, "m", "0.1.2") != nil || len(kv.vals) != 1 {
|
||||
t.Fatalf("asked: %v, %d items, want one item however often it is asked", err, len(kv.vals))
|
||||
}
|
||||
e, _ := kv.Get(ctx, key)
|
||||
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
|
||||
if len(queued) != 1 || decodeItem(t, kv.vals[key]).Tries != 0 {
|
||||
t.Fatalf("the try queued %v, tries %d: want the publish put once, no try counted", queued, decodeItem(t, kv.vals[key]).Tries)
|
||||
}
|
||||
var settled []string
|
||||
for range 5 {
|
||||
m := queuedMsg(t, "m", "0.1.2")
|
||||
p.take(ctx, m)
|
||||
settled = append(settled, m.settled...)
|
||||
}
|
||||
got := decodeItem(t, kv.vals[key])
|
||||
if len(sent) != 4 || got.Tries != 4 || got.Answer == "" || got.Answered.IsZero() || len(ended) != 1 || !strings.Contains(ended[0], "4 tries") {
|
||||
t.Fatalf("sent %v, item %+v, ended %v: want four sends, then the end said with its words and the condition", sent, got, ended)
|
||||
}
|
||||
if want := "[nak 30s nak 1m0s nak 2m0s nak 2m0s term]"; fmt.Sprint(settled) != want {
|
||||
t.Errorf("the items were settled %v, want %s (handed back with the pause doubled and capped, then terminated)", settled, want)
|
||||
if err := p.Ask(ctx, "m", "0.1.2"); err != nil || len(queued) != 1 || len(kv.vals) != 0 {
|
||||
t.Fatalf("asked: %v, queued %v, %d items: want the publish put once and no item kept", err, queued, len(kv.vals))
|
||||
}
|
||||
m := queuedMsg(t, "m", "0.1.2")
|
||||
if p.take(ctx, m); fmt.Sprint(m.settled) != "[term]" || len(sent) != 4 {
|
||||
t.Errorf("an item of an ended publish item was settled %v, sent %d: want it terminated unsent", m.settled, len(sent))
|
||||
p.take(ctx, m)
|
||||
if len(sent) != 1 || !slices.Equal(m.settled, []string{"term"}) {
|
||||
t.Fatalf("a failed send: sent %v, settled %v, want one send and the item terminated, never handed back with a pause", sent, m.settled)
|
||||
}
|
||||
// design 47 H2 H-A-745: a read of the builder's own state that failed leaves the item unacknowledged, ended nowhere.
|
||||
fate = versions.SendFate{Unread: "its reservation cannot be read: down"}
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
p.take(ctx, m)
|
||||
if len(sent) != 2 || len(m.settled) != 0 {
|
||||
t.Fatalf("an unread send: sent %v, settled %v, want it left unacknowledged", sent, m.settled)
|
||||
}
|
||||
// design 47 H2 H-A-613 (3): while its calls wait the item is marked in progress at the kept call's pace, so the bus gives it again only
|
||||
// when the builder itself stopped; the send here answers once the bus has been told three times.
|
||||
told := make(chan struct{})
|
||||
p.progressEvery = time.Millisecond
|
||||
p.send = func(context.Context, versions.QueuedPublish) versions.SendFate {
|
||||
select {
|
||||
case <-told:
|
||||
return versions.SendFate{Unread: "not answered within the bound"}
|
||||
case <-time.After(10 * time.Second):
|
||||
return versions.SendFate{Failed: "the item was never marked in progress"}
|
||||
}
|
||||
}
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
var once sync.Once
|
||||
m.onWorking = func(n int64) {
|
||||
if n >= 3 {
|
||||
once.Do(func() { close(told) })
|
||||
}
|
||||
}
|
||||
p.take(ctx, m)
|
||||
if n := m.progress.Load(); n < 3 || len(m.settled) != 0 {
|
||||
t.Fatalf("a send whose call waits: told in progress %d times, settled %v, want 3 or more and the item left, never ended", n, m.settled)
|
||||
}
|
||||
p.send = func(_ context.Context, q versions.QueuedPublish) versions.SendFate {
|
||||
sent = append(sent, q.Module+" "+q.Version)
|
||||
return fate
|
||||
}
|
||||
fate = versions.SendFate{Sent: true}
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
p.take(ctx, m)
|
||||
if len(m.settled) != 0 {
|
||||
t.Fatalf("a sent item is settled %v, want it held until its publish is heard", m.settled)
|
||||
}
|
||||
// An item whose artifacts are all published is acknowledged unsent; its publish item stays until its release is written (A-456b).
|
||||
_ = p.Ask(ctx, "m", "0.3.0")
|
||||
pk := versions.PublishItemKey("m", "0.3.0")
|
||||
m = queuedMsg(t, "m", "0.3.0")
|
||||
if p.take(ctx, m); fmt.Sprint(m.settled) != "[ack]" || len(sent) != 4 || !kv.has(pk) {
|
||||
t.Errorf("an item whose artifacts are published was settled %v, sent %d, kept %v: want it acknowledged unsent, its publish item kept", m.settled, len(sent), kv.has(pk))
|
||||
p.take(ctx, m)
|
||||
if !slices.Equal(m.settled, []string{"ack"}) {
|
||||
t.Errorf("an item whose artifacts are published settled %v, want ack", m.settled)
|
||||
}
|
||||
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
|
||||
// At the start every reservation of a done build with no release is asked, one item each.
|
||||
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
|
||||
p.allDone = func(context.Context) ([]versions.ReservedVersion, error) {
|
||||
published := versions.ReservedVersion{Module: "n", Version: "0.2.0", Artifacts: map[string]string{"n:a": "sha256:a"}, Published: map[string]bool{"n:a": true}, BuiltAt: now}
|
||||
withdrawn := versions.ReservedVersion{Module: "w", Version: "0.4.0", BuiltAt: now, Withdrawn: map[string]string{"0.4.0": "fp"}}
|
||||
return builtOf([]versions.ReservedVersion{v, published, withdrawn, {Module: "o", Version: "0.1.0"}}), nil // the last build has not ended
|
||||
}
|
||||
_ = p.Ask(ctx, "w", "0.4.0") // asked before its reservation was withdrawn
|
||||
p.AskAllDone(ctx)
|
||||
if _, ok := kv.vals[versions.PublishItemKey("w", "0.4.0")]; len(kv.vals) != 2 || ok {
|
||||
t.Errorf("the start left %d items (withdrawn's kept: %v), want one per done unreleased reservation and none for a withdrawn one (H-A-290 (2))", len(kv.vals), ok)
|
||||
}
|
||||
// A start with three unreleased done versions of one module asks only the newest and retires the two (H-A-291 (1), H-A-275).
|
||||
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
|
||||
_ = p.Ask(ctx, "s", "0.1.3") // asked in an earlier run
|
||||
p.allDone = func(context.Context) ([]versions.ReservedVersion, error) {
|
||||
var out []versions.ReservedVersion
|
||||
for _, ver := range []string{"0.1.3", "0.1.10", "0.1.2"} { // one series (H-A-293)
|
||||
out = append(out, versions.ReservedVersion{Module: "s", Version: ver, Artifacts: map[string]string{"s:a": "sha256:a"}, BuiltAt: now})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
p.retired = (&versions.Reserver{}).Retired
|
||||
p.AskAllDone(ctx)
|
||||
if _, ok := kv.vals[versions.PublishItemKey("s", "0.1.10")]; len(kv.vals) != 1 || !ok {
|
||||
t.Errorf("the start left the items %v, want only the newest, s 0.1.10, asked and the two older retired", slices.Collect(maps.Keys(kv.vals)))
|
||||
}
|
||||
kv.vals, kv.revs = map[string][]byte{}, map[string]uint64{}
|
||||
// A released version's item is deleted; a version no longer reserved has it deleted at its next try.
|
||||
p.Done(ctx, "m", "0.1.2")
|
||||
p.Done(ctx, "n", "0.2.0")
|
||||
if len(kv.vals) != 0 {
|
||||
t.Errorf("the release left %v", kv.vals)
|
||||
}
|
||||
// A withdrawn reservation has its item ended at its try, nothing queued (H-A-290 (2)).
|
||||
queued = nil
|
||||
_ = p.Ask(ctx, "m", "0.1.2")
|
||||
v.Withdrawn = map[string]string{"0.1.2": "fp"}
|
||||
e, _ = kv.Get(ctx, key)
|
||||
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
|
||||
if len(kv.vals) != 0 || len(queued) != 0 {
|
||||
t.Errorf("a withdrawn reservation left its item %v, queued %v", kv.vals, queued)
|
||||
}
|
||||
v.Withdrawn = nil
|
||||
_ = p.Ask(ctx, "m", "0.1.2")
|
||||
reserved = false
|
||||
e, _ = kv.Get(ctx, key)
|
||||
p.Try(ctx, kv, e, decodeItem(t, e.Value()))
|
||||
if len(kv.vals) != 0 {
|
||||
t.Errorf("a dropped reservation left its item %v", kv.vals)
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
p.take(ctx, m)
|
||||
if !slices.Equal(m.settled, []string{"term"}) {
|
||||
t.Errorf("an item of a version no longer reserved settled %v, want term", m.settled)
|
||||
}
|
||||
}
|
||||
|
||||
// TestThePublishSettingsAreReadFromTheirFiles: design 47 G A-457a, H2 H-A-446 (2) — the three settings, 30 s, 30 min and 5 tries
|
||||
// unless set, and a
|
||||
// content that is no number is refused naming its file.
|
||||
func TestThePublishSettingsAreReadFromTheirFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, v string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(v), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
reserved = true
|
||||
// design 47 H2 H-A-746: a publish dropped by hand is kept on the reservation, read as its standing: the item is terminated unsent.
|
||||
v.Dropped = &versions.PublishDropped{By: "a person", Why: "why", At: now}
|
||||
before := len(sent)
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
p.take(ctx, m)
|
||||
if !slices.Equal(m.settled, []string{"term"}) || len(sent) != before {
|
||||
t.Errorf("a dropped publish: settled %v, sent %d more, want it terminated and not sent", m.settled, len(sent)-before)
|
||||
}
|
||||
env := map[string]string{}
|
||||
got, err := publishSettingsOf(func(k string) string { return env[k] })
|
||||
if err != nil || got != defaultPublishSettings || got.Pause != 30*time.Second || got.PauseMax != 30*time.Minute || got.Tries != 5 {
|
||||
t.Fatalf("defaults = %+v (%v)", got, err)
|
||||
v.Dropped = nil
|
||||
// design 47 H2 H-A-653, H-A-703: the delivery where an item reaches the queue's ten ends it and raises version-unreleased.
|
||||
var words []string
|
||||
p.unreleased = func(_ context.Context, _ versions.ReservedVersion, why string) { words = append(words, why) }
|
||||
before = len(sent)
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
m.delivered = publishesMaxDeliver - 1
|
||||
p.take(ctx, m)
|
||||
if len(words) != 0 || len(sent) != before+1 {
|
||||
t.Errorf("a ninth delivery: said %v, sent %d more, want it sent", words, len(sent)-before)
|
||||
}
|
||||
env["MESH_BUILDER_PUBLISH_PAUSE_FILE"], env["MESH_BUILDER_PUBLISH_PAUSE_MAX_FILE"], env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("p", "5\n"), write("m", "2"), write("t", "3")
|
||||
if got, err = publishSettingsOf(func(k string) string { return env[k] }); err != nil || got != (publishSettings{5 * time.Second, 2 * time.Minute, 3}) {
|
||||
t.Errorf("set = %+v (%v)", got, err)
|
||||
m = queuedMsg(t, "m", "0.1.2")
|
||||
m.delivered = publishesMaxDeliver
|
||||
p.take(ctx, m)
|
||||
if !slices.Equal(m.settled, []string{"term"}) || len(sent) != before+1 || len(words) != 1 || words[0] != "given up after 10 deliveries" {
|
||||
t.Errorf("a tenth delivery: settled %v, said %v, want it terminated unsent with %q", m.settled, words, "given up after 10 deliveries")
|
||||
}
|
||||
env["MESH_BUILDER_PUBLISH_TRIES_FILE"] = write("bad", "many")
|
||||
if _, err = publishSettingsOf(func(k string) string { return env[k] }); err == nil || !strings.Contains(err.Error(), "bad") {
|
||||
t.Errorf("a content that is no number: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch: design 47 G A-457a, A-456b — a mode-publish value of the re-ask state
|
||||
// reaches the item's try through reAsked; a done build gets an item; the catalog's version-released, a drop and a takeover delete it
|
||||
// and the release is kept by module.
|
||||
func TestThePublishItemsAreWiredToTheReservationsAndTheReAskWatch(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
st := &memFindings{vals: map[string][]byte{}}
|
||||
found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
|
||||
call := func(string, any) (json.RawMessage, error) {
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
|
||||
}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf)
|
||||
rv.filled.Store(true)
|
||||
tried := make(chan string, 4)
|
||||
items := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: time.Now, logf: t.Logf,
|
||||
reserved: func(ctx context.Context, m, v string) (versions.ReservedVersion, bool, error) {
|
||||
return rv.r.Of(ctx, m, v)
|
||||
},
|
||||
republish: func(_ context.Context, m, v string) ([]string, error) { tried <- m + " " + v; return nil, nil }}
|
||||
releases := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
wirePublishItems(rv, items, releases, 2)
|
||||
done := func(fp string) versions.ReservedVersion {
|
||||
v, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: fp})
|
||||
// design 47 H2 H-A-749 (2): at the start an answered publish-drop ask is carried onto its version's reservation as dropped, where
|
||||
// it stands and holds none; a refused one is not; each record of mode publish is deleted, the drop's own ask staying.
|
||||
res := &versions.Reserver{Store: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, Now: func() time.Time { return now },
|
||||
ReleasedOf: func(context.Context, string) ([]string, error) { return nil, nil }}
|
||||
for _, m := range []string{"m", "n"} {
|
||||
rv, err := res.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "src2:" + m})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rv.Built(ctx, "m", v.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil {
|
||||
if _, _, err := res.Built(ctx, m, rv.Version, map[string]string{m + ":a": "sha256:a"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
first := done("src2:one")
|
||||
key := versions.PublishItemKey("m", first.Version)
|
||||
if !kv.has(key) {
|
||||
t.Fatalf("a done build has no publish item: %v", kv.vals)
|
||||
old := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
put := func(key string, r build.ReAsk) {
|
||||
raw, _ := json.Marshal(r)
|
||||
old.vals[key], old.revs[key] = raw, 1
|
||||
}
|
||||
// A build whose artifacts are all published still gets its item, until its release is written (A-456b).
|
||||
if _, _, err := rv.r.Published(ctx, versions.NameOf("m", "a"), first.Version, "sha256:a"); err != nil {
|
||||
t.Fatal(err)
|
||||
put("publish-drop.1", build.ReAsk{V: 1, Mode: build.ModePublishDrop, Module: "m", Version: "0.1.0", By: "op@node", Why: "a person's drop", At: now, Answered: now})
|
||||
put("publish-drop.2", build.ReAsk{V: 1, Mode: build.ModePublishDrop, Module: "n", Version: "0.1.0", By: "op@node", Why: "refused", At: now, Answered: now, Refused: true})
|
||||
put("publish.m.0.1.0", build.ReAsk{V: 1, Mode: "publish", Module: "m", Version: "0.1.0", Answer: "dropped by op@node: a person's drop", Answered: now})
|
||||
carryDrops(ctx, old, res, t.Logf)
|
||||
if m0, _, _ := res.Of(ctx, "m", "0.1.0"); m0.Dropped == nil || m0.Dropped.By != "op@node" || m0.Dropped.Why != "a person's drop" || !m0.Dropped.At.Equal(now) {
|
||||
t.Errorf("m's reservation reads dropped %+v, want the earlier drop carried onto it", m0.Dropped)
|
||||
}
|
||||
items.Done(ctx, "m", first.Version)
|
||||
if err := rv.Built(ctx, "m", first.Version, map[string]string{"m:a": "sha256:a"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !kv.has(key) {
|
||||
t.Fatalf("a build with every artifact published has no item: %v", kv.vals)
|
||||
}
|
||||
// The watch hands the item to its try, which queues the publish.
|
||||
e, _ := kv.Get(ctx, key)
|
||||
reAsked(ctx, nil, versions.Acts{}, items, kv, e, t.Logf)
|
||||
select {
|
||||
case got := <-tried:
|
||||
if got != "m "+first.Version {
|
||||
t.Errorf("tried %q", got)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("a mode-publish value was not handed to the item's try")
|
||||
}
|
||||
// A takeover by another build deletes the older's item and asks the newer's.
|
||||
second := done("src2:two")
|
||||
if kv.has(key) {
|
||||
t.Errorf("the taken-over reservation kept its item")
|
||||
}
|
||||
secondKey := versions.PublishItemKey("m", second.Version)
|
||||
if !kv.has(secondKey) {
|
||||
t.Fatalf("the newer build has no item: %v", kv.vals)
|
||||
}
|
||||
// version-released deletes the item and keeps the release.
|
||||
msg := &wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"v":1,"module":"m","version":"` + second.Version + `","source":1,"artifacts":[]}`)}
|
||||
if !rv.heard(ctx, msg) || !msg.acked {
|
||||
t.Fatal("version-released was not taken in")
|
||||
}
|
||||
if kv.has(secondKey) {
|
||||
t.Errorf("a released version kept its publish item")
|
||||
}
|
||||
if ok, _ := rv.ReleasedFor(ctx, "m", "src2:two"); !ok {
|
||||
t.Errorf("the release is not kept by fingerprint")
|
||||
}
|
||||
// A drop deletes the item too.
|
||||
third := done("src2:three")
|
||||
if _, err := rv.dropped(ctx, "m", "0.1", "op", "never", time.Unix(0, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kv.has(versions.PublishItemKey("m", third.Version)) {
|
||||
t.Errorf("a dropped reservation kept its item")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard: design 47 H H-A-269 (2), H-A-272, H-A-274, H-A-275 — a try asks the
|
||||
// publish again only while the builder's durable holds fewer than a hundred messages not yet heard and the registries' record lacks
|
||||
// an artifact; a record holding every missing artifact with the built digest marks them published from it; a record holding the
|
||||
// version at another digest moves the build to the next free number and ends this item; a skipped try spends no try and is written
|
||||
// again with its pause; a count that cannot be read holds no ask.
|
||||
func TestAPublishIsNotAskedAgainWhileItsPublishedMayBeUnheard(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.Date(2026, 11, 21, 15, 21, 0, 0, time.UTC)
|
||||
v := versions.ReservedVersion{Module: "node-tools", Version: "0.1.37", Artifacts: map[string]string{"node-tools:program": "sha256:7c9b10"}, BuiltAt: now}
|
||||
at := versions.HeldArtifact{Ref: "node-tools:program", Seat: versions.SeatArtifacts, Name: "node-tools/program", Version: "0.1.37", Digest: "sha256:7c9b10"}
|
||||
other := at
|
||||
other.Digest = "sha256:83bec1"
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
unheard int
|
||||
countErr error
|
||||
judged versions.Judged
|
||||
wantAsked, wantMark, wantMov bool
|
||||
}{
|
||||
{name: "thousands behind: no ask, the registry not read", unheard: 2944},
|
||||
{name: "at the bound: no ask", unheard: versions.UnheardBound},
|
||||
{name: "heard up, the registry holds it: marked from its record, no ask", unheard: versions.UnheardBound - 1, judged: versions.Judged{All: true, Held: []versions.HeldArtifact{at}}, wantMark: true},
|
||||
{name: "the registry holds the number at another digest: moved, no ask", unheard: 3, judged: versions.Judged{Elsewhere: []versions.HeldArtifact{other}}, wantMov: true},
|
||||
{name: "heard up, the registry lacks it: asked", unheard: 3, judged: versions.Judged{Lacks: "none"}, wantAsked: true},
|
||||
{name: "the count unreadable, the registry lacks it: asked", countErr: errors.New("no consumer"), judged: versions.Judged{Lacks: "none"}, wantAsked: true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
kv := &itemKV{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
asked, judged, marked, moved := 0, 0, 0, 0
|
||||
p := &publishItems{reasks: func() jetstream.KeyValue { return kv }, set: defaultPublishSettings, now: func() time.Time { return now }, logf: t.Logf,
|
||||
reserved: func(context.Context, string, string) (versions.ReservedVersion, bool, error) { return v, true, nil },
|
||||
send: func(context.Context, versions.QueuedPublish) versions.SendFate {
|
||||
asked++
|
||||
return versions.SendFate{Sent: true}
|
||||
},
|
||||
unheard: func(context.Context) (int, error) { return c.unheard, c.countErr },
|
||||
judge: func(context.Context, versions.ReservedVersion) (versions.Judged, error) {
|
||||
judged++
|
||||
return c.judged, nil
|
||||
},
|
||||
markHeld: func(_ context.Context, _ versions.ReservedVersion, h []versions.HeldArtifact) {
|
||||
if len(h) == 1 && h[0].Digest == "sha256:7c9b10" {
|
||||
marked++
|
||||
}
|
||||
},
|
||||
moveElsewhere: func(context.Context, versions.ReservedVersion, versions.Judged) error {
|
||||
moved++
|
||||
delete(kv.vals, versions.PublishItemKey(v.Module, v.Version)) // the takeover ends the old item
|
||||
return nil
|
||||
}}
|
||||
if err := p.Ask(ctx, v.Module, v.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := versions.PublishItemKey(v.Module, v.Version)
|
||||
m := queuedMsg(t, v.Module, v.Version)
|
||||
m.data = []byte(strings.ReplaceAll(string(m.data), `"node-tools:a"`, `"node-tools:program"`))
|
||||
p.take(ctx, m)
|
||||
if (asked == 1) != c.wantAsked || (marked == 1) != c.wantMark || (moved == 1) != c.wantMov {
|
||||
t.Fatalf("asked %d, marked %d, moved %d; want asked %v, marked %v, moved %v", asked, marked, moved, c.wantAsked, c.wantMark, c.wantMov)
|
||||
}
|
||||
if c.wantMov {
|
||||
if _, ok := kv.vals[key]; ok || fmt.Sprint(m.settled) != "[term]" {
|
||||
t.Errorf("the moved version's old item is written again, or its item settled %v, not terminated", m.settled)
|
||||
}
|
||||
return
|
||||
}
|
||||
got := decodeItem(t, kv.vals[key])
|
||||
if got.Tries != map[bool]int{true: 1, false: 0}[c.wantAsked] || (c.wantAsked && !got.NextTry.After(now)) {
|
||||
t.Errorf("tries %d, next try %s: want a try spent only when sent, the item written with its pause", got.Tries, got.NextTry)
|
||||
}
|
||||
if !c.wantAsked && fmt.Sprint(m.settled) != "[nak 30s]" {
|
||||
t.Errorf("an item not sent was settled %v, want it handed back with the pause and no try spent", m.settled)
|
||||
}
|
||||
if c.unheard >= versions.UnheardBound && judged != 0 {
|
||||
t.Error("the registry is read while a published may be unheard")
|
||||
}
|
||||
})
|
||||
if n0, _, _ := res.Of(ctx, "n", "0.1.0"); n0.Dropped != nil || old.has("publish.m.0.1.0") || !old.has("publish-drop.1") || !old.has("publish-drop.2") {
|
||||
t.Errorf("n dropped %+v, publish record left %v: want a refused drop not carried, the record gone and the asks kept", n0.Dropped, old.has("publish.m.0.1.0"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,13 +45,6 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi
|
||||
if r.Answer != "" {
|
||||
return
|
||||
}
|
||||
if r.Mode == build.ModePublish {
|
||||
// A version's publish item (design 47 G A-457a): its try waits for its pause, so it is made beside the watch.
|
||||
if items != nil {
|
||||
go items.Try(ctx, kv, e, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
if r.Mode == build.ModeBuild {
|
||||
// The answer comes when the claim and the asks are written, so it is made beside the watch, not in it.
|
||||
go builtAgain(ctx, b, kv, e, r, logf)
|
||||
@@ -65,7 +58,7 @@ func reAsked(ctx context.Context, b askAgainer, acts versions.Acts, items *publi
|
||||
released(ctx, b, kv, e, r, logf)
|
||||
return
|
||||
}
|
||||
if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeFloorAgain || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop || r.Mode == build.ModeReserveDone {
|
||||
if r.Mode == build.ModeRepublish || r.Mode == build.ModePublishDrop || r.Mode == build.ModeOldFormDrop || r.Mode == build.ModeReservedDrop {
|
||||
// A version's hand act (design 51 *Tools of the builder*) may build again, so it is answered beside the watch.
|
||||
go versionActed(ctx, acts, kv, e, r, logf)
|
||||
return
|
||||
@@ -196,16 +189,21 @@ func emitBuildEnded(ctx context.Context, js jetstream.JetStream, cred process.Ac
|
||||
return nil
|
||||
}
|
||||
|
||||
// versionActed answers a reasks value of builder_publish_again, builder_floor_again or builder_old_form's drop, a hand act said in the log.
|
||||
// versionActed answers a reasks value of builder_publish_again, builder_publish_drop, builder_reserved_drop or builder_old_form's drop, a hand act said in the log.
|
||||
func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue, e jetstream.KeyValueEntry, r build.ReAsk, logf func(string, ...any)) {
|
||||
var err error
|
||||
if r.Mode == build.ModeRepublish {
|
||||
if acts.Republish == nil {
|
||||
err = errors.New("this builder publishes nothing again")
|
||||
} else {
|
||||
r.Queued, err = acts.Republish(ctx, r.Module, r.Version)
|
||||
var said []string
|
||||
r.Queued, said, err = acts.Republish(ctx, r.Module, r.Version)
|
||||
if err == nil {
|
||||
r.Answer = "queued " + fmt.Sprint(len(r.Queued)) + " versions to publish again: " + strings.Join(r.Queued, ", ") + "; builder_publish_queue shows them"
|
||||
if len(said) > 0 {
|
||||
// A published version the catalog holds no release of has its package-published said again (H-A-773 (1)).
|
||||
r.Answer += "; said the package-published again of " + fmt.Sprint(len(said)) + " published versions the catalog holds no release of: " + strings.Join(said, ", ")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if r.Mode == build.ModePublishDrop {
|
||||
@@ -215,26 +213,16 @@ func versionActed(ctx context.Context, acts versions.Acts, kv jetstream.KeyValue
|
||||
} else {
|
||||
r.Answer, err = act(ctx, r.Module, r.Version, r.By, r.Why)
|
||||
}
|
||||
} else if r.Mode == build.ModeReserveDone {
|
||||
if acts.ReserveDone == nil {
|
||||
err = errors.New("this builder keeps no reservations")
|
||||
} else {
|
||||
r.Answer, err = acts.ReserveDone(ctx, r.Name, r.FP, r.By, r.Why, r.At)
|
||||
}
|
||||
} else if r.Mode == build.ModeReservedDrop {
|
||||
if acts.DropReserved == nil {
|
||||
err = errors.New("this builder keeps no reservations")
|
||||
} else {
|
||||
r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.By, r.Why, r.At)
|
||||
}
|
||||
} else if r.Mode == build.ModeOldFormDrop {
|
||||
if acts.DropOldForm == nil {
|
||||
err = errors.New("this builder keeps no old-form window")
|
||||
} else {
|
||||
r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
|
||||
r.Answer, err = acts.DropReserved(ctx, r.Name, r.FP, r.Version, r.By, r.Why, r.At)
|
||||
}
|
||||
} else if acts.DropOldForm == nil {
|
||||
err = errors.New("this builder keeps no old-form window")
|
||||
} else {
|
||||
r.Answer, err = acts.FloorAgain(ctx, r.Name)
|
||||
r.Answer, err = acts.DropOldForm(ctx, r.Name, r.By, r.Why, r.At)
|
||||
}
|
||||
if err != nil {
|
||||
r.Answer, r.Refused = err.Error(), true
|
||||
|
||||
@@ -42,7 +42,7 @@ import (
|
||||
// its grant. The gate over the seat's assignments, and its refusal, are mesh-sdk's (buildrun.PlacedNodes,
|
||||
// issue 774).
|
||||
func TestARefusedBucketIsSaidAndThePartGoesOn(t *testing.T) {
|
||||
t.Run("a floor's wake is heard on the events consumer (design 51 The floor)", aFloorsWakeIsHeard)
|
||||
t.Run("a registry seat's outcome is heard on the events consumer (DLV-B4)", aSeatsOutcomeIsHeard)
|
||||
t.Run("a failed trunk build is a finding until a later done one (DLV-B7)", aFailedTrunkBuildIsAFinding)
|
||||
refused := refusingBus{err: errors.New("nats: permissions violation for publish to $JS.API.CONSUMER.CREATE.KV_mesh-delivery-indexer_modules")}
|
||||
if _, err := process.EssentialBucket(context.Background(), refusingBus{refuseOpen: true, err: refused.err}, "builder", "mesh-delivery-indexer_modules", "work"); err == nil ||
|
||||
@@ -250,33 +250,16 @@ func (m *wakeMsg) Headers() nats.Header {
|
||||
return nil
|
||||
}
|
||||
|
||||
func aFloorsWakeIsHeard(t *testing.T) {
|
||||
func aSeatsOutcomeIsHeard(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
holders := map[string]string{"git": "mesh-delivery-forge-bridge", "mesh-catalog": "mesh-delivery-indexer"}
|
||||
waits := &versions.FloorWaits{Holder: func(seat string) (string, bool) { h, ok := holders[seat]; return h, ok }}
|
||||
waits.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceRequirements}}, nil, time.Unix(0, 0))
|
||||
waits.Wait("m/img", versions.SeatImages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0))
|
||||
f := &floorWake{b: &build.Builder{}, waits: waits, logf: log.New(&logs, "", 0).Printf}
|
||||
accepted := &wakeMsg{subject: takenInSubject}
|
||||
if !f.heard(context.Background(), accepted) || !accepted.acked || !strings.Contains(logs.String(), "the floor of m/lib is asked again: take-in.taken") {
|
||||
t.Fatalf("take-in.taken: acked %v, log %q", accepted.acked, logs.String())
|
||||
}
|
||||
logs.Reset()
|
||||
cleared := &wakeMsg{subject: conditionClearedSubject, data: []byte(`{"subject":{"scope":"probe","id":"ace/mesh-delivery-forge-bridge"}}`)}
|
||||
if !f.heard(context.Background(), cleared) || !strings.Contains(logs.String(), "the floor of m/img is asked again: condition-cleared") {
|
||||
t.Fatalf("condition-cleared: log %q", logs.String())
|
||||
}
|
||||
if f.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
|
||||
t.Fatal("artifacts-gone was taken as a floor's wake")
|
||||
}
|
||||
// DLV-B4: a registry seat's outcome on the same consumer moves a version; a published wakes a name whose seat was
|
||||
// silent; one the state cannot take is left for the bus to give again.
|
||||
logs.Reset()
|
||||
waits.Wait("m/pkg", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceSeat}}, nil, time.Unix(0, 0))
|
||||
h := &seatHearer{n: &versions.Numberer{Versions: versions.Versions{Store: noVersions{}}, Waits: waits}, b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
|
||||
// DLV-B4: a registry seat's outcome on the events consumer moves a version; a by-digest publish marks none and is taken.
|
||||
h := &seatHearer{b: &build.Builder{}, logf: log.New(&logs, "", 0).Printf}
|
||||
byDigest := &wakeMsg{subject: "mesh.seat.go-package-registry.event.published", data: []byte(`{"name":"m/other","digest":"sha256:aa","kind":"package","holder":"gitea"}`)}
|
||||
if !h.heard(context.Background(), byDigest) || !byDigest.acked || !strings.Contains(logs.String(), "the floor of m/pkg is asked again: go-package-registry said published") {
|
||||
t.Fatalf("published: acked %v, log %q", byDigest.acked, logs.String())
|
||||
if !h.heard(context.Background(), byDigest) || !byDigest.acked || byDigest.naked {
|
||||
t.Fatalf("published: acked %v, naked %v, log %q", byDigest.acked, byDigest.naked, logs.String())
|
||||
}
|
||||
if h.heard(context.Background(), &wakeMsg{subject: sweep.SubjectArtifactsGone}) {
|
||||
t.Fatal("artifacts-gone was taken as a seat's outcome")
|
||||
}
|
||||
// Design 47 G §369, A-415: a published of a version the reservation numbered, which the state versions does not hold, is
|
||||
// taken: its artifact is marked and package-published said, never left for the bus to give again.
|
||||
@@ -284,9 +267,8 @@ func aFloorsWakeIsHeard(t *testing.T) {
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, func(string, any) (json.RawMessage, error) {
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
|
||||
}, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
|
||||
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil, t.Logf)
|
||||
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { saidPub = append(saidPub, p); return nil }
|
||||
rv.filled.Store(true)
|
||||
res, err := rv.Reserve(context.Background(), "m", "0.1", []string{"m:program"}, versions.Source{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -299,9 +281,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
|
||||
if !h.heard(context.Background(), published) || !published.acked || published.naked || len(saidPub) != 1 || saidPub[0].Artifact != "m:program" {
|
||||
t.Fatalf("a published of a reserved version: acked %v, naked %v, said %+v, log %q", published.acked, published.naked, saidPub, logs.String())
|
||||
}
|
||||
if h.heard(context.Background(), &wakeMsg{subject: takenInSubject}) {
|
||||
t.Fatal("take-in.taken was taken as a seat's outcome")
|
||||
}
|
||||
// Design 47 G A-420: a message left for the bus is said given up on the last delivery its consumer allows, never before.
|
||||
for _, n := range []uint64{4, EventDeliveries} {
|
||||
logs.Reset()
|
||||
@@ -313,27 +292,6 @@ func aFloorsWakeIsHeard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// noVersions is a state versions that holds nothing.
|
||||
type noVersions struct{}
|
||||
|
||||
func (noVersions) Get(context.Context, string) ([]byte, uint64, bool, error) {
|
||||
return nil, 0, false, nil
|
||||
}
|
||||
func (noVersions) Create(context.Context, string, []byte) (uint64, error) {
|
||||
return 0, errors.New("read only")
|
||||
}
|
||||
func (noVersions) Update(context.Context, string, []byte, uint64) (uint64, error) {
|
||||
return 0, errors.New("read only")
|
||||
}
|
||||
func (noVersions) KeysOf(context.Context, string) ([]string, error) { return nil, nil }
|
||||
|
||||
// failingVersions is a state versions that cannot be read.
|
||||
type failingVersions struct{ noVersions }
|
||||
|
||||
func (failingVersions) KeysOf(context.Context, string) ([]string, error) {
|
||||
return nil, errors.New("down")
|
||||
}
|
||||
|
||||
func aFailedTrunkBuildIsAFinding(t *testing.T) {
|
||||
st := &memFindings{vals: map[string][]byte{}}
|
||||
f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
|
||||
@@ -354,30 +312,11 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
|
||||
if _, ok := st.vals[key]; ok {
|
||||
t.Error("a later done trunk build leaves build-failed")
|
||||
}
|
||||
// The floor finding: raised while a name waits on its floor, cleared once it is known.
|
||||
fw := &versions.FloorWaits{Said: f.floorSaid(context.Background())}
|
||||
fw.Wait("m/lib", versions.SeatGoPackages, "", versions.Floor{Silent: []string{versions.SourceTags}}, nil, time.Unix(0, 0))
|
||||
floorKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/lib", versions.FloorSilent)
|
||||
if got, err := decodeFinding(st.vals[floorKey]); err != nil || !strings.Contains(got.Summary, "git.tags did not answer") {
|
||||
t.Fatalf("the floor finding = %+v, %v", got, err)
|
||||
}
|
||||
fw.Answered("m/lib")
|
||||
if _, ok := st.vals[floorKey]; ok {
|
||||
t.Error("a known floor leaves floor-silent")
|
||||
}
|
||||
// Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a version
|
||||
// no holder answered within its bound publish-unanswered, a seat's outcome that does not read seat-outcome-unread;
|
||||
// a later published of the name clears the first two, the seat's next outcome that reads the third.
|
||||
vs := versions.Versions{Store: memVersions{}}
|
||||
for _, v := range []string{"0.1.3", "0.1.4"} {
|
||||
raw, err := versions.Encode(versions.Entry{Name: "m/program", Kind: versions.KindBundle, Series: "0.1", Version: v, Seat: "oci-artifact-registry", State: versions.Numbered})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vs.Store.(memVersions)[versions.Key("m/program", v)] = raw
|
||||
}
|
||||
pubs := &publishes{bounds: func() jetstream.KeyValue { return nil }, versions: vs, findings: f, bound: versions.PublishBound, logf: t.Logf}
|
||||
h := &seatHearer{n: &versions.Numberer{Versions: vs}, b: &build.Builder{}, logf: t.Logf, pub: pubs}
|
||||
// Design 51 *Health and conditions* (review round 1): a holder's refused is publish-refused with its reason, a seat's outcome
|
||||
// that does not read seat-outcome-unread; a later published of the name clears the first, the seat's next outcome that
|
||||
// reads the second. The numbered version's bound goes with the numbering from before G (design 47 H §756).
|
||||
pubs := &publishes{findings: f}
|
||||
h := &seatHearer{b: &build.Builder{}, logf: t.Logf, pub: pubs}
|
||||
refusedKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishRefused)
|
||||
refused := &wakeMsg{subject: "mesh.seat.oci-artifact-registry.event.refused", data: []byte(`{"name":"m/program","version":"0.1.3","digest":"sha256:bb","reason":"bytes differ"}`)}
|
||||
if !h.heard(context.Background(), refused) || !refused.acked {
|
||||
@@ -386,18 +325,10 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
|
||||
if got, err := decodeFinding(st.vals[refusedKey]); err != nil || !strings.Contains(got.Summary, "refused to publish m/program@0.1.3") || !strings.Contains(got.Summary, "bytes differ") {
|
||||
t.Fatalf("a holder's refused: the finding = %+v, %v", got, err)
|
||||
}
|
||||
pubs.ended(context.Background(), purged{key: versions.PublishBoundKey("m/program", "0.1.4")})
|
||||
// A publish-unanswered a builder of before the change raised is cleared by the name's next published.
|
||||
unansweredKey := meshconditionsclient.Key(meshconditionsclient.ScopeModule, "m/program", versions.PublishUnanswered)
|
||||
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "neither published nor refused of m/program@0.1.4") {
|
||||
t.Fatalf("a bound ended unanswered: the finding = %+v, %v", got, err)
|
||||
}
|
||||
// Review round 2: a bound that cannot be written is publish-unanswered at once; a watch of bounds that cannot start
|
||||
// is family-not-heard naming the state.
|
||||
delete(st.vals, unansweredKey)
|
||||
pubs.arm(context.Background(), versions.Entry{Name: "m/program", Version: "0.1.4", Seat: "oci-artifact-registry"})
|
||||
if got, err := decodeFinding(st.vals[unansweredKey]); err != nil || !strings.Contains(got.Summary, "its bound could not be written") {
|
||||
t.Fatalf("a bound not written: the finding = %+v, %v", got, err)
|
||||
}
|
||||
st.vals[unansweredKey] = st.vals[refusedKey]
|
||||
// A watch of bounds that cannot start is family-not-heard naming the state (review round 2).
|
||||
watchBounds(context.Background(), refusedWatch{err: errors.New("permissions violation")}, func(jetstream.KeyValueEntry) {}, f.notHeard(context.Background()), nil, t.Logf)
|
||||
if got, err := decodeFinding(st.vals[heard.Key(builds.BuilderModule, versions.BoundsState)]); err != nil || !strings.Contains(got.Summary, "permissions violation") {
|
||||
t.Fatalf("bounds not watched: the finding = %+v, %v", got, err)
|
||||
@@ -465,6 +396,26 @@ func aFailedTrunkBuildIsAFinding(t *testing.T) {
|
||||
if _, ok := st.vals[unheardKey]; ok {
|
||||
t.Error("a consumer bound leaves family-not-heard")
|
||||
}
|
||||
// H-A-877: the hub's Start answers nil once started; EVENTS is heard only when the hub's unheard list names no EVENTS entry.
|
||||
hubSays := eventsUnheard(notHeard, "a branch's end is not heard")
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
list []process.Unheard
|
||||
finding bool
|
||||
}{
|
||||
{"EVENTS unbound", []process.Unheard{{Pattern: "mesh.seat.x.event.>", Stream: "EVENTS", Why: "consumer not found"}}, true},
|
||||
{"a kept stream only", []process.Unheard{{Pattern: "mesh.seat.y.event.z", Stream: "SEAT_y_z", Why: "refused"}}, false},
|
||||
{"all heard", nil, false},
|
||||
} {
|
||||
hubSays(row.list)
|
||||
got, err := decodeFinding(st.vals[unheardKey])
|
||||
if row.finding && (err != nil || !strings.Contains(got.Summary, "consumer not found")) {
|
||||
t.Errorf("%s: the finding = %+v, %v", row.name, got, err)
|
||||
}
|
||||
if _, ok := st.vals[unheardKey]; ok != row.finding {
|
||||
t.Errorf("%s: finding present = %v, want %v", row.name, ok, row.finding)
|
||||
}
|
||||
}
|
||||
// DLV-B9, the old form's window: one counted node reading only the first form holds it; seven days on it is
|
||||
// old-form-held about that node; the node stating the newest form closes it, said once, the finding cleared; a
|
||||
// retired node dropped by hand leaves the count.
|
||||
@@ -603,6 +554,17 @@ func (m *memFindings) Write(_ context.Context, f mcseat.Finding) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Held answers the findings kept, as the held writer answers those it holds.
|
||||
func (m *memFindings) Held() []mcseat.Finding {
|
||||
var out []mcseat.Finding
|
||||
for _, v := range m.vals {
|
||||
if f, err := decodeFinding(v); err == nil {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Clear deletes the finding of scope, id and kind.
|
||||
func (m *memFindings) Clear(_ context.Context, scope, id, kind, _ string) error {
|
||||
delete(m.vals, views.FindingKey(scope, id, kind))
|
||||
@@ -624,4 +586,8 @@ func TestTheBuildersFindingsAreObservedByItsCredentialsModule(t *testing.T) {
|
||||
if err != nil || got.Observer != "acme-builder" {
|
||||
t.Fatalf("the finding = %+v, %v; want the observer acme-builder", got, err)
|
||||
}
|
||||
// H2 H-A-578 (1): floor-silent, which no code of the builder raises any more, is cleared at the writer's start
|
||||
if !slices.ContainsFunc(retiredFindingKinds, func(r views.RetiredKind) bool { return r.Kind == "floor-silent" && len(r.IDs) == 0 }) || slices.ContainsFunc(retiredFindingKinds, func(r views.RetiredKind) bool { return r.Kind == BuildFailed }) {
|
||||
t.Error("the writer's retired kinds are not floor-silent alone")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,11 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
@@ -47,9 +49,15 @@ func publishAskID(p versions.Publish) string {
|
||||
// artifact store, addressed by digest. The four seats' publish take one wire form; an answer that lacks parts, or a fault of
|
||||
// the call, is the holder's refusal, said in its words (not stored when the holder lacks the bytes). The publish is a kept
|
||||
// call carrying its ask id (design 47 H2 §775), made again through transport faults at the kept-call pace within ctx's bound.
|
||||
func sendVia(call keptCaller) func(ctx context.Context, p versions.Publish) error {
|
||||
//
|
||||
// said is told when the call has waited five minutes unanswered and once at its answer (busretry.WaitSaid; design 47 H2 H-A-613 (4),
|
||||
// H-A-620 (3): call-unanswered written after five minutes, ADR 0668 §3); nil is told nothing.
|
||||
func sendVia(call keptCaller, said func(p versions.Publish, w busretry.Waited)) func(ctx context.Context, p versions.Publish) error {
|
||||
return func(ctx context.Context, p versions.Publish) error {
|
||||
ask := process.KeptAsk{ID: publishAskID(p)}
|
||||
if said != nil {
|
||||
ask.Hook = func(w busretry.Waited) { said(p, w) }
|
||||
}
|
||||
if d, ok := ctx.Deadline(); ok {
|
||||
ask.Bound = time.Until(d)
|
||||
}
|
||||
@@ -62,6 +70,11 @@ func sendVia(call keptCaller) func(ctx context.Context, p versions.Publish) erro
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return fmt.Errorf("%s answered what is no publish answer: %w", p.Seat, err)
|
||||
}
|
||||
// A version held with other bytes is answered, never failed (design 47 H2 H-A-729); it is read before the transfer, which is
|
||||
// absent exactly then (H-A-732).
|
||||
if a.OtherBytes != nil {
|
||||
return &versions.OtherBytes{Seat: p.Seat, Name: p.Name, Version: p.Version, Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}
|
||||
}
|
||||
if len(a.Lacks) > 0 {
|
||||
return fmt.Errorf("%s%s holds %d of the parts of %s %s", versions.NotStoredWords, p.Seat, len(a.Lacks), p.Name, p.Version)
|
||||
}
|
||||
@@ -96,3 +109,18 @@ func callWithin(ctx context.Context, call toolCaller, key string, body any) (jso
|
||||
func publishBody(p versions.Publish) gopackageregistry.PublishInput {
|
||||
return gopackageregistry.PublishInput{Commit: p.Commit, Digest: p.Digest, Fingerprint: p.Fingerprint, Kind: p.Kind, Name: p.Name, Transfer: p.Transfer, Version: p.Version}
|
||||
}
|
||||
|
||||
// publishUnanswered is what a publish's kept call tells when it has waited five minutes and at its answer (design 47 H2 H-A-613 (4),
|
||||
// H-A-620 (3); ADR 0668 §3): the finding call-unanswered about the publish's ask id is raised at the first and cleared at the second.
|
||||
func publishUnanswered(ctx context.Context, f *findings) func(versions.Publish, busretry.Waited) {
|
||||
return func(p versions.Publish, w busretry.Waited) {
|
||||
id := publishAskID(p)
|
||||
if w.Answered {
|
||||
f.clear(ctx, meshconditionsclient.KindCallUnanswered, meshconditionsclient.ScopeCall, id)
|
||||
return
|
||||
}
|
||||
o := callUnanswered(id, "seat:"+p.Seat+"."+versions.VerbPublish+" of "+p.Name+" "+p.Version, "", w.Last, "builder."+meshconditionsclient.KindCallUnanswered, w.Since)
|
||||
o.needs = "the call is made again by itself until the holder answers; builder_publish_queue shows the item."
|
||||
f.raise(ctx, o)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
@@ -54,7 +57,7 @@ func TestRepublishSend(t *testing.T) {
|
||||
send := sendVia(func(ask process.KeptAsk, key string, body any) (json.RawMessage, error) {
|
||||
asked, id = key, ask.ID
|
||||
return json.RawMessage(c.answer), c.err
|
||||
})
|
||||
}, nil)
|
||||
err := send(context.Background(), p)
|
||||
// design 47 H2 §775: the publish carries its ask id, the same for the same publish
|
||||
if asked != "seat:oci-artifact-registry.publish" || id != publishAskID(p) || strings.Contains(id, ".") || (c.want == "") != (err == nil) || (err != nil && !strings.Contains(err.Error(), c.want)) {
|
||||
@@ -73,7 +76,7 @@ func TestRepublishSend(t *testing.T) {
|
||||
}
|
||||
for name, call := range map[string]func(context.Context) error{
|
||||
"the publish": func(ctx context.Context) error {
|
||||
return sendVia(func(_ process.KeptAsk, k string, b any) (json.RawMessage, error) { return slow(k, b) })(ctx, p)
|
||||
return sendVia(func(_ process.KeptAsk, k string, b any) (json.RawMessage, error) { return slow(k, b) }, nil)(ctx, p)
|
||||
},
|
||||
"the entry": func(ctx context.Context) error { _, err := entryVia(slow)(ctx, "fp"); return err },
|
||||
} {
|
||||
@@ -89,3 +92,29 @@ func TestRepublishSend(t *testing.T) {
|
||||
}
|
||||
|
||||
func versionsNow() time.Time { return time.Unix(1, 0) }
|
||||
|
||||
// Design 47 H2 H-A-613 (4), H-A-620 (3): a publish's kept call that has waited five minutes raises call-unanswered about its ask id,
|
||||
// and its answer clears it; the call carries the hook that says so.
|
||||
func TestAPublishWaitedFiveMinutesIsCallUnanswered(t *testing.T) {
|
||||
p := versions.Publish{Seat: versions.SeatArtifacts, Kind: "bundle", Name: "m/prog", Version: "0.1.3", Digest: "sha256:aa"}
|
||||
st := &memFindings{vals: map[string][]byte{}}
|
||||
f := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
|
||||
said := publishUnanswered(context.Background(), f)
|
||||
var hook func(busretry.Waited)
|
||||
_ = sendVia(func(ask process.KeptAsk, _ string, _ any) (json.RawMessage, error) {
|
||||
hook = ask.Hook
|
||||
return json.RawMessage(`{"held":true}`), nil
|
||||
}, said)(context.Background(), p)
|
||||
if hook == nil {
|
||||
t.Fatal("the publish's kept call carries no hook")
|
||||
}
|
||||
key := meshconditionsclient.Key(meshconditionsclient.ScopeCall, publishAskID(p), meshconditionsclient.KindCallUnanswered)
|
||||
hook(busretry.Waited{Since: time.Unix(0, 0), Last: "no responders"})
|
||||
if got, err := decodeFinding(st.vals[key]); err != nil || got.Kind != meshconditionsclient.KindCallUnanswered || !strings.Contains(got.Summary, "m/prog 0.1.3") {
|
||||
t.Fatalf("the call waited: finding %+v, %v", got, err)
|
||||
}
|
||||
hook(busretry.Waited{Answered: true})
|
||||
if st.vals[key] != nil {
|
||||
t.Error("the call answered: the finding stands")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
@@ -22,10 +22,10 @@ import (
|
||||
)
|
||||
|
||||
// The reservations (design 47 G §369): the builder's state reserved, the catalog's versions it numbers from, and the
|
||||
// catalog's version-released and versions-filled it hears.
|
||||
// catalog's version-released it hears.
|
||||
|
||||
// awaitedReserved is the state reserved as versions.ReserveStore: bound once the bus holds it.
|
||||
type awaitedReserved struct{ awaitedVersions }
|
||||
type awaitedReserved struct{ awaitedState }
|
||||
|
||||
func (s awaitedReserved) Delete(ctx context.Context, key string) error {
|
||||
kv, err := s.kv()
|
||||
@@ -48,11 +48,9 @@ type reservations struct {
|
||||
// ended ends the publish item of a build withdrawn, superseded or dropped, its held items terminated; heard acknowledges the
|
||||
// held items of a version a published newly marked (design 47 H2 §793). Nil are none.
|
||||
itemEnded, itemHeard func(ctx context.Context, module, version string)
|
||||
filled atomic.Bool
|
||||
bounds func() jetstream.KeyValue
|
||||
found *findings
|
||||
bound time.Duration
|
||||
wake func(context.Context)
|
||||
logf func(string, ...any)
|
||||
// withdraw ends the running build of a module's fingerprint, superseded, with why (H-A-225); nil ends none.
|
||||
withdraw func(module, fingerprint, why string)
|
||||
@@ -61,6 +59,10 @@ type reservations struct {
|
||||
recordAgain func(ctx context.Context, module, fp, when string) (string, error)
|
||||
// rebuild builds a done key of module at fp again (the build-again path, A-490; H-A-279); nil builds none.
|
||||
rebuild func(ctx context.Context, module, fp, why string) error
|
||||
// looking says a look of the builder holds the build key of module at fp now (builder_reserved_drop refuses it); nil says none.
|
||||
looking func(module, fp string) bool
|
||||
// judge reads the registries' record of a reservation's artifacts at its version (the republisher's Held); nil reads none.
|
||||
judge func(ctx context.Context, v versions.ReservedVersion) (versions.Judged, error)
|
||||
// say says package-published on the seat mesh-builds; nil says none.
|
||||
say func(context.Context, meshbuilds.PackagePublished) error
|
||||
// names is each package's name as its series key names it (for Go, its module path), and sayReserved says version-reserved on
|
||||
@@ -116,9 +118,9 @@ func sayReservedOn(js jetstream.JetStream, cred process.Account) func(context.Co
|
||||
|
||||
// newReservations makes the reserving over store; the released versions of a module are asked of the seat mesh-catalog's
|
||||
// verb versions through call (design 47 G §348), the only source numbering reads them from.
|
||||
func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, wake func(context.Context), logf func(string, ...any)) *reservations {
|
||||
rv := &reservations{bounds: bounds, found: found, bound: versions.UnreleasedBound, wake: wake, logf: logf}
|
||||
rv.r = &versions.Reserver{Store: store, Filled: rv.filled.Load, ReleasedOf: func(_ context.Context, module string) ([]string, error) {
|
||||
func newReservations(store versions.ReserveStore, call toolCaller, bounds func() jetstream.KeyValue, found *findings, logf func(string, ...any)) *reservations {
|
||||
rv := &reservations{bounds: bounds, found: found, bound: defaultPublishAckMinutes * time.Minute, logf: logf}
|
||||
rv.r = &versions.Reserver{Store: store, ReleasedOf: func(_ context.Context, module string) ([]string, error) {
|
||||
raw, err := call("seat:"+meshcatalog.Seat+".versions", meshcatalog.VersionsInput{Module: module})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -134,9 +136,17 @@ func newReservations(store versions.ReserveStore, call toolCaller, bounds func()
|
||||
return out, nil
|
||||
}}
|
||||
rv.r.Took, rv.r.Logf, rv.r.Reserved = rv.took, logf, rv.reservedSaid
|
||||
rv.setBound(rv.bound)
|
||||
return rv
|
||||
}
|
||||
|
||||
// setBound sets the publish's bound, the setting publish-ack-minutes (design 47 H2 H-A-613 (3)): past it a built reservation
|
||||
// with an artifact unpublished is the finding version-unreleased, armed and judged by this one value.
|
||||
func (rv *reservations) setBound(d time.Duration) {
|
||||
rv.bound = d
|
||||
rv.r.Bound = d
|
||||
}
|
||||
|
||||
// reindex writes the reservations' index again from the reservations, once at the builder's start (H-A-269 (1), H-A-271), and
|
||||
// says so.
|
||||
func (rv *reservations) reindex(ctx context.Context) {
|
||||
@@ -189,66 +199,135 @@ func (rv *reservations) TakenOver(ctx context.Context, module, fingerprint strin
|
||||
return rv.r.TakenOver(ctx, module, fingerprint)
|
||||
}
|
||||
|
||||
func (rv *reservations) Filled() bool { return rv.filled.Load() }
|
||||
// PublishedOf answers the seat mesh-builds' published rule for the build's pins (H-A-328, design 47 H2 H-A-707 (4)).
|
||||
func (rv *reservations) PublishedOf(ctx context.Context, module, artifact, fingerprint string) (meshbuilds.PublishedAnswer, error) {
|
||||
return rv.r.PublishedOf(ctx, module, artifact, fingerprint)
|
||||
}
|
||||
|
||||
func (rv *reservations) Reserve(ctx context.Context, module, series string, artifacts []string, src versions.Source) (versions.ReservedVersion, error) {
|
||||
return rv.r.Reserve(ctx, module, series, artifacts, src)
|
||||
}
|
||||
|
||||
// Built records the digests; once every artifact has one, the publish's bound starts (a key of the state bounds with its
|
||||
// own time to live): its end with the reservation standing is version-unreleased.
|
||||
// Built records the digests, in one compare-and-set of the reservation (issue 1984 note 8, 1984/AC4), and then takes the
|
||||
// reservation's state in, whatever ended its build: this record or one before it whose end was lost, as a look hands a recorded
|
||||
// reservation here with its digests (1984/AC5). A built reservation has the published kept on it taken in first, and then, on the
|
||||
// reservation as that take-in left it, its publish's bound armed and its publish item asked (design 47 G A-457a; it stands until
|
||||
// its release, A-456b).
|
||||
func (rv *reservations) Built(ctx context.Context, module, version string, digests map[string]string, deps map[string][]meshbuilds.Dependency) error {
|
||||
for ref, d := range digests {
|
||||
if _, err := rv.r.Built(ctx, module, version, ref, d, deps[ref]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cur, found, err := rv.r.Of(ctx, module, version)
|
||||
if err != nil || !found || cur.BuiltAt.IsZero() {
|
||||
cur, standing, err := rv.r.Built(ctx, module, version, digests, deps)
|
||||
if err != nil || !standing || cur.BuiltAt.IsZero() {
|
||||
return err
|
||||
}
|
||||
if cur, standing = rv.takeKept(ctx, cur); !standing {
|
||||
return nil
|
||||
}
|
||||
rv.arm(ctx, cur)
|
||||
if rv.built != nil {
|
||||
if err := rv.built(ctx, module, version); err != nil {
|
||||
rv.logf("%v", err)
|
||||
}
|
||||
}
|
||||
// A published heard before the digests were recorded marks its artifact now, said as one heard after (design 47 G A-415).
|
||||
marked, unmatched, err := rv.r.Kept(ctx, module, version)
|
||||
if err != nil {
|
||||
rv.logf("the published kept on %s %s are not taken in: %v", module, version, err)
|
||||
}
|
||||
for _, h := range unmatched {
|
||||
rv.logf("a published of %s@%s kept on %s %s marks no artifact: its digest %s is none of the built digests %v", h.Name, h.Version, module, version, h.Digest, cur.Artifacts)
|
||||
// A build whose recorded digest differs from what the holder holds at its version fails loudly at once: the version is taken
|
||||
// and no artifact is marked for it, so it is never released (design 47 G A-490j).
|
||||
rv.unreleased(ctx, cur, fmt.Sprintf("the holder holds %s@%s under digest %s, which no artifact of the build carries (%v): the version is taken and is never released",
|
||||
h.Name, h.Version, h.Digest, cur.Artifacts))
|
||||
}
|
||||
for _, m := range marked {
|
||||
rv.sayPublished(ctx, m, m.Reserved.Artifacts[m.Artifact])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// takeKept takes the published kept on a built reservation in (design 47 G A-415): each whose digest is an artifact's marks it and
|
||||
// is said as package-published, as one heard after; one whose digest no artifact carries raises version-unreleased at once (A-490j).
|
||||
// It answers the reservation as the take-in left it, and whether it stands built at its version, so its bound is judged on the
|
||||
// artifacts the take-in marked (1984/AC5); one whose kept cannot be taken in is answered as it was given, its kept said not taken.
|
||||
func (rv *reservations) takeKept(ctx context.Context, cur versions.ReservedVersion) (versions.ReservedVersion, bool) {
|
||||
if len(cur.Kept) == 0 {
|
||||
return cur, true
|
||||
}
|
||||
took, err := rv.r.Kept(ctx, cur.Module, cur.Version)
|
||||
if err != nil {
|
||||
rv.logf("the published kept on %s %s are not taken in: %v", cur.Module, cur.Version, err)
|
||||
return cur, true
|
||||
}
|
||||
if !took.Standing {
|
||||
rv.logf("the published kept on %s %s are not taken in: its reservation stands no more built at the version", cur.Module, cur.Version)
|
||||
return cur, false
|
||||
}
|
||||
for _, h := range took.Unmatched {
|
||||
rv.logf("a published of %s@%s kept on %s %s marks no artifact: its digest %s is none of the built digests %v", h.Name, h.Version, cur.Module, cur.Version, h.Digest, cur.Artifacts)
|
||||
// A build whose recorded digest differs from what the holder holds at its version fails loudly at once: the version is taken
|
||||
// and no artifact is marked for it, so it is never released (design 47 G A-490j).
|
||||
rv.unreleased(ctx, took.Reserved, fmt.Sprintf("the holder holds %s@%s under digest %s, which no artifact of the build carries (%v): the version is taken and is never released",
|
||||
h.Name, h.Version, h.Digest, cur.Artifacts))
|
||||
}
|
||||
for _, m := range took.Marked {
|
||||
rv.sayPublished(ctx, m, m.Reserved.Artifacts[m.Artifact])
|
||||
}
|
||||
return took.Reserved, true
|
||||
}
|
||||
|
||||
// now is the reservations' clock, the Reserver's, from which a build's end (BuiltAt) is written.
|
||||
func (rv *reservations) now() time.Time {
|
||||
if rv.r.Now != nil {
|
||||
return rv.r.Now().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
// arm arms a built reservation's publish's bound, a key of the state bounds with its own time to live, counted from its build's
|
||||
// end (BuiltAt): its end with the reservation standing is version-unreleased. One armed already stands; at a look or the start
|
||||
// after the bound passed, a reservation left with an artifact unpublished is version-unreleased at once (lapsed), and its bound
|
||||
// is not armed again (issue 1984 note 8, 1984/AC5); one with every artifact published is version-unreleased at once too when the
|
||||
// catalog's versions hold no release of it or cannot be read, even when its package-published were said a moment before, and its
|
||||
// version-released clears it (design 47 H2 H-A-773 (2), (5), (7)).
|
||||
func (rv *reservations) arm(ctx context.Context, v versions.ReservedVersion) {
|
||||
ends := v.BuiltAt.Add(rv.bound)
|
||||
left := ends.Sub(rv.now())
|
||||
if left <= 0 {
|
||||
if len(v.Missing()) > 0 {
|
||||
rv.lapsed(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound))
|
||||
} else {
|
||||
rv.lostRelease(ctx, v, fmt.Sprintf("within %s of its build", rv.bound))
|
||||
}
|
||||
return
|
||||
}
|
||||
kv := rv.bounds()
|
||||
var err error
|
||||
if kv == nil {
|
||||
err = fmt.Errorf("%s is not on the bus yet", versions.BoundsState)
|
||||
} else if _, err = kv.Create(ctx, versions.ReservedBoundKey(v.Module, v.Series), versions.EncodeBound("the release of "+v.Module+" "+v.Version, time.Now().Add(rv.bound)), jetstream.KeyTTL(rv.bound)); errors.Is(err, jetstream.ErrKeyExists) {
|
||||
} else if _, err = kv.Create(ctx, versions.ReservedBoundKey(v.Module, v.Series), versions.EncodeBound("the release of "+v.Module+" "+v.Version, ends),
|
||||
jetstream.KeyTTL(max(time.Second, left.Round(time.Second)))); errors.Is(err, jetstream.ErrKeyExists) {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
rv.logf("the release bound of %s %s is not written, so it is raised unreleased now: %v", v.Module, v.Version, err)
|
||||
rv.unreleased(ctx, v, fmt.Sprintf("its bound could not be written (%v)", err))
|
||||
rv.lapsed(ctx, v, fmt.Sprintf("its bound could not be written (%v)", err))
|
||||
}
|
||||
}
|
||||
|
||||
// unreleased raises version-unreleased about the module, naming the version and the artifacts missing.
|
||||
// lapsed raises version-unreleased for a built reservation whose bound ended or could not be armed, only when the module's
|
||||
// version-unreleased does not stand already (the held writer's Held, design 47 G A-38): a standing one keeps the words it was
|
||||
// raised with, a holder's refusal of a publish again (ADR 0674 §3) or a digest no artifact carries (A-490j). Those two raise
|
||||
// through unreleased, as they happen, and write over a standing one with their words.
|
||||
func (rv *reservations) lapsed(ctx context.Context, v versions.ReservedVersion, why string) {
|
||||
if rv.found.stands(versions.VersionUnreleased, meshconditionsclient.ScopeModule, v.Module) {
|
||||
return
|
||||
}
|
||||
rv.unreleased(ctx, v, why)
|
||||
}
|
||||
|
||||
// lostRelease raises version-unreleased for a built reservation past its bound with every artifact published whose version the
|
||||
// catalog's verb versions does not hold, its release lost, and for one whose versions cannot be read, saying so (design 47 H2
|
||||
// H-A-773 (2), (5), (6)); a standing one keeps its words (lapsed). within says the bound.
|
||||
func (rv *reservations) lostRelease(ctx context.Context, v versions.ReservedVersion, within string) {
|
||||
lost, err := rv.r.ReleaseLost(ctx, v)
|
||||
switch {
|
||||
case err != nil:
|
||||
rv.lapsed(ctx, v, fmt.Sprintf("the catalog's versions could not be read %s to say whether it is released: %v", within, err))
|
||||
case lost:
|
||||
rv.lapsed(ctx, v, "the catalog holds no release of it "+within+": its release was lost")
|
||||
}
|
||||
}
|
||||
|
||||
// unreleased raises version-unreleased about the module, naming the version and the artifacts missing, or that every artifact is
|
||||
// published (H-A-773 (2)).
|
||||
func (rv *reservations) unreleased(ctx context.Context, v versions.ReservedVersion, why string) {
|
||||
missing := v.Missing()
|
||||
what := "an artifact is unpublished"
|
||||
what := "every artifact is published"
|
||||
if len(missing) > 0 {
|
||||
what = strings.Join(missing, ", ") + " unpublished"
|
||||
}
|
||||
@@ -257,7 +336,7 @@ func (rv *reservations) unreleased(ctx context.Context, v versions.ReservedVersi
|
||||
headline: "A built version is not released",
|
||||
explanation: "The builder reserved " + v.Module + " " + v.Version + " and its build ended, and the catalog has not said version-released: " + what + ".",
|
||||
resolved: "The catalog says version-released for " + v.Module + " " + v.Version + ".",
|
||||
needs: "builder_reserved shows the reservation; builder_publish_again publishes the missing artifacts under it; builder_reserved_drop drops it."})
|
||||
needs: "builder_reserved shows the reservation; builder_publish_again publishes the missing artifacts under it, or says a published one's package-published again; builder_reserved_drop drops it."})
|
||||
}
|
||||
|
||||
// unreleasedWords raises version-unreleased about a version with the words of a publish again that ended badly.
|
||||
@@ -266,7 +345,9 @@ func (rv *reservations) unreleasedWords(ctx context.Context, v versions.Reserved
|
||||
}
|
||||
|
||||
// ended is told each change of the state bounds: a reservation's bound whose time ended raises version-unreleased while
|
||||
// the reservation stands built.
|
||||
// the reservation stands built with an artifact unpublished (lapsed: a standing one keeps its words); one with every artifact
|
||||
// published is not left unmarked (issue 1984 note 8, 1984/AC5), and raises it when the catalog's versions hold no release of it,
|
||||
// its release lost, or cannot be read (design 47 H2 H-A-773 (2), (5), (6)).
|
||||
func (rv *reservations) ended(ctx context.Context, e jetstream.KeyValueEntry) bool {
|
||||
key, ok := versions.ReservedBoundOf(e.Key())
|
||||
if !ok {
|
||||
@@ -279,7 +360,11 @@ func (rv *reservations) ended(ctx context.Context, e jetstream.KeyValueEntry) bo
|
||||
if err != nil || !found || v.BuiltAt.IsZero() {
|
||||
return true
|
||||
}
|
||||
rv.unreleased(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound))
|
||||
if len(v.Missing()) == 0 {
|
||||
rv.lostRelease(ctx, v, fmt.Sprintf("within %s of its build", rv.bound))
|
||||
return true
|
||||
}
|
||||
rv.lapsed(ctx, v, fmt.Sprintf("nothing within %s of its build", rv.bound))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -292,16 +377,10 @@ func (rv *reservations) dropBound(ctx context.Context, key string) {
|
||||
}
|
||||
}
|
||||
|
||||
// heard takes the catalog's version-released and versions-filled in, and a registry seat's published (published): a
|
||||
// heard takes the catalog's version-released in, and a registry seat's published (published): a
|
||||
// message that is none of them is left to the others. A state that cannot take one leaves it for the bus to give again.
|
||||
func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
|
||||
switch m.Subject() {
|
||||
case meshcatalog.SubjectVersionsFilled:
|
||||
rv.filled.Store(true)
|
||||
rv.logf("the catalog said versions-filled: versions are reserved from now on")
|
||||
if rv.wake != nil {
|
||||
rv.wake(ctx)
|
||||
}
|
||||
case meshcatalog.SubjectVersionReleased:
|
||||
var ev meshcatalog.VersionReleasedEvent
|
||||
if err := json.Unmarshal(m.Data(), &ev); err != nil || ev.Module == "" || ev.Version == "" {
|
||||
@@ -328,6 +407,10 @@ func (rv *reservations) heard(ctx context.Context, m jetstream.Msg) bool {
|
||||
// release takes a released version in as the catalog's version-released says it (design 47 G §369): its reservation released,
|
||||
// its bound and publish item ended and its findings cleared. No git tag is written (design 47 H2 H-A-494).
|
||||
func (rv *reservations) release(ctx context.Context, ev meshcatalog.VersionReleasedEvent) error {
|
||||
// A version no reservation holds is acknowledged at once from its one key, never by listing (H-A-514 addendum).
|
||||
if held, err := rv.r.Holds(ctx, ev.Module, ev.Version); err == nil && !held {
|
||||
return nil
|
||||
}
|
||||
gone, err := rv.r.Released(ctx, ev.Module, ev.Version)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -350,7 +433,9 @@ func (rv *reservations) release(ctx context.Context, ev meshcatalog.VersionRelea
|
||||
// (design 47 H2 H-A-494).
|
||||
// A module whose versions cannot be read, and a release that is not taken, are said and left to its next version-released.
|
||||
// Before that, a standing reservation with no digests recorded whose build key is done has them recorded from the done key
|
||||
// (design 47 H2 H-A-492), so it is held against the released versions too.
|
||||
// (design 47 H2 H-A-492), so it is held against the released versions too. Every built reservation not released is taken in as
|
||||
// its record's end would have (issue 1984 note 8, 1984/AC5): the published kept on it taken in and said, and then its bound armed
|
||||
// on the reservation as that take-in left it.
|
||||
func (rv *reservations) releasedAtStart(ctx context.Context) {
|
||||
all, err := rv.r.All(ctx)
|
||||
if err != nil {
|
||||
@@ -376,6 +461,10 @@ func (rv *reservations) releasedAtStart(ctx context.Context) {
|
||||
read[v.Module] = released
|
||||
}
|
||||
if !slices.Contains(released, v.Version) {
|
||||
// Taken in as its record's end would have (1984/AC5); its publish item is asked by AskAllDone, next.
|
||||
if cur, standing := rv.takeKept(ctx, v); standing {
|
||||
rv.arm(ctx, cur)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := rv.release(ctx, meshcatalog.VersionReleasedEvent{Module: v.Module, Version: v.Version}); err != nil {
|
||||
@@ -386,8 +475,8 @@ func (rv *reservations) releasedAtStart(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// recordedAtStart records the digests of every standing reservation that has none recorded and whose build key is done (design 47
|
||||
// H2 H-A-492): a record its build's end lost. It answers whether one was recorded; one that cannot be is said.
|
||||
// recordedAtStart records the digests of every standing reservation that has not all recorded and whose build key is done (design
|
||||
// 47 H2 H-A-492): a record its build's end lost, whole or in part. It answers whether one was recorded; one that cannot be is said.
|
||||
func (rv *reservations) recordedAtStart(ctx context.Context, all []versions.ReservedVersion) bool {
|
||||
if rv.recordAgain == nil {
|
||||
return false
|
||||
@@ -434,35 +523,70 @@ func (rv *reservations) published(ctx context.Context, o versions.Outcome, inPro
|
||||
}
|
||||
}
|
||||
|
||||
// sayPublished says the seat mesh-builds' package-published of an artifact a published marked.
|
||||
func (rv *reservations) sayPublished(ctx context.Context, m versions.Marked, digest string) {
|
||||
// sayPublished says the seat mesh-builds' package-published of an artifact a published marked, and answers why it could not; the
|
||||
// log says both.
|
||||
func (rv *reservations) sayPublished(ctx context.Context, m versions.Marked, digest string) error {
|
||||
if rv.say == nil {
|
||||
rv.logf("package-published of %s at %s not said: no seat to say it on", m.Artifact, m.Reserved.Version)
|
||||
return
|
||||
return errors.New("no seat to say it on")
|
||||
}
|
||||
if err := rv.say(ctx, m.PackagePublished(digest, time.Now())); err != nil {
|
||||
rv.logf("the package-published of %s at %s is not said: %v", m.Artifact, m.Reserved.Version, err)
|
||||
} else {
|
||||
rv.logf("package-published said: %s at %s, digest %s", m.Artifact, m.Reserved.Version, digest)
|
||||
return err
|
||||
}
|
||||
rv.logf("package-published said: %s at %s, digest %s", m.Artifact, m.Reserved.Version, digest)
|
||||
return nil
|
||||
}
|
||||
|
||||
// dropped is builder_reserved_drop: the reservation is deleted and its bound ended.
|
||||
func (rv *reservations) dropped(ctx context.Context, module, series, by, why string, at time.Time) (string, error) {
|
||||
cur, held, _ := rv.r.At(ctx, versions.ReservedKey(module, series))
|
||||
// dropped is builder_reserved_drop (design 47 H2 H-A-592): it names its version, and the reservation of the series is deleted whole
|
||||
// only when it stands at that version and its fingerprint is not building; the publish item and the version-unreleased go with it,
|
||||
// the bound ends, and the answer names what was forgotten.
|
||||
func (rv *reservations) dropped(ctx context.Context, module, series, version, by, why string, at time.Time) (string, error) {
|
||||
cur, held, err := rv.r.At(ctx, versions.ReservedKey(module, series))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !held {
|
||||
return "", fmt.Errorf("%s holds no reservation of %s", module, series)
|
||||
}
|
||||
if cur.Version != version {
|
||||
return "", fmt.Errorf("%s's reservation of %s stands at %s, not %s: a reservation a newer build took is never dropped", module, series, cur.Version, version)
|
||||
}
|
||||
if rv.looking != nil && rv.looking(module, cur.Fingerprint) {
|
||||
return "", fmt.Errorf("the build of %s at %s, which holds %s, is building: drop it when that build ends or its ask is dropped (builder_stuck reads it)", module, cur.Fingerprint, version)
|
||||
}
|
||||
atRegistries := "the registries' record was not read"
|
||||
if rv.judge != nil {
|
||||
if j, jerr := rv.judge(ctx, cur); jerr == nil {
|
||||
var names []string
|
||||
for _, h := range append(append([]versions.HeldArtifact{}, j.Held...), j.Elsewhere...) {
|
||||
names = append(names, h.Seat+" "+h.Name)
|
||||
}
|
||||
atRegistries = "the registries keep " + strings.Join(names, ", ") + " at it, a gap the next reserve skips"
|
||||
if len(names) == 0 {
|
||||
atRegistries = "no registry holds an artifact at it"
|
||||
}
|
||||
}
|
||||
}
|
||||
ok, err := rv.r.Drop(ctx, module, series)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ok && held && rv.itemEnded != nil {
|
||||
rv.itemEnded(ctx, module, cur.Version) // its publish item goes with its reservation (A-456b), its items terminated (§793)
|
||||
}
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%s holds no reservation of %s", module, series)
|
||||
}
|
||||
if rv.itemEnded != nil {
|
||||
rv.itemEnded(ctx, module, cur.Version) // its publish item goes with its reservation (A-456b), its items terminated (§793)
|
||||
}
|
||||
rv.dropBound(ctx, versions.ReservedKey(module, series))
|
||||
rv.found.clear(ctx, versions.VersionUnreleased, meshconditionsclient.ScopeModule, module)
|
||||
return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s)", module, series, by, why), nil
|
||||
withdrawn := make([]string, 0, len(cur.Withdrawn))
|
||||
for v := range cur.Withdrawn {
|
||||
withdrawn = append(withdrawn, v)
|
||||
}
|
||||
sort.Strings(withdrawn)
|
||||
return fmt.Sprintf("the reservation of %s %s is dropped (%s, %s): forgot version %s of fingerprint %s, %d recorded digests, withdrawn numbers %v and its publish item and version-unreleased; %s",
|
||||
module, series, by, why, cur.Version, cur.Fingerprint, len(cur.Artifacts), withdrawn, atRegistries), nil
|
||||
}
|
||||
|
||||
// noMark says why a published marked nothing, from the reservations the published read (design 47 H H-A-280: no second read):
|
||||
@@ -490,35 +614,49 @@ func (rv *reservations) noMark(ctx context.Context, o versions.Outcome, read []v
|
||||
return strings.Join(out, "; ") + " (" + standing + "; a published heard before the build recorded its digests is kept until it does)"
|
||||
}
|
||||
|
||||
// reserveDoneAct is builder_reserve_done's act (design 47 G A-455): the next version of the series is reserved for a done trunk build
|
||||
// that reserved none, and its publish is queued as builder_publish_again queues it. Its answer says the version and the queued
|
||||
// publishes; a reservation whose publish could not be queued is said so, with the tool that queues it.
|
||||
func reserveDoneAct(reserve func(ctx context.Context, module, fp string) (versions.ReservedVersion, error),
|
||||
republish func(ctx context.Context, module, version string) ([]string, error), logf func(string, ...any)) func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) {
|
||||
return func(ctx context.Context, module, fp, by, why string, at time.Time) (string, error) {
|
||||
res, err := reserve(ctx, module, fp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
logf("%s at %s: version %s is reserved by hand (%s, %s) for the done build", module, fp, res.Version, by, why)
|
||||
queued, err := republish(ctx, module, res.Version)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s is reserved for %s at %s, but its publish is not queued (builder_publish_again queues it): %w", res.Version, module, fp, err)
|
||||
}
|
||||
return fmt.Sprintf("reserved %s for %s at %s and queued %d versions to publish: %s; builder_publish_queue shows them", res.Version, module, fp, len(queued), strings.Join(queued, ", ")), nil
|
||||
}
|
||||
}
|
||||
|
||||
// ReleasedFor says whether a version was released for the build of fingerprint (design 47 G A-456a).
|
||||
func (rv *reservations) ReleasedFor(ctx context.Context, module, fingerprint string) (bool, error) {
|
||||
return rv.r.ReleasedFor(ctx, module, fingerprint)
|
||||
}
|
||||
|
||||
// MarkRegistryHeld reads the registries' record of v's artifacts and writes the held digest of each artifact a registry holds at v's version
|
||||
// for the build's fingerprint on the reservation, marked published, and says package-published of each once (design 47 H2 H-A-588
|
||||
// (4)); what the registries do not hold loses its recorded digest (H-A-664). A read that does not answer is said and nothing is
|
||||
// written, so the build goes on.
|
||||
func (rv *reservations) MarkRegistryHeld(ctx context.Context, v versions.ReservedVersion) {
|
||||
if rv.judge == nil {
|
||||
return
|
||||
}
|
||||
j, err := rv.judge(ctx, v)
|
||||
if err != nil {
|
||||
rv.logf("%s %s: the registries' record of its artifacts is not read before the build module is asked again, so none is marked held: %v", v.Module, v.Version, err)
|
||||
return
|
||||
}
|
||||
marked, _, err := rv.r.MarkHeld(ctx, v.Module, v.Version, j.Held)
|
||||
if err != nil {
|
||||
rv.logf("%s %s: what the registries hold is not written on the reservation: %v", v.Module, v.Version, err)
|
||||
return
|
||||
}
|
||||
for _, m := range marked {
|
||||
var held versions.HeldArtifact
|
||||
for _, h := range j.Held {
|
||||
if h.Ref == m.Artifact {
|
||||
held = h
|
||||
}
|
||||
}
|
||||
rv.logf("%s %s: %s holds %s %s at %s for this build: marked published from its record before the build is asked again", v.Module, v.Version, held.Seat, held.Name, held.Version, held.Digest)
|
||||
rv.sayPublished(ctx, m, held.Digest)
|
||||
}
|
||||
}
|
||||
|
||||
// markHeld marks the artifacts the registries' record holds at their version with the built digest published, as their published
|
||||
// heard would, and says package-published of each (design 47 H H-A-274): a published heard and lost never leaves the publish
|
||||
// asked for ever. The version's release follows from the catalog as for any published.
|
||||
func (rv *reservations) markHeld(ctx context.Context, v versions.ReservedVersion, held []versions.HeldArtifact) {
|
||||
for _, h := range held {
|
||||
if v.Published[h.Ref] {
|
||||
continue // marked already: its package-published was said (design 47 H2 H-A-588 (4): once)
|
||||
}
|
||||
rv.logf("%s %s: %s holds %s %s with the built digest %s: marked published from its record", v.Module, v.Version, h.Seat, h.Name, h.Version, h.Digest)
|
||||
rv.published(ctx, versions.Outcome{Name: h.Name, Version: h.Version, Digest: h.Digest, Holder: h.Seat}, nil)
|
||||
}
|
||||
@@ -551,11 +689,40 @@ func (rv *reservations) movedElsewhere(ctx context.Context, v versions.ReservedV
|
||||
}
|
||||
return err
|
||||
}
|
||||
var at []string
|
||||
for _, h := range j.Elsewhere {
|
||||
at = append(at, fmt.Sprintf("%s holds %s %s at %s, built %s", h.Seat, h.Name, h.Version, h.Digest, v.Artifacts[h.Ref]))
|
||||
}
|
||||
why := fmt.Sprintf("%s is withdrawn and the build of %s is built again at the next free number: %s", v.Version, v.Fingerprint, strings.Join(at, "; "))
|
||||
why := elsewhereWords(v, j.Elsewhere)
|
||||
rv.heldElsewhere(ctx, v.Module, why)
|
||||
return rv.rebuild(ctx, v.Module, v.Fingerprint, why)
|
||||
}
|
||||
|
||||
// elsewhereWords says what withdrew v's number: each artifact a registry holds there for another build, with the seat, both digests and
|
||||
// the fingerprint the registry keeps for it when one is kept (design 47 H2 H-A-590 (1), H-A-279).
|
||||
func elsewhereWords(v versions.ReservedVersion, elsewhere []versions.HeldArtifact) string {
|
||||
var at []string
|
||||
for _, h := range elsewhere {
|
||||
w := fmt.Sprintf("%s holds %s %s at %s, built %s", h.Seat, h.Name, h.Version, h.Digest, v.Artifacts[h.Ref])
|
||||
if h.Fingerprint != "" {
|
||||
w += ", for fingerprint " + h.Fingerprint
|
||||
}
|
||||
at = append(at, w)
|
||||
}
|
||||
return fmt.Sprintf("%s is withdrawn and the build of %s is built again at the next free number: %s", v.Version, v.Fingerprint, strings.Join(at, "; "))
|
||||
}
|
||||
|
||||
// unstoredAgain builds a key again whose reservation's first artifact a holder refused as not stored (design 47 H2 H-A-662): the
|
||||
// build under its standing version completes what the registries lack, as the person's builder_build_again would. A key the
|
||||
// build again refuses (not a first branch's trunk build, or released) is said and left to the person's tool.
|
||||
func (rv *reservations) unstoredAgain(ctx context.Context, v versions.ReservedVersion, ref, words string) {
|
||||
if rv.rebuild == nil {
|
||||
return
|
||||
}
|
||||
why := fmt.Sprintf("%s refused by its holder as not stored (%s): the build of %s is built again under %s", ref, words, v.Fingerprint, v.Version)
|
||||
if err := rv.rebuild(ctx, v.Module, v.Fingerprint, why); err != nil {
|
||||
rv.logf("%s %s: the build again is not started: %v; builder_build_again builds it", v.Module, v.Version, err)
|
||||
}
|
||||
}
|
||||
|
||||
// movedFrom is told by the reserver a standing number it withdrew at a build again (design 47 H2 H-A-590 (1)): the finding is raised;
|
||||
// the reserve itself takes the next number no registry holds.
|
||||
func (rv *reservations) movedFrom(ctx context.Context, v versions.ReservedVersion, elsewhere []versions.HeldArtifact) {
|
||||
rv.heldElsewhere(ctx, v.Module, elsewhereWords(v, elsewhere))
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
|
||||
"slices"
|
||||
@@ -14,9 +15,11 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
@@ -24,8 +27,9 @@ import (
|
||||
|
||||
// memReserve is the state reserved in memory.
|
||||
type memReserve struct {
|
||||
vals map[string][]byte
|
||||
revs map[string]uint64
|
||||
vals map[string][]byte
|
||||
revs map[string]uint64
|
||||
lists int // how often its keys were listed
|
||||
}
|
||||
|
||||
func (m *memReserve) Get(_ context.Context, key string) ([]byte, uint64, bool, error) {
|
||||
@@ -47,6 +51,7 @@ func (m *memReserve) Update(_ context.Context, key string, v []byte, rev uint64)
|
||||
return rev + 1, nil
|
||||
}
|
||||
func (m *memReserve) KeysOf(_ context.Context, filter string) ([]string, error) {
|
||||
m.lists++
|
||||
var out []string
|
||||
for k := range m.vals {
|
||||
if versions.FilterMatches(filter, k) { // as the bus reads a filter
|
||||
@@ -60,14 +65,18 @@ func (m *memReserve) Delete(_ context.Context, key string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// boundsKV keeps the keys created and deleted in the state bounds.
|
||||
// boundsKV keeps the keys created and deleted in the state bounds, and with vals each created key's value.
|
||||
type boundsKV struct {
|
||||
jetstream.KeyValue
|
||||
keys map[string]bool
|
||||
vals map[string][]byte
|
||||
}
|
||||
|
||||
func (b *boundsKV) Create(_ context.Context, key string, _ []byte, _ ...jetstream.KVCreateOpt) (uint64, error) {
|
||||
func (b *boundsKV) Create(_ context.Context, key string, v []byte, _ ...jetstream.KVCreateOpt) (uint64, error) {
|
||||
b.keys[key] = true
|
||||
if b.vals != nil {
|
||||
b.vals[key] = v
|
||||
}
|
||||
return 1, nil
|
||||
}
|
||||
func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDeleteOpt) error {
|
||||
@@ -75,33 +84,23 @@ func (b *boundsKV) Delete(_ context.Context, key string, _ ...jetstream.KVDelete
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestTheCatalogsWordsMoveTheReservations: design 47 G §369, §372 (test 102) — versions-filled opens the reserving and wakes
|
||||
// the builds that wait; a built reservation arms its bound and its end raises version-unreleased naming the artifacts
|
||||
// TestTheCatalogsWordsMoveTheReservations: design 47 G §369 (test 102) — a built reservation arms its bound and its end raises version-unreleased naming the artifacts
|
||||
// missing; the catalog's version-released deletes the key and the bound and clears the finding; builder_reserved_drop drops one.
|
||||
func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := &memFindings{vals: map[string][]byte{}}
|
||||
found := &findings{module: builds.BuilderModule, w: st, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
|
||||
bounds := &boundsKV{keys: map[string]bool{}}
|
||||
woke := 0
|
||||
call := func(addr string, body any) (json.RawMessage, error) {
|
||||
if addr != "seat:mesh-catalog.versions" {
|
||||
t.Errorf("the released versions were asked of %q", addr)
|
||||
}
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m", Versions: []meshcatalog.VersionEntry{{Module: "m", Version: "1.4.2"}}})
|
||||
}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found,
|
||||
func(context.Context) { woke++ }, t.Logf)
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, t.Logf)
|
||||
var items []string // design 47 G A-457a: the end of a build asks its publish, the release ends it
|
||||
rv.built = func(_ context.Context, m, v string) error { items = append(items, "asked "+m+" "+v); return nil }
|
||||
rv.released = func(_ context.Context, m, v string) { items = append(items, "ended "+m+" "+v) }
|
||||
if _, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}); err == nil || rv.Filled() {
|
||||
t.Fatalf("a version was reserved before versions-filled (%v)", err)
|
||||
}
|
||||
filled := &wakeMsg{subject: meshcatalog.SubjectVersionsFilled, data: []byte(`{"v":1}`)}
|
||||
if !rv.heard(ctx, filled) || !filled.acked || !rv.Filled() || woke != 1 {
|
||||
t.Fatalf("versions-filled: acked %v, filled %v, woke %d", filled.acked, rv.Filled(), woke)
|
||||
}
|
||||
var said []meshbuilds.PackagePublished
|
||||
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
|
||||
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
|
||||
@@ -145,13 +144,14 @@ func TestTheCatalogsWordsMoveTheReservations(t *testing.T) {
|
||||
if all, _ := rv.r.All(ctx); len(all) != 0 || bounds.keys[boundKey] || len(st.vals) != 0 {
|
||||
t.Errorf("after version-released: reservations %v, bounds %v, findings %v; want none", all, bounds.keys, st.vals)
|
||||
}
|
||||
if _, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{}); err != nil {
|
||||
again, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a"}, versions.Source{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if answer, err := rv.dropped(ctx, "m", "1.4", "op", "never released", time.Unix(0, 0)); err != nil || !strings.Contains(answer, "dropped") {
|
||||
if answer, err := rv.dropped(ctx, "m", "1.4", again.Version, "op", "never released", time.Unix(0, 0)); err != nil || !strings.Contains(answer, "dropped") {
|
||||
t.Errorf("builder_reserved_drop: %q (%v)", answer, err)
|
||||
}
|
||||
if _, err := rv.dropped(ctx, "m", "1.4", "op", "again", time.Unix(0, 0)); err == nil {
|
||||
if _, err := rv.dropped(ctx, "m", "1.4", again.Version, "op", "again", time.Unix(0, 0)); err == nil {
|
||||
t.Error("a reservation that is gone was dropped again")
|
||||
}
|
||||
}
|
||||
@@ -177,8 +177,7 @@ func TestAReleasedVersionWritesNoTag(t *testing.T) {
|
||||
fw := &memFindings{vals: map[string][]byte{}}
|
||||
found := &findings{module: builds.BuilderModule, w: fw, logf: t.Logf, now: func() time.Time { return time.Unix(0, 0) }}
|
||||
store := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
rv := newReservations(store, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, nil, t.Logf)
|
||||
rv.filled.Store(true)
|
||||
rv := newReservations(store, call, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} }, found, t.Logf)
|
||||
rv.names = func(_ context.Context, _, artifact string) (string, bool, error) {
|
||||
return "git.example/o/r/go", artifact == "lib", nil
|
||||
}
|
||||
@@ -213,6 +212,21 @@ func TestAReleasedVersionWritesNoTag(t *testing.T) {
|
||||
if all, _ := rv.r.All(ctx); len(all) != 0 {
|
||||
t.Fatalf("the released version still stands: %v", all)
|
||||
}
|
||||
// Design 47 H2 H-A-514 addendum: a version-released of a version no reservation holds is acknowledged at once from its
|
||||
// series' one key, the module's keys never listed.
|
||||
if _, err := rv.Reserve(ctx, "late", "0.2", []string{"late:bin"}, versions.Source{Repository: "o/l", Commit: "c1", Fingerprint: "fpL"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.lists = 0
|
||||
if m := release("late", "0.2.7"); !m.acked || m.naked || store.lists != 0 {
|
||||
t.Fatalf("a release no reservation holds: acked %v naked %v, the keys listed %d times; want it acknowledged with none", m.acked, m.naked, store.lists)
|
||||
}
|
||||
if _, standing, _ := rv.r.Of(ctx, "late", "0.2.0"); !standing {
|
||||
t.Fatal("a release of another version took the standing reservation late 0.2.0")
|
||||
}
|
||||
if _, err := rv.r.Drop(ctx, "late", "0.2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The start check (H-A-484 c): a built reservation the catalog holds released is released at the start, no tag written; one
|
||||
// not built, or not released, stands.
|
||||
// Design 47 H2 H-A-492: at the start, a standing reservation with no digests recorded whose build key is done has them
|
||||
@@ -223,7 +237,7 @@ func TestAReleasedVersionWritesNoTag(t *testing.T) {
|
||||
var recordedAt []string
|
||||
rv.recordAgain = func(ctx context.Context, module, fp, when string) (string, error) {
|
||||
recordedAt = append(recordedAt, module+" "+fp+" "+when)
|
||||
_, err := rv.r.Built(ctx, module, "0.1.0", "rec:bin", "sha256:bb", nil) // its done key's digest
|
||||
_, _, err := rv.r.Built(ctx, module, "0.1.0", map[string]string{"rec:bin": "sha256:bb"}, nil) // its done key's digest
|
||||
return "0.1.0", err
|
||||
}
|
||||
catalog = []meshcatalog.VersionEntry{{Module: "rec", Version: "0.1.0"}}
|
||||
@@ -242,7 +256,7 @@ func TestAReleasedVersionWritesNoTag(t *testing.T) {
|
||||
if all, _ := rv.r.All(ctx); len(all) != 1 {
|
||||
t.Fatalf("at the start with no build done: reservations %v; want the reservation standing", all)
|
||||
}
|
||||
if _, err := rv.r.Built(ctx, "pkg", "0.1.0", "pkg:lib", "sha256:aa", nil); err != nil {
|
||||
if _, _, err := rv.r.Built(ctx, "pkg", "0.1.0", map[string]string{"pkg:lib": "sha256:aa"}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rv.releasedAtStart(ctx) // the catalog holds none released: it stands
|
||||
@@ -302,10 +316,9 @@ func TestAPublishedHeardBeforeTheDigestsIsSaidWhenTheBuildRecordsThem(t *testing
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
|
||||
}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
|
||||
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, logf)
|
||||
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, logf)
|
||||
var said []meshbuilds.PackagePublished
|
||||
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
|
||||
rv.filled.Store(true)
|
||||
res, err := rv.Reserve(ctx, "m", "1.4", []string{"m:a", "m:b"}, versions.Source{Branch: "main", Revision: 41})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -339,6 +352,297 @@ func TestAPublishedHeardBeforeTheDigestsIsSaidWhenTheBuildRecordsThem(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
// TestABuildsDigestsAreRecordedInOneWrite: issue 1984 note 8, 1984/AC4 — recording a build's digests is one compare-and-set of
|
||||
// its reservation and one reindex for all its artifacts (39 here, as mesh-delivery-contracts 0.1.108 had); a record tried again
|
||||
// after one that timed out writes only what that one left (an artifact recorded already is skipped), and nothing when every
|
||||
// digest stands recorded.
|
||||
func TestABuildsDigestsAreRecordedInOneWrite(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &countedReserve{memReserve: &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, writes: map[string]int{}}
|
||||
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
|
||||
rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
|
||||
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
var asked []string
|
||||
rv.built = func(_ context.Context, m, v string) error { asked = append(asked, m+" "+v); return nil }
|
||||
refsOf := func(module string) ([]string, map[string]string) {
|
||||
var refs []string
|
||||
digests := map[string]string{}
|
||||
for i := range 39 {
|
||||
ref := fmt.Sprintf("%s:a%02d", module, i)
|
||||
refs, digests[ref] = append(refs, ref), fmt.Sprintf("sha256:%s%02d", module, i)
|
||||
}
|
||||
return refs, digests
|
||||
}
|
||||
built := func(module string) versions.ReservedVersion {
|
||||
t.Helper()
|
||||
v, found, err := rv.r.Of(ctx, module, "")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("%s: no reservation (%v)", module, err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
refs, digests := refsOf("c")
|
||||
res, err := rv.Reserve(ctx, "c", "0.1", refs, versions.Source{Fingerprint: "fpC"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := versions.ReservedKey("c", "0.1")
|
||||
clear(store.writes)
|
||||
store.indexReads = 0
|
||||
if err := rv.Built(ctx, "c", res.Version, digests, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// One reindex reads each index key the built reservation stands under (its version and its 39 digests) and the one it leaves
|
||||
// (its version's unbuilt): 41 reads, never one reindex per artifact.
|
||||
if w, r := store.writes[key], store.indexReads; w != 1 || r > 41 {
|
||||
t.Errorf("39 digests recorded with %d writes of %s and %d reads of the index, want one write and one reindex (at most 41 reads) (1984/AC4)", w, key, r)
|
||||
}
|
||||
if v := built("c"); v.BuiltAt.IsZero() || len(v.Missing()) != 39 || !slices.Equal(asked, []string{"c " + res.Version}) {
|
||||
t.Errorf("after the record: built at %v, %d unpublished, publish items asked %v; want the build ended, 39 awaited and its item asked once", v.BuiltAt, len(v.Missing()), asked)
|
||||
}
|
||||
|
||||
// A record that timed out left 30 of 39 digests written and the build not ended (the form the record of one artifact at a
|
||||
// time wrote): the record tried again writes the reservation once, skipping the 30.
|
||||
refs, digests = refsOf("d")
|
||||
res, err = rv.Reserve(ctx, "d", "0.1", refs, versions.Source{Fingerprint: "fpD"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key = versions.ReservedKey("d", "0.1")
|
||||
left := res
|
||||
left.Artifacts = map[string]string{}
|
||||
for i, ref := range refs {
|
||||
left.Artifacts[ref] = map[bool]string{true: digests[ref], false: ""}[i < 30]
|
||||
}
|
||||
store.vals[key], _ = json.Marshal(left)
|
||||
clear(store.writes)
|
||||
if err := rv.Built(ctx, "d", res.Version, digests, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := store.writes[key]; w != 1 || built("d").BuiltAt.IsZero() {
|
||||
t.Errorf("the record tried again wrote %s %d times (built at %v), want once, the 30 recorded skipped (1984/AC4)", key, w, built("d").BuiltAt)
|
||||
}
|
||||
// Tried again once more, every digest recorded: nothing is written.
|
||||
clear(store.writes)
|
||||
if err := rv.Built(ctx, "d", res.Version, digests, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := store.writes[key]; w != 0 {
|
||||
t.Errorf("a record of digests all recorded wrote %s %d times, want none (1984/AC4)", key, w)
|
||||
}
|
||||
}
|
||||
|
||||
// TestABuiltReservationIsTakenInFromItsState: issue 1984 note 8, 1984/AC5 — what follows a build's record follows the
|
||||
// reservation's state, not whether the record before ended: at a look (the builder's RecordAgain hands a recorded reservation to
|
||||
// Built with its digests) and at the start, a built reservation with published kept on it takes them in, says package-published
|
||||
// and arms its bound, counted from its build's end; one left unmarked past its bound raises version-unreleased, its bound not
|
||||
// armed again, and one whose kept published mark every artifact raises nothing. A version-unreleased standing with a holder's
|
||||
// words keeps them past the bound and at the bound's end.
|
||||
func TestABuiltReservationIsTakenInFromItsState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}
|
||||
// The catalog's verb versions holds held released, or fails with versionsErr (design 47 H2 H-A-773 (2), (5)).
|
||||
var held []string
|
||||
var versionsErr error
|
||||
catalog := func(string, any) (json.RawMessage, error) {
|
||||
if versionsErr != nil {
|
||||
return nil, versionsErr
|
||||
}
|
||||
a := meshcatalog.VersionsAnswer{}
|
||||
for _, v := range held {
|
||||
a.Versions = append(a.Versions, meshcatalog.VersionEntry{Version: v})
|
||||
}
|
||||
return json.Marshal(a)
|
||||
}
|
||||
fs := &memFindings{vals: map[string][]byte{}}
|
||||
bounds := &boundsKV{keys: map[string]bool{}, vals: map[string][]byte{}}
|
||||
rv := newReservations(store, catalog, func() jetstream.KeyValue { return bounds },
|
||||
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
var said []string
|
||||
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error {
|
||||
said = append(said, p.Artifact+"@"+p.Version+" "+p.Digest)
|
||||
return nil
|
||||
}
|
||||
var asked []string
|
||||
rv.built = func(_ context.Context, m, v string) error { asked = append(asked, m+" "+v); return nil }
|
||||
now := time.Now().UTC()
|
||||
// recordedLost is module's reservation as a record whose end was lost leaves it: the published of the artifacts heard (a, b)
|
||||
// heard before the digests kept on it, every digest recorded and the build ended at builtAt, and nothing after (no bound, the
|
||||
// kept published not taken in).
|
||||
recordedLost := func(module string, builtAt time.Time, heard ...string) versions.ReservedVersion {
|
||||
t.Helper()
|
||||
res, err := rv.Reserve(ctx, module, "0.1", []string{module + ":a", module + ":b"}, versions.Source{Fingerprint: "fp" + module, Branch: "main", Revision: 41})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, a := range heard {
|
||||
rv.published(ctx, versions.Outcome{Name: module + "-" + a, Version: res.Version, Digest: "sha256:" + module + a}, nil)
|
||||
}
|
||||
v, _, _ := rv.r.Of(ctx, module, res.Version)
|
||||
if len(v.Kept) != len(heard) {
|
||||
t.Fatalf("%s: kept %v, want the published heard before the digests kept", module, v.Kept)
|
||||
}
|
||||
v.Artifacts = map[string]string{module + ":a": "sha256:" + module + "a", module + ":b": "sha256:" + module + "b"}
|
||||
v.BuiltAt = builtAt
|
||||
key := versions.ReservedKey(module, "0.1")
|
||||
store.vals[key], _ = json.Marshal(v)
|
||||
return v
|
||||
}
|
||||
unreleased := func(module string) string {
|
||||
return string(fs.vals[meshconditionsclient.Key(meshconditionsclient.ScopeModule, module, versions.VersionUnreleased)])
|
||||
}
|
||||
boundEnds := func(module string) time.Time {
|
||||
var b versions.Bound
|
||||
_ = json.Unmarshal(bounds.vals[versions.ReservedBoundKey(module, "0.1")], &b)
|
||||
return b.Ends
|
||||
}
|
||||
|
||||
t.Run("at a look", func(t *testing.T) {
|
||||
v := recordedLost("look", now.Add(-5*time.Minute), "a")
|
||||
said, asked = nil, nil
|
||||
if err := rv.Built(ctx, "look", v.Version, v.Artifacts, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Its publish item is asked as the build's end asks it: it stands until its release (design 47 G A-456b).
|
||||
if !slices.Equal(said, []string{"look:a@" + v.Version + " sha256:looka"}) || !slices.Equal(asked, []string{"look " + v.Version}) {
|
||||
t.Errorf("at a look: said %v, publish items asked %v; want look:a's package-published said and its item asked", said, asked)
|
||||
}
|
||||
if ends := boundEnds("look"); !ends.Equal(v.BuiltAt.Add(defaultPublishAckMinutes * time.Minute)) {
|
||||
t.Errorf("the bound armed at a look ends %v, want %v: counted from the build's end", ends, v.BuiltAt.Add(defaultPublishAckMinutes*time.Minute))
|
||||
}
|
||||
if cur, _, _ := rv.r.Of(ctx, "look", v.Version); len(cur.Kept) != 0 || !cur.Published["look:a"] {
|
||||
t.Errorf("after the look: kept %v, published %v; want the kept published taken in", cur.Kept, cur.Published)
|
||||
}
|
||||
})
|
||||
t.Run("at a look with publish-ack-minutes at 30", func(t *testing.T) {
|
||||
rv.setBound(30 * time.Minute)
|
||||
defer rv.setBound(defaultPublishAckMinutes * time.Minute)
|
||||
v := recordedLost("thirty", now.Add(-5*time.Minute), "a")
|
||||
if err := rv.Built(ctx, "thirty", v.Version, v.Artifacts, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ends := boundEnds("thirty"); !ends.Equal(v.BuiltAt.Add(30 * time.Minute)) {
|
||||
t.Errorf("the bound armed ends %v, want %v: the setting's 30 minutes, not 10", ends, v.BuiltAt.Add(30*time.Minute))
|
||||
}
|
||||
if unreleased("thirty") != "" {
|
||||
t.Errorf("a build 5 minutes old raised %s with the bound at 30 minutes", unreleased("thirty"))
|
||||
}
|
||||
})
|
||||
t.Run("at the start", func(t *testing.T) {
|
||||
v := recordedLost("start", now.Add(-time.Minute), "a")
|
||||
said = nil
|
||||
rv.releasedAtStart(ctx)
|
||||
if !slices.Contains(said, "start:a@"+v.Version+" sha256:starta") || !bounds.keys[versions.ReservedBoundKey("start", "0.1")] {
|
||||
t.Errorf("at the start: said %v, bounds %v; want start:a's package-published said and its bound armed", said, bounds.keys)
|
||||
}
|
||||
if unreleased("start") != "" {
|
||||
t.Errorf("a built reservation within its bound raised %s", unreleased("start"))
|
||||
}
|
||||
})
|
||||
t.Run("past its bound", func(t *testing.T) {
|
||||
for _, when := range []string{"a look", "the start"} {
|
||||
module := map[string]string{"a look": "pastlook", "the start": "paststart"}[when]
|
||||
v := recordedLost(module, now.Add(-defaultPublishAckMinutes*time.Minute-time.Minute), "a")
|
||||
takeIn := func() {
|
||||
if when == "a look" {
|
||||
if err := rv.Built(ctx, module, v.Version, v.Artifacts, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
rv.releasedAtStart(ctx)
|
||||
}
|
||||
}
|
||||
takeIn()
|
||||
if got := unreleased(module); !strings.Contains(got, module+":b unpublished") || !strings.Contains(got, v.Version) {
|
||||
t.Errorf("at %s, a built reservation left unmarked past its bound raised %q, want version-unreleased naming %s:b of %s", when, got, module, v.Version)
|
||||
}
|
||||
if bounds.keys[versions.ReservedBoundKey(module, "0.1")] {
|
||||
t.Errorf("at %s, the bound of a reservation past it was armed again", when)
|
||||
}
|
||||
// One standing is left as it was raised: the next take-in does not write it again over the holder's words (ADR 0674 §3).
|
||||
rv.unreleasedWords(ctx, v, "the holder refused the publish again: no space left")
|
||||
takeIn()
|
||||
if got := unreleased(module); !strings.Contains(got, "no space left") || strings.Contains(got, "nothing within") {
|
||||
t.Errorf("at %s again, version-unreleased reads %q, want the holder's words it was left with", when, got)
|
||||
}
|
||||
|
||||
// Note 8's own case: every artifact's published kept on it is taken in before its bound is judged, so nothing is
|
||||
// unpublished; each is said as package-published. The catalog holds no release of it past its bound, so it is
|
||||
// version-unreleased, its release lost, and its version-released clears it (design 47 H2 H-A-773 (2), (7)).
|
||||
module = map[string]string{"a look": "keptlook", "the start": "keptstart"}[when]
|
||||
v = recordedLost(module, now.Add(-defaultPublishAckMinutes*time.Minute-time.Minute), "a", "b")
|
||||
said = nil
|
||||
takeIn()
|
||||
if got := unreleased(module); !strings.Contains(got, "every artifact is published") || !strings.Contains(got, "its release was lost") || strings.Contains(got, "unpublished") {
|
||||
t.Errorf("at %s, a reservation past its bound whose kept published mark every artifact raised %q, want version-unreleased saying its release was lost", when, got)
|
||||
}
|
||||
if !slices.Contains(said, module+":a@"+v.Version+" sha256:"+module+"a") || !slices.Contains(said, module+":b@"+v.Version+" sha256:"+module+"b") {
|
||||
t.Errorf("at %s, said %v, want package-published of %s:a and %s:b", when, said, module, module)
|
||||
}
|
||||
if bounds.keys[versions.ReservedBoundKey(module, "0.1")] {
|
||||
t.Errorf("at %s, the bound of a reservation past it was armed", when)
|
||||
}
|
||||
if err := rv.release(ctx, meshcatalog.VersionReleasedEvent{Module: module, Version: v.Version}); err != nil || unreleased(module) != "" {
|
||||
t.Errorf("at %s, its version-released (%v) left %q, want version-unreleased cleared", when, err, unreleased(module))
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("its bound ending", func(t *testing.T) {
|
||||
v := recordedLost("ends", now.Add(-time.Minute), "a")
|
||||
if err := rv.Built(ctx, "ends", v.Version, v.Artifacts, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
boundKey := versions.ReservedBoundKey("ends", "0.1")
|
||||
// The holder refused a publish again within the bound (ADR 0674 §3): the bound's end keeps those words.
|
||||
rv.unreleasedWords(ctx, v, "the holder refused the publish again: no space left")
|
||||
if !rv.ended(ctx, purged{key: boundKey}) {
|
||||
t.Fatal("the reservation's bound was not taken in")
|
||||
}
|
||||
if got := unreleased("ends"); !strings.Contains(got, "no space left") || strings.Contains(got, "nothing within") {
|
||||
t.Errorf("at the bound's end, version-unreleased reads %q, want the holder's words it was left with", got)
|
||||
}
|
||||
// With none standing, the bound's end raises it, naming the artifact unpublished.
|
||||
_ = fs.Clear(ctx, meshconditionsclient.ScopeModule, "ends", versions.VersionUnreleased, "")
|
||||
rv.ended(ctx, purged{key: boundKey})
|
||||
if got := unreleased("ends"); !strings.Contains(got, "ends:b unpublished") || !strings.Contains(got, "nothing within") {
|
||||
t.Errorf("at the bound's end with none standing, version-unreleased reads %q, want nothing within naming ends:b", got)
|
||||
}
|
||||
// One whose every artifact is published is not left unmarked (1984/AC5). Its bound's end asks the catalog's verb versions
|
||||
// (design 47 H2 H-A-773 (2), (5), (6)): one the catalog holds released raises nothing; one it holds no release of is
|
||||
// version-unreleased, its release lost; one whose versions cannot be read is raised too, saying so.
|
||||
all := recordedLost("endsall", now.Add(-time.Minute), "a", "b")
|
||||
if err := rv.Built(ctx, "endsall", all.Version, all.Artifacts, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cur, _, _ := rv.r.Of(ctx, "endsall", all.Version); len(cur.Missing()) != 0 {
|
||||
t.Fatalf("endsall: %v unpublished after the take-in, want every artifact published", cur.Missing())
|
||||
}
|
||||
allKey := versions.ReservedBoundKey("endsall", "0.1")
|
||||
held = []string{all.Version}
|
||||
rv.ended(ctx, purged{key: allKey})
|
||||
if got := unreleased("endsall"); got != "" {
|
||||
t.Errorf("at the bound's end, a published reservation the catalog holds released raised %q, want no version-unreleased", got)
|
||||
}
|
||||
held = nil
|
||||
rv.ended(ctx, purged{key: allKey})
|
||||
if got := unreleased("endsall"); !strings.Contains(got, "every artifact is published") || !strings.Contains(got, "its release was lost") ||
|
||||
!strings.Contains(got, all.Version) || !strings.Contains(got, "says a published one's package-published again") {
|
||||
t.Errorf("at the bound's end, a published reservation the catalog holds no release of raised %q, want version-unreleased saying its release was lost", got)
|
||||
}
|
||||
_ = fs.Clear(ctx, meshconditionsclient.ScopeModule, "endsall", versions.VersionUnreleased, "")
|
||||
versionsErr = errors.New("no holder of mesh-catalog answered")
|
||||
rv.ended(ctx, purged{key: allKey})
|
||||
versionsErr = nil
|
||||
if got := unreleased("endsall"); !strings.Contains(got, "the catalog's versions could not be read") || !strings.Contains(got, "no holder of mesh-catalog answered") {
|
||||
t.Errorf("at the bound's end with the catalog's versions unread, version-unreleased reads %q, want it raised saying they could not be read", got)
|
||||
}
|
||||
if cur, found, _ := rv.r.Of(ctx, "endsall", all.Version); !found || cur.BuiltAt.IsZero() {
|
||||
t.Errorf("at the bound's end, the reservation of endsall %s stands no more, want it waiting for its version-released", all.Version)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo: design 47 G A-455 — a build that reserves while the series is
|
||||
// reserved by an older build never released drops the older one's bound and finding and says so in the builder's journal; and
|
||||
// H-A-225 — the older build is withdrawn, so nothing publishes under the dropped number, while a re-run of the newer keeps it.
|
||||
@@ -351,9 +655,7 @@ func TestABuildTakingOverAnOlderReservationDropsItsBoundAndSaysSo(t *testing.T)
|
||||
call := func(string, any) (json.RawMessage, error) {
|
||||
return json.Marshal(meshcatalog.VersionsAnswer{Module: "m"})
|
||||
}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found,
|
||||
nil, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
|
||||
rv.filled.Store(true)
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, call, func() jetstream.KeyValue { return bounds }, found, func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) })
|
||||
var withdrawn []string
|
||||
rv.withdraw = func(module, fp, why string) { withdrawn = append(withdrawn, module+" "+fp+": "+why) }
|
||||
older, err := rv.Reserve(ctx, "m", "0.1", []string{"m:a"}, versions.Source{Fingerprint: "fp-old"})
|
||||
@@ -412,59 +714,61 @@ func (e ansEntry) Revision() uint64 { return 1 }
|
||||
func (e ansEntry) Value() []byte { return e.value }
|
||||
func (e ansEntry) Operation() jetstream.KeyValueOp { return jetstream.KeyValuePut }
|
||||
|
||||
// TestAReserveDoneIsAnsweredWithTheVersionAndItsQueuedPublish: design 47 G A-455 — the reasks value of builder_reserve_done reaches
|
||||
// the act, which reserves for the done build and queues the publish as publish again does, and its answer names both; a
|
||||
// refusal of the reserving queues nothing and is the answer; a publish that cannot be queued says the version is reserved.
|
||||
func TestAReserveDoneIsAnsweredWithTheVersionAndItsQueuedPublish(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
var queued []string
|
||||
var logged []string
|
||||
logf := func(f string, a ...any) { logged = append(logged, fmt.Sprintf(f, a...)) }
|
||||
reserve := func(_ context.Context, module, fp string) (versions.ReservedVersion, error) {
|
||||
if fp == "refused" {
|
||||
return versions.ReservedVersion{}, fmt.Errorf("the build key of %s at %s is not done", module, fp)
|
||||
}
|
||||
return versions.ReservedVersion{Module: module, Version: "0.1.13", Fingerprint: fp}, nil
|
||||
}
|
||||
republish := func(_ context.Context, module, version string) ([]string, error) {
|
||||
if module == "nope" {
|
||||
return nil, fmt.Errorf("the queue is full")
|
||||
}
|
||||
queued = append(queued, module+"@"+version)
|
||||
return []string{module + "@" + version}, nil
|
||||
}
|
||||
acts := versions.Acts{ReserveDone: reserveDoneAct(reserve, republish, logf)}
|
||||
for _, c := range []struct {
|
||||
module, fp, want string
|
||||
refused bool
|
||||
}{
|
||||
{"node-tools", "src2:7df8", "reserved 0.1.13 for node-tools at src2:7df8 and queued 1 versions to publish: node-tools@0.1.13", false},
|
||||
{"node-tools", "refused", "not done", true},
|
||||
{"nope", "src2:1", "0.1.13 is reserved for nope at src2:1, but its publish is not queued", true},
|
||||
} {
|
||||
value, err := json.Marshal(build.ReAsk{V: 1, Why: "w", By: "me", Mode: build.ModeReserveDone, Name: c.module, FP: c.fp})
|
||||
if err != nil {
|
||||
// TestPublishAgainAnswersTheVersionsItSaidAgain: design 47 H2 H-A-773 (1) — builder_publish_again's answer names, beside the
|
||||
// versions it queued, the published versions the catalog holds no release of whose package-published it said again.
|
||||
func TestPublishAgainAnswersTheVersionsItSaidAgain(t *testing.T) {
|
||||
kv := &ansKV{wrote: make(chan []byte, 1)}
|
||||
r := build.ReAsk{V: 1, Why: "its release was lost", By: "op@node", At: time.Now(), Mode: build.ModeRepublish, Module: "watchman"}
|
||||
raw, _ := json.Marshal(r)
|
||||
acts := versions.Acts{Republish: func(context.Context, string, string) ([]string, []string, error) {
|
||||
return nil, []string{"watchman 0.1.170"}, nil
|
||||
}}
|
||||
versionActed(context.Background(), acts, kv, ansEntry{key: "republish.1", value: raw}, r, t.Logf)
|
||||
var got build.ReAsk
|
||||
select {
|
||||
case v := <-kv.wrote:
|
||||
if err := json.Unmarshal(v, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kv := &ansKV{wrote: make(chan []byte, 1)}
|
||||
// reAsked sends a reserve-done to the version acts (b is not asked), and the answer is written back to the key.
|
||||
reAsked(ctx, nil, acts, nil, kv, ansEntry{key: "reserve-done." + c.module, value: value}, logf)
|
||||
var wrote []byte
|
||||
select {
|
||||
case wrote = <-kv.wrote:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("%s at %s: no answer was written to the key", c.module, c.fp)
|
||||
}
|
||||
var got build.ReAsk
|
||||
if err := json.Unmarshal(wrote, &got); err != nil || got.Refused != c.refused || !strings.Contains(got.Answer, c.want) || got.Answered.IsZero() {
|
||||
t.Errorf("%s at %s: written %s (%v), want refused=%v containing %q", c.module, c.fp, wrote, err, c.refused, c.want)
|
||||
}
|
||||
default:
|
||||
t.Fatal("the publish again was not answered")
|
||||
}
|
||||
if !slices.Equal(queued, []string{"node-tools@0.1.13"}) {
|
||||
t.Errorf("queued %v, want only node-tools@0.1.13", queued)
|
||||
if got.Refused || len(got.Queued) != 0 || !strings.Contains(got.Answer, "queued 0 versions") ||
|
||||
!strings.Contains(got.Answer, "said the package-published again of 1 published versions the catalog holds no release of: watchman 0.1.170") {
|
||||
t.Errorf("answered %q (queued %v, refused %v); want the version said again named", got.Answer, got.Queued, got.Refused)
|
||||
}
|
||||
if !slices.ContainsFunc(logged, func(l string) bool { return strings.Contains(l, "0.1.13 is reserved by hand") }) {
|
||||
t.Errorf("the reserving by hand is not said in the log: %q", logged)
|
||||
}
|
||||
|
||||
// noAskKnown is a builder none of whose lanes waits: it records the keys asked again and builds, announces and releases nothing.
|
||||
type noAskKnown struct{ asked []string }
|
||||
|
||||
func (n *noAskKnown) AskAgain(key, _ string) []string { n.asked = append(n.asked, key); return nil }
|
||||
func (n *noAskKnown) BuildAgain(context.Context, string, string, string, string, time.Duration) build.BuildAgainResult {
|
||||
return build.BuildAgainResult{}
|
||||
}
|
||||
func (n *noAskKnown) AnnounceAgain(context.Context, string, string, string, string) build.BuildAgainResult {
|
||||
return build.BuildAgainResult{}
|
||||
}
|
||||
func (n *noAskKnown) Release(context.Context, string, string, string, string) string { return "" }
|
||||
|
||||
// TestAReserveDoneReAskIsNoAskTheBuilderKnows: design 47 H2 H-A-706 (DQ-39), AC-B14b — builder_reserve_done is gone, so a re-ask of its mode
|
||||
// reserve-done is no hand act of a version: it is answered as any ask of a key no lane of the builder waits on, and writes no reservation.
|
||||
func TestAReserveDoneReAskIsNoAskTheBuilderKnows(t *testing.T) {
|
||||
kv := &ansKV{wrote: make(chan []byte, 1)}
|
||||
raw, _ := json.Marshal(build.ReAsk{V: 1, Why: "a test asks it", By: "op@node", At: time.Now(), Mode: "reserve-done", Name: "m", Version: "0.1.0"})
|
||||
b := &noAskKnown{}
|
||||
reAsked(context.Background(), b, versions.Acts{}, nil, kv, ansEntry{key: "m.fp", value: raw}, t.Logf)
|
||||
var got build.ReAsk
|
||||
select {
|
||||
case v := <-kv.wrote:
|
||||
if err := json.Unmarshal(v, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
default:
|
||||
t.Fatal("the re-ask was not answered")
|
||||
}
|
||||
if !strings.Contains(got.Answer, "no ask of this key waits in this builder") || !slices.Equal(b.asked, []string{"m.fp"}) || got.Answered.IsZero() {
|
||||
t.Errorf("a re-ask of mode reserve-done answered %q (asked %v), want it answered as an ask no lane waits on", got.Answer, b.asked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,7 +784,7 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
|
||||
}
|
||||
bounds := &boundsKV{keys: map[string]bool{}}
|
||||
rv := newReservations(&memReserve{vals: map[string][]byte{}, revs: map[string]uint64{}}, none, func() jetstream.KeyValue { return bounds },
|
||||
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, nil, t.Logf)
|
||||
&findings{module: builds.BuilderModule, w: fs, logf: t.Logf, now: time.Now}, t.Logf)
|
||||
var said []meshbuilds.PackagePublished
|
||||
rv.say = func(_ context.Context, p meshbuilds.PackagePublished) error { said = append(said, p); return nil }
|
||||
var asked, ended []string
|
||||
@@ -488,8 +792,13 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
|
||||
rv.released = func(_ context.Context, m, v string) { ended = append(ended, m+" "+v) }
|
||||
rv.itemEnded = rv.released // a build withdrawn or superseded ends its publish item too (§793)
|
||||
registry := []string{"0.1.37"}
|
||||
rv.r.HeldNumbers = func(context.Context, string, string, []string) ([]string, error) { return registry, nil }
|
||||
rv.filled.Store(true)
|
||||
rv.r.HeldRecords = func(context.Context, string, string, []string) ([]versions.HeldArtifact, error) {
|
||||
var out []versions.HeldArtifact
|
||||
for _, v := range registry {
|
||||
out = append(out, versions.HeldArtifact{Version: v})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
res, err := rv.Reserve(ctx, "node-tools", "0.1", []string{"node-tools:program"}, versions.Source{Fingerprint: "fp1"})
|
||||
if err != nil || res.Version != "0.1.0" {
|
||||
t.Fatalf("reserved %q (%v)", res.Version, err)
|
||||
@@ -553,18 +862,34 @@ func TestARegistrysRecordEndsOrMovesAPublish(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// countedReserve counts the reads of reservation keys (two tokens).
|
||||
// countedReserve counts the reads of reservation keys (two tokens) and of the index beside them, and with writes the writes of
|
||||
// each key (issue 1984 note 8).
|
||||
type countedReserve struct {
|
||||
*memReserve
|
||||
reads int
|
||||
reads, indexReads int
|
||||
writes map[string]int
|
||||
}
|
||||
|
||||
func (c *countedReserve) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
|
||||
if !strings.HasPrefix(key, "index.") {
|
||||
c.reads++
|
||||
} else {
|
||||
c.indexReads++
|
||||
}
|
||||
return c.memReserve.Get(ctx, key)
|
||||
}
|
||||
func (c *countedReserve) Create(ctx context.Context, key string, v []byte) (uint64, error) {
|
||||
if c.writes != nil {
|
||||
c.writes[key]++
|
||||
}
|
||||
return c.memReserve.Create(ctx, key, v)
|
||||
}
|
||||
func (c *countedReserve) Update(ctx context.Context, key string, v []byte, rev uint64) (uint64, error) {
|
||||
if c.writes != nil {
|
||||
c.writes[key]++
|
||||
}
|
||||
return c.memReserve.Update(ctx, key, v, rev)
|
||||
}
|
||||
|
||||
// TestAPublishedThatMarksNothingIsSaidFromWhatItRead: design 47 H H-A-280 — a published whose digest no reservation holds, at a
|
||||
// version many reservations share, reads only the unbuilt ones there, each once; its journal line is made from those reads with
|
||||
@@ -575,9 +900,8 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
|
||||
none := func(string, any) (json.RawMessage, error) { return json.Marshal(meshcatalog.VersionsAnswer{}) }
|
||||
var logs []string
|
||||
rv := newReservations(store, none, func() jetstream.KeyValue { return &boundsKV{keys: map[string]bool{}} },
|
||||
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now}, nil,
|
||||
&findings{module: builds.BuilderModule, w: &memFindings{vals: map[string][]byte{}}, logf: t.Logf, now: time.Now},
|
||||
func(f string, a ...any) { logs = append(logs, fmt.Sprintf(f, a...)) })
|
||||
rv.filled.Store(true)
|
||||
for i := range 14 {
|
||||
m := fmt.Sprintf("m%02d", i)
|
||||
res, err := rv.Reserve(ctx, m, "0.1", []string{m + ":a"}, versions.Source{Fingerprint: "fp" + m})
|
||||
@@ -657,10 +981,35 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-683 (1), H-A-737 (1): the builder gives the hub each pattern's key: a registry seat's outcome by its name,
|
||||
// version-released by its module, the seat node-engine's running and manifest-reads-changed by the node their subject names;
|
||||
// the hub holds one key's events in order and the keys side by side (mesh-sdk's tests).
|
||||
func TestEventsAreHeldByTheKeyTheyName(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, subject, body, want string
|
||||
}{
|
||||
{"a registry seat's outcome by its name", gopackageregistry.SubjectPublished, `{"name":"a","version":"1","digest":"sha256:aa"}`, "name a"},
|
||||
{"a version-released by its module", meshcatalog.SubjectVersionReleased, `{"module":"m","version":"0.1.0"}`, "module m"},
|
||||
{"a running by its node", "mesh.seat.node-engine.event.running.ace.mod", `{}`, "node ace"},
|
||||
{"a manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.g14", `{}`, "node g14"},
|
||||
{"another node's manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.ace", `{}`, "node ace"},
|
||||
{"another event of the seat node-engine shares", "mesh.seat.node-engine.event.composed.ace", `{}`, ""},
|
||||
{"an event naming none shares", "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", `{}`, ""},
|
||||
} {
|
||||
if got := eventKey(c.subject, []byte(c.body)); got != c.want {
|
||||
t.Errorf("%s: the key is %q, want %q", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// oneHandler is an event hub with one handler.
|
||||
type oneHandler struct{ handle func(jetstream.Msg) }
|
||||
|
||||
func (h *oneHandler) Handle(_ string, f func(jetstream.Msg)) error { h.handle = f; return nil }
|
||||
func (h *oneHandler) HandleByKey(_ string, _ process.EventKey, f func(jetstream.Msg)) error {
|
||||
h.handle = f
|
||||
return nil
|
||||
}
|
||||
|
||||
// agedTestMsg is a message of the builder's events consumer, with the metadata a ledger reads.
|
||||
type agedTestMsg struct {
|
||||
|
||||
@@ -178,4 +178,66 @@ func TestTheProcessAnswersReserved(t *testing.T) {
|
||||
if _, err := drop("", json.RawMessage(`{"id":"ask-3"}`)); err == nil {
|
||||
t.Error("a drop with no why was taken")
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-514: each ask's take and its ask-taken are its own worker's, started at the pull, so an ask whose
|
||||
// ask-taken hangs holds neither the pull nor the next ask's ask-taken.
|
||||
hang, release := make(chan struct{}), make(chan struct{})
|
||||
saidTaken := make(chan string, 4)
|
||||
slow := &stepQueue{node: "n1", builder: blockingBuilder{started: make(chan string, 2)}, taken: &takenFake{vals: map[string][]byte{}, ttls: map[string]time.Duration{}},
|
||||
takenBound: 10 * time.Minute, inProgress: func() time.Duration { return 0 }, logf: t.Logf, now: time.Now, running: map[string]*runningAsk{},
|
||||
say: func(_ context.Context, subject, _ string, _ any) error {
|
||||
if subject == meshbuilds.SubjectAskTaken("ask-5") {
|
||||
close(hang)
|
||||
<-release
|
||||
}
|
||||
if strings.Contains(subject, "ask-taken") {
|
||||
saidTaken <- subject
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
pulled := make(chan struct{})
|
||||
go func() {
|
||||
slow.take(t.Context(), stepMsg("ask-5"))
|
||||
<-hang
|
||||
slow.take(t.Context(), stepMsg("ask-6"))
|
||||
close(pulled)
|
||||
}()
|
||||
await(t, pulled, "the pull of ask-6 while ask-5's ask-taken hangs")
|
||||
select {
|
||||
case s := <-saidTaken:
|
||||
if s != meshbuilds.SubjectAskTaken("ask-6") {
|
||||
t.Errorf("said %s first, want ask-6's ask-taken", s)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("ask-6's ask-taken waited behind ask-5's")
|
||||
}
|
||||
close(release)
|
||||
await(t, saidTaken, "ask-5's ask-taken once let go")
|
||||
|
||||
// The H-A-514 addendum: while an ask builds or its build waits for a package, the builder says the seat mesh-builds'
|
||||
// step-progress of it at each tick of its minute clock, so the runner's bound of the ask is armed again.
|
||||
tick := make(chan time.Time)
|
||||
progressed := make(chan meshbuilds.StepProgressEvent, 1)
|
||||
building := make(chan string, 1)
|
||||
pq := &stepQueue{node: "n1", builder: blockingBuilder{started: building}, taken: &takenFake{vals: map[string][]byte{}, ttls: map[string]time.Duration{}},
|
||||
takenBound: 10 * time.Minute, inProgress: func() time.Duration { return 0 }, logf: t.Logf, now: time.Now, running: map[string]*runningAsk{},
|
||||
progress: func() (<-chan time.Time, func()) { return tick, func() {} },
|
||||
say: func(_ context.Context, subject, _ string, body any) error {
|
||||
if p, ok := body.(meshbuilds.StepProgressEvent); ok && subject == meshbuilds.SubjectStepProgress("n1") {
|
||||
progressed <- p
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
pq.take(t.Context(), stepMsg("ask-7"))
|
||||
await(t, building, "the build of ask-7")
|
||||
at := time.Date(2026, 11, 23, 2, 41, 0, 0, time.UTC)
|
||||
tick <- at
|
||||
select {
|
||||
case p := <-progressed:
|
||||
if p.Ask != "ask-7" || p.Asker != "main.1.m" || p.Phase != meshbuilds.StepProgressEventPhaseBuild || !p.At.Equal(at) {
|
||||
t.Errorf("step-progress said %+v", p)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("no step-progress was said of ask-7 while it builds")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// The builder's retake of a key failed on a transport fault, on the node-engine seat's events (design 47 G §568, ADR 0673): the
|
||||
@@ -87,3 +88,26 @@ func (d *decisions) heard(m jetstream.Msg) bool {
|
||||
d.handle(m)
|
||||
return true
|
||||
}
|
||||
|
||||
// publishingAgain is the builder's publish again on ADR 0674 §2's events (design 47 H2 H-A-606): the wiring of versions.Againer to the
|
||||
// events consumer.
|
||||
type publishingAgain struct{ a *versions.Againer }
|
||||
|
||||
// heard hands a message of the events consumer to the publish again: one whose state cannot take it is left for the bus to give
|
||||
// again (Nak); every message goes on to the other parts.
|
||||
func (g *publishingAgain) heard(ctx context.Context, m jetstream.Msg, logf func(string, ...any)) (stop bool) {
|
||||
meta, err := m.Metadata()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
handled, err := g.a.Heard(ctx, m.Subject(), m.Data(), meta.Sequence.Stream)
|
||||
if handled && err != nil {
|
||||
logf("%v; heard again", err)
|
||||
if nakErr := m.Nak(); nakErr != nil {
|
||||
logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
|
||||
}
|
||||
givenUp(m, "its event", err, logf)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -4,9 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
@@ -44,10 +42,9 @@ var seatEvents = map[string]seatEvent{
|
||||
npmpackageregistry.SubjectKept: {npmpackageregistry.Seat, npmpackageregistry.EventKept},
|
||||
}
|
||||
|
||||
// seatHearer takes the registry seats' outcomes in: each moves a numbered version (versions.Numberer.Heard), and a
|
||||
// `published` that wakes a name waiting on its floor looks at every module again.
|
||||
// seatHearer takes the registry seats' outcomes in: the publishes' findings and the reservations hear them (design 47 G §369,
|
||||
// A-415); the numbering from before G, which marked its state versions with them, is gone (design 47 H §756).
|
||||
type seatHearer struct {
|
||||
n *versions.Numberer
|
||||
b *build.Builder
|
||||
logf func(string, ...any)
|
||||
// pub raises and clears the findings of a publish that ended badly; nil raises none.
|
||||
@@ -79,26 +76,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
|
||||
if h.pub != nil {
|
||||
h.pub.read(ctx, se.seat)
|
||||
}
|
||||
id := ""
|
||||
if m.Headers() != nil {
|
||||
id = m.Headers().Get("x-event-id")
|
||||
}
|
||||
wake, err := h.n.Heard(ctx, se.seat, se.event, id, o)
|
||||
if errors.Is(err, versions.ErrNotNumbered) {
|
||||
// The version is no entry of the state versions, design 51's numbering by name, which G keeps only until it is removed
|
||||
// (§372); the reservation numbers a version (§369, §52) and takes the outcome in (A-415). Heard again it would stay
|
||||
// unnumbered there, so it is taken, not left for the bus.
|
||||
h.logf("%v in the state versions; the reservations take it (design 47 G §369, A-415)", err)
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
h.logf("%v; heard again (delivery %s)", err, deliveryOf(m))
|
||||
if nakErr := m.Nak(); nakErr != nil {
|
||||
h.logf("leaving %s for the bus to give again: %v", m.Subject(), nakErr)
|
||||
}
|
||||
givenUp(m, fmt.Sprintf("%s's %s of %s@%s", se.seat, se.event, o.Name, o.Version), err, h.logf)
|
||||
return true
|
||||
}
|
||||
if h.pub != nil {
|
||||
h.pub.heard(ctx, se.seat, se.event, o)
|
||||
}
|
||||
@@ -115,10 +92,6 @@ func (h *seatHearer) heard(ctx context.Context, m jetstream.Msg) bool {
|
||||
h.b.PackagePublished(o.Name, o.Version)
|
||||
}
|
||||
h.ack(m)
|
||||
if len(wake) > 0 {
|
||||
h.logf("the floor of %s is asked again: %s said %s", strings.Join(wake, ", "), se.seat, se.event)
|
||||
h.b.Reconsider(ctx)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -150,7 +123,7 @@ func (h *seatHearer) ack(m jetstream.Msg) {
|
||||
}
|
||||
}
|
||||
|
||||
// kvKeeper is the state floor-waits as versions.FloorKeeper.
|
||||
// kvKeeper is a state of the builder as a keeper of keys: Put a key's value, Delete its key.
|
||||
type kvKeeper struct {
|
||||
ctx context.Context
|
||||
kv jetstream.KeyValue
|
||||
@@ -168,27 +141,3 @@ func (k kvKeeper) Delete(key string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// heldFloorWaits are the waits floor-waits holds at the builder's start; a value that is no wait is said and left.
|
||||
func heldFloorWaits(ctx context.Context, kv jetstream.KeyValue, logf func(string, ...any)) []versions.FloorWait {
|
||||
l, err := kv.ListKeys(ctx)
|
||||
if err != nil {
|
||||
logf("%s cannot be listed, so a restart's waits are asked at their next claim: %v", versions.FloorWaitsState, err)
|
||||
return nil
|
||||
}
|
||||
defer func() { _ = l.Stop() }()
|
||||
var out []versions.FloorWait
|
||||
for k := range l.Keys() {
|
||||
e, err := kv.Get(ctx, k)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
w, err := versions.DecodeFloorWait(e.Value())
|
||||
if err != nil {
|
||||
logf("%s.%s holds what is no floor wait, left: %v", versions.FloorWaitsState, k, err)
|
||||
continue
|
||||
}
|
||||
out = append(out, w)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -68,6 +68,33 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) {
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("no step-ended within 20 s")
|
||||
}
|
||||
// Design 47 H2 H-A-577 (1), AC-B2: an ask whose revision the picture does not hold says wait-held (step build, on revision:<R>, kept
|
||||
// under <module>.<fingerprint>.revision) and wait-ended with how ran once it does.
|
||||
waits := make(chan *nats.Msg, 8)
|
||||
for _, ev := range []string{"wait-held", "wait-ended"} {
|
||||
w, err := sub.ChanSubscribe("mesh.mod.*.event."+ev+".netcheck.>", waits)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer w.Unsubscribe()
|
||||
}
|
||||
revisionWait := func(event string) waitBody {
|
||||
t.Helper()
|
||||
for bound := time.After(20 * time.Second); ; {
|
||||
select {
|
||||
case m := <-waits:
|
||||
var w waitBody
|
||||
if err := json.Unmarshal(m.Data, &w); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(m.Subject, ".event."+event+".") && strings.HasSuffix(m.Subject, ".revision") {
|
||||
return w
|
||||
}
|
||||
case <-bound:
|
||||
t.Fatalf("no %s of the revision wait within 20 s", event)
|
||||
}
|
||||
}
|
||||
}
|
||||
// H-A-155: an ask naming a source revision the builder's picture of main does not hold yet waits for it, said in the
|
||||
// journal, and is answered once a revision taken in from it arrives.
|
||||
run.Pipeline, run.Revision, run.Source = "main.2.netcheck", 2, 2
|
||||
@@ -79,6 +106,9 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.awaitSaid(t, "main.2.netcheck: revision 2 of main not in the builder's picture yet")
|
||||
if w := revisionWait("wait-held"); w.On != "revision:2" || w.Step != "build" || w.Module != "netcheck" || w.Fingerprint != fp {
|
||||
t.Errorf("wait-held of the ask for revision 2 = %+v, want step build, on revision:2, netcheck at %s", w, fp)
|
||||
}
|
||||
b.catalog.mu.Lock()
|
||||
b.catalog.source = 2
|
||||
b.catalog.mu.Unlock()
|
||||
@@ -93,6 +123,9 @@ func TestTheRunnersBuildStepAskIsAnsweredAsStepEnded(t *testing.T) {
|
||||
case <-time.After(20 * time.Second):
|
||||
t.Fatal("no step-ended for ask-2 within 20 s")
|
||||
}
|
||||
if w := revisionWait("wait-ended"); w.On != "revision:2" || w.How != "ran" {
|
||||
t.Errorf("wait-ended of the ask for revision 2 = %+v, want on revision:2 ended ran", w)
|
||||
}
|
||||
// Each ask is acknowledged once its end was said: the seat's worker holds none pending.
|
||||
stream, worker := buscompose.SeatQueueStreamName(meshbuilds.Seat), buscompose.SeatQueueWorkerName(meshbuilds.Seat)
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
|
||||
@@ -66,6 +66,9 @@ type stepQueue struct {
|
||||
takenBound time.Duration
|
||||
// inProgress is how often a running ask is said in progress: the seat definition's in-progress.
|
||||
inProgress func() time.Duration
|
||||
// progress is the clock step-progress is said on while an ask builds or its build waits for a package: every
|
||||
// stepProgressEvery (design 47 H2 H-A-514 addendum); a test's when set.
|
||||
progress func() (<-chan time.Time, func())
|
||||
// say publishes a seat event of the builder (emitSeatEvent).
|
||||
say func(ctx context.Context, subject, id string, body any) error
|
||||
logf func(string, ...any)
|
||||
@@ -75,6 +78,19 @@ type stepQueue struct {
|
||||
running map[string]*runningAsk
|
||||
}
|
||||
|
||||
// stepProgressEvery is how often the builder says step-progress of an ask it builds (design 47 H2 H-A-514 addendum): once a
|
||||
// minute, as the seat mesh-wants' holder says its own.
|
||||
const stepProgressEvery = time.Minute
|
||||
|
||||
// progressClock is the clock of step-progress: the test's, else a ticker of stepProgressEvery.
|
||||
func (q *stepQueue) progressClock() (<-chan time.Time, func()) {
|
||||
if q.progress != nil {
|
||||
return q.progress()
|
||||
}
|
||||
t := time.NewTicker(stepProgressEvery)
|
||||
return t.C, t.Stop
|
||||
}
|
||||
|
||||
// runningAsk is an ask the builder took and builds now.
|
||||
type runningAsk struct {
|
||||
run meshbuilds.StepRun
|
||||
@@ -91,10 +107,9 @@ func askIDOf(h nats.Header) string {
|
||||
}
|
||||
|
||||
// take handles one ask pulled from the queue: an ask that is no build step with an id is terminated, said; one this
|
||||
// builder runs already (handed again while it runs) is left to the run that holds it; any other is taken (ask-taken said
|
||||
// the first time its id is taken) and built on its own goroutine, in progress while it runs, acknowledged once its end is
|
||||
// said. A repeat of an id taken before that runs here no longer (the builder started again) is answered as its builds
|
||||
// stand now, read afresh by BuildStep (H-A-381 (1)): an entry built is answered built, never built twice.
|
||||
// builder runs already (handed again while it runs) is left to the run that holds it; any other is held here and handed to
|
||||
// a worker of its own, started at once (design 47 H2 H-A-514): the pull never waits on a state call or a publish of an
|
||||
// earlier ask, so each ask's ask-taken is said within its bound whatever the others do.
|
||||
func (q *stepQueue) take(ctx context.Context, m queueMsg) {
|
||||
id := askIDOf(m.Headers())
|
||||
var run meshbuilds.StepRun
|
||||
@@ -110,36 +125,43 @@ func (q *stepQueue) take(ctx context.Context, m queueMsg) {
|
||||
q.logf("the ask %s (%s) was handed again while it runs here: its run answers it", id, run.Pipeline)
|
||||
return
|
||||
}
|
||||
// An ask dropped before it was pulled ends could-not-run naming the drop, with no build (H-A-404).
|
||||
if d := q.droppedAsk(id); d != nil {
|
||||
work, cancel := context.WithCancelCause(ctx)
|
||||
cancel(d)
|
||||
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
|
||||
q.running[id] = ra
|
||||
q.mu.Unlock()
|
||||
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, run.Pipeline, d.Error())
|
||||
go q.build(work, m, id, ra)
|
||||
return
|
||||
}
|
||||
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
|
||||
if err != nil {
|
||||
q.mu.Unlock()
|
||||
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, run.Pipeline, process.TakenState, err)
|
||||
_ = m.Nak()
|
||||
return
|
||||
}
|
||||
work, cancel := context.WithCancelCause(ctx)
|
||||
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
|
||||
q.running[id] = ra
|
||||
q.mu.Unlock()
|
||||
go q.work(ctx, work, m, id, ra)
|
||||
}
|
||||
|
||||
// work is one ask's worker (H-A-514): an ask dropped before it was pulled ends could-not-run naming the drop, with no build
|
||||
// (H-A-404); any other is taken once by its id in the state taken (ask-taken said the first time it is taken) and built, in
|
||||
// progress while it runs, acknowledged once its end is said. A repeat of an id taken before that runs here no longer (the
|
||||
// builder started again) is answered as its builds stand now, read afresh by BuildStep (H-A-381 (1)): an entry built is
|
||||
// answered built, never built twice. An ask the state taken refuses is let go and handed again.
|
||||
func (q *stepQueue) work(ctx, work context.Context, m queueMsg, id string, ra *runningAsk) {
|
||||
if d := q.droppedAsk(id); d != nil {
|
||||
ra.cancel(d)
|
||||
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, ra.run.Pipeline, d.Error())
|
||||
q.build(work, m, id, ra)
|
||||
return
|
||||
}
|
||||
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
|
||||
if err != nil {
|
||||
ra.cancel(nil)
|
||||
q.mu.Lock()
|
||||
delete(q.running, id)
|
||||
q.mu.Unlock()
|
||||
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, ra.run.Pipeline, process.TakenState, err)
|
||||
_ = m.Nak()
|
||||
return
|
||||
}
|
||||
if first {
|
||||
if err := q.say(ctx, meshbuilds.SubjectAskTaken(id), id+"-taken", meshbuilds.AskTakenEvent{Ask: id, Node: q.node, At: ra.taken.UTC()}); err != nil {
|
||||
q.logf("saying ask-taken of %s: %v", id, err)
|
||||
}
|
||||
} else {
|
||||
q.logf("the ask %s (%s) was taken before: it is answered as its builds stand now", id, run.Pipeline)
|
||||
q.logf("the ask %s (%s) was taken before: it is answered as its builds stand now", id, ra.run.Pipeline)
|
||||
}
|
||||
go q.build(work, m, id, ra)
|
||||
q.build(work, m, id, ra)
|
||||
}
|
||||
|
||||
// build runs one taken ask to its end and says it.
|
||||
@@ -157,6 +179,10 @@ func (q *stepQueue) build(ctx context.Context, m queueMsg, id string, ra *runnin
|
||||
defer t.Stop()
|
||||
tick = t.C
|
||||
}
|
||||
// step-progress is said every minute while the step builds or waits for a package, so the asker's bound of the ask is
|
||||
// armed again (design 47 H2 H-A-514 addendum).
|
||||
progress, stop := q.progressClock()
|
||||
defer stop()
|
||||
done := make(chan meshbuilds.StepEnded, 1)
|
||||
go func() { done <- q.builder.BuildStep(ctx, id, ra.run) }()
|
||||
var end meshbuilds.StepEnded
|
||||
@@ -166,6 +192,11 @@ func (q *stepQueue) build(ctx context.Context, m queueMsg, id string, ra *runnin
|
||||
waiting = false
|
||||
case <-tick:
|
||||
_ = m.InProgress()
|
||||
case at := <-progress:
|
||||
p := meshbuilds.StepProgressEvent{Ask: id, Asker: ra.run.Pipeline, Phase: meshbuilds.StepProgressEventPhaseBuild, At: at.UTC()}
|
||||
if err := q.say(ctx, meshbuilds.SubjectStepProgress(q.node), fmt.Sprintf("%s-progress-%d", id, at.UnixNano()), p); err != nil {
|
||||
q.logf("saying step-progress of %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := q.say(context.WithoutCancel(ctx), meshbuilds.SubjectStepEnded(q.node), id, end); err != nil {
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"module": "disk-load",
|
||||
"version": "0.1",
|
||||
"class": "leaf",
|
||||
"tools": [
|
||||
"disk_load",
|
||||
"disk_top",
|
||||
"disk_filesystems",
|
||||
"disk_folders",
|
||||
"disk_devices",
|
||||
"cpu_top",
|
||||
"disk_readings",
|
||||
"disk_round",
|
||||
"disk_measure"
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools-go",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/disk-load",
|
||||
"binary": "disk-load",
|
||||
"loads": [
|
||||
"disk-load"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "diskreadings",
|
||||
"kind": "package",
|
||||
"language": "go",
|
||||
"paths": [
|
||||
"diskreadings"
|
||||
],
|
||||
"series": "0.1"
|
||||
}
|
||||
]
|
||||
},
|
||||
"state": [
|
||||
"readings",
|
||||
{
|
||||
"name": "rounds",
|
||||
"per-machine": true
|
||||
}
|
||||
],
|
||||
"reads": [
|
||||
"mesh-host.data"
|
||||
]
|
||||
}
|
||||
@@ -5,42 +5,34 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
|
||||
"mesh-delivery-builder/internal/build"
|
||||
"mesh-delivery-builder/internal/versions"
|
||||
)
|
||||
|
||||
// awaitedVersions is the state versions as versions.Store: bound once the bus holds it (the grants part makes it, issue
|
||||
// 1790); until then every use is an error, so a trunk build is built unnumbered and said (build.Builder.number).
|
||||
type awaitedVersions struct {
|
||||
b *process.AwaitedBucket
|
||||
// bucket names the state in the error of one not on the bus yet; empty is the versions'.
|
||||
// awaitedState is one of the builder's states as versions.Store: bound once the bus holds it (the grants part makes it,
|
||||
// issue 1790); until then every use is an error naming the state's bucket.
|
||||
type awaitedState struct {
|
||||
b *process.AwaitedBucket
|
||||
bucket string
|
||||
}
|
||||
|
||||
var errVersionsMissing = errors.New("the state " + versions.State + " is not on the bus yet")
|
||||
|
||||
func (s awaitedVersions) kv() (jetstream.KeyValue, error) {
|
||||
func (s awaitedState) kv() (jetstream.KeyValue, error) {
|
||||
if kv := s.b.KV(); kv != nil {
|
||||
return kv, nil
|
||||
}
|
||||
if s.bucket != "" {
|
||||
return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
|
||||
}
|
||||
return nil, errVersionsMissing
|
||||
return nil, errors.New("the state " + s.bucket + " is not on the bus yet")
|
||||
}
|
||||
|
||||
func (s awaitedVersions) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
|
||||
func (s awaitedState) Get(ctx context.Context, key string) ([]byte, uint64, bool, error) {
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
@@ -62,7 +54,7 @@ func versionsConflict(err error) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (uint64, error) {
|
||||
func (s awaitedState) Create(ctx context.Context, key string, value []byte) (uint64, error) {
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -71,7 +63,7 @@ func (s awaitedVersions) Create(ctx context.Context, key string, value []byte) (
|
||||
return rev, versionsConflict(err)
|
||||
}
|
||||
|
||||
func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
|
||||
func (s awaitedState) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -80,7 +72,7 @@ func (s awaitedVersions) Update(ctx context.Context, key string, value []byte, r
|
||||
return rev, versionsConflict(err)
|
||||
}
|
||||
|
||||
func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, error) {
|
||||
func (s awaitedState) KeysOf(ctx context.Context, filter string) ([]string, error) {
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -97,92 +89,6 @@ func (s awaitedVersions) KeysOf(ctx context.Context, filter string) ([]string, e
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// publishedVersionsVia asks the Go package registry seat's verb versions for one package path (design 47 H H-A-194): its
|
||||
// versions, newest first.
|
||||
func publishedVersionsVia(call toolCaller) func(context.Context, string) ([]string, error) {
|
||||
return func(_ context.Context, path string) ([]string, error) {
|
||||
raw, err := call("seat:"+gopackageregistry.Seat+"."+gopackageregistry.VerbVersions, gopackageregistry.VersionsInput{Name: path})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var a gopackageregistry.VersionsAnswer
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", gopackageregistry.Seat, err)
|
||||
}
|
||||
var out []string
|
||||
for _, v := range a.Versions {
|
||||
if v.Version != "" {
|
||||
out = append(out, v.Version)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
// floorVia is the floor's three sources as calls of the builder's own account (design 51 *The floor*): the seat's verb
|
||||
// versions, the seat git's tags and the requirements the catalog half's entries name (A-119). A call that fails is that source
|
||||
// silent.
|
||||
func floorVia(call toolCaller, requirements func(context.Context, string) ([]string, error)) versions.FloorSources {
|
||||
return versions.FloorSources{
|
||||
Seat: func(_ context.Context, seat, name string) ([]string, error) {
|
||||
raw, err := call("seat:"+seat+".versions", map[string]any{"name": name})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var a struct {
|
||||
Versions []struct {
|
||||
Version string `json:"version"`
|
||||
} `json:"versions"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return nil, fmt.Errorf("%s's versions answered what is no list of versions: %w", seat, err)
|
||||
}
|
||||
var out []string
|
||||
for _, v := range a.Versions {
|
||||
if v.Version != "" {
|
||||
out = append(out, v.Version)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
Tags: func(ctx context.Context, repository, prefix string) ([]string, error) {
|
||||
tags, _, err := tagsVia(call)(ctx, repository, prefix)
|
||||
out := make([]string, 0, len(tags))
|
||||
for _, t := range tags {
|
||||
out = append(out, t.Tag)
|
||||
}
|
||||
return out, err
|
||||
},
|
||||
Requirements: requirements,
|
||||
}
|
||||
}
|
||||
|
||||
// tagsVia reads a repository's tags starting with prefix, each with the commit it names, through the seat git's verb tags,
|
||||
// whichever module holds the seat (design 47 G §7, A-82), page by page; its answer is read tolerantly, form 2 naming each tag's
|
||||
// commit (design 47 H2 §796, §780). away says the read met a transport fault or the error kind away (§776).
|
||||
func tagsVia(call toolCaller) func(ctx context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
|
||||
return func(_ context.Context, repository, prefix string) ([]gitseat.Tag, bool, error) {
|
||||
var out []gitseat.Tag
|
||||
for page := int64(1); ; page++ {
|
||||
raw, err := call("seat:"+gitseat.Seat+"."+gitseat.VerbTags, gitseat.TagsInput{Repository: repository, Prefix: prefix, Page: page})
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
a, _, err := gitseat.DecodeTagsAnswer(raw)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("the seat git's tags answered what is no list of tags: %w", err)
|
||||
}
|
||||
if a.Error != "" {
|
||||
return nil, a.ErrorKind == gitseat.ErrorKindAway, fmt.Errorf("the seat git's tags: %s (%s)", a.Error, a.ErrorKind)
|
||||
}
|
||||
out = append(out, a.Tags...)
|
||||
if !a.More {
|
||||
return out, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// emitEvent says one of the builder's events, mesh.mod.<module>.event.<event>, with the SDK's envelope headers and id as
|
||||
// the bus's dedup id.
|
||||
func emitEvent(ctx context.Context, js jetstream.JetStream, cred process.Account, event, id string, body any) error {
|
||||
@@ -222,64 +128,143 @@ func emitSeatEvent(ctx context.Context, js jetstream.JetStream, cred process.Acc
|
||||
return err
|
||||
}
|
||||
|
||||
// The events on the builder's consumer of EVENTS that wake a floor (design 51 *The floor*, DLV-B3b).
|
||||
var (
|
||||
// The indexer's take-in.taken, which the builder consumes in place of the retired manifest-accepted (design 47 H H-A-116).
|
||||
takenInSubject = "mesh.mod.mesh-delivery-indexer.event.take-in.taken"
|
||||
conditionClearedSubject = meshconditions.SubjectConditionCleared
|
||||
)
|
||||
|
||||
// floorWake asks the floor of the names an event wakes again, by looking at every module again: a trunk build is
|
||||
// numbered before its claim (build.Builder.number).
|
||||
type floorWake struct {
|
||||
b *build.Builder
|
||||
waits *versions.FloorWaits
|
||||
logf func(string, ...any)
|
||||
// markLifetime writes the marks of the state acted with the bus's per-message lifetime of the setting acted-days, each write giving
|
||||
// it again (design 47 H2 H-A-720 (1)); the release record and every other key it writes with none (H-A-720 (2)). An update is the
|
||||
// one publish carrying the lifetime and the expected last sequence of the key (H-A-741).
|
||||
type markLifetime struct {
|
||||
awaitedReserved
|
||||
days int
|
||||
js jetstream.JetStream
|
||||
}
|
||||
|
||||
// heard takes a message of the consumer in when it is one that wakes a floor, acknowledged, and answers whether it was.
|
||||
func (f *floorWake) heard(ctx context.Context, m jetstream.Msg) bool {
|
||||
switch m.Subject() {
|
||||
case takenInSubject:
|
||||
f.ack(m)
|
||||
f.wake(ctx, versions.WakeTakenIn, "", "")
|
||||
case conditionClearedSubject:
|
||||
f.ack(m)
|
||||
var e meshconditions.ConditionEvent
|
||||
if err := json.Unmarshal(m.Data(), &e); err != nil {
|
||||
f.logf("%s holds what is no condition, left: %v", m.Subject(), err)
|
||||
return true
|
||||
}
|
||||
if e.Subject == nil {
|
||||
return true
|
||||
}
|
||||
for _, module := range conditionModules(e.Subject.ID) {
|
||||
f.wake(ctx, versions.WakeCleared, "", module)
|
||||
}
|
||||
default:
|
||||
return false
|
||||
func (s markLifetime) life(key string) (time.Duration, bool) {
|
||||
if mark, _ := versions.ActedFormOf(key); mark {
|
||||
return time.Duration(s.days) * 24 * time.Hour, true
|
||||
}
|
||||
return true
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (f *floorWake) ack(m jetstream.Msg) {
|
||||
if err := m.Ack(); err != nil {
|
||||
f.logf("acknowledging %s: %v", m.Subject(), err)
|
||||
func (s markLifetime) Create(ctx context.Context, key string, value []byte) (uint64, error) {
|
||||
ttl, ok := s.life(key)
|
||||
if !ok {
|
||||
return s.awaitedReserved.Create(ctx, key, value)
|
||||
}
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rev, err := kv.Create(ctx, key, value, jetstream.KeyTTL(ttl))
|
||||
return rev, versionsConflict(err)
|
||||
}
|
||||
|
||||
// wake looks at every module again when the event wakes a name, and says which.
|
||||
func (f *floorWake) wake(ctx context.Context, kind, seat, module string) {
|
||||
names := f.waits.Wake(kind, seat, module, "")
|
||||
if len(names) == 0 {
|
||||
func (s markLifetime) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
|
||||
ttl, ok := s.life(key)
|
||||
if !ok {
|
||||
return s.awaitedReserved.Update(ctx, key, value, revision)
|
||||
}
|
||||
kv, err := s.kv()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
_ = kv
|
||||
return updateWithLifetime(ctx, s.js, s.bucket, key, value, revision, ttl)
|
||||
}
|
||||
|
||||
// updateWithLifetime is one publish to the key's subject carrying the per-message lifetime and the expected last sequence of the
|
||||
// key: the compare-and-set update that gives the lifetime again (design 47 H2 H-A-741).
|
||||
func updateWithLifetime(ctx context.Context, js jetstream.JetStream, bucket, key string, value []byte, revision uint64, ttl time.Duration) (uint64, error) {
|
||||
msg := nats.NewMsg("$KV." + bucket + "." + key)
|
||||
msg.Data = value
|
||||
msg.Header.Set("Nats-TTL", fmt.Sprintf("%ds", int64(ttl/time.Second)))
|
||||
msg.Header.Set("Nats-Expected-Last-Subject-Sequence", strconv.FormatUint(revision, 10))
|
||||
ack, err := js.PublishMsg(ctx, msg)
|
||||
if err != nil {
|
||||
var apiErr *jetstream.APIError
|
||||
if errors.As(err, &apiErr) && apiErr.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequence {
|
||||
return 0, versions.ErrConflict
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return ack.Sequence, nil
|
||||
}
|
||||
|
||||
// deleteUnknown deletes each key of the state acted of a form the builder does not write (design 47 H2 H-A-720 (3)) and says the
|
||||
// count once.
|
||||
func deleteUnknown(ctx context.Context, kv jetstream.KeyValue, logf func(string, ...any)) {
|
||||
l, err := kv.ListKeys(ctx)
|
||||
if err != nil {
|
||||
logf("the keys of the state %s are not listed, so none of no form is deleted: %v", versions.ActedState, err)
|
||||
return
|
||||
}
|
||||
f.logf("the floor of %s is asked again: %s", strings.Join(names, ", "), kind)
|
||||
f.b.Reconsider(ctx)
|
||||
var gone []string
|
||||
for k := range l.Keys() {
|
||||
if _, known := versions.ActedFormOf(k); !known {
|
||||
gone = append(gone, k)
|
||||
}
|
||||
}
|
||||
_ = l.Stop()
|
||||
n := 0
|
||||
for _, k := range gone {
|
||||
if err := kv.Delete(ctx, k); err != nil {
|
||||
logf("the key %s of the state %s, of no form the builder writes, is not deleted: %v", k, versions.ActedState, err)
|
||||
continue
|
||||
}
|
||||
n++
|
||||
}
|
||||
if len(gone) > 0 {
|
||||
logf("the state %s: %d keys of no form the builder writes were deleted at the start", versions.ActedState, n)
|
||||
}
|
||||
}
|
||||
|
||||
// conditionModules are the tokens of a condition's subject id (`<node>/<module>`, `<module>.<check>`): a module named
|
||||
// among them is the one whose condition cleared.
|
||||
func conditionModules(id string) []string {
|
||||
return strings.FieldsFunc(id, func(r rune) bool { return r == '/' || r == '.' || r == ':' })
|
||||
// carryDrops is the builder's start of the re-ask state (design 47 H2 H-A-749 (2)): each answered publish-drop ask is carried onto
|
||||
// its version's reservation as dropped (the ask's by, why and at) where the reservation stands and holds none, so a drop made before
|
||||
// is kept; then each record of mode publish, whose readers are gone, is deleted. It says the counts once.
|
||||
func carryDrops(ctx context.Context, kv jetstream.KeyValue, r *versions.Reserver, logf func(string, ...any)) {
|
||||
l, err := kv.ListKeys(ctx)
|
||||
if err != nil {
|
||||
logf("the keys of the state %s are not listed, so no earlier drop is carried and no publish record deleted: %v", build.ReAsksState, err)
|
||||
return
|
||||
}
|
||||
var keys []string
|
||||
for k := range l.Keys() {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
_ = l.Stop()
|
||||
slices.Sort(keys)
|
||||
var carried, deleted int
|
||||
var records []string
|
||||
for _, k := range keys {
|
||||
e, err := kv.Get(ctx, k)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ask, err := build.DecodeReAsk(e.Value())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case ask.Mode == "publish": // the record of a version's publish item, written before H-A-746
|
||||
records = append(records, k)
|
||||
case ask.Mode == build.ModePublishDrop && !ask.Answered.IsZero() && !ask.Refused:
|
||||
v, found, err := r.Of(ctx, ask.Module, ask.Version)
|
||||
if err != nil || !found || v.Dropped != nil {
|
||||
continue
|
||||
}
|
||||
if ok, err := r.MarkDropped(ctx, ask.Module, ask.Version, ask.By, ask.Why, ask.At); err != nil {
|
||||
logf("the drop of %s %s by %s is not carried onto its reservation: %v", ask.Module, ask.Version, ask.By, err)
|
||||
} else if ok {
|
||||
carried++
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, k := range records {
|
||||
if err := kv.Delete(ctx, k); err != nil {
|
||||
logf("the publish record %s of the state %s is not deleted: %v", k, build.ReAsksState, err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
if carried > 0 || deleted > 0 {
|
||||
logf("the state %s at the start: %d earlier drops carried onto their reservations as dropped, %d publish records deleted", build.ReAsksState, carried, deleted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,9 +27,16 @@ type waitBody struct {
|
||||
Since time.Time `json:"since"`
|
||||
Bound string `json:"bound,omitempty"`
|
||||
How string `json:"how,omitempty"`
|
||||
// Publisher, Revision and Until are a pin wait's (design 47 H2 H-A-707 (5), DQ-53).
|
||||
Publisher string `json:"publisher,omitempty"`
|
||||
Revision int64 `json:"revision,omitempty"`
|
||||
Until time.Time `json:"until,omitzero"`
|
||||
}
|
||||
|
||||
const waitStepBuilding = "building"
|
||||
const (
|
||||
waitStepBuilding = "building"
|
||||
waitStepBuild = "build"
|
||||
)
|
||||
|
||||
// waitsKept keeps the builder's toolchain waits in its old state waits, one key <module>.<fingerprint> (design 47 G §672),
|
||||
// and says wait-held and wait-ended on its old stream waits; at its start it says wait-held again for every key.
|
||||
@@ -48,7 +55,24 @@ func newWaitsKept(kv *process.AwaitedBucket, say func(context.Context, string, s
|
||||
}
|
||||
|
||||
func (w *waitsKept) body(t build.ToolchainWait, how string) waitBody {
|
||||
return waitBody{Step: waitStepBuilding, On: t.On(), Part: t.Package, Module: t.Module, Fingerprint: t.Fingerprint, Since: t.Since, Bound: w.bound.String(), How: how}
|
||||
b := waitBody{Step: waitStepBuilding, On: t.On(), Part: t.Package, Module: t.Module, Fingerprint: t.Fingerprint, Since: t.Since, Bound: w.bound.String(), How: how,
|
||||
Publisher: t.Publisher, Until: t.Until}
|
||||
if !t.Until.IsZero() { // a pin wait says the bound of `package-wait-minutes`, which it carries, and the revision it holds
|
||||
b.Bound, b.Revision = t.Bound, t.Revision
|
||||
}
|
||||
if t.IsRevision() { // a step ask's wait for its revision: `step` build, its own bound (design 47 H2 H-A-577 (1))
|
||||
b.Step, b.Bound = waitStepBuild, t.Bound
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// slotOf is the part of a wait's key and subject after `<module>.<fingerprint>`: a revision wait keeps its own, so it is told apart
|
||||
// from that key's toolchain wait.
|
||||
func slotOf(t build.ToolchainWait) string {
|
||||
if t.IsRevision() {
|
||||
return ".revision"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// start reads the state whole and says wait-held again for each key.
|
||||
@@ -76,26 +100,33 @@ func (w *waitsKept) start(ctx context.Context, kv jetstream.KeyValue) {
|
||||
}
|
||||
|
||||
func (w *waitsKept) said(ctx context.Context, event string, t build.ToolchainWait, how string) {
|
||||
if err := w.say(ctx, event+"."+t.Module+"."+t.Fingerprint, event+"-"+t.Module+"-"+t.Fingerprint+"-"+t.Since.UTC().Format(time.RFC3339Nano)+how, w.body(t, how)); err != nil {
|
||||
if err := w.say(ctx, event+"."+t.Module+"."+t.Fingerprint+slotOf(t), event+"-"+t.Module+"-"+t.Fingerprint+slotOf(t)+"-"+t.Since.UTC().Format(time.RFC3339Nano)+how, w.body(t, how)); err != nil {
|
||||
w.logf("saying %s of %s at %s: %v", event, t.Module, t.Fingerprint, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Hold keeps the wait and says wait-held, once.
|
||||
// Hold keeps the wait and says wait-held, once. A key holds the build's one current wait (design 47 H2 H-A-723 (1)): a Hold over a
|
||||
// standing wait of another kind or other fields ends that wait, said wait-ended with how replaced, and holds the new one; a Hold equal
|
||||
// to the standing wait changes nothing.
|
||||
func (w *waitsKept) Hold(ctx context.Context, t build.ToolchainWait) {
|
||||
key, err := builds.BuilderBuildKey(t.Module, t.Fingerprint)
|
||||
if err != nil {
|
||||
w.logf("a wait of %s at %s has no key: %v", t.Module, t.Fingerprint, err)
|
||||
return
|
||||
}
|
||||
key += slotOf(t)
|
||||
w.mu.Lock()
|
||||
if _, had := w.held[key]; had {
|
||||
old, had := w.held[key]
|
||||
if had && old.SameWait(t) {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.held[key] = t
|
||||
w.mu.Unlock()
|
||||
if kv := w.kv.KV(); kv != nil {
|
||||
if had {
|
||||
w.said(ctx, "wait-ended", old, build.WaitReplaced)
|
||||
}
|
||||
if kv := w.bucket(); kv != nil {
|
||||
data, _ := json.Marshal(t)
|
||||
if _, err := kv.Put(ctx, key, data); err != nil {
|
||||
w.logf("%s.%s could not be written, so the wait is kept in memory only: %v", build.WaitsState, key, err)
|
||||
@@ -106,14 +137,25 @@ func (w *waitsKept) Hold(ctx context.Context, t build.ToolchainWait) {
|
||||
|
||||
// End deletes the wait and says wait-ended with how; it answers whether one was held.
|
||||
func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool {
|
||||
return w.end(ctx, module, fp, "", how)
|
||||
}
|
||||
|
||||
// EndRevision ends the revision wait of module's fingerprint, kept under its own key.
|
||||
func (w *waitsKept) EndRevision(ctx context.Context, module, fp, how string) bool {
|
||||
return w.end(ctx, module, fp, ".revision", how)
|
||||
}
|
||||
|
||||
func (w *waitsKept) end(ctx context.Context, module, fp, slot, how string) bool {
|
||||
key, err := builds.BuilderBuildKey(module, fp)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
key += slot
|
||||
w.mu.Lock()
|
||||
t, had := w.held[key]
|
||||
// A key queued behind a package ends only when it is published, and a toolchain wait never by that (design 47 G A-192).
|
||||
if had && (t.Package != "") != (how == build.WaitPublished) {
|
||||
// A key queued behind a package ends only when it is published, and a toolchain wait never by that (design 47 G A-192); a wait
|
||||
// ended failed is ended whatever its kind (design 47 H2 H-A-723 (2)).
|
||||
if had && slot == "" && how != build.WaitFailed && (t.Package != "") != (how == build.WaitPublished) {
|
||||
had = false
|
||||
}
|
||||
if had {
|
||||
@@ -123,7 +165,7 @@ func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool {
|
||||
if !had {
|
||||
return false
|
||||
}
|
||||
if kv := w.kv.KV(); kv != nil {
|
||||
if kv := w.bucket(); kv != nil {
|
||||
if err := kv.Delete(ctx, key); err != nil && !errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||
w.logf("%s.%s could not be deleted: %v", build.WaitsState, key, err)
|
||||
}
|
||||
@@ -131,3 +173,11 @@ func (w *waitsKept) End(ctx context.Context, module, fp, how string) bool {
|
||||
w.said(ctx, "wait-ended", t, how)
|
||||
return true
|
||||
}
|
||||
|
||||
// bucket is the state waits once it is on the bus; none before, and none for a form kept in memory alone.
|
||||
func (w *waitsKept) bucket() jetstream.KeyValue {
|
||||
if w.kv == nil {
|
||||
return nil
|
||||
}
|
||||
return w.kv.KV()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -18,4 +21,50 @@ func TestAWaitBodyNamesItsPart(t *testing.T) {
|
||||
if tc := w.body(build.ToolchainWait{Module: "m", Fingerprint: "src2:f", Language: "go", Version: "go1.26.0"}, ""); tc.Part != "" || tc.On != "toolchain:go@go1.26.0" {
|
||||
t.Errorf("a toolchain wait says %+v", tc)
|
||||
}
|
||||
// H2 H-A-577 (1): a revision wait says `step` build, `on` revision:<R> and its own bound, under the subject token `.revision`
|
||||
rev := build.ToolchainWait{Module: "m", Fingerprint: "src2:f", Kind: build.WaitKindRevision, Revision: 7, Bound: "2m0s"}
|
||||
if rv := w.body(rev, ""); rv.Step != "build" || rv.On != "revision:7" || rv.Bound != "2m0s" || slotOf(rev) != ".revision" || slotOf(build.ToolchainWait{}) != "" {
|
||||
t.Errorf("a revision wait says %+v, slot %q", rv, slotOf(rev))
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-723, H-A-707 (5), DQ-53 (H-A-717): a key holds one wait. A pin wait held over a toolchain wait ends it as `replaced`
|
||||
// and stands; an equal Hold writes nothing; a pin wait ended `failed` is deleted; its body says `package-wait-minutes` as its bound
|
||||
// and carries publisher, revision and until, the package its path alone.
|
||||
func TestAKeyHoldsTheBuildsOneWait(t *testing.T) {
|
||||
var said []string
|
||||
var bodies []waitBody
|
||||
w := newWaitsKept(nil, func(_ context.Context, event, _ string, body any) error {
|
||||
said = append(said, strings.SplitN(event, ".", 2)[0])
|
||||
bodies = append(bodies, body.(waitBody))
|
||||
return nil
|
||||
}, time.Hour, t.Logf)
|
||||
ctx := context.Background()
|
||||
since := time.Unix(100, 0)
|
||||
tc := build.ToolchainWait{Module: "m", Fingerprint: fpw, Language: "go", Version: "go1.26.0", Since: since}
|
||||
pin := build.ToolchainWait{Module: "m", Fingerprint: fpw, Package: "git.x/y/sdk", Publisher: "sdk@src2:p", Revision: 7, Bound: "10m0s", Since: since, Until: since.Add(10 * time.Minute)}
|
||||
w.Hold(ctx, tc)
|
||||
w.Hold(ctx, tc)
|
||||
if !slices.Equal(said, []string{"wait-held"}) {
|
||||
t.Fatalf("a toolchain wait held twice said %v, want one wait-held", said)
|
||||
}
|
||||
w.Hold(ctx, pin)
|
||||
if !slices.Equal(said, []string{"wait-held", "wait-ended", "wait-held"}) || bodies[1].How != build.WaitReplaced || bodies[1].On != "toolchain:go@go1.26.0" {
|
||||
t.Fatalf("a pin wait over a toolchain wait said %v, %+v, want the toolchain wait ended replaced", said, bodies)
|
||||
}
|
||||
if p := bodies[2]; p.Bound != "10m0s" || p.Publisher != "sdk@src2:p" || p.Revision != 7 || !p.Until.Equal(pin.Until) || p.Part != "git.x/y/sdk" || p.On != "package:git.x/y/sdk" {
|
||||
t.Errorf("the pin wait says %+v", p)
|
||||
}
|
||||
w.Hold(ctx, pin)
|
||||
if len(said) != 3 {
|
||||
t.Errorf("a Hold equal to the standing wait said %v, want nothing", said[3:])
|
||||
}
|
||||
if w.End(ctx, "m", fpw, build.WaitRan) {
|
||||
t.Error("a pin wait ended ran")
|
||||
}
|
||||
if !w.End(ctx, "m", fpw, build.WaitFailed) || len(w.held) != 0 || bodies[len(bodies)-1].How != build.WaitFailed {
|
||||
t.Errorf("a pin wait ended failed: held %v, said %v", w.held, said)
|
||||
}
|
||||
}
|
||||
|
||||
var fpw = "src2:" + strings.Repeat("a", 64)
|
||||
|
||||
@@ -50,6 +50,8 @@ require (
|
||||
|
||||
replace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/buildrun => ./buildrun
|
||||
|
||||
replace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds => ./builds
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-contracts/go/seats/nodeengine v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user