MV1: move contracts and sdk under modules/, importers follow

The delivery repository's contracts and SDK live under modules/ as
mesh-delivery-contracts and mesh-delivery-sdk, their Go module paths
renamed to match the folders (the TypeScript names already did), and
every importer in mesh-delivery, mesh-catalog, mesh-host, mesh-tools
and mesh-sdk follows in the same group: a design as it should be, one
path per module, checked by the group's check building every importer.

Builds: design 47 G §427, §88

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
This commit is contained in:
2026-11-12 05:09:56 +01:00
parent 512bb3c75c
commit 71a35a6376
769 changed files with 1277 additions and 1277 deletions
-70
View File
@@ -1,70 +0,0 @@
package buildrecord
import "time"
// BuildRecord is the layout the ended controller's chain wrote (mesh-controller internal/chain/records.go Build, line 91),
// the fields a reader outside it read (novox/hq ADR 0437 §4 §5, issue 1223). The controller's record carries more; a decode ignores
// what is not here. Path is the module's directory in its repository, as the controller writes it (Build.Path, records.go:100,
// set from the build request trimmed of slashes at internal/inventory/chain_requests.go:19); empty for a module whose
// manifest is the repository's root. SourceInputs has no json keys of its own: it is written under its Go field names, as the controller
// writes it.
type BuildRecord struct {
ID string `json:"id"`
State string `json:"state,omitempty"`
Failed string `json:"failed,omitempty"`
Repository string `json:"repository"`
Ref string `json:"ref,omitempty"`
Module string `json:"module,omitempty"`
Path string `json:"path,omitempty"`
Commit string `json:"commit,omitempty"`
At time.Time `json:"at,omitzero"`
SourceFingerprint string `json:"source-fingerprint,omitempty"`
SourceInputs *SourceInputs `json:"source-inputs,omitempty"`
// Made is what the build made (Build.Made, records.go:110); the digest is the tail of an artifact's Reference.
Made []Artifact `json:"made,omitempty"`
}
// Artifact is one thing a build made: mesh-controller internal/chain/records.go Artifact, json keys name, kind and
// reference, nothing else (novox/hq ADR 0478 clause 8).
type Artifact struct {
Name string `json:"name"`
Kind string `json:"kind"`
Reference string `json:"reference"`
}
// BuildKey is a build's record under its module, a build that knew none under the request's key: copied from
// mesh-controller internal/chain/keys.go:35-40 (BuildKey, with RequestKey at line 42).
func BuildKey(module, id string) string {
if module == "" {
return "req." + id
}
return module + ".build." + id
}
// NewestKey is the key of a module's newest build, of any state: copied from mesh-controller internal/chain/keys.go:44.
// The key holds no record: its value is the newest build's id as raw bytes (internal/inventory/chain_builds.go:210 and
// :546), and the record lives at BuildKey(module, id). The pointer is a hint, checked against that record.
func NewestKey(module string) string { return module + ".newest" }
// SourceInputs are what the ended controller's source fingerprint (src1) was of, as its build records hold them
// (BuildRecord), read and never computed again (novox/hq ADR 0437 §5): the module, the git tree of
// its directory, its bases (references, of which only the digest counts), the root tree of each repository its
// artifacts read (by artifact), each artifact's toolchain line, and the reason the source does not pin the build
// when it does not (a build that resolves packages when built). A context is the value the builder records for it:
// a repository's root tree, or for an image that compiles a Go program the `narrow:` hash of the build source it was
// handed (mesh-controller internal/builder/builder.go:1146-1156).
type SourceInputs struct {
Module string
Tree string
Bases []string
Contexts map[string]string
Toolchains map[string]string
Unpinned string
}
// IsTrunkBuild is whether the record is a successful build of the trunk that recorded its source inputs: an outcome
// (the controller writes no state on one; state asked is a request, records.go:57-59), not failed, and ref "main" or none. A build a delivery plan asked after a merge, or rebuild or build --behind, follows the branch
// without naming it, so it carries no ref; a build of any other branch or of a commit names it (issue 1281).
func (r BuildRecord) IsTrunkBuild() bool {
return r.State == "" && r.Failed == "" && r.SourceInputs != nil && (r.Ref == "" || r.Ref == "main")
}
-179
View File
@@ -1,179 +0,0 @@
package buildrecord
import (
"encoding/json"
"os"
"testing"
"time"
)
// The fixture's path is what the controller writes for a build request: strings.Trim(path, "/") at mesh-controller
// internal/inventory/chain_requests.go:19, the module's directory in its repository (Build.Path, internal/chain/records.go:100).
// The fixture started as a record the controller's own encoder wrote (json.Marshal of a chain.Build, mesh-controller
// internal/chain, a throwaway test run once and deleted) with build-agent's build-1792395447088936520 values, plus a
// manifest-digest and one made artifact (shape: mesh-controller internal/chain/records.go:91-117 Build, json tags, at commit
// 1f708e2d8d72e2c27dbeaba02f14c128d700eada; an outcome has no state key and a build asked after a merge no ref, records.go:57-59), which a BuildRecord does not carry. It was then edited by hand
// to the controller's layout for an outcome: state and ref removed, the repository a clone URL (issue 1281).
func loadBuildFixture(t *testing.T) []byte {
t.Helper()
raw, err := os.ReadFile("testdata/build-record-build-agent.json")
if err != nil {
t.Fatal(err)
}
return raw
}
func TestBuildRecordDecodes(t *testing.T) { // 1223/AC1
var r BuildRecord
if err := json.Unmarshal(loadBuildFixture(t), &r); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ name, got, want string }{
{"id", r.ID, "build-1792395447088936520"},
{"module", r.Module, "build-agent"},
{"repository", r.Repository, "http://novox.internal:20000/novox/mesh-controller.git"},
{"ref", r.Ref, ""},
{"commit", r.Commit, "7a74cee83f88e6585a5511c3cc53bdf0f5303d20"},
{"state", r.State, ""},
{"failed", r.Failed, ""},
{"source-fingerprint", r.SourceFingerprint, "src1:e846efe73716b78e80860baaac96153de2cb76551325753838ca245d2160a3d7"},
} {
if c.got != c.want {
t.Errorf("%s = %q, want %q", c.name, c.got, c.want)
}
}
if want := time.Date(2026, 10, 19, 9, 38, 0, 0, time.UTC); !r.At.Equal(want) {
t.Errorf("at = %v, want %v", r.At, want)
}
if !r.IsTrunkBuild() { // 1281/AC7
t.Error("the fixture, a record as the controller writes it, is not a trunk build")
}
if r.SourceInputs == nil {
t.Fatal("source-inputs missing")
}
}
func TestBuildRecordPath(t *testing.T) { // 1233/AC1
var r BuildRecord
if err := json.Unmarshal(loadBuildFixture(t), &r); err != nil {
t.Fatal(err)
}
if r.Path != "modules/build-agent" {
t.Errorf("path = %q, want modules/build-agent", r.Path)
}
// mesh-controller's manifest is its repository's root: the controller writes no path (omitempty), so the path is "".
var m map[string]json.RawMessage
if err := json.Unmarshal(loadBuildFixture(t), &m); err != nil {
t.Fatal(err)
}
delete(m, "path")
raw, _ := json.Marshal(m)
var root BuildRecord
if err := json.Unmarshal(raw, &root); err != nil {
t.Fatal(err)
}
if root.Path != "" {
t.Errorf("path of a root module = %q, want empty", root.Path)
}
// Every field 1223/AC1 checks is still equal in both.
if root.ID != r.ID || root.Module != r.Module || root.Repository != r.Repository || root.Ref != r.Ref ||
root.Commit != r.Commit || root.State != r.State || root.SourceFingerprint != r.SourceFingerprint || !root.At.Equal(r.At) {
t.Errorf("fields differ: %+v vs %+v", root, r)
}
// And the path survives a round trip through the SDK's own type.
back, _ := json.Marshal(r)
var again BuildRecord
if err := json.Unmarshal(back, &again); err != nil || again.Path != r.Path {
t.Errorf("round trip path = %q (%v)", again.Path, err)
}
}
func TestBuildRecordWithoutInputs(t *testing.T) { // 1223/AC2
var m map[string]json.RawMessage
if err := json.Unmarshal(loadBuildFixture(t), &m); err != nil {
t.Fatal(err)
}
delete(m, "source-inputs")
raw, _ := json.Marshal(m)
var r BuildRecord
if err := json.Unmarshal(raw, &r); err != nil {
t.Fatal(err)
}
if r.SourceInputs != nil {
t.Errorf("source-inputs = %+v, want nil", r.SourceInputs)
}
if r.Module != "build-agent" {
t.Errorf("module = %q, want build-agent", r.Module)
}
}
func TestBuildKeys(t *testing.T) { // 1223/AC3
// Literal values of mesh-controller internal/broker/controller_buckets.go:101 (BucketName(ControllerSeat, ChainBuilds)
// is "mesh-controller_builds") and internal/chain/keys.go:35-44.
if got := BuildKey("build-agent", "build-1"); got != "build-agent.build.build-1" {
t.Errorf("BuildKey = %q", got)
}
if got := BuildKey("", "build-1"); got != "req.build-1" {
t.Errorf("BuildKey without a module = %q", got)
}
if got := NewestKey("build-agent"); got != "build-agent.newest" {
t.Errorf("NewestKey = %q", got)
}
}
// The fixture's made artifacts are the controller's Artifact (mesh-controller internal/chain/records.go, json tags name,
// kind, reference; the controller writes no digest key, the digest is the tail of the reference). The kinds and references
// are those of the live record mesh-controller.builds printed for build-agent build-1792540091397811913 (2026-10-21 01:49).
func TestBuildRecordMade(t *testing.T) { // 1588/AC2
var r BuildRecord
if err := json.Unmarshal(loadBuildFixture(t), &r); err != nil {
t.Fatal(err)
}
want := []Artifact{
{Name: "server", Kind: "image", Reference: "artifact-store://build-agent/server@sha256:a79c13f1c727ff94959e80824cc704ea58b80d80ecdd00fd447698acebb35090"},
{Name: "files", Kind: "archive", Reference: "artifact-store://build-agent/files/blobs/sha256:bccd3f47851436d1b45a3063cc2d7e34c5c109b2d030739bfbb4b9781703f9a9"},
}
if len(r.Made) != len(want) {
t.Fatalf("made = %+v, want %+v", r.Made, want)
}
for i := range want {
if r.Made[i] != want[i] {
t.Errorf("made[%d] = %+v, want %+v", i, r.Made[i], want[i])
}
}
var none BuildRecord
if err := json.Unmarshal([]byte(`{"id":"b","repository":"a/b"}`), &none); err != nil || none.Made != nil {
t.Errorf("a record without made: %+v, %v", none, err)
}
}
func TestIsTrunkBuild(t *testing.T) { // 1281/AC2
inputs := &SourceInputs{Module: "zsh", Tree: "t"}
for _, c := range []struct {
name string
r BuildRecord
want bool
}{
{"built on main", BuildRecord{Ref: "main", SourceInputs: inputs}, true},
// a build a delivery plan asked after a merge, or rebuild / build --behind, carries no ref (live builds,
// 2026-10-19: zsh build-1792417485811374131, mesh-delivery build-1792435539606203626)
{"built with no ref", BuildRecord{SourceInputs: inputs}, true},
{"another branch", BuildRecord{Ref: "feat/x", SourceInputs: inputs}, false},
{"a commit", BuildRecord{Ref: "9efdd87a", SourceInputs: inputs}, false},
{"asked", BuildRecord{State: "asked", SourceInputs: inputs}, false},
{"answered, state answered, no source inputs", BuildRecord{State: "answered"}, false},
{"failed", BuildRecord{Failed: "boom", Ref: "main", SourceInputs: inputs}, false},
{"no source inputs", BuildRecord{Ref: "main"}, false},
{"no ref and no source inputs", BuildRecord{}, false},
} {
if got := c.r.IsTrunkBuild(); got != c.want {
t.Errorf("%s: IsTrunkBuild = %v, want %v", c.name, got, c.want)
}
}
// decoded as the controller writes it: the key "ref" is absent
var r BuildRecord
raw := `{"id":"build-1792417485811374131","repository":"http://novox.internal:20000/novox/mesh-catalog.git","module":"zsh","source-inputs":{"Module":"zsh","Tree":"t"}}`
if err := json.Unmarshal([]byte(raw), &r); err != nil || !r.IsTrunkBuild() {
t.Errorf("a decoded record with no ref: trunk = %v, err %v", r.IsTrunkBuild(), err)
}
}
@@ -1 +0,0 @@
{"id":"build-1792395447088936520","repository":"http://novox.internal:20000/novox/mesh-controller.git","module":"build-agent","commit":"7a74cee83f88e6585a5511c3cc53bdf0f5303d20","path":"modules/build-agent","manifest-digest":"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","source-fingerprint":"src1:e846efe73716b78e80860baaac96153de2cb76551325753838ca245d2160a3d7","source-inputs":{"Module":"build-agent","Tree":"11c0b4f90cae0d6e4ef9cc48cbfdf9f6dbe52bca","Bases":["sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc","sha256:8ac98ca534ac3f51e1f420a1dd2c15e74c75cfa0f23f3ad27eb5d7236c349a0c"],"Contexts":{"server":"narrow:d51ca744fd11af59d616c858f76c27b3e58e16e11fbdc0c720eb9d7d19d55fac"},"Toolchains":null,"Unpinned":""},"made":[{"name":"server","kind":"image","reference":"artifact-store://build-agent/server@sha256:a79c13f1c727ff94959e80824cc704ea58b80d80ecdd00fd447698acebb35090"},{"name":"files","kind":"archive","reference":"artifact-store://build-agent/files/blobs/sha256:bccd3f47851436d1b45a3063cc2d7e34c5c109b2d030739bfbb4b9781703f9a9"}],"at":"2026-10-19T09:38:00Z"}
-52
View File
@@ -1,52 +0,0 @@
package buildrun
import (
"encoding/json"
"sync"
"testing"
"time"
"git.novox.be/novox/mesh-delivery/sdk/buildstep"
)
// keys is a steps state in memory: every value put, in order, per key, and a signal for each end.
type keys struct {
mu sync.Mutex
puts map[string][]buildstep.Step
ended chan string
}
func newKeys() *keys { return &keys{puts: map[string][]buildstep.Step{}, ended: make(chan string, 16)} }
func (k *keys) put(key string, value any) (uint64, error) {
step, err := buildstep.DecodeStep(value.(json.RawMessage))
if err != nil {
return 0, err
}
k.mu.Lock()
k.puts[key] = append(k.puts[key], step)
n := uint64(len(k.puts[key]))
k.mu.Unlock()
if step.State != buildstep.StepRunning {
k.ended <- key
}
return n, nil
}
func (k *keys) last(key string) buildstep.Step {
k.mu.Lock()
defer k.mu.Unlock()
s := k.puts[key]
return s[len(s)-1]
}
func (k *keys) waitEnd(t *testing.T) string {
t.Helper()
select {
case key := <-k.ended:
return key
case <-time.After(3 * time.Second):
t.Fatal("the step never ended on its key")
return ""
}
}
-339
View File
@@ -1,339 +0,0 @@
package buildrun
import (
"context"
"encoding/json"
"errors"
"fmt"
"git.novox.be/novox/mesh-delivery/sdk/buildstep"
"os"
"strconv"
"strings"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// RestartReason is why a step a previous process left running is ended.
const RestartReason = "the build module restarted while it ran"
// Boot is when this process began. A step with no owner (written by an older build) started at or after it is taken
// for this process's, which may still run it, so EndOne refuses it.
var Boot = time.Now()
// Owner is this process as a step's owner (buildstep.Step.Owner): `<boot id>.<pid>.<start>`, the node's boot id
// (/proc/sys/kernel/random/boot_id), the pid and Boot in milliseconds, base 36. The start keeps two processes apart
// that a reboot or a pid namespace gave the same pid. A running step whose owner is another is a previous process's.
var Owner = ownerOf(bootID, os.Getpid(), Boot)
// bootID is the node's boot id as Owner holds it; noBootID when it could not be read, which EndStaleAtStart says once.
var bootID = readBootID()
const noBootID = "no-boot-id"
func ownerOf(bootID string, pid int, start time.Time) string {
return bootID + "." + strconv.Itoa(pid) + "." + strconv.FormatInt(start.UnixMilli(), 36)
}
// readBootID is the node's boot id, or noBootID where it cannot be read (the pid and the start then tell the processes
// apart).
func readBootID() string {
b, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
if id := strings.TrimSpace(string(b)); err == nil && id != "" {
return id
}
return noBootID
}
// Scan reads and writes a steps state with its revisions: its keys, a key's stored value and revision (nil and 0 for
// none), a write that lands only while the key is still at the revision read (KeptState.Update), and a delete of a key
// still at the revision read; both fail with stdio.ErrChanged when another writer was first.
type Scan struct {
Keys func() ([]string, error)
Get func(key string) (json.RawMessage, uint64, error)
Update func(key string, value any, revision uint64) (uint64, error)
Delete func(key string, revision uint64) error
}
// ScanOf is the Scan of a state the process keeps.
//
// Its Delete reads the key again and deletes it only while it is still at the revision read: the runtime's
// mesh/state.delete takes no revision yet, so a write landing between that read and the delete (a few milliseconds) is
// deleted with it. For a step key that is a redelivered ask begun on this node in that moment: its running key leaves
// the steps state until its run writes its end, which its asker still reads (a watch takes puts only).
func ScanOf(s stdio.KeptState) Scan {
get := func(key string) (json.RawMessage, uint64, error) {
e, err := s.Get(key)
if err != nil || e == nil {
return nil, 0, err
}
return e.Value, e.Revision, nil
}
return Scan{Keys: s.Keys, Update: s.Update, Get: get, Delete: func(key string, revision uint64) error {
_, rev, err := get(key)
if err != nil {
return err
}
if rev != revision {
return stdio.ErrChanged
}
return s.Delete(key)
}}
}
// isAsk says a step is a pulled ask's: its key is <node>.<ask id> and its tool is "<kind> ask" (a hand-started step
// has the tool's name). An ask's key is the stream's to settle, never a restart's: the puller leaves an ask it was
// running unacknowledged so the stream redelivers it, and the asker's wait takes the first end it reads on the key.
// A key a gone process owns is deleted, never ended (EndStale); one with no owner is ended only once the asker's bound
// has passed (buildstep.StepBound), when it is nobody's.
func isAsk(key string, s buildstep.Step) bool {
_, _, err := buildstep.ParseAskStepKey(key)
return err == nil && strings.HasSuffix(s.Tool, " ask")
}
// AskWhat says what an ask is, in one line: its kind, and its repository, head and levels, or its module and
// fingerprint.
func AskWhat(a buildstep.Ask) string {
short := func(s string) string {
if len(s) > 12 {
return s[:12]
}
return s
}
str := func(m map[string]any, k string) string { v, _ := m[k].(string); return v }
parts := []string{a.Kind + " ask"}
switch {
case a.Check != nil:
parts = append(parts, str(a.Check.Fetch, "repository")+"@"+short(str(a.Check.Fetch, "commit")), "levels "+strings.Join(a.Check.Levels, ","))
if a.Check.Run != "" {
parts = append(parts, "run "+a.Check.Run)
}
case a.Build != nil:
parts = append(parts, "module "+a.Build.Module)
if r := str(a.Build.Fetch, "repository"); r != "" {
parts = append(parts, r+"@"+short(str(a.Build.Fetch, "commit")))
}
if a.Build.FP != "" {
parts = append(parts, "fp "+short(a.Build.FP))
}
case a.Compose != nil:
parts = append(parts, "compose", str(a.Compose.Fetch, "repository")+"@"+short(str(a.Compose.Fetch, "commit")))
case a.Run != nil:
parts = append(parts, "run "+a.Run.Program.Package, a.Run.Program.Repository+"@"+short(a.Run.Program.Commit))
if len(a.Run.Args) > 0 {
parts = append(parts, strings.Join(a.Run.Args, " "))
}
parts = append(parts, fmt.Sprintf("%d heads", len(a.Run.Heads)))
}
return strings.Join(parts, ", ")
}
// endRunning writes step ended failed with why, only while its key is still at revision.
func endRunning(scan Scan, key string, step buildstep.Step, revision uint64, why string) error {
step.State, step.Reason, step.Ended, step.Result = buildstep.StepFailed, why, now().UTC(), nil
raw, err := buildstep.EncodeStep(step)
if err != nil {
return err
}
_, err = scan.Update(key, json.RawMessage(raw), revision)
return err
}
// EndStale ends this node's running steps that no process of this module runs any more, and answers their ids. Only keys
// of node are read; a value that is no step is left alone.
// - A hand-started step with an owner (buildstep.Step.Owner) that is not this process (Owner) is ended failed with
// RestartReason at once, whatever its age: its process is gone and nothing redelivers it, so nothing else would
// write its end (issue 1890, note 21).
// - A pulled ask's step with an owner that is not this process is deleted, not ended (novox/hq ADR 0525 §6): the
// stream redelivers an ask whose node stopped (the puller neither ends nor acknowledges one at its stop), and its
// asker takes the first end it reads, so an end written here would fail a check the redelivery would still run. Its
// asker's watch takes puts only and keeps waiting for the redelivery's key, its bound the backstop; the stale running
// key leaves the steps state, and with it the delivery view's and the checker's count of what runs (note 21: it
// held one of a build node's two slots).
// - A step owned by this process is left: it may run now. A redelivered ask begun on this node is owned by it.
// - A step with no owner (written by an older build) keeps the earlier rule: a hand-started step started before
// `before` (the start of this process) is ended; a pulled ask is left to the stream's redelivery (isAsk) until its
// start is older than buildstep.StepBound, and then ended "past the step bound: its asker stopped waiting at <time>".
//
// Each end and delete is logged, naming the step, its owner and why. A key written by another writer since it was read
// (a redelivered ask's start, a real end) is skipped.
func EndStale(scan Scan, node string, before time.Time, logf func(string, ...any)) ([]string, error) {
keys, err := scan.Keys()
if err != nil {
return nil, fmt.Errorf("buildstep: listing the steps of %s: %w", node, err)
}
var ended []string
for _, k := range keys {
_, n, _, perr := buildstep.ParseStepKey(k)
if perr != nil || n != node {
continue
}
raw, rev, err := scan.Get(k)
if err != nil {
return ended, fmt.Errorf("buildstep: reading the step %s: %w", k, err)
}
if len(raw) == 0 {
continue
}
step, err := buildstep.DecodeStep(raw)
if err != nil || step.State != buildstep.StepRunning {
continue
}
why, said := staleWhy(k, step, before)
if why == "" {
continue
}
done := "ended"
if step.Owner != "" && isAsk(k, step) {
done = "deleted, left to the stream's redelivery"
if scan.Delete == nil {
err = fmt.Errorf("the steps state takes no delete")
} else {
err = scan.Delete(k, rev)
}
} else {
err = endRunning(scan, k, step, rev, why)
}
if err != nil {
if errors.Is(err, stdio.ErrChanged) {
continue
}
return ended, fmt.Errorf("buildstep: ending the step %s: %w", k, err)
}
if logf != nil {
logf("the step %s (%s, started %s) was left running and is %s: %s; %s", k, step.Tool,
step.Started.UTC().Format(time.RFC3339), done, why, said)
}
ended = append(ended, step.ID)
}
return ended, nil
}
// staleWhy is why a running step is ended (or, for an ask with an owner, deleted) by EndStale and what the log says of
// its owner, or "" to leave it.
func staleWhy(key string, step buildstep.Step, before time.Time) (why, said string) {
switch {
case step.Owner == Owner:
return "", ""
case step.Owner != "":
return RestartReason, "its owner " + step.Owner + " is not this process " + Owner
case isAsk(key, step):
if !step.Started.Add(buildstep.StepBound).Before(now()) {
return "", ""
}
return "past the step bound: its asker stopped waiting at " + step.Started.Add(buildstep.StepBound).UTC().Format("2006-01-02T15:04:05Z"),
"it names no owner (an older build wrote it)"
case step.Started.Before(before):
return RestartReason, "it names no owner (an older build wrote it) and started before this process"
}
return "", ""
}
// EndOne ends this node's running step id (or the key <node>.<id>) as failed with why. A step that is not running is
// refused, and so is one this process owns (Owner; for a step with no owner, one started since Boot: it may still run,
// whether a pulled ask or a step a tool started), one live reports as held, and one whose key changed since it was read.
func EndOne(scan Scan, node, id, why string, live func(id string) bool) (buildstep.Step, error) {
id = strings.TrimSpace(id)
if n, rest, ok := strings.Cut(id, "."); ok {
if n != node {
return buildstep.Step{}, fmt.Errorf("the step %q is of node %q, this module runs on %q", id, n, node)
}
id = rest
}
if strings.TrimSpace(why) == "" {
return buildstep.Step{}, fmt.Errorf("say why the step is ended (why)")
}
key, err := buildstep.StepKey(node, id)
if err != nil {
return buildstep.Step{}, err
}
raw, rev, err := scan.Get(key)
if err != nil {
return buildstep.Step{}, err
}
if len(raw) == 0 {
return buildstep.Step{}, fmt.Errorf("no step %s in the steps state", key)
}
step, err := buildstep.DecodeStep(raw)
if err != nil {
return buildstep.Step{}, err
}
if step.State != buildstep.StepRunning {
return buildstep.Step{}, fmt.Errorf("the step %s is %s, not running", key, step.State)
}
if step.Owner == Owner || (step.Owner == "" && !step.Started.Before(Boot)) || (live != nil && live(id)) {
return buildstep.Step{}, fmt.Errorf("the step %s was started by this process and may run now; only a step a previous process left is ended", key)
}
if err := endRunning(scan, key, step, rev, why); err != nil {
if errors.Is(err, stdio.ErrChanged) {
return buildstep.Step{}, fmt.Errorf("the step %s changed while it was being ended; read it again", key)
}
return buildstep.Step{}, err
}
step.State, step.Reason = buildstep.StepFailed, why
return step, nil
}
// StaleAttempts and StaleRetry bound EndStaleAtStart's tries: the steps state is readable once the runtime serves.
var (
StaleAttempts = 6
StaleRetry = 5 * time.Second
)
// StaleServed is what EndStaleAtStart waits for before it reads the steps state: the runtime serving (stdio.Served).
// The conformance kit's left-running case (conformance.LeftRunning) hands it a closed channel, to run a module's own
// start sweep in its test.
var StaleServed = stdio.Served
// EndStaleAtStart is what a build module runs once at its start, in a goroutine: it waits for the runtime to serve,
// then ends this node's steps a previous process left running (EndStale), trying again when the state cannot be read
// yet. A step names its owner, so `before` (the start of this process) matters only for a step with no owner, written
// by an older build: such a step started before it is a previous process's. When the node's boot id cannot be read it
// says so once: Owner then tells processes apart by their pid and start only.
func EndStaleAtStart(ctx context.Context, scan Scan, node string, before time.Time, logf func(string, ...any)) {
select {
case <-ctx.Done():
return
case <-StaleServed():
}
if bootID == noBootID && logf != nil {
logf("the boot id of %s cannot be read (/proc/sys/kernel/random/boot_id): its steps' owner is %s, told apart by pid and start only", node, Owner)
}
for attempt := 1; ; attempt++ {
ended, err := EndStale(scan, node, before, logf)
if err == nil {
if logf != nil {
logf("%d steps of %s left running by a previous process ended", len(ended), node)
}
return
}
if logf != nil {
logf("ending the steps left running (try %d of %d): %v", attempt, StaleAttempts, err)
}
if attempt >= StaleAttempts {
return
}
select {
case <-ctx.Done():
return
case <-time.After(StaleRetry):
}
}
}
// EndStaleRound is EndStale as the module's periodic round runs it: at once, and only when the runtime serves (a round
// before that is skipped, the start's EndStaleAtStart and the next round cover it). It ends the steps a previous
// process left and the asks past buildstep.StepBound.
func EndStaleRound(scan Scan, node string, logf func(string, ...any)) {
select {
case <-stdio.Served():
default:
return
}
if _, err := EndStale(scan, node, Boot, logf); err != nil && logf != nil {
logf("ending the steps left running: %v", err)
}
}
// now is the clock; a test sets it.
var now = time.Now
-177
View File
@@ -1,177 +0,0 @@
package buildrun
import (
"encoding/json"
"fmt"
"git.novox.be/novox/mesh-delivery/sdk/buildstep"
"strings"
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// scanOf is the steps a keys double holds, last value per key, its revision the count of its puts; a write through
// Update lands only at the revision read, as the state's does. race, when set, runs once before the next Update's check.
func scanOf(k *keys, race func(key string)) Scan {
return Scan{
Keys: func() ([]string, error) {
k.mu.Lock()
defer k.mu.Unlock()
var out []string
for key := range k.puts {
out = append(out, key)
}
return out, nil
},
Get: func(key string) (json.RawMessage, uint64, error) {
k.mu.Lock()
defer k.mu.Unlock()
s, ok := k.puts[key]
if !ok {
return nil, 0, nil
}
raw, err := buildstep.EncodeStep(s[len(s)-1])
return raw, uint64(len(s)), err
},
Delete: func(key string, revision uint64) error {
k.mu.Lock()
defer k.mu.Unlock()
if uint64(len(k.puts[key])) != revision {
return stdio.ErrChanged
}
delete(k.puts, key)
return nil
},
Update: func(key string, value any, revision uint64) (uint64, error) {
if race != nil {
race(key)
}
k.mu.Lock()
n := uint64(len(k.puts[key]))
k.mu.Unlock()
if n != revision {
return 0, stdio.ErrChanged
}
return k.put(key, value)
},
}
}
// 1890 and 1890/AC6: EndStale ends this node's hand-started running steps of another owner at once, whatever their age,
// and deletes its asks of another owner (the stream redelivers them, ADR 0525 §6); of
// the steps with no owner (an older build's), the hand-started ones left running before the process began and the asks
// past the step bound (a younger ask is the stream's to redeliver); never a step this process owns or a key written
// meanwhile. EndOne ends one by hand, never one this process owns or started.
func TestEndStaleAndEndOne(t *testing.T) {
k := newKeys()
boot := time.Now()
oldBoot := Boot
Boot = boot
defer func() { Boot = oldBoot }()
gone := ownerOf("b00t", 4242, boot.Add(-time.Hour))
put := func(node, id, tool, state string, started time.Time, owner string) {
key, _ := buildstep.StepKey(node, id)
_, _ = k.put(key, json.RawMessage(mustStep(t, buildstep.Step{ID: id, Tool: tool, Node: node, State: state, Started: started, Owner: owner})))
}
put("ace", "old1", "build_go_fetch", buildstep.StepRunning, boot.Add(-time.Hour), "")
put("ace", "mjk3l9x0abcdef", "check ask", buildstep.StepRunning, boot.Add(-time.Hour), "")
put("ace", "mjk3l9x0abcdee", "check ask", buildstep.StepRunning, time.Now().Add(-5*time.Minute), "")
put("ace", "mjk3l9x0abcded", "check ask", buildstep.StepRunning, time.Now().Add(-5*time.Minute), gone) // note 21's ghost
put("ace", "gone2", "build_go_test", buildstep.StepRunning, boot.Add(time.Second), gone)
put("ace", "mine1", "check ask", buildstep.StepRunning, boot.Add(-time.Hour), Owner)
put("ace", "raced1", "build_go_test", buildstep.StepRunning, boot.Add(-time.Hour), "")
put("ace", "new1", "build_go_fetch", buildstep.StepRunning, boot.Add(time.Second), "")
put("ace", "done1", "build_go_fetch", buildstep.StepPassed, boot.Add(-time.Hour), gone)
put("ace", "again1", "build_go_fetch", buildstep.StepAgain, boot.Add(-time.Hour), gone) // issue 1748: the bus gives it again; the sweep leaves it
put("g14", "other1", "build_go_fetch", buildstep.StepRunning, boot.Add(-time.Hour), gone)
// raced1 is ended by its own run between the read and the write.
raced := false
scan := scanOf(k, func(key string) {
if key == "ace.raced1" && !raced {
raced = true
put("ace", "raced1", "build_go_test", buildstep.StepPassed, boot.Add(-time.Hour), "")
}
})
var said []string
ended, err := EndStale(scan, "ace", boot, func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) })
if err != nil || len(ended) != 4 {
t.Fatalf("ended %v, %v", ended, err)
}
if s := k.last("ace.again1"); s.State != buildstep.StepAgain {
t.Errorf("the sweep ended a step the bus gives again: %+v", s)
}
if _, held := k.puts["ace.mjk3l9x0abcded"]; held {
t.Errorf("the ghost ask's key is still held: %+v", k.last("ace.mjk3l9x0abcded"))
}
for _, key := range []string{"ace.old1", "ace.gone2"} {
if s := k.last(key); s.State != buildstep.StepFailed || s.Reason != RestartReason || s.Ended.IsZero() {
t.Errorf("%s = %+v", key, s)
}
}
if s := k.last("ace.mjk3l9x0abcdef"); s.State != buildstep.StepFailed || !strings.HasPrefix(s.Reason, "past the step bound: its asker stopped waiting at ") {
t.Errorf("the old ask = %+v", s)
}
if log := strings.Join(said, "\n"); !strings.Contains(log, "ace.mjk3l9x0abcded") || !strings.Contains(log, "deleted, left to the stream's redelivery") || !strings.Contains(log, "its owner "+gone+" is not this process "+Owner) {
t.Errorf("the log does not name the ghost and its owner:\n%s", log)
}
for key, state := range map[string]string{"ace.mjk3l9x0abcdee": buildstep.StepRunning, "ace.mine1": buildstep.StepRunning, "ace.raced1": buildstep.StepPassed,
"ace.new1": buildstep.StepRunning, "ace.done1": buildstep.StepPassed, "g14.other1": buildstep.StepRunning} {
if s := k.last(key); s.State != state {
t.Errorf("%s = %s, want %s", key, s.State, state)
}
}
// EndOne: refuses without why, a held step, one this process owns or (with no owner) started, a step not running and
// another node's; ends a step a previous process left.
for _, c := range []struct{ id, why string }{{"old1", ""}, {"new1", "stuck"}, {"mine1", "stuck"}, {"done1", "x"}, {"g14.other1", "x"}} {
if _, err := EndOne(scan, "ace", c.id, c.why, nil); err == nil {
t.Errorf("ended %s with why %q", c.id, c.why)
}
}
put("ace", "old2", "build_go_fetch", buildstep.StepRunning, boot.Add(time.Second), gone)
if _, err := EndOne(scan, "ace", "old2", "x", func(string) bool { return true }); err == nil {
t.Error("ended a held step")
}
if _, err := EndOne(scan, "ace", "ace.old2", "stuck for good", nil); err != nil {
t.Fatal(err)
}
if s := k.last("ace.old2"); s.State != buildstep.StepFailed || s.Reason != "stuck for good" || s.Owner != gone {
t.Errorf("old2 = %+v", s)
}
if a, b := ownerOf("b", 1, boot), ownerOf("b", 1, boot.Add(time.Second)); a == b {
t.Errorf("two starts of one pid share the owner %q", a)
}
}
func mustStep(t *testing.T, s buildstep.Step) []byte {
t.Helper()
raw, err := buildstep.EncodeStep(s)
if err != nil {
t.Fatal(err)
}
return raw
}
// 1890: AskWhat names the repository, head and levels of a check ask and the module of a build ask.
func TestAskWhat(t *testing.T) {
var check, build buildstep.Ask
for raw, into := range map[string]*buildstep.Ask{
`{"kind":"check","check":{"fetch":{"repository":"novox/mesh-sdk","commit":"0123456789abcdef0123"},"levels":["unit","integration"]}}`: &check,
`{"kind":"delivery","build":{"module":"mesh-x","fp":"abcdef0123456789"}}`: &build,
} {
if err := json.Unmarshal([]byte(raw), into); err != nil {
t.Fatal(err)
}
}
if got, want := AskWhat(check), "check ask, novox/mesh-sdk@0123456789ab, levels unit,integration"; got != want {
t.Errorf("check = %q", got)
}
if got, want := AskWhat(build), "delivery ask, module mesh-x, fp abcdef012345"; got != want {
t.Errorf("build = %q", got)
}
// 1921: a run ask's step names the program, where it is built, its arguments and how many heads it reads.
run := buildstep.Ask{Kind: "check", Run: &buildstep.RunJob{Program: buildstep.RunProgram{Repository: "novox/mesh-delivery", Commit: "fedcba9876543210", Package: "./cmd/mesh-checking-program"}, Heads: []buildstep.RunHead{{}, {}}, Args: []string{"-verdict"}}}
if got, want := AskWhat(run), "check ask, run ./cmd/mesh-checking-program, novox/mesh-delivery@fedcba987654, -verdict, 2 heads"; got != want {
t.Errorf("run = %q", got)
}
}
-843
View File
@@ -1,843 +0,0 @@
package buildstep
import (
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"path"
"slices"
"sort"
"strings"
"time"
meshkeys "git.novox.be/novox/mesh-sdk/go/keys"
)
// **The build ask, once.** The three build seats (node-build-go, node-build-image, node-build-node) accept the same ask,
// defined once as the part `build-step` of the Delivery contracts. The generator writes one Go type per seat, so the
// seat packages hold three structurally equal StepAsks; this file is the one neutral form the shared runner and the
// askers use, and AskOf is the one conversion from any seat's (a seat's value and this form are the same JSON, held
// equal by the part's fixtures: the contracts' tests decode each in both). This package imports no seat's contract
// (novox/hq ADR 0634 §6).
// The kinds of ask: the seat's accepted kinds, in the order a holder pulls them.
const (
AskDelivery = "delivery"
AskCheck = "check"
AskRecheck = "recheck"
// AskStep is a pipeline step the runner sends (novox/hq design 47 *The steps and who serves them*: the accepted kind
// step on the stream check, after delivery and before recheck).
AskStep = "step"
)
// AskKinds are the accepted kinds of a build seat, in the order a holder pulls them (ADR 0536 §4).
var AskKinds = []string{AskDelivery, AskCheck, AskStep, AskRecheck}
// The languages of the build seats: each is one build module's (mesh-build-<language>) and one seat's
// (node-build-<language>).
const (
AskGo = "go"
AskNode = "node"
AskImage = "image"
)
// AskLanguages are the build seats' languages.
var AskLanguages = []string{AskGo, AskNode, AskImage}
// NeedNodeBuildNode is the need of a check whose tests run through the Node build seat's holder on the same node
// (issue 890): a node that holds no Node build module declines the ask.
const NeedNodeBuildNode = "node-build-node"
// AskNeeds are the needs an ask may name.
var AskNeeds = []string{NeedNodeBuildNode}
// CheckNeed refuses a need an ask may not name.
func CheckNeed(need string) error {
if !slices.Contains(AskNeeds, need) {
return fmt.Errorf("buildstep: %q is not a need an ask may name (%s)", need, strings.Join(AskNeeds, ", "))
}
return nil
}
// Lacks are the needs has does not say its node has; a nil has lacks all.
func Lacks(needs []string, has func(need string) bool) []string {
var out []string
for _, n := range needs {
if has == nil || !has(n) {
out = append(out, n)
}
}
return out
}
// AskRuns is how many times a holder runs one ask before it ends refused; AskMaxDeliver is the redelivery bound that
// leaves one more for the terminal step (ADR 0525 §5).
const (
AskRuns = 3
AskMaxDeliver = AskRuns + 2
)
// AgainAfter is how long the bus waits before it gives an ask again after its run-th run ended on a transport fault: 1
// minute after the first, 4 after the second (ADR 0664 §2). It outlasts a per-source penalty of a forge's sshd.
func AgainAfter(run int) time.Duration {
if run < 1 {
run = 1
}
return time.Minute << (2 * (run - 1))
}
// StepAskVersion is the layout version of an ask.
const StepAskVersion = 1
// The levels a check ask names.
const (
LevelUnit = "unit"
LevelIntegration = "integration"
)
// The registry seats a build publishes through (ADR 0605 §1).
var RegistrySeats = []string{"npm-package-registry", "go-package-registry", "container-image-registry", "oci-artifact-registry"}
// NodeNamesArg and NodeNamesEnv carry the node names a check's tests run against.
const (
NodeNamesArg = "node-names"
NodeNamesEnv = "MESH_NODE_NAMES"
)
func checkAskKind(kind string) error {
if !slices.Contains(AskKinds, kind) {
return fmt.Errorf("buildstep: the ask kind %q is not delivery, check, step or recheck", kind)
}
return nil
}
func checkAskLanguage(language string) error {
if !slices.Contains(AskLanguages, language) {
return fmt.Errorf("buildstep: the ask language %q is not go, node or image", language)
}
return nil
}
// BuildSeat is the seat of a language's build module.
func BuildSeat(language string) (string, error) {
if err := checkAskLanguage(language); err != nil {
return "", err
}
return "node-build-" + language, nil
}
// AskSubject is the subject a build seat accepts a kind of ask on: the seat's accept subject of main's form, which names no
// asker (design 47 G §600, §483).
func AskSubject(language, kind string) (string, error) {
seat, err := BuildSeat(language)
if err != nil {
return "", err
}
if err := checkAskKind(kind); err != nil {
return "", err
}
return "mesh.seat." + seat + ".accept." + kind, nil
}
// AskerBuilder is the builder's name as an asker: the last token of the subject its asks are put on and the first of its
// step keys (design 47 G §600, §481).
const AskerBuilder = "builder"
// AskSubjectBy is the subject a build seat accepts a queue's ask of asker on: `mesh.seat.<seat>.accept.<queue>.<asker>`, the
// asker's name the last token (design 47 G §481, §600). An empty asker is main's subject (AskSubject).
func AskSubjectBy(language, kind, asker string) (string, error) {
subject, err := AskSubject(language, kind)
if err != nil || asker == "" {
return subject, err
}
if !askerOK.MatchString(asker) {
return "", fmt.Errorf("buildstep: %q is not an asker's name", asker)
}
return subject + "." + asker, nil
}
// ParseAskSubject is the inverse of AskSubject and of AskSubjectBy: the language and the queue of either form.
func ParseAskSubject(subject string) (language, kind string, err error) {
language, kind, _, err = ParseAskSubjectBy(subject)
return language, kind, err
}
// ParseAskSubjectBy is the inverse of AskSubjectBy: the language, the queue and the asker, which is empty for main's form.
func ParseAskSubjectBy(subject string) (language, kind, asker string, err error) {
rest, ok := strings.CutPrefix(subject, "mesh.seat.node-build-")
if !ok {
return "", "", "", fmt.Errorf("buildstep: %q is not a build seat's accept subject", subject)
}
language, kind, ok = strings.Cut(rest, ".accept.")
if !ok {
return "", "", "", fmt.Errorf("buildstep: %q is not a build seat's accept subject", subject)
}
kind, asker, _ = strings.Cut(kind, ".")
if want, err := AskSubjectBy(language, kind, asker); err != nil || want != subject {
return "", "", "", fmt.Errorf("buildstep: %q is not a build seat's accept subject: %v", subject, err)
}
return language, kind, asker, nil
}
// AskStream is the work-queue stream of a language's build seat.
func AskStream(language string) (string, error) {
seat, err := BuildSeat(language)
if err != nil {
return "", err
}
return "SEAT_" + strings.ToUpper(strings.ReplaceAll(seat, "-", "_")), nil
}
// AskWorker is the shared pull worker of a kind on a language's stream.
func AskWorker(language, kind string) (string, error) {
stream, err := AskStream(language)
if err != nil {
return "", err
}
if err := checkAskKind(kind); err != nil {
return "", err
}
return stream + "_" + strings.ToUpper(kind) + "_worker", nil
}
// AskStepKey is the key of the step of the ask askID on node.
func AskStepKey(node, askID string) (string, error) {
if err := CheckAskID(askID); err != nil {
return "", err
}
return StepKey(node, askID)
}
// AskStepWatch is the key pattern of an ask's step on any node.
func AskStepWatch(askID string) (string, error) {
if err := CheckAskID(askID); err != nil {
return "", err
}
return "*." + askID, nil
}
// StepAsk is one ask of a build module: the part's `StepAsk`.
type StepAsk struct {
V int `json:"v"`
ID string `json:"id"`
Kind string `json:"kind"`
Language string `json:"language"`
Asker string `json:"asker"`
At time.Time `json:"at,omitzero"`
// Version is the version MAJOR.MINOR.PATCH the builder reserved for the build, which the build module passes as
// MESH_VERSION; empty for a build that reserves none, which stamps none (design 47 G §573).
Version string `json:"version,omitempty"`
Build *BuildJob `json:"build,omitempty"`
Check *CheckJob `json:"check,omitempty"`
Compose *ComposeJob `json:"compose,omitempty"`
// Run is a run ask's job (run.go): a program built from a change and run over the heads, on the Go seat's check
// stream alone, as a compose.
Run *RunJob `json:"run,omitempty"`
// Step is a pipeline step the runner sends as the accepted kind step (novox/hq ADR 0666 §7): lint or tests of one
// artifact.
Step *StepRun `json:"step,omitempty"`
// Needs are what a check's tests need of the holder's node (CheckNeed); a holder lacking one declines the ask.
Needs []string `json:"needs,omitempty"`
// Packages pin the mesh packages a build or a check builds against.
Packages PackageVersions `json:"packages,omitempty"`
}
// Fetch is what a build module's fetch tool is asked, inside an ask: the part's `Fetch`.
type Fetch struct {
V int `json:"v,omitempty"`
Repository string `json:"repository"`
Commit string `json:"commit"`
Ref string `json:"ref,omitempty"`
Base string `json:"base,omitempty"`
Dir string `json:"dir,omitempty"`
Paths []string `json:"paths,omitempty"`
Packages PackageVersions `json:"packages,omitempty"`
// Package is the TypeScript module's group package: the group's tagged version ({name, version}) or the group's package
// member ({repository, commit, ref}).
Package *FetchPackage `json:"package,omitempty"`
Beside []FetchBeside `json:"beside,omitempty"`
// Builds name a group run's package members by their builds' digests (design 47 G §465): a package named here is named in
// neither Packages nor Package.
Builds []FetchBuild `json:"builds,omitempty"`
}
// FetchBuild is one package member of a group run by its build: the package's name in its ecosystem (the Go module path, the
// npm name), the member's module and artifact, and its build's `sha256:` digest (design 47 G §465).
type FetchBuild struct {
Package string `json:"package"`
Module string `json:"module"`
Artifact string `json:"artifact"`
Digest string `json:"digest"`
}
// FetchPackage is the group package a TypeScript fetch takes (ADR 0607 §3, ADR 0500 §5): either the group's tagged version
// (Name and Version) or the group's package member (Repository, Commit and Ref).
type FetchPackage struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Repository string `json:"repository,omitempty"`
Commit string `json:"commit,omitempty"`
Ref string `json:"ref,omitempty"`
}
// FetchBeside is a sibling repository placed beside the fetched tree.
type FetchBeside struct {
Repository string `json:"repository"`
Commit string `json:"commit"`
}
// ToolchainUsed is the toolchain a build ran with.
type ToolchainUsed struct {
Language string `json:"language"`
Recipe string `json:"recipe"`
Version string `json:"version"`
// Digest is the building node's digest of its toolchain program, the entry of kind 3 (design 47 G §466, §472), never the
// build module's own program.
Digest string `json:"digest,omitempty"`
}
// AskArtifact is one artifact of a build ask: built from the fetched tree, or copied from an upstream pin (From).
type AskArtifact struct {
Artifact string `json:"artifact"`
From string `json:"from,omitempty"`
Seat string `json:"seat,omitempty"`
Version string `json:"version,omitempty"`
}
// BuildJob is a trunk fingerprint's build.
type BuildJob struct {
Module string `json:"module"`
Path string `json:"path,omitempty"`
Fp string `json:"fp,omitempty"`
Fetch *Fetch `json:"fetch,omitempty"`
Artifacts []AskArtifact `json:"artifacts"`
Publish bool `json:"publish,omitempty"`
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
}
// CheckJob is the check of one or both levels of a fetched tree.
type CheckJob struct {
Fetch Fetch `json:"fetch"`
Levels []string `json:"levels"`
Kept bool `json:"kept,omitempty"`
Runner string `json:"runner,omitempty"`
RunnerWhen string `json:"runner_when,omitempty"`
Run string `json:"run,omitempty"`
Packages []string `json:"packages,omitempty"`
NodeNames []string `json:"node-names,omitempty"`
// Toolchain is the toolchain the checker agreed for the language (ADR 0584 clause 2): a holder whose node reports
// another version declines the check.
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
}
// ComposeJob asks one compose-candidate build.
type ComposeJob struct {
Fetch Fetch `json:"fetch"`
Dir string `json:"dir"`
Package string `json:"package"`
// Request is the composer's request: a JSON object, or a JSON string PackedRequestPrefix + the base64 of the object
// gzip-compressed (issue 1966; the checker packs every request it sends, and
// the part's `request` describes both forms). The part types it `any`, so both fit it; a
// build module that does not know the packed form refuses the ask naming that it holds no request object.
Request json.RawMessage `json:"request"`
Reader string `json:"reader,omitempty"`
}
// PackedRequestPrefix opens a compose job's request that travels gzip-compressed.
const PackedRequestPrefix = "gzip+base64:"
// PackRequest sets the job's request from the JSON object raw, packed.
func (c *ComposeJob) PackRequest(raw []byte) error {
var b bytes.Buffer
zw := gzip.NewWriter(&b)
if _, err := zw.Write(raw); err != nil {
return err
}
if err := zw.Close(); err != nil {
return err
}
packed, err := json.Marshal(PackedRequestPrefix + base64.StdEncoding.EncodeToString(b.Bytes()))
c.Request = packed
return err
}
// RequestBytes is the job's request as a JSON object, unpacked when it travels packed.
func (c ComposeJob) RequestBytes() ([]byte, error) {
var packed string
if len(c.Request) == 0 || c.Request[0] != '"' {
return c.Request, nil
}
if err := json.Unmarshal(c.Request, &packed); err != nil || !strings.HasPrefix(packed, PackedRequestPrefix) {
return nil, fmt.Errorf("buildstep: a compose job's request is a string that is no packed request")
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(packed, PackedRequestPrefix))
if err != nil {
return nil, fmt.Errorf("buildstep: the packed request of a compose job is no base64: %w", err)
}
zr, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("buildstep: the packed request of a compose job is no gzip: %w", err)
}
return io.ReadAll(zr)
}
// AskOf is any seat's ask (or this form) as the neutral StepAsk: the one conversion, since the three seats' types
// are the part's one layout. A value that does not fit the layout is refused.
func AskOf[T any](seatAsk T) (StepAsk, error) {
raw, err := json.Marshal(seatAsk)
if err != nil {
return StepAsk{}, fmt.Errorf("buildstep: an ask does not encode: %w", err)
}
return DecodeStepAsk(raw)
}
// AskAs is the neutral ask as a seat's type T (the inverse of AskOf).
func AskAs[T any](a StepAsk) (T, error) {
var out T
raw, err := json.Marshal(a)
if err != nil {
return out, err
}
err = json.Unmarshal(raw, &out)
return out, err
}
func (a StepAsk) check() error {
if err := CheckAskID(a.ID); err != nil {
return err
}
if err := checkAskKind(a.Kind); err != nil {
return err
}
if err := checkAskLanguage(a.Language); err != nil {
return err
}
if err := meshkeys.CheckName("asker", a.Asker); err != nil {
return err
}
if a.At.IsZero() {
return fmt.Errorf("buildstep: the ask %s names no time", a.ID)
}
jobs := 0
for _, set := range []bool{a.Build != nil, a.Check != nil, a.Compose != nil, a.Run != nil, a.Step != nil} {
if set {
jobs++
}
}
switch {
case jobs != 1:
return fmt.Errorf("buildstep: the ask %s holds a build, a check, a compose, a run or a step, exactly one", a.ID)
case a.Compose != nil && (a.Kind != AskCheck || a.Language != AskGo):
return fmt.Errorf("buildstep: the ask %s is a compose, which the Go seat's check stream alone carries", a.ID)
case a.Run != nil && (a.Kind != AskCheck || a.Language != AskGo):
return fmt.Errorf("buildstep: the ask %s is a run, which the Go seat's check stream alone carries", a.ID)
case (a.Step != nil) != (a.Kind == AskStep):
return fmt.Errorf("buildstep: the ask %s is sent as %s and holds a pipeline step, or not: the accepted kind step carries a step alone", a.ID, a.Kind)
case a.Step != nil && a.Language == AskImage && a.Step.Step != StepLint:
return fmt.Errorf("buildstep: the ask %s is a %s step of an image, which has no tests", a.ID, a.Step.Step)
case a.Build != nil && a.Kind == AskRecheck:
return fmt.Errorf("buildstep: the ask %s is a build on the recheck stream, which carries checks alone", a.ID)
case a.Check != nil && a.Kind == AskDelivery:
return fmt.Errorf("buildstep: the ask %s is a check on the delivery stream, which carries trunk builds alone", a.ID)
case a.Check != nil && a.Language == AskImage:
return fmt.Errorf("buildstep: the ask %s is a check of an image, which has no tests", a.ID)
case len(a.Needs) > 0 && a.Check == nil:
return fmt.Errorf("buildstep: the ask %s names needs and is no check, whose tests alone need a node", a.ID)
case len(a.Packages) > 0 && a.Compose != nil:
return fmt.Errorf("buildstep: the ask %s is a compose and names package versions, which a compose does not take", a.ID)
}
if err := a.Packages.Check(); err != nil {
return fmt.Errorf("the ask %s: %w", a.ID, err)
}
for _, n := range a.Needs {
if err := CheckNeed(n); err != nil {
return fmt.Errorf("the ask %s: %w", a.ID, err)
}
}
switch {
case a.Build != nil:
return a.Build.check(a.ID)
case a.Compose != nil:
return a.Compose.check(a.ID)
case a.Run != nil:
return a.Run.check(a.ID)
case a.Step != nil:
return a.Step.check(a.ID)
}
return a.Check.check(a.ID)
}
func (c ComposeJob) check(id string) error {
if err := c.Fetch.check(id); err != nil {
return err
}
if c.Dir == "" || c.Dir != path.Clean(c.Dir) || strings.HasPrefix(c.Dir, "/") || c.Dir == ".." || strings.HasPrefix(c.Dir, "../") {
return fmt.Errorf("buildstep: the compose ask %s names no clean directory inside the repository (%q)", id, c.Dir)
}
if c.Package == "" {
return fmt.Errorf("buildstep: the compose ask %s names no package to build", id)
}
req, err := c.RequestBytes()
if err != nil {
return err
}
if !json.Valid(req) || len(req) == 0 || req[0] != '{' {
return fmt.Errorf("buildstep: the compose ask %s holds no request object", id)
}
return nil
}
func (b BuildJob) check(id string) error {
if err := meshkeys.CheckName("module", b.Module); err != nil {
return err
}
if len(b.Artifacts) == 0 {
return fmt.Errorf("buildstep: the build ask %s names no artifact", id)
}
fetch := false
for _, a := range b.Artifacts {
if err := meshkeys.CheckName("artifact", a.Artifact); err != nil {
return err
}
if a.Seat != "" && !slices.Contains(RegistrySeats, a.Seat) {
return fmt.Errorf("buildstep: the build ask %s publishes %s through %q, which is no registry seat (%s)", id,
a.Artifact, a.Seat, strings.Join(RegistrySeats, ", "))
}
if a.Version != "" && a.Seat == "" {
return fmt.Errorf("buildstep: the build ask %s gives %s the version %s and names no seat to publish it through",
id, a.Artifact, a.Version)
}
fetch = fetch || a.From == ""
}
if fetch {
if b.Path == "" {
return fmt.Errorf("buildstep: the build ask %s names no directory (path) for the module %s", id, b.Module)
}
if b.Fetch == nil {
return fmt.Errorf("buildstep: the ask %s fetches no repository <owner>/<name>", id)
}
return b.Fetch.check(id)
}
return nil
}
func (c CheckJob) check(id string) error {
if len(c.Levels) == 0 {
return fmt.Errorf("buildstep: the check ask %s names no level", id)
}
for _, l := range c.Levels {
if l != LevelUnit && l != LevelIntegration {
return fmt.Errorf("buildstep: the level %q is not %s or %s", l, LevelUnit, LevelIntegration)
}
}
for _, p := range c.Packages {
if p == "" || strings.ContainsAny(p, " \t\n") {
return fmt.Errorf("buildstep: the check ask %s names a package %q that is no import path", id, p)
}
}
if t := c.Toolchain; t != nil && (t.Language == "" || t.Version == "" || t.Recipe == "") {
return fmt.Errorf("buildstep: the check ask %s names a toolchain without its language, version and recipe", id)
}
seen := map[string]bool{}
for _, n := range c.NodeNames {
if err := meshkeys.CheckName("node", n); err != nil || strings.Contains(n, ",") || seen[n] {
return fmt.Errorf("buildstep: the check ask %s names the node %q, which is no node name or named twice", id, n)
}
seen[n] = true
}
return c.Fetch.check(id)
}
func (f Fetch) check(id string) error {
if f.Repository == "" || !strings.Contains(f.Repository, "/") {
return fmt.Errorf("buildstep: the ask %s fetches no repository <owner>/<name>", id)
}
if !askCommitOK.MatchString(f.Commit) {
return fmt.Errorf("buildstep: the ask %s fetches no full commit", id)
}
return nil
}
// EncodeStepAsk is a as the bytes the asker puts on a build seat's stream: stamped with the version and UTC, checked.
func EncodeStepAsk(a StepAsk) ([]byte, error) {
a.V = StepAskVersion
a.At = a.At.UTC()
if err := a.check(); err != nil {
return nil, err
}
return json.Marshal(a)
}
// DecodeStepAsk reads an ask, refusing another version, an unknown shape or a malformed ask.
func DecodeStepAsk(data []byte) (StepAsk, error) {
var probe struct {
V *int `json:"v"`
}
if err := json.Unmarshal(data, &probe); err != nil {
return StepAsk{}, fmt.Errorf("buildstep: an ask is not JSON: %w", err)
}
if probe.V == nil || *probe.V != StepAskVersion {
return StepAsk{}, fmt.Errorf("%w: an ask of version %v, this reader reads %d", ErrUnknownVersion, probe.V, StepAskVersion)
}
var a StepAsk
if err := json.Unmarshal(data, &a); err != nil {
return StepAsk{}, fmt.Errorf("buildstep: an ask does not fit its shape: %w", err)
}
if err := a.check(); err != nil {
return StepAsk{}, err
}
return a, nil
}
// PackageNeeds is what a package of a check needs of a node.
type PackageNeeds struct {
Package string `json:"package"`
Needs []string `json:"needs"`
}
// StepDeclined is the result of a step a holder declined: its node lacks what the ask needs.
type StepDeclined struct {
Declined bool `json:"declined"`
Needs []string `json:"needs"`
Lacks []string `json:"lacks"`
}
// DeclinedOf reads a refused step's result as a decline.
func DeclinedOf(step Step) (StepDeclined, bool) {
if step.State != StepRefused || len(step.Result) == 0 {
return StepDeclined{}, false
}
var d StepDeclined
if err := json.Unmarshal(step.Result, &d); err != nil || !d.Declined {
return StepDeclined{}, false
}
return d, true
}
// UnmetNeeds are the needs the levels' unmet packages name, sorted, once each.
func UnmetNeeds(levels []LevelAnswer) []string {
seen := map[string]bool{}
var out []string
for _, l := range levels {
for _, u := range l.Unmet {
for _, n := range u.Needs {
if !seen[n] {
seen[n] = true
out = append(out, n)
}
}
}
}
sort.Strings(out)
return out
}
// BuildAnswer is what a build ask's step answers.
type BuildAnswer struct {
Artifacts []AskBuilt `json:"artifacts"`
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
Imports []string `json:"imports,omitempty"`
OutOfStep []string `json:"out-of-step,omitempty"`
// Kept is the digest of the artifact this node kept for the artifact store's holder instead of storing it through
// the seat oci-artifact-registry (served by the verb kept-artifact; the keeping node is the step's own); empty when
// every artifact was stored.
Kept string `json:"kept,omitempty"`
}
// AskBuilt is one artifact a build made.
type AskBuilt struct {
Artifact string `json:"artifact"`
Digest string `json:"digest"`
Reference string `json:"reference,omitempty"`
// Resolved are the mesh packages the build resolved, one each, with the digest of the package's bytes as the build fetched
// them (design 47 G §466).
Resolved []AskResolved `json:"resolved,omitempty"`
}
// AskResolved is one mesh package a build resolved: its name, its version and the `sha256:` digest of its bytes.
type AskResolved struct {
Package string `json:"package"`
Version string `json:"version"`
Digest string `json:"digest"`
}
// CheckAnswer is what a check ask's step answers.
type CheckAnswer struct {
Fetch FetchAnswer `json:"fetch"`
Levels []LevelAnswer `json:"levels,omitempty"`
}
// FetchAnswer is what a build module's fetch tool answers, whole: the part's `FetchAnswer`. A check keeps it as the
// answer's fetch, so the checker reads a conflict (a head that does not merge is an answer, not an error), the changed
// paths, the programs and the trees from it.
type FetchAnswer struct {
Workspace string `json:"workspace"`
Commit string `json:"commit"`
Modules []string `json:"modules"`
// The merge preview, only when the call gave a base.
Base string `json:"base,omitempty"`
Merge string `json:"merge,omitempty"`
Conflicts []string `json:"conflicts,omitempty"`
Changed []string `json:"changed,omitempty"`
Programs []Program `json:"programs,omitempty"`
Trees map[string]ModuleTree `json:"trees,omitempty"`
// The Go module's.
Beside []PlacedBeside `json:"beside,omitempty"`
Packages []TakenVersion `json:"packages,omitempty"`
// The TypeScript module's.
Installed []string `json:"installed,omitempty"`
Refused []FetchRefusal `json:"refused,omitempty"`
Group string `json:"group,omitempty"`
}
// Program is a changed file that is a compiled program (issue 1577).
type Program struct {
Path string `json:"path"`
Kind string `json:"kind"` // ELF, Mach-O or PE
Commit string `json:"commit,omitempty"`
}
// PlacedBeside is a sibling repository placed as a plain directory under the workspace's beside directory.
type PlacedBeside struct {
Repository string `json:"repository"`
Commit string `json:"commit"`
Dir string `json:"dir"`
}
// TakenVersion is, of a directory whose go.mod requires an asked mesh package, the version it is built against.
type TakenVersion struct {
Dir string `json:"dir"`
Package string `json:"package"`
Asked string `json:"asked"`
Named string `json:"named"`
Built string `json:"built"`
Sum string `json:"sum,omitempty"`
Said string `json:"said,omitempty"`
}
// FetchRefusal is a TypeScript module whose packages the fetch did not install, with why.
type FetchRefusal struct {
Module string `json:"module"`
Reason string `json:"reason"`
}
// StepResult is what any step answered: one layout for the five kinds, as the seats' `StepResult` (the fields of the
// kinds do not meet). A step's result bytes read into it strictly.
type StepResult struct {
Artifacts []AskBuilt `json:"artifacts,omitempty"`
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
Imports []string `json:"imports,omitempty"`
OutOfStep []string `json:"out-of-step,omitempty"`
Kept string `json:"kept,omitempty"`
Fetch *FetchAnswer `json:"fetch,omitempty"`
Levels []LevelAnswer `json:"levels,omitempty"`
Built bool `json:"built,omitempty"`
Key string `json:"key,omitempty"`
Verdict json.RawMessage `json:"verdict,omitempty"`
Exit int `json:"exit,omitempty"`
Output json.RawMessage `json:"output,omitempty"`
Said string `json:"said,omitempty"`
Declined bool `json:"declined,omitempty"`
Needs []string `json:"needs,omitempty"`
Lacks []string `json:"lacks,omitempty"`
}
// ComposeAnswer is what a compose ask's step answers.
type ComposeAnswer struct {
Built bool `json:"built"`
Key string `json:"key,omitempty"`
Verdict json.RawMessage `json:"verdict,omitempty"`
}
// LevelAnswer is one level of a check.
type LevelAnswer struct {
Level string `json:"level"`
Judged string `json:"judged,omitempty"`
Digest *LevelDigest `json:"digest,omitempty"`
Kept []KeptTaken `json:"kept,omitempty"`
Tests []json.RawMessage `json:"tests,omitempty"`
Unmet []PackageNeeds `json:"unmet,omitempty"`
}
// LevelDigest is the digest of a level's tests by package.
type LevelDigest struct {
Level string `json:"level,omitempty"`
Packages []PackageDigest `json:"packages,omitempty"`
Beside []string `json:"beside,omitempty"`
WithoutTests []string `json:"without_tests,omitempty"`
JudgedBy string `json:"judged_by,omitempty"`
Needs []PackageNeeds `json:"needs,omitempty"`
}
// PackageDigest is the digest of one package's tests.
type PackageDigest struct {
Package string `json:"package"`
Digest string `json:"digest"`
}
// KeptTaken is a package whose kept verdict a level took instead of running its tests.
type KeptTaken struct {
Package string `json:"package"`
Digest string `json:"digest"`
Tests int `json:"tests"`
}
// UnmarshalJSON reads the packages as the list or as the older map by package.
func (d *LevelDigest) UnmarshalJSON(raw []byte) error {
var v struct {
Level string `json:"level"`
Packages json.RawMessage `json:"packages"`
Beside []string `json:"beside"`
WithoutTests []string `json:"without_tests"`
JudgedBy string `json:"judged_by"`
Needs []PackageNeeds `json:"needs"`
}
if err := json.Unmarshal(raw, &v); err != nil {
return err
}
var pkgs []PackageDigest
if p := strings.TrimSpace(string(v.Packages)); p != "" && p != "null" {
if strings.HasPrefix(p, "{") {
var m map[string]string
if err := json.Unmarshal(v.Packages, &m); err != nil {
return fmt.Errorf("a digest's packages: %w", err)
}
for pkg, digest := range m {
pkgs = append(pkgs, PackageDigest{Package: pkg, Digest: digest})
}
} else if err := json.Unmarshal(v.Packages, &pkgs); err != nil {
return fmt.Errorf("a digest's packages: %w", err)
}
}
sort.Slice(pkgs, func(i, j int) bool { return pkgs[i].Package < pkgs[j].Package })
*d = LevelDigest{Level: v.Level, Packages: pkgs, Beside: v.Beside, WithoutTests: v.WithoutTests, JudgedBy: v.JudgedBy, Needs: v.Needs}
return nil
}
// NeedsOf are the needs of a package in the digest.
func (d *LevelDigest) NeedsOf(pkg string) []string {
if d == nil {
return nil
}
for _, n := range d.Needs {
if n.Package == pkg {
return n.Needs
}
}
return nil
}
// Map is the digest as digest by package.
func (d *LevelDigest) Map() map[string]string {
if d == nil || len(d.Packages) == 0 {
return nil
}
m := make(map[string]string, len(d.Packages))
for _, p := range d.Packages {
m[p.Package] = p.Digest
}
return m
}
-622
View File
@@ -1,622 +0,0 @@
package buildstep
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
const (
testCommit = "0123456789abcdef0123456789abcdef01234567"
testAskID = "m2kx9a1b3c4d5e"
)
func goodBuild() StepAsk {
return StepAsk{ID: testAskID, Kind: AskDelivery, Language: AskGo, Asker: "mesh-delivery-builder",
At: time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC),
Build: &BuildJob{Module: "nats", Path: "modules/nats", Fetch: &Fetch{Repository: "novox/mesh-catalog", Commit: testCommit},
Artifacts: []AskArtifact{{Artifact: "go"}}}}
}
func goodCheck() StepAsk {
return StepAsk{ID: testAskID, Kind: AskCheck, Language: AskGo, Asker: "mesh-delivery-checker",
At: time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC),
Check: &CheckJob{Fetch: Fetch{Repository: "novox/mesh-catalog", Commit: testCommit}, Levels: []string{LevelUnit}}}
}
// runAsk is the checker's run of a checking program built at a mesh-delivery head, over two heads (issue 1921, B0).
func runAsk() StepAsk {
in, err := RunInputOf("seat:mesh-delivery-checker.input", []byte(`{"v":1}`))
if err != nil {
panic(err)
}
return StepAsk{ID: testAskID, Kind: AskCheck, Language: AskGo, Asker: "mesh-delivery-checker",
At: time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC),
Run: &RunJob{Program: RunProgram{Repository: "novox/mesh-delivery", Commit: testCommit, Dir: "modules/mesh-delivery-checker",
Package: "./cmd/mesh-checking-program"},
Heads: []RunHead{{Repository: "novox/mesh-delivery", Commit: testCommit}, {Repository: "novox/mesh-sdk", Commit: testCommit}},
Input: in, Args: []string{"-verdict"}}}
}
// stepAsk is the runner's unit step of one artifact (086 A-D31): its kept result.
func stepAsk() StepAsk {
return StepAsk{ID: testAskID, Kind: AskStep, Language: AskGo, Asker: "mesh-delivery-pipeline",
At: time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC),
Step: &StepRun{Pipeline: "main.12.nats", Step: StepUnit, Module: "nats", Artifact: "nats:program", Branch: "main",
Commit: testCommit, Revision: 12, Fingerprint: "fp-0123", Fetch: Fetch{Repository: "novox/mesh-catalog", Commit: testCommit},
Kept: []KeptResult{{Package: "./modules/nats/a", Digest: "sha256:bbbb", Level: StepUnit}}}}
}
// The ask the three build seats share is one neutral form: it round-trips, and every ill-formed ask is refused,
// naming what is wrong (the rules of the old delivery.StepAsk, now the shared runner's).
func TestAskCheckAndRoundTrip(t *testing.T) {
for _, a := range []StepAsk{goodBuild(), goodCheck(), runAsk(), stepAsk()} {
raw, err := EncodeStepAsk(a)
if err != nil {
t.Fatal(err)
}
back, err := DecodeStepAsk(raw)
if err != nil || back.ID != a.ID || back.V != StepAskVersion {
t.Fatalf("round trip: %+v, %v", back, err)
}
}
for _, c := range []struct {
name string
edit func(*StepAsk)
want string
}{
{"no id", func(a *StepAsk) { a.ID = "x" }, "not an ask id"},
{"unknown kind", func(a *StepAsk) { a.Kind = "build" }, "ask kind"},
{"unknown language", func(a *StepAsk) { a.Language = "rust" }, "ask language"},
{"no time", func(a *StepAsk) { a.At = time.Time{} }, "names no time"},
{"recheck build", func(a *StepAsk) { a.Kind = AskRecheck }, "recheck stream"},
{"two jobs", func(a *StepAsk) { a.Check = goodCheck().Check }, "exactly one"},
{"needs on a build", func(a *StepAsk) { a.Needs = []string{NeedNodeBuildNode} }, "names needs"},
{"unknown registry seat", func(a *StepAsk) { a.Build.Artifacts[0].Seat = "somewhere" }, "no registry seat"},
{"version without seat", func(a *StepAsk) { a.Build.Artifacts[0].Version = "1.0.0" }, "names no seat"},
{"no path", func(a *StepAsk) { a.Build.Path = "" }, "names no directory"},
{"short commit", func(a *StepAsk) { a.Build.Fetch.Commit = "abc" }, "full commit"},
{"bad package pin", func(a *StepAsk) { a.Packages = PackageVersions{"m": "main"} }, "neither a full commit"},
} {
a := goodBuild()
c.edit(&a)
if _, err := EncodeStepAsk(a); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: %v, want %q", c.name, err, c.want)
}
}
// 1921 (B0, G): a run ask goes only on the Go seat's check stream, alone, builds a clean package at a full commit
// over heads named once at full commits, and names its input on a seat's verb by a digest within its bound.
for _, c := range []struct {
name string
edit func(*StepAsk)
want string
}{
{"run beside a check", func(a *StepAsk) { a.Check = goodCheck().Check }, "or a step, exactly one"},
{"run on the delivery stream", func(a *StepAsk) { a.Kind = AskDelivery }, "is a run"},
{"run on the Node seat", func(a *StepAsk) { a.Language = AskNode }, "is a run"},
{"run at a short commit", func(a *StepAsk) { a.Run.Program.Commit = "0123456" }, "no full commit"},
{"run outside the repository", func(a *StepAsk) { a.Run.Program.Dir = "../x" }, "no clean directory"},
{"run of no package", func(a *StepAsk) { a.Run.Program.Package = "" }, "no package"},
{"run over no head", func(a *StepAsk) { a.Run.Heads = nil }, "no head"},
{"run over a head twice", func(a *StepAsk) { a.Run.Heads = append(a.Run.Heads, a.Run.Heads[0]) }, "twice"},
{"run over a branch", func(a *StepAsk) { a.Run.Heads[1].Commit = "main" }, "novox/mesh-sdk at no full commit"},
{"input on a state", func(a *StepAsk) { a.Run.Input.Verb = "mesh-delivery-checker.inputs" }, "no seat:<seat>.<verb>"},
{"input on one machine", func(a *StepAsk) { a.Run.Input.Verb = "seat:mesh-delivery-checker.input@ace" }, "no seat:<seat>.<verb>"},
{"input by no digest", func(a *StepAsk) { a.Run.Input.Digest = "d1" }, "no sha256 digest"},
{"input over its bound", func(a *StepAsk) { a.Run.Input.Size = RunInputBound + 1 }, "outside 1 to"},
{"argument of the shell", func(a *StepAsk) { a.Run.Args = []string{"-x; rm"} }, "no word or flag"},
} {
a := runAsk()
c.edit(&a)
if _, err := EncodeStepAsk(a); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: %v, want %q", c.name, err, c.want)
}
}
// 086 A-D31: a pipeline step is the accepted kind step alone, names its artifact of its module at a full commit and
// fingerprint, and carries the registrations' names; a rerun names the caller the runtime proved.
for _, c := range []struct {
name string
edit func(*StepAsk)
want string
}{
{"step beside a check", func(a *StepAsk) { a.Check = goodCheck().Check }, "exactly one"},
{"step sent as a check", func(a *StepAsk) { a.Kind = AskCheck }, "carries a step alone"},
{"check sent as a step", func(a *StepAsk) { a.Step, a.Check = nil, goodCheck().Check }, "carries a step alone"},
{"unit step of an image", func(a *StepAsk) { a.Language = AskImage }, "has no tests"},
{"unknown step", func(a *StepAsk) { a.Step.Step = "review" }, `the step "review"`},
{"artifact of another module", func(a *StepAsk) { a.Step.Artifact = "nats-tools:program" }, "not nats:<artifact>"},
{"step at a branch", func(a *StepAsk) { a.Step.Commit = "main" }, "no full commit"},
{"no fingerprint", func(a *StepAsk) { a.Step.Fingerprint = "" }, "no build-input fingerprint"},
{"rerun with no caller", func(a *StepAsk) { a.Step.Rerun = true }, "rerun with no caller"},
} {
a := stepAsk()
c.edit(&a)
if _, err := EncodeStepAsk(a); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: %v, want %q", c.name, err, c.want)
}
}
if a := stepAsk(); !a.Step.Skips("./modules/nats/a", "sha256:bbbb") || a.Step.Skips("./modules/nats/a", "sha256:cccc") {
t.Error("a kept result skips its package at its digest and level only")
}
if _, err := RunInputOf("seat:mesh-delivery-checker.input", make([]byte, RunInputBound+1)); err == nil || !strings.Contains(err.Error(), "262145 bytes") {
t.Errorf("an input over its bound: %v", err)
}
in := runAsk().Run.Input
if err := in.Verify([]byte(`{"v":1}`)); err != nil {
t.Errorf("the input's own bytes: %v", err)
}
if err := in.Verify([]byte(`{"v":2}`)); err == nil || !strings.Contains(err.Error(), "not the one the ask names") {
t.Errorf("bytes that are not the digest: %v", err)
}
chk := goodCheck()
chk.Check.Levels = []string{"nightly"}
if _, err := EncodeStepAsk(chk); err == nil || !strings.Contains(err.Error(), "nightly") {
t.Errorf("a level: %v", err)
}
chk = goodCheck()
chk.Check.Toolchain = &ToolchainUsed{Language: "go", Version: "1.26.0", Recipe: "2"}
raw, err := EncodeStepAsk(chk)
if err != nil {
t.Fatal(err)
}
if back, err := DecodeStepAsk(raw); err != nil || back.Check.Toolchain == nil || back.Check.Toolchain.Version != "1.26.0" {
t.Errorf("the check's toolchain is lost in a round trip: %+v, %v", back.Check, err)
}
chk.Check.Toolchain.Recipe = ""
if _, err := EncodeStepAsk(chk); err == nil || !strings.Contains(err.Error(), "toolchain") {
t.Errorf("a toolchain without a recipe: %v", err)
}
chk = goodCheck()
chk.Language = AskImage
if _, err := EncodeStepAsk(chk); err == nil || !strings.Contains(err.Error(), "no tests") {
t.Errorf("an image check: %v", err)
}
if _, err := DecodeStepAsk([]byte(`{"v":2}`)); !errors.Is(err, ErrUnknownVersion) {
t.Errorf("another version: %v", err)
}
// Issue 1966: a compose job's request travels packed when it passes the bus's message limit, and reads back as sent.
t.Run("1966: a compose request travels packed", func(t *testing.T) {
obj := []byte(`{"v":1,"input":{"nodes":[]}}`)
job := ComposeJob{Fetch: Fetch{Repository: "novox/mesh-host", Commit: strings.Repeat("a", 40)}, Dir: ".", Package: "p"}
if err := job.PackRequest(obj); err != nil {
t.Fatal(err)
}
if got, err := job.RequestBytes(); err != nil || string(got) != string(obj) {
t.Errorf("read back %s, %v", got, err)
}
if err := job.check("ask"); err != nil {
t.Errorf("a packed request is refused: %v", err)
}
job.Request = json.RawMessage(`"not packed"`)
if err := job.check("ask"); err == nil {
t.Errorf("a string that is no packed request is accepted")
}
job.Request = obj
if got, err := job.RequestBytes(); err != nil || string(got) != string(obj) {
t.Errorf("a whole request read back %s, %v", got, err)
}
})
}
// The seat's value and the neutral form are the same JSON: AskOf takes any seat's type (here its shape, with a
// pointer time), AskAs gives one back.
func TestAskOfAnySeatsType(t *testing.T) {
type seatAsk struct {
V int64 `json:"v,omitempty"`
ID string `json:"id"`
Kind string `json:"kind"`
Lang string `json:"language"`
Asker string `json:"asker"`
At *time.Time `json:"at,omitempty"`
Check *struct {
Fetch Fetch `json:"fetch"`
Levels []string `json:"levels"`
} `json:"check,omitempty"`
}
at := time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC)
s := seatAsk{V: 1, ID: testAskID, Kind: AskCheck, Lang: AskGo, Asker: "mesh-delivery-checker", At: &at}
s.Check = &struct {
Fetch Fetch `json:"fetch"`
Levels []string `json:"levels"`
}{Fetch{Repository: "novox/mesh-catalog", Commit: testCommit}, []string{LevelUnit}}
a, err := AskOf(s)
if err != nil || a.Check == nil || !a.At.Equal(at) || a.Check.Fetch.Commit != testCommit {
t.Fatalf("%+v %v", a, err)
}
back, err := AskAs[seatAsk](a)
if err != nil || back.ID != s.ID || !back.At.Equal(at) {
t.Fatalf("%+v %v", back, err)
}
s.Check = nil
if _, err := AskOf(s); err == nil {
t.Error("an ask with no job is accepted")
}
}
func TestAskSubjectsStreamsAndKeys(t *testing.T) {
for _, l := range AskLanguages {
for _, k := range AskKinds {
subj, err := AskSubject(l, k)
if err != nil {
t.Fatal(err)
}
gl, gk, err := ParseAskSubject(subj)
if err != nil || gl != l || gk != k {
t.Errorf("%s: %s %s %v", subj, gl, gk, err)
}
}
}
if got, _ := AskWorker(AskGo, AskCheck); got != "SEAT_NODE_BUILD_GO_CHECK_worker" {
t.Errorf("worker %q", got)
}
if got, _ := AskStream(AskImage); got != "SEAT_NODE_BUILD_IMAGE" {
t.Errorf("stream %q", got)
}
if _, _, err := ParseAskSubject("mesh.seat.node-build-go.accept.nothing"); err == nil {
t.Error("an unknown kind parses")
}
if _, err := AskSubject("rust", AskCheck); err == nil {
t.Error("an unknown language has a subject")
}
if k, err := AskStepKey("ace", testAskID); err != nil || k != "ace."+testAskID {
t.Errorf("%q %v", k, err)
}
if w, _ := AskStepWatch(testAskID); w != "*."+testAskID {
t.Errorf("watch %q", w)
}
if k, _ := PauseKey("ace"); k != "paused.ace" {
t.Errorf("pause key %q", k)
}
if k, _ := CapacityKey("ace"); k != "capacity.ace" {
t.Errorf("capacity key %q", k)
}
if _, err := CapacityKey("a.b"); err == nil {
t.Error("a dotted node keys")
}
// 086 A-D31: a step's end is said on its own node's subject, and one naming another node is refused.
subj, err := StepEndedSubject(AskNode, "ace")
if err != nil || subj != "mesh.seat.node-build-node.event.step-ended.ace" {
t.Fatalf("step-ended subject %q %v", subj, err)
}
if l, n, err := ParseStepEndedSubject(subj); err != nil || l != AskNode || n != "ace" {
t.Errorf("parse %q: %s %s %v", subj, l, n, err)
}
end, err := EndOf(stepAsk(), "ace", OutcomePassed)
if err != nil {
t.Fatal(err)
}
end.Tests = &TestCounts{Unit: 14}
raw, err := EncodeStepEnded(end)
if err != nil {
t.Fatal(err)
}
goSubj, _ := StepEndedSubject(AskGo, "ace")
if back, err := DecodeStepEnded(goSubj, raw); err != nil || back.Fingerprint != "fp-0123" || back.Tests.Unit != 14 ||
back.Asker != stepAsk().Asker || back.Ask != testAskID {
t.Errorf("round trip: %+v %v", back, err)
}
// 1966/CT12 (G §548, §602): the end of an ask outside a pipeline names its asker, the ask and when, never a commit.
at := time.Date(2026, 11, 11, 10, 3, 0, 0, time.UTC)
build := StepEnded{ID: testAskID, Asker: "mesh-delivery-builder", Ask: testAskID, Node: "ace", Outcome: OutcomePassed, At: at}
if raw, err := EncodeStepEnded(build); err != nil || strings.Contains(string(raw), "commit") {
t.Errorf("a builder's build end: %s %v", raw, err)
} else if back, err := DecodeStepEnded(goSubj, raw); err != nil || back.Asker != "mesh-delivery-builder" || !back.At.Equal(at) {
t.Errorf("a builder's build end reads back as %+v %v", back, err)
}
for name, bad := range map[string]func(*StepEnded){
"no asker": func(e *StepEnded) { e.Asker = "" },
"no time": func(e *StepEnded) { e.At = time.Time{} },
"a commit": func(e *StepEnded) { e.Commit = "0123456789abcdef0123456789abcdef01234567" },
"a fingerprint": func(e *StepEnded) { e.Fingerprint = "fp-0123" },
} {
e := build
bad(&e)
if _, err := EncodeStepEnded(e); err == nil {
t.Errorf("an end outside a pipeline with %s is said", name)
}
}
g14, _ := StepEndedSubject(AskGo, "g14")
if _, err := DecodeStepEnded(g14, raw); err == nil || !strings.Contains(err.Error(), "said on g14's subject") {
t.Errorf("an end said on another node's subject: %v", err)
}
failed, _ := EndOf(stepAsk(), "ace", OutcomeCouldNotRun)
if _, err := EncodeStepEnded(failed); err == nil || !strings.Contains(err.Error(), "and not why") {
t.Errorf("could not run without why: %v", err)
}
if _, err := EndOf(goodCheck(), "ace", OutcomePassed); err == nil {
t.Error("a check has a step's end")
}
}
func TestDeclinesNeedsAndLevelDigest(t *testing.T) {
// design 47, the artifact store's holder takes its own new build (test 60): only the store holder's trunk build is
// kept, and kept-artifact answers the kept one or refuses another digest, a module claiming no store, one not kept.
t.Run("kept-artifact", func(t *testing.T) {
holder := catalogue.Manifest{Module: "demo", Claims: []catalogue.Claim{{Name: StoreSeat, Scope: "mesh"}}}
if KeepOf(true, holder, "fp1") == nil || KeepOf(false, holder, "fp1") != nil || KeepOf(true, catalogue.Manifest{Module: "web"}, "fp1") != nil {
t.Error("only the store holder's trunk build is kept")
}
hex := strings.Repeat("a", 64)
name, desc := KeptObject(KeptFor{Module: "demo", Fp: "fp1"}, "ace", "sha256:"+hex)
at := time.Date(2026, 11, 10, 10, 0, 0, 0, time.UTC)
kept := KeptBuildsOf([]buscalls.ObjectInfo{{Name: name, Size: 9, Description: desc, Modified: at},
{Name: "bb", Description: `{"module":"demo","fp":"fp1","node":"g14"}`}}, "ace")
if len(kept) != 1 || kept[0].Digest != hex || kept[0].Bytes != 9 {
t.Fatalf("kept on ace: %+v", kept)
}
claims := func(m string) (bool, error) {
man := `{"module":"` + m + `"}`
if m != "other" {
man = `{"module":"` + m + `","claims":[{"name":"oci-artifact-registry","scope":"mesh"}]}`
}
return ClaimsStoreOf(m, []byte(`{"module":{"module":"`+m+`","manifest":`+man+`}}`))
}
for _, c := range []struct{ name, module, digest, refused, store string }{
{"the kept build", "demo", hex, "", "mesh-build-go_kept-builds"},
{"another digest", "demo", strings.Repeat("b", 64), KeptRefusedDigestDiffers, ""},
{"a module claiming no store", "other", hex, KeptRefusedClaimsNoStore, ""},
{"a holder not kept here", "lost", hex, KeptRefusedNotKept, ""},
} {
a := KeptArtifact(c.module, "fp1", c.digest, kept, "mesh-build-go_kept-builds", claims)
if a.Refused != c.refused || a.Store != c.store || a.Error != "" || (c.refused != "" && !strings.Contains(a.Words, c.module)) {
t.Errorf("%s: %+v", c.name, a)
}
}
if a := KeptArtifact("lost", "fp1", hex, kept, "s", func(string) (bool, error) { return false, errors.New("no answer") }); !strings.Contains(a.Error, "no answer") {
t.Errorf("an unanswered catalog: %+v", a)
}
})
if got := Lacks([]string{NeedNodeBuildNode}, nil); len(got) != 1 {
t.Errorf("a nil has lacks all: %v", got)
}
if got := Lacks([]string{NeedNodeBuildNode}, func(string) bool { return true }); len(got) != 0 {
t.Errorf("%v", got)
}
step := Step{State: StepRefused, Result: json.RawMessage(`{"declined":true,"needs":["node-build-node"],"lacks":["node-build-node"]}`)}
if d, ok := DeclinedOf(step); !ok || d.Lacks[0] != NeedNodeBuildNode {
t.Errorf("%+v %v", d, ok)
}
step.State = StepFailed
if _, ok := DeclinedOf(step); ok {
t.Error("a failed step is a decline")
}
var l LevelAnswer
raw := `{"level":"unit","digest":{"packages":{"b":"2","a":"1"},"needs":[{"package":"a","needs":["node-build-node"]}]},"unmet":[{"package":"a","needs":["node-build-node"]}]}`
if err := json.Unmarshal([]byte(raw), &l); err != nil {
t.Fatal(err)
}
if p := l.Digest.Packages; len(p) != 2 || p[0].Package != "a" || l.Digest.Map()["b"] != "2" || l.Digest.NeedsOf("a")[0] != NeedNodeBuildNode {
t.Errorf("%+v", l.Digest)
}
if got := UnmetNeeds([]LevelAnswer{l, l}); len(got) != 1 {
t.Errorf("%v", got)
}
}
func TestPauseCapacityAndComposerKey(t *testing.T) {
raw, err := EncodePause(Pause{Paused: true, By: "operator@shanks", At: time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC)})
if err != nil {
t.Fatal(err)
}
if p, err := DecodePause(raw); err != nil || !p.Paused || p.V != Version {
t.Fatalf("%+v %v", p, err)
}
if _, err := DecodePause([]byte(`{"v":9}`)); !errors.Is(err, ErrUnknownVersion) {
t.Errorf("%v", err)
}
craw, _ := EncodeCapacity(Capacity{Effective: 2, Configured: 2, Why: "fits"})
if c, err := DecodeCapacity(craw); err != nil || c.Effective != 2 {
t.Fatalf("%+v %v", c, err)
}
tc := ToolchainUsed{Language: "go", Version: "1.26.0", Recipe: "1"}
if k := ComposerKey("novox/r", testCommit, "d", "p", tc, nil); k != ComposerKey("novox/r", testCommit, "d", "p", tc, nil) || !strings.HasPrefix(k, "composer-") || len(k) != len("composer-")+16 {
t.Errorf("composer key %q", k)
}
if ComposerKey("novox/r", testCommit, "d", "p", tc, nil) == ComposerKey("novox/r", testCommit, "d2", "p", tc, nil) {
t.Error("the directory is not in the key")
}
// 1921: the asked versions are in the key, in any order of naming; none gives the key without them.
a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
k := ComposerKey("novox/r", testCommit, "d", "p", tc, PackageVersions{"m/x": a, "m/y": b})
if k != ComposerKey("novox/r", testCommit, "d", "p", tc, PackageVersions{"m/y": b, "m/x": a}) {
t.Error("the key depends on the order of the versions")
}
if k == ComposerKey("novox/r", testCommit, "d", "p", tc, PackageVersions{"m/x": b, "m/y": a}) || k == ComposerKey("novox/r", testCommit, "d", "p", tc, nil) {
t.Error("other versions, or none, share the key")
}
// 1921 (B0): a run's program is kept the same way, under a key of its own kind.
p := RunProgram{Repository: "novox/mesh-delivery", Commit: testCommit, Dir: "modules/mesh-delivery-checker", Package: "p"}
if rk := RunKey(p, tc, nil); !strings.HasPrefix(rk, "program-") || len(rk) != len("program-")+16 || rk != RunKey(p, tc, nil) ||
RunKey(p, tc, PackageVersions{"m/x": a}) == rk {
t.Errorf("run key = %q", rk)
}
if ComposerKey("novox/r", testCommit, "d", "p", tc, nil) != ComposerKey("novox/r", testCommit, "d", "p", tc, PackageVersions{}) {
t.Error("an empty ask changed the key")
}
// Issue 1748 (ADR 0664): a transport fault is told from a wrong source by its words; a step given again is no end; the
// bus waits 1 minute after the first run and 4 after the second.
for words, want := range map[string]bool{
`Get "https://proxy": dial tcp: lookup proxy.golang.org: i/o timeout`: true,
`Head http://store.internal:5100/v2/x: dial tcp 10.10.0.1:5100: i/o timeout`: true,
"kex_exchange_identification: read: Connection reset by peer": true,
"Connection closed by 10.10.0.1 port 222": true,
"npm error code EAI_AGAIN": true,
"npm error code ETIMEDOUT": true,
"npm error code ECONNRESET": true,
"fatal: unable to access the forge: Could not resolve host: mesh-forge": true,
"Get \"https://example.com/x.tar.gz\": context deadline exceeded (Client.Timeout exceeded while awaiting headers)": true,
(&HolderSilent{Seat: "go-package-registry", Holder: "gopkgs", Node: "ace"}).Error(): true,
`invalid version: Get "https://proxy.golang.org/x/@v/y.info": dial tcp [2a00::1]:443: connect: network is unreachable`: true,
"dial tcp 10.10.0.1:22: connect: No route to host": true,
"nats: no responders available for request": false,
"fatal: unknown revision or path not in the working tree": false,
"verifying module: checksum mismatch": false,
"./main.go:3:1: syntax error: unexpected }": false,
} {
if PassingCause(words) != want {
t.Errorf("PassingCause(%q) = %v, want %v", words, !want, want)
}
}
if !IsPassing(fmt.Errorf("fetch: %w", &HolderSilent{Seat: "s"})) || IsPassing(errors.New("i/o timeout")) {
t.Error("a HolderSilent is a Passing error and a bare error is none")
}
if Ended(Step{State: StepRunning}) || Ended(Step{State: StepAgain}) || !Ended(Step{State: StepPassed}) || !Ended(Step{State: StepFailed}) {
t.Error("Ended: running and again are no end")
}
// Review 1: a step ended by the seat's verb drop is the state dropped, an end that decodes (ADR 0664 §4).
if raw, err := EncodeStep(Step{ID: "mvl0frv18d1990", Tool: "go ask", Node: "ace", State: StepDropped, Reason: "withdrawn"}); err != nil || !Ended(Step{State: StepDropped}) {
t.Errorf("a dropped step: %v (%s)", err, raw)
}
if AgainAfter(1) != time.Minute || AgainAfter(2) != 4*time.Minute {
t.Errorf("AgainAfter = %v, %v", AgainAfter(1), AgainAfter(2))
}
}
// The part `build-step` is one layout for the three build seats: each seat's fixtures read strictly in the neutral
// forms (an unknown field, or a field this package lacks, fails). Where the generator cannot share a part, this is
// what holds the three seats' types and this form equal.
func TestTheThreeSeatsFixturesFitTheNeutralForms(t *testing.T) {
strict := func(t *testing.T, raw json.RawMessage, into any) {
t.Helper()
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(into); err != nil {
t.Error(err)
}
}
seen := 0
for _, seat := range []string{"node-build-go", "node-build-image", "node-build-node"} {
raw, err := os.ReadFile(filepath.Join("..", "..", "contracts", "seats", seat, "fixtures", "states.json"))
if err != nil {
t.Fatal(err)
}
var fixtures []struct {
Name string `json:"name"`
Of string `json:"of"`
Given json.RawMessage `json:"given"`
}
if err := json.Unmarshal(raw, &fixtures); err != nil {
t.Fatal(err)
}
for _, f := range fixtures {
t.Run(seat+"/"+f.Name, func(t *testing.T) {
switch {
case strings.HasPrefix(f.Of, "accept:"):
seen++
strict(t, f.Given, &StepAsk{})
case strings.HasPrefix(f.Of, "state:pauses/paused."):
seen++
strict(t, f.Given, &Pause{})
case strings.HasPrefix(f.Of, "state:pauses/dropped."):
seen++ // its layout is the generated contracts' Drop, which seatgen checks the fixture against
case strings.HasPrefix(f.Of, "state:pauses/capacity."):
seen++
strict(t, f.Given, &Capacity{})
case strings.HasPrefix(f.Of, "state:steps/"):
seen++
strict(t, f.Given, &Step{})
var st Step
if err := json.Unmarshal(f.Given, &st); err == nil && len(st.Result) > 0 {
// a step's result keeps what the tool answered, whole (the fetch tool's answer too)
strict(t, st.Result, &StepResult{})
}
}
})
}
}
// 086 A-D31: each seat's step-ended fixtures are the neutral StepEnded, said on their node's subject.
ended := 0
for _, seat := range []string{"node-build-go", "node-build-image", "node-build-node"} {
raw, err := os.ReadFile(filepath.Join("..", "..", "contracts", "seats", seat, "fixtures", "events.json"))
if err != nil {
t.Fatal(err)
}
var fixtures []struct {
Name string `json:"name"`
Of string `json:"of"`
Subject string `json:"subject"`
Given json.RawMessage `json:"given"`
}
if err := json.Unmarshal(raw, &fixtures); err != nil {
t.Fatal(err)
}
for _, f := range fixtures {
if f.Of == "event:step-ended" {
ended++
strict(t, f.Given, &StepEnded{})
if _, err := DecodeStepEnded(f.Subject, f.Given); err != nil {
t.Errorf("%s/%s: %v", seat, f.Name, err)
}
}
}
}
if ended < 6 {
t.Errorf("only %d step-ended fixtures read", ended)
}
if seen < 12 {
t.Errorf("only %d fixtures read", seen)
}
}
// 1966 (G §465, §466): a build ask's fetch names each package member's build, a built artifact the packages it resolved,
// and the toolchain the building node's digest, each read whole by the neutral forms.
func TestFetchBuildsResolvedAndToolchainDigestAreRead(t *testing.T) {
strict := func(raw string, into any) {
t.Helper()
dec := json.NewDecoder(strings.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(into); err != nil {
t.Error(err)
}
}
var job BuildJob
strict(`{"module":"m","fetch":{"repository":"r","commit":"c","builds":[{"package":"example.org/m/go","module":"m","artifact":"go-m","digest":"sha256:aa"}]},"artifacts":[]}`, &job)
if job.Fetch == nil || len(job.Fetch.Builds) != 1 || job.Fetch.Builds[0] != (FetchBuild{Package: "example.org/m/go", Module: "m", Artifact: "go-m", Digest: "sha256:aa"}) {
t.Errorf("fetch builds: %+v", job.Fetch)
}
var built AskBuilt
strict(`{"artifact":"go-m","digest":"sha256:bb","resolved":[{"package":"example.org/s/go","version":"0.1.4","digest":"sha256:cc"}]}`, &built)
if len(built.Resolved) != 1 || built.Resolved[0] != (AskResolved{Package: "example.org/s/go", Version: "0.1.4", Digest: "sha256:cc"}) {
t.Errorf("resolved: %+v", built)
}
var tc ToolchainUsed
strict(`{"language":"go","recipe":"r","version":"1.26.0","digest":"sha256:dd"}`, &tc)
if tc.Digest != "sha256:dd" {
t.Errorf("toolchain digest: %+v", tc)
}
}
// §481, §600: a queue's ask of an asker is put on accept.<queue>.<asker>, and both forms parse.
func TestAskSubjectBy(t *testing.T) {
got, err := AskSubjectBy(AskGo, AskDelivery, AskerBuilder)
if err != nil || got != "mesh.seat.node-build-go.accept.delivery.builder" {
t.Fatalf("%q %v", got, err)
}
for _, c := range []struct{ subject, language, kind, asker string }{
{got, "go", "delivery", "builder"},
{"mesh.seat.node-build-node.accept.check", "node", "check", ""},
} {
l, k, a, err := ParseAskSubjectBy(c.subject)
if err != nil || l != c.language || k != c.kind || a != c.asker {
t.Errorf("%s: %q %q %q %v", c.subject, l, k, a, err)
}
if l, k, err := ParseAskSubject(c.subject); err != nil || l != c.language || k != c.kind {
t.Errorf("%s: ParseAskSubject %q %q %v", c.subject, l, k, err)
}
}
if _, err := AskSubjectBy(AskGo, AskDelivery, "Bad.Name"); err == nil {
t.Error("a bad asker has a subject")
}
if _, _, _, err := ParseAskSubjectBy("mesh.seat.node-build-go.accept.delivery.builder.extra"); err == nil {
t.Error("a subject of four tokens after accept parses")
}
}
-33
View File
@@ -1,33 +0,0 @@
package buildstep
import (
"go/parser"
"go/token"
"path/filepath"
"strconv"
"strings"
"testing"
)
// The layouts, keys and codecs of this package are read by modules that never touch the bus (a composer's tool, the
// builder's published package): it imports neither the bus library nor mesh-sdk's runtime (the root package), whose
// part that runs is package buildrun's.
func TestThePackageIsFreeOfTheBus(t *testing.T) {
files, _ := filepath.Glob("*.go")
fset := token.NewFileSet()
for _, f := range files {
if strings.HasSuffix(f, "_test.go") {
continue
}
parsed, err := parser.ParseFile(fset, f, nil, parser.ImportsOnly)
if err != nil {
t.Fatal(err)
}
for _, imp := range parsed.Imports {
path, _ := strconv.Unquote(imp.Path.Value)
if strings.HasPrefix(path, "github.com/nats-io/") || path == "git.novox.be/novox/mesh-sdk/go" {
t.Errorf("%s imports %s, which reaches the bus", f, path)
}
}
}
}
-7
View File
@@ -1,7 +0,0 @@
package buildstep
// CapacitySetting is the build modules' setting of the node's build capacity (novox/hq ADR 0525 §5, ADR 0567 §12): how
// many asks the node takes at once, an integer config value set on each node's layer of mesh-config. No repository names
// a node: each build module declares it with the default 0, which pulls nothing, and the controller (or mesh-config)
// lays the node's value into the module's settings file.
const CapacitySetting = "capacity"
-5
View File
@@ -1,5 +0,0 @@
// Package buildstep is the contract of a build step every delivery part reads (novox/hq ADR 0593 §1): a step's id, the
// fetch request, a step a previous process left running and its end, a failure's words, a module tree's shape, the
// capacity setting and the launchers' names. The runner the build modules share is the Go build module's own package
// (mesh-catalog modules/mesh-build-go/buildstep), which imports this one.
package buildstep
-141
View File
@@ -1,141 +0,0 @@
package buildstep
import (
"fmt"
"strings"
"git.novox.be/novox/mesh-sdk/go/sdkversion"
)
// Failure is one test that failed, or a package or file that failed with no test to name (a build that failed, a test
// program that panicked, a test file that did not load). The JSON names are the ones mesh-build-go and the checker have
// always used; File is new and an older reader ignores it.
type Failure struct {
// Package is the Go package's import path, or the TypeScript package's directory in the workspace.
Package string `json:"package"`
// Test names the failing test, or the tests that were running when the program stopped; "" when none can be named.
Test string `json:"test,omitempty"`
// File is where the failing test is (a Go test's file and line is in its Cause; node names the test's file:line:col).
File string `json:"file,omitempty"`
// Cause is the one line that says why: the assertion's or the error's first line, a "panic:" line, a build's first
// error, or words saying how the program stopped. **Never empty, and never a passing line** (PassingLine).
Cause string `json:"cause,omitempty"`
// Output is the failing test's own output, its last lines up to OutputBytes, Cause first: an older checker reads
// only its first line.
Output string `json:"output,omitempty"`
}
// OutputBytes is the most a failure keeps of its output, and LineBytes the most of one line: four kilobytes holds a long
// assertion message and stays far under a bus message's or a verdict's bound.
const (
OutputBytes = 4096
LineBytes = 1024
)
// By names a build module and the SDK it was built with, for a result's "by": the checker names it when a failure hides
// its cause ("the build module hid the failure (<by>)").
func By(module string) string {
return module + " with mesh-sdk " + sdkversion.Version()
}
// PassingLine says a line is a test runner's word for a test or a package that passed: node's '✔', TAP's "ok N" (at any
// indent), go test's "ok \t<pkg>", "PASS" and "--- PASS". A line of a test's own that starts "ok " is none of these. Such a line is never a failure's cause, nor part of a failure's output.
func PassingLine(l string) bool {
if strings.HasPrefix(l, "ok \t") { // go test's package line, at column 0
return true
}
t := strings.TrimSpace(l)
switch {
case t == "PASS", strings.HasPrefix(t, "✔"), strings.HasPrefix(t, "--- PASS"):
return true
}
return tapOk(t)
}
// Hidden says how a failure hides why it failed, or "" when it does not: it has no cause, or its cause is a passing line.
// The checker says it loudly (issue 1901): a build module that sends such a failure does not keep the contract.
func Hidden(f Failure) string {
c := strings.TrimSpace(f.Cause)
switch {
case c == "":
return "it sent no cause"
case PassingLine(c):
return fmt.Sprintf("its cause is a passing line (%q)", CutLine(c))
}
return ""
}
// Clip joins the last lines of a failure's output that fit OutputBytes, each cut to LineBytes, and says how many earlier
// lines it left out. **Its first line is the cause**, put ahead when the kept lines do not start with it, or, with no
// cause and lines left out, the first non-empty line, then the marker: an older checker reads only the first line.
// Passing lines are dropped.
func Clip(lines []string, cause string) string {
own := make([]string, 0, len(lines))
for _, l := range lines {
if !PassingLine(l) {
own = append(own, l)
}
}
lines = own
size, from := 0, len(lines)
for from > 0 {
n := len(CutLine(lines[from-1])) + 1
if size+n > OutputBytes && from < len(lines) {
break
}
size += n
from--
}
kept := make([]string, 0, len(lines)-from+2)
head := strings.TrimSpace(cause)
for i := 0; head == "" && i < from; i++ {
head = strings.TrimSpace(lines[i])
}
if head != "" && (from > 0 || len(lines) == 0 || strings.TrimSpace(lines[from]) != head) {
kept = append(kept, CutLine(head))
}
if from > 0 {
kept = append(kept, fmt.Sprintf("... (%d earlier lines)", from))
}
for _, l := range lines[from:] {
kept = append(kept, CutLine(l))
}
return strings.Join(kept, "\n")
}
// CutLine cuts a line to LineBytes, on a character boundary.
func CutLine(l string) string {
if len(l) <= LineBytes {
return l
}
return strings.ToValidUTF8(l[:LineBytes], "") + "..."
}
// ConsoleFailure is the failure of a command that is no test runner (go vet, gofmt, tsc, a build script): its cause is the
// first line that names an error (tsc's "error TS", go vet's "file.go:12:3: ..."), else the first line that is not a
// heading ("# <package>", npm's "> script"), and its output the command's lines without passing ones.
func ConsoleFailure(pkg, test, out string) Failure {
var lines []string
for _, l := range strings.Split(strings.ReplaceAll(stripANSI(out), "\r\n", "\n"), "\n") {
if t := strings.TrimSpace(l); t != "" && !PassingLine(t) {
lines = append(lines, strings.TrimRight(l, " \t"))
}
}
cause := ""
for _, l := range lines {
if t := strings.TrimSpace(l); strings.Contains(t, "error") || strings.Contains(t, "Error") || goPosition.MatchString(t) {
cause = t
break
}
}
for _, l := range lines {
if t := strings.TrimSpace(l); cause == "" && !strings.HasPrefix(t, "# ") && !strings.HasPrefix(t, "> ") && !strings.HasPrefix(t, "npm ") {
cause = t
}
}
if cause == "" {
cause = test + " failed and wrote nothing that says why"
}
cause = CutLine(cause)
return Failure{Package: pkg, Test: test, Cause: cause, Output: Clip(lines, cause)}
}
-19
View File
@@ -1,19 +0,0 @@
package buildstep
import (
"regexp"
"strings"
)
// goPosition matches a line that starts with a Go file's position, as go vet and the compiler write an error.
var goPosition = regexp.MustCompile(`^\S+\.go:\d+(:\d+)?: `)
var ansiEscape = regexp.MustCompile("\x1b\\[[0-9;]*m")
func stripANSI(s string) string { return ansiEscape.ReplaceAllString(s, "") }
// tapOk says a line is a passing test's "ok N - name", indented or not.
func tapOk(l string) bool {
rest, ok := strings.CutPrefix(strings.TrimSpace(l), "ok ")
return ok && rest != "" && rest[0] >= '0' && rest[0] <= '9'
}
-148
View File
@@ -1,148 +0,0 @@
package buildstep
import (
"encoding/json"
"fmt"
"slices"
"strings"
"time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// **The artifact store's holder takes its own new build even when its seat is the one broken** (novox/hq design 47,
// lines 1888-1906 at b33ac325; test 60): when the seat oci-artifact-registry refuses or does not answer the store of a
// trunk build of a module that claims that seat, the build module keeps that build on the bus, one object per build
// named by its digest, and the node-engine composing the holder asks the build seats' verb kept-artifact where it is.
// The judgement the three build modules share is here (ADR 0634 §2): what may be kept, the kept builds a node holds,
// and the verb's answer with its three refusals. The store and the verb's serving are each build module's own.
// StoreSeat is the seat whose holder's builds a build node keeps.
const StoreSeat = "oci-artifact-registry"
// The refusals of kept-artifact, the words of the part build-step's enum.
const (
KeptRefusedClaimsNoStore = "claims no " + StoreSeat
KeptRefusedNotKept = "not kept"
KeptRefusedDigestDiffers = "digest differs"
)
// CatalogModuleVerb is the seat mesh-catalog's verb that answers one module's manifest, as a manifest invokes it.
const CatalogModuleVerb = "seat:mesh-catalog.module"
// KeptFor is what a build keeps a refused artifact for: the module, which claims the store's seat, and its build's
// fingerprint, which kept-artifact is asked by.
type KeptFor struct{ Module, Fp string }
// KeepOf is the keep of a build, or nil when nothing may be kept: only a trunk build (publish) of a module whose manifest
// at the built commit claims the store's seat, named by its fingerprint.
func KeepOf(publish bool, manifest catalogue.Manifest, fp string) *KeptFor {
if !publish || fp == "" || !manifest.ClaimsSeat(StoreSeat) {
return nil
}
return &KeptFor{Module: manifest.Module, Fp: fp}
}
// KeptBuild is one kept build: the object's description names its module, fingerprint and the node that kept it.
type KeptBuild struct {
Module string `json:"module"`
Fp string `json:"fp"`
Node string `json:"node"`
Digest string `json:"digest"`
Bytes uint64 `json:"bytes"`
LastUsed time.Time `json:"last-used"`
}
// KeptObject is the object name (the hex digest of "sha256:<hex>") and description a build is kept under on node.
func KeptObject(k KeptFor, node, digest string) (name, description string) {
desc, _ := json.Marshal(KeptBuild{Module: k.Module, Fp: k.Fp, Node: node})
return strings.TrimPrefix(digest, "sha256:"), string(desc)
}
// KeptBuildsOf are the builds node keeps among a store's objects, by digest.
func KeptBuildsOf(infos []buscalls.ObjectInfo, node string) []KeptBuild {
out := []KeptBuild{}
for _, i := range infos {
var k KeptBuild
if i.Deleted || json.Unmarshal([]byte(i.Description), &k) != nil || k.Node != node {
continue
}
k.Digest, k.Bytes, k.LastUsed = i.Name, i.Size, i.Modified.UTC()
out = append(out, k)
}
slices.SortFunc(out, func(a, b KeptBuild) int { return strings.Compare(a.Digest, b.Digest) })
return out
}
// ClaimsStoreOf reads the seat mesh-catalog's answer of one module (CatalogModuleVerb): whether its manifest claims the
// store's seat; a module the catalog holds no manifest of claims nothing.
func ClaimsStoreOf(module string, raw []byte) (bool, error) {
var a struct {
Module struct {
Manifest json.RawMessage `json:"manifest"`
} `json:"module"`
}
if err := json.Unmarshal(raw, &a); err != nil {
return false, fmt.Errorf("%s answered what is no module: %w", CatalogModuleVerb, err)
}
if len(a.Module.Manifest) == 0 {
return false, nil
}
man, err := catalogue.Decode(a.Module.Manifest)
if err != nil {
return false, fmt.Errorf("the manifest of %s: %w", module, err)
}
return man.ClaimsSeat(StoreSeat), nil
}
// KeptArtifactAnswer is the verb kept-artifact's answer, the part build-step's layout.
type KeptArtifactAnswer struct {
Module string `json:"module"`
Fp string `json:"fp"`
Digest string `json:"digest,omitempty"`
Size int64 `json:"size,omitempty"`
Store string `json:"store,omitempty"`
Object string `json:"object,omitempty"`
Refused string `json:"refused,omitempty"`
Words string `json:"words,omitempty"`
Error string `json:"error,omitempty"`
}
// KeptArtifact answers kept-artifact for module, fp and the hex digest from the builds this node keeps, in store (the
// store's name on the bus); claims asks the seat mesh-catalog whether a module claims the store's seat, only when no
// build of it is kept here at that digest.
func KeptArtifact(module, fp, digest string, kept []KeptBuild, store string, claims func(module string) (bool, error)) KeptArtifactAnswer {
a := KeptArtifactAnswer{Module: module, Fp: fp}
var other *KeptBuild
for i, k := range kept {
if k.Module != module || k.Fp != fp {
continue
}
if k.Digest == digest {
a.Digest, a.Size, a.Object = k.Digest, int64(k.Bytes), k.Digest
if store == "" {
a.Error = "this module runs with no name of its own (MESH_MODULE), so its store's name on the bus is unknown"
return a
}
a.Store = store
return a
}
other = &kept[i]
}
ok, err := claims(module)
switch {
case err != nil:
a.Error = "asking whether " + module + " claims " + StoreSeat + ": " + err.Error()
case !ok:
a.Refused = KeptRefusedClaimsNoStore
a.Words = fmt.Sprintf("%s claims no %s: a build node keeps builds for that seat's holder alone", module, StoreSeat)
case other != nil:
a.Refused, a.Digest = KeptRefusedDigestDiffers, other.Digest
a.Words = fmt.Sprintf("this node keeps the build of %s at %s under the digest %s, not %s", module, fp, other.Digest, digest)
default:
a.Refused = KeptRefusedNotKept
a.Words = fmt.Sprintf("this node keeps no build of %s at %s (never kept, or swept)", module, fp)
}
return a
}
-14
View File
@@ -1,14 +0,0 @@
package buildstep
import "git.novox.be/novox/mesh-sdk/go/catalogue"
// LauncherSuffix is what a TypeScript entrypoint's launcher is called beside it: index.js is started as
// index.serve.mjs (novox/hq ADR 0193), an ES module by its own extension whatever the bundle's package.json says.
const LauncherSuffix = catalogue.LauncherSuffix
// Launchers are the launchers a bundle's build writes, by entrypoint, relative to the bundle's root
// (catalogue.Launchers): the one rule mesh-build-node, build-agent, the controller and a node taking in a build share
// (R4e, issue 1126), so the name a build writes is the name a reader expects.
func Launchers(language string, entrypoints []string) map[string]string {
return catalogue.Launchers(language, entrypoints)
}
-22
View File
@@ -1,22 +0,0 @@
package buildstep
import (
"reflect"
"testing"
)
// A TypeScript bundle's entrypoint x.js is started as x.serve.mjs beside it (novox/hq ADR 0193), the rule mesh-build-node
// and build-agent both apply; an entrypoint that is not .js gets none, and another language gets none.
func TestATypeScriptEntrypointIsStartedByTheLauncherBesideIt(t *testing.T) {
got := Launchers("typescript", []string{"index.js", "tools/x.js", "data.json"})
want := map[string]string{"index.js": "index.serve.mjs", "tools/x.js": "tools/x.serve.mjs"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("Launchers(typescript) = %v, want %v", got, want)
}
if got := Launchers("go", []string{"index.js"}); len(got) != 0 {
t.Fatalf("a Go bundle got launchers: %v", got)
}
if got := Launchers("typescript", nil); len(got) != 0 {
t.Fatalf("a bundle with no entrypoint got launchers: %v", got)
}
}
-58
View File
@@ -1,58 +0,0 @@
package buildstep
import (
"errors"
"fmt"
"strings"
)
// Passing is a fault of the network between a build node and what it reaches (a name lookup, a timeout, a reset
// connection, a forge's sshd refusing a burst, a store that does not answer), not of the source or the toolchain. A
// build module wraps it, and the shared runner then writes the step again and settles its ask with a delayed nak, up to
// AskRuns runs (ADR 0664 §1, §2). Any other error ends the step failed at once.
type Passing struct{ Err error }
func (p *Passing) Error() string { return p.Err.Error() }
func (p *Passing) Unwrap() error { return p.Err }
// IsPassing says err is, or wraps, a Passing.
func IsPassing(err error) bool {
var p *Passing
return errors.As(err, &p)
}
// HolderSilentWords opens the words of a HolderSilent, so PassingCause reads them from a step's reason too.
const HolderSilentWords = "the holder is silent"
// HolderSilent is a seat verb that answered "no responders" while the assigner names a holder of the seat: its tool
// runner is being replaced, a moment later it answers. It is a Passing fault (ADR 0664 §1); a seat nothing holds is not.
type HolderSilent struct{ Seat, Holder, Node string }
func (h *HolderSilent) Error() string {
return fmt.Sprintf("%s: seat %s, held by %s on %s, answered no responders", HolderSilentWords, h.Seat, h.Holder, h.Node)
}
// Unwrap makes a HolderSilent a Passing.
func (h *HolderSilent) Unwrap() error { return &Passing{Err: errors.New(h.Error())} }
// passingWords are the words of a network that did not answer, lower-cased: go's and git's (a lookup, a timeout, a refused or
// reset connection, ssh's key exchange cut by a forge's per-source penalty) and npm's error codes. "no responders" alone is not
// one: it is the same for a seat nothing holds (HolderSilent is the case a holder is named).
var passingWords = []string{"i/o timeout", "no such host", "temporary failure in name resolution", "connection refused",
"connection reset", "tls handshake timeout", "network is unreachable", "no route to host", "lookup ", "kex_exchange_identification", "connection closed by",
"could not resolve host", "client.timeout", "operation timed out", "connection timed out", "eai_again", "etimedout", "econnreset", "econnrefused", "enotfound", strings.ToLower(HolderSilentWords)}
// PassingCause says words (a tool's output or a step's reason) are those of a transport fault.
func PassingCause(words string) bool {
words = strings.ToLower(words)
for _, w := range passingWords {
if strings.Contains(words, w) {
return true
}
}
return false
}
// TransportFaultWords open the reason of a step that ended failed after its runs met a transport fault (the asker says them,
// "a transport fault on 3 runs (nodes): cause"): a reader tells that end from a fault of the source by them (ADR 0664 §3).
const TransportFaultWords = "a transport fault on "
-124
View File
@@ -1,124 +0,0 @@
package buildstep
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
)
// The states `pauses` of the build seats, whose three seats hold the same layouts (the part `build-step`): a node's
// pause under `paused.<node>`, its capacity under `capacity.<node>`.
// PausesState is the name of the state.
const PausesState = "pauses"
// PauseKey is the key of a node's pause.
func PauseKey(node string) (string, error) {
if err := checkNode(node); err != nil {
return "", err
}
return "paused." + node, nil
}
// CapacityKey is the key of a node's capacity.
func CapacityKey(node string) (string, error) {
if err := checkNode(node); err != nil {
return "", err
}
return "capacity." + node, nil
}
// DropKey is the key of an ask's drop in a build seat's pauses state: "dropped.<id>" (the part build-step).
func DropKey(askID string) string { return "dropped." + askID }
// DroppedPrefix opens every key DropKey makes.
const DroppedPrefix = "dropped."
// Pause is whether a node takes no new ask, and who said so.
type Pause struct {
V int `json:"v"`
Paused bool `json:"paused"`
By string `json:"by,omitempty"`
At time.Time `json:"at,omitzero"`
}
// EncodePause is p as a pauses value.
func EncodePause(p Pause) ([]byte, error) {
p.V = Version
p.At = p.At.UTC()
return json.Marshal(p)
}
// DecodePause reads a pause, refusing another version.
func DecodePause(data []byte) (Pause, error) {
var p Pause
if err := decodeVersioned(data, &p, func() int { return p.V }); err != nil {
return Pause{}, err
}
return p, nil
}
// Capacity is how many steps a node runs at once, and why.
type Capacity struct {
V int `json:"v"`
Effective int `json:"effective"`
Configured int `json:"configured"`
ConfiguredFrom string `json:"configured-from,omitempty"`
QuotaCores float64 `json:"quota-cores,omitempty"`
QuotaFrom string `json:"quota-from"`
CoresPerStep float64 `json:"cores-per-step"`
ByCPU int `json:"by-cpu,omitempty"`
BuildHours string `json:"build-hours,omitempty"`
OutsideHours bool `json:"outside-hours,omitempty"`
BuildHoursFault string `json:"build-hours-fault,omitempty"`
Ineligible string `json:"ineligible,omitempty"`
Why string `json:"why"`
At time.Time `json:"at,omitzero"`
}
// EncodeCapacity is c as a pauses value.
func EncodeCapacity(c Capacity) ([]byte, error) {
c.V = Version
c.At = c.At.UTC()
return json.Marshal(c)
}
// DecodeCapacity reads a capacity, refusing another version.
func DecodeCapacity(data []byte) (Capacity, error) {
var c Capacity
if err := decodeVersioned(data, &c, func() int { return c.V }); err != nil {
return Capacity{}, err
}
return c, nil
}
func decodeVersioned(data []byte, into any, version func() int) error {
if err := json.Unmarshal(data, into); err != nil {
return fmt.Errorf("buildstep: value does not fit its shape: %w", err)
}
if v := version(); v != Version {
return fmt.Errorf("%w: a value of version %d, this reader reads %d", ErrUnknownVersion, v, Version)
}
return nil
}
// ComposerKey is the key a composer build is kept under: the fetched commit, the directory, the package and the
// toolchain it ran with. The mesh package versions the ask names are an input of the build, so they are in the key,
// sorted, when there are any; an ask that names none gets the key it always had (issue 1921).
func ComposerKey(repository, commit, dir, pkg string, toolchain ToolchainUsed, versions PackageVersions) string {
parts := []string{repository, commit, dir, pkg, toolchain.Version, toolchain.Recipe}
pkgs := make([]string, 0, len(versions))
for p := range versions {
pkgs = append(pkgs, p)
}
sort.Strings(pkgs)
for _, p := range pkgs {
parts = append(parts, p+"="+versions[p])
}
sum := sha256.Sum256([]byte(strings.Join(parts, "\n")))
return "composer-" + hex.EncodeToString(sum[:8])
}
-243
View File
@@ -1,243 +0,0 @@
package buildstep
import (
"encoding/json"
"fmt"
"slices"
"strings"
"time"
meshkeys "git.novox.be/novox/mesh-sdk/go/keys"
)
// **A pipeline step, once.** The runner (seat mesh-pipeline-runner) asks each lint and test step of an artifact on the
// serving build seat's stream check, and the seat's holder says its end as the seat's event step-ended on its own node's
// subject (novox/hq ADR 0666 §7, §8, §21; design 47 *Pipeline steps and the policy*). These are the neutral forms of the
// part build-step's StepRun and StepEnded, which the three build modules share; the publish itself is the holder's.
// The pipeline steps a build seat runs.
const (
StepLint = "lint"
StepUnit = "unit"
StepIntegration = "integration"
)
// PipelineSteps are the steps a build seat serves, in a pipeline's order.
var PipelineSteps = []string{StepLint, StepUnit, StepIntegration}
// The outcomes a build seat says of a step: never passed for a step that ran nothing.
const (
OutcomePassed = "passed"
OutcomeFailed = "failed"
OutcomeNothingToRun = "nothing to run"
OutcomeCouldNotRun = "could not run"
)
// StepOutcomes are the outcomes a build seat may say.
var StepOutcomes = []string{OutcomePassed, OutcomeFailed, OutcomeNothingToRun, OutcomeCouldNotRun}
// StepEndedVersion is the layout version of a step's end.
const StepEndedVersion = 1
// KeptResult is a package's passing result at the digest of what its tests read (ADR 0666 §8).
type KeptResult struct {
Package string `json:"package"`
Digest string `json:"digest"`
Level string `json:"level"`
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
Pipeline string `json:"pipeline,omitempty"`
}
// TestCounts are how many tests a step ran and carried, per level.
type TestCounts struct {
Unit int `json:"unit,omitempty"`
Integration int `json:"integration,omitempty"`
}
// StepRun is one pipeline step of one artifact at one commit.
type StepRun struct {
Pipeline string `json:"pipeline"`
Step string `json:"step"`
Module string `json:"module"`
Artifact string `json:"artifact"`
Branch string `json:"branch,omitempty"`
Commit string `json:"commit"`
Revision int `json:"revision,omitempty"`
Fingerprint string `json:"fingerprint"`
Fetch Fetch `json:"fetch"`
Toolchain *ToolchainUsed `json:"toolchain,omitempty"`
Kept []KeptResult `json:"kept,omitempty"`
Rerun bool `json:"rerun,omitempty"`
By string `json:"by,omitempty"`
}
// Skips says whether the step runs no tests of pkg at digest, its kept result holding them.
func (r StepRun) Skips(pkg, digest string) bool {
return slices.ContainsFunc(r.Kept, func(k KeptResult) bool {
return k.Package == pkg && k.Digest == digest && k.Level == r.Step
})
}
func (r StepRun) check(id string) error {
if !slices.Contains(PipelineSteps, r.Step) {
return fmt.Errorf("buildstep: the step ask %s names the step %q, not %s", id, r.Step, strings.Join(PipelineSteps, ", "))
}
if r.Pipeline == "" {
return fmt.Errorf("buildstep: the step ask %s names no pipeline", id)
}
if err := meshkeys.CheckName("module", r.Module); err != nil {
return fmt.Errorf("the step ask %s: %w", id, err)
}
if mod, art, ok := strings.Cut(r.Artifact, ":"); !ok || mod != r.Module || art == "" {
return fmt.Errorf("buildstep: the step ask %s names the artifact %q, not %s:<artifact>", id, r.Artifact, r.Module)
}
if !askCommitOK.MatchString(r.Commit) {
return fmt.Errorf("buildstep: the step ask %s names no full commit (%q)", id, r.Commit)
}
if r.Fingerprint == "" {
return fmt.Errorf("buildstep: the step ask %s names no build-input fingerprint", id)
}
if err := r.Fetch.check(id); err != nil {
return err
}
if r.Rerun != (r.By != "") {
return fmt.Errorf("buildstep: the step ask %s is a rerun with no caller, or names a caller and is no rerun", id)
}
return nil
}
// StepEnded is an ask's end, said by the build seat's holder on the node that ran it, whatever its asker (design 47 G
// §602): a pipeline step's end names its pipeline, step, module, artifact, commit and fingerprint; the end of any other
// ask names its asker, the ask, the node, the outcome and when, and neither commit nor fingerprint (G §548).
type StepEnded struct {
V int `json:"v"`
ID string `json:"id"`
Asker string `json:"asker"`
Ask string `json:"ask"`
Pipeline string `json:"pipeline,omitempty"`
Step string `json:"step,omitempty"`
Module string `json:"module,omitempty"`
Artifact string `json:"artifact,omitempty"`
Commit string `json:"commit,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
Node string `json:"node"`
Outcome string `json:"outcome"`
Tests *TestCounts `json:"tests,omitempty"`
Carried []KeptResult `json:"carried,omitempty"`
Kept []KeptResult `json:"kept,omitempty"`
Said string `json:"said,omitempty"`
Output string `json:"output,omitempty"`
OutputObject string `json:"output-object,omitempty"`
Rerun bool `json:"rerun,omitempty"`
By string `json:"by,omitempty"`
Started time.Time `json:"started,omitzero"`
Ended time.Time `json:"ended,omitzero"`
At time.Time `json:"at,omitzero"`
}
// EndOf is the end of the step a holds, on node, with outcome: the ask's names copied, so the runner can match the ask,
// the commit and the fingerprint (ADR 0666 §21).
func EndOf(a StepAsk, node, outcome string) (StepEnded, error) {
if a.Step == nil {
return StepEnded{}, fmt.Errorf("buildstep: the ask %s is no pipeline step", a.ID)
}
s := a.Step
e := StepEnded{V: StepEndedVersion, ID: a.ID, Asker: a.Asker, Ask: a.ID, Pipeline: s.Pipeline, Step: s.Step, Module: s.Module, Artifact: s.Artifact,
Commit: s.Commit, Fingerprint: s.Fingerprint, Node: node, Outcome: outcome, Rerun: s.Rerun, By: s.By}
return e, e.check()
}
func (e StepEnded) check() error {
if err := CheckAskID(e.ID); err != nil {
return err
}
if err := checkNode(e.Node); err != nil {
return err
}
if e.Pipeline == "" {
// G §548, §602: the end of an ask outside a pipeline names its asker, the ask and when, and no commit or
// fingerprint.
if !slices.Contains(StepOutcomes, e.Outcome) {
return fmt.Errorf("buildstep: the end of %s says %q, not one of %s", e.ID, e.Outcome, strings.Join(StepOutcomes, ", "))
}
if e.Asker == "" || e.Ask == "" || e.At.IsZero() {
return fmt.Errorf("buildstep: the end of %s, an ask outside a pipeline, names no asker, ask or time", e.ID)
}
if e.Commit != "" || e.Fingerprint != "" {
return fmt.Errorf("buildstep: the end of %s names a commit or a fingerprint and no pipeline", e.ID)
}
return nil
}
if !slices.Contains(PipelineSteps, e.Step) {
return fmt.Errorf("buildstep: the end of %s names the step %q", e.ID, e.Step)
}
if !slices.Contains(StepOutcomes, e.Outcome) {
return fmt.Errorf("buildstep: the end of %s says %q, not one of %s", e.ID, e.Outcome, strings.Join(StepOutcomes, ", "))
}
if e.Pipeline == "" || e.Module == "" || e.Artifact == "" || !askCommitOK.MatchString(e.Commit) || e.Fingerprint == "" {
return fmt.Errorf("buildstep: the end of %s names no pipeline, module, artifact, full commit or fingerprint", e.ID)
}
return nil
}
// EncodeStepEnded is a step's end as its event's body; one that could not run or failed says why.
func EncodeStepEnded(e StepEnded) ([]byte, error) {
e.V = StepEndedVersion
if err := e.check(); err != nil {
return nil, err
}
if (e.Outcome == OutcomeCouldNotRun || e.Outcome == OutcomeFailed) && e.Said == "" {
return nil, fmt.Errorf("buildstep: the end of %s says %s and not why", e.ID, e.Outcome)
}
return json.Marshal(e)
}
// DecodeStepEnded reads a step's end heard on subject: the node it names must be the subject's, the one node whose
// holder's account may publish there (ADR 0363 §2, ADR 0666 §21).
func DecodeStepEnded(subject string, data []byte) (StepEnded, error) {
_, node, err := ParseStepEndedSubject(subject)
if err != nil {
return StepEnded{}, err
}
var e StepEnded
if err := json.Unmarshal(data, &e); err != nil {
return StepEnded{}, fmt.Errorf("buildstep: a step's end does not fit its shape: %w", err)
}
if e.V != StepEndedVersion {
return StepEnded{}, fmt.Errorf("%w: a step's end of version %d, this reader reads %d", ErrUnknownVersion, e.V, StepEndedVersion)
}
if err := e.check(); err != nil {
return StepEnded{}, err
}
if e.Node != node {
return StepEnded{}, fmt.Errorf("buildstep: the end of %s names the node %s and was said on %s's subject", e.ID, e.Node, node)
}
return e, nil
}
// StepEndedSubject is where the holder of a language's build seat on node says a step's end.
func StepEndedSubject(language, node string) (string, error) {
seat, err := BuildSeat(language)
if err != nil {
return "", err
}
if err := checkNode(node); err != nil {
return "", err
}
return "mesh.seat." + seat + ".event.step-ended." + node, nil
}
// ParseStepEndedSubject is the inverse of StepEndedSubject.
func ParseStepEndedSubject(subject string) (language, node string, err error) {
rest, ok := strings.CutPrefix(subject, "mesh.seat.node-build-")
if ok {
language, node, ok = strings.Cut(rest, ".event.step-ended.")
}
if !ok {
return "", "", fmt.Errorf("buildstep: %q is not a build seat's step-ended subject", subject)
}
if want, err := StepEndedSubject(language, node); err != nil || want != subject {
return "", "", fmt.Errorf("buildstep: %q is not a build seat's step-ended subject: %v", subject, err)
}
return language, node, nil
}
-161
View File
@@ -1,161 +0,0 @@
package buildstep
import (
"fmt"
"maps"
"path"
"regexp"
"strings"
)
var (
requestCommitOK = regexp.MustCompile(`^[0-9a-f]{40}$`)
requestRepositoryOK = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$`)
)
// FetchRequest is what a build module's fetch tool is asked: the repository and the full commit, the pull request's
// ref when only its head carries the commit, the trunk commit to merge onto for a merge preview, and, for a build of a
// module whose every artifact names its paths, that module's directory and its named paths (novox/hq ADR 0499 clause 4).
//
// **The paths come from the builder, not from a manifest** (ADR 0495 clause 1; the lead's decision L8 of R4e): the
// builder fills Dir and Paths from the indexer's Module value (Path, and KeptInputs2.Paths' keys), and the build module
// gives the build and test steps a workspace holding those paths, the manifest and its lock files. A request without
// them builds from the module's directory, as before.
type FetchRequest struct {
Repository string `json:"repository"`
Commit string `json:"commit"`
Ref string `json:"ref,omitempty"`
Base string `json:"base,omitempty"`
Dir string `json:"dir,omitempty"`
Paths []string `json:"paths,omitempty"`
// Packages are the version of each mesh package the build or the check builds against (Ask.Packages,
// novox/hq ADR 0573 §2, §4): the build module writes each into the workspace's go.mod and go.sum, whatever version
// the repository names, checksum-verified, and names them in its log.
Packages PackageVersions `json:"packages,omitempty"`
}
// FetchRequestProperties are the JSON schema properties of FetchRequest's dir and paths, for a fetch tool's Input.
func FetchRequestProperties() map[string]any {
return map[string]any{
"dir": map[string]any{"type": "string", "description": "the module's directory in the repository (\".\" for its root), with paths"},
"paths": map[string]any{"type": "array", "items": map[string]any{"type": "string"},
"description": "the paths the module names, relative to dir, from the indexer's kept inputs: the build sees only these, the manifest and its lock files"},
"packages": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"},
"description": "optional: the version (a full commit) of each mesh package to build against, by its module path, whatever version go.mod names (novox/hq ADR 0573 §2); the builder and the checker fill it"},
}
}
// Args is r as a tool call's arguments.
func (r FetchRequest) Args() map[string]any {
args := map[string]any{"repository": r.Repository, "commit": r.Commit}
for k, v := range map[string]string{"ref": r.Ref, "base": r.Base, "dir": r.Dir} {
if v != "" {
args[k] = v
}
}
if len(r.Paths) > 0 {
args["paths"] = append([]string(nil), r.Paths...)
}
if len(r.Packages) > 0 {
args["packages"] = map[string]any{}
for p, v := range r.Packages {
args["packages"].(map[string]any)[p] = v
}
}
return args
}
// ParseFetchRequest reads a fetch tool's arguments; arguments it does not know (a build module's own) are left to the
// caller. It refuses a repository that is not <owner>/<name>, a commit or a base that is not 40 hex digits, paths with no
// module directory or a directory with no path, a directory leaving the repository and a path leaving the directory,
// naming each.
func ParseFetchRequest(args map[string]any) (FetchRequest, error) {
var r FetchRequest
r.Repository, _ = args["repository"].(string)
r.Commit, _ = args["commit"].(string)
r.Ref, _ = args["ref"].(string)
r.Base, _ = args["base"].(string)
r.Dir, _ = args["dir"].(string)
switch v := args["paths"].(type) {
case nil:
case []string:
r.Paths = append([]string(nil), v...)
case []any:
for _, p := range v {
s, ok := p.(string)
if !ok {
return FetchRequest{}, fmt.Errorf("paths is a list of strings")
}
r.Paths = append(r.Paths, s)
}
default:
return FetchRequest{}, fmt.Errorf("paths is a list of strings")
}
packages, err := PackagesArg(args["packages"])
if err != nil {
return FetchRequest{}, err
}
r.Packages = packages
return r, r.Check()
}
// PackagesArg reads a tool call's packages argument, an object of strings (as JSON gives it) or the map an ask gives;
// nil for none.
func PackagesArg(v any) (PackageVersions, error) {
out := PackageVersions{}
switch v := v.(type) {
case nil:
return nil, nil
case PackageVersions:
maps.Copy(out, v)
case map[string]string:
maps.Copy(out, v)
case map[string]any:
for p, version := range v {
s, ok := version.(string)
if !ok {
return nil, fmt.Errorf("packages is an object of versions (strings), by package")
}
out[p] = s
}
default:
return nil, fmt.Errorf("packages is an object of versions (strings), by package")
}
if len(out) == 0 {
return nil, nil
}
return out, out.Check()
}
// Check is what ParseFetchRequest refuses.
func (r FetchRequest) Check() error {
if !requestRepositoryOK.MatchString(r.Repository) || strings.Contains(r.Repository, "..") {
return fmt.Errorf("%q is not a repository, <owner>/<name>", r.Repository)
}
if !requestCommitOK.MatchString(r.Commit) {
return fmt.Errorf("%q is not a full commit (40 hex digits)", r.Commit)
}
if r.Base != "" && !requestCommitOK.MatchString(r.Base) {
return fmt.Errorf("%q is not a trunk commit (40 hex digits)", r.Base)
}
switch {
case len(r.Paths) > 0 && r.Dir == "":
return fmt.Errorf("the request names paths and names no module directory (dir) they are relative to")
case len(r.Paths) == 0 && r.Dir != "":
return fmt.Errorf("the request names a module directory and no path")
}
if r.Dir != "" && (outside(r.Dir) || strings.HasPrefix(r.Dir, "/")) {
return fmt.Errorf("the module directory %q leaves the repository", r.Dir)
}
for _, p := range r.Paths {
if p == "" || strings.HasPrefix(p, "/") || outside(p) || path.Clean(p) == "." {
return fmt.Errorf("the path %q leaves the module's directory or is not a path in it", p)
}
}
return nil
}
func outside(p string) bool {
c := path.Clean(p)
return c == ".." || strings.HasPrefix(c, "../")
}
-64
View File
@@ -1,64 +0,0 @@
package buildstep
import (
"reflect"
"strings"
"testing"
)
// A build's fetch is handed the paths of a module that names them (novox/hq ADR 0499 clause 4): the builder fills them
// from the indexer's kept inputs and the build module reads them from the call, never from the manifest (ADR 0495
// clause 1). The request survives the trip through a tool call's arguments.
func TestAFetchRequestCarriesTheNamedPathsThroughTheToolCall(t *testing.T) {
// And the versions of the mesh packages to build against (novox/hq ADR 0573 §2; issue 1585 S4).
req := FetchRequest{Repository: "novox/mesh-sdk", Commit: strings.Repeat("a", 40), Ref: "refs/pull/7/head",
Dir: ".", Paths: []string{"package.json", "src"}, Packages: map[string]string{"git.novox.be/novox/mesh-sdk/go": strings.Repeat("d", 40)}}
args := req.Args()
// A tool call's arguments arrive as JSON: lists of any, objects of any.
args["paths"] = []any{"package.json", "src"}
if p, ok := args["packages"].(map[string]any); !ok || p["git.novox.be/novox/mesh-sdk/go"] != strings.Repeat("d", 40) {
t.Fatalf("the packages are not in the call's arguments: %v", args["packages"])
}
got, err := ParseFetchRequest(args)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, req) {
t.Fatalf("got %+v, want %+v", got, req)
}
plain, err := ParseFetchRequest(map[string]any{"repository": "novox/x", "commit": strings.Repeat("b", 40),
"base": strings.Repeat("c", 40), "beside": []any{}})
if err != nil || plain.Paths != nil || plain.Base != strings.Repeat("c", 40) {
t.Fatalf("a request without paths: %+v, %v", plain, err)
}
ok := map[string]any{"repository": "novox/x", "commit": strings.Repeat("b", 40)}
for _, c := range []struct {
set map[string]any
says string
}{
{map[string]any{"repository": "novox"}, "is not a repository"},
{map[string]any{"repository": "novox/../x"}, "is not a repository"},
{map[string]any{"commit": "abc"}, "is not a full commit"},
{map[string]any{"base": "abc"}, "is not a trunk commit"},
{map[string]any{"paths": []any{"src"}}, "names no module directory"},
{map[string]any{"dir": "modules/a", "paths": []any{"../b"}}, "leaves the module's directory"},
{map[string]any{"dir": "../a", "paths": []any{"src"}}, "leaves the repository"},
{map[string]any{"dir": "modules/a", "paths": []any{3}}, "paths is a list of strings"},
{map[string]any{"dir": "modules/a"}, "names a module directory and no path"},
{map[string]any{"packages": map[string]any{"git.novox.be/novox/mesh-sdk/go": "main"}}, "neither a full commit nor a Go semantic version"},
{map[string]any{"packages": map[string]any{"a b": strings.Repeat("d", 40)}}, "no module path"},
{map[string]any{"packages": []any{"x"}}, "packages is an object"},
} {
args := map[string]any{}
for k, v := range ok {
args[k] = v
}
for k, v := range c.set {
args[k] = v
}
if _, err := ParseFetchRequest(args); err == nil || !strings.Contains(err.Error(), c.says) {
t.Errorf("%v: %v, wanted a refusal saying %q", c.set, err, c.says)
}
}
}
-181
View File
@@ -1,181 +0,0 @@
package buildstep
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"path"
"regexp"
"strings"
"git.novox.be/novox/mesh-sdk/go/calladdress"
)
// **A run ask has a program built from a change and run in the build seat's sandbox** (novox/hq ADR 0644, ADR 0656;
// design 47, *What ADR 0656 leaves to this design*: the build seat's ask `run`; issue 1921). It goes on the Go seat's
// check stream, a whole job pulled where there is capacity, like a compose: the build module fetches Program at its
// commit and builds it once per RunKey, in a step that runs nothing but the build; fetches every head of Heads and lays
// each read-only under the directory RunHeadsEnv names, at its repository's path (`<owner>/<name>`); reads the input
// Input names, checks its digest and writes it to the file RunInputEnv names; then runs the program with Args, no
// network and no bus account (ADR 0448 §2, §4), and answers RunAnswer on its step key.
//
// The input is carried by reference, as a compose carries its manifests: the asker keeps it by its digest, measured
// against RunInputBound before it asks, and serves it on a verb of its seat (RunInput.Verb); the build module asks that
// verb as its manifest's `invokes` grants it, never reading the asker's state (ADR 0596 §2), so the ask on the stream
// never carries it (issue 1930). The layouts are the part build-step's `RunJob`, `RunProgram`, `RunHead`, `RunInput`
// and `RunAnswer`.
// RunJob is a run ask's job.
type RunJob struct {
// Program is where the program is built: the repository and full commit fetched, the Go module's directory in it and
// the program's import path. The ask's Packages are the mesh package versions it builds against (ADR 0573 §2, §4).
Program RunProgram `json:"program"`
// Heads are the commits the program reads, each laid read-only at its repository's path; a repository at most once.
Heads []RunHead `json:"heads"`
// Input names the program's input, kept by the asker by its digest and served on a verb of its seat.
Input RunInput `json:"input"`
// Args are the program's arguments (a checking program's `-seats` or `-verdict`), each a word or a flag.
Args []string `json:"args,omitempty"`
// Reader names, for a reader of the ask, what the run is for ("checking program of mesh-delivery head").
Reader string `json:"reader,omitempty"`
}
// RunProgram is where a run's program is built from.
type RunProgram struct {
Repository string `json:"repository"`
Commit string `json:"commit"`
Dir string `json:"dir"`
Package string `json:"package"`
}
// RunHead is one commit a run's program reads.
type RunHead struct {
Repository string `json:"repository"`
Commit string `json:"commit"`
}
// RunInput is a run's input by reference: the seat verb the asker serves it on, named as a manifest's `invokes` names it
// (`seat:<seat>.<verb>`, asked of no one machine), its digest (the sha256 of its bytes, 64 lowercase hex digits) and its
// size in bytes.
type RunInput struct {
Verb string `json:"verb"`
Digest string `json:"digest"`
Size int `json:"size"`
}
// RunAnswer is a run ask's step result: whether this run built the program or took the one kept under its key, the
// key, the program's exit, the last line of its standard output (Output, raw when it is JSON, else as a JSON string),
// and Said: the first line of its standard error, or why the step could not run it.
type RunAnswer struct {
Built bool `json:"built"`
Key string `json:"key"`
Exit int `json:"exit"`
Output json.RawMessage `json:"output,omitempty"`
Said string `json:"said,omitempty"`
}
// RunInputBound is the most bytes a run's input may hold: the bus's value limit the design already uses (256 KiB), so
// the asker keeps it as one value (the lead's ruling on milestone 47/B0, 2026-11-06).
const RunInputBound = 256 << 10
// RunHeadsEnv names, for the program, the directory its heads are laid in; RunInputEnv the file its input is written to.
const (
RunHeadsEnv = "MESH_RUN_HEADS"
RunInputEnv = "MESH_RUN_INPUT"
)
// RunInputOf is the reference to body served on verb (`seat:<seat>.<verb>`), refusing a body over RunInputBound, naming
// its size, so an asker refuses it before asking.
func RunInputOf(verb string, body []byte) (RunInput, error) {
if len(body) > RunInputBound {
return RunInput{}, fmt.Errorf("buildstep: a run's input of %d bytes is over its bound of %d bytes", len(body), RunInputBound)
}
sum := sha256.Sum256(body)
in := RunInput{Verb: verb, Digest: hex.EncodeToString(sum[:]), Size: len(body)}
return in, in.check("")
}
// Verify refuses body when it is not the input i names: another size or another digest.
func (i RunInput) Verify(body []byte) error {
sum := sha256.Sum256(body)
if len(body) != i.Size || hex.EncodeToString(sum[:]) != i.Digest {
return fmt.Errorf("buildstep: the input %s answered for %s is not the one the ask names (%d bytes, %d named)", i.Verb, i.Digest, len(body), i.Size)
}
return nil
}
var (
runDigestOK = regexp.MustCompile(`^[0-9a-f]{64}$`)
runArgOK = regexp.MustCompile(`^[-=_./a-zA-Z0-9]+$`)
)
func (i RunInput) check(id string) error {
switch {
case !runVerbOK(i.Verb):
return fmt.Errorf("buildstep: the run ask %s serves its input on %q, which is no seat:<seat>.<verb> of no one machine", id, i.Verb)
case !runDigestOK.MatchString(i.Digest):
return fmt.Errorf("buildstep: the run ask %s names its input by %q, which is no sha256 digest", id, i.Digest)
case i.Size <= 0 || i.Size > RunInputBound:
return fmt.Errorf("buildstep: the run ask %s names an input of %d bytes, outside 1 to %d", id, i.Size, RunInputBound)
}
return nil
}
// runVerbOK says key names a seat's verb, asked of no one machine.
func runVerbOK(key string) bool {
a, err := calladdress.Parse(key)
return err == nil && a.Seat != "" && a.Node == ""
}
func checkRunRepository(id, what, repository string) error {
owner, name, ok := strings.Cut(repository, "/")
if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
return fmt.Errorf("buildstep: the run ask %s names %s %q, which is no repository <owner>/<name>", id, what, repository)
}
return nil
}
func (r RunJob) check(id string) error {
p := r.Program
if err := checkRunRepository(id, "its program's repository", p.Repository); err != nil {
return err
}
if !askCommitOK.MatchString(p.Commit) {
return fmt.Errorf("buildstep: the run ask %s builds its program at no full commit", id)
}
if p.Dir == "" || p.Dir != path.Clean(p.Dir) || strings.HasPrefix(p.Dir, "/") || p.Dir == ".." || strings.HasPrefix(p.Dir, "../") {
return fmt.Errorf("buildstep: the run ask %s names no clean directory inside the repository (%q)", id, p.Dir)
}
if p.Package == "" || strings.ContainsAny(p.Package, " \t\n") {
return fmt.Errorf("buildstep: the run ask %s names no package to build (%q)", id, p.Package)
}
if len(r.Heads) == 0 {
return fmt.Errorf("buildstep: the run ask %s names no head", id)
}
seen := map[string]bool{}
for _, h := range r.Heads {
if err := checkRunRepository(id, "a head of", h.Repository); err != nil {
return err
}
if !askCommitOK.MatchString(h.Commit) {
return fmt.Errorf("buildstep: the run ask %s names the head of %s at no full commit", id, h.Repository)
}
if seen[h.Repository] {
return fmt.Errorf("buildstep: the run ask %s names %s twice", id, h.Repository)
}
seen[h.Repository] = true
}
for _, a := range r.Args {
if !runArgOK.MatchString(a) {
return fmt.Errorf("buildstep: the run ask %s names the argument %q, which is no word or flag", id, a)
}
}
return r.Input.check(id)
}
// RunKey is the key a build module keeps a built program under, as ComposerKey keeps a composer: what it was built
// from, the toolchain and the asked package versions, hashed (`program-` and 16 hex digits).
func RunKey(p RunProgram, toolchain ToolchainUsed, versions PackageVersions) string {
return "program-" + strings.TrimPrefix(ComposerKey(p.Repository, p.Commit, p.Dir, p.Package, toolchain, versions), "composer-")
}
-24
View File
@@ -1,24 +0,0 @@
package buildstep
import (
"encoding/json"
"os"
"testing"
)
// The seat's `build` acting rule matches an artifact by its kind, an image having no language (design 47 G §324, §397).
func TestTheSeatsBuildRuleActsOnTheKindImage(t *testing.T) {
raw, err := os.ReadFile("../../contracts/seats/node-build-image/seat.json")
if err != nil {
t.Fatal(err)
}
var def struct {
Acts []struct{ Step, On, Bound string } `json:"acts"`
}
if err := json.Unmarshal(raw, &def); err != nil {
t.Fatal(err)
}
if len(def.Acts) != 1 || def.Acts[0].Step != "build" || def.Acts[0].On != "kind:image" {
t.Errorf("acts = %+v; wanted the one rule {build, kind:image}", def.Acts)
}
}
-22
View File
@@ -1,22 +0,0 @@
// Package buildstep is what both build modules share: the runner of a long step that answers a tool call at once
// and ends on its key in the module's `steps` state (novox/hq ADR 0469 §2; issue 1471), the toolchain guard
// (issue 1473), the fetch of one commit over SSH (issue 1474), and the failure contract of a test level with the parsers
// of go test -json and node --test's TAP that fill it (failure.go, issue 1901; its conformance kit is package conformance).
package buildstep
import (
"crypto/rand"
"encoding/hex"
"strconv"
"time"
)
var now = time.Now
// NewID is a step id: the time in milliseconds in base 36 and six random hex digits, lower-case letters and
// digits only, so it is one key token and differs between two steps of one node even in one millisecond.
func NewID() string {
var b [3]byte
_, _ = rand.Read(b[:])
return strconv.FormatInt(now().UnixMilli(), 36) + hex.EncodeToString(b[:])
}
-89
View File
@@ -1,89 +0,0 @@
package buildstep
import (
"encoding/json"
"sync"
"testing"
"time"
)
// keys is a steps state in memory: every value put, in order, per key, and a signal for each end.
type keys struct {
mu sync.Mutex
puts map[string][]Step
ended chan string
}
func newKeys() *keys { return &keys{puts: map[string][]Step{}, ended: make(chan string, 16)} }
func (k *keys) put(key string, value any) (uint64, error) {
step, err := DecodeStep(value.(json.RawMessage))
if err != nil {
return 0, err
}
k.mu.Lock()
k.puts[key] = append(k.puts[key], step)
n := uint64(len(k.puts[key]))
k.mu.Unlock()
if step.State != StepRunning {
k.ended <- key
}
return n, nil
}
func (k *keys) last(key string) Step {
k.mu.Lock()
defer k.mu.Unlock()
s := k.puts[key]
return s[len(s)-1]
}
func (k *keys) waitEnd(t *testing.T) string {
t.Helper()
select {
case key := <-k.ended:
return key
case <-time.After(3 * time.Second):
t.Fatal("the step never ended on its key")
return ""
}
}
// 1471/AC5: ids made in one and the same millisecond differ, and each is one key token. The clock is fixed
// while no step runs, so no goroutine reads it meanwhile.
func TestTwoIDsInOneMillisecondDiffer(t *testing.T) {
was := now
defer func() { now = was }()
at := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC)
now = func() time.Time { return at }
seen := map[string]bool{}
for i := 0; i < 50; i++ {
id := NewID()
if seen[id] {
t.Fatalf("id %q handed out twice", id)
}
seen[id] = true
if _, err := StepKey("ace", id); err != nil {
t.Errorf("id %q: %v", id, err)
}
}
}
// 1966 (G §484, §649): ParseStepKey reads both forms of a key, main's answering no asker, and refuses a third.
func TestParseStepKeyReadsBothFormsAndRefusesAThird(t *testing.T) {
for _, tc := range []struct{ key, asker, node, id string }{
{"ace.abc123", "", "ace", "abc123"},
{"runner.ace.abc123", "runner", "ace", "abc123"},
{"builder.g14.x1", "builder", "g14", "x1"},
} {
asker, node, id, err := ParseStepKey(tc.key)
if err != nil || asker != tc.asker || node != tc.node || id != tc.id {
t.Errorf("%s: %q %q %q %v", tc.key, asker, node, id, err)
}
}
for _, key := range []string{"ace", "a.b.c.d", "Runner.ace.abc123", "runner.ace.ABC", ".ace.abc123", "ace."} {
if _, _, _, err := ParseStepKey(key); err == nil {
t.Errorf("%q was read as a step key", key)
}
}
}
-225
View File
@@ -1,225 +0,0 @@
package buildstep
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
)
// The layouts this package reads and writes are the part `build-step`'s, shared by the three build seats'
// contracts in mesh-delivery-contracts (novox/hq ADR 0634 §6): this package imports no seat's contract, so the Go,
// image and Node build modules each use it with their own seat's, and the layout is held equal by the part's
// fixtures (a step's value decodes in both).
// Version is the layout version of a step value; a reader refuses another.
const Version = 1
// ErrUnknownVersion is what DecodeStep returns for a value whose version is missing or not Version.
var ErrUnknownVersion = errors.New("buildstep: unknown value version")
// The states of a step.
const (
StepRunning = "running"
// StepAgain is a step that ended on a transport fault with runs left: the bus gives its ask again after AgainAt
// (ADR 0664 §1). It is not an end (Ended), and nothing acknowledges the ask.
StepAgain = "again"
StepPassed = "passed"
StepFailed = "failed"
StepRefused = "refused"
// StepDropped is a step ended by the seat's verb drop: its asker no longer waited for it (ADR 0664 §4). The cause its
// caller named is its reason. It is an end, and no failure of the source.
StepDropped = "dropped"
)
// StepBound is how long an asker waits for one ask's step once a build node took it (30 minutes): past it the asker
// has stopped waiting, so a key still running is nobody's.
const StepBound = 30 * time.Minute
// Step is one value of a build module's `steps` state.
type Step struct {
V int `json:"v"`
ID string `json:"id"`
Tool string `json:"tool"`
Node string `json:"node"`
State string `json:"state"`
Started time.Time `json:"started"`
Ended time.Time `json:"ended,omitzero"`
Reason string `json:"reason,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
What string `json:"what,omitempty"`
Phase string `json:"phase,omitempty"`
PhaseAt time.Time `json:"phase-at,omitzero"`
Owner string `json:"owner,omitempty"`
// Run is which run of the ask this is, counted by the bus's delivery count (1 for the first); AgainAt when the bus
// gives it again (the state again); Passing says the step ended on a transport fault, so a failed end after the
// last run says so (ADR 0664 §1, §2).
Run int `json:"run,omitempty"`
AgainAt time.Time `json:"again-at,omitzero"`
Passing bool `json:"passing,omitempty"`
}
// Ended says a step's state is an end: passed, failed, refused or dropped. A step running, or ended on a transport fault with runs
// left (StepAgain), is not.
func Ended(s Step) bool { return s.State != StepRunning && s.State != StepAgain && s.State != "" }
var (
nameOK = regexp.MustCompile(`^[-/_=a-zA-Z0-9]+$`)
stepIDOK = regexp.MustCompile(`^[a-z0-9]+$`)
askerOK = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
askIDOK = regexp.MustCompile(`^[0-9a-z]{8,9}[0-9a-f]{6}$`)
)
func checkNode(node string) error {
if node == "" || !nameOK.MatchString(node) {
return fmt.Errorf("buildstep: the node name %q is empty or holds a dot, a wildcard, whitespace or a character a key refuses", node)
}
return nil
}
// StepKey is the key of a step in the steps state: `<node>.<id>`.
func StepKey(node, id string) (string, error) {
if err := checkNode(node); err != nil {
return "", err
}
if !stepIDOK.MatchString(id) {
return "", fmt.Errorf("buildstep: the step id %q is not lower-case letters and digits", id)
}
return node + "." + id, nil
}
// ParseStepKey reads both forms of a step's key (design 47 G §484, §649): `<asker>.<node>.<id>`, and main's `<node>.<id>`,
// which answers no asker (an empty asker). A third form is refused.
func ParseStepKey(key string) (asker, node, id string, err error) {
parts := strings.Split(key, ".")
switch len(parts) {
case 2:
node, id = parts[0], parts[1]
case 3:
asker, node, id = parts[0], parts[1], parts[2]
if !askerOK.MatchString(asker) {
return "", "", "", fmt.Errorf("buildstep: %q is not a step key: %q is not an asker", key, asker)
}
default:
return "", "", "", fmt.Errorf("buildstep: %q is not a step key, <asker>.<node>.<id> or <node>.<id>", key)
}
if _, err := StepKey(node, id); err != nil {
return "", "", "", fmt.Errorf("buildstep: %q is not a step key: %w", key, err)
}
return asker, node, id, nil
}
// ParseAskStepKey is ParseStepKey for the key of a pulled ask's step, whose id is the ask's (base-36 milliseconds
// and six hex digits).
func ParseAskStepKey(key string) (node, askID string, err error) {
_, node, askID, err = ParseStepKey(key)
if err != nil {
return "", "", err
}
if !askIDOK.MatchString(askID) {
return "", "", fmt.Errorf("buildstep: %q is not an ask's step key: %q is not an ask id", key, askID)
}
return node, askID, nil
}
func (s Step) check() error {
if _, err := StepKey(s.Node, s.ID); err != nil {
return err
}
if s.Tool == "" {
return fmt.Errorf("buildstep: a step needs its tool")
}
switch s.State {
case StepRunning, StepAgain, StepPassed, StepFailed, StepRefused, StepDropped:
default:
return fmt.Errorf("buildstep: the step state %q is not running, again, passed, failed, refused or dropped", s.State)
}
if len(s.Result) > 0 && !json.Valid(s.Result) {
return fmt.Errorf("buildstep: the step's result is not JSON")
}
return nil
}
// EncodeStep is a step as its value, refusing one that is not whole.
func EncodeStep(s Step) ([]byte, error) {
if err := s.check(); err != nil {
return nil, err
}
s.V = Version
return json.Marshal(s)
}
// DecodeStep reads a steps value; it refuses an unknown version (ErrUnknownVersion) and what EncodeStep refuses.
func DecodeStep(data []byte) (Step, error) {
var probe struct {
V *int `json:"v"`
}
if err := json.Unmarshal(data, &probe); err != nil {
return Step{}, fmt.Errorf("buildstep: value is not JSON: %w", err)
}
if probe.V == nil || *probe.V != Version {
return Step{}, fmt.Errorf("%w: this reader reads %d", ErrUnknownVersion, Version)
}
var s Step
if err := json.Unmarshal(data, &s); err != nil {
return Step{}, fmt.Errorf("buildstep: value does not fit its shape: %w", err)
}
if err := s.check(); err != nil {
return Step{}, err
}
return s, nil
}
var (
askCommitOK = regexp.MustCompile(`^[0-9a-f]{40}$`)
// PackageSemver is a Go semantic version as a delivery group's check names a tagged version (`v0.1.15-feat-x.2`).
PackageSemver = regexp.MustCompile(`^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`)
)
// PackageVersions are the versions of the mesh packages a build or a check builds against, by package (a Go module's
// path): each a full commit or a Go semantic version.
type PackageVersions map[string]string
// Check refuses a package that is no module path or a version that is neither a full commit nor a Go semantic
// version, naming it.
func (p PackageVersions) Check() error {
for pkg, version := range p {
if pkg == "" || strings.ContainsAny(pkg, " \t\n@") || strings.HasPrefix(pkg, "/") {
return fmt.Errorf("buildstep: the package %q is no module path", pkg)
}
if !askCommitOK.MatchString(version) && !PackageSemver.MatchString(version) {
return fmt.Errorf("buildstep: the package %s names the version %q, which is neither a full commit nor a Go semantic version (v0.1.15-feat-x.2)", pkg, version)
}
}
return nil
}
// Ask is the part of a build seat's ask that AskWhat reads: the layout is the part's `StepAsk`.
type Ask struct {
Kind string `json:"kind"`
Build *struct {
Module string `json:"module"`
FP string `json:"fp"`
Fetch map[string]any `json:"fetch"`
} `json:"build"`
Check *struct {
Fetch map[string]any `json:"fetch"`
Levels []string `json:"levels"`
Run string `json:"run"`
} `json:"check"`
Compose *struct {
Fetch map[string]any `json:"fetch"`
} `json:"compose"`
Run *RunJob `json:"run"`
}
// CheckAskID refuses an id that is no ask's: base-36 milliseconds and six hex digits, as NewID gives. Its form keeps it apart from
// a module's or a node's name in a key.
func CheckAskID(id string) error {
if !askIDOK.MatchString(id) {
return fmt.Errorf("buildstep: %q is not an ask id (base-36 milliseconds and six hex digits)", id)
}
return nil
}
-84
View File
@@ -1,84 +0,0 @@
package buildstep
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"time"
)
// ToolchainVersion is the layout version of a toolchains value.
const ToolchainVersion = 1
// Toolchain is the value of a build module's state toolchains under the key <node>.<language>: the version of the
// language's toolchain installed on the node, the build module's recipe version, and when the module saw them. It is
// the part build-step's `Toolchain`, the layout every node-build seat gives that state; the three build modules share
// this neutral form (a seat's generated type is one package per seat). A test reads each seat's fixture strictly into it.
type Toolchain struct {
V int `json:"v,omitempty"`
Language string `json:"language"`
Version string `json:"version"`
Recipe string `json:"recipe"`
// Digest is the sha256: digest of the language's toolchain program as the build module runs it, the program of the
// module that provides that language's toolchain, never the build module's own (design 47 G §472).
Digest string `json:"digest,omitempty"`
At time.Time `json:"at,omitzero"`
}
func checkToolchainLanguage(language string) error {
switch language {
case "go", "typescript":
return nil
}
return fmt.Errorf("buildstep: the toolchain language %q is not go or typescript", language)
}
// ToolchainKey is the key of a node's toolchain of one language: <node>.<language>. It refuses an empty node, a node
// with a dot and a language other than go or typescript.
func ToolchainKey(node, language string) (string, error) {
if node == "" || strings.ContainsAny(node, ". ") {
return "", fmt.Errorf("buildstep: %q is not a node name", node)
}
if err := checkToolchainLanguage(language); err != nil {
return "", err
}
return node + "." + language, nil
}
func (t Toolchain) check() error {
if err := checkToolchainLanguage(t.Language); err != nil {
return err
}
if t.Version == "" || t.Recipe == "" {
return fmt.Errorf("buildstep: a %s toolchain needs its version and its recipe", t.Language)
}
return nil
}
// EncodeToolchain is t as JSON; it refuses a language other than go or typescript and an empty version or recipe.
func EncodeToolchain(t Toolchain) ([]byte, error) {
if err := t.check(); err != nil {
return nil, err
}
t.V = ToolchainVersion
return json.Marshal(t)
}
// DecodeToolchain reads a toolchains value, refusing an unknown field, another layout version and what
// EncodeToolchain refuses.
func DecodeToolchain(data []byte) (Toolchain, error) {
var t Toolchain
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&t); err != nil {
return Toolchain{}, fmt.Errorf("buildstep: a toolchain does not read: %w", err)
}
if t.V != ToolchainVersion {
return Toolchain{}, fmt.Errorf("buildstep: a toolchain of version %d, this reads %d", t.V, ToolchainVersion)
}
if err := t.check(); err != nil {
return Toolchain{}, err
}
return t, nil
}
-80
View File
@@ -1,80 +0,0 @@
package buildstep
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// The toolchains value and key are the layout all three node-build seats generate: each seat's fixture of the state
// reads strictly into Toolchain, and the key is the seat's key form <node>.<language>.
func TestTheToolchainsValueAndKeyAreTheSeatsLayout(t *testing.T) {
read := 0
for _, seat := range []string{"node-build-go", "node-build-image", "node-build-node"} {
raw, err := os.ReadFile(filepath.Join("..", "..", "contracts", "seats", seat, "fixtures", "states.json"))
if err != nil {
t.Fatal(err)
}
var fixtures []struct {
Of string `json:"of"`
Given json.RawMessage `json:"given"`
}
if err := json.Unmarshal(raw, &fixtures); err != nil {
t.Fatal(err)
}
for _, f := range fixtures {
if f.Of != "state:toolchains/<node>.<language>" {
continue
}
if back, err := DecodeToolchain(f.Given); err != nil || back.Version == "" {
t.Errorf("%s: the fixture reads as %+v, %v", seat, back, err)
}
if _, err := EncodeToolchain(mustToolchain(t, f.Given)); err != nil {
t.Errorf("%s: %v", seat, err)
}
dec := json.NewDecoder(bytes.NewReader(f.Given))
dec.DisallowUnknownFields()
if err := dec.Decode(&Toolchain{}); err != nil {
t.Errorf("%s: %v", seat, err)
}
read++
}
}
if read != 6 { // 1966/CT12 (G §472): each seat's fixture with its program's digest too
t.Errorf("%d toolchain fixtures read, want 6", read)
}
raw, err := EncodeToolchain(Toolchain{Language: "go", Version: "go1.27.1", Recipe: "3", At: time.Date(2026, 11, 5, 10, 0, 0, 0, time.UTC)})
if err != nil {
t.Fatal(err)
}
if back, err := DecodeToolchain(raw); err != nil || back.Version != "go1.27.1" || back.At.IsZero() {
t.Errorf("the value reads back as %+v, %v", back, err)
}
if key, err := ToolchainKey("ace", "typescript"); err != nil || key != "ace.typescript" {
t.Errorf("key %q, %v", key, err)
}
for _, bad := range [][2]string{{"", "go"}, {"a.b", "go"}, {"ace", "rust"}} {
if _, err := ToolchainKey(bad[0], bad[1]); err == nil {
t.Errorf("the key of %v was made", bad)
}
}
if _, err := EncodeToolchain(Toolchain{Language: "go", Version: "go1.27"}); err == nil {
t.Error("a toolchain without its recipe was written")
}
if _, err := DecodeToolchain([]byte(`{"v":1,"language":"go","version":"x","recipe":"1","extra":1}`)); err == nil || !strings.Contains(err.Error(), "extra") {
t.Errorf("a field the layout lacks was read: %v", err)
}
}
func mustToolchain(t *testing.T, raw []byte) Toolchain {
t.Helper()
var tc Toolchain
if err := json.Unmarshal(raw, &tc); err != nil {
t.Fatal(err)
}
return tc
}
-91
View File
@@ -1,91 +0,0 @@
package buildstep
import (
"fmt"
"sort"
"strings"
)
// **The toolchain a language's builders agree on** (novox/hq ADR 0584): the nodes report their toolchain in the state
// `toolchains` of a node-build seat (the seat's generated type holds the entry); this file holds the one rule over the
// entries every reader of that state shares, over a seat-neutral form, so no reader copies it.
// ToolchainNoReport is the reason AgreedToolchain gives when no node has reported a language's toolchain.
const ToolchainNoReport = "toolchain not yet reported"
// NodeToolchain is one node's entry of a language, as read from a build seat's state toolchains (the entry is Toolchain).
type NodeToolchain struct {
Node string
Toolchain
}
// SittingOut is a node whose toolchain of a language is not the agreed one: it builds nothing of that language until
// it reports the agreed version (novox/hq ADR 0584 clause 2).
type SittingOut struct {
Node string
Version string
Recipe string
}
// Agreement is what the nodes' entries of one language come to. Toolchain is the agreed one (its language, version and
// recipe), set when Wait is empty.
// Wait is why nothing is agreed: "toolchain not yet reported" with no entries, or "builders disagree" naming each version
// and recipe with the nodes reporting it, when no version has a strict majority. SittingOut lists, sorted by node, the
// nodes that report another version than the agreed one.
type Agreement struct {
Toolchain Toolchain
SittingOut []SittingOut
Wait string
}
// ToolchainAgreement is the agreed toolchain of a language: the version and recipe a strict majority of the reporting
// nodes report (novox/hq ADR 0584 clause 1). With no strict majority (two against two) or no entry it gives no toolchain
// and says why in Wait. The answer does not depend on the entries' order. The entries must all be of one language.
func ToolchainAgreement(entries []NodeToolchain) Agreement {
if len(entries) == 0 {
return Agreement{Wait: ToolchainNoReport}
}
type identity struct{ Language, Version, Recipe string }
groups := map[identity][]string{}
for _, e := range entries {
k := identity{e.Language, e.Version, e.Recipe}
groups[k] = append(groups[k], e.Node)
}
for k, nodes := range groups {
if 2*len(nodes) > len(entries) {
a := Agreement{Toolchain: Toolchain{Language: k.Language, Version: k.Version, Recipe: k.Recipe}}
for _, e := range entries {
if e.Version != k.Version || e.Recipe != k.Recipe {
a.SittingOut = append(a.SittingOut, SittingOut{Node: e.Node, Version: e.Version, Recipe: e.Recipe})
}
}
sort.Slice(a.SittingOut, func(i, j int) bool { return a.SittingOut[i].Node < a.SittingOut[j].Node })
return a
}
}
parts := make([]string, 0, len(groups))
for k, nodes := range groups {
sort.Strings(nodes)
parts = append(parts, fmt.Sprintf("%s recipe %s on %s", k.Version, k.Recipe, strings.Join(nodes, ", ")))
}
sort.Strings(parts)
return Agreement{Wait: "builders disagree: " + strings.Join(parts, "; ")}
}
// AgreedToolchain is ToolchainAgreement's toolchain, or none and why (its Wait).
func AgreedToolchain(entries []NodeToolchain) (tc Toolchain, none string) {
a := ToolchainAgreement(entries)
return a.Toolchain, a.Wait
}
// ParseToolchainKey is the inverse of ToolchainKey.
func ParseToolchainKey(key string) (node, language string, err error) {
node, language, ok := strings.Cut(key, ".")
if !ok {
return "", "", fmt.Errorf("buildstep: %q is not a toolchain key, <node>.<language>", key)
}
if _, err := ToolchainKey(node, language); err != nil {
return "", "", fmt.Errorf("buildstep: %q is not a toolchain key: %w", key, err)
}
return node, language, nil
}
-73
View File
@@ -1,73 +0,0 @@
package buildstep
import (
"strings"
"testing"
)
func tcEntry(node, lang, version, recipe string) NodeToolchain {
return NodeToolchain{Node: node, Toolchain: Toolchain{Language: lang, Version: version, Recipe: recipe}}
}
// 1443/AC2-4, ADR 0584: the agreed toolchain is the strict majority's; a minority node sits out; a tie waits.
func TestToolchainAgreement(t *testing.T) {
e := tcEntry
for _, c := range []struct {
name string
in []NodeToolchain
version string
out []SittingOut
wait []string // "" wait means agreed
}{
{"all agree", []NodeToolchain{e("ace", "go", "1.26.1", "3"), e("novox", "go", "1.26.1", "3")}, "1.26.1", nil, nil},
{"three against one", []NodeToolchain{e("ace", "typescript", "26.12.1", "3"), e("g14", "typescript", "26.13.0", "3"), e("novox", "typescript", "26.13.0", "3"), e("shanks", "typescript", "26.13.0", "3")},
"26.13.0", []SittingOut{{"ace", "26.12.1", "3"}}, nil},
{"two against two", []NodeToolchain{e("ace", "go", "1.26.1", "3"), e("novox", "go", "1.26.2", "3"), e("g14", "go", "1.26.1", "3"), e("shanks", "go", "1.26.2", "3")},
"", nil, []string{"builders disagree", "1.26.1 recipe 3 on ace, g14", "1.26.2 recipe 3 on novox, shanks"}},
{"one node alone", []NodeToolchain{e("ace", "go", "1.26.1", "3")}, "1.26.1", nil, nil},
{"no report", nil, "", nil, []string{ToolchainNoReport}},
} {
a := ToolchainAgreement(c.in)
rev := make([]NodeToolchain, len(c.in))
for i, x := range c.in {
rev[len(c.in)-1-i] = x
}
if b := ToolchainAgreement(rev); b.Wait != a.Wait || b.Toolchain != a.Toolchain {
t.Errorf("%s: order changed the answer: %+v vs %+v", c.name, a, b)
}
if a.Toolchain.Version != c.version || len(a.SittingOut) != len(c.out) {
t.Errorf("%s: %+v", c.name, a)
}
for i := range c.out {
if a.SittingOut[i] != c.out[i] {
t.Errorf("%s: sitting out %+v, want %+v", c.name, a.SittingOut, c.out)
}
}
if (len(c.wait) == 0) != (a.Wait == "") {
t.Errorf("%s: wait %q", c.name, a.Wait)
}
for _, w := range c.wait {
if !strings.Contains(a.Wait, w) {
t.Errorf("%s: %q does not name %q", c.name, a.Wait, w)
}
}
if tc, none := AgreedToolchain(c.in); tc != a.Toolchain || none != a.Wait {
t.Errorf("%s: AgreedToolchain %+v %q", c.name, tc, none)
}
}
}
func TestToolchainKeyParsesBack(t *testing.T) {
key, err := ToolchainKey("ace", "go")
if err != nil {
t.Fatal(err)
}
if node, lang, err := ParseToolchainKey(key); err != nil || node != "ace" || lang != "go" {
t.Errorf("%q parsed to %q %q %v", key, node, lang, err)
}
for _, bad := range []string{"ace", "ace.rust", ".go", "a.b.go"} {
if _, _, err := ParseToolchainKey(bad); err == nil {
t.Errorf("%q parsed", bad)
}
}
}
-15
View File
@@ -1,15 +0,0 @@
package buildstep
// ModuleTree is what a merge holds of one module directory, as a build module's preview answers it (novox/hq ADR 0484
// clause 3, as ADR 0593 §2 changes it): its git tree id, the sha256 of its module.json, the sha256 of each lock file it
// has (go.sum, package-lock.json), and, of a module whose every artifact names its paths, each named path's git object
// id at the commit. The indexer alone computes from them (the named tree, the fingerprint); the build module's runner
// (mesh-build-go's buildstep.ModuleTrees) fills them.
type ModuleTree struct {
Tree string `json:"tree"`
Manifest string `json:"manifest"`
Locks map[string]string `json:"locks,omitempty"`
Paths map[string]string `json:"paths,omitempty"`
// Packages are no longer filled (ADR 0593 §2): kept so a preview written before still decodes.
Packages []string `json:"packages,omitempty"`
}
-32
View File
@@ -1,32 +0,0 @@
// Package catalogkey is the codec of a catalog key's parts (design 47 G §670): a fingerprint as the part of a bus
// key, and back. It imports neither mesh-sdk's views nor the bus client, so a package that only reads and writes keys
// (the builder's builds package) reaches no bus; meshcatalogclient imports it.
package catalogkey
import (
"fmt"
"strings"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// SourcePrefix2 is the prefix of a fingerprint of the current form.
const SourcePrefix2 = "src2:"
// KeyPart is a fingerprint as a key part: its 64 hex digits without the prefix, since a bus key may not hold ':'. It
// refuses a value that is not `src2:` and 64 lowercase hex digits, a src1 fingerprint included, naming it.
func KeyPart(fp string) (string, error) {
part, ok := strings.CutPrefix(fp, SourcePrefix2)
if !ok || !keys.IsHex64(part) {
return "", fmt.Errorf("fingerprint: %q is not a fingerprint of the form, %s and 64 lowercase hex digits", fp, SourcePrefix2)
}
return part, nil
}
// ParseKeyPart is the inverse of KeyPart. It refuses a part that is not 64 lowercase hex digits, naming it.
func ParseKeyPart(part string) (string, error) {
if !keys.IsHex64(part) {
return "", fmt.Errorf("fingerprint: %q is not the key part of a fingerprint, 64 lowercase hex digits", part)
}
return SourcePrefix2 + part, nil
}
-39
View File
@@ -1,39 +0,0 @@
package catalogkey
import (
"go/build"
"strings"
"testing"
)
func TestKeyPartRoundTripsAndRefusesOthers(t *testing.T) {
fp := "src2:" + strings.Repeat("a", 64)
part, err := KeyPart(fp)
if err != nil || part != strings.Repeat("a", 64) {
t.Fatalf("KeyPart = %q, %v", part, err)
}
if back, err := ParseKeyPart(part); err != nil || back != fp {
t.Fatalf("ParseKeyPart = %q, %v", back, err)
}
for _, bad := range []string{"src1:" + strings.Repeat("a", 64), "src2:abc", strings.Repeat("a", 64)} {
if _, err := KeyPart(bad); err == nil {
t.Errorf("KeyPart(%q) accepted", bad)
}
}
if _, err := ParseKeyPart("abc"); err == nil {
t.Error("ParseKeyPart(abc) accepted")
}
}
// Design 47 G §670: the package imports no bus.
func TestThePackageImportsNoBus(t *testing.T) {
p, err := build.ImportDir(".", 0)
if err != nil {
t.Fatal(err)
}
for _, i := range p.Imports {
if strings.Contains(i, "nats") || strings.Contains(i, "/views") {
t.Errorf("catalogkey imports %s", i)
}
}
}
-213
View File
@@ -1,213 +0,0 @@
// Package composer is the shape of a composition over a plain request (novox/hq ADR 0482 clause 4, issue 1621, as ADR
// 0593 §7 changes it): the request the command mesh-compose reads and the verdict it answers. The command and the
// composer that runs it are the node-engine's (mesh-host cmd/mesh-compose), built from its repository at a group's
// head, so a change to its composition code is judged by that code.
//
// **It reads its request and nothing else.** No bus, store, network, file or environment: the manifests come inside the
// request (raw, as their repository holds them), the rest of the mesh is a compose.Input, and the answer is a value.
// A manifest named only by its digest in the delivery indexer's bucket is filled before the run by Fill, by whoever
// holds the bus (the Go build module's compose job); Run refuses a digest left unfilled.
package composer
import (
"encoding/json"
"errors"
"fmt"
"slices"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// Version is the version of a Request and of a Verdict; a reader refuses another.
const Version = 1
// Package is the import path of the command, which a compose job builds at a commit of the node-engine's repository
// (novox/hq ADR 0593 §7).
const Package = "github.com/novox/mesh-host/cmd/mesh-compose"
// The depths of a composition.
const (
// DepthResolve resolves each machine's set over the rest of the mesh (compose.Resolve): what the assigner judges
// while the facts snapshot is not on the bus (issue 1461).
DepthResolve = "resolve"
// DepthCompose composes each machine's whole declaration and runs the node-engine's validator over it
// (compose.Compose).
DepthCompose = "compose"
)
// Request is everything one run composes: the rest of the mesh, one or more cases of manifests composed over it, and
// the machines composed in each case.
type Request struct {
V int `json:"v"`
// Input is the composition's input without its catalogue (and without each node's kept manifests): the cases give
// those. A Catalogue or Kept it holds is ignored. It is the node-engine's composition input as JSON, which only the
// composer decodes (novox/hq ADR 0593 §7), so this shape imports no composition.
Input json.RawMessage `json:"input"`
// Cases are composed one after the other over Input, each with its own manifests; their names are unique.
Cases []Case `json:"cases"`
// Machines are the nodes composed in every case; none means the manifests are only read.
Machines []string `json:"machines,omitempty"`
// Depth is DepthResolve or DepthCompose; empty is DepthCompose.
Depth string `json:"depth,omitempty"`
// HoldingsFromClaims adds to Input's holdings every seat an assigned module claims, held on its node (the
// assigner's input, which has no holdings of record).
HoldingsFromClaims bool `json:"holdings_from_claims,omitempty"`
// Declarations asks each composed machine's declared paths (DepthCompose only).
Declarations bool `json:"declarations,omitempty"`
// Predefined is the list of predefined keys at the catalogue's root (predefined.json, novox/hq ADR 0348 §7). No
// longer read: the composer judges no manifest (novox/hq ADR 0578 §5), the indexer's judge does, and its verdicts
// come in each case's Verdicts. Kept so an asker that still sends it is read.
Predefined catalogue.PredefinedList `json:"predefined,omitempty"`
// Packages are the known packages a manifest's `packages` may name, each by its name in its own ecosystem (design 32:
// a Go package's go.mod module path, a TypeScript package's package.json name), for the indexer's judge (novox/hq ADR
// 0578 §5, ADR 0606 §4); the composer does not read them. Nil is no list at hand, and the judge judges no name; an
// empty list is a list, and every name is unknown to it.
Packages []string `json:"packages,omitzero"`
// Seats are the seat definitions the judge judges and the composer composes against, as the asker's seat list reader holds
// them (the definitions of the seat mesh-catalog, resolved), raw so that this package names no seat (ADR 0635 §4, ADR 0636
// §1). The judge and the composer read them. None is no list at hand: a composer handed none judges no machine (ADR 0636 §1).
Seats []json.RawMessage `json:"seats,omitempty"`
}
// Case is one catalogue composed: every module's manifest by name, and per node the manifests kept at the build it runs.
//
// Assignments are, by node, the assignments the case composes that node with in place of what Input says of it: a change's
// own assignments files, so a check composes a catalogue pull request's assignments (issue 1126, frombus.Placed); a null
// assignments leaves nothing placed on the node. A case without them composes Input's.
//
// Verdicts are, by module, as raw JSON (this package is seat-neutral, novox/hq ADR 0635 §4; the node-engine's composer decodes the
// mesh-catalog seat's manifest verdict, and Assignments the mesh-module-assigner seat's assignments), the indexer's judge's verdict on its manifest in Manifests (novox/hq ADR 0578 §5), put in by
// the assigner or the checker that runs the composer: a refused one is held, composed as its stub so what it offers
// still shapes the rest, and named in the case's verdict. A module without one is accepted (the mesh-catalog seat's ManifestVerdict, taken by its readers).
type Case struct {
Name string `json:"name"`
Manifests map[string]Manifest `json:"manifests"`
Verdicts map[string]json.RawMessage `json:"verdicts,omitempty"`
Kept map[string]map[string]Manifest `json:"kept,omitempty"`
Assignments map[string]json.RawMessage `json:"assignments,omitempty"`
}
// Manifest is a module's manifest as its repository holds it (Raw, the bytes), or the digest the delivery indexer keeps
// it under (Digest), which Fill replaces by the bytes. On the wire it is the manifest itself, or {"digest": "..."}.
type Manifest struct {
Raw json.RawMessage
Digest string
}
// MarshalJSON writes the raw manifest, or {"digest": ...} when only the digest is known.
func (m Manifest) MarshalJSON() ([]byte, error) {
if len(m.Raw) > 0 {
return m.Raw, nil
}
return json.Marshal(map[string]string{"digest": m.Digest})
}
// UnmarshalJSON reads {"digest": "..."} (an object with that one key) as a digest, and any other value as the raw
// manifest.
func (m *Manifest) UnmarshalJSON(raw []byte) error {
var probe map[string]json.RawMessage
if json.Unmarshal(raw, &probe) == nil && len(probe) == 1 {
if d, ok := probe["digest"]; ok {
var digest string
if err := json.Unmarshal(d, &digest); err != nil {
return fmt.Errorf("a manifest's digest is not a string: %w", err)
}
*m = Manifest{Digest: digest}
return nil
}
}
*m = Manifest{Raw: slices.Clone(raw)}
return nil
}
// Verdict is what one run answers: the mesh-sdk the command was built with, and each case's verdict in the order asked.
type Verdict struct {
V int `json:"v"`
SDK string `json:"sdk"`
Cases []CaseVerdict `json:"cases"`
}
// CaseVerdict is one case's: every manifest read or refused, every machine composed or not.
type CaseVerdict struct {
Name string `json:"name"`
Manifests map[string]ManifestRead `json:"manifests"`
Machines map[string]Machine `json:"machines,omitempty"`
}
// ManifestRead is one manifest as this mesh-sdk reads it: accepted, or refused with why: the indexer's verdict
// (Case.Verdicts) or bytes that do not decode. A field the decoder does not know is set aside, named in SetAside, and
// the manifest still accepted (novox/hq ADR 0578 §6).
type ManifestRead struct {
Accepted bool `json:"accepted"`
Refused string `json:"refused,omitempty"`
SetAside string `json:"set_aside,omitempty"`
}
// Machine is one machine composed: whether it composes (resolves, at DepthResolve), why not, the node-engine
// validator's problems and the composition's refusals (DepthCompose), and its declared paths when asked. NotJudged says,
// in words, why the composer did not judge the machine (an older node-engine's input that does not say how it composes,
// novox/hq ADR 0593 §9): the machine is then neither composed nor refused, and a reader decides by this field alone,
// never by the words of Reason.
type Machine struct {
Composes bool `json:"composes"`
NotJudged string `json:"not_judged,omitempty"`
Reason string `json:"reason,omitempty"`
Problems []string `json:"problems,omitempty"`
Refusals []string `json:"refusals,omitempty"`
Declared []Path `json:"declared,omitempty"`
}
// Path is one path a declaration puts on the machine, with its kind (the resource's type), owner, group and mode as
// declared, and the module it is of.
type Path struct {
Path string `json:"path"`
Kind string `json:"kind"`
Owner string `json:"owner,omitempty"`
Group string `json:"group,omitempty"`
Mode string `json:"mode,omitempty"`
Module string `json:"module,omitempty"`
}
// ErrUnfilled is a manifest named by a digest that nobody replaced by its bytes.
var ErrUnfilled = errors.New("composer: a manifest is named by its digest and was not filled")
// Decode reads a request; it refuses one that is not JSON or of another version.
func Decode(data []byte) (Request, error) {
var r Request
if err := json.Unmarshal(data, &r); err != nil {
return Request{}, fmt.Errorf("composer: the request is not JSON of its shape: %w", err)
}
if r.V != Version {
return Request{}, fmt.Errorf("composer: a request of version %d, this composer reads %d", r.V, Version)
}
return r, nil
}
// Fill replaces every manifest named by its digest by the bytes get answers for that digest; a digest get cannot answer
// stops it, named.
func Fill(r *Request, get func(digest string) ([]byte, error)) error {
fill := func(m map[string]Manifest) error {
for name, man := range m {
if len(man.Raw) > 0 {
continue
}
raw, err := get(man.Digest)
if err != nil {
return fmt.Errorf("composer: the manifest of %s (digest %s): %w", name, man.Digest, err)
}
m[name] = Manifest{Raw: raw}
}
return nil
}
for _, c := range r.Cases {
if err := fill(c.Manifests); err != nil {
return err
}
for _, kept := range c.Kept {
if err := fill(kept); err != nil {
return err
}
}
}
return nil
}
-58
View File
@@ -1,58 +0,0 @@
package composer
import (
"encoding/json"
"errors"
"strings"
"testing"
)
const demo = `{"module": "demo", "version": "1", "claims": [{"name": "node-files"}]}`
// A manifest named by its digest goes on the wire as {"digest": ...}, and Fill puts the bytes the indexer keeps in its
// place; a raw manifest goes as itself.
func TestAManifestIsItsBytesOrItsDigest(t *testing.T) {
r := Request{V: Version, Cases: []Case{{Name: "change", Manifests: map[string]Manifest{
"demo": {Digest: "d1"}, "raw": {Raw: json.RawMessage(`{"module":"raw","version":"1"}`)}},
Kept: map[string]map[string]Manifest{"laptop": {"demo": {Digest: "d1"}}}}}}
wire, err := json.Marshal(r)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(wire), `"demo":{"digest":"d1"}`) || !strings.Contains(string(wire), `"raw":{"module":"raw","version":"1"}`) {
t.Fatalf("on the wire: %s", wire)
}
back, err := Decode(wire)
if err != nil {
t.Fatal(err)
}
asked := 0
if err := Fill(&back, func(d string) ([]byte, error) {
asked++
if d != "d1" {
return nil, errors.New("no such digest")
}
return []byte(demo), nil
}); err != nil {
t.Fatal(err)
}
if asked != 2 || string(back.Cases[0].Manifests["demo"].Raw) != demo || string(back.Cases[0].Kept["laptop"]["demo"].Raw) != demo {
t.Fatalf("filled %d times: %+v", asked, back.Cases[0])
}
// The known packages: none is no list (not on the wire), an empty list is a list, and a list reads back whole.
for _, known := range [][]string{nil, {}, {"git.novox.be/novox/mesh-sdk", "@novox/mesh-sdk"}} {
wire, err := json.Marshal(Request{V: Version, Packages: known})
if err != nil {
t.Fatal(err)
}
back, err := Decode(wire)
if err != nil || (back.Packages == nil) != (known == nil) || strings.Join(back.Packages, ",") != strings.Join(known, ",") ||
known == nil && strings.Contains(string(wire), "packages") {
t.Errorf("the known packages %#v went as %s and read back %#v (%v)", known, wire, back.Packages, err)
}
}
bad := Request{V: Version, Cases: []Case{{Name: "c", Manifests: map[string]Manifest{"x": {Digest: "nope"}}}}}
if err := Fill(&bad, func(string) ([]byte, error) { return nil, errors.New("not there") }); err == nil || !strings.Contains(err.Error(), "nope") {
t.Fatalf("a digest the indexer does not hold: %v", err)
}
}
-107
View File
@@ -1,107 +0,0 @@
// Package forgekey holds the Delivery domain's names beside mesh-sdk's forgekey (novox/hq ADR 0635 §4): the kind of
// key a build module keeps, the runner whose commands get exactly the environment they are given (a fetch holds no
// registry password), and the words a failed command is reported in. mesh-sdk's forgekey keeps what every module's
// key keeper shares: KeyKeeper, KeyPutter, Runner, ExecRunner and Ran.
package forgekey
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
"unicode/utf8"
sdk "git.novox.be/novox/mesh-sdk/go/forgekey"
)
// KindBuilder is the kind of key a build module's account keeps (ADR 0466 §2); sdk.KindMachine is a machine's own.
const KindBuilder = "builder"
// ExecRunnerClean is a runner whose commands get exactly the env argument as their environment, and nothing of this
// process's (issue 1497; novox/hq ADR 0466 §4: no registry password in a fetch's environment). The caller gives PATH
// and HOME itself. A directory is the command's own business (`git -C`, `go -C`): it is started in the HOME it is
// given, or the machine's temporary directory, never in this process's. bound 0 leaves only the step's own context.
func ExecRunnerClean(bound time.Duration) sdk.Runner {
return func(ctx context.Context, env []string, name string, args ...string) sdk.Ran {
if bound > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, bound)
defer cancel()
}
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = append([]string{}, env...) // non-nil, so an empty list is an empty environment
cmd.Dir = homeOrTemp(env)
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
err := cmd.Run()
r := sdk.Ran{Stdout: out.String(), Stderr: errb.String()}
var exitErr *exec.ExitError
switch {
case errors.Is(ctx.Err(), context.DeadlineExceeded):
r.Status, r.Err = 124, "ended by its step's deadline"
if bound > 0 {
r.Err = fmt.Sprintf("no answer within %d s", int(bound/time.Second))
}
case errors.Is(err, exec.ErrNotFound):
r.Status, r.Err = 127, "ENOENT"
case errors.As(err, &exitErr):
r.Status = exitErr.ExitCode()
case err != nil:
r.Status, r.Err = 1, err.Error()
}
return r
}
}
// homeOrTemp is the directory a clean command starts in: the HOME it is given, or the temporary directory (novox/hq
// issue 734: never one that may be deleted under it, as a module's build directory is when a new build replaces it).
func homeOrTemp(env []string) string {
for i := len(env) - 1; i >= 0; i-- {
if home, ok := strings.CutPrefix(env[i], "HOME="); ok {
if info, err := os.Stat(home); err == nil && info.IsDir() {
return home
}
break
}
}
return os.TempDir()
}
// SaidBound bounds what Said keeps of a command's words, so a reason stays a line of a step's record and of a log.
const SaidBound = 600
// Said is what a command said of its failure in its own words, for a reason: every line that says something, trimmed
// and joined with "; ", bounded at SaidBound bytes. A line that is a bare prefix and nothing else (git writes "error:"
// alone before and after the forge's own message, "remote:" or "fatal:" likewise) is left out, so the cause is never
// cut off behind it.
func Said(s string) string {
var keep []string
for _, l := range strings.Split(s, "\n") {
l = strings.TrimSpace(l)
if l == "" || barePrefix(l) {
continue
}
keep = append(keep, l)
}
out := strings.Join(keep, "; ")
if len(out) > SaidBound {
cut := SaidBound
for cut > 0 && !utf8.RuneStart(out[cut]) {
cut--
}
out = out[:cut] + " …"
}
return out
}
// barePrefix says whether a line is one word and a colon, such as "error:" or "remote:", with nothing after it.
func barePrefix(l string) bool {
if !strings.HasSuffix(l, ":") {
return false
}
return !strings.ContainsAny(strings.TrimSuffix(l, ":"), " \t:")
}
-49
View File
@@ -1,49 +0,0 @@
package forgekey
import (
"context"
"os"
"strings"
"testing"
sdk "git.novox.be/novox/mesh-sdk/go/forgekey"
)
func TestSaidKeepsTheCauseBehindABarePrefix(t *testing.T) {
forge := "error: \nerror: User: 22:nox-builder is not authorized to read novox/x.\nerror: \nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\n"
for _, c := range []struct{ name, in, want string }{
{"forge refusal", forge, "error: User: 22:nox-builder is not authorized to read novox/x.; fatal: Could not read from remote repository.; Please make sure you have the correct access rights"},
{"one line", "fatal: couldn't find remote ref x\n", "fatal: couldn't find remote ref x"},
{"bare prefixes only", "error:\nremote:\n", ""},
{"a colon inside stays", " ENOENT \nfatal: bad: thing\n", "ENOENT; fatal: bad: thing"},
{"empty", "", ""},
} {
if got := Said(c.in); got != c.want {
t.Errorf("%s: Said = %q, want %q", c.name, got, c.want)
}
}
long := Said(strings.Repeat("é", SaidBound))
if !strings.HasSuffix(long, " …") || len(long) > SaidBound+len(" …") || !strings.HasPrefix(long, "é") {
t.Errorf("long: %d bytes, ends %q", len(long), long[len(long)-6:])
}
}
// ExecRunnerClean gives the command only the env argument, and starts it in the HOME it is given, even when this
// process's directory was deleted under it (issue 1497, issue 734).
func TestExecRunnerCleanGivesTheCommandOnlyTheEnvArgument(t *testing.T) {
t.Setenv("MESH_TEST_SECRET", "x")
var run sdk.Runner = ExecRunnerClean(0)
r := run(context.Background(), []string{"PATH=" + os.Getenv("PATH"), "HOME=/h"}, "env")
if r.Status != 0 || !strings.Contains(r.Stdout, "HOME=/h") || strings.Contains(r.Stdout, "MESH_TEST_SECRET") {
t.Errorf("ran = %+v", r)
}
home, gone := t.TempDir(), t.TempDir()
t.Chdir(gone)
if err := os.Remove(gone); err != nil {
t.Fatal(err)
}
r = run(context.Background(), []string{"PATH=" + os.Getenv("PATH"), "HOME=" + home}, "pwd")
if r.Status != 0 || strings.TrimSpace(r.Stdout) != home {
t.Errorf("a clean command run from a deleted directory = %+v, want it started in its HOME %s", r, home)
}
}
-18
View File
@@ -1,18 +0,0 @@
module git.novox.be/novox/mesh-delivery/sdk
go 1.26.0
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-contracts/go/seats/nodeengine v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000
github.com/klauspost/compress v1.20.1 // indirect
github.com/nats-io/nats.go v1.54.0 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/sys v0.48.0 // indirect
)
require git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000
-12
View File
@@ -1,12 +0,0 @@
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
-26
View File
@@ -1,26 +0,0 @@
package graph
import (
"maps"
"slices"
"git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
)
// NodeOf is the node of the module graph a catalog graph entry carries, as the indexer took it in (design 47, *Two
// graphs*): the catalog half's holder reads its graph back from its newest trunk revision, and every part that reads the
// catalog half reads the module graph from its entries, never from the holder's state.
func NodeOf(e meshcatalog.CatalogEntry) Node {
n := Node{V: Version, FP: e.Fp, None: e.None, Repository: e.Repository, Path: e.Path, Bases: e.Bases,
Provides: e.Provides, Requires: e.Requires, Awaits: e.Awaits, Invokes: e.Invokes, Serves: e.Serves, LeftOut: e.LeftOut}
if len(e.Packages) > 0 {
n.Packages = slices.Sorted(maps.Keys(e.Packages))
}
for language, t := range e.Toolchains {
if n.Toolchains == nil {
n.Toolchains = map[string]Toolchain{}
}
n.Toolchains[language] = Toolchain{Module: t.Module, Version: t.Version, Recipe: t.Recipe}
}
return n
}
-621
View File
@@ -1,621 +0,0 @@
package graph
import (
"encoding/json"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"strings"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-delivery/sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
)
// Version is the version of a node's value this package writes and the only one it reads.
const Version = 1
// ErrUnknownVersion is what Decode returns for a value whose version is missing or not Version.
var ErrUnknownVersion = errors.New("graph: unknown value version")
func decode(data []byte, into *Node) error {
var probe struct {
V *int `json:"v"`
}
if err := json.Unmarshal(data, &probe); err != nil {
return fmt.Errorf("graph: value does not fit its shape: %w", err)
}
if probe.V == nil || *probe.V != Version {
return fmt.Errorf("%w: this reader reads %d", ErrUnknownVersion, Version)
}
if err := json.Unmarshal(data, into); err != nil {
return fmt.Errorf("graph: value does not fit its shape: %w", err)
}
return nil
}
// checkName refuses a module name a key cannot hold (meshcatalogclient.ModulesKey's rule).
func checkName(kind, name string) error {
if _, err := meshcatalogclient.ModulesKey(name); err != nil {
return fmt.Errorf("graph: the %s name %q: %w", kind, name, err)
}
return nil
}
// checkRepository refuses a repository that is not <owner>/<name>.
func checkRepository(repository string) error {
owner, name, ok := strings.Cut(repository, "/")
if !ok || owner == "" || name == "" || strings.Contains(name, "/") {
return fmt.Errorf("graph: the repository %q is not <owner>/<name>", repository)
}
return nil
}
// The module graph (novox/hq ADR 0603 §2, ADR 0604 §1): the indexer keeps, as its state `graph`, one key per module it
// holds the inputs of, written at every recompute and deleted with the module. A key holds the module's build edges
// (its bases, the mesh packages its fingerprint takes, and per language the build module, toolchain version and recipe
// version its fingerprint names, ADR 0530 §1) and its provision edges (what its manifest provides, requires, and of what
// it requires what a want of it waits for). Nothing stores an order: a reader works it out from the edges (ADR 0603
// §1, §6). The indexer writes it and works the edges out (EdgesOf), the delivery view, the checker and the indexer's
// answers of the seat mesh-catalog read it; all three are in this repository, which uses this package by path (the
// operator, 2026-11-03: no graph-related code in mesh-sdk, only contracts). It names no module.
const (
// State is the name of the indexer's state of the module graph, as its manifest declares it: one key per module
// (Key). Its bucket is the holder's name and the state's, which the indexer and each reader name from its own
// manifest, never this package (ADR 0625 §4).
State = "graph"
// History is the revisions the graph state keeps per key (ADR 0603 §2).
History = 5
)
// Key is the key, in Bucket, of a module: `<module>`, as ModulesKey.
func Key(module string) (string, error) { return meshcatalogclient.ModulesKey(module) }
// ParseKey is the inverse of Key.
func ParseKey(key string) (string, error) {
module, err := Key(key)
if err != nil {
return "", fmt.Errorf("graph: %q is not a graph key: %w", key, err)
}
return module, nil
}
// Node is the value of a graph key: one module's edges as its last recompute computed them. FP is its new-form
// fingerprint then, or None why it has none (exactly one is set); Repository and Path say where it is (as Module), so a
// package edge is resolved to the module that publishes it (GraphPublisher). Bases are the modules it is built on;
// Packages the mesh packages (Go module paths) its fingerprint took (Module.Packages); Toolchains, by language, the
// build module and the toolchain it was computed with. Provides are the provisions its manifest offers (its own name is
// provided too and is not listed), Requires what it requires and does not require optionally, and Awaits those of
// Requires a want of it waits for (catalogue.Awaited, ADR 0570 §4): the provision edges that order a source revision.
// A bus-state entry of its manifest is a requirement of the provision BusState (ADR 0614 §5). Invokes are the seat verbs
// (`seat:<seat>.<verb>`) and module tools (`<module>.<tool>`) its manifest and its own bus accounts invoke, Serves those
// its claims serve and its own tools answer, in the same two forms (ADR 0614 §2), and LeftOut those of Invokes whose
// verb edge lies on a cycle and is left out of the graph, so no want waits on it (§3; LeaveOut works them out).
// Every list is sorted and each entry once; an encode sorts them.
type Node struct {
V int `json:"v"`
FP string `json:"fp,omitempty"`
None string `json:"none,omitempty"`
Repository string `json:"repository"`
Path string `json:"path,omitempty"`
Bases []string `json:"bases,omitempty"`
Packages []string `json:"packages,omitempty"`
Toolchains map[string]Toolchain `json:"toolchains,omitempty"`
Provides []string `json:"provides,omitempty"`
Requires []string `json:"requires,omitempty"`
Awaits []string `json:"awaits,omitempty"`
Invokes []string `json:"invokes,omitempty"`
Serves []string `json:"serves,omitempty"`
LeftOut []string `json:"left-out,omitempty"`
}
// BusState is the provision a bus-state entry of a manifest requires (ADR 0614 §5): the bus module's build that offers it
// goes before the module that asks bus state.
const BusState = "bus-state"
// Toolchain is a build edge of one language: the build module that builds it (Module) and the toolchain version
// and recipe version its fingerprint names.
type Toolchain struct {
Module string `json:"module"`
Version string `json:"version"`
Recipe string `json:"recipe"`
}
func (g Node) check() error {
switch {
case (g.FP == "") == (g.None == ""):
return fmt.Errorf("graph: a graph node has either a fingerprint or a reason for none, not both or neither")
case g.FP != "" && !strings.HasPrefix(g.FP, meshcatalogclient.SourcePrefix2):
return fmt.Errorf("graph: the graph node's fingerprint %q does not start with %s", g.FP, meshcatalogclient.SourcePrefix2)
}
if err := checkRepository(g.Repository); err != nil {
return err
}
for _, b := range g.Bases {
if err := checkName("base", b); err != nil {
return err
}
}
for _, p := range g.Packages {
if _, _, ok := trunk.PackageRepository(p); !ok {
return fmt.Errorf("graph: the graph node's package %q is no mesh package's path", p)
}
}
for language, t := range g.Toolchains {
if err := checkName("build module", t.Module); err != nil {
return fmt.Errorf("graph: the graph node's toolchain of %q: %w", language, err)
}
if language == "" || t.Version == "" || t.Recipe == "" {
return fmt.Errorf("graph: the graph node's toolchain of %q needs its language, version and recipe version", language)
}
}
for _, list := range [][]string{g.Provides, g.Requires, g.Awaits} {
if slices.Contains(list, "") {
return fmt.Errorf("graph: a graph node names an empty provision")
}
}
for _, a := range g.Awaits {
if !slices.Contains(g.Requires, a) {
return fmt.Errorf("graph: the graph node awaits %q, which it does not require", a)
}
}
for _, list := range [][]string{g.Invokes, g.Serves} {
for _, v := range list {
if !isVerb(v) {
return fmt.Errorf("graph: the graph node names %q, which is neither seat:<seat>.<verb> nor <module>.<tool>", v)
}
}
}
for _, l := range g.LeftOut {
if !slices.Contains(g.Invokes, l) {
return fmt.Errorf("graph: the graph node leaves out %q, which it does not invoke", l)
}
}
return nil
}
// isVerb says whether v is a seat verb `seat:<seat>.<verb>` or a module tool `<module>.<tool>`.
func isVerb(v string) bool {
if _, _, ok := catalogue.SeatInvoke(v); ok {
return true
}
module, tool, ok := strings.Cut(v, ".")
return ok && module != "" && tool != "" && !strings.HasPrefix(v, "seat:")
}
func sortedOnce(in []string) []string {
if len(in) == 0 {
return nil
}
out := slices.Clone(in)
slices.Sort(out)
return slices.Compact(out)
}
func (g Node) normal() Node {
g.Bases, g.Packages = sortedOnce(g.Bases), sortedOnce(g.Packages)
g.Provides, g.Requires, g.Awaits = sortedOnce(g.Provides), sortedOnce(g.Requires), sortedOnce(g.Awaits)
g.Invokes, g.Serves, g.LeftOut = sortedOnce(g.Invokes), sortedOnce(g.Serves), sortedOnce(g.LeftOut)
if len(g.Toolchains) == 0 {
g.Toolchains = nil
}
return g
}
// Encode is g as JSON at Version, its lists sorted; it refuses what Node's contract does not hold.
func Encode(g Node) ([]byte, error) {
g = g.normal()
if err := g.check(); err != nil {
return nil, err
}
g.V = Version
return json.Marshal(g)
}
// Decode reads a graph node; it refuses an unknown version (ErrUnknownVersion) and what Encode refuses.
func Decode(data []byte) (Node, error) {
var g Node
if err := decode(data, &g); err != nil {
return Node{}, err
}
if err := g.check(); err != nil {
return Node{}, err
}
return g.normal(), nil
}
// Same says whether two graph nodes are the same value once sorted, so a writer writes only when they differ.
func Same(a, b Node) bool {
a, b = a.normal(), b.normal()
a.V, b.V = 0, 0
return reflect.DeepEqual(a, b)
}
// Graph is the module graph as a reader holds it: every graph node, by module.
type Graph map[string]Node
// Providers are the modules that provide provision: each whose Provides names it, and the module of that name (a module
// provides its own name), sorted.
func (g Graph) Providers(provision string) []string {
var out []string
for name, n := range g {
if name == provision || slices.Contains(n.Provides, provision) {
out = append(out, name)
}
}
slices.Sort(out)
return out
}
// Requirers are the modules that require provision, not optionally, sorted.
func (g Graph) Requirers(provision string) []string {
var out []string
for name, n := range g {
if slices.Contains(n.Requires, provision) {
out = append(out, name)
}
}
slices.Sort(out)
return out
}
// Publisher is the module of the graph whose repository and directory publish the mesh package pkg (PackageRepository):
// the module whose directory is the package's directory or the nearest one above it (the longest match, a package
// published from inside a module's directory belonging to that module), or "" when the graph holds none.
func (g Graph) Publisher(pkg string) string {
repository, dir, ok := trunk.PackageRepository(pkg)
if !ok {
return ""
}
if dir == "" {
dir = meshcatalogclient.RootPath
}
best, bestLen := "", -1
for _, name := range slices.Sorted(maps.Keys(g)) {
n := g[name]
if n.Repository != repository {
continue
}
switch {
case n.Path == dir:
return name
case n.Path == meshcatalogclient.RootPath:
if bestLen < 0 {
best, bestLen = name, 0
}
case strings.HasPrefix(dir, n.Path+"/") && len(n.Path) > bestLen:
best, bestLen = name, len(n.Path)
}
}
return best
}
// buildEdges are the modules n's build edges reach: its bases, the publisher of each of its packages, and the build
// module of each language.
func (g Graph) buildEdges(n Node) []string {
out := slices.Clone(n.Bases)
for _, p := range n.Packages {
if m := g.Publisher(p); m != "" {
out = append(out, m)
}
}
for _, t := range n.Toolchains {
out = append(out, t.Module)
}
return sortedOnce(out)
}
// Dependents are the modules whose build edges reach module, directly or through other modules' (a base of a base, a
// module built by a build module that stands on module), sorted and without module itself (ADR 0604 §1): what a
// change of module builds again.
func (g Graph) Dependents(module string) []string {
reverse := map[string][]string{}
for _, name := range slices.Sorted(maps.Keys(g)) {
for _, to := range g.buildEdges(g[name]) {
reverse[to] = append(reverse[to], name)
}
}
seen := map[string]bool{module: true}
queue := []string{module}
var out []string
for len(queue) > 0 {
at := queue[0]
queue = queue[1:]
for _, from := range reverse[at] {
if !seen[from] {
seen[from] = true
out = append(out, from)
queue = append(queue, from)
}
}
}
slices.Sort(out)
return out
}
// Servers are the modules whose Serves names invoke (a seat verb or a module tool), sorted.
func (g Graph) Servers(invoke string) []string {
var out []string
for name, n := range g {
if slices.Contains(n.Serves, invoke) {
out = append(out, name)
}
}
slices.Sort(out)
return out
}
// waits are the modules name waits for, sorted: its bases, for each provision it awaits every other module that provides
// it (ADR 0603 §1), and with verbs for each invoke the module serving it (ADR 0614 §2), those it leaves out (§3) left
// out unless all is set.
func (g Graph) waits(name string, verbs, all bool) []string {
n := g[name]
out := slices.Clone(n.Bases)
for _, a := range n.Awaits {
for _, p := range g.Providers(a) {
if p != name {
out = append(out, p)
}
}
}
if verbs {
for _, v := range n.Invokes {
if !all && slices.Contains(n.LeftOut, v) {
continue
}
for _, s := range g.Servers(v) {
if s != name || all {
out = append(out, s)
}
}
}
}
return sortedOnce(out)
}
// Before are the modules name waits for, by the graph's ordering edges, sorted: its bases, for each provision it awaits
// (bus state among them, ADR 0614 §5) every other module that provides it (ADR 0603 §1), and for each verb it invokes
// and the graph keeps, every other module that serves it (ADR 0614 §2, §3). A toolchain or package edge orders nothing:
// it is a trigger, never a wait (ADR 0614 §6).
func (g Graph) Before(name string) []string { return g.waits(name, true, false) }
// LeaveOut sets each node's LeftOut (ADR 0614 §3): every invoke whose verb edge lies on a cycle of the edges a part waits
// on (bases, awaited provisions, every verb edge), whichever module the edge starts from, a module invoking what it
// serves itself included. An edge lies on a cycle when the module it reaches reaches the module it starts from: both are
// in one strongly connected part of the graph. What is left of the graph then has no cycle through a verb edge, so the
// check's refusal (Cycle) never meets one.
func (g Graph) LeaveOut() {
part := g.parts(func(name string) []string { return g.waits(name, true, true) })
for _, name := range slices.Sorted(maps.Keys(g)) {
n := g[name]
n.LeftOut = nil
for _, v := range n.Invokes {
for _, s := range g.Servers(v) {
if part[s] == part[name] {
n.LeftOut = append(n.LeftOut, v)
break
}
}
}
g[name] = n.normal()
}
}
// parts numbers each module by the strongly connected part of edges it is in (Tarjan's), so two modules have one number
// when each reaches the other.
func (g Graph) parts(edges func(string) []string) map[string]int {
index, low, part := map[string]int{}, map[string]int{}, map[string]int{}
onStack := map[string]bool{}
var stack []string
next, parts := 0, 0
var visit func(string)
visit = func(name string) {
index[name], low[name] = next, next
next++
stack = append(stack, name)
onStack[name] = true
for _, to := range edges(name) {
if _, ours := g[to]; !ours {
continue
}
if _, seen := index[to]; !seen {
visit(to)
low[name] = min(low[name], low[to])
} else if onStack[to] {
low[name] = min(low[name], index[to])
}
}
if low[name] == index[name] {
for {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
onStack[top] = false
part[top] = parts
if top == name {
break
}
}
parts++
}
}
for _, name := range slices.Sorted(maps.Keys(g)) {
if _, seen := index[name]; !seen {
visit(name)
}
}
return part
}
// Cycle is the first cycle of the graph's ordering edges (Before), as the modules it passes through with the first named
// again at its end (a -> b -> a), or nil for none (ADR 0603 §2: the check refuses it and names it). The ordering edges
// are what a part waits on, provisions, bus state and the verb edges the graph keeps (ADR 0614 §6), and bases, since a
// module built on another's artifact can never build in a cycle of bases: modules ordered on each other would each wait
// for the other for good. A verb edge the graph leaves out (LeaveOut) is none, and neither is a toolchain edge (ADR 0603
// §3: nothing waits on a build module) or a package edge (ADR 0614 §6: a trigger). The modules are visited in sorted
// order, so the same graph names the same cycle.
func (g Graph) Cycle() []string {
edges := g.Before
const (
unseen = iota
onPath
done
)
state := map[string]int{}
var path []string
var visit func(string) []string
visit = func(name string) []string {
state[name] = onPath
path = append(path, name)
for _, to := range edges(name) {
if _, ours := g[to]; !ours {
continue
}
switch state[to] {
case onPath:
i := slices.Index(path, to)
return append(slices.Clone(path[i:]), to)
case unseen:
if c := visit(to); c != nil {
return c
}
}
}
path = path[:len(path)-1]
state[name] = done
return nil
}
for _, name := range slices.Sorted(maps.Keys(g)) {
if state[name] == unseen {
if c := visit(name); c != nil {
return c
}
}
}
return nil
}
// EdgesOf is the graph node of manifest's own edges: its bases (each module its build stands on), what it provides,
// what it requires and does not require optionally, a bus-state entry as a requirement of BusState (ADR 0614 §5), and of
// those what a want of it waits for (catalogue.Awaited, as the assigner judges it; BusState whenever a provider offers
// it), providers answering the manifests that provide a provision; and the verbs and tools it invokes and serves
// (InvokesOf, ServesOf). The fingerprint, place, packages, toolchains and the verb edges left out (LeaveOut, over the
// whole graph) are the indexer's to add; this is the part a reader of manifests alone (the checker) works out the same way.
func EdgesOf(manifest catalogue.Manifest, providers func(provision string) []catalogue.Manifest) Node {
var n Node
if manifest.Build != nil {
for _, on := range manifest.Build.On {
if on.Module != "" {
n.Bases = append(n.Bases, on.Module)
}
}
}
for _, o := range manifest.Provides {
n.Provides = append(n.Provides, o.Name)
}
for _, r := range manifest.Requires {
if !manifest.OptionalRequires[r] {
n.Requires = append(n.Requires, r)
}
}
n.Awaits = catalogue.Awaited(manifest, providers)
if len(manifest.BusState) > 0 {
n.Requires = append(n.Requires, BusState)
if len(providers(BusState)) > 0 {
n.Awaits = append(n.Awaits, BusState)
}
}
n.Invokes, n.Serves = InvokesOf(manifest), ServesOf(manifest)
return n.normal()
}
// InvokesOf are the seat verbs and module tools manifest invokes, its own and its processes' and tools bundles' bus
// accounts' (catalogue.Manifest.BusAccounts), sorted, each once; `*`, every tool, names no edge and is left out.
func InvokesOf(manifest catalogue.Manifest) []string {
all := slices.Clone(manifest.Invokes)
for _, a := range manifest.BusAccounts() {
all = append(all, a.Bus.Invokes...)
}
var out []string
for _, v := range all {
if isVerb(v) {
out = append(out, v)
}
}
return sortedOnce(out)
}
// ServesOf are the seat verbs manifest's claims serve (`seat:<seat>.<verb>`, catalogue.Claim.ServesFor) and its own
// tools (`<module>.<tool>`), sorted, each once.
func ServesOf(manifest catalogue.Manifest) []string {
var out []string
for _, c := range manifest.Claims {
for _, v := range c.ServesFor(manifest) {
out = append(out, "seat:"+c.Name+"."+v)
}
}
for _, t := range manifest.Tools {
out = append(out, manifest.Module+"."+t)
}
var verbs []string
for _, v := range out {
if isVerb(v) {
verbs = append(verbs, v)
}
}
return sortedOnce(verbs)
}
// OfManifests is the graph of these manifests' own edges (EdgesOf), by module, each provision's providers being
// the manifests among them that offer it, with the verb edges on a cycle left out (LeaveOut): what the check works out
// for a change to find a cycle (ADR 0603 §2, ADR 0614 §3).
func OfManifests(manifests map[string]catalogue.Manifest) Graph {
providers := func(provision string) []catalogue.Manifest {
var out []catalogue.Manifest
for _, name := range slices.Sorted(maps.Keys(manifests)) {
if slices.Contains(manifests[name].Offers(), provision) {
out = append(out, manifests[name])
}
}
return out
}
g := Graph{}
for name, m := range manifests {
g[name] = EdgesOf(m, providers)
}
g.LeaveOut()
return g
}
// Served is whether a running build serves a seat verb or module tool (ADR 0614 §2, §7), counted from the holders' own
// haves as a provider is (ADR 0603 §5): every have running healthy, by node and module, whose build's manifest serves it
// (servesOf answers the verbs of a module's build at a fingerprint, ServesOf of its manifest, and whether it was read).
// A build whose manifest cannot be read counts what fallback answers of its module (the graph's Serves, so a build read
// late never holds its callers for good, or nothing), and is named in unread, sorted, so its reader says so.
func Served(haves map[string]map[string]nodeengine.HaveByNodeModuleValue, servesOf func(module, fp string) ([]string, bool),
fallback func(module string) []string) (served func(invoke string) bool, unread []string) {
set := map[string]bool{}
for _, node := range slices.Sorted(maps.Keys(haves)) {
for _, module := range slices.Sorted(maps.Keys(haves[node])) {
h := haves[node][module]
if h.Phase != nodeengine.HaveByNodeModuleValuePhaseRunning || h.Health != nodeengine.HaveByNodeModuleValueHealthOk {
continue
}
serves, ok := servesOf(module, h.Fp)
if !ok {
unread = append(unread, module)
if fallback != nil {
serves = fallback(module)
}
}
for _, v := range serves {
set[v] = true
}
}
}
return func(v string) bool { return set[v] }, slices.Compact(slices.Sorted(slices.Values(unread)))
}
-333
View File
@@ -1,333 +0,0 @@
package graph
import (
"errors"
"maps"
"reflect"
"slices"
"strings"
"testing"
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// TestGraphEdges: the module graph's cycle, dependents and providers, each from the edges alone (ADR 0603 §2, ADR 0604 §1).
func TestGraphEdges(t *testing.T) {
t.Run("a node's value", nodeValues)
t.Run("a reader of the seat list waits for its holder", readersOfTheSeatList)
t.Run("a verb is served by a running healthy have of the node-engine contract", servedByHaves)
// ADR 0636 §2, issue 1966: a need of a bootstrapped seat is read by every engine whatever its statement names; a seat
// not bootstrapped and a word stay missing, and an engine stating none is read as the baseline.
t.Run("a bootstrapped seat is read by every engine", func(t *testing.T) {
stated := []string{"word:claims", "word:invokes"}
for _, c := range []struct {
name string
needs, stated []string
want []string
}{
{"mesh-catalog and node-backup", []string{"seat:mesh-catalog", "seat:node-backup", "word:invokes"}, stated, nil},
{"a seat not bootstrapped", []string{"seat:mesh-catalog", "seat:mesh-vault"}, stated, []string{"seat:mesh-vault"}},
{"a word", []string{"seat:node-engine", "word:zone"}, stated, []string{"word:zone"}},
{"the baseline", []string{"seat:mesh-catalog", "form:seat-reach"}, nil, []string{"form:seat-reach"}},
} {
if got := MissingReads(c.needs, c.stated); !slices.Equal(got, c.want) {
t.Errorf("%s: missing %v, want %v", c.name, got, c.want)
}
}
})
fp := "src2:" + strings.Repeat("b", 64)
node := func(repository, path string, edit func(*Node)) Node {
n := Node{FP: fp, Repository: repository, Path: path}
if edit != nil {
edit(&n)
}
return n
}
gotool := map[string]Toolchain{"go": {Module: "build-go", Version: "go1", Recipe: "1"}}
// A base chain, a package and a build module: app stands on base, imports lib's package, is built by build-go.
g := Graph{
"build-go": node("novox/mesh-catalog", "modules/build-go", func(n *Node) { n.Toolchains = gotool }),
"lib": node("novox/lib", meshcatalogclient.RootPath, nil),
"base": node("novox/mesh-catalog", "modules/base", nil),
"app": node("novox/mesh-catalog", "modules/app", func(n *Node) {
n.Bases, n.Packages, n.Toolchains = []string{"base"}, []string{"git.novox.be/novox/lib"}, gotool
}),
"top": node("novox/mesh-catalog", "modules/top", func(n *Node) { n.Bases = []string{"app"} }),
// A package published from inside a module's directory belongs to that module (ADR 0604 §1): users imports build-go's.
"users": node("novox/other", "modules/users", func(n *Node) {
n.Packages = []string{"git.novox.be/novox/mesh-catalog/modules/build-go/buildrun"}
}),
"db": node("novox/mesh-catalog", "modules/db", func(n *Node) { n.Provides = []string{"database"} }),
"web": node("novox/mesh-catalog", "modules/web", func(n *Node) {
n.Requires, n.Awaits = []string{"database", "db"}, []string{"database"}
}),
}
for module, want := range map[string][]string{
"base": {"app", "top"},
"lib": {"app", "top"},
"build-go": {"app", "top", "users"}, // build-go's own toolchain edge reaches itself, which is left out
"top": nil,
"db": nil, // a provision edge is no build edge
} {
if got := g.Dependents(module); !reflect.DeepEqual(got, want) {
t.Errorf("dependents of %s = %v, want %v", module, got, want)
}
}
if got := g.Providers("database"); !reflect.DeepEqual(got, []string{"db"}) {
t.Errorf("providers of database = %v", got)
}
if got := g.Providers("db"); !reflect.DeepEqual(got, []string{"db"}) { // a module provides its own name
t.Errorf("providers of db = %v", got)
}
if got := g.Before("web"); !reflect.DeepEqual(got, []string{"db"}) { // web awaits database, which db provides
t.Errorf("web waits for %v", got)
}
if got := g.Before("top"); !reflect.DeepEqual(got, []string{"app"}) {
t.Errorf("top waits for %v", got)
}
if got := g.Requirers("db"); !reflect.DeepEqual(got, []string{"web"}) {
t.Errorf("requirers of db = %v", got)
}
for pkg, want := range map[string]string{
"git.novox.be/novox/mesh-catalog/modules/build-go/buildrun": "build-go", // inside its directory
"git.novox.be/novox/mesh-catalog/modules/build-go": "build-go", // its directory
"git.novox.be/novox/mesh-catalog/modules/build-gone": "", // beside it, not inside
"git.novox.be/novox/lib/sub": "lib", // a root module publishes what is below it
} {
if got := g.Publisher(pkg); got != want {
t.Errorf("publisher of %s = %q, want %q", pkg, got, want)
}
}
if g.Publisher("git.novox.be/novox/lib") != "lib" || g.Publisher("git.novox.be/novox/mesh-sdk/go") != "" {
t.Error("a package's publisher is not the module at its repository and directory")
}
// From manifests alone (the check's graph): a requirement answered by a helper at mesh scope is awaited, an optional
// one is not, and two modules awaiting each other's provision are a cycle.
offer := func(name string) []catalogue.Offer {
return []catalogue.Offer{{Name: name, Scope: catalogue.ScopeMesh, AnsweredBy: catalogue.AnsweredByHelper}}
}
ms := map[string]catalogue.Manifest{
"db": {Module: "db", Provides: offer("database"), Requires: []string{"site", "logs"}, OptionalRequires: map[string]bool{"logs": true}},
"web": {Module: "web", Provides: offer("site"), Requires: []string{"database"}, Build: &catalogue.Build{On: []catalogue.BuildsOn{{Module: "base"}}}},
}
mg := OfManifests(ms)
if db := mg["db"]; !reflect.DeepEqual(db.Requires, []string{"site"}) || !reflect.DeepEqual(db.Awaits, []string{"site"}) ||
!reflect.DeepEqual(mg["web"].Bases, []string{"base"}) || !reflect.DeepEqual(db.Provides, []string{"database"}) {
t.Errorf("the graph of manifests = %+v", mg)
}
if got := mg.Cycle(); !reflect.DeepEqual(got, []string{"db", "web", "db"}) {
t.Errorf("the cycle of manifests = %v", got)
}
// The verb and bus-state edges (ADR 0614 §2, §3, §5, §6), from manifests alone: a caller waits for the module serving
// what it invokes, a bus-state entry requires bus-state of the bus module offering it, the builder's remove and the
// holder's builder_versions close a cycle and both are left out, read from either side, a package edge gives no order,
// and a module invoking its own tool is no wait.
builder := catalogue.Manifest{Module: "builder", Tools: []string{"builder_versions"}, Invokes: []string{"seat:artifact-store.remove"}}
store := catalogue.Manifest{Module: "store", Claims: []catalogue.Claim{{Name: "artifact-store", Scope: catalogue.ScopeMesh,
Serves: []string{"remove"}}}, Invokes: []string{"builder.builder_versions", "*"}}
verbs := map[string]catalogue.Manifest{
"builder": builder, "store": store,
"bus": {Module: "bus", Provides: []catalogue.Offer{{Name: BusState, Scope: catalogue.ScopeMesh}}},
"keeper": {Module: "keeper", BusState: []catalogue.BusStateEntry{{Name: "cache", Storage: "key-value"}}},
"caller": {Module: "caller", Invokes: []string{"seat:artifact-store.remove", "caller.own", "nobody.serves"}, Tools: []string{"own"}},
}
vg := OfManifests(verbs)
for name, want := range map[string][]string{"caller": {"store"}, "keeper": {"bus"}, "builder": nil, "store": nil} {
if got := vg.Before(name); !reflect.DeepEqual(got, want) {
t.Errorf("%s waits for %v, want %v", name, got, want)
}
}
if b, s := vg["builder"], vg["store"]; !reflect.DeepEqual(b.LeftOut, []string{"seat:artifact-store.remove"}) ||
!reflect.DeepEqual(s.LeftOut, []string{"builder.builder_versions"}) ||
!reflect.DeepEqual(s.Serves, []string{"seat:artifact-store.remove"}) || !reflect.DeepEqual(s.Invokes, []string{"builder.builder_versions"}) {
t.Errorf("the builder's cycle is not left out from either side: %+v %+v", b, s)
}
if k := vg["keeper"]; !reflect.DeepEqual(k.Requires, []string{BusState}) || !reflect.DeepEqual(k.Awaits, []string{BusState}) {
t.Errorf("a bus-state entry is no requirement of bus-state: %+v", k)
}
if c := vg["caller"]; !reflect.DeepEqual(c.LeftOut, []string{"caller.own"}) || vg.Cycle() != nil {
t.Errorf("a module's own tool is a wait, or a left-out verb edge a cycle: %+v %v", c, vg.Cycle())
}
if got := OfManifests(map[string]catalogue.Manifest{"keeper": verbs["keeper"]})["keeper"]; got.Awaits != nil {
t.Errorf("bus-state with no module offering it is awaited: %+v", got)
}
// The words of a want held on a verb or a reader capability name their edge, and no other words do.
for words, want := range map[string]string{
VerbWaitWords("seat:mesh-catalog.modules", "artifact-store-tools", "g14"): "verb seat:mesh-catalog.modules",
ReaderWaitWords("g14", []string{"tool-runner", "bus-state"}, "node-tools", "src2:abcdef"): "reader capability tool-runner, bus-state",
BusStateWaitWords("keeper", "g14"): "bus state",
"the verb is served": "",
"the node-engine of g14 has not started": "",
} {
if got := EdgeOfWords(words); got != want {
t.Errorf("the edge of %q = %q, want %q", words, got, want)
}
}
for name, c := range map[string]struct {
edit func(Graph)
want []string
}{
"none: a toolchain on itself and a requirement not awaited order nothing": {func(Graph) {}, nil},
"bases": {func(g Graph) {
b := g["base"]
b.Bases = []string{"top"}
g["base"] = b
}, []string{"app", "base", "top", "app"}},
"provisions a -> b -> a": {func(g Graph) {
d := g["db"]
d.Requires, d.Awaits = []string{"site"}, []string{"site"}
g["db"] = d
w := g["web"]
w.Provides = []string{"site"}
g["web"] = w
}, []string{"db", "web", "db"}},
"a package cycle orders nothing": {func(g Graph) {
l := g["lib"]
l.Packages = []string{"git.novox.be/novox/mesh-catalog/modules/app"}
g["lib"] = l
}, nil},
"a verb edge with a provision, before LeaveOut leaves it out": {func(g Graph) {
d := g["db"]
d.Invokes = []string{"web.page"}
g["db"] = d
w := g["web"]
w.Serves = []string{"web.page"}
g["web"] = w
}, []string{"db", "web", "db"}},
"a requirement not awaited is no edge": {func(g Graph) {
d := g["db"]
d.Requires = []string{"site"}
g["db"] = d
w := g["web"]
w.Provides = []string{"site"}
g["web"] = w
}, nil},
} {
h := Graph{}
for k, v := range g {
h[k] = v
}
c.edit(h)
if got := h.Cycle(); !reflect.DeepEqual(got, c.want) {
t.Errorf("%s: cycle = %v, want %v", name, got, c.want)
}
if h.LeaveOut(); h.Cycle() != nil && slices.ContainsFunc(slices.Collect(maps.Values(h)), func(n Node) bool { return len(n.Invokes) > 0 }) {
t.Errorf("%s: a cycle through a verb edge is left once its verb edges are left out: %v", name, h.Cycle())
}
}
}
// sampleNode is a graph node with every kind of edge, its lists unsorted.
func sampleNode() Node {
return Node{FP: "src2:" + strings.Repeat("a", 64), Repository: "novox/mesh-catalog", Path: "modules/gitea",
Bases: []string{"z-base", "a-base"}, Packages: []string{"git.novox.be/novox/mesh-sdk/go"},
Toolchains: map[string]Toolchain{"go": {Module: "build-go", Version: "go1.27.1", Recipe: "3"}},
Provides: []string{"forge"}, Requires: []string{"postgres-database", "dns"}, Awaits: []string{"postgres-database"},
Invokes: []string{"seat:mesh-catalog.modules", "builder.builder_versions"}, Serves: []string{"seat:forge.pulls"},
LeftOut: []string{"builder.builder_versions"}}
}
// nodeValues: a node round-trips with its lists sorted, an unknown version is refused, a node that does not hold is
// refused naming why, and the state is the indexer's graph (ADR 0603 §2).
func nodeValues(t *testing.T) {
if History != 5 || State != "graph" {
t.Error("the graph's state differs from the decided layout")
}
g := sampleNode()
data, err := Encode(g)
if err != nil || !strings.Contains(string(data), `"v":1`) {
t.Fatalf("encode: %s %v", data, err)
}
if got, err := Decode(data); err != nil || !Same(got, g) || !slices.IsSorted(got.Bases) {
t.Errorf("round trip: %+v %v", got, err)
}
if Same(g, Node{None: "x", Repository: "a/b"}) {
t.Error("different graph nodes are the same")
}
for _, in := range []string{`{"none":"x","repository":"a/b"}`, `{"v":2,"none":"x","repository":"a/b"}`} {
if _, err := Decode([]byte(in)); !errors.Is(err, ErrUnknownVersion) {
t.Errorf("decode of %s = %v, want ErrUnknownVersion", in, err)
}
}
for name, c := range map[string]struct {
change func(*Node)
word string
}{
"both": {func(g *Node) { g.None = "why" }, "both"},
"neither": {func(g *Node) { g.FP = "" }, "neither"},
"an old form": {func(g *Node) { g.FP = "src1:x" }, "src2:"},
"a dotted base": {func(g *Node) { g.Bases = []string{"a.b"} }, "a.b"},
"a foreign package": {func(g *Node) { g.Packages = []string{"example.com/x"} }, "example.com/x"},
"a toolchain of no module": {func(g *Node) { g.Toolchains = map[string]Toolchain{"go": {Version: "go1", Recipe: "1"}} }, "build module"},
"a toolchain of no recipe": {func(g *Node) { g.Toolchains = map[string]Toolchain{"go": {Module: "b", Version: "go1"}} }, "recipe"},
"awaiting what it does not require": {func(g *Node) { g.Awaits = []string{"other"} }, "other"},
"no repository": {func(g *Node) { g.Repository = "" }, "repositor"},
"leaving out what it does not invoke": {func(g *Node) { g.LeftOut = []string{"x.y"} }, "x.y"},
"an invoke of no verb": {func(g *Node) { g.Invokes = []string{"seat:nothing"} }, "seat:nothing"},
} {
g := sampleNode()
c.change(&g)
if _, err := Encode(g); err == nil || !strings.Contains(err.Error(), c.word) {
t.Errorf("a node with %s: %v, want it refused naming %q", name, err, c.word)
}
}
}
// readersOfTheSeatList (D-31): a module whose manifest invokes the seat mesh-catalog's seat-definitions waits, by the verb
// edge, for the module that claims the seat and serves the verb, so the delivery plan puts the holder first (ADR 0614 §2); a
// foundation part the holder itself invokes lies on a cycle with it and the edge is left out, so the part is carried by the
// bootstrapped three until the holder's new build runs (ADR 0636 §1).
func readersOfTheSeatList(t *testing.T) {
const list = "seat:mesh-catalog.seat-definitions"
fp := "src2:" + strings.Repeat("c", 64)
node := func(edit func(*Node)) Node {
n := Node{FP: fp, Repository: "novox/mesh-delivery", Path: "modules/x"}
edit(&n)
return n
}
g := Graph{
"indexer": node(func(n *Node) {
n.Serves = []string{list, "seat:mesh-catalog.modules"}
n.Invokes = []string{"seat:node-engine.composed"}
}),
"checker": node(func(n *Node) { n.Invokes = []string{list} }),
"node-agent": node(func(n *Node) { n.Invokes = []string{list}; n.Serves = []string{"seat:node-engine.composed"} }),
}
if got := g.Servers(list); !reflect.DeepEqual(got, []string{"indexer"}) {
t.Errorf("servers of the seat list = %v", got)
}
if got := g.Before("checker"); !reflect.DeepEqual(got, []string{"indexer"}) {
t.Errorf("the checker waits for %v, want the indexer", got)
}
g.LeaveOut()
if got := g.Before("checker"); !reflect.DeepEqual(got, []string{"indexer"}) {
t.Errorf("after the cycles are left out the checker waits for %v, want the indexer", got)
}
if got := g["node-agent"].LeftOut; !reflect.DeepEqual(got, []string{list}) {
t.Errorf("the node-agent leaves out %v, want the seat list (a cycle with the holder)", got)
}
if got := g.Before("node-agent"); len(got) != 0 {
t.Errorf("the node-agent waits for %v, want nothing: the bootstrap carries it", got)
}
}
// servedByHaves: Served counts the node-engine contract's haves, running and healthy only; an unread build is named.
func servedByHaves(t *testing.T) {
running := nodeengine.HaveByNodeModuleValue{Fp: "a", Phase: nodeengine.HaveByNodeModuleValuePhaseRunning, Health: nodeengine.HaveByNodeModuleValueHealthOk}
failed := nodeengine.HaveByNodeModuleValue{Fp: "b", Phase: nodeengine.HaveByNodeModuleValuePhaseRunning, Health: nodeengine.HaveByNodeModuleValueHealthFailed}
haves := map[string]map[string]nodeengine.HaveByNodeModuleValue{"n1": {"m1": running, "m2": failed, "m3": running}}
served, unread := Served(haves, func(module, fp string) ([]string, bool) {
if module == "m3" {
return nil, false
}
return []string{module + ".verb"}, true
}, nil)
if !served("m1.verb") || served("m2.verb") {
t.Fatalf("a running healthy have serves, a failed one does not: m1 %v, m2 %v", served("m1.verb"), served("m2.verb"))
}
if !reflect.DeepEqual(unread, []string{"m3"}) {
t.Fatalf("unread = %v, want [m3]", unread)
}
}
-37
View File
@@ -1,37 +0,0 @@
package graph
import (
"slices"
"strings"
"sync"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatlist"
)
// bootstrappedReads are the reader capabilities `seat:<seat>` of the bootstrapped seats: the embedded files' own, so
// computed once.
var bootstrappedReads = sync.OnceValue(func() []string {
var out []string
for _, d := range seatlist.Bootstrapped() {
out = append(out, catalogue.ReadSeat+d.Seat)
}
return out
})
// MissingReads is catalogue.MissingManifestReads with every need of a bootstrapped seat counted as read (novox/hq ADR 0614
// §4, ADR 0636 §2): every reader of the seat list holds the bootstrapped seats from its start, before it has read the list,
// so a manifest naming one is read by every node-engine whatever its statement names. Without it an engine whose statement
// was made before its list was in use states no seat, and the node-engine's own build naming mesh-catalog is held on the
// very engine that would state it (issue 1966). The assigner's capability hold and the indexer's hold both judge with it,
// so the rule is one.
func MissingReads(needs, stated []string) []string {
boot := bootstrappedReads()
missing := slices.DeleteFunc(catalogue.MissingManifestReads(needs, stated), func(n string) bool {
return strings.HasPrefix(n, catalogue.ReadSeat) && slices.Contains(boot, n)
})
if len(missing) == 0 {
return nil
}
return missing
}
-61
View File
@@ -1,61 +0,0 @@
package graph
import (
"fmt"
"strings"
)
// The words of a want held on an edge of ADR 0614 (novox/hq ADR 0614 §2, §4, §5): no reader knows a rule number of its own for
// either yet, so the assigner holds them under the provisions' and the composition's rules, and these words are the one
// place they are written and read. The assigner writes them (VerbWaitWords, ReaderWaitWords, BusStateWaitWords); the delivery view names
// the edge a want waits on from them (EdgeOfWords).
const (
verbOpen = "the verb "
verbClose = " invokes is served by no running build"
readerOpen = "the node-engine of "
readerMid = " does not read "
readerTail = ", which the manifest of "
busOpen = "bus state: "
)
// BusStateWaitWords are the words of a want of module on node held until a build of a module offering bus-state runs
// healthy on a node present (ADR 0614 §5, through ADR 0603 §5's count of the provider's own have).
func BusStateWaitWords(module, node string) string {
return fmt.Sprintf("%s%s asks bus state, and no build of a module offering %s runs healthy on a node present: its want on %s waits for one (ADR 0614 §5)",
busOpen, module, BusState, node)
}
// VerbWaitWords are the words of a want of module on node held until a build serving verb runs healthy (ADR 0614 §2).
func VerbWaitWords(verb, module, node string) string {
return fmt.Sprintf("%s%s %s%s: its want on %s waits until a build serving it runs healthy (ADR 0614 §2)", verbOpen, verb,
module, verbClose, node)
}
// ReaderWaitWords are the words of a want of module at fp held on node until its node-engine states the reader
// capabilities missing (ADR 0614 §4).
func ReaderWaitWords(node string, missing []string, module, fp string) string {
return fmt.Sprintf("%s%s%s%s%s%s at %s needs: the want moves once that engine states it", readerOpen, node, readerMid,
strings.Join(missing, ", "), readerTail, module, fp)
}
// EdgeOfWords is the edge a held want's words name: `verb <verb>` for a verb wait, `reader capability <capabilities>` for
// a reader capability's hold, `bus state` for a bus-state wait, or "" for words of none of them.
func EdgeOfWords(words string) string {
if strings.HasPrefix(words, busOpen) {
return "bus state"
}
if rest, ok := strings.CutPrefix(words, verbOpen); ok {
if verb, _, ok := strings.Cut(rest, " "); ok && strings.Contains(rest, verbClose) {
return "verb " + verb
}
}
if rest, ok := strings.CutPrefix(words, readerOpen); ok {
if _, rest, ok := strings.Cut(rest, readerMid); ok {
if missing, _, ok := strings.Cut(rest, readerTail); ok {
return "reader capability " + missing
}
}
}
return ""
}
-65
View File
@@ -1,65 +0,0 @@
// Package grouppackages is the one place that names the versions a build at a delivery group's heads uses (novox/hq
// ADR 0573 §2, §4; issue 1921). A build writes into its workspace the version of every mesh package it is asked, whatever
// its go.mod names; a requirement at the zero version that no ask names a commit for cannot be fetched. So every part
// that asks a build for a check, a try or a candidate (the checker's check, judge and compose asks, the indexer's
// candidate modules) takes the versions from Heads, and a member of the group that publishes no package yet is named too.
package grouppackages
import (
"strings"
"git.novox.be/novox/mesh-sdk/go/sdkversion"
"git.novox.be/novox/mesh-delivery/sdk/buildstep"
"git.novox.be/novox/mesh-delivery/sdk/trunk"
)
// rootOf is the module a member of repo stands for when no package of it is known: its root module path, or for the
// repository of mesh-sdk its Go module (sdkversion.Module, which is not at the root).
func rootOf(repo string) (string, bool) {
if sdkRepo, _, ok := trunk.PackageRepository(sdkversion.Module); ok && trunk.SameRepository(repo, sdkRepo) {
return sdkversion.Module, true
}
name, found := strings.CutPrefix(repo, "novox/")
if !found || name == "" {
return "", false
}
return trunk.ForgeModulePrefix + name, true
}
// Heads is the version of each mesh package a build of own builds against: latest (the latest published version of each
// package the mesh's modules use, nil for none) with every package of a group member at that member's head (heads, by
// repository <owner>/<name>, a full commit each), and for a member of which latest holds no package, the member's root
// module path (mesh-sdk's Go module for mesh-sdk) at its head: the build module takes the head of a
// repository from any package of it. A package of own comes with the tree the build fetched, and is left out, as is a
// package no version is known of. Nil for none. latest is not changed.
func Heads(latest buildstep.PackageVersions, heads map[string]string, own string) buildstep.PackageVersions {
versions := buildstep.PackageVersions{}
held := map[string]bool{}
for pkg, version := range latest {
repo, _, ok := trunk.PackageRepository(pkg)
if !ok || trunk.SameRepository(repo, own) {
continue
}
if head := heads[repo]; len(head) == 40 {
version = head
}
if version == "" {
continue
}
versions[pkg] = version
held[repo] = true
}
for repo, head := range heads {
if trunk.SameRepository(repo, own) || len(head) != 40 || held[repo] {
continue
}
if root, ok := rootOf(repo); ok {
versions[root] = head
}
}
if len(versions) == 0 {
return nil
}
return versions
}
-34
View File
@@ -1,34 +0,0 @@
// Package kept holds what the layouts of the Delivery domain's kept values share: the reading of one at its version and the form
// of a digest. It names no seat and no module (ADR 0634 §2). The version (keys.Version, keys.CheckVersion), the rule a name
// must keep to be a key part (keys.CheckName), keys.IsHex64 and the escaping of a name (keys.EscapeName) are mesh-sdk's,
// since more than one domain uses them.
package kept
import (
"encoding/json"
"fmt"
"regexp"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// Decode reads data into into after CheckVersion.
func Decode(data []byte, into any) error {
if err := keys.CheckVersion(data); err != nil {
return err
}
if err := json.Unmarshal(data, into); err != nil {
return fmt.Errorf("kept: value does not fit its shape: %w", err)
}
return nil
}
var digestForm = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
// CheckDigest refuses a digest that is not sha256:<64 lowercase hex digits>, saying what it is of.
func CheckDigest(digest, of string) error {
if !digestForm.MatchString(digest) {
return fmt.Errorf("kept: %s %q is not sha256:<64 lowercase hex digits>", of, digest)
}
return nil
}
-24
View File
@@ -1,24 +0,0 @@
package kept
import (
"errors"
"git.novox.be/novox/mesh-sdk/go/keys"
"strings"
"testing"
)
func TestAKeptValueIsReadOnlyAtItsVersionAndAKeyPartOnlyOfKeyCharacters(t *testing.T) {
var v struct{ V int }
for data, ok := range map[string]bool{`{"v":1}`: true, `{"v":2}`: false, `{}`: false} {
err := Decode([]byte(data), &v)
if (err == nil) != ok || (!ok && !errors.Is(err, keys.ErrUnknownVersion)) {
t.Errorf("Decode(%s) = %v", data, err)
}
}
if Decode([]byte(`nope`), &v) == nil {
t.Error("a value that is no JSON is read")
}
if CheckDigest("sha256:"+strings.Repeat("0", 64), "x") != nil || CheckDigest("sha256:0", "x") == nil {
t.Error("CheckDigest reads a wrong form")
}
}
-37
View File
@@ -1,37 +0,0 @@
package sdk
import (
"encoding/json"
"os"
"testing"
)
// The module's one package artifact is the module's whole directory, which it says by leaving `paths` out: the manifest
// validator refuses the word "." as a path (a package artifact naming one directory).
func TestThePackageArtifactNamesNoPathForTheWholeDirectory(t *testing.T) {
raw, err := os.ReadFile("module.json")
if err != nil {
t.Fatal(err)
}
var m struct {
Build struct {
Artifacts []struct {
Name string `json:"name"`
Paths []string `json:"paths"`
} `json:"artifacts"`
} `json:"build"`
}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
if len(m.Build.Artifacts) != 1 {
t.Fatalf("artifacts are %+v: one", m.Build.Artifacts)
}
for _, a := range m.Build.Artifacts {
for _, p := range a.Paths {
if p == "." || p == "" {
t.Errorf("artifact %s names %q as a path: leave `paths` out for the module's whole directory", a.Name, p)
}
}
}
}
-15
View File
@@ -1,15 +0,0 @@
{
"module": "mesh-delivery-sdk",
"version": "0.1",
"build": {
"artifacts": [
{
"name": "go-sdk",
"kind": "package",
"language": "go",
"series": "0.1"
}
]
},
"resources": []
}
-69
View File
@@ -1,69 +0,0 @@
// Package packagename reads a package artifact's name in its own ecosystem (design 32, a package named by its name in its
// own language): a Go package by the module line of its go.mod, a TypeScript package by the name in its package.json, read
// at a commit of the repository that builds it. The indexer reads it so at each trunk merge (its packages state's series
// keys), and the checker so at a delivery group member's head for a package new in the group, so the judge is handed one
// name for each package whoever reads it (mesh-sdk composer.Request.Packages).
package packagename
import (
"context"
"encoding/json"
"fmt"
"path"
"strings"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// ReadFile reads one file of a repository at a commit; a file the commit does not hold is nil with no error.
type ReadFile func(ctx context.Context, repository, commit, file string) ([]byte, error)
// Of is a package artifact's name in its ecosystem, read at commit from the first of its paths (or the module's directory
// dir, meshcatalogclient.RootPath or empty for the repository's root) that holds its go.mod (Go) or package.json (TypeScript). A
// file read that fails, a go.mod that names no module and a package.json that names no name are errors, said.
func Of(ctx context.Context, read ReadFile, repository, commit, dir string, a catalogue.Artifact) (string, error) {
file := "package.json"
if a.Language == "go" {
file = "go.mod"
}
base := dir
if base == meshcatalogclient.RootPath {
base = ""
}
roots := a.Paths
if len(roots) == 0 {
roots = []string{"."}
}
for _, r := range roots {
p := path.Join(base, r, file)
if strings.HasSuffix(r, file) {
p = path.Join(base, r)
}
raw, err := read(ctx, repository, commit, p)
if err != nil {
return "", fmt.Errorf("%s: %w", p, err)
}
if raw == nil {
continue
}
if a.Language == "go" {
for _, line := range strings.Split(string(raw), "\n") {
if rest, ok := strings.CutPrefix(strings.TrimSpace(line), "module "); ok {
if name := strings.Trim(strings.TrimSpace(rest), `"`); name != "" {
return name, nil
}
}
}
return "", fmt.Errorf("%s names no module", p)
}
var pj struct {
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &pj); err != nil || pj.Name == "" {
return "", fmt.Errorf("%s names no name (%v)", p, err)
}
return pj.Name, nil
}
return "", fmt.Errorf("no %s under %v", file, roots)
}
-154
View File
@@ -1,154 +0,0 @@
package parts
import (
"encoding/json"
"errors"
"fmt"
"sync/atomic"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/busstate"
)
// BusObjects is a Receiver's Objects over the holder's own object store, asked for in `requires` by local (the
// template objects, novox/hq ADR 0595 §2), through the runtime: every holder binds the same adapter, none its own.
func BusObjects(local string) Objects { return busObjects{busstate.ObjectsOf(local)} }
type busObjects struct{ o busstate.Objects }
func (b busObjects) Put(name string, data []byte) error {
_, err := b.o.Put(name, data, "")
return err
}
func (b busObjects) Get(name string) ([]byte, error) {
d, err := b.o.Get(name)
return d.Data, err
}
func (b busObjects) Delete(name string) error { return b.o.Delete(name) }
func (b busObjects) Used() (uint64, error) {
f, err := b.o.Fill()
return f.Bytes, err
}
// BusTransfers is a Receiver's Transfers over the holder's own key-value state of that name (the template state),
// through the runtime, each transfer under its id.
func BusTransfers[M any](state string) Transfers[M] { return busTransfers[M]{state} }
type busTransfers[M any] struct{ state string }
func (b busTransfers[M]) Get(id string) (Transfer[M], bool, error) {
var t Transfer[M]
e, err := stdio.State(b.state).Get(id)
if err != nil || e == nil {
return t, false, err
}
return t, true, json.Unmarshal(e.Value, &t)
}
func (b busTransfers[M]) Put(t Transfer[M]) error {
if t.ID == "" {
return errors.New("a transfer without an id cannot be kept")
}
_, err := stdio.State(b.state).Put(t.ID, t)
return err
}
func (b busTransfers[M]) Delete(id string) error { return stdio.State(b.state).Delete(id) }
func (b busTransfers[M]) List() ([]Transfer[M], error) {
keys, err := stdio.State(b.state).Keys()
if err != nil {
return nil, err
}
var out []Transfer[M]
for _, k := range keys {
if t, ok, err := b.Get(k); err == nil && ok {
out = append(out, t)
}
}
return out, nil
}
// BusCap is a Receiver's Bound over the holder's own object store of that name: the cap its binding carries (the bus's
// own bound, the store's max bytes), read through the runtime once it answers one, since a binding's cap does not
// change while the bundle runs. Make it once per bundle, not per receiver.
func BusCap(local string) func() (uint64, error) {
var known atomic.Uint64
return func() (uint64, error) {
if c := known.Load(); c > 0 {
return c, nil
}
f, err := busstate.ObjectsOf(local).Fill()
if err != nil {
return 0, fmt.Errorf("%s's cap cannot be read from its binding: %w", local, err)
}
if f.MaxBytes == 0 {
return 0, fmt.Errorf("%s's binding carries no cap", local)
}
known.Store(f.MaxBytes)
return f.MaxBytes, nil
}
}
// BusArm is a Receiver's Arm over the holder's own key-value state of that name, declared key-ttl: one key per open
// transfer with its own time to live; a key already there is the same bound, kept.
func BusArm(state string) func(id string, ttl time.Duration) error {
return func(id string, ttl time.Duration) error {
if _, err := stdio.State(state).CreateTTL(id, map[string]any{"transfer": id}, ttl); err != nil && !errors.Is(err, stdio.ErrChanged) {
return err
}
return nil
}
}
// FollowIdle follows the holder's idle state (the one BusArm writes) once the bundle serves, and hands the end of each
// key (the bus's marker, OpExpire) to expired, a Receiver's Expired: the event drops an idle transfer, no timer runs.
// Once the watch is taken it hands every transfer open (open, such as IDs of the holder's Transfers) to expired too, so
// a key that ended while the bundle was down, whose marker no watch saw, still drops its transfer, and a key lost is
// armed again. said is told each outcome (dropped, or the error that stopped it) for the holder's log. It returns
// once the start's look is done; run it in its own goroutine.
func FollowIdle(state string, open func() ([]string, error), expired func(id string) (bool, error), said func(id string, dropped bool, err error)) {
<-stdio.Served()
stdio.State(state).Follow("", func(ch stdio.StateChange) error {
if ch.Op != stdio.OpExpire {
return nil
}
dropped, err := expired(ch.Key)
if said != nil && (dropped || err != nil) {
said(ch.Key, dropped, err)
}
return err
})
expireOpen(state, open, expired, said)
}
// expireOpen is FollowIdle's look at its start: every open transfer handed to expired, as its key's end would.
func expireOpen(state string, open func() ([]string, error), expired func(id string) (bool, error), said func(id string, dropped bool, err error)) {
say := func(id string, dropped bool, err error) {
if said != nil && (dropped || err != nil) {
said(id, dropped, err)
}
}
ids, err := open()
if err != nil {
say("", false, fmt.Errorf("the open transfers cannot be read at the start of %s's watch, so one whose idle key ended while the bundle was down waits for a look by hand: %w", state, err))
return
}
for _, id := range ids {
dropped, err := expired(id)
say(id, dropped, err)
}
}
// IDs answers the ids of the transfers open in t: FollowIdle's open.
func IDs[M any](t Transfers[M]) func() ([]string, error) {
return func() ([]string, error) {
all, err := t.List()
if err != nil {
return nil, err
}
out := make([]string, 0, len(all))
for _, x := range all {
out = append(out, x.ID)
}
return out, nil
}
}
-145
View File
@@ -1,145 +0,0 @@
// Package parts is the runtime's sender of a file in parts (novox/hq ADR 0611, ADR 0627 §2, design 51 *Publishing*):
// the caller opens a transfer naming every part's digest and size, the receiver answers the parts it lacks, and only
// those travel, in chunks a bus message carries, in sequence with the last marked. A cut transfer goes on from what
// the receiver answers when the same transfer is opened again. It names no seat, no verb and no seat's type: the
// caller's Open and Chunk are its own calls (a registry seat's client binds them to that seat's verbs and types), so
// this package holds no transport and no contract.
package parts
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
)
// MaxChunk is the most bytes of a part one chunk carries: base64 makes it about 1 000 KiB, under 1 MiB, the server's
// largest message, with the message's own fields (design 51: each part travels in chunks of at most 1 MiB).
const MaxChunk = 760 << 10
// Part is one part of a transfer: its digest (sha256:<hex>), its size and how to read its bytes.
type Part struct {
Digest string
Size int64
Open func() (io.ReadCloser, error)
}
// Opened is the receiver's answer to opening a transfer: whether it holds the whole already, and the digests of the
// parts it lacks.
type Opened struct {
Held bool
Lacks []string
}
// Open opens (or opens again) the transfer on the receiver, naming every part: the caller's own call.
type Open func(ctx context.Context, parts []Part) (Opened, error)
// Chunk sends one chunk of a part: the part's digest, its sequence from 0, whether it is the part's last, its bytes.
type Chunk func(ctx context.Context, part string, sequence int, last bool, data []byte) error
// Sent is what a Send did: whether the receiver held the whole, the parts it lacked and were sent, the chunks they
// took.
type Sent struct {
Held bool
Parts []string
Chunks int
}
// Send opens the transfer and sends the parts the receiver answers it lacks, each in chunks of at most MaxChunk, in
// sequence, the last marked. A part whose bytes do not hash to its digest is refused before anything of it is sent; a
// part the receiver does not name is never read; a part the receiver names that the transfer does not is refused.
func Send(ctx context.Context, open Open, chunk Chunk, parts []Part) (Sent, error) {
byDigest := map[string]Part{}
for _, p := range parts {
byDigest[p.Digest] = p
}
opened, err := open(ctx, parts)
if err != nil {
return Sent{}, err
}
sent := Sent{Held: opened.Held}
for _, d := range opened.Lacks {
p, ok := byDigest[d]
if !ok {
return sent, fmt.Errorf("the receiver lacks the part %s, which the transfer does not name", d)
}
if err := ctx.Err(); err != nil {
return sent, err
}
if err := check(p); err != nil {
return sent, err
}
n, err := sendPart(ctx, chunk, p)
sent.Chunks += n
if err != nil {
return sent, err
}
sent.Parts = append(sent.Parts, d)
}
return sent, nil
}
// check reads the part once and refuses it when its bytes are not its digest or its size.
func check(p Part) error {
r, err := p.Open()
if err != nil {
return fmt.Errorf("the part %s cannot be read: %w", p.Digest, err)
}
defer r.Close()
h := sha256.New()
n, err := io.Copy(h, r)
if err != nil {
return fmt.Errorf("the part %s cannot be read: %w", p.Digest, err)
}
if got := "sha256:" + hex.EncodeToString(h.Sum(nil)); got != p.Digest || n != p.Size {
return fmt.Errorf("the part %s holds %d bytes of digest %s, not its own %d: nothing of it is sent", p.Digest, n, got, p.Size)
}
return nil
}
func sendPart(ctx context.Context, chunk Chunk, p Part) (int, error) {
r, err := p.Open()
if err != nil {
return 0, fmt.Errorf("the part %s cannot be read: %w", p.Digest, err)
}
defer r.Close()
buf := make([]byte, MaxChunk)
// A chunk is sent once the next read says whether it is the last, so the last is always marked: an empty part is
// one empty chunk, marked last.
var prev []byte
sent := 0
send := func(data []byte, last bool) error {
if err := chunk(ctx, p.Digest, sent, last, data); err != nil {
return fmt.Errorf("chunk %d of the part %s: %w", sent, p.Digest, err)
}
sent++
return nil
}
for {
if err := ctx.Err(); err != nil {
return sent, err
}
n, err := io.ReadFull(r, buf)
end := errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)
if err != nil && !end {
return sent, fmt.Errorf("the part %s cannot be read: %w", p.Digest, err)
}
if end && n == 0 {
if prev == nil {
prev = []byte{}
}
return sent, send(prev, true)
}
if prev != nil {
if err := send(prev, false); err != nil {
return sent, err
}
}
prev = append([]byte(nil), buf[:n]...)
if end {
return sent, send(prev, true)
}
}
}
-122
View File
@@ -1,122 +0,0 @@
package parts
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"strings"
"testing"
)
// A file travels in parts (ADR 0611, ADR 0627 §2, design 51 *Publishing*; SDK-1), both sides in one test, since
// mesh-sdk is over its test budget: the sender's and the holder's (aHolderTakesAFileInParts, receive_test.go).
func TestAFileTravelsInTheParts(t *testing.T) {
t.Run("the sender sends only what the holder lacks", theSenderSendsOnlyWhatTheHolderLacks)
t.Run("a holder takes a file in parts", aHolderTakesAFileInParts)
}
// Only the parts the holder says it lacks are read and sent, each in chunks of at most MaxChunk in sequence with the
// last marked, so a cut transfer opened again goes on from what the holder holds; a part whose bytes are not its
// digest is refused before any of it travels.
func theSenderSendsOnlyWhatTheHolderLacks(t *testing.T) {
big := bytes.Repeat([]byte("x"), MaxChunk+10)
small, empty := []byte("config"), []byte{}
part := func(b []byte, opened *int) Part {
sum := sha256.Sum256(b)
return Part{Digest: "sha256:" + hex.EncodeToString(sum[:]), Size: int64(len(b)),
Open: func() (io.ReadCloser, error) { *opened++; return io.NopCloser(bytes.NewReader(b)), nil }}
}
type chunk struct {
part string
seq int64
last bool
data []byte
}
type receiver struct {
open Open
chunk Chunk
}
holder := func(lacks []string, got *[]chunk, asked *[]string) receiver {
return receiver{
open: func(_ context.Context, ps []Part) (Opened, error) {
*asked = append(*asked, "open")
return Opened{Lacks: lacks, Held: len(lacks) == 0}, nil
},
chunk: func(_ context.Context, part string, seq int, last bool, data []byte) error {
if len(data) > MaxChunk {
t.Errorf("a chunk is %d bytes, over MaxChunk", len(data))
}
*got = append(*got, chunk{part, int64(seq), last, append([]byte(nil), data...)})
return nil
},
}
}
var opens [3]int
parts := []Part{part(big, &opens[0]), part(small, &opens[1]), part(empty, &opens[2])}
for _, c := range []struct {
name string
lacks []int
chunks int
err string
}{
{"a fresh transfer sends every part, the big one in two chunks and the empty one as one", []int{0, 1, 2}, 4, ""},
{"a cut transfer opened again sends only what the holder lacks", []int{2}, 1, ""},
{"a digest the holder holds sends nothing", nil, 0, ""},
} {
opens = [3]int{}
var lacks []string
for _, i := range c.lacks {
lacks = append(lacks, parts[i].Digest)
}
var got []chunk
var asked []string
r := holder(lacks, &got, &asked)
sent, err := Send(context.Background(), r.open, r.chunk, parts)
if err != nil || sent.Chunks != c.chunks || len(got) != c.chunks || len(sent.Parts) != len(c.lacks) {
t.Errorf("%s: sent %+v, %d chunks heard, %v", c.name, sent, len(got), err)
continue
}
for i := range parts {
want := 0
for _, l := range c.lacks {
if l == i {
want = 2 // read once to check its digest, once to send it
}
}
if opens[i] != want {
t.Errorf("%s: part %d read %d times, want %d", c.name, i, opens[i], want)
}
}
whole := map[string][]byte{}
for i, ch := range got {
whole[ch.part] = append(whole[ch.part], ch.data...)
lastOfPart := i == len(got)-1 || got[i+1].part != ch.part
if ch.last != lastOfPart || (i > 0 && got[i-1].part == ch.part && got[i-1].seq+1 != ch.seq) {
t.Errorf("%s: chunk %d of %s is %d, last %v", c.name, i, ch.part[:12], ch.seq, ch.last)
}
}
for _, l := range c.lacks {
if p := parts[l]; int64(len(whole[p.Digest])) != p.Size {
t.Errorf("%s: part %d arrived as %d bytes of %d", c.name, l, len(whole[p.Digest]), p.Size)
}
}
}
// A part whose bytes are not its digest travels not at all; a part the holder names that the transfer does not is
// refused, naming it.
liar := part(small, &opens[1])
liar.Digest = parts[0].Digest
var got []chunk
var asked []string
r := holder([]string{liar.Digest}, &got, &asked)
if _, err := Send(context.Background(), r.open, r.chunk, []Part{liar}); err == nil || len(got) != 0 || !strings.Contains(err.Error(), "nothing of it is sent") {
t.Errorf("a part not its digest: %v, %d chunks sent", err, len(got))
}
r = holder([]string{"sha256:" + strings.Repeat("f", 64)}, &got, &asked)
if _, err := Send(context.Background(), r.open, r.chunk, parts); err == nil || !strings.Contains(err.Error(), "does not name") {
t.Errorf("a part the transfer does not name: %v", err)
}
}
-446
View File
@@ -1,446 +0,0 @@
package parts
// The receiving side of a file in parts (novox/hq ADR 0611, ADR 0627 §2, design 51 *Publishing*): a holder opens a
// transfer naming every part, takes the chunks of the parts it lacks into its own objects, checks each whole part's
// hash, drops a transfer left idle when its idle bound ends and says when its objects fill. Like the sender it names no seat, no verb and no
// seat's type: the caller's own shape of an opening rides along as M, its objects and its state are its own, and the
// checks before storing, the storing and the saying of a refusal are the caller's functions. Each holder binds it to
// the seat it holds.
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"slices"
"sort"
"strings"
"time"
)
// The bounds design 51 gives the receiving side; a Receiver's own fields override them.
const (
// MaxReceived is the most bytes one chunk may carry when it arrives.
MaxReceived = 1 << 20
// IdleAfter is how long a transfer with no chunk stays open.
IdleAfter = 24 * time.Hour
// FullPercent is the fill of the objects past which the receiver says they fill.
FullPercent = 80
)
// Want is one part an opening names: its digest (sha256:<hex>) and its size.
type Want struct {
Digest string `json:"digest"`
Size int64 `json:"size"`
}
// Transfer is one open transfer, kept in the caller's state; its chunks are objects of the caller's object store. Shape
// is the caller's own body of the opening, kept as it came.
type Transfer[M any] struct {
ID string `json:"id"`
Opener string `json:"opener"`
Parts []Want `json:"parts"`
// Held are the parts whose every chunk arrived and hashed right, or that the holder held at the open; Chunks the
// chunks taken per part.
Held []string `json:"held,omitempty"`
Chunks map[string]int `json:"chunks,omitempty"`
Opened time.Time `json:"opened"`
Last time.Time `json:"last"`
Shape M `json:"shape"`
}
// Lacks is the digests of the parts the transfer does not hold yet, sorted.
func (t Transfer[M]) Lacks() []string {
var out []string
for _, p := range t.Parts {
if !slices.Contains(t.Held, p.Digest) && !slices.Contains(out, p.Digest) {
out = append(out, p.Digest)
}
}
sort.Strings(out)
return out
}
// Taken says whether any chunk of the part was taken in this transfer (a part held at the open was not).
func (t Transfer[M]) Taken(digest string) bool {
_, ok := t.Chunks[digest]
return ok
}
// Objects is the holder's own object store the chunks go into.
type Objects interface {
Put(name string, data []byte) error
Get(name string) ([]byte, error)
Delete(name string) error
// Used is the bytes the store holds.
Used() (uint64, error)
}
// Transfers is the holder's own state of open transfers, keyed by Transfer.ID.
type Transfers[M any] interface {
Get(id string) (Transfer[M], bool, error)
Put(t Transfer[M]) error
Delete(id string) error
List() ([]Transfer[M], error)
}
// Received is the receiver's answer to an open or a chunk: the parts still lacked, and whether the transfer ended
// (stored or refused).
type Received struct {
ID string
Lacks []string
Ended bool
}
// AtCap opens the reason of a refusal for want of room: the objects would pass their cap. A holder tells it from
// the other refusals with RefusedAtCap, so the finding it raises for it can clear once it takes a file again.
const AtCap = "the objects are at their cap"
// RefusedAtCap says whether a refusal's reason is one for want of room (AtCap).
func RefusedAtCap(reason string) bool { return strings.HasPrefix(reason, AtCap) }
// Receiver takes transfers in parts into a holder's own objects.
type Receiver[M any] struct {
Objects Objects
Transfers Transfers[M]
// Prefix starts the name of every chunk object, so two receivers can share one object store.
Prefix string
// Cap is the bytes the objects may hold; an opening that would pass it is refused. Required: it is said where
// Bound answers no cap.
Cap uint64
// Bound reads the cap the objects' binding carries (BusCap): the bus's own bound, which then counts over Cap.
// Optional; an error or a zero falls back to Cap.
Bound func() (uint64, error)
// MaxChunk, Idle and Full override MaxReceived, IdleAfter and FullPercent when set.
MaxChunk int
Idle time.Duration
Full uint64
// Holds says the holder already holds a part, which then counts as held at the open and is not sent. Optional.
Holds func(t Transfer[M], digest string) bool
// Check is the caller's check of a whole transfer before anything is stored; its error is the refusal's reason.
// Optional.
Check func(t Transfer[M]) error
// Store stores a whole, checked transfer: the parts taken in it by digest (not those held at the open). It says
// the outcome itself; its error is answered as it is.
Store func(t Transfer[M], parts map[string][]byte) error
// Refuse says a refusal by the receiver (the cap, the caller's check, a part it cannot read back). Its own error is
// joined to the refusal's.
Refuse func(t Transfer[M], reason string) error
// Filled is told the objects' fill after every change: used, the cap and whether it is past Full percent. Optional.
Filled func(used, cap uint64, full bool)
// Arm writes a transfer's idle key with its own time to live, once (BusArm over a state declared key-ttl); one
// already there is no fault. The key's end is the event that calls Expired, so an open transfer left with no
// chunk is dropped without a timer. Optional: nil arms nothing, and only DropIdle drops.
Arm func(id string, ttl time.Duration) error
Now func() time.Time
}
func (r *Receiver[M]) now() time.Time {
if r.Now != nil {
return r.Now().UTC()
}
return time.Now().UTC()
}
func (r *Receiver[M]) maxChunk() int {
if r.MaxChunk > 0 {
return r.MaxChunk
}
return MaxReceived
}
func (r *Receiver[M]) idle() time.Duration {
if r.Idle > 0 {
return r.Idle
}
return IdleAfter
}
// CapNow is the cap the receiver counts against: the binding's (Bound) when it answers one, else Cap.
func (r *Receiver[M]) CapNow() uint64 {
if r.Bound != nil {
if c, err := r.Bound(); err == nil && c > 0 {
return c
}
}
return r.Cap
}
func (r *Receiver[M]) fullPct() uint64 {
if r.Full > 0 {
return r.Full
}
return FullPercent
}
// Open opens a transfer for opener, or opens it again: a transfer already open answers what it lacks, so a cut transfer
// goes on from there, and only its opener may open it again. A new transfer that would pass the cap is refused; parts
// the holder holds count as held; when nothing is lacked the transfer ends at once.
func (r *Receiver[M]) Open(id, opener string, parts []Want, shape M) (Received, error) {
switch {
case strings.TrimSpace(id) == "" || strings.ContainsAny(id, "/. *>"):
return Received{}, fmt.Errorf("transfer %q is no transfer id", id)
case len(parts) == 0:
return Received{}, errors.New("no parts")
}
for _, p := range parts {
if !strings.HasPrefix(p.Digest, "sha256:") || len(p.Digest) != len("sha256:")+64 {
return Received{}, fmt.Errorf("part digest %q is no sha256 digest", p.Digest)
}
}
if t, found, err := r.Transfers.Get(id); err != nil {
return Received{}, err
} else if found {
if t.Opener != opener {
return Received{}, fmt.Errorf("refused for %s: transfer %s was opened by another caller", opener, id)
}
return Received{ID: id, Lacks: t.Lacks()}, r.arm(id)
}
t := Transfer[M]{ID: id, Opener: opener, Parts: parts, Chunks: map[string]int{}, Opened: r.now(), Last: r.now(), Shape: shape}
used, err := r.Objects.Used()
if err != nil {
return Received{}, fmt.Errorf("the objects' fill cannot be read: %w", err)
}
var size uint64
for _, p := range parts {
size += uint64(max(p.Size, 0))
}
if cap := r.CapNow(); used+size > cap {
return Received{ID: id, Ended: true}, r.refuse(t, fmt.Sprintf(AtCap+" of %d bytes (%d held, %d asked)", cap, used, size))
}
if r.Holds != nil {
for _, p := range parts {
if r.Holds(t, p.Digest) {
t.Held = append(t.Held, p.Digest)
}
}
}
if err := r.Transfers.Put(t); err != nil {
return Received{}, fmt.Errorf("transfer %s cannot be kept: %w", id, err)
}
r.fill()
if len(t.Lacks()) == 0 {
return Received{ID: id, Ended: true}, r.finish(t)
}
return Received{ID: id, Lacks: t.Lacks()}, r.arm(id)
}
// arm bounds an open transfer by its idle key. A key that cannot be written fails the open loudly (the transfer is
// kept, so the opener's next open of it answers what is held and arms it again).
func (r *Receiver[M]) arm(id string) error {
if r.Arm == nil {
return nil
}
if err := r.Arm(id, r.idle()); err != nil {
return fmt.Errorf("transfer %s is open but its idle bound is not kept, so it would never be dropped: %w", id, err)
}
return nil
}
// Take takes one chunk of a part from the transfer's opener: chunks of a part arrive in sequence from 0, the last
// marked, and a chunk 0 again starts the part afresh (its earlier chunks are dropped); the whole part must hash to its
// digest, else its chunks are dropped and the part is lacked again. Belongs, when given, refuses a transfer the caller's own shape says is not this call's (another seat's, say). When the last
// lacked part arrives the transfer ends: the caller's check, then its store.
func (r *Receiver[M]) Take(id, opener, digest string, sequence int, last bool, data []byte, belongs func(Transfer[M]) error) (Received, error) {
t, found, err := r.Transfers.Get(id)
switch {
case err != nil:
return Received{}, err
case !found:
return Received{}, fmt.Errorf("transfer %s is not open (dropped after %s with no chunk, or never opened)", id, r.idle())
case t.Opener != opener:
return Received{}, fmt.Errorf("refused for %s: transfer %s was opened by another caller", opener, id)
}
if belongs != nil {
if err := belongs(t); err != nil {
return Received{}, err
}
}
switch {
case len(data) > r.maxChunk():
return Received{}, fmt.Errorf("a chunk of %d bytes is over the %d a chunk may carry", len(data), r.maxChunk())
case !slices.ContainsFunc(t.Parts, func(p Want) bool { return p.Digest == digest }):
return Received{}, fmt.Errorf("transfer %s names no part %s", id, digest)
case slices.Contains(t.Held, digest):
return Received{ID: id, Lacks: t.Lacks()}, nil
case sequence != t.Chunks[digest] && sequence != 0:
return Received{}, fmt.Errorf("part %s of transfer %s waits for chunk %d, not %d", digest, id, t.Chunks[digest], sequence)
}
if sequence == 0 && t.Chunks[digest] != 0 {
// A part the holder lacks travels again whole from chunk 0 (design 51 Publishing): its earlier chunks are dropped.
r.dropChunks(t, digest)
t.Chunks[digest] = 0
}
if err := r.Objects.Put(r.chunkName(id, digest, sequence), data); err != nil {
return Received{}, fmt.Errorf("the objects did not take the chunk: %w", err)
}
// A transfer read back from a key-value state has no Chunks until one was taken: the empty map is kept omitted.
if t.Chunks == nil {
t.Chunks = map[string]int{}
}
t.Chunks[digest] = sequence + 1
t.Last = r.now()
if last {
whole, err := r.part(t, digest)
if err != nil {
return Received{}, err
}
if got := "sha256:" + sum(whole); got != digest {
r.dropChunks(t, digest)
delete(t.Chunks, digest)
_ = r.Transfers.Put(t)
r.fill()
return Received{}, fmt.Errorf("refused: the bytes of part %s hash to %s; send the part again", digest, got)
}
t.Held = append(t.Held, digest)
}
if err := r.Transfers.Put(t); err != nil {
return Received{}, err
}
r.fill()
if len(t.Lacks()) == 0 {
return Received{ID: id, Ended: true}, r.finish(t)
}
return Received{ID: id, Lacks: t.Lacks()}, nil
}
// finish checks and stores a whole transfer; its chunks and its key go either way.
func (r *Receiver[M]) finish(t Transfer[M]) error {
defer func() {
for _, p := range t.Parts {
r.dropChunks(t, p.Digest)
}
_ = r.Transfers.Delete(t.ID)
r.fill()
}()
if r.Check != nil {
if err := r.Check(t); err != nil {
return r.refuse(t, err.Error())
}
}
parts := map[string][]byte{}
for _, p := range t.Parts {
if !t.Taken(p.Digest) {
continue // held by the holder already
}
b, err := r.part(t, p.Digest)
if err != nil {
return r.refuse(t, "part "+p.Digest+" cannot be read from the objects: "+err.Error())
}
parts[p.Digest] = b
}
return r.Store(t, parts)
}
func (r *Receiver[M]) refuse(t Transfer[M], reason string) error {
err := errors.New("refused: " + reason)
if r.Refuse != nil {
if serr := r.Refuse(t, reason); serr != nil {
return fmt.Errorf("%w; and the refusal could not be said: %w", err, serr)
}
}
return err
}
func (r *Receiver[M]) part(t Transfer[M], digest string) ([]byte, error) {
var buf bytes.Buffer
for seq := 0; seq < t.Chunks[digest]; seq++ {
b, err := r.Objects.Get(r.chunkName(t.ID, digest, seq))
if err != nil {
return nil, err
}
buf.Write(b)
}
return buf.Bytes(), nil
}
func (r *Receiver[M]) dropChunks(t Transfer[M], digest string) {
for seq := 0; seq < t.Chunks[digest]; seq++ {
_ = r.Objects.Delete(r.chunkName(t.ID, digest, seq))
}
}
func (r *Receiver[M]) chunkName(id, digest string, seq int) string {
return fmt.Sprintf("%s%s/%s/%d", r.Prefix, id, strings.TrimPrefix(digest, "sha256:"), seq)
}
// fill tells Filled the objects' fill.
func (r *Receiver[M]) fill() {
cap := r.CapNow()
if r.Filled == nil || cap == 0 {
return
}
used, err := r.Objects.Used()
if err != nil {
return
}
r.Filled(used, cap, used*100 >= cap*r.fullPct())
}
// Drop drops a transfer, by hand or because it was idle: its chunks and its key.
func (r *Receiver[M]) Drop(id string) (Transfer[M], error) {
t, found, err := r.Transfers.Get(id)
if err != nil {
return Transfer[M]{}, err
}
if !found {
return Transfer[M]{}, fmt.Errorf("transfer %s is not open", id)
}
for _, p := range t.Parts {
r.dropChunks(t, p.Digest)
}
if err := r.Transfers.Delete(id); err != nil {
return Transfer[M]{}, err
}
r.fill()
return t, nil
}
// Expired is told that a transfer's idle key ended (the bus's marker, FollowIdle): a transfer with no chunk for Idle
// is dropped with its chunks; one that took a chunk since is armed again for the rest of its bound; one already gone
// is nothing to do. It answers whether it dropped the transfer.
func (r *Receiver[M]) Expired(id string) (bool, error) {
t, found, err := r.Transfers.Get(id)
if err != nil {
return false, fmt.Errorf("transfer %s's idle bound ended, but it cannot be read: %w", id, err)
}
if !found {
return false, nil
}
idle := r.now().Sub(t.Last)
if idle >= r.idle() {
if _, err := r.Drop(id); err != nil {
return false, fmt.Errorf("transfer %s had no chunk for %s and is not dropped: %w", id, r.idle(), err)
}
return true, nil
}
if r.Arm == nil {
return false, nil
}
return false, r.Arm(id, max(r.idle()-idle, time.Second))
}
// DropIdle drops every transfer with no chunk for Idle and answers their ids: a look by hand (a listing tool). The
// drop itself follows each transfer's idle key (Arm, Expired), never a timer.
func (r *Receiver[M]) DropIdle() ([]string, error) {
all, err := r.Transfers.List()
if err != nil {
return nil, err
}
var out []string
for _, t := range all {
if r.now().Sub(t.Last) >= r.idle() {
if _, err := r.Drop(t.ID); err == nil {
out = append(out, t.ID)
}
}
}
sort.Strings(out)
return out, nil
}
func sum(b []byte) string {
s := sha256.Sum256(b)
return hex.EncodeToString(s[:])
}
-310
View File
@@ -1,310 +0,0 @@
package parts
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
)
type memObjects map[string][]byte
func (m memObjects) Put(n string, d []byte) error { m[n] = append([]byte(nil), d...); return nil }
func (m memObjects) Get(n string) ([]byte, error) {
if d, ok := m[n]; ok {
return d, nil
}
return nil, errors.New("no object " + n)
}
func (m memObjects) Delete(n string) error { delete(m, n); return nil }
func (m memObjects) Used() (uint64, error) {
var u uint64
for _, d := range m {
u += uint64(len(d))
}
return u, nil
}
// memTransfers keeps each transfer as the bus keeps it, its JSON, so every case reads back what a key-value state
// gives (BusTransfers): an empty map kept with omitempty comes back nil.
type memTransfers[M any] map[string][]byte
func (m memTransfers[M]) Get(id string) (Transfer[M], bool, error) {
var t Transfer[M]
raw, ok := m[id]
if !ok {
return t, false, nil
}
return t, true, json.Unmarshal(raw, &t)
}
func (m memTransfers[M]) Put(t Transfer[M]) error {
raw, err := json.Marshal(t)
m[t.ID] = raw
return err
}
func (m memTransfers[M]) Delete(id string) error { delete(m, id); return nil }
func (m memTransfers[M]) List() ([]Transfer[M], error) {
var out []Transfer[M]
for id := range m {
t, _, err := m.Get(id)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, nil
}
// Two shapes of an opening, as two different seats' holders would keep them.
type packageShape struct{ Name, Version string }
type imageShape struct {
Repository string
Layers int
}
type ended struct {
id, outcome string
parts map[string][]byte
}
func digestOf(b []byte) string { s := sha256.Sum256(b); return "sha256:" + hex.EncodeToString(s[:]) }
func receiverOf[M any](objects memObjects, prefix string, now *time.Time, log *[]ended, check func(Transfer[M]) error) *Receiver[M] {
return &Receiver[M]{Objects: objects, Transfers: memTransfers[M]{}, Prefix: prefix, Cap: 1 << 20, MaxChunk: 1000,
Check: check, Now: func() time.Time { return *now },
Store: func(t Transfer[M], parts map[string][]byte) error {
*log = append(*log, ended{t.ID, "stored", parts})
return nil
},
Refuse: func(t Transfer[M], reason string) error {
*log = append(*log, ended{t.ID, "refused: " + reason, nil})
return nil
}}
}
// aHolderTakesAFileInParts (a case of TestAFileTravelsInTheParts) runs the receiving side for two holders with two shapes and two prefixes on one object
// store (ADR 0627 §2): neither names a seat; the shapes, the checks and the saying are each caller's own.
func aHolderTakesAFileInParts(t *testing.T) {
objects := memObjects{}
now := time.Unix(1000, 0)
var pkgLog, imgLog []ended
pkg := receiverOf(objects, "npm/", &now, &pkgLog, func(t Transfer[packageShape]) error {
if t.Shape.Version == "" {
return errors.New("the builder did not number it")
}
return nil
})
img := receiverOf[imageShape](objects, "image/", &now, &imgLog, nil)
blob := []byte(strings.Repeat("a", 1500))
part := Want{Digest: digestOf(blob), Size: int64(len(blob))}
layer := []byte("layer")
held := Want{Digest: digestOf(layer), Size: int64(len(layer))}
img.Holds = func(_ Transfer[imageShape], d string) bool { return d == held.Digest }
t.Run("two holders, one transfer id, two shapes", func(t *testing.T) {
a, err := pkg.Open("t1", "builder", []Want{part}, packageShape{"m/program", "0.1.4"})
if err != nil || !reflect.DeepEqual(a.Lacks, []string{part.Digest}) {
t.Fatalf("pkg open = %+v, %v", a, err)
}
b, err := img.Open("t1", "builder", []Want{part, held}, imageShape{"m/app", 2})
if err != nil || !reflect.DeepEqual(b.Lacks, []string{part.Digest}) {
t.Fatalf("img open = %+v, %v: a part the holder holds is not lacked", b, err)
}
for _, r := range []func(int, bool, []byte) (Received, error){
func(s int, l bool, d []byte) (Received, error) {
return pkg.Take("t1", "builder", part.Digest, s, l, d, nil)
},
func(s int, l bool, d []byte) (Received, error) {
return img.Take("t1", "builder", part.Digest, s, l, d, nil)
},
} {
if _, err := r(0, false, blob[:1000]); err != nil {
t.Fatal(err)
}
}
// A cut transfer opened again goes on from what is held; another caller may not.
if a, _ := pkg.Open("t1", "builder", []Want{part}, packageShape{}); !reflect.DeepEqual(a.Lacks, []string{part.Digest}) {
t.Errorf("reopen = %+v", a)
}
if _, err := pkg.Open("t1", "other", []Want{part}, packageShape{}); err == nil || !strings.Contains(err.Error(), "another caller") {
t.Errorf("reopen by another = %v", err)
}
// 1966/AC203-2: a chunk that is neither the cursor nor 0 is refused, naming the cursor.
if _, err := pkg.Take("t1", "builder", part.Digest, 2, false, blob[:1000], nil); err == nil || !strings.Contains(err.Error(), "waits for chunk 1, not 2") {
t.Errorf("a chunk out of sequence = %v", err)
}
// 1966/AC203-1: a chunk 0 again (the part lacked travels whole again) drops the earlier chunks and takes it.
if _, err := pkg.Take("t1", "builder", part.Digest, 0, false, blob[:1000], nil); err != nil {
t.Errorf("chunk 0 again = %v", err)
}
a, err = pkg.Take("t1", "builder", part.Digest, 1, true, blob[1000:], nil)
if err != nil || !a.Ended || len(pkgLog) != 1 || pkgLog[0].outcome != "stored" || string(pkgLog[0].parts[part.Digest]) != string(blob) {
t.Fatalf("pkg end = %+v, %v, %+v", a, err, pkgLog)
}
// The image holder's chunks stood apart under its own prefix and are still there.
if _, ok := objects["image/t1/"+strings.TrimPrefix(part.Digest, "sha256:")+"/0"]; !ok || len(objects) != 1 {
t.Fatalf("objects after pkg's end = %v keys, want only the image holder's chunk", len(objects))
}
b, err = img.Take("t1", "builder", part.Digest, 1, true, blob[1000:], func(t Transfer[imageShape]) error { return nil })
if err != nil || !b.Ended || len(imgLog) != 1 || len(imgLog[0].parts) != 1 {
t.Fatalf("img end = %+v, %v, %+v: only the part taken is stored", b, err, imgLog)
}
if len(objects) != 0 {
t.Errorf("objects after both ends = %d, want none", len(objects))
}
})
t.Run("refusals", func(t *testing.T) {
for _, c := range []struct {
name, want string
do func() error
}{
{"no transfer id", "no transfer id", func() error { _, err := pkg.Open("a/b", "builder", []Want{part}, packageShape{}); return err }},
{"no sha256 digest", "no sha256 digest", func() error {
_, err := pkg.Open("t", "builder", []Want{{Digest: "md5:x"}}, packageShape{})
return err
}},
{"another caller's chunk", "another caller", func() error {
_, _ = pkg.Open("t2", "builder", []Want{part}, packageShape{"m", "1"})
_, err := pkg.Take("t2", "other", part.Digest, 0, true, blob, nil)
return err
}},
{"a chunk over the bound", "over the 1000", func() error {
_, err := pkg.Take("t2", "builder", part.Digest, 0, false, make([]byte, 1001), nil)
return err
}},
{"a part the transfer does not name", "names no part", func() error {
_, err := pkg.Take("t2", "builder", held.Digest, 0, true, layer, nil)
return err
}},
{"the caller's own belongs", "not this seat's", func() error {
_, err := pkg.Take("t2", "builder", part.Digest, 0, true, blob, func(Transfer[packageShape]) error { return errors.New("not this seat's") })
return err
}},
{"bytes that do not hash", "send the part again", func() error {
_, err := pkg.Take("t2", "builder", part.Digest, 0, true, []byte("other"), nil)
return err
}},
{"the caller's check", "refused: the builder did not number it", func() error {
_, _ = pkg.Open("t3", "builder", []Want{part}, packageShape{Name: "m"})
_, _ = pkg.Take("t3", "builder", part.Digest, 0, false, blob[:1000], nil)
_, err := pkg.Take("t3", "builder", part.Digest, 1, true, blob[1000:], nil)
return err
}},
{"the cap", "at their cap", func() error {
pkg.Cap = 100
defer func() { pkg.Cap = 1 << 20 }()
_, err := pkg.Open("t4", "builder", []Want{part}, packageShape{})
return err
}},
} {
if err := c.do(); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: err = %v, want %q", c.name, err, c.want)
}
}
if got := pkgLog[len(pkgLog)-1].outcome; !strings.HasPrefix(got, "refused: the objects are at their cap") {
t.Errorf("the cap's refusal said %q", got)
}
if !RefusedAtCap(strings.TrimPrefix(pkgLog[len(pkgLog)-1].outcome, "refused: ")) || RefusedAtCap(strings.TrimPrefix(pkgLog[len(pkgLog)-2].outcome, "refused: ")) {
t.Errorf("RefusedAtCap tells the cap's refusal from the check's: %q, %q", pkgLog[len(pkgLog)-1].outcome, pkgLog[len(pkgLog)-2].outcome)
}
if got := pkgLog[len(pkgLog)-2].outcome; got != "refused: the builder did not number it" {
t.Errorf("the check's refusal said %q", got)
}
// A part that did not hash is lacked again, its chunk gone.
if a, _ := pkg.Open("t2", "builder", []Want{part}, packageShape{}); !reflect.DeepEqual(a.Lacks, []string{part.Digest}) {
t.Errorf("after a bad hash = %+v", a)
}
})
t.Run("idle drop and the fill", func(t *testing.T) {
var fills []bool
pkg.Filled = func(used, cap uint64, full bool) { fills = append(fills, full) }
pkg.Cap, pkg.Full = 1500, 60
defer func() { pkg.Cap, pkg.Full, pkg.Filled = 1<<20, 0, nil }()
_, _ = pkg.Open("t5", "builder", []Want{part}, packageShape{"m", "1"})
_, _ = pkg.Take("t5", "builder", part.Digest, 0, false, blob[:1000], nil)
if len(fills) == 0 || !fills[len(fills)-1] {
t.Errorf("fills = %v, want full at 1000 of 1500 bytes (60 percent)", fills)
}
now = now.Add(IdleAfter)
dropped, err := pkg.DropIdle()
if err != nil || !reflect.DeepEqual(dropped, []string{"t2", "t5"}) {
t.Errorf("DropIdle = %v, %v", dropped, err)
}
if fills[len(fills)-1] || len(objects) != 0 {
t.Errorf("after the drop: full %v, %d objects", fills[len(fills)-1], len(objects))
}
if _, err := pkg.Take("t5", "builder", part.Digest, 1, true, blob[1000:], nil); err == nil || !strings.Contains(err.Error(), "not open") {
t.Errorf("a chunk after the drop = %v", err)
}
})
// An open transfer is bounded by its idle key (Arm); the key's end (Expired) drops it idle, arms it again for the
// rest when it took a chunk since, and leaves a gone one; a key not written fails the open loudly. The cap the
// binding carries (Bound) counts over Cap.
t.Run("the idle key and the binding's cap", func(t *testing.T) {
armed := map[string]time.Duration{}
pkg.Arm = func(id string, ttl time.Duration) error { armed[id] = ttl; return nil }
defer func() { pkg.Arm, pkg.Bound = nil, nil }()
if _, err := pkg.Open("t6", "builder", []Want{part}, packageShape{"m", "1"}); err != nil || armed["t6"] != IdleAfter {
t.Fatalf("open = %v, armed %v; want t6's idle key for %s", err, armed, IdleAfter)
}
now = now.Add(time.Hour)
_, _ = pkg.Take("t6", "builder", part.Digest, 0, false, blob[:1000], nil)
now = now.Add(IdleAfter - time.Hour)
if dropped, err := pkg.Expired("t6"); err != nil || dropped || armed["t6"] != time.Hour {
t.Errorf("expired after a chunk = %v, %v, armed %v; want armed again for the hour left", dropped, err, armed["t6"])
}
now = now.Add(time.Hour)
if dropped, err := pkg.Expired("t6"); err != nil || !dropped || len(objects) != 0 {
t.Errorf("expired idle = %v, %v, %d objects; want dropped with its chunks", dropped, err, len(objects))
}
if dropped, err := pkg.Expired("t6"); err != nil || dropped {
t.Errorf("expired once gone = %v, %v; want nothing to do", dropped, err)
}
pkg.Arm = func(string, time.Duration) error { return errors.New("bus down") }
if _, err := pkg.Open("t7", "builder", []Want{part}, packageShape{"m", "1"}); err == nil || !strings.Contains(err.Error(), "never be dropped") {
t.Errorf("open with no idle key = %v, want a loud failure", err)
}
pkg.Bound = func() (uint64, error) { return 100, nil }
if _, err := pkg.Open("t8", "builder", []Want{part}, packageShape{}); err == nil || !strings.Contains(err.Error(), "cap of 100 bytes") {
t.Errorf("open past the binding's cap = %v, want refused at 100 bytes", err)
}
if pkg.Bound = func() (uint64, error) { return 0, errors.New("no binding") }; pkg.CapNow() != pkg.Cap {
t.Errorf("CapNow with no binding read = %d, want Cap %d", pkg.CapNow(), pkg.Cap)
}
pkg.Bound = nil
// At the start of the idle watch every open transfer is looked at (expireOpen): one whose key ended while the
// bundle was down is dropped, one still within its bound is armed again for the rest.
pkg.Arm = func(id string, ttl time.Duration) error { armed[id] = ttl; return nil }
for id := range pkg.Transfers.(memTransfers[packageShape]) {
_, _ = pkg.Drop(id)
}
_, _ = pkg.Open("t9", "builder", []Want{part}, packageShape{"m", "1"})
now = now.Add(IdleAfter + time.Hour)
_, _ = pkg.Open("t10", "builder", []Want{part}, packageShape{"m", "1"})
now = now.Add(time.Hour)
var dropped []string
expireOpen("idle", IDs(pkg.Transfers), pkg.Expired, func(id string, d bool, err error) {
if err != nil {
t.Errorf("start's look at %s: %v", id, err)
}
if d {
dropped = append(dropped, id)
}
})
if !reflect.DeepEqual(dropped, []string{"t9"}) || armed["t10"] != IdleAfter-time.Hour {
t.Errorf("at the start: dropped %v, t10 armed for %s; want t9 dropped and t10 armed for %s", dropped, armed["t10"], IdleAfter-time.Hour)
}
var said error
expireOpen("idle", func() ([]string, error) { return nil, errors.New("bus down") }, pkg.Expired, func(_ string, _ bool, err error) { said = err })
if said == nil || !strings.Contains(said.Error(), "bus down") {
t.Errorf("start's look with no list said %v, want the failure", said)
}
})
}
-64
View File
@@ -1,64 +0,0 @@
package seatdefs
// Where a seat of the mesh's own contracts may be defined (novox/hq ADR 0636 §5, ADR 0634 §7): a definition names its
// glossary domain; a seat of the mesh's own contracts is taken only from that domain's contracts module
// (mesh-<domain>-contracts), or from mesh-contracts for a domain with none. A definition moving from mesh-contracts to
// its domain's contracts module is a handover: the new definer takes the seat over, and a removal from the module that is
// not the seat's domain's keeps the last trunk definition until the domain's module defines it.
import (
"fmt"
"slices"
"strings"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// Fallback is the mesh's contracts module for a domain with no contracts module of its own.
const Fallback = "mesh-contracts"
// domainsWithContracts are the domains whose seats have a contracts module of their own (ADR 0634 §7). Every other
// domain's seats are defined in Fallback.
var domainsWithContracts = []string{"Delivery", "Provisioning", "Identity and access", "Health and repair",
"Connectivity", "Operator and conversation"}
// DomainContracts is the module that defines a domain's seats: mesh-<domain>-contracts, the heading lowercased with its
// spaces as dashes, or Fallback for a domain with none.
func DomainContracts(domain string) string {
if !slices.Contains(domainsWithContracts, domain) {
return Fallback
}
return "mesh-" + strings.ReplaceAll(strings.ToLower(domain), " ", "-") + "-contracts"
}
// Own says a contracts module is one of the mesh's own: Fallback or a domain's.
func Own(module string) bool {
return module == Fallback || slices.ContainsFunc(seatdef.Domains, func(d string) bool {
return module == DomainContracts(d) && module != Fallback
})
}
// Refusal is, for a definition a contracts module of the mesh's own holds, why it may not: the words naming the module
// and the domain's. Empty when the module may define the seat (a module outside the mesh's own contracts defines what it
// likes, ADR 0625 §7).
func Refusal(module string, d seatdef.Definition) string {
if !Own(module) {
return ""
}
if want := DomainContracts(d.Domain); want != module {
return fmt.Sprintf("it is a seat of the domain %q, whose seats %s defines, and %s defines it", d.Domain, want, module)
}
return ""
}
// HandsOver says a seat its holder defines is handed over to a definer: the holder is a module of the mesh's own that is
// not the definer, and the definer is the seat's domain's contracts module.
func HandsOver(holder, definer string, d seatdef.Definition) bool {
return holder != definer && Own(holder) && DomainContracts(d.Domain) == definer
}
// HandoverPending says a seat a holder of the mesh's own no longer defines waits for its domain's module: the holder is
// not the domain's (named by the definition it held), so its last definition stays until that module defines it.
func HandoverPending(holder, domain string) bool {
return Own(holder) && DomainContracts(domain) != holder
}
-172
View File
@@ -1,172 +0,0 @@
// Package seatdefs is how a seat definition is read from a contracts module at a commit, and which contracts module may
// define a seat (novox/hq ADR 0608 §2-§3, ADR 0635 §2, ADR 0636 §5, ADR 0634 §1-§2): the one reading the indexer keeps
// in its state seat-definitions and the checker lays over the seat list for a case's heads, so both take the same
// definitions from the same modules. It names no transport: the caller's Forge binds the forge's listing and its
// get-file to its own calls.
package seatdefs
import (
"context"
"errors"
"fmt"
"path"
"slices"
"strings"
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// ErrUnanswered wraps a read the forge did not answer (never a file or a directory it does not hold): the caller tries
// again rather than taking the module's definitions as gone.
var ErrUnanswered = errors.New("the forge did not answer")
// Forge is what the reading asks of the forge.
type Forge struct {
// Files lists every file under each directory at a commit, by directory then path relative to it; a directory the
// commit lacks is absent from the answer (no error).
Files func(ctx context.Context, repository, commit string, dirs []string) (map[string]map[string]string, error)
// File reads one file at a commit; a file the commit does not hold is nil with no error.
File func(ctx context.Context, repository, commit, path string) ([]byte, error)
}
// Module is a contracts module: its name, its directory in the repository and its definitions' directory.
type Module struct{ Module, Dir, Defs string }
// Of is the contracts module a manifest in a directory is (a package artifact naming `generated-from`), and whether it
// is one at all.
func Of(dir string, m catalogue.Manifest) (Module, bool) {
if m.Build == nil {
return Module{}, false
}
for _, a := range m.Build.Artifacts {
if a.GeneratedFrom == "" {
continue
}
base := strings.Trim(dir, "/")
if base == meshcatalogclient.RootPath {
base = ""
}
return Module{Module: m.Module, Dir: dir, Defs: path.Clean(path.Join(base, a.GeneratedFrom))}, true
}
return Module{}, false
}
// ContractsModules are the contracts modules among raw manifests by directory, in directory order. A manifest that does
// not decode is no contracts module here: the manifest validator says why it is refused.
func ContractsModules(manifests map[string]string) []Module {
var out []Module
for dir, raw := range manifests {
m, err := catalogue.Decode([]byte(raw))
if err != nil {
continue
}
if c, ok := Of(dir, m); ok {
out = append(out, c)
}
}
slices.SortFunc(out, func(a, b Module) int { return strings.Compare(a.Dir, b.Dir) })
return out
}
// under is a path of the module's definitions' directory.
func (c Module) under(rel string) string {
if c.Defs == "." || c.Defs == "" {
return rel
}
return c.Defs + "/" + rel
}
// Seats names the seats a contracts module defines at a commit: every directory of its definitions' `seats/` that holds
// a `seat.json`, whatever the seat's grain (ADR 0635 §2, §6), from the forge's one listing of that directory. No index
// file names them.
func (f Forge) Seats(ctx context.Context, repository, commit string, c Module) ([]string, error) {
if f.Files == nil {
return nil, fmt.Errorf("%w: no listing of %s's seats", ErrUnanswered, c.Module)
}
dir := c.under("seats")
got, err := f.Files(ctx, repository, commit, []string{dir})
if err != nil {
return nil, fmt.Errorf("%w: the seats of %s at %.12s: %w", ErrUnanswered, c.Module, commit, err)
}
var seats []string
for p := range got[dir] {
if seat, ok := strings.CutSuffix(p, "/seat.json"); ok && seat != "" && !strings.Contains(seat, "/") {
seats = append(seats, seat)
}
}
slices.Sort(seats)
return seats, nil
}
// Read reads a contracts module's definitions at a commit: each seat's definition (Seats) and the parts it includes,
// each resolved. A seat whose definition is missing, does not parse, names another seat than its directory's, or whose
// part does not parse or resolve, is answered in unparsed by its words; a read the forge did not answer is an error
// wrapping ErrUnanswered.
func (f Forge) Read(ctx context.Context, repository, commit string, c Module) (defs map[string]seatdef.Definition, unparsed map[string]string, err error) {
if f.File == nil {
return nil, nil, fmt.Errorf("%w: no reader of %s's definitions", ErrUnanswered, c.Module)
}
file := func(rel string) ([]byte, error) {
p := c.under(rel)
raw, err := f.File(ctx, repository, commit, p)
if err != nil {
return nil, fmt.Errorf("%w: %s at %.12s: %w", ErrUnanswered, p, commit, err)
}
if raw == nil {
return nil, fmt.Errorf("%s at %.12s: the forge holds no such file", p, commit)
}
return raw, nil
}
seats, err := f.Seats(ctx, repository, commit, c)
if err != nil {
return nil, nil, err
}
defs, unparsed = map[string]seatdef.Definition{}, map[string]string{}
parts := map[string]seatdef.Part{}
for _, seat := range seats {
raw, err := file("seats/" + seat + "/seat.json")
if err != nil {
if errors.Is(err, ErrUnanswered) {
return nil, nil, err
}
unparsed[seat] = err.Error()
continue
}
d, err := seatdef.Parse(raw)
if err == nil && d.Seat != seat {
err = fmt.Errorf("it names the seat %q, not %q", d.Seat, seat)
}
if err == nil {
for _, name := range d.Includes {
if _, ok := parts[name]; ok {
continue
}
praw, perr := file("parts/" + name + ".json")
if perr == nil {
var p seatdef.Part
if p, perr = seatdef.ParsePart(praw); perr == nil {
parts[name] = p
}
}
if errors.Is(perr, ErrUnanswered) {
return nil, nil, perr
}
if perr != nil {
err = fmt.Errorf("its part %s: %w", name, perr)
break
}
}
}
if err == nil {
d, err = seatdef.Resolve(d, parts)
}
if err != nil {
unparsed[seat] = err.Error()
continue
}
defs[seat] = d
}
return defs, unparsed, nil
}
-136
View File
@@ -1,136 +0,0 @@
// Package sourcebranches is the follower of the branches the seat mesh-delivery's verb source keeps (design 47 G §614),
// in the Delivery domain's SDK so that a seat's client holds no other seat's types (ADR 0625 §4): the first view of the
// verb given no branch, then each source-moved heard, and the asking again until a change heard is held.
package sourcebranches
import (
"context"
"encoding/json"
"fmt"
"slices"
"time"
delivery "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdelivery"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/views"
)
// Seat is the seat whose verb source and event source-moved are followed.
const Seat = delivery.Seat
// EventSourceMoved is the event the seat says when a branch's source moved.
const EventSourceMoved = delivery.EventSourceMoved
// SourceVerb is the gate's verb a part reads the branches the gate keeps a source revision of by, before the first
// registrations, as its manifest's invokes names it (design 47 G §614).
const SourceVerb = "seat:" + delivery.Seat + "." + delivery.VerbSource
// StateSourceBranches names the view of the branches the gate's source keeps in a part's reader (`mesh-delivery.source`).
const StateSourceBranches = "source"
// Call asks one seat verb over the bus and answers what the holder said, whatever wraps it (process.Conn.Call, or
// stdio.Ask through the tool runner).
type Call func(key string, body any) (json.RawMessage, error)
// Created stands for the picture's Created in a follower: followed by the seat's event, never by an owner's views family,
// so one fixed time, never zero.
var Created = time.Unix(0, 0).UTC()
// ClipBytes is data cut to 200 bytes for a message.
func ClipBytes(b []byte) string {
if len(b) > 200 {
return string(b[:200]) + "…"
}
return string(b)
}
// SourceBranches is a part's follower of the branches the gate's `source` keeps (design 47 G §614): a first view of the
// verb `source` given no branch, then each `source-moved` heard. Its picture is keyed by the escaped branch name.
type SourceBranches struct {
Follower *views.Follower
call Call
}
// New is a SourceBranches asking the gate through call. Nothing is asked before the reader starts it.
func New(call Call) *SourceBranches {
s := &SourceBranches{call: call}
s.Follower = &views.Follower{Owner: Seat, Tool: SourceVerb, State: StateSourceBranches, Ask: s.ask}
return s
}
// Branches is the escaped name of each branch the picture holds.
func (s *SourceBranches) Branches() []string {
out := make([]string, 0)
for b := range s.Follower.Values() {
out = append(out, b)
}
slices.Sort(out)
return out
}
// Hear takes one `source-moved` event: a branch the picture does not hold asks the first view again until it does, on
// its own goroutine, so the consumer is never held. Data that is no such event is an error.
func (s *SourceBranches) Hear(ctx context.Context, data []byte) error {
var ev delivery.SourceMovedEvent
if err := json.Unmarshal(data, &ev); err != nil || ev.Branch == "" {
return fmt.Errorf("sourcebranches: not a %s event: %s", EventSourceMoved, ClipBytes(data))
}
held := func() bool { _, ok := s.Follower.Get(keys.EscapeName(ev.Branch)); return ok }
if held() {
return nil
}
go CatchUp(ctx, s.Follower, held, fmt.Sprintf("source of %s moved", ev.Branch))
return nil
}
func (s *SourceBranches) ask(_ context.Context, _ string) (views.Answer, error) {
raw, err := s.call(SourceVerb, delivery.SourceInput{})
if err != nil {
return views.Answer{}, err
}
answer, said, ok := buscalls.Unwrap(raw)
if !ok {
return views.Answer{}, fmt.Errorf("%s answered: %s", SourceVerb, said)
}
var a delivery.SourceAnswer
if err := json.Unmarshal(answer, &a); err != nil {
return views.Answer{}, fmt.Errorf("%s answered no branches: %s", SourceVerb, ClipBytes(answer))
}
if a.Error != "" {
return views.Answer{}, fmt.Errorf("%s answered: %s", SourceVerb, a.Error)
}
values := make(map[string]json.RawMessage, len(a.Branches))
for _, b := range a.Branches {
values[b] = json.RawMessage(`{}`)
}
return views.Answer{V: 1, Owner: Seat, State: StateSourceBranches, Created: Created, Values: values, At: time.Now()}, nil
}
// CatchUp asks f's first view again until held says it holds what was heard, pausing between asks as the follower's Wait
// says (doubling to a minute), or until ctx ends: an ask already running may have been answered before the change was
// written.
func CatchUp(ctx context.Context, f *views.Follower, held func() bool, why string) {
wait := f.Wait
if wait == 0 {
wait = 5 * time.Second
}
for !held() {
if err := f.Gap(ctx, why); err != nil {
return
}
if held() {
return
}
p, cancel := context.WithTimeout(ctx, wait)
<-p.Done()
cancel()
if ctx.Err() != nil {
return
}
if wait *= 2; wait > time.Minute {
wait = time.Minute
}
}
}
-43
View File
@@ -1,43 +0,0 @@
package trunk
import (
"fmt"
"strings"
)
// A mesh package is a Go module of a repository of the mesh's forge (ForgeModulePrefix): mesh-sdk's Go module, and an
// owner module's package (novox/hq ADR 0593 §1). The indexer alone reads which packages a module imports, their content
// digests and their latest published versions, and writes them in its state (PublishedPackages, ADR 0593 §2); a build
// writes the version it is asked into its own go.mod and go.sum (StepAsk.Packages).
// ForgeModulePrefix is the module path prefix of the Go modules the mesh's forge serves: a Go module whose path starts
// with it is a mesh package, git.novox.be/novox/<repository>[/<directory of the module in it>].
const ForgeModulePrefix = "git.novox.be/novox/"
// PackageRepository is the repository (<owner>/<name>) a mesh package is published from and the package's directory in
// it ("" for its root); false for a path that is not a forge module's.
func PackageRepository(pkg string) (repository, dir string, ok bool) {
rest, found := strings.CutPrefix(pkg, ForgeModulePrefix)
if !found || rest == "" {
return "", "", false
}
name, dir, _ := strings.Cut(rest, "/")
if name == "" {
return "", "", false
}
return "novox/" + name, dir, true
}
// CheckImports refuses an import set (the imports of a module's kept inputs, of a build's answer and of a build log entry)
// that holds a path that is no mesh package's, or is not sorted and each once.
func CheckImports(imports []string) error {
for i, pkg := range imports {
if _, _, ok := PackageRepository(pkg); !ok || strings.ContainsAny(pkg, " \t\n@") {
return fmt.Errorf("trunk: the import %q is no mesh package's path (it starts with %s)", pkg, ForgeModulePrefix)
}
if i > 0 && imports[i-1] >= pkg {
return fmt.Errorf("trunk: the imports are not sorted and each once (%s after %s)", pkg, imports[i-1])
}
}
return nil
}
-41
View File
@@ -1,41 +0,0 @@
package trunk
import (
"fmt"
"strings"
"git.novox.be/novox/mesh-sdk/go/keys"
)
// RepositoryName is the repository as the forge names it, "owner/name", from either spelling the mesh holds: the name
// itself, or the clone URL a build record carries ("http://host:port/owner/name.git", with or without ".git" or a
// trailing slash). A string of fewer than two path segments is returned as it is, trimmed (issue 1281).
func RepositoryName(s string) string {
s = strings.TrimSpace(s)
s = strings.TrimRight(s, "/")
s = strings.TrimSuffix(s, ".git")
s = strings.TrimRight(s, "/")
parts := strings.FieldsFunc(s, func(r rune) bool { return r == '/' || r == ':' })
if len(parts) < 2 {
return s
}
return parts[len(parts)-2] + "/" + parts[len(parts)-1]
}
// SameRepository is whether two spellings name one repository: the same owner and name, whichever way each is written
// (RepositoryName), compared without regard to case as the forge does. An empty spelling names none (issue 1281).
func SameRepository(a, b string) bool {
a, b = RepositoryName(a), RepositoryName(b)
return a != "" && strings.EqualFold(a, b)
}
// RepositoryKey is a repository's key in the indexer's state `taken` and the view's state `reach`: its forge name `owner/name` (RepositoryName), in
// lower case as the forge compares it, escaped as a key part (keys.EscapeName). An empty spelling, or one with no owner, is
// refused.
func RepositoryKey(repository string) (string, error) {
name := strings.ToLower(RepositoryName(repository))
if owner, repo, ok := strings.Cut(name, "/"); !ok || owner == "" || repo == "" {
return "", fmt.Errorf("trunk: %q names no repository as owner/name", repository)
}
return keys.EscapeName(name), nil
}
-58
View File
@@ -1,58 +0,0 @@
package trunk
import (
"testing"
)
func TestSameRepository(t *testing.T) { // 1281/AC1
const forge = "novox/mesh-catalog"
for _, c := range []struct {
a, b string
same bool
}{
// the clone URL as a build record carries it (mesh-controller.command builds, 2026-10-19 ~21:20 local)
{forge, "http://novox.internal:20000/novox/mesh-catalog.git", true},
{forge, "http://novox.internal:20000/novox/mesh-catalog", true},
{forge, "http://novox.internal:20000/novox/mesh-catalog.git/", true},
{"http://novox.internal:20000/novox/mesh-catalog.git/", forge, true},
{forge, "novox/mesh-catalog", true},
{forge, "Novox/Mesh-Catalog", true},
{forge, "http://novox.internal:20000/novox/mesh-catalog-x.git", false},
{forge, "novox/mesh-catalog-x", false},
{forge, "http://novox.internal:20000/other/mesh-catalog.git", false},
{forge, "other/mesh-catalog", false},
{forge, "http://novox.internal:20000/novox/mesh-media-catalog.git", false},
{forge, "", false},
{"", "", false},
} {
if got := SameRepository(c.a, c.b); got != c.same {
t.Errorf("SameRepository(%q, %q) = %v, want %v", c.a, c.b, got, c.same)
}
}
if got := RepositoryName("http://novox.internal:20000/novox/mesh-catalog.git"); got != "novox/mesh-catalog" {
t.Errorf("RepositoryName = %q", got)
}
}
func TestAnImportSetHoldsMeshPackagesSortedAndEachOnce(t *testing.T) {
a, b := ForgeModulePrefix+"mesh-sdk/go", ForgeModulePrefix+"mesh-delivery/sdk"
if err := CheckImports([]string{b, a}); err != nil {
t.Errorf("a sorted set is refused: %v", err)
}
for name, bad := range map[string][]string{"unsorted": {a, b}, "twice": {a, a}, "not a mesh package": {"github.com/x/y"}, "a version": {a + "@v1"}} {
if CheckImports(bad) == nil {
t.Errorf("%s: %v is taken", name, bad)
}
}
}
// A repository keys the indexer's taken and the view's reach by its forge name, in lower case, from either spelling (ADR 0556).
func TestARepositoryIsKeyedByItsLowerCaseForgeName(t *testing.T) {
for in, want := range map[string]string{"novox/Mesh-SDK": "novox/mesh-sdk", "http://h:3000/novox/mesh-sdk.git": "novox/mesh-sdk",
"a/b.c": "a/b=2ec", "": "", "nope": "", "/x": ""} {
got, err := RepositoryKey(in)
if (want == "") != (err != nil) || got != want {
t.Errorf("RepositoryKey(%q) = %q, %v; want %q", in, got, err, want)
}
}
}
-64
View File
@@ -1,64 +0,0 @@
package window
import (
"slices"
"sort"
"time"
)
// WindowHeld is the part of a window every window keeper shares (design 51: distribution's old seat name and direct
// writes, the builder's old reference form): whether it is open, the nodes holding it and since when, and when it last
// closed and who held it then. A keeper embeds it in its own record, so its JSON is the record's.
type WindowHeld struct {
Open bool `json:"open"`
Holding []string `json:"holding,omitempty"`
Since map[string]time.Time `json:"since,omitempty"`
Closed time.Time `json:"closed,omitzero"`
// LastHolding are the nodes that held it last, said when it closes.
LastHolding []string `json:"last_holding,omitempty"`
}
// StepWindow is the one rule every window keeper steps its window by (security-upgrade review F3, the second of a
// kind): named is every node the read named, dropped ones included, and holding those of them that hold the window at
// now. A read that names no node judges nothing, as a first view's empty answer at revision 0 is no empty state (ADR
// 0615): an empty node_haves or assignments not yet read never closes a window, and the window stays as it was. A read
// naming nodes, none holding, closes an open window (closed true, once); one naming a holder opens it, each holder's
// since kept from w. overdue are the holders whose since is at least findingAfter before now (the keeper's finding,
// cleared for every other node); a read naming no node keeps w's holders' overdue as they stand at now.
func StepWindow(w WindowHeld, named, holding []string, now time.Time, findingAfter time.Duration) (next WindowHeld, closed bool, overdue []string) {
now = now.UTC()
if len(named) == 0 {
next = w
for _, n := range w.Holding {
if since, ok := w.Since[n]; ok && now.Sub(since) >= findingAfter {
overdue = append(overdue, n)
}
}
return next, false, overdue
}
if len(holding) == 0 {
next = WindowHeld{Closed: w.Closed, LastHolding: w.LastHolding}
if w.Open {
next.Closed, next.LastHolding = now, slices.Clone(w.Holding)
if next.LastHolding == nil {
next.LastHolding = []string{}
}
return next, true, nil
}
return next, false, nil
}
held := slices.Clone(holding)
sort.Strings(held)
next = WindowHeld{Open: true, Holding: held, Since: map[string]time.Time{}, Closed: w.Closed, LastHolding: w.LastHolding}
for _, n := range held {
since, had := w.Since[n]
if !had {
since = now
}
next.Since[n] = since
if now.Sub(since) >= findingAfter {
overdue = append(overdue, n)
}
}
return next, false, overdue
}
-41
View File
@@ -1,41 +0,0 @@
package window
import (
"slices"
"testing"
"time"
)
// The one rule every window keeper steps by (design 51; security-upgrade review F3): a read naming no node judges
// nothing, so an empty node_haves or an unread assignments never closes a window.
func TestStepWindow(t *testing.T) {
now := time.Date(2026, 11, 4, 17, 0, 0, 0, time.UTC)
week := 7 * 24 * time.Hour
long := now.Add(-8 * 24 * time.Hour)
open := WindowHeld{Open: true, Holding: []string{"n1"}, Since: map[string]time.Time{"n1": long}}
for _, c := range []struct {
name string
w WindowHeld
named, holding []string
open, closed bool
holds, overdue []string
}{
{"a read naming no node leaves an open window open, its holder still overdue", open, nil, nil, true, false, []string{"n1"}, []string{"n1"}},
{"a read naming no node leaves a closed window closed", WindowHeld{Closed: long}, nil, nil, false, false, nil, nil},
{"a read naming nodes, none holding, closes an open window once", open, []string{"n1", "n2"}, nil, false, true, nil, nil},
{"a closed window a read finds unheld stays closed, said no more", WindowHeld{Closed: long, LastHolding: []string{"n1"}}, []string{"n1"}, nil, false, false, nil, nil},
{"a new holder opens it, since now, not overdue", WindowHeld{}, []string{"n1", "n2"}, []string{"n2"}, true, false, []string{"n2"}, nil},
{"a holder keeps its since and is overdue past the bound", open, []string{"n1", "n2"}, []string{"n2", "n1"}, true, false, []string{"n1", "n2"}, []string{"n1"}},
} {
next, closed, overdue := StepWindow(c.w, c.named, c.holding, now, week)
if next.Open != c.open || closed != c.closed || !slices.Equal(next.Holding, c.holds) || !slices.Equal(overdue, c.overdue) {
t.Errorf("%s: open %v closed %v holding %v overdue %v", c.name, next.Open, closed, next.Holding, overdue)
}
if closed && (!next.Closed.Equal(now) || !slices.Equal(next.LastHolding, c.w.Holding)) {
t.Errorf("%s: closed at %v, last held by %v", c.name, next.Closed, next.LastHolding)
}
if !c.open && !closed && !next.Closed.Equal(c.w.Closed) {
t.Errorf("%s: its last close moved to %v", c.name, next.Closed)
}
}
}