Join: merge A3 (wip/registry-a3)
Conflicts, both sides kept: artifact-store-tools' invokes (the assigner's and indexer's read tools, followed through views, beside the registry seats' hold, release and remove), its main (the views reader and the seat asker), its manifest row; gitea's invokes (the indexer's read tool, the hand act and the builder's versions) and its consumes of the indexer's views. gitea's account test takes the packages account's names; repoCheckFacts, removed on main, is not imported. No catalogue module reads the indexer's state. Claude-Session: https://claude.ai/code/session_01JG73KJNrH5EgFXMKKYSrig
This commit is contained in:
@@ -135,11 +135,30 @@ that vendors), `go build -ldflags "-s -w -X main.builtFor=<system>" -o .mesh-bui
|
||||
module's directory, by the installed go (`GOTOOLCHAIN=local`) from the module cache the fetch filled and no network
|
||||
(`GOPROXY=off`). The binary is named as the build agent names it. The output directory is packed with the build runner's `Pack`,
|
||||
as the build agent packs; two build nodes on the same toolchain give the same digest for the same tree (ADR 0477 §6). The step ends with the artifact, the binary, the digest, the size and
|
||||
the reference of the archive: once the build ended, this process pushes it to the artifact store (novox/hq ADR 0498 §1 §2,
|
||||
the build runner's `buildstep.PushBlob`) under `<module>/<artifact>` by its digest, a candidate's as a trunk build's, and answers
|
||||
`artifact-store://<module>/<artifact>/blobs/<digest>`; a push that fails fails the step `not stored: <artifact>: <the
|
||||
store's words>`. The packed bytes never stay on the node. The store's address is `${dir:state}/registry`, placed by the
|
||||
manifest, which requires `artifact-store`. The go build runs shut off in bubblewrap (ADR 0448, `isolate.go`): no
|
||||
the reference of the archive: once the build ended, this process publishes it through the seat `oci-artifact-registry`
|
||||
(design 51 *Publishing*; `publish.go`): its verbs `publish` and `publish-part`, which the manifest `invokes`, with mesh-sdk's
|
||||
sender (`publish.Publish`), under `<module>/<artifact>` by its digest and of kind `bundle` or `archive`, a candidate's as a
|
||||
trunk build's, in chunks, only what the holder lacks; the holder asks the builder and says `published` or `refused` on the
|
||||
seat's events. The step answers the seat's form `oci-artifact-registry/<module>/<artifact>@<digest>` (ADR 0605 §9); the
|
||||
builder writes the older form beside it while a counted node-engine reads only that (ADR 0624); a publish the holder refuses, or a
|
||||
seat nothing holds, fails the step `not stored: <artifact>: <the holder's words>`. The packed bytes never stay on the node.
|
||||
A build the builder numbers later is published late: the module consumes the builder's `version.numbered` and, for a
|
||||
bundle or an archive with a digest, publishes that held digest under its version, naming its one part by digest and
|
||||
sending nothing (`latepublish.go`); a holder that no longer holds the digest fails the event, which is offered again. Every
|
||||
ask of a seat a build module makes (a publish, a late publish, an image's copy) is narrated by `buildstep/narrate.go`:
|
||||
asked, waiting on the seat every five minutes while it has not answered, stored or refused, each the ask's phase on its
|
||||
running step key (logged outside an ask).
|
||||
A contracts module (a package artifact naming `generated-from`) has its generated Go files regenerated with the seat
|
||||
generator this module is built with and compared (`buildstep/generated.go`): the unit level of `build_go_test` fails
|
||||
naming each file that differs, is missing or was not written by the generator (its `out-of-step`), and a build ask
|
||||
answers the same files in its answer's `out-of-step`, a failed build's too, so a trunk build's end can raise
|
||||
`generated-types-out-of-step` where no test step runs. Its TypeScript files are mesh-build-node's to compare.
|
||||
|
||||
The module writes into no store itself and requires no `artifact-store`. A Go package (kind `package`, language `go`; `gopackage.go`) is
|
||||
the directory its one path names packed as Go's module zip, every file under `<module path>@<version>/`, its digest the
|
||||
zip's (no `h1:` sum is answered: nothing carries it on); a trunk build the builder gave a version publishes it through
|
||||
`go-package-registry` under its Go module path and that version (the manifest `invokes` both verbs) and answers
|
||||
`<module path>@<version>`; a candidate's is packed under `v0.0.0` and publishes nothing. The go build runs shut off in bubblewrap (ADR 0448, `isolate.go`): no
|
||||
network, none of the account, the caches beneath a throwaway layer unless the step is told `publish` (a trunk build). An artifact that is neither a Go
|
||||
bundle nor an archive fails the step naming it.
|
||||
|
||||
@@ -154,9 +173,16 @@ and xz, read in Go as the build agent reads it, issue 1590); it runs no command
|
||||
- The build runner (the pull of asks, the step lifecycle, the toolchain guard, the fetch, the parsers of `go test -json` and
|
||||
`node --test`, `Pack`, the conformance kit and the `mesh-pack` command) is this module's package
|
||||
`git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep`, a Go module of its own in `buildstep/`. mesh-build-node
|
||||
and mesh-build-image require it and replace it to the sibling directory, since it is the same repository. What the delivery
|
||||
and mesh-build-image require it and replace it to the sibling directory, since it is the same repository. It is declared
|
||||
as this module's Go package artifact `buildstep`, series `0.1` (ADR 0606): a user in another repository accepts its
|
||||
series, never a commit. What the delivery
|
||||
parts read of a step (the failure contract, the fetch request, the stale-step sweep, the step id) stays in mesh-sdk's
|
||||
`buildstep`.
|
||||
- The seat generator (design 26 *Contracts modules*) is the package `buildstep/seatgen` and the command `buildstep/cmd/seatgen`,
|
||||
one program writing a contracts module's Go and TypeScript (`seatgen <dir>`; `seatgen -check <dir>` names every path out of
|
||||
step and runs the client and artifact checks). Its version is buildstep's, so the build input of a compare is the
|
||||
mesh-build-go (or mesh-build-node) build itself: a new generator is a new build module and a new fingerprint. A contracts
|
||||
repository runs it as `go run git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep/cmd/seatgen@<version> -check .`.
|
||||
- `build_go_imports` (a tool, and the last step of a build ask that built an artifact) answers the mesh packages the module's
|
||||
Go programs import: `go list -deps` of each Go bundle's program, tests left out, the packages of the forge outside the
|
||||
module's own directory (a sibling package of its own repository counts), sorted and each once. A build ask carries them as
|
||||
|
||||
@@ -29,6 +29,10 @@ type AskSteps struct {
|
||||
// {"imports": [...]}, sorted, from the workspace the build ran in. A build that built an artifact asks it once, at
|
||||
// its end; nil reports none.
|
||||
Imports StepFunc
|
||||
// Compare regenerates a contracts module's generated files (a package artifact naming generated-from) and answers
|
||||
// {"out-of-step": [...]} (CompareStep): a build ask runs it once on the fetched workspace and answers the paths in
|
||||
// its out-of-step, a failed build's too, so a trunk build's end names them where no test step runs. Nil compares none.
|
||||
Compare StepFunc
|
||||
// Toolchain is the toolchain the module builds with now; a build ask naming another is declined (Declining). Nil checks nothing
|
||||
// (an image or an archive names none).
|
||||
Toolchain func(ctx context.Context) (delivery.ToolchainUsed, error)
|
||||
@@ -156,6 +160,24 @@ func (s AskSteps) build(ctx context.Context, job delivery.BuildJob) (any, error)
|
||||
}
|
||||
}
|
||||
f = got
|
||||
if s.Compare != nil {
|
||||
Phase(ctx, "compare the generated files")
|
||||
out, err := s.Compare(ctx, map[string]any{"workspace": f.Workspace, "module": job.Path})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the generated files of %s: %w", job.Module, err)
|
||||
}
|
||||
r, err := raw(out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var read struct {
|
||||
OutOfStep []string `json:"out-of-step"`
|
||||
}
|
||||
if err := json.Unmarshal(r, &read); err != nil {
|
||||
return nil, fmt.Errorf("the compare of %s answered what is not a list: %s", job.Module, r)
|
||||
}
|
||||
answer.OutOfStep = read.OutOfStep
|
||||
}
|
||||
}
|
||||
var (
|
||||
out any
|
||||
@@ -175,10 +197,21 @@ func (s AskSteps) build(ctx context.Context, job delivery.BuildJob) (any, error)
|
||||
if job.Publish {
|
||||
args["publish"] = true
|
||||
}
|
||||
// The seat it is published through and the version the builder gave it (design 51 *Publishing*, CAT-BG2).
|
||||
if a.Seat != "" {
|
||||
args["seat"] = a.Seat
|
||||
}
|
||||
if a.Version != "" {
|
||||
args["version"] = a.Version
|
||||
}
|
||||
Phase(ctx, "build "+a.Artifact)
|
||||
out, err = s.Build(ctx, args)
|
||||
}
|
||||
if err != nil {
|
||||
// The compare's out-of-step is answered with the failure, so the build's end still names it.
|
||||
if len(answer.OutOfStep) > 0 {
|
||||
return answer, fmt.Errorf("%s: %w", a.Artifact, err)
|
||||
}
|
||||
return nil, fmt.Errorf("%s: %w", a.Artifact, err)
|
||||
}
|
||||
r, err := raw(out)
|
||||
|
||||
@@ -70,7 +70,8 @@ func ask(job any) delivery.StepAsk {
|
||||
}
|
||||
|
||||
// 1887/A3: a build ask fetches once, builds each artifact from the workspace with publish, copies a pinned one without a
|
||||
// fetch, and answers each artifact's digest and reference.
|
||||
// fetch, and answers each artifact's digest and reference; an artifact's seat and the version the builder gave it reach
|
||||
// its build (CAT-BG2).
|
||||
func TestRunAskBuilds(t *testing.T) {
|
||||
r := &recorder{fetch: map[string]any{"workspace": "/w/1"}}
|
||||
steps := r.steps()
|
||||
@@ -85,7 +86,7 @@ func TestRunAskBuilds(t *testing.T) {
|
||||
// Issue 1585: the ask's package versions reach the fetch, and the ask's own fetch arguments stay as they were.
|
||||
a := ask(delivery.BuildJob{Module: "m", Path: "modules/m", Publish: true,
|
||||
Fetch: map[string]any{"repository": "novox/x", "commit": runCommit},
|
||||
Artifacts: []delivery.AskArtifact{{Artifact: "base", From: "registry/b@sha256:00"}, {Artifact: "bundle"}, {Artifact: "lib"}}})
|
||||
Artifacts: []delivery.AskArtifact{{Artifact: "base", From: "registry/b@sha256:00"}, {Artifact: "bundle"}, {Artifact: "lib", Seat: "go-package-registry", Version: "v0.1.15"}}})
|
||||
a.Packages = delivery.PackageVersions{"git.novox.be/novox/mesh-sdk/go": runCommit}
|
||||
out, err := RunAsk(context.Background(), steps, a)
|
||||
if err != nil {
|
||||
@@ -98,7 +99,7 @@ func TestRunAskBuilds(t *testing.T) {
|
||||
want := `copy {"artifact":"base","from":"registry/b@sha256:00","module":"m"}
|
||||
fetch {"commit":"` + runCommit + `","packages":{"git.novox.be/novox/mesh-sdk/go":"` + runCommit + `"},"repository":"novox/x"}
|
||||
build {"artifact":"bundle","module":"modules/m","publish":true,"workspace":"/w/1"}
|
||||
build {"artifact":"lib","module":"modules/m","publish":true,"workspace":"/w/1"}
|
||||
build {"artifact":"lib","module":"modules/m","publish":true,"seat":"go-package-registry","version":"v0.1.15","workspace":"/w/1"}
|
||||
imports {"module":"modules/m","workspace":"/w/1"}`
|
||||
if got != want {
|
||||
t.Fatalf("calls:\n%s\nwant:\n%s", got, want)
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
package buildstep
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RegistryWait is how long a push waits for an artifact store that refuses connections, longer than its nightly
|
||||
// collection holds it still (about a minute and a half, issue 457); RegistryFirstPause is the first pause, doubling
|
||||
// to RegistryMostPause. Variables so a test shortens them.
|
||||
var (
|
||||
RegistryWait = 5 * time.Minute
|
||||
RegistryFirstPause = time.Second
|
||||
RegistryMostPause = 10 * time.Second
|
||||
)
|
||||
|
||||
// BlobReference is where a pushed bundle or archive is, as a done key names it and the controller delivers from
|
||||
// (novox/hq ADR 0498 clause 1): artifact-store://<module>/<artifact>/blobs/<digest>, the store's address left out
|
||||
// (issue 102).
|
||||
func BlobReference(module, artifact, digest string) string {
|
||||
return "artifact-store://" + module + "/" + artifact + "/blobs/" + digest
|
||||
}
|
||||
|
||||
// PushBlob puts body into the artifact store at registry (host:port) as a blob of repository (<module>/<artifact>) by
|
||||
// its digest (`sha256:` and hex), from the build module's own process, after the build step ended (novox/hq ADR 0498
|
||||
// clauses 1 and 2): a blob the store already holds is done without an upload; otherwise it is uploaded (POST
|
||||
// blobs/uploads/, then PUT with the digest). A store refusing connections is waited out up to RegistryWait; any other
|
||||
// refusal fails, naming the store's status and its own words, for the caller's `not stored:` error. Bytes that are not
|
||||
// their digest are refused before anything is sent.
|
||||
func PushBlob(ctx context.Context, client *http.Client, registry, repository, digest string, body []byte) error {
|
||||
sum := sha256.Sum256(body)
|
||||
if got := "sha256:" + hex.EncodeToString(sum[:]); got != digest {
|
||||
return fmt.Errorf("the blob is %s, not the digest %s it was to be pushed as", got, digest)
|
||||
}
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
base := "http://" + registry + "/v2/" + repository + "/blobs/"
|
||||
var present bool
|
||||
if err := waitForStore(ctx, registry, func() error {
|
||||
var err error
|
||||
present, err = blobPresent(ctx, client, base+digest)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if present {
|
||||
return nil
|
||||
}
|
||||
var location string
|
||||
if err := waitForStore(ctx, registry, func() error {
|
||||
var err error
|
||||
location, err = startUpload(ctx, client, base+"uploads/")
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
target, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loc, err := target.Parse(location)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the store answered the upload's location %q, which is not a URL: %w", location, err)
|
||||
}
|
||||
q := loc.Query()
|
||||
q.Set("digest", digest)
|
||||
loc.RawQuery = q.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, loc.String(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("putting %s of %s: %w", digest, repository, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
return storeSaid(resp, "putting "+digest+" of "+repository)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func blobPresent(ctx context.Context, client *http.Client, at string) (bool, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodHead, at, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
resp.Body.Close()
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
return true, nil
|
||||
case http.StatusNotFound:
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("asking the store for %s: it answered %s", at, resp.Status)
|
||||
}
|
||||
|
||||
func startUpload(ctx context.Context, client *http.Client, at string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, at, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
return "", storeSaid(resp, "starting an upload at "+at)
|
||||
}
|
||||
location := resp.Header.Get("Location")
|
||||
if location == "" {
|
||||
return "", fmt.Errorf("starting an upload at %s: the store named no location", at)
|
||||
}
|
||||
return location, nil
|
||||
}
|
||||
|
||||
// storeSaid is the store's refusal: its status and the first of its own words.
|
||||
func storeSaid(resp *http.Response, what string) error {
|
||||
words, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
|
||||
return fmt.Errorf("%s: the store answered %s: %s", what, resp.Status, strings.TrimSpace(string(words)))
|
||||
}
|
||||
|
||||
// refused is whether an error is a connection refused.
|
||||
func refused(err error) bool {
|
||||
return err != nil && (errors.Is(err, syscall.ECONNREFUSED) || strings.Contains(err.Error(), "connection refused"))
|
||||
}
|
||||
|
||||
// waitForStore runs try, and while it fails because the store refuses connections, tries again with a growing pause
|
||||
// until RegistryWait has passed. A refusal is the one error waited for: nothing was sent, so trying again does nothing
|
||||
// twice.
|
||||
func waitForStore(ctx context.Context, registry string, try func() error) error {
|
||||
err := try()
|
||||
if !refused(err) {
|
||||
return err
|
||||
}
|
||||
started, pause := time.Now(), RegistryFirstPause
|
||||
for {
|
||||
left := RegistryWait - time.Since(started)
|
||||
if left <= 0 {
|
||||
return fmt.Errorf("the artifact store at %s refused every connection for %s, longer than its nightly collection holds it still, so it is down, not paused: %w",
|
||||
registry, time.Since(started).Round(time.Millisecond), err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("stopped while waiting for the artifact store at %s: %w (last: %v)", registry, ctx.Err(), err)
|
||||
case <-time.After(min(pause, left)):
|
||||
}
|
||||
pause = min(pause*2, RegistryMostPause)
|
||||
if err = try(); !refused(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package buildstep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
func digestOfBytes(b []byte) string {
|
||||
h := sha256.Sum256(b)
|
||||
return "sha256:" + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// registry is an artifact store as far as a blob push needs one: HEAD a blob, start an upload, PUT it with its digest.
|
||||
type registry struct {
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte
|
||||
calls []string
|
||||
put int // the status a PUT answers, 201 when 0
|
||||
}
|
||||
|
||||
func (r *registry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.calls = append(r.calls, req.Method+" "+req.URL.Path)
|
||||
switch {
|
||||
case req.Method == http.MethodHead && strings.Contains(req.URL.Path, "/blobs/sha256:"):
|
||||
if _, ok := r.blobs[req.URL.Path[strings.LastIndex(req.URL.Path, "/")+1:]]; ok {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case req.Method == http.MethodPost && strings.HasSuffix(req.URL.Path, "/blobs/uploads/"):
|
||||
w.Header().Set("Location", strings.TrimSuffix(req.URL.Path, "/")+"/u1?state=x")
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
case req.Method == http.MethodPut && strings.Contains(req.URL.Path, "/blobs/uploads/u1"):
|
||||
if r.put != 0 {
|
||||
w.WriteHeader(r.put)
|
||||
_, _ = io.WriteString(w, `{"errors":[{"code":"DIGEST_INVALID","message":"provided digest did not match uploaded content"}]}`)
|
||||
return
|
||||
}
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
d := req.URL.Query().Get("digest")
|
||||
if req.URL.Query().Get("state") != "x" || d != digestOfBytes(body) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
r.blobs[d] = body
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
// A done build's bundle or archive is pushed to the artifact store by its build module (novox/hq ADR 0498 clauses 1
|
||||
// and 2): a blob the store already holds is done with no upload; one it lacks is uploaded by digest; its reference is
|
||||
// the artifact-store form the builder's key and the controller check.
|
||||
func TestABlobIsPushedOnceByItsDigest(t *testing.T) {
|
||||
reg := ®istry{blobs: map[string][]byte{}}
|
||||
srv := httptest.NewServer(reg)
|
||||
defer srv.Close()
|
||||
addr := strings.TrimPrefix(srv.URL, "http://")
|
||||
body := []byte("the packed bundle")
|
||||
d := digestOfBytes(body)
|
||||
if err := PushBlob(context.Background(), srv.Client(), addr, "mail/code", d, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(reg.blobs[d]) != string(body) {
|
||||
t.Fatalf("the store holds %q", reg.blobs[d])
|
||||
}
|
||||
reg.calls = nil
|
||||
if err := PushBlob(context.Background(), srv.Client(), addr, "mail/code", d, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reg.calls) != 1 || !strings.HasPrefix(reg.calls[0], "HEAD ") {
|
||||
t.Fatalf("a blob the store holds was uploaded again: %v", reg.calls)
|
||||
}
|
||||
ref := BlobReference("mail", "code", d)
|
||||
if ref != "artifact-store://mail/code/blobs/"+d {
|
||||
t.Fatalf("BlobReference = %q", ref)
|
||||
}
|
||||
b := delivery.BuilderBuild{State: delivery.BuildDone, Manifest: strings.Repeat("4", 64),
|
||||
Artifacts: []delivery.BuiltArtifact{{Name: "code", Kind: "bundle", Digest: d, Reference: ref}}}
|
||||
if _, err := delivery.EncodeBuilderBuild(b); err != nil {
|
||||
t.Fatalf("the key refuses the reference BlobReference gives: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A store that refuses the upload fails the push naming the store's own words; bytes that are not the digest are
|
||||
// refused before anything is sent.
|
||||
func TestAPushTheStoreRefusesSaysTheStoresWords(t *testing.T) {
|
||||
reg := ®istry{blobs: map[string][]byte{}, put: http.StatusBadRequest}
|
||||
srv := httptest.NewServer(reg)
|
||||
defer srv.Close()
|
||||
addr := strings.TrimPrefix(srv.URL, "http://")
|
||||
body := []byte("x")
|
||||
err := PushBlob(context.Background(), srv.Client(), addr, "mail/code", digestOfBytes(body), body)
|
||||
if err == nil || !strings.Contains(err.Error(), "provided digest did not match") || !strings.Contains(err.Error(), "400") {
|
||||
t.Fatalf("a refused upload said %v", err)
|
||||
}
|
||||
reg.calls = nil
|
||||
err = PushBlob(context.Background(), srv.Client(), addr, "mail/code", digestOfBytes([]byte("other")), body)
|
||||
if err == nil || len(reg.calls) != 0 {
|
||||
t.Fatalf("bytes that are not their digest: %v, calls %v", err, reg.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// A store refusing connections (its nightly collection holds it still) is waited out, up to RegistryWait (issue 457).
|
||||
func TestAPushWaitsOutAStoreRefusingConnections(t *testing.T) {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := l.Addr().String()
|
||||
l.Close() // refusing now
|
||||
reg := ®istry{blobs: map[string][]byte{}}
|
||||
go func() {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
l2, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = http.Serve(l2, reg)
|
||||
}()
|
||||
beforeWait, beforePause := RegistryWait, RegistryFirstPause
|
||||
RegistryWait, RegistryFirstPause = 3*time.Second, 100*time.Millisecond
|
||||
defer func() { RegistryWait, RegistryFirstPause = beforeWait, beforePause }()
|
||||
body := []byte("late")
|
||||
if err := PushBlob(context.Background(), http.DefaultClient, addr, "mail/code", digestOfBytes(body), body); err != nil {
|
||||
t.Fatalf("a store that came back was not waited for: %v", err)
|
||||
}
|
||||
|
||||
l3, _ := net.Listen("tcp", "127.0.0.1:0")
|
||||
gone := l3.Addr().String()
|
||||
l3.Close()
|
||||
RegistryWait = 300 * time.Millisecond
|
||||
err = PushBlob(context.Background(), http.DefaultClient, gone, "mail/code", digestOfBytes(body), body)
|
||||
if err == nil || !strings.Contains(err.Error(), "refused every connection") {
|
||||
t.Fatalf("a store that stayed down said %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Command seatgen writes, or with -check compares, a contracts module's generated Go and TypeScript.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep/seatgen"
|
||||
)
|
||||
|
||||
func main() {
|
||||
check := flag.Bool("check", false, "compare instead of writing: name every path out of step")
|
||||
goModule := flag.String("go-module", "git.novox.be/novox/mesh-contracts/go", "the generated Go tree's module path")
|
||||
tsPackage := flag.String("ts-package", "@novox/mesh-contracts", "the generated TypeScript package's name")
|
||||
flag.Parse()
|
||||
dir := flag.Arg(0)
|
||||
m, err := seatgen.Load(dir, *goModule, *tsPackage)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
files, err := seatgen.Generate(m)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *check {
|
||||
out, err := seatgen.Compare(dir, files)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// The clients beside the contracts (ADR 0627 §3) and module.json's Go and npm package artifacts (ADR 0625 §1, §3).
|
||||
for _, check := range []func(string, *seatgen.Module) ([]string, error){seatgen.CheckClients, seatgen.CheckArtifacts} {
|
||||
more, err := check(dir, m)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
out = append(out, more...)
|
||||
}
|
||||
for _, p := range out {
|
||||
fmt.Println(p)
|
||||
}
|
||||
if len(out) > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, root := range seatgen.GeneratedRoots {
|
||||
_ = os.RemoveAll(filepath.Join(dir, root, "src"))
|
||||
}
|
||||
// Each seat's npm package's sources too (ADR 0625 §1), so a file no definition writes any more is gone.
|
||||
stale, _ := filepath.Glob(filepath.Join(dir, "ts", "seats", "*", "src"))
|
||||
for _, p := range stale {
|
||||
_ = os.RemoveAll(p)
|
||||
}
|
||||
paths := make([]string, 0, len(files))
|
||||
for p := range files {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
for _, p := range paths {
|
||||
full := filepath.Join(dir, p)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := os.WriteFile(full, files[p], 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
fmt.Println(len(paths), "files")
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package buildstep
|
||||
|
||||
// **Regenerate and compare** (CAT-BG5, CAT-BN2; novox/hq ADR 0608 §5, design 26 *Contracts modules*). A module whose
|
||||
// package artifact names `generated-from` holds contracts only: every file under its generated roots is written by the
|
||||
// seat generator (package seatgen beside this file, command cmd/seatgen) from the definitions in that directory. A build module regenerates them with the generator
|
||||
// it was built with (its version is this package's requirement, so a new generator is a new build module and a new
|
||||
// fingerprint of what it builds) and names each file out of step: one that differs, one missing, one under a generated
|
||||
// root the generator did not write. The test step fails on any; a trunk build's ask answers them in its out-of-step
|
||||
// (delivery.BuildAnswer.OutOfStep), so the builder's build end raises generated-types-out-of-step even where no test
|
||||
// step runs. Each build module compares its own roots: mesh-build-go `go`, mesh-build-node `ts`.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep/seatgen"
|
||||
)
|
||||
|
||||
// GeneratedRootGo and GeneratedRootTS are the generated roots of a contracts module, one per build module.
|
||||
const (
|
||||
GeneratedRootGo = "go"
|
||||
GeneratedRootTS = "ts"
|
||||
)
|
||||
|
||||
var goModuleLine = regexp.MustCompile(`(?m)^module\s+(\S+)`)
|
||||
|
||||
// OutOfStep is every file under root, a path from the module's directory, that the generator writes otherwise than the
|
||||
// module holds it, for each `generated-from` its package artifacts name, sorted and each once; none for a module naming
|
||||
// none. The generated Go tree's module path is read from <from>/go/go.mod and the TypeScript package's name from
|
||||
// <from>/ts/package.json, as the contracts module states them.
|
||||
func OutOfStep(moduleDir, root string) ([]string, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil // no manifest here: nothing names generated-from
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the module's manifest cannot be read for its generated files: %w", err)
|
||||
}
|
||||
var m catalogue.Manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return nil, fmt.Errorf("the module's manifest does not parse: %w", err)
|
||||
}
|
||||
froms := map[string]bool{}
|
||||
if m.Build != nil {
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a.GeneratedFrom != "" {
|
||||
froms[filepath.Clean(a.GeneratedFrom)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for from := range froms {
|
||||
if filepath.IsAbs(from) || from == ".." || strings.HasPrefix(from, "../") {
|
||||
return nil, fmt.Errorf("generated-from %q is not inside the module", from)
|
||||
}
|
||||
dir := filepath.Join(moduleDir, from)
|
||||
goModule, tsPackage, err := generatedNames(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g, err := seatgen.Load(dir, goModule, tsPackage)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the seat definitions in %s do not load: %w", from, err)
|
||||
}
|
||||
files, err := seatgen.Generate(g)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the seat definitions in %s do not generate: %w", from, err)
|
||||
}
|
||||
out, err := seatgen.Compare(dir, files)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, line := range out {
|
||||
p, _, _ := strings.Cut(line, ": ")
|
||||
if p == root || strings.HasPrefix(p, root+"/") {
|
||||
seen[filepath.ToSlash(filepath.Join(from, p))] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
paths := make([]string, 0, len(seen))
|
||||
for p := range seen {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func generatedNames(dir string) (goModule, tsPackage string, err error) {
|
||||
if raw, err := os.ReadFile(filepath.Join(dir, GeneratedRootGo, "go.mod")); err == nil {
|
||||
if m := goModuleLine.FindSubmatch(raw); m != nil {
|
||||
goModule = string(m[1])
|
||||
}
|
||||
}
|
||||
if raw, err := os.ReadFile(filepath.Join(dir, GeneratedRootTS, "package.json")); err == nil {
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if json.Unmarshal(raw, &p) == nil {
|
||||
tsPackage = p.Name
|
||||
}
|
||||
}
|
||||
if goModule == "" || tsPackage == "" {
|
||||
return "", "", errors.New("a contracts module names its generated Go module in go/go.mod and its TypeScript package in ts/package.json; " +
|
||||
filepath.Base(dir) + " names " + map[bool]string{true: "not the TypeScript package", false: "not the Go module"}[goModule != ""])
|
||||
}
|
||||
return goModule, tsPackage, nil
|
||||
}
|
||||
|
||||
// CompareStep is AskSteps.Compare for a build module comparing root: it reads {"workspace", "module"}, the workspace's
|
||||
// tree where tree says it is (the build module's own layout), and answers {"out-of-step": [...]}.
|
||||
func CompareStep(root string, tree func(workspace string) string) StepFunc {
|
||||
return func(_ context.Context, args map[string]any) (any, error) {
|
||||
ws, _ := args["workspace"].(string)
|
||||
mod, _ := args["module"].(string)
|
||||
if ws == "" {
|
||||
return nil, Refuse("the compare names no workspace")
|
||||
}
|
||||
paths, err := OutOfStep(filepath.Join(tree(ws), filepath.FromSlash(mod)), root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"out-of-step": paths}, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package buildstep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep/seatgen"
|
||||
)
|
||||
|
||||
// contracts writes a contracts module of one seat, its generated files as the generator writes them, and answers its
|
||||
// directory and the generated paths.
|
||||
func contracts(t *testing.T, manifest string) (string, []string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
for p, text := range map[string]string{
|
||||
"module.json": manifest,
|
||||
"seats/index.json": `{"format":1,"seats":["one-store"]}`,
|
||||
"seats/one-store/seat.json": `{"format":1,"seat":"one-store","scope":"mesh","grain":"seat-list","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"}}]}`,
|
||||
} {
|
||||
writeContract(t, filepath.Join(dir, p), text)
|
||||
}
|
||||
m, err := seatgen.Load(dir, "example.org/c/go", "@example/c")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, err := seatgen.Generate(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var paths []string
|
||||
for p, b := range files {
|
||||
writeContract(t, filepath.Join(dir, p), string(b))
|
||||
paths = append(paths, p)
|
||||
}
|
||||
// The names the compare reads, where the contracts module states them; a generated go.mod or package.json is kept.
|
||||
if _, ok := files["go/go.mod"]; !ok {
|
||||
writeContract(t, filepath.Join(dir, "go/go.mod"), "module example.org/c/go\n")
|
||||
}
|
||||
if _, ok := files["ts/package.json"]; !ok {
|
||||
writeContract(t, filepath.Join(dir, "ts/package.json"), `{"name":"@example/c"}`)
|
||||
}
|
||||
return dir, paths
|
||||
}
|
||||
|
||||
func writeContract(t *testing.T, path, text string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// **CAT-BG5, CAT-BN2**: a contracts module's generated files are regenerated and compared, each build module its own
|
||||
// root; a file that differs, one missing and one the generator did not write are each named; a clean tree and a module
|
||||
// naming no generated-from name none; a build ask answers them in its out-of-step.
|
||||
func TestAContractsModulesGeneratedFilesAreComparedWithTheGenerator(t *testing.T) {
|
||||
marked := `{"module":"c","build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"],"generated-from":"."}]}}`
|
||||
dir, paths := contracts(t, marked)
|
||||
var goFile, tsFile string
|
||||
for _, p := range paths {
|
||||
if strings.HasPrefix(p, "go/") && strings.HasSuffix(p, ".go") && goFile == "" {
|
||||
goFile = p
|
||||
}
|
||||
if strings.HasPrefix(p, "ts/") && strings.HasSuffix(p, ".ts") && tsFile == "" {
|
||||
tsFile = p
|
||||
}
|
||||
}
|
||||
if goFile == "" || tsFile == "" {
|
||||
t.Fatalf("the generator wrote no Go or no TypeScript file: %v", paths)
|
||||
}
|
||||
for _, root := range []string{GeneratedRootGo, GeneratedRootTS} {
|
||||
if got, err := OutOfStep(dir, root); err != nil || len(got) != 0 {
|
||||
t.Fatalf("a clean tree, root %s: %v %v", root, got, err)
|
||||
}
|
||||
}
|
||||
writeContract(t, filepath.Join(dir, goFile), "package changed\n")
|
||||
writeContract(t, filepath.Join(dir, "go/extra.go"), "package extra\n")
|
||||
writeContract(t, filepath.Join(dir, tsFile), "// changed\n")
|
||||
got, err := OutOfStep(dir, GeneratedRootGo)
|
||||
if want := sorted(goFile, "go/extra.go"); err != nil || !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Go root: %v %v, want %v", got, err, want)
|
||||
}
|
||||
if got, _ := OutOfStep(dir, GeneratedRootTS); !reflect.DeepEqual(got, []string{tsFile}) {
|
||||
t.Errorf("TypeScript root: %v, want %s alone", got, tsFile)
|
||||
}
|
||||
_ = os.Remove(filepath.Join(dir, goFile))
|
||||
if got, _ := OutOfStep(dir, GeneratedRootGo); !reflect.DeepEqual(got, sorted(goFile, "go/extra.go")) {
|
||||
t.Errorf("a missing file is not named: %v", got)
|
||||
}
|
||||
plain, _ := contracts(t, `{"module":"p","build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"]}]}}`)
|
||||
writeContract(t, filepath.Join(plain, "go/extra.go"), "package extra\n")
|
||||
if got, err := OutOfStep(plain, GeneratedRootGo); err != nil || len(got) != 0 {
|
||||
t.Errorf("a module naming no generated-from compared: %v %v", got, err)
|
||||
}
|
||||
|
||||
// The build ask answers them beside what it built, and with a failed build too.
|
||||
built := 0
|
||||
steps := AskSteps{Compare: CompareStep(GeneratedRootGo, func(ws string) string { return ws }),
|
||||
Fetch: func(context.Context, map[string]any) (any, error) {
|
||||
return map[string]any{"workspace": filepath.Dir(dir)}, nil
|
||||
},
|
||||
Build: func(context.Context, map[string]any) (any, error) {
|
||||
if built++; built > 1 {
|
||||
return nil, errors.New("the second artifact does not build")
|
||||
}
|
||||
return map[string]any{"digest": "sha256:aa"}, nil
|
||||
}}
|
||||
job := delivery.BuildJob{Module: "c", Path: filepath.Base(dir), Fetch: map[string]any{"repository": "novox/c"},
|
||||
Artifacts: []delivery.AskArtifact{{Artifact: "go"}}}
|
||||
out, err := RunAsk(context.Background(), steps, ask(job))
|
||||
if a, ok := out.(delivery.BuildAnswer); err != nil || !ok || !reflect.DeepEqual(a.OutOfStep, sorted(goFile, "go/extra.go")) || len(a.Artifacts) != 1 {
|
||||
t.Errorf("the build ask's out-of-step: %+v %v", out, err)
|
||||
}
|
||||
job.Artifacts = append(job.Artifacts, delivery.AskArtifact{Artifact: "go-other"})
|
||||
built = 0
|
||||
out, err = RunAsk(context.Background(), steps, ask(job))
|
||||
if a, ok := out.(delivery.BuildAnswer); err == nil || !ok || len(a.OutOfStep) != 2 {
|
||||
t.Errorf("a failed build answered no out-of-step: %+v %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func sorted(paths ...string) []string {
|
||||
sort.Strings(paths)
|
||||
return paths
|
||||
}
|
||||
@@ -8,6 +8,14 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/gopackageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/npmpackageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package buildstep
|
||||
|
||||
// **The late publish** (novox/hq ADR 0617 §1, design 51 *The versions*, *Publishing*; CAT-BG2, CAT-BI1): a trunk build
|
||||
// whose number the builder did not know yet publishes its digest unnumbered; the builder says version.numbered once it
|
||||
// numbers that fingerprint, and the build module publishes the held digest again under that version. Nothing travels:
|
||||
// the publish names the one part by its digest, which the holder holds, so it answers held and tags the version (the
|
||||
// holder asks builder_versions first, ADR 0605 §4). The bytes never stayed on the node, so a holder that no longer holds
|
||||
// the digest is said and the event offered again. Every instance may hear the same event; the publish is the same call
|
||||
// under the same transfer name, so a second one is answered held. One place for every build module: mesh-build-go's
|
||||
// bundles and archives on oci-artifact-registry, mesh-build-image's images on container-image-registry.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
reg "git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
"git.novox.be/novox/mesh-sdk/go/parts"
|
||||
)
|
||||
|
||||
// NumberedPattern is the event type a build module consumes for the late publish, as its manifest's `consumes` names it.
|
||||
const NumberedPattern = delivery.BuilderModule + "." + delivery.VersionNumberedEvent
|
||||
|
||||
// errNotHere is a held part's Open: its bytes did not stay on the node.
|
||||
var errNotHere = errors.New("the built bytes did not stay on the node; the holder must hold the digest")
|
||||
|
||||
// LatePublish publishes a numbered build's held digest under its version on seat, from the builder's version.numbered
|
||||
// body, when its kind is one of kinds. It answers false, nil for an event that is not the module's to publish: another
|
||||
// kind, another seat (an event naming none is the artifact seat's, as the builder wrote it before images), or a version
|
||||
// numbered with no digest.
|
||||
func LatePublish(ctx context.Context, call SeatCall, body []byte, seat string, kinds ...string) (bool, error) {
|
||||
n, err := delivery.DecodeVersionNumbered(body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
on := n.Seat
|
||||
if on == "" {
|
||||
on = ArtifactSeat
|
||||
}
|
||||
if n.Digest == "" || on != seat || !slices.Contains(kinds, n.Kind) {
|
||||
return false, nil
|
||||
}
|
||||
in := reg.PublishInput{Name: n.Name, Kind: n.Kind, Version: n.Version, Tag: n.Tag, Digest: n.Digest,
|
||||
Fingerprint: n.Fingerprint, Commit: n.Commit, Transfer: TransferName(n.Name, "v"+n.Version, n.Digest)}
|
||||
sent, err := OnSeat(ctx, seat, "late publish of "+n.Name+" "+n.Version+" at "+n.Digest, func() (parts.Sent, error) {
|
||||
return PublishParts(ctx, call, seat, in, []parts.Part{{Digest: n.Digest,
|
||||
Open: func() (io.ReadCloser, error) { return nil, errNotHere }}})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("the late publish of %s@%s (%s): %w", n.Name, n.Version, n.Digest, err)
|
||||
}
|
||||
if len(sent.Parts) > 0 {
|
||||
return false, fmt.Errorf("the late publish of %s@%s sent parts it should not have", n.Name, n.Version)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// HearNumbered subscribes late to the builder's version.numbered, asking again until the runtime takes it, and says
|
||||
// each publish and each failure; an error is the event's, which is offered again.
|
||||
func HearNumbered(ctx context.Context, late func(ctx context.Context, body []byte) (bool, error)) {
|
||||
handle := func(e stdio.Envelope) error {
|
||||
did, err := late(ctx, e.Body)
|
||||
if err != nil {
|
||||
log.Printf("%v", err)
|
||||
return err
|
||||
}
|
||||
if did {
|
||||
log.Printf("published a numbered build's held digest under its version (%s)", e.Headers["x-event-id"])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
|
||||
err := stdio.Subscribe(NumberedPattern, handle)
|
||||
if err == nil {
|
||||
log.Printf("listening for the builder's %s", NumberedPattern)
|
||||
return
|
||||
}
|
||||
log.Printf("not hearing the builder's %s yet (%v); asking again in %s", NumberedPattern, err, wait)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(wait):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package buildstep
|
||||
|
||||
// **A build narrates its asks of a seat** (CAT-NR1; design 51 *Publishing*): asked, waiting on the seat (said again every
|
||||
// NarrateEvery while it waits), stored, refused. Each line is the ask's phase (phase.go): logged with the ask's id and
|
||||
// written to its running step key, so the builder and the delivery view read from the bus where a publish or a copy
|
||||
// stands; outside an ask's run (a late publish, a tool called by hand) it is logged. One place for every build module:
|
||||
// PublishOne and PublishFiles narrate through it, and a step that waits on a seat's event (an image's copy) uses
|
||||
// NarrateSeat itself.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NarrateEvery is how often a build says again that it still waits on a seat.
|
||||
var NarrateEvery = 5 * time.Minute
|
||||
|
||||
// narrateTicks is the clock of the waiting lines; a test hands its own.
|
||||
var narrateTicks = func(every time.Duration) (<-chan time.Time, func()) {
|
||||
t := time.NewTicker(every)
|
||||
return t.C, t.Stop
|
||||
}
|
||||
|
||||
// SeatNarration is one ask of a build on a seat, said as it moves.
|
||||
type SeatNarration struct {
|
||||
ctx context.Context
|
||||
seat, what string
|
||||
asked time.Time
|
||||
tick <-chan time.Time
|
||||
stop func()
|
||||
}
|
||||
|
||||
// NarrateSeat says that the build asked seat for what (a verb and its object, such as "publish of nats/server") and
|
||||
// starts the waiting lines; Stored or Refused ends it.
|
||||
func NarrateSeat(ctx context.Context, seat, what string) *SeatNarration {
|
||||
n := &SeatNarration{ctx: ctx, seat: seat, what: what, asked: now()}
|
||||
n.tick, n.stop = narrateTicks(NarrateEvery)
|
||||
n.say("asked %s: %s", seat, what)
|
||||
return n
|
||||
}
|
||||
|
||||
// Waiting is the clock a waiting step selects on beside its outcome; on each tick it calls StillWaiting.
|
||||
func (n *SeatNarration) Waiting() <-chan time.Time { return n.tick }
|
||||
|
||||
// StillWaiting says that the build still waits on the seat, and since when.
|
||||
func (n *SeatNarration) StillWaiting() {
|
||||
n.say("waiting on %s: %s, %s since asked", n.seat, n.what, now().Sub(n.asked).Round(time.Second))
|
||||
}
|
||||
|
||||
// Stored says that the seat holds what the build asked it to keep (how: where, or what travelled).
|
||||
func (n *SeatNarration) Stored(how string) {
|
||||
n.stop()
|
||||
if how != "" {
|
||||
how = " (" + how + ")"
|
||||
}
|
||||
n.say("stored on %s: %s%s", n.seat, n.what, how)
|
||||
}
|
||||
|
||||
// Refused says that the seat did not keep it, and why.
|
||||
func (n *SeatNarration) Refused(err error) {
|
||||
n.stop()
|
||||
n.say("refused by %s: %s: %v", n.seat, n.what, err)
|
||||
}
|
||||
|
||||
func (n *SeatNarration) say(format string, a ...any) {
|
||||
line := fmt.Sprintf(format, a...)
|
||||
if r, ok := n.ctx.Value(phaseKey{}).(*phases); ok && r != nil {
|
||||
r.enter(line)
|
||||
return
|
||||
}
|
||||
log.Print(line)
|
||||
}
|
||||
|
||||
// OnSeat runs call as one narrated ask of the build on seat: asked, waiting every NarrateEvery while call runs, then
|
||||
// stored (how(answer)) or refused (its error).
|
||||
func OnSeat[T any](ctx context.Context, seat, what string, call func() (T, error), how func(T) string) (T, error) {
|
||||
n := NarrateSeat(ctx, seat, what)
|
||||
type answer struct {
|
||||
v T
|
||||
err error
|
||||
}
|
||||
done := make(chan answer, 1)
|
||||
go func() {
|
||||
v, err := call()
|
||||
done <- answer{v, err}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case a := <-done:
|
||||
if a.err != nil {
|
||||
n.Refused(a.err)
|
||||
} else {
|
||||
h := ""
|
||||
if how != nil {
|
||||
h = how(a.v)
|
||||
}
|
||||
n.Stored(h)
|
||||
}
|
||||
return a.v, a.err
|
||||
case <-n.Waiting():
|
||||
n.StillWaiting()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package buildstep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
reg "git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
// CAT-NR1: a build's publish on a seat says asked, waiting on the seat (on every tick of NarrateEvery while the holder
|
||||
// has not answered), and stored or refused, each as the ask's phase written to its running step key.
|
||||
func TestABuildNarratesItsPublishOnASeat(t *testing.T) {
|
||||
digest := "sha256:" + strings.Repeat("c", 64)
|
||||
for name, c := range map[string]struct {
|
||||
answer error
|
||||
ticks int
|
||||
want []string
|
||||
}{
|
||||
"stored": {want: []string{
|
||||
"asked go-package-registry: publish of mod 1.2.3 at " + digest,
|
||||
"stored on go-package-registry: publish of mod 1.2.3 at " + digest + " (0 of its 1 parts sent, the rest held)"}},
|
||||
"refused": {answer: errors.New("the holder is down"), want: []string{
|
||||
"asked go-package-registry: publish of mod 1.2.3 at " + digest,
|
||||
"refused by go-package-registry: publish of mod 1.2.3 at " + digest + ": go-package-registry's publish of mod: the holder is down"}},
|
||||
"waiting twice, then stored": {ticks: 2, want: []string{
|
||||
"asked go-package-registry: publish of mod 1.2.3 at " + digest,
|
||||
"waiting on go-package-registry: publish of mod 1.2.3 at " + digest + ", 5m0s since asked",
|
||||
"waiting on go-package-registry: publish of mod 1.2.3 at " + digest + ", 10m0s since asked",
|
||||
"stored on go-package-registry: publish of mod 1.2.3 at " + digest + " (0 of its 1 parts sent, the rest held)"}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
clock := time.Date(2026, 11, 4, 16, 0, 0, 0, time.UTC)
|
||||
var mu sync.Mutex
|
||||
oldNow, oldTicks := now, narrateTicks
|
||||
now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock }
|
||||
tick := make(chan time.Time)
|
||||
stopped := make(chan struct{})
|
||||
narrateTicks = func(every time.Duration) (<-chan time.Time, func()) {
|
||||
if every != 5*time.Minute {
|
||||
t.Errorf("the waiting lines come every %s, want 5m", every)
|
||||
}
|
||||
return tick, func() { close(stopped) }
|
||||
}
|
||||
t.Cleanup(func() { now, narrateTicks = oldNow, oldTicks })
|
||||
|
||||
var said []string
|
||||
wrote := make(chan struct{}, 16)
|
||||
step := delivery.Step{ID: "a1", Tool: "build", Node: "ace", State: delivery.StepRunning, Started: clock}
|
||||
ph := &phases{key: "ace.a1", step: step, put: func(key string, value any) (uint64, error) {
|
||||
var s delivery.Step
|
||||
_ = json.Unmarshal(value.(json.RawMessage), &s)
|
||||
phasesMu.Lock()
|
||||
said = append(said, s.Phase)
|
||||
phasesMu.Unlock()
|
||||
wrote <- struct{}{}
|
||||
return 1, nil
|
||||
}}
|
||||
release := make(chan struct{})
|
||||
call := func(key string, body any) (json.RawMessage, error) {
|
||||
<-release
|
||||
if c.answer != nil {
|
||||
return nil, c.answer
|
||||
}
|
||||
return json.Marshal(reg.PublishAnswer{Held: true, Transfer: "t"})
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), phaseKey{}, ph)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- PublishOne(ctx, call, GoSeat, "mod", "package", "1.2.3", digest, "t", []byte("x")) }()
|
||||
line := func() {
|
||||
select {
|
||||
case <-wrote:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the publish said no line")
|
||||
}
|
||||
}
|
||||
line() // asked, at the clock's start
|
||||
for i := 0; i < c.ticks; i++ {
|
||||
mu.Lock()
|
||||
clock = clock.Add(5 * time.Minute)
|
||||
mu.Unlock()
|
||||
tick <- clock
|
||||
line() // its waiting line
|
||||
}
|
||||
close(release)
|
||||
err := <-done
|
||||
if (err != nil) != (c.answer != nil) {
|
||||
t.Fatalf("PublishOne = %v", err)
|
||||
}
|
||||
<-stopped
|
||||
phasesMu.Lock()
|
||||
defer phasesMu.Unlock()
|
||||
// Each line is the step's phase, written to its key, in order.
|
||||
if fmt.Sprint(said) != fmt.Sprint(c.want) {
|
||||
t.Errorf("phases =\n%s\nwant\n%s", strings.Join(said, "\n"), strings.Join(c.want, "\n"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var phasesMu sync.Mutex
|
||||
@@ -0,0 +1,116 @@
|
||||
package buildstep
|
||||
|
||||
// The publish of a done build's file through a registry seat (novox/hq design 51 *Publishing*, ADR 0611; CAT-BG1,
|
||||
// CAT-BN3): from the build module's own process, after the build step ended, through the seat's verbs publish and
|
||||
// publish-part, which each build module's manifest `invokes`, in chunks, only what the holder lacks. The holder checks
|
||||
// the build with the builder and says published or refused on the seat's events. One place for every build module: it
|
||||
// binds each seat to its client in mesh-contracts (ADR 0627 §1), over mesh-sdk's seat-neutral sender of parts (§2).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
imageclient "git.novox.be/novox/mesh-contracts/go/clients/containerimageregistryclient"
|
||||
goclient "git.novox.be/novox/mesh-contracts/go/clients/gopackageregistryclient"
|
||||
npmclient "git.novox.be/novox/mesh-contracts/go/clients/npmpackageregistryclient"
|
||||
ociclient "git.novox.be/novox/mesh-contracts/go/clients/ociartifactregistryclient"
|
||||
reg "git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry"
|
||||
goseat "git.novox.be/novox/mesh-contracts/go/seats/gopackageregistry"
|
||||
npmseat "git.novox.be/novox/mesh-contracts/go/seats/npmpackageregistry"
|
||||
ociseat "git.novox.be/novox/mesh-contracts/go/seats/ociartifactregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/parts"
|
||||
)
|
||||
|
||||
// The registry seats a build module publishes on.
|
||||
const (
|
||||
ArtifactSeat = ociseat.Seat
|
||||
ImageSeat = reg.Seat
|
||||
GoSeat = goseat.Seat
|
||||
NpmSeat = npmseat.Seat
|
||||
)
|
||||
|
||||
// SeatCall asks one verb of a seat, `seat:<seat>.<verb>`, with a body, and answers its JSON (the bundle's stdio.Ask).
|
||||
type SeatCall = func(key string, body any) (json.RawMessage, error)
|
||||
|
||||
// TransferName is a transfer's name, the build module's own: the name, a qualifier and the digest's head, safe as a
|
||||
// transfer id.
|
||||
func TransferName(name, qualifier, digest string) string {
|
||||
head := strings.TrimPrefix(digest, "sha256:")
|
||||
if len(head) > 16 {
|
||||
head = head[:16]
|
||||
}
|
||||
return strings.NewReplacer("/", "-", ".", "-", " ", "-", "*", "-", ">", "-", "@", "-").Replace(name + "-" + qualifier + "-" + head)
|
||||
}
|
||||
|
||||
// PublishOne publishes body, of digest, as name (at version, when it has one) of kind on seat, in one part.
|
||||
func PublishOne(ctx context.Context, call SeatCall, seat, name, kind, version, digest, transfer string, body []byte) error {
|
||||
in := reg.PublishInput{Name: name, Kind: kind, Version: version, Digest: digest, Transfer: transfer}
|
||||
_, err := OnSeat(ctx, seat, publishWhat(in), func() (parts.Sent, error) {
|
||||
return PublishParts(ctx, call, seat, in, []parts.Part{{Digest: digest, Size: int64(len(body)),
|
||||
Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil }}})
|
||||
}, SentHow(1))
|
||||
return err
|
||||
}
|
||||
|
||||
// publishWhat names a publish in a narration: its name, its version when it has one, and its digest.
|
||||
func publishWhat(in reg.PublishInput) string {
|
||||
what := "publish of " + in.Name
|
||||
if in.Version != "" {
|
||||
what += " " + in.Version
|
||||
}
|
||||
return what + " at " + in.Digest
|
||||
}
|
||||
|
||||
// SentHow says what of a publish of parts travelled, for its stored line.
|
||||
func SentHow(n int) func(parts.Sent) string {
|
||||
return func(s parts.Sent) string {
|
||||
return fmt.Sprintf("%d of its %d parts sent, the rest held", len(s.Parts), n)
|
||||
}
|
||||
}
|
||||
|
||||
// PublishParts publishes in with ps as its parts on seat, through that seat's client: in's fields are the seat's own
|
||||
// (the four registry seats share the publish verb's input, design 51), the parts are written by the client.
|
||||
func PublishParts(ctx context.Context, call SeatCall, seat string, in reg.PublishInput, ps []parts.Part) (parts.Sent, error) {
|
||||
switch seat {
|
||||
case ImageSeat:
|
||||
s, err := imageclient.Publish(ctx, imageclient.Call(call), in, ps)
|
||||
return s.Sent, err
|
||||
case ArtifactSeat:
|
||||
s, err := ociclient.Publish(ctx, ociclient.Call(call), ociseat.PublishInput{Name: in.Name, Kind: in.Kind, Version: in.Version,
|
||||
Tag: in.Tag, Digest: in.Digest, Fingerprint: in.Fingerprint, Commit: in.Commit, Transfer: in.Transfer}, ps)
|
||||
return s.Sent, err
|
||||
case GoSeat:
|
||||
s, err := goclient.Publish(ctx, goclient.Call(call), goseat.PublishInput{Name: in.Name, Kind: in.Kind, Version: in.Version,
|
||||
Tag: in.Tag, Digest: in.Digest, Fingerprint: in.Fingerprint, Commit: in.Commit, Transfer: in.Transfer}, ps)
|
||||
return s.Sent, err
|
||||
case NpmSeat:
|
||||
s, err := npmclient.Publish(ctx, npmclient.Call(call), npmseat.PublishInput{Name: in.Name, Kind: in.Kind, Version: in.Version,
|
||||
Tag: in.Tag, Digest: in.Digest, Fingerprint: in.Fingerprint, Commit: in.Commit, Transfer: in.Transfer}, ps)
|
||||
return s.Sent, err
|
||||
}
|
||||
return parts.Sent{}, fmt.Errorf("%s is no registry seat a build publishes on", seat)
|
||||
}
|
||||
|
||||
// File is one part of a publish kept on disk: an image's config, layer or manifest, by its digest and size.
|
||||
type File struct {
|
||||
Digest string
|
||||
Size int64
|
||||
Path string
|
||||
}
|
||||
|
||||
// PublishFiles publishes in with files as its parts (an image's config, layers and manifest, CAT-BI1): the holder
|
||||
// answers the parts it lacks, and only those are read and sent.
|
||||
func PublishFiles(ctx context.Context, call SeatCall, seat string, in reg.PublishInput, files []File) (parts.Sent, error) {
|
||||
ps := make([]parts.Part, 0, len(files))
|
||||
for _, f := range files {
|
||||
ps = append(ps, parts.Part{Digest: f.Digest, Size: f.Size, Open: func() (io.ReadCloser, error) { return os.Open(f.Path) }})
|
||||
}
|
||||
return OnSeat(ctx, seat, publishWhat(in), func() (parts.Sent, error) {
|
||||
return PublishParts(ctx, call, seat, in, ps)
|
||||
}, SentHow(len(files)))
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
re "regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
// ClientRoot is where a seat's hand-written client packages live (ADR 0625 §4, §5; ADR 0627): one directory per
|
||||
// client, `go/clients/<seat without hyphens>client`, a Go module of its own (ADR 0625 §3), so the seat set's importers
|
||||
// never import a client and a client's import of mesh-sdk forms no cycle. Compare leaves the tree to CheckClients.
|
||||
const ClientRoot = "go/clients"
|
||||
|
||||
// RuntimeModule is mesh-sdk's Go module: the one module beside its own seat's contract a client may import (ADR 0625
|
||||
// §3, §4).
|
||||
const RuntimeModule = "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
// ClientGoModule is the Go module of a seat's client, beside its contract's.
|
||||
func ClientGoModule(root, seat string) string { return root + "/clients/" + pkgName(seat) + "client" }
|
||||
|
||||
// a module's tool address (`<module>.<tool_name>`) or call (`<module>.<tool>` written with an underscore).
|
||||
var toolAddress = re.MustCompile(`^[a-z][a-z0-9-]*\.[a-z0-9]+_[a-z0-9_]+$`)
|
||||
|
||||
// CheckClients is ADR 0627 §3's catalog check of the clients, and ADR 0625 §5's rule for the files beside them: every
|
||||
// directory under ClientRoot is the client of one seat defined whole, a Go module of its own at ClientGoModule; it
|
||||
// imports only the standard library, its own seat's contract module and mesh-sdk's runtime (never another seat's
|
||||
// contract or client); and no string in it names a module's subject (`mesh.mod.`), a module's tool, or another seat
|
||||
// (its name, its subjects, its `seat:` call). Each problem is named once, sorted.
|
||||
func CheckClients(dir string, m *Module) ([]string, error) {
|
||||
var out []string
|
||||
entries, err := os.ReadDir(filepath.Join(dir, ClientRoot))
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bySeatPkg := map[string]string{}
|
||||
for name, d := range m.Seats {
|
||||
if d.Grain == seatdef.Whole {
|
||||
bySeatPkg[pkgName(name)+"client"] = name
|
||||
}
|
||||
}
|
||||
for _, e := range entries {
|
||||
at := ClientRoot + "/" + e.Name()
|
||||
if !e.IsDir() {
|
||||
out = append(out, at+": a file under the clients' root, in no client")
|
||||
continue
|
||||
}
|
||||
seat, ok := bySeatPkg[e.Name()]
|
||||
if !ok {
|
||||
out = append(out, at+": the client of no seat defined whole (a client is `<seat without hyphens>client`)")
|
||||
continue
|
||||
}
|
||||
mod, err := os.ReadFile(filepath.Join(dir, at, "go.mod"))
|
||||
want := "module " + ClientGoModule(m.GoModule, seat)
|
||||
if err != nil || strings.SplitN(string(mod), "\n", 2)[0] != want {
|
||||
out = append(out, at+"/go.mod: not "+strconv.Quote(want)+": a client is a Go module of its own (ADR 0625 §3)")
|
||||
}
|
||||
problems, err := checkClient(dir, at, seat, m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, problems...)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func checkClient(dir, at, seat string, m *Module) ([]string, error) {
|
||||
var out []string
|
||||
own := SeatGoModule(m.GoModule, seat)
|
||||
others := map[string]bool{}
|
||||
for name := range m.Seats {
|
||||
if name != seat {
|
||||
others[name] = true
|
||||
}
|
||||
}
|
||||
namesOther := func(s string) bool {
|
||||
if others[s] {
|
||||
return true
|
||||
}
|
||||
for name := range others {
|
||||
if strings.HasPrefix(s, "mesh.seat."+name+".") || strings.HasPrefix(s, "seat:"+name+".") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
err := filepath.WalkDir(filepath.Join(dir, at), func(p string, e os.DirEntry, err error) error {
|
||||
if err != nil || e.IsDir() || !strings.HasSuffix(p, ".go") {
|
||||
return err
|
||||
}
|
||||
r := rel(dir, p)
|
||||
f, err := parser.ParseFile(token.NewFileSet(), p, nil, parser.SkipObjectResolution)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, im := range f.Imports {
|
||||
path, _ := strconv.Unquote(im.Path.Value)
|
||||
switch {
|
||||
case !strings.Contains(strings.SplitN(path, "/", 2)[0], "."):
|
||||
case path == own:
|
||||
case path == RuntimeModule || strings.HasPrefix(path, RuntimeModule+"/"):
|
||||
case strings.HasPrefix(path, m.GoModule+"/clients/"):
|
||||
out = append(out, r+": imports "+path+", another seat's client (ADR 0625 §4)")
|
||||
case path == m.GoModule || strings.HasPrefix(path, m.GoModule+"/"):
|
||||
out = append(out, r+": imports "+path+", not its own seat's contract (ADR 0625 §4)")
|
||||
default:
|
||||
out = append(out, r+": imports "+path+": a client uses only its seat's contract and mesh-sdk's runtime (ADR 0625 §3)")
|
||||
}
|
||||
}
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
v, err := strconv.Unquote(lit.Value)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(v, "mesh.mod."):
|
||||
out = append(out, fmt.Sprintf("%s: names a module's subject %q (ADR 0625 §4)", r, v))
|
||||
case toolAddress.MatchString(v):
|
||||
out = append(out, fmt.Sprintf("%s: names a module's tool %q (ADR 0625 §4)", r, v))
|
||||
case namesOther(v):
|
||||
out = append(out, fmt.Sprintf("%s: names another seat %q (ADR 0625 §4)", r, v))
|
||||
}
|
||||
return true
|
||||
})
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// TSSetArtifact is the seat set's npm package artifact, at ts/.
|
||||
const TSSetArtifact = "lib"
|
||||
|
||||
// CheckArtifacts is the check of module.json's package artifacts against the tree (ADR 0625 §1, §3), per language.
|
||||
// Go: the root module is the artifact `go` at `go`, each seat defined whole the artifact `go-<seat without hyphens>`
|
||||
// at its module's directory, each client present the artifact `go-<seat without hyphens>client` at its directory.
|
||||
// npm: the seat set's package is the artifact `lib` at `ts`, each seat defined whole the artifact
|
||||
// `ts-<seat without hyphens>` at TSSeatDir. No other package artifact of either language. Each problem is named once,
|
||||
// sorted.
|
||||
func CheckArtifacts(dir string, m *Module) ([]string, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "module.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var mf struct {
|
||||
Build struct {
|
||||
Artifacts []struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Language string `json:"language"`
|
||||
Paths []string `json:"paths"`
|
||||
} `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &mf); err != nil {
|
||||
return nil, fmt.Errorf("module.json: %w", err)
|
||||
}
|
||||
want := map[string]map[string]string{
|
||||
"go": {"go": "go"},
|
||||
"typescript": {TSSetArtifact: "ts"},
|
||||
}
|
||||
for name, d := range m.Seats {
|
||||
if d.Grain == seatdef.Whole {
|
||||
want["go"]["go-"+pkgName(name)] = "go/seats/" + pkgName(name)
|
||||
want["typescript"]["ts-"+pkgName(name)] = TSSeatDir(name)
|
||||
}
|
||||
}
|
||||
if entries, err := os.ReadDir(filepath.Join(dir, ClientRoot)); err == nil {
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
want["go"]["go-"+e.Name()] = ClientRoot + "/" + e.Name()
|
||||
}
|
||||
}
|
||||
}
|
||||
said := map[string]string{"go": "Go", "typescript": "npm"}
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, a := range mf.Build.Artifacts {
|
||||
paths, lang := want[a.Language]
|
||||
if a.Kind != "package" || !lang {
|
||||
continue
|
||||
}
|
||||
seen[a.Language+"/"+a.Name] = true
|
||||
path, ok := paths[a.Name]
|
||||
switch {
|
||||
case !ok:
|
||||
out = append(out, "module.json: the "+said[a.Language]+" package artifact "+a.Name+" is no seat's module, no client's and not the seat set's")
|
||||
case len(a.Paths) != 1 || a.Paths[0] != path:
|
||||
out = append(out, fmt.Sprintf("module.json: the artifact %s's paths are %v, not [%s]", a.Name, a.Paths, path))
|
||||
}
|
||||
}
|
||||
for lang, paths := range want {
|
||||
for name, path := range paths {
|
||||
if !seen[lang+"/"+name] {
|
||||
out = append(out, "module.json: no "+said[lang]+" package artifact "+name+" for "+path)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ADR 0627 §3's catalog check of a client, ADR 0625 §5's rule for what is hand-written, and module.json's Go package
|
||||
// artifacts against the tree (ADR 0625 §1, §3): each row writes one tree and names what the checks must say of it.
|
||||
func TestAClientUsesOnlyItsSeatAndTheRuntime(t *testing.T) {
|
||||
m, err := Load("testdata/contracts", "example.org/contracts/go", "@example/contracts")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, err := Generate(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const good = `package aregistryclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"example.org/contracts/go/seats/aregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/parts"
|
||||
)
|
||||
|
||||
func Publish(ctx context.Context) string { _ = parts.MaxChunk; return "seat:" + aregistry.Seat + ".publish" }
|
||||
`
|
||||
const ts = `,{"name":"lib","kind":"package","language":"typescript","paths":["ts"]},
|
||||
{"name":"ts-aregistry","kind":"package","language":"typescript","paths":["ts/seats/aregistry"]},
|
||||
{"name":"ts-bregistry","kind":"package","language":"typescript","paths":["ts/seats/bregistry"]}`
|
||||
artifacts := func(extra string) string {
|
||||
return `{"build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"]},
|
||||
{"name":"go-aregistry","kind":"package","language":"go","paths":["go/seats/aregistry"]},
|
||||
{"name":"go-bregistry","kind":"package","language":"go","paths":["go/seats/bregistry"]}` + ts + extra + `]}}`
|
||||
}
|
||||
clientArtifact := `,{"name":"go-aregistryclient","kind":"package","language":"go","paths":["go/clients/aregistryclient"]}`
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
tree map[string]string
|
||||
module string
|
||||
want []string
|
||||
}{
|
||||
{"no client: the seats alone", nil, artifacts(""), nil},
|
||||
{"a client of its own seat over the runtime", map[string]string{
|
||||
"go/clients/aregistryclient/go.mod": "module example.org/contracts/go/clients/aregistryclient\n",
|
||||
"go/clients/aregistryclient/client.go": good,
|
||||
}, artifacts(clientArtifact), nil},
|
||||
{"a client with no artifact, and an artifact of no module", map[string]string{
|
||||
"go/clients/aregistryclient/go.mod": "module example.org/contracts/go/clients/aregistryclient\n",
|
||||
"go/clients/aregistryclient/client.go": good,
|
||||
}, artifacts(`,{"name":"go-extra","kind":"package","language":"go","paths":["go/extra"]}`),
|
||||
[]string{"module.json: no Go package artifact go-aregistryclient", "module.json: the Go package artifact go-extra is no seat's"}},
|
||||
{"a seat's npm package with no artifact, one at another path, and one of no package", nil,
|
||||
`{"build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"]},
|
||||
{"name":"go-aregistry","kind":"package","language":"go","paths":["go/seats/aregistry"]},
|
||||
{"name":"go-bregistry","kind":"package","language":"go","paths":["go/seats/bregistry"]},
|
||||
{"name":"lib","kind":"package","language":"typescript","paths":["ts"]},
|
||||
{"name":"ts-aregistry","kind":"package","language":"typescript","paths":["ts"]},
|
||||
{"name":"ts-onestore","kind":"package","language":"typescript","paths":["ts/seats/onestore"]}]}}`,
|
||||
[]string{"module.json: no npm package artifact ts-bregistry", "module.json: the artifact ts-aregistry's paths are [ts], not [ts/seats/aregistry]",
|
||||
"module.json: the npm package artifact ts-onestore is no seat's"}},
|
||||
{"a client of no seat defined whole, and one not a module of its own", map[string]string{
|
||||
"go/clients/onestoreclient/x.go": "package onestoreclient\n",
|
||||
"go/clients/aregistryclient/go.mod": "module example.org/contracts/go\n",
|
||||
}, artifacts(clientArtifact + `,{"name":"go-onestoreclient","kind":"package","language":"go","paths":["go/clients/onestoreclient"]}`),
|
||||
[]string{"go/clients/aregistryclient/go.mod: not", "go/clients/onestoreclient: the client of no seat defined whole"}},
|
||||
{"a client using another seat, its client, a module's subject and tool", map[string]string{
|
||||
"go/clients/aregistryclient/go.mod": "module example.org/contracts/go/clients/aregistryclient\n",
|
||||
"go/clients/aregistryclient/client.go": `package aregistryclient
|
||||
|
||||
import (
|
||||
"example.org/contracts/go/seats/bregistry"
|
||||
"example.org/contracts/go/clients/bregistryclient"
|
||||
"github.com/some/thing"
|
||||
)
|
||||
|
||||
var a, b, c, d, e = bregistry.Seat, bregistryclient.X, thing.Y, "mesh.mod.holder.event.x", "seat:b-registry.publish"
|
||||
var f = "records.records_search"
|
||||
`,
|
||||
}, artifacts(clientArtifact), []string{
|
||||
`client.go: imports example.org/contracts/go/clients/bregistryclient, another seat's client`,
|
||||
`client.go: imports example.org/contracts/go/seats/bregistry, not its own seat's contract`,
|
||||
`client.go: imports github.com/some/thing: a client uses only`,
|
||||
`client.go: names a module's subject "mesh.mod.holder.event.x"`,
|
||||
`client.go: names a module's tool "records.records_search"`,
|
||||
`client.go: names another seat "seat:b-registry.publish"`,
|
||||
}},
|
||||
} {
|
||||
dir := t.TempDir()
|
||||
write := func(p, s string) {
|
||||
full := filepath.Join(dir, p)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(s), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for p, b := range files {
|
||||
write(p, string(b))
|
||||
}
|
||||
for p, s := range c.tree {
|
||||
write(p, s)
|
||||
}
|
||||
write("module.json", c.module)
|
||||
var got []string
|
||||
cmp, err := Compare(dir, files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, cmp...)
|
||||
for _, check := range []func(string, *Module) ([]string, error){CheckClients, CheckArtifacts} {
|
||||
more, err := check(dir, m)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", c.name, err)
|
||||
}
|
||||
got = append(got, more...)
|
||||
}
|
||||
if len(got) != len(c.want) {
|
||||
t.Errorf("%s: said %d problems, want %d:\n%s", c.name, len(got), len(c.want), strings.Join(got, "\n"))
|
||||
continue
|
||||
}
|
||||
for _, w := range c.want {
|
||||
found := false
|
||||
for _, g := range got {
|
||||
found = found || strings.Contains(g, w)
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("%s: no problem says %q:\n%s", c.name, w, strings.Join(got, "\n"))
|
||||
}
|
||||
}
|
||||
}
|
||||
// A hand-written file outside a client is still out of step (ADR 0625 §5).
|
||||
dir := t.TempDir()
|
||||
for p, b := range files {
|
||||
full := filepath.Join(dir, p)
|
||||
_ = os.MkdirAll(filepath.Dir(full), 0o755)
|
||||
_ = os.WriteFile(full, b, 0o644)
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(dir, "go/seats/aregistry/helper.go"), []byte("package aregistry\n"), 0o644)
|
||||
if out, _ := Compare(dir, files); len(out) != 1 || !strings.Contains(out[0], "helper.go: not written by the generator") {
|
||||
t.Errorf("a hand-written file beside a contract: %v", out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
const header = "// Code generated by seatgen from the seat definitions; DO NOT EDIT.\n\n"
|
||||
|
||||
func goFiles(m *Module, out map[string][]byte) error {
|
||||
// The seat set is the contracts module's root Go module; each seat defined whole is a Go module of its own beside
|
||||
// it, so a change of one seat moves only its importers, whose fingerprint counts a Go module's go.mod and go.sum
|
||||
// (ADR 0625 §1, §2). A seat's module imports nothing: the parts it includes are written into it whole.
|
||||
out["go/go.mod"] = goMod(m.GoModule)
|
||||
set, err := goSeatList(m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out["go/seats/seats.go"] = set
|
||||
for _, name := range m.Order {
|
||||
d := m.Seats[name]
|
||||
if d.Grain != seatdef.Whole {
|
||||
continue
|
||||
}
|
||||
src, test, err := goWhole(m, d)
|
||||
if err != nil {
|
||||
return fmt.Errorf("seat %s: %w", name, err)
|
||||
}
|
||||
dir := "go/seats/" + pkgName(name) + "/"
|
||||
out[dir+"go.mod"] = goMod(SeatGoModule(m.GoModule, name))
|
||||
out[dir+"contract.go"] = src
|
||||
if test != nil {
|
||||
out[dir+"contract_test.go"] = test
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SeatGoModule is the Go module of a seat defined whole, beside the seat set's.
|
||||
func SeatGoModule(root, seat string) string { return root + "/seats/" + pkgName(seat) }
|
||||
|
||||
func goMod(path string) []byte { return []byte("module " + path + "\n\ngo 1.26.0\n") }
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func gofmt(b *bytes.Buffer) ([]byte, error) {
|
||||
src, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the generated Go does not parse: %w\n%s", err, b.String())
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
// goSeatList is go/seats/seats.go: the seat list's types, every seat's name and the compiled list in reading order.
|
||||
func goSeatList(m *Module) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
b.WriteString(header)
|
||||
b.WriteString(`// Package seats is the mesh's seat list, generated from every seat's definition (design 26 *The seat set has one
|
||||
// source*): what each seat is, where it is held, the provision it delivers, its verbs with their inputs, what it
|
||||
// accepts and emits, what it receives and the paths it owns. mesh-sdk's runtime reads it; a seat its holder declares
|
||||
// itself has a name here and no entry in the list.
|
||||
package seats
|
||||
|
||||
// Seat is one role the mesh defines.
|
||||
type Seat struct {
|
||||
Name string
|
||||
Scope string
|
||||
Grain string
|
||||
Replicated bool
|
||||
Delivers string
|
||||
Accepts []string
|
||||
Emits []string
|
||||
PulledByKind bool
|
||||
Yields bool
|
||||
Serves []Verb
|
||||
Receives []Receivable
|
||||
Paths []Path
|
||||
HeldByTheEngine bool
|
||||
Decision string
|
||||
}
|
||||
|
||||
// Verb is one verb a seat serves: its input and answer as JSON Schema.
|
||||
type Verb struct {
|
||||
Name string
|
||||
Description string
|
||||
Input map[string]any
|
||||
Output map[string]any
|
||||
Optional bool
|
||||
Replaces []string
|
||||
}
|
||||
|
||||
// Receivable is one kind of contribution a seat receives.
|
||||
type Receivable struct {
|
||||
Kind string
|
||||
Comment string
|
||||
Dirs bool
|
||||
Shape *Shape
|
||||
Offered bool
|
||||
}
|
||||
|
||||
// Shape is a kind given as data. Its checks are the runtime's.
|
||||
type Shape struct {
|
||||
Places []PlaceField
|
||||
Order string
|
||||
Examples []map[string]any
|
||||
Text bool
|
||||
}
|
||||
|
||||
// PlaceField is one field a holder places by, and the values it takes.
|
||||
type PlaceField struct {
|
||||
Field string
|
||||
Values []string
|
||||
}
|
||||
|
||||
// Path is one path on its machine a seat's holder owns.
|
||||
type Path struct {
|
||||
Path string
|
||||
StepsBackFor string
|
||||
}
|
||||
|
||||
// The name of every seat defined.
|
||||
const (
|
||||
`)
|
||||
for _, name := range m.Order {
|
||||
fmt.Fprintf(&b, "\t%s = %q\n", ident(name), name)
|
||||
}
|
||||
b.WriteString(")\n\n// Names is every seat defined, in reading order, the ones their holders declare included.\nfunc Names() []string {\n\treturn []string{")
|
||||
for _, name := range m.Order {
|
||||
b.WriteString(ident(name) + ", ")
|
||||
}
|
||||
b.WriteString("}\n}\n\n// List is the seat list, in reading order: a new copy each call.\nfunc List() []Seat {\n\treturn []Seat{\n")
|
||||
for _, name := range m.Order {
|
||||
d := m.Seats[name]
|
||||
if d.HolderDeclares {
|
||||
continue
|
||||
}
|
||||
b.WriteString(goSeat(d))
|
||||
}
|
||||
b.WriteString("\t}\n}\n")
|
||||
return gofmt(&b)
|
||||
}
|
||||
|
||||
func goSeat(d seatdef.Definition) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "{Name: %s, Scope: %q, Grain: %q, Decision: %q", ident(d.Seat), d.Scope, d.Grain, d.Decision)
|
||||
if d.Replicated {
|
||||
b.WriteString(", Replicated: true")
|
||||
}
|
||||
if d.Delivers != "" {
|
||||
fmt.Fprintf(&b, ", Delivers: %q", d.Delivers)
|
||||
}
|
||||
if len(d.Accepts) > 0 {
|
||||
b.WriteString(", Accepts: " + goLit(anyStrings(seatdef.MessageNames(d.Accepts))))
|
||||
}
|
||||
if len(d.Events) > 0 {
|
||||
b.WriteString(", Emits: " + goLit(anyStrings(seatdef.MessageNames(d.Events))))
|
||||
}
|
||||
if d.PulledByKind {
|
||||
b.WriteString(", PulledByKind: true")
|
||||
}
|
||||
if d.Yields {
|
||||
b.WriteString(", Yields: true")
|
||||
}
|
||||
if d.HeldByTheEngine {
|
||||
b.WriteString(", HeldByTheEngine: true")
|
||||
}
|
||||
if len(d.Verbs) > 0 {
|
||||
b.WriteString(",\n\t\tServes: []Verb{\n")
|
||||
for _, v := range d.Verbs {
|
||||
fmt.Fprintf(&b, "\t\t\t{Name: %q, Description: %q", v.Name, v.Description)
|
||||
if v.Optional {
|
||||
b.WriteString(", Optional: true")
|
||||
}
|
||||
if v.Input != nil {
|
||||
b.WriteString(",\n\t\t\t\tInput: " + goLit(resolveRefs(v.Input, d.Defs)))
|
||||
}
|
||||
if v.Answer != nil {
|
||||
b.WriteString(",\n\t\t\t\tOutput: " + goLit(resolveRefs(v.Answer, d.Defs)))
|
||||
}
|
||||
if len(v.Replaces) > 0 {
|
||||
b.WriteString(", Replaces: " + goLit(anyStrings(v.Replaces)))
|
||||
}
|
||||
b.WriteString("},\n")
|
||||
}
|
||||
b.WriteString("\t\t}")
|
||||
}
|
||||
if len(d.Receives) > 0 {
|
||||
b.WriteString(",\n\t\tReceives: []Receivable{")
|
||||
for _, r := range d.Receives {
|
||||
fmt.Fprintf(&b, "{Kind: %q, Comment: %q", r.Kind, r.Comment)
|
||||
if r.Dirs {
|
||||
b.WriteString(", Dirs: true")
|
||||
}
|
||||
if r.Offered {
|
||||
b.WriteString(", Offered: true")
|
||||
}
|
||||
if s := r.Shape; s != nil {
|
||||
b.WriteString(", Shape: &Shape{")
|
||||
if len(s.Places) > 0 {
|
||||
b.WriteString("Places: []PlaceField{")
|
||||
for _, p := range s.Places {
|
||||
fmt.Fprintf(&b, "{Field: %q, Values: %s}, ", p.Field, goLit(anyStrings(p.Values)))
|
||||
}
|
||||
b.WriteString("}, ")
|
||||
}
|
||||
if s.Order != "" {
|
||||
fmt.Fprintf(&b, "Order: %q, ", s.Order)
|
||||
}
|
||||
if len(s.Examples) > 0 {
|
||||
b.WriteString("Examples: []map[string]any{")
|
||||
for _, e := range s.Examples {
|
||||
b.WriteString(goLit(e) + ", ")
|
||||
}
|
||||
b.WriteString("}, ")
|
||||
}
|
||||
if s.Text {
|
||||
b.WriteString("Text: true")
|
||||
}
|
||||
b.WriteString("}")
|
||||
}
|
||||
b.WriteString("}, ")
|
||||
}
|
||||
b.WriteString("}")
|
||||
}
|
||||
if len(d.Paths) > 0 {
|
||||
b.WriteString(", Paths: []Path{")
|
||||
for _, p := range d.Paths {
|
||||
fmt.Fprintf(&b, "{Path: %q, StepsBackFor: %q}, ", p.Path, p.StepsBackFor)
|
||||
}
|
||||
b.WriteString("}")
|
||||
}
|
||||
b.WriteString("},\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func anyStrings(s []string) []any {
|
||||
out := make([]any, len(s))
|
||||
for i, v := range s {
|
||||
out[i] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// goLit is a JSON value as a Go literal, in the form encoding/json decodes it, but for a list of strings alone,
|
||||
// which is a []string as the seat list wrote it: a map's keys sorted, a number a float64.
|
||||
func goLit(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return "nil"
|
||||
case string:
|
||||
return strconv.Quote(x)
|
||||
case bool:
|
||||
return strconv.FormatBool(x)
|
||||
case float64:
|
||||
return "float64(" + strconv.FormatFloat(x, 'g', -1, 64) + ")"
|
||||
case int:
|
||||
return "float64(" + strconv.Itoa(x) + ")"
|
||||
case json.Number:
|
||||
return "float64(" + x.String() + ")"
|
||||
case []string:
|
||||
return goLit(anyStrings(x))
|
||||
case []any:
|
||||
allStrings := len(x) > 0
|
||||
for _, e := range x {
|
||||
if _, ok := e.(string); !ok {
|
||||
allStrings = false
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
if allStrings {
|
||||
b.WriteString("[]string{")
|
||||
} else {
|
||||
b.WriteString("[]any{")
|
||||
}
|
||||
for i, e := range x {
|
||||
if i > 0 {
|
||||
b.WriteString(", ")
|
||||
}
|
||||
b.WriteString(goLit(e))
|
||||
}
|
||||
b.WriteString("}")
|
||||
return b.String()
|
||||
case map[string]any:
|
||||
var b strings.Builder
|
||||
b.WriteString("map[string]any{")
|
||||
for i, k := range sortedKeys(x) {
|
||||
if i > 0 {
|
||||
b.WriteString(", ")
|
||||
}
|
||||
b.WriteString(strconv.Quote(k) + ": " + goLit(x[k]))
|
||||
}
|
||||
b.WriteString("}")
|
||||
return b.String()
|
||||
}
|
||||
// Any other value (a typed list from a definition read in Go) goes through JSON once.
|
||||
raw, _ := json.Marshal(v)
|
||||
var back any
|
||||
_ = json.Unmarshal(raw, &back)
|
||||
return goLit(back)
|
||||
}
|
||||
|
||||
// declareAll declares a definition's types: its own named types, then each verb's input and answer, each accept,
|
||||
// event, holder event, record and provision; a name given by a part (in fromPart) is an alias of the part's.
|
||||
func declareAll(d seatdef.Definition, fromPart map[string]string) (*typer, error) {
|
||||
tp := newTyper()
|
||||
decl := func(name, desc string, s map[string]any) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
if _, ok := fromPart[name]; ok {
|
||||
tp.taken[name] = true
|
||||
return nil
|
||||
}
|
||||
return tp.declare(name, desc, s)
|
||||
}
|
||||
for _, n := range d.DefNames() {
|
||||
if err := decl(n, "", d.Defs[n]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, v := range d.Verbs {
|
||||
if err := decl(ident(v.Name)+"Input", "is what "+v.Name+" takes.", v.Input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := decl(ident(v.Name)+"Answer", "is what "+v.Name+" answers.", v.Answer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, a := range d.Accepts {
|
||||
if err := decl(ident(a.Name)+"Accept", "is the body of "+a.Name+".", a.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, e := range d.Events {
|
||||
if err := decl(ident(e.Name)+"Event", "is the body of the event "+e.Name+".", e.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, e := range d.HolderEvents {
|
||||
if err := decl(ident(e.Name)+"HolderEvent", "is the body of the holder's event "+e.Name+".", e.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, r := range d.Records {
|
||||
if err := decl(ident(r.Name)+"Record", "is one value of the record "+r.Name+".", r.Value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, p := range d.Provisions {
|
||||
if err := decl(ident(p.Name)+"Form", "is the form of the provision "+p.Name+".", p.Form); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return tp, nil
|
||||
}
|
||||
|
||||
func oneLine(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return "no description."
|
||||
}
|
||||
return strings.ReplaceAll(s, "\n", " ")
|
||||
}
|
||||
|
||||
func writeNames(b *bytes.Buffer, prefix string, names []string) {
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
b.WriteString("const (\n")
|
||||
for _, n := range names {
|
||||
fmt.Fprintf(b, "\t%s%s = %q\n", prefix, ident(n), n)
|
||||
}
|
||||
b.WriteString(")\n\n")
|
||||
}
|
||||
|
||||
func writeList(b *bytes.Buffer, fn, prefix, what string, names []string) {
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(b, "// %s is %s: a new copy each call.\nfunc %s() []string {\n\treturn []string{", fn, what, fn)
|
||||
for i, n := range names {
|
||||
if i > 0 {
|
||||
b.WriteString(", ")
|
||||
}
|
||||
b.WriteString(prefix + ident(n))
|
||||
}
|
||||
b.WriteString("}\n}\n\n")
|
||||
}
|
||||
|
||||
// goWhole is a whole seat's package: its names, subjects and types, and the test of its fixtures.
|
||||
func goWhole(m *Module, d seatdef.Definition) ([]byte, []byte, error) {
|
||||
fromPart := map[string]string{}
|
||||
tp, err := declareAll(d, fromPart)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pkg := pkgName(d.Seat)
|
||||
var b bytes.Buffer
|
||||
b.WriteString(header)
|
||||
fmt.Fprintf(&b, "// Package %s is the contract of the seat %q, defined whole (seats/%s/seat.json): %s\npackage %s\n\n",
|
||||
pkg, d.Seat, d.Seat, oneLine(d.Description), pkg)
|
||||
fmt.Fprintf(&b, "// Seat is the seat's name.\nconst Seat = %q\n\n", d.Seat)
|
||||
writeNames(&b, "Verb", seatdef.VerbNames(d.Verbs))
|
||||
writeNames(&b, "Accept", seatdef.MessageNames(d.Accepts))
|
||||
writeNames(&b, "Event", seatdef.MessageNames(d.Events))
|
||||
writeList(&b, "Verbs", "Verb", "every verb the seat serves, in its definition's order", seatdef.VerbNames(d.Verbs))
|
||||
writeList(&b, "Events", "Event", "every event published on the seat's subject", seatdef.MessageNames(d.Events))
|
||||
if f := d.Family; f != nil {
|
||||
fmt.Fprintf(&b, "// Family is where the seat's events are kept: the shared events stream, filtered to the seat's subjects.\nconst (\n\tFamily = %q\n\tFamilyMaxAgeDays = %d\n)\n\n", f.Name, f.MaxAgeDays)
|
||||
}
|
||||
for _, e := range d.Events {
|
||||
subj := seatdef.EventSubject(d.Seat, e.Name)
|
||||
if e.ByCaller {
|
||||
fmt.Fprintf(&b, "// Subject%s is where %s is published for one caller.\nfunc Subject%s(caller string) string { return %q + caller }\n\n",
|
||||
ident(e.Name), e.Name, ident(e.Name), subj+".")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "// Subject%s is where %s is published.\nconst Subject%s = %q\n\n", ident(e.Name), e.Name, ident(e.Name), subj)
|
||||
}
|
||||
}
|
||||
for _, a := range d.Accepts {
|
||||
subj := seatdef.AcceptSubject(d.Seat, a.Name)
|
||||
if a.ByCaller {
|
||||
fmt.Fprintf(&b, "// AcceptSubject%s is where one caller sends %s.\nfunc AcceptSubject%s(caller string) string { return %q + caller }\n\n",
|
||||
ident(a.Name), a.Name, ident(a.Name), subj+".")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "// AcceptSubject%s is where %s is sent.\nconst AcceptSubject%s = %q\n\n", ident(a.Name), a.Name, ident(a.Name), subj)
|
||||
}
|
||||
}
|
||||
if len(d.HolderEvents) > 0 {
|
||||
b.WriteString("// The holder's own events, listed beside the seat and published under the holder's subjects (ADR 0620 §2).\nconst (\n")
|
||||
for _, e := range d.HolderEvents {
|
||||
fmt.Fprintf(&b, "\tHolderEvent%s = %q\n", ident(e.Name), e.Name)
|
||||
}
|
||||
b.WriteString(")\n\n")
|
||||
for _, e := range d.HolderEvents {
|
||||
before, after, _ := strings.Cut(e.Subject, "<holder>")
|
||||
fmt.Fprintf(&b, "// HolderSubject%s is where the holder publishes %s", ident(e.Name), e.Name)
|
||||
if e.Family != "" {
|
||||
fmt.Fprintf(&b, ", kept in %s", e.Family)
|
||||
}
|
||||
fmt.Fprintf(&b, ".\nfunc HolderSubject%s(holder string) string { return %q + holder + %q }\n\n", ident(e.Name), before, after)
|
||||
}
|
||||
}
|
||||
if len(d.Records) > 0 {
|
||||
writeNames(&b, "Record", recordNames(d.Records))
|
||||
}
|
||||
if err := goTypes(&b, tp, map[string]*typ{}); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
src, err := gofmt(&b)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
test, err := goFixtures(m, d, pkg, tp, fromPart)
|
||||
return src, test, err
|
||||
}
|
||||
|
||||
func recordNames(rs []seatdef.Record) []string {
|
||||
out := make([]string, len(rs))
|
||||
for i, r := range rs {
|
||||
out[i] = r.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// goTypes writes every declared type; also are the kinds of types declared elsewhere (a part's), by name.
|
||||
func goTypes(b *bytes.Buffer, tp *typer, also map[string]*typ) error {
|
||||
kinds := map[string]*typ{}
|
||||
for k, v := range also {
|
||||
kinds[k] = v
|
||||
}
|
||||
for _, t := range tp.types {
|
||||
kinds[t.name] = t.t
|
||||
}
|
||||
for _, t := range tp.types {
|
||||
desc := strings.TrimSpace(t.desc)
|
||||
if desc == "" {
|
||||
desc = "is a type of the contract."
|
||||
} else if !strings.HasPrefix(desc, "is ") {
|
||||
desc = "is " + strings.TrimSuffix(desc, ".") + "."
|
||||
}
|
||||
fmt.Fprintf(b, "// %s %s\n", t.name, oneLine(desc))
|
||||
if t.t.kind != "struct" {
|
||||
fmt.Fprintf(b, "type %s = %s\n\n", t.name, goType(t.t, kinds, true))
|
||||
goEnum(b, t.name, t.name, t.t)
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "type %s struct {\n", t.name)
|
||||
for _, f := range t.t.fields {
|
||||
if f.desc != "" {
|
||||
fmt.Fprintf(b, "\t// %s\n", oneLine(f.desc))
|
||||
}
|
||||
tag := f.json
|
||||
if !f.required {
|
||||
tag += ",omitempty"
|
||||
}
|
||||
fmt.Fprintf(b, "\t%s %s `json:%q`\n", ident(f.json), goType(f.t, kinds, f.required), tag)
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
for _, f := range t.t.fields {
|
||||
goEnum(b, t.name+"'s "+f.json, t.name+ident(f.json), f.t)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// goEnum writes a string's enum as one constant per value, named prefix and the value (RemoveInputReasonRetention), so a
|
||||
// caller names a value the definition gives and never writes it by hand.
|
||||
func goEnum(b *bytes.Buffer, what, prefix string, t *typ) {
|
||||
if t.kind != "string" || len(t.enum) == 0 {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(b, "// The values of %s.\nconst (\n", what)
|
||||
for _, v := range t.enum {
|
||||
fmt.Fprintf(b, "\t%s%s = %q\n", prefix, ident(v), v)
|
||||
}
|
||||
b.WriteString(")\n\n")
|
||||
}
|
||||
|
||||
func goType(t *typ, kinds map[string]*typ, required bool) string {
|
||||
switch t.kind {
|
||||
case "string":
|
||||
return "string"
|
||||
case "integer":
|
||||
return "int64"
|
||||
case "number":
|
||||
return "float64"
|
||||
case "boolean":
|
||||
return "bool"
|
||||
case "object":
|
||||
return "map[string]any"
|
||||
case "map":
|
||||
return "map[string]" + goType(t.elem, kinds, true)
|
||||
case "slice":
|
||||
return "[]" + goType(t.elem, kinds, true)
|
||||
case "ref":
|
||||
if k, ok := kinds[t.ref]; ok && k.kind == "struct" && !required {
|
||||
return "*" + t.ref
|
||||
}
|
||||
return t.ref
|
||||
}
|
||||
return "any"
|
||||
}
|
||||
|
||||
// goFixtures is the test that every fixture of the seat decodes into its type and reads back as its wire says, and
|
||||
// that the subject it names is the one the contract gives.
|
||||
func goFixtures(m *Module, d seatdef.Definition, pkg string, tp *typer, fromPart map[string]string) ([]byte, error) {
|
||||
fx := m.Fixtures[d.Seat]
|
||||
if len(fx) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
has := map[string]bool{}
|
||||
for _, t := range tp.types {
|
||||
has[t.name] = true
|
||||
}
|
||||
for n := range fromPart {
|
||||
has[n] = true
|
||||
}
|
||||
var b bytes.Buffer
|
||||
b.WriteString(header)
|
||||
fmt.Fprintf(&b, "package %s\n\nimport (\n\t\"encoding/json\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"testing\"\n)\n\n", pkg)
|
||||
fmt.Fprintf(&b, "// TestFixtures reads every fixture of seats/%s/fixtures: each decodes into its type, a field the type does not\n"+
|
||||
"// know is dropped (ADR 0608 §6), and it reads back as its wire says; each subject named is the contract's.\n", d.Seat)
|
||||
b.WriteString("func TestFixtures(t *testing.T) {\n\tcases := []struct {\n\t\tname, subject, given, wire string\n\t\tdecode func([]byte) (any, error)\n\t\tsubjectIs *regexp.Regexp\n\t}{\n")
|
||||
for _, f := range fx {
|
||||
kind, name, _ := f.Instance()
|
||||
typeName, pattern, err := fixtureTarget(d, kind, name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fixture %q: %w", f.Name, err)
|
||||
}
|
||||
given, _ := json.Marshal(f.Given)
|
||||
wire := given
|
||||
if f.Wire != nil {
|
||||
wire, _ = json.Marshal(f.Wire)
|
||||
}
|
||||
decoder := "func(b []byte) (any, error) { var v map[string]any; err := json.Unmarshal(b, &v); return v, err }"
|
||||
if has[typeName] {
|
||||
decoder = fmt.Sprintf("func(b []byte) (any, error) { var v %s; err := json.Unmarshal(b, &v); return v, err }", typeName)
|
||||
}
|
||||
subjectIs := "nil"
|
||||
if pattern != "" {
|
||||
subjectIs = "regexp.MustCompile(" + strconv.Quote(pattern) + ")"
|
||||
} else if f.Subject != "" {
|
||||
return nil, fmt.Errorf("fixture %q names a subject, and a verb's message has none in the contract", f.Name)
|
||||
}
|
||||
if pattern != "" && f.Subject == "" {
|
||||
return nil, fmt.Errorf("fixture %q of %s names no subject (design 26: each event's subject is named)", f.Name, f.Of)
|
||||
}
|
||||
fmt.Fprintf(&b, "\t\t{name: %q, subject: %q, given: %s, wire: %s,\n\t\t\tdecode: %s, subjectIs: %s},\n",
|
||||
f.Name, f.Subject, strconv.Quote(string(given)), strconv.Quote(string(wire)), decoder, subjectIs)
|
||||
}
|
||||
b.WriteString(` }
|
||||
for _, c := range cases {
|
||||
v, err := c.decode([]byte(c.given))
|
||||
if err != nil {
|
||||
t.Errorf("%s: does not decode: %v", c.name, err)
|
||||
continue
|
||||
}
|
||||
back, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Errorf("%s: does not encode: %v", c.name, err)
|
||||
continue
|
||||
}
|
||||
var got, want any
|
||||
if err := json.Unmarshal(back, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(c.wire), &want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("%s: reads back as %s, want %s", c.name, back, c.wire)
|
||||
}
|
||||
if c.subjectIs != nil && !c.subjectIs.MatchString(c.subject) {
|
||||
t.Errorf("%s: subject %q is not the contract's %s", c.name, c.subject, c.subjectIs)
|
||||
}
|
||||
}
|
||||
}
|
||||
`)
|
||||
return gofmt(&b)
|
||||
}
|
||||
|
||||
// fixtureTarget is the type a fixture decodes into and the pattern its subject must match, if it has one.
|
||||
func fixtureTarget(d seatdef.Definition, kind, name string) (string, string, error) {
|
||||
switch kind {
|
||||
case "verb-input", "verb-answer":
|
||||
for _, v := range d.Verbs {
|
||||
if v.Name == name {
|
||||
if kind == "verb-input" {
|
||||
return ident(name) + "Input", "", nil
|
||||
}
|
||||
return ident(name) + "Answer", "", nil
|
||||
}
|
||||
}
|
||||
case "accept", "event":
|
||||
ms, subj := d.Accepts, seatdef.AcceptSubject(d.Seat, name)
|
||||
suffix := "Accept"
|
||||
if kind == "event" {
|
||||
ms, subj, suffix = d.Events, seatdef.EventSubject(d.Seat, name), "Event"
|
||||
}
|
||||
for _, msg := range ms {
|
||||
if msg.Name == name {
|
||||
p := "^" + regexp(subj)
|
||||
if msg.ByCaller {
|
||||
p += `\.[A-Za-z0-9_-]+`
|
||||
}
|
||||
return ident(name) + suffix, p + "$", nil
|
||||
}
|
||||
}
|
||||
case "holder-event":
|
||||
for _, e := range d.HolderEvents {
|
||||
if e.Name == name {
|
||||
before, after, _ := strings.Cut(e.Subject, "<holder>")
|
||||
p := "^" + regexp(before)
|
||||
if strings.Contains(e.Subject, "<holder>") {
|
||||
p += "[a-z0-9-]+" + regexp(after)
|
||||
}
|
||||
return ident(name) + "HolderEvent", p + "$", nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", "", fmt.Errorf("the definition has no %s %q", kind, name)
|
||||
}
|
||||
|
||||
func regexp(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
if strings.ContainsRune(`\.+*?()|[]{}^$`, r) {
|
||||
b.WriteRune('\\')
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
re "regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
// TestEachSeatDefinedWholeIsAGoModuleOfItsOwn is ADR 0625's generator check (§1, §2, §3): the seat set is one package in
|
||||
// the root Go module, each seat defined whole is a Go module of its own holding its package alone, the parts it
|
||||
// includes are written into it, and no generated Go file imports anything outside the standard library.
|
||||
func TestEachSeatDefinedWholeIsAGoModuleOfItsOwn(t *testing.T) {
|
||||
m, err := Load("testdata/contracts", "example.org/contracts/go", "@example/contracts")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, err := Generate(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mods := map[string]string{}
|
||||
for p, b := range files {
|
||||
if strings.HasPrefix(p, "go/") && strings.HasSuffix(p, "go.mod") {
|
||||
mods[strings.TrimSuffix(p, "go.mod")] = strings.SplitN(string(b), "\n", 2)[0]
|
||||
}
|
||||
}
|
||||
want := map[string]string{
|
||||
"go/": "module example.org/contracts/go",
|
||||
"go/seats/aregistry/": "module example.org/contracts/go/seats/aregistry",
|
||||
"go/seats/bregistry/": "module example.org/contracts/go/seats/bregistry",
|
||||
}
|
||||
for dir, line := range want {
|
||||
if mods[dir] != line {
|
||||
t.Errorf("%sgo.mod says %q, want %q", dir, mods[dir], line)
|
||||
}
|
||||
}
|
||||
// Every seat the definitions mark whole has its own module, whatever the seat set says of it (ADR 0627: the seat
|
||||
// set marks ten whole, and none is without its package).
|
||||
for name, d := range m.Seats {
|
||||
if d.Grain == seatdef.Whole && mods["go/seats/"+pkgName(name)+"/"] == "" {
|
||||
t.Errorf("the seat %s is defined whole and has no Go module of its own", name)
|
||||
}
|
||||
}
|
||||
if len(mods) != len(want) {
|
||||
t.Errorf("Go modules %v, want %v", mods, want)
|
||||
}
|
||||
for p, b := range files {
|
||||
if !strings.HasPrefix(p, "go/") || !strings.HasSuffix(p, ".go") {
|
||||
continue
|
||||
}
|
||||
dir := p[:strings.LastIndex(p, "/")+1]
|
||||
if dir != "go/seats/" && mods[dir] == "" {
|
||||
t.Errorf("%s is in no seat's own Go module, nor the seat set's package", p)
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), p, b, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, im := range f.Imports {
|
||||
if path := strings.Trim(im.Path.Value, `"`); strings.Contains(strings.SplitN(path, "/", 2)[0], ".") {
|
||||
t.Errorf("%s imports %s: a generated package imports nothing outside the standard library", p, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, seat := range []string{"aregistry", "bregistry"} {
|
||||
src := string(files["go/seats/"+seat+"/contract.go"])
|
||||
if !strings.Contains(src, "type Ref struct") || !strings.Contains(src, "type PublishedEvent") {
|
||||
t.Errorf("%s does not hold the part's types whole", seat)
|
||||
}
|
||||
// A string's enum is a constant per value, so a caller names the definition's value (A3t: the removal reason).
|
||||
if !re.MustCompile(`RefReasonRetention\s+= "retention"`).MatchString(src) || !re.MustCompile(`RefReasonTagGone\s+= "tag-gone"`).MatchString(src) {
|
||||
t.Errorf("%s does not name the part's enum values:\n%s", seat, src)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(files["go/seats/seats.go"]), "OneStore") {
|
||||
t.Error("the seat set does not name the seat at the seat list's grain")
|
||||
}
|
||||
|
||||
// The npm side (ADR 0625 §1): the indexer counts an npm package a lock resolves, so each seat defined whole is an
|
||||
// npm package of its own (`<package>-<seat>` at ts/seats/<seat without hyphens>), holding its parts' types whole and
|
||||
// importing nothing outside itself; the seat set's package (ts/) holds the seat list alone.
|
||||
pkgs := map[string]string{}
|
||||
for p, b := range files {
|
||||
if strings.HasPrefix(p, "ts/") && strings.HasSuffix(p, "package.json") {
|
||||
var pj struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &pj); err != nil {
|
||||
t.Fatalf("%s: %v", p, err)
|
||||
}
|
||||
pkgs[strings.TrimSuffix(p, "package.json")] = pj.Name
|
||||
}
|
||||
}
|
||||
wantPkgs := map[string]string{
|
||||
"ts/": "@example/contracts",
|
||||
"ts/seats/aregistry/": "@example/contracts-a-registry",
|
||||
"ts/seats/bregistry/": "@example/contracts-b-registry",
|
||||
}
|
||||
if len(pkgs) != len(wantPkgs) {
|
||||
t.Errorf("npm packages %v, want %v", pkgs, wantPkgs)
|
||||
}
|
||||
for dir, name := range wantPkgs {
|
||||
if pkgs[dir] != name {
|
||||
t.Errorf("%spackage.json names %q, want %q", dir, pkgs[dir], name)
|
||||
}
|
||||
}
|
||||
for p, b := range files {
|
||||
if !strings.HasPrefix(p, "ts/") || !strings.HasSuffix(p, ".ts") {
|
||||
continue
|
||||
}
|
||||
dir := ""
|
||||
for d := range pkgs {
|
||||
if strings.HasPrefix(p, d) && len(d) > len(dir) {
|
||||
dir = d
|
||||
}
|
||||
}
|
||||
if dir == "" || !strings.HasPrefix(p, dir+"src/") {
|
||||
t.Errorf("%s is in no npm package's src", p)
|
||||
}
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
i := strings.Index(line, ` from "`)
|
||||
if l := strings.TrimSpace(line); i >= 0 && (strings.HasPrefix(l, "import") || strings.HasPrefix(l, "export")) {
|
||||
from := strings.Trim(line[i+len(` from `):], `";`)
|
||||
if !strings.HasPrefix(from, "./") {
|
||||
t.Errorf("%s imports %s: a generated npm package imports only its own files", p, from)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, seat := range []string{"aregistry", "bregistry"} {
|
||||
if !strings.Contains(string(files["ts/seats/"+seat+"/src/index.ts"]), "export type PublishedEvent = registry.PublishedEvent") ||
|
||||
!strings.Contains(string(files["ts/seats/"+seat+"/src/parts/registry.ts"]), "export type PublishedEvent") {
|
||||
t.Errorf("the npm package of %s does not hold the part's types whole", seat)
|
||||
}
|
||||
}
|
||||
if ix := string(files["ts/src/index.ts"]); strings.Contains(ix, "Registry") || !strings.Contains(ix, "seats") {
|
||||
t.Errorf("the seat set's npm package exports a seat's contract or not the seat list:\n%s", ix)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// Package seatgen writes a contracts module's Go and TypeScript from its seat definitions (design 26 *The
|
||||
// generator*): the seat list every reader compiles, and for each seat defined whole its names, subjects and message
|
||||
// types, with a test of its fixtures. The same input gives the same bytes. It is the build modules' logic (the Go
|
||||
// build module's for Go, the Node build module's for TypeScript); this copy wrote mesh-contracts' first files and is
|
||||
// handed to them as it stands.
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
// Module is a contracts module read from its directory.
|
||||
type Module struct {
|
||||
// GoModule is the Go module path of the generated Go tree (`<module>/go`).
|
||||
GoModule string
|
||||
// TSPackage is the npm package's name.
|
||||
TSPackage string
|
||||
// Order is the seat list's reading order (seats/index.json).
|
||||
Order []string
|
||||
// Seats are every definition, resolved, by name.
|
||||
Seats map[string]seatdef.Definition
|
||||
// Raw are every definition as written, its parts not taken in.
|
||||
Raw map[string]seatdef.Definition
|
||||
// Parts are every part, by name.
|
||||
Parts map[string]seatdef.Part
|
||||
// Fixtures are each seat's fixtures, by seat, in file order.
|
||||
Fixtures map[string][]seatdef.Fixture
|
||||
}
|
||||
|
||||
// Load reads a contracts module: `seats/index.json`, `seats/<seat>/seat.json`, `seats/<seat>/fixtures/*.json`
|
||||
// and `parts/*.json`. A seat with a directory and not in the index, or in the index with no directory, is refused.
|
||||
func Load(dir, goModule, tsPackage string) (*Module, error) {
|
||||
m := &Module{GoModule: goModule, TSPackage: tsPackage, Seats: map[string]seatdef.Definition{},
|
||||
Raw: map[string]seatdef.Definition{}, Parts: map[string]seatdef.Part{}, Fixtures: map[string][]seatdef.Fixture{}}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "seats", "index.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ix, err := seatdef.ParseIndex(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seats/index.json: %w", err)
|
||||
}
|
||||
m.Order = ix.Seats
|
||||
parts, _ := filepath.Glob(filepath.Join(dir, "parts", "*.json"))
|
||||
sort.Strings(parts)
|
||||
for _, p := range parts {
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
part, err := seatdef.ParsePart(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", rel(dir, p), err)
|
||||
}
|
||||
if want := strings.TrimSuffix(filepath.Base(p), ".json"); part.Part != want {
|
||||
return nil, fmt.Errorf("%s: names part %q", rel(dir, p), part.Part)
|
||||
}
|
||||
m.Parts[part.Part] = part
|
||||
}
|
||||
dirs, _ := filepath.Glob(filepath.Join(dir, "seats", "*", "seat.json"))
|
||||
inIndex := map[string]bool{}
|
||||
for _, s := range m.Order {
|
||||
inIndex[s] = true
|
||||
}
|
||||
for _, p := range dirs {
|
||||
name := filepath.Base(filepath.Dir(p))
|
||||
if !inIndex[name] {
|
||||
return nil, fmt.Errorf("%s: seat %q is not in seats/index.json", rel(dir, p), name)
|
||||
}
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d, err := seatdef.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", rel(dir, p), err)
|
||||
}
|
||||
if d.Seat != name {
|
||||
return nil, fmt.Errorf("%s: names seat %q", rel(dir, p), d.Seat)
|
||||
}
|
||||
m.Raw[name] = d
|
||||
resolved, err := seatdef.Resolve(d, m.Parts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", rel(dir, p), err)
|
||||
}
|
||||
m.Seats[name] = resolved
|
||||
fx, _ := filepath.Glob(filepath.Join(filepath.Dir(p), "fixtures", "*.json"))
|
||||
sort.Strings(fx)
|
||||
for _, f := range fx {
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cases, err := seatdef.ParseFixtures(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", rel(dir, f), err)
|
||||
}
|
||||
m.Fixtures[name] = append(m.Fixtures[name], cases...)
|
||||
}
|
||||
}
|
||||
for _, s := range m.Order {
|
||||
if _, ok := m.Seats[s]; !ok {
|
||||
return nil, fmt.Errorf("seats/index.json names %q, which has no seats/%s/seat.json", s, s)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func rel(dir, p string) string {
|
||||
if r, err := filepath.Rel(dir, p); err == nil {
|
||||
return r
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Generate is every file the module's generated trees hold, by path from the module's root.
|
||||
func Generate(m *Module) (map[string][]byte, error) {
|
||||
out := map[string][]byte{}
|
||||
if err := goFiles(m, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tsFiles(m, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GeneratedRoots are the directories every file of which the generator writes: a file there it did not write is
|
||||
// out of step (design 26: the compare step).
|
||||
var GeneratedRoots = []string{"go", "ts"}
|
||||
|
||||
// Compare is every path out of step between what the generator writes and the tree in dir: a file that differs, one
|
||||
// missing, or one under a generated root the generator did not write, each named once, sorted.
|
||||
func Compare(dir string, files map[string][]byte) ([]string, error) {
|
||||
var out []string
|
||||
for p, want := range files {
|
||||
got, err := os.ReadFile(filepath.Join(dir, p))
|
||||
switch {
|
||||
case os.IsNotExist(err):
|
||||
out = append(out, p+": missing")
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case string(got) != string(want):
|
||||
out = append(out, p+": differs")
|
||||
}
|
||||
}
|
||||
for _, root := range GeneratedRoots {
|
||||
err := filepath.WalkDir(filepath.Join(dir, root), func(p string, e os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return err
|
||||
}
|
||||
if e.IsDir() {
|
||||
if e.Name() == "node_modules" || e.Name() == "dist" || rel(dir, p) == ClientRoot {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
r := rel(dir, p)
|
||||
if _, ok := files[r]; !ok {
|
||||
out = append(out, r+": not written by the generator")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// pkgName is a seat's or part's Go package: its name without hyphens.
|
||||
func pkgName(name string) string { return strings.ReplaceAll(name, "-", "") }
|
||||
|
||||
// ident is a name in Go's exported form: mesh-broker → MeshBroker, publish-part → PublishPart, preview.written →
|
||||
// PreviewWritten, local-name → LocalName, id → ID.
|
||||
func ident(name string) string {
|
||||
var b strings.Builder
|
||||
for _, w := range strings.FieldsFunc(name, func(r rune) bool { return r == '-' || r == '_' || r == '.' || r == ' ' }) {
|
||||
switch w {
|
||||
case "id":
|
||||
b.WriteString("ID")
|
||||
case "url":
|
||||
b.WriteString("URL")
|
||||
case "mib":
|
||||
b.WriteString("MiB")
|
||||
default:
|
||||
b.WriteString(strings.ToUpper(w[:1]) + w[1:])
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// tsName is a name in TypeScript's camel form for a constant: publish-part → publishPart.
|
||||
func tsName(name string) string {
|
||||
id := ident(name)
|
||||
if strings.HasPrefix(id, "ID") {
|
||||
return "id" + id[2:]
|
||||
}
|
||||
return strings.ToLower(id[:1]) + id[1:]
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{"format":1,"part":"registry","verbs":[{"name":"publish","input":{"$ref":"#/defs/Ref"},"answer":{"type":"object"}}],
|
||||
"events":[{"name":"published","body":{"$ref":"#/defs/Ref"}}],
|
||||
"defs":{"Ref":{"type":"object","properties":{"digest":{"type":"string"},"reason":{"type":"string","enum":["tag-gone","retention"]}},"required":["digest"]}}}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{"format":1,"seat":"a-registry","scope":"mesh","grain":"whole","decision":"ADR 1","includes":["registry"],
|
||||
"verbs":[{"name":"hold","input":{"type":"object"},"answer":{"type":"object"}}],
|
||||
"family":{"name":"a-registry.events","max-age-days":7}}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{"format":1,"seat":"b-registry","scope":"mesh","grain":"whole","decision":"ADR 1","includes":["registry"],
|
||||
"verbs":[{"name":"hold","input":{"type":"object"},"answer":{"type":"object"}}],
|
||||
"family":{"name":"b-registry.events","max-age-days":7}}
|
||||
@@ -0,0 +1 @@
|
||||
{"format":1,"seats":["one-store","a-registry","b-registry"]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"format":1,"seat":"one-store","scope":"mesh","grain":"seat-list","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"}}]}
|
||||
@@ -0,0 +1,313 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||
)
|
||||
|
||||
const tsHeader = "// Code generated by seatgen from the seat definitions; DO NOT EDIT.\n\n"
|
||||
|
||||
// TSSeatDir is where a seat defined whole has its npm package (ADR 0625 §1): the indexer counts the npm package a
|
||||
// lock resolves, so each such seat is a package of its own and a module is rebuilt only for the seats it uses.
|
||||
func TSSeatDir(seat string) string { return "ts/seats/" + pkgName(seat) }
|
||||
|
||||
// TSSeatPackage is the npm package name of a seat defined whole, beside the seat set's package root.
|
||||
func TSSeatPackage(root, seat string) string { return root + "-" + seat }
|
||||
|
||||
const tsConfig = `{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
`
|
||||
|
||||
// tsPackage writes one npm package's package.json and tsconfig.json at dir.
|
||||
func tsPackage(out map[string][]byte, dir, name, description string) {
|
||||
pkg := map[string]any{
|
||||
"name": name, "version": "0.1.0", "type": "module",
|
||||
"description": description,
|
||||
"exports": map[string]any{".": "./dist/index.js"},
|
||||
"files": []any{"dist"},
|
||||
"scripts": map[string]any{"build": "tsc", "prepare": "tsc"},
|
||||
"devDependencies": map[string]any{"typescript": "^5.6.0"},
|
||||
}
|
||||
raw, _ := json.MarshalIndent(pkg, "", " ")
|
||||
out[dir+"/package.json"] = append(raw, '\n')
|
||||
out[dir+"/tsconfig.json"] = []byte(tsConfig)
|
||||
}
|
||||
|
||||
// tsFiles writes the npm side: the seat set's package at ts/ (the seat list alone, ADR 0625 §2) and one package per
|
||||
// seat defined whole at TSSeatDir (ADR 0625 §1), holding the parts it includes whole and importing nothing outside it.
|
||||
func tsFiles(m *Module, out map[string][]byte) error {
|
||||
tsPackage(out, "ts", m.TSPackage, "The mesh's seat set, generated from every seat's definition.")
|
||||
out["ts/src/index.ts"] = []byte(tsHeader + "export * as seats from \"./seats.js\";\n")
|
||||
out["ts/src/seats.ts"] = tsSeatList(m)
|
||||
partTypes := map[string]*typer{}
|
||||
partFiles := map[string][]byte{}
|
||||
for _, name := range sortedKeys(m.Parts) {
|
||||
p := m.Parts[name]
|
||||
d := seatdef.Definition{Grain: seatdef.Whole, Verbs: p.Verbs, Events: p.Events, Defs: p.Defs}
|
||||
tp, err := declareAll(d, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
partTypes[name] = tp
|
||||
var b bytes.Buffer
|
||||
b.WriteString(tsHeader)
|
||||
fmt.Fprintf(&b, "// The part %q several seats include whole: %s\n\n", p.Part, oneLine(p.Description))
|
||||
tsNames(&b, "verbs", seatdef.VerbNames(p.Verbs))
|
||||
tsNames(&b, "events", seatdef.MessageNames(p.Events))
|
||||
tsTypes(&b, tp)
|
||||
partFiles[name] = b.Bytes()
|
||||
}
|
||||
for _, name := range m.Order {
|
||||
d := m.Seats[name]
|
||||
if d.Grain != seatdef.Whole {
|
||||
continue
|
||||
}
|
||||
dir := TSSeatDir(name)
|
||||
tsPackage(out, dir, TSSeatPackage(m.TSPackage, name), fmt.Sprintf("The contract of the seat %s, generated from its definition.", name))
|
||||
raw := m.Raw[name]
|
||||
fromPart := map[string]string{}
|
||||
for _, inc := range raw.Includes {
|
||||
for _, t := range partTypes[inc].types {
|
||||
fromPart[t.name] = inc
|
||||
}
|
||||
out[dir+"/src/parts/"+inc+".ts"] = partFiles[inc]
|
||||
}
|
||||
tp, err := declareAll(d, fromPart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var b bytes.Buffer
|
||||
b.WriteString(tsHeader)
|
||||
fmt.Fprintf(&b, "// The contract of the seat %q, defined whole (seats/%s/seat.json): %s\n\n", d.Seat, d.Seat, oneLine(d.Description))
|
||||
for _, inc := range raw.Includes {
|
||||
fmt.Fprintf(&b, "import type * as %s from \"./parts/%s.js\";\n\n", tsName(inc), inc)
|
||||
}
|
||||
fmt.Fprintf(&b, "export const seat = %q;\n\n", d.Seat)
|
||||
tsNames(&b, "verbs", seatdef.VerbNames(d.Verbs))
|
||||
tsNames(&b, "accepts", seatdef.MessageNames(d.Accepts))
|
||||
tsNames(&b, "events", seatdef.MessageNames(d.Events))
|
||||
if f := d.Family; f != nil {
|
||||
fmt.Fprintf(&b, "export const family = { name: %q, maxAgeDays: %d", f.Name, f.MaxAgeDays)
|
||||
b.WriteString(" } as const;\n\n")
|
||||
}
|
||||
for _, e := range d.Events {
|
||||
subj := seatdef.EventSubject(d.Seat, e.Name)
|
||||
if e.ByCaller {
|
||||
fmt.Fprintf(&b, "export function %sSubject(caller: string): string {\n return %q + caller;\n}\n\n", tsName(e.Name), subj+".")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "export const %sSubject = %q;\n\n", tsName(e.Name), subj)
|
||||
}
|
||||
}
|
||||
for _, a := range d.Accepts {
|
||||
subj := seatdef.AcceptSubject(d.Seat, a.Name)
|
||||
if a.ByCaller {
|
||||
fmt.Fprintf(&b, "export function %sSubject(caller: string): string {\n return %q + caller;\n}\n\n", tsName(a.Name), subj+".")
|
||||
} else {
|
||||
fmt.Fprintf(&b, "export const %sSubject = %q;\n\n", tsName(a.Name), subj)
|
||||
}
|
||||
}
|
||||
if len(d.HolderEvents) > 0 {
|
||||
tsNames(&b, "holderEvents", holderNames(d.HolderEvents))
|
||||
for _, e := range d.HolderEvents {
|
||||
before, after, _ := strings.Cut(e.Subject, "<holder>")
|
||||
fmt.Fprintf(&b, "export function %sHolderSubject(holder: string): string {\n return %q + holder + %q;\n}\n\n",
|
||||
tsName(e.Name), before, after)
|
||||
}
|
||||
}
|
||||
for _, n := range sortedKeys(fromPart) {
|
||||
fmt.Fprintf(&b, "export type %s = %s.%s;\n", n, tsName(fromPart[n]), n)
|
||||
}
|
||||
if len(fromPart) > 0 {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
tsTypes(&b, tp)
|
||||
out[dir+"/src/index.ts"] = b.Bytes()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func holderNames(es []seatdef.HolderEvent) []string {
|
||||
out := make([]string, len(es))
|
||||
for i, e := range es {
|
||||
out[i] = e.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func tsNames(b *bytes.Buffer, what string, names []string) {
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(b, "export const %s = {\n", what)
|
||||
for _, n := range names {
|
||||
fmt.Fprintf(b, " %s: %q,\n", tsName(n), n)
|
||||
}
|
||||
b.WriteString("} as const;\n\n")
|
||||
}
|
||||
|
||||
func tsTypes(b *bytes.Buffer, tp *typer) {
|
||||
for _, t := range tp.types {
|
||||
if d := strings.TrimSpace(t.desc); d != "" {
|
||||
fmt.Fprintf(b, "/** %s */\n", oneLine(d))
|
||||
}
|
||||
if t.t.kind != "struct" {
|
||||
fmt.Fprintf(b, "export type %s = %s;\n\n", t.name, tsType(t.t))
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "export interface %s {\n", t.name)
|
||||
for _, f := range t.t.fields {
|
||||
if f.desc != "" {
|
||||
fmt.Fprintf(b, " /** %s */\n", oneLine(f.desc))
|
||||
}
|
||||
opt := "?"
|
||||
if f.required {
|
||||
opt = ""
|
||||
}
|
||||
fmt.Fprintf(b, " %s%s: %s;\n", strconv.Quote(f.json), opt, tsType(f.t))
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
func tsType(t *typ) string {
|
||||
switch t.kind {
|
||||
case "string":
|
||||
if len(t.enum) > 0 {
|
||||
parts := make([]string, len(t.enum))
|
||||
for i, e := range t.enum {
|
||||
parts[i] = strconv.Quote(e)
|
||||
}
|
||||
return strings.Join(parts, " | ")
|
||||
}
|
||||
return "string"
|
||||
case "integer", "number":
|
||||
return "number"
|
||||
case "boolean":
|
||||
return "boolean"
|
||||
case "object":
|
||||
return "Record<string, unknown>"
|
||||
case "map":
|
||||
return "Record<string, " + tsType(t.elem) + ">"
|
||||
case "slice":
|
||||
el := tsType(t.elem)
|
||||
if strings.Contains(el, "|") {
|
||||
el = "(" + el + ")"
|
||||
}
|
||||
return el + "[]"
|
||||
case "ref":
|
||||
return t.ref
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// tsSeatList is ts/src/seats.ts: the seat list as data, and every seat's name.
|
||||
func tsSeatList(m *Module) []byte {
|
||||
var b bytes.Buffer
|
||||
b.WriteString(tsHeader)
|
||||
b.WriteString(`// The mesh's seat list, generated from every seat's definition (design 26).
|
||||
|
||||
export interface Verb {
|
||||
name: string;
|
||||
description: string;
|
||||
input?: Record<string, unknown>;
|
||||
output?: Record<string, unknown>;
|
||||
optional?: boolean;
|
||||
replaces?: string[];
|
||||
}
|
||||
|
||||
export interface Seat {
|
||||
name: string;
|
||||
scope: "mesh" | "node";
|
||||
grain: "whole" | "seat-list";
|
||||
decision: string;
|
||||
delivers?: string;
|
||||
replicated?: boolean;
|
||||
accepts?: string[];
|
||||
emits?: string[];
|
||||
pulledByKind?: boolean;
|
||||
yields?: boolean;
|
||||
heldByTheEngine?: boolean;
|
||||
serves?: Verb[];
|
||||
}
|
||||
|
||||
`)
|
||||
b.WriteString("export const names = {\n")
|
||||
for _, n := range m.Order {
|
||||
fmt.Fprintf(&b, " %s: %q,\n", tsName(n), n)
|
||||
}
|
||||
b.WriteString("} as const;\n\nexport const list: readonly Seat[] = ")
|
||||
var list []map[string]any
|
||||
for _, n := range m.Order {
|
||||
d := m.Seats[n]
|
||||
if d.HolderDeclares {
|
||||
continue
|
||||
}
|
||||
e := map[string]any{"name": d.Seat, "scope": d.Scope, "grain": d.Grain, "decision": d.Decision}
|
||||
if d.Delivers != "" {
|
||||
e["delivers"] = d.Delivers
|
||||
}
|
||||
if d.Replicated {
|
||||
e["replicated"] = true
|
||||
}
|
||||
if len(d.Accepts) > 0 {
|
||||
e["accepts"] = seatdef.MessageNames(d.Accepts)
|
||||
}
|
||||
if len(d.Events) > 0 {
|
||||
e["emits"] = seatdef.MessageNames(d.Events)
|
||||
}
|
||||
if d.PulledByKind {
|
||||
e["pulledByKind"] = true
|
||||
}
|
||||
if d.Yields {
|
||||
e["yields"] = true
|
||||
}
|
||||
if d.HeldByTheEngine {
|
||||
e["heldByTheEngine"] = true
|
||||
}
|
||||
var verbs []map[string]any
|
||||
for _, v := range d.Verbs {
|
||||
vm := map[string]any{"name": v.Name, "description": v.Description}
|
||||
if v.Input != nil {
|
||||
vm["input"] = resolveRefs(v.Input, d.Defs)
|
||||
}
|
||||
if v.Answer != nil {
|
||||
vm["output"] = resolveRefs(v.Answer, d.Defs)
|
||||
}
|
||||
if v.Optional {
|
||||
vm["optional"] = true
|
||||
}
|
||||
if len(v.Replaces) > 0 {
|
||||
vm["replaces"] = v.Replaces
|
||||
}
|
||||
verbs = append(verbs, vm)
|
||||
}
|
||||
if len(verbs) > 0 {
|
||||
e["serves"] = verbs
|
||||
}
|
||||
list = append(list, e)
|
||||
}
|
||||
enc := json.NewEncoder(&b)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(list)
|
||||
b.Truncate(b.Len() - 1)
|
||||
b.WriteString(";\n")
|
||||
return b.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package seatgen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A typ is one JSON Schema read as a type both languages write: the subset the definitions use (objects with
|
||||
// properties, maps, arrays, strings, integers, numbers, booleans, references to a definition's own types). Anything
|
||||
// else is `any`, so a schema the generator does not understand still decodes.
|
||||
type typ struct {
|
||||
kind string // string, integer, number, boolean, any, map, slice, struct, ref, object (free)
|
||||
elem *typ // a map's value or a slice's item
|
||||
ref string // a referenced type's name
|
||||
fields []field
|
||||
enum []string
|
||||
}
|
||||
|
||||
type field struct {
|
||||
json string
|
||||
required bool
|
||||
desc string
|
||||
t *typ
|
||||
}
|
||||
|
||||
// named is one type a seat's package declares: a struct, or an alias of another.
|
||||
type named struct {
|
||||
name string
|
||||
desc string
|
||||
t *typ
|
||||
}
|
||||
|
||||
// typer reads schemas into named types, naming each inline object by where it sits.
|
||||
type typer struct {
|
||||
types []named
|
||||
taken map[string]bool
|
||||
}
|
||||
|
||||
func newTyper() *typer { return &typer{taken: map[string]bool{}} }
|
||||
|
||||
// declare reads schema s as the type called name and declares it.
|
||||
func (tp *typer) declare(name, desc string, s map[string]any) error {
|
||||
if tp.taken[name] {
|
||||
return fmt.Errorf("two types would be called %s", name)
|
||||
}
|
||||
tp.taken[name] = true
|
||||
t, err := tp.read(name, s, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
if desc == "" {
|
||||
desc, _ = s["description"].(string)
|
||||
}
|
||||
tp.types = append(tp.types, named{name: name, desc: desc, t: t})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tp *typer) read(where string, s map[string]any, top bool) (*typ, error) {
|
||||
if s == nil {
|
||||
return &typ{kind: "any"}, nil
|
||||
}
|
||||
if r, ok := s["$ref"].(string); ok {
|
||||
n, found := strings.CutPrefix(r, "#/defs/")
|
||||
if !found || n == "" {
|
||||
return nil, fmt.Errorf("$ref %q is not #/defs/<name>", r)
|
||||
}
|
||||
return &typ{kind: "ref", ref: n}, nil
|
||||
}
|
||||
t, _ := s["type"].(string)
|
||||
switch t {
|
||||
case "string":
|
||||
out := &typ{kind: "string"}
|
||||
if e, ok := s["enum"].([]any); ok {
|
||||
for _, v := range e {
|
||||
if str, ok := v.(string); ok {
|
||||
out.enum = append(out.enum, str)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
case "integer", "number", "boolean":
|
||||
return &typ{kind: t}, nil
|
||||
case "array":
|
||||
items, _ := s["items"].(map[string]any)
|
||||
el, err := tp.inline(where+"Item", items)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &typ{kind: "slice", elem: el}, nil
|
||||
case "object":
|
||||
props, hasProps := s["properties"].(map[string]any)
|
||||
if !hasProps {
|
||||
if ap, ok := s["additionalProperties"].(map[string]any); ok {
|
||||
el, err := tp.inline(where+"Value", ap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &typ{kind: "map", elem: el}, nil
|
||||
}
|
||||
return &typ{kind: "object"}, nil
|
||||
}
|
||||
required := map[string]bool{}
|
||||
switch r := s["required"].(type) {
|
||||
case []any:
|
||||
for _, v := range r {
|
||||
if str, ok := v.(string); ok {
|
||||
required[str] = true
|
||||
}
|
||||
}
|
||||
case []string:
|
||||
for _, v := range r {
|
||||
required[v] = true
|
||||
}
|
||||
}
|
||||
names := make([]string, 0, len(props))
|
||||
for k := range props {
|
||||
names = append(names, k)
|
||||
}
|
||||
sort.Strings(names)
|
||||
out := &typ{kind: "struct"}
|
||||
for _, k := range names {
|
||||
ps, _ := props[k].(map[string]any)
|
||||
ft, err := tp.inline(where+ident(k), ps)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
desc, _ := ps["description"].(string)
|
||||
out.fields = append(out.fields, field{json: k, required: required[k], desc: desc, t: ft})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
return &typ{kind: "any"}, nil
|
||||
}
|
||||
|
||||
// inline is a nested schema's type: an object with properties becomes a named type of its own, called where.
|
||||
func (tp *typer) inline(where string, s map[string]any) (*typ, error) {
|
||||
if s != nil {
|
||||
if _, props := s["properties"].(map[string]any); props && s["type"] == "object" {
|
||||
desc, _ := s["description"].(string)
|
||||
if err := tp.declare(where, desc, s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &typ{kind: "ref", ref: where}, nil
|
||||
}
|
||||
}
|
||||
return tp.read(where, s, false)
|
||||
}
|
||||
|
||||
// resolveRefs is a schema with every reference to a definition's own type replaced by that type, for the seat list
|
||||
// a reader shows: a caller reading a verb's input there never meets a reference it cannot follow.
|
||||
func resolveRefs(s map[string]any, defs map[string]map[string]any) map[string]any {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
v := resolveValue(s, defs, 0)
|
||||
m, _ := v.(map[string]any)
|
||||
return m
|
||||
}
|
||||
|
||||
func resolveValue(v any, defs map[string]map[string]any, depth int) any {
|
||||
if depth > 32 {
|
||||
return v
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
if r, ok := x["$ref"].(string); ok {
|
||||
if d, ok := defs[strings.TrimPrefix(r, "#/defs/")]; ok {
|
||||
return resolveValue(d, defs, depth+1)
|
||||
}
|
||||
}
|
||||
out := make(map[string]any, len(x))
|
||||
for k, e := range x {
|
||||
out[k] = resolveValue(e, defs, depth+1)
|
||||
}
|
||||
return out
|
||||
case []any:
|
||||
out := make([]any, len(x))
|
||||
for i, e := range x {
|
||||
out[i] = resolveValue(e, defs, depth+1)
|
||||
}
|
||||
return out
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -83,6 +83,12 @@ func finish(put Put, key string, step delivery.Step, result any, err error, logf
|
||||
step.State, step.Reason = delivery.StepRefused, err.Error()
|
||||
default:
|
||||
step.State, step.Reason = delivery.StepFailed, err.Error()
|
||||
// A failed step may answer what it found on the way (a build's out-of-step files): kept on its end.
|
||||
if result != nil {
|
||||
if raw, merr := json.Marshal(result); merr == nil {
|
||||
step.Result = raw
|
||||
}
|
||||
}
|
||||
}
|
||||
werr := writeEnd(put, key, step)
|
||||
if werr == nil {
|
||||
|
||||
@@ -77,7 +77,7 @@ func (m *Module) buildArchive(ctx context.Context, workspace, module, name, dir
|
||||
if !within(realDir, realRoot) {
|
||||
return nil, fmt.Errorf("the archive %s is taken from %q, which lies outside the module: it resolves to %s, and the module is %s", art.Name, art.From, realRoot, realDir)
|
||||
}
|
||||
return m.packInto(ctx, workspace, module, name, art.Name, root)
|
||||
return m.packInto(ctx, workspace, module, name, art.Name, "archive", root)
|
||||
}
|
||||
|
||||
// pinnedArchive fetches the file an artifact is pinned to, checks it against the pin, lays it out as the artifact says
|
||||
@@ -111,7 +111,7 @@ func (m *Module) pinnedArchive(ctx context.Context, workspace, module, name stri
|
||||
} else if err := unpackUpstream(file, laid, art.Within); err != nil {
|
||||
return nil, fmt.Errorf("%s: %s (%s): %w", art.Name, art.URL, art.Version, err)
|
||||
}
|
||||
return m.packInto(ctx, workspace, module, name, art.Name, laid)
|
||||
return m.packInto(ctx, workspace, module, name, art.Name, "archive", laid)
|
||||
}
|
||||
|
||||
// pinnedFile is the path of the pinned file in the workspace: kept from an earlier build when its bytes are still the
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep"
|
||||
@@ -38,6 +39,7 @@ func (m *Module) askSteps(steps []StepTool) buildstep.AskSteps {
|
||||
return buildstep.AskSteps{
|
||||
Fetch: byName["build_go_fetch"], Build: byName["build_go_build"], Digest: byName["build_go_digest"], Test: byName["build_go_test"],
|
||||
Imports: byName[ImportsTool],
|
||||
Compare: buildstep.CompareStep(buildstep.GeneratedRootGo, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }),
|
||||
Toolchain: func(ctx context.Context) (delivery.ToolchainUsed, error) {
|
||||
installed, err := m.Probe(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -34,23 +34,27 @@ type BuildResult struct {
|
||||
Binary string `json:"binary"`
|
||||
Digest string `json:"digest"`
|
||||
Size int `json:"size"`
|
||||
// Reference is where the archive is in the artifact store (novox/hq ADR 0498 §1):
|
||||
// artifact-store://<module>/<artifact>/blobs/<digest>.
|
||||
// Reference is where the archive is, in the form the seat it was published through answers (novox/hq ADR 0605
|
||||
// §9): oci-artifact-registry/<module>/<artifact>@<digest>. The builder writes the older form beside it while a
|
||||
// counted node-engine reads only that (ADR 0624 §1, §3).
|
||||
Reference string `json:"reference"`
|
||||
}
|
||||
|
||||
func (m *Module) buildTool() StepTool {
|
||||
return StepTool{
|
||||
Name: "build_go_build",
|
||||
Description: "Build one Go bundle or archive artifact of a module of a fetched workspace with the build agent's recipe, by the " +
|
||||
"installed Go and no network, and pack it. Answers a step id at once; the step ends on its key with the " +
|
||||
"artifact's digest, size and the archive's path.",
|
||||
Description: "Build one Go bundle, archive or Go package artifact of a module of a fetched workspace with the build agent's " +
|
||||
"recipe, by the installed Go and no network, and pack it (a Go package as Go's module zip); a bundle or archive is " +
|
||||
"published on oci-artifact-registry, a Go package given a version on go-package-registry under its module path. " +
|
||||
"Answers a step id at once; the step ends on its key with the artifact's digest, size and reference.",
|
||||
Input: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"workspace": map[string]any{"type": "string", "description": "the workspace id build_go_fetch answered"},
|
||||
"module": map[string]any{"type": "string", "description": "the module's directory in the workspace, . for the repository's root"},
|
||||
"artifact": map[string]any{"type": "string", "description": "the artifact's name in the module's manifest"},
|
||||
"version": map[string]any{"type": "string", "description": "the version the builder gave a package at the trunk's claim; absent for a candidate, whose package is not published"},
|
||||
"seat": map[string]any{"type": "string", "description": "the registry seat the artifact is published through, as the build ask names it"},
|
||||
"publish": map[string]any{"type": "boolean", "description": "true for a merged trunk commit alone: the build writes the shared Go caches; without it (a candidate) they are read beneath a throwaway layer"},
|
||||
},
|
||||
"required": []string{"workspace", "module", "artifact"},
|
||||
@@ -109,6 +113,11 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) {
|
||||
if art == nil {
|
||||
return nil, fmt.Errorf("the module %s has no artifact %q (it has %s)", manifest.Module, name, strings.Join(names, ", "))
|
||||
}
|
||||
if art.Kind == catalogue.ArtifactPackage && art.Language == "go" {
|
||||
version, _ := args["version"].(string)
|
||||
seat, _ := args["seat"].(string)
|
||||
return m.buildGoPackage(ctx, workspace, dir, *art, version, seat)
|
||||
}
|
||||
if art.Kind == "archive" {
|
||||
return m.buildArchive(ctx, workspace, module, manifest.Module, dir, *art)
|
||||
}
|
||||
@@ -149,7 +158,7 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) {
|
||||
if err := m.insideModule(workspace, dir, out); err != nil {
|
||||
return nil, fmt.Errorf("the output directory of %s: %w", art.Name, err)
|
||||
}
|
||||
res, err := m.packInto(ctx, workspace, module, manifest.Module, art.Name, out)
|
||||
res, err := m.packInto(ctx, workspace, module, manifest.Module, art.Name, "bundle", out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -157,20 +166,20 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// packInto packs a directory with mesh-sdk's Pack, as the build agent packs every artifact, and pushes the archive to
|
||||
// the artifact store from this process, after the build step ended (novox/hq ADR 0498 §1 §2): a candidate's as a trunk
|
||||
// build's, under <module>/<artifact> by its digest. The step answers the reference; a push that fails fails the step
|
||||
// `not stored:`. The packed bytes never stay on the node: they are held in this process until the push answered (the
|
||||
// lead's decision L9).
|
||||
func (m *Module) packInto(ctx context.Context, workspace, module, name, artifact, root string) (BuildResult, error) {
|
||||
// packInto packs a directory with mesh-sdk's Pack, as the build agent packs every artifact, and publishes the archive
|
||||
// on the seat oci-artifact-registry from this process, after the build step ended (design 51 *Publishing*; publish.go):
|
||||
// a candidate's as a trunk build's, under <module>/<artifact> by its digest, of kind (bundle or archive). The step
|
||||
// answers the reference; a publish the seat refuses fails the step `not stored:`. The packed bytes never stay on the
|
||||
// node: they are held in this process until the publish answered (the lead's decision L9).
|
||||
func (m *Module) packInto(ctx context.Context, workspace, module, name, artifact, kind, root string) (BuildResult, error) {
|
||||
archive, digest, err := buildstep.Pack(root)
|
||||
if err != nil {
|
||||
return BuildResult{}, fmt.Errorf("packing %s: %w", artifact, err)
|
||||
}
|
||||
if err := m.push(ctx, name+"/"+artifact, digest, archive); err != nil {
|
||||
if err := m.publishArchive(ctx, name, artifact, kind, digest, archive); err != nil {
|
||||
return BuildResult{}, fmt.Errorf("%s%s: %v", delivery.NotStored, artifact, err)
|
||||
}
|
||||
return BuildResult{Artifact: artifact, Digest: digest, Size: len(archive), Reference: buildstep.BlobReference(name, artifact, digest)}, nil
|
||||
return BuildResult{Artifact: artifact, Digest: digest, Size: len(archive), Reference: catalogue.SeatReference(ArtifactSeat, name, artifact, digest)}, nil
|
||||
}
|
||||
|
||||
// buildEnv is the environment of the compile: the build agent's (CGO_ENABLED=0, GOFLAGS) with the installed go
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -310,15 +311,58 @@ func (m *Module) goEnv() []string {
|
||||
if m.GoModCache != "" {
|
||||
modcache = m.GoModCache
|
||||
}
|
||||
return append([]string{
|
||||
env := []string{
|
||||
"GOTOOLCHAIN=local",
|
||||
"GOFLAGS=-mod=mod",
|
||||
"GOMODCACHE=" + modcache,
|
||||
"GOCACHE=" + filepath.Join(m.Cache, "gobuild"),
|
||||
"GOPRIVATE=git.novox.be",
|
||||
"GIT_TERMINAL_PROMPT=0",
|
||||
"GIT_SSH_COMMAND=ssh -o BatchMode=yes",
|
||||
}, m.threadEnv()...)
|
||||
}
|
||||
if proxy := m.goSeat(); proxy != "" {
|
||||
// The Go seat first, the public proxy second, the forge's git last (CAT-BG3, E11: direct goes in the first
|
||||
// change after mesh-sdk's and mesh-contracts' first numbered versions are in the Go seat); no GOPRIVATE, and
|
||||
// the checksum database off for the forge's paths, which go.sum and the builder's h1: digest guard instead.
|
||||
env = append(env, "GOPROXY="+proxy+","+PublicGoProxy+",direct", "GONOSUMDB="+ForgeGoPaths, "GOPRIVATE=")
|
||||
} else {
|
||||
env = append(env, "GOPRIVATE="+ForgeGoPaths)
|
||||
}
|
||||
return append(append(env, "GIT_TERMINAL_PROMPT=0", "GIT_SSH_COMMAND=ssh -o BatchMode=yes"), m.threadEnv()...)
|
||||
}
|
||||
|
||||
// PublicGoProxy is Go's public module proxy; ForgeGoPaths the module paths the forge serves.
|
||||
const (
|
||||
PublicGoProxy = "https://proxy.golang.org"
|
||||
ForgeGoPaths = "git.novox.be"
|
||||
)
|
||||
|
||||
// goSeat is the Go seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the
|
||||
// module holds no binding of it or the binding names no address.
|
||||
func (m *Module) goSeat() string {
|
||||
if m.GoSeatFile == "" {
|
||||
return ""
|
||||
}
|
||||
raw, err := os.ReadFile(m.GoSeatFile)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var b struct {
|
||||
At string `json:"at"`
|
||||
Serves struct {
|
||||
Scheme string `json:"scheme"`
|
||||
Port int `json:"port"`
|
||||
GoPath string `json:"go-path"`
|
||||
} `json:"serves"`
|
||||
}
|
||||
if json.Unmarshal(raw, &b) != nil || b.At == "" || b.Serves.GoPath == "" {
|
||||
return ""
|
||||
}
|
||||
scheme := b.Serves.Scheme
|
||||
if scheme == "" {
|
||||
scheme = "http"
|
||||
}
|
||||
if b.Serves.Port == 0 {
|
||||
return fmt.Sprintf("%s://%s%s", scheme, b.At, b.Serves.GoPath)
|
||||
}
|
||||
return fmt.Sprintf("%s://%s:%d%s", scheme, b.At, b.Serves.Port, b.Serves.GoPath)
|
||||
}
|
||||
|
||||
// goEnvFor is goEnv for a command run in dir: a directory that vendors (vendor/modules.txt) is read from its vendor
|
||||
|
||||
@@ -145,6 +145,20 @@ func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// CAT-BG3: with the Go seat bound, the fetch goes through it first, Go's public proxy second and the forge's git
|
||||
// last, with no GOPRIVATE and the checksum database off for the forge's paths.
|
||||
seat := filepath.Join(t.TempDir(), "go-package-registry.json")
|
||||
if err := os.WriteFile(seat, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.GoSeatFile = seat
|
||||
env := strings.Join(m.goEnv(), " ")
|
||||
for _, want := range []string{"GOPROXY=http://forge.mesh:3000/api/packages/novox/go,https://proxy.golang.org,direct", "GONOSUMDB=git.novox.be", "GOPRIVATE= "} {
|
||||
if !strings.Contains(env+" ", want) {
|
||||
t.Errorf("with the Go seat bound the environment lacks %q: %s", want, env)
|
||||
}
|
||||
}
|
||||
m.GoSeatFile = ""
|
||||
if downloads != 2 || verifies != 2 {
|
||||
t.Errorf("%d downloads and %d verifies, want 2 each (go.mod and sub/dir/go.mod):\n%s", downloads, verifies, lines)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -143,10 +144,10 @@ func TestForgeFilesRenderFromTheBoundValuesInTheModulesOwnHome(t *testing.T) {
|
||||
// template in the files/ archive (novox/hq ADR 0349 §2).
|
||||
func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *testing.T) {
|
||||
m := readForgeManifest(t)
|
||||
// artifact-store: the module pushes a done build's archive itself (ADR 0498 §2).
|
||||
// node-tools: the module pulls its asks through the tool runner's seat pull (1911).
|
||||
if len(m.Requires) != 4 || m.Requires[0] != "forge-account" || m.Requires[1] != "go-toolchain" || m.Requires[2] != "artifact-store" || m.Requires[3] != "node-tools" {
|
||||
t.Errorf("requires = %v, want [forge-account go-toolchain artifact-store node-tools]", m.Requires)
|
||||
// go-package-registry: the Go seat's read side, the fetch's first source (design 51, CAT-BG3, E2).
|
||||
if want := []any{"forge-account", "go-toolchain", "go-package-registry", "node-tools"}; !slices.Equal(m.Requires, want) {
|
||||
t.Errorf("requires = %v, want %v", m.Requires, want)
|
||||
}
|
||||
keeps := false
|
||||
for _, s := range m.State {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
// The build of a Go package (CAT-BG2; novox/hq design 51 *Publishing*, ADR 0605 §3, §9): the directory the artifact
|
||||
// names (its one path, else the module's own) packed as Go's module zip, every file under <module path>@<version>/,
|
||||
// as Go's module proxy protocol serves it; its digest is the zip's sha256 (no h1: sum is answered: nothing in the contract carries
|
||||
// it on, the lead's ruling on A3n). A
|
||||
// trunk build given a version by the builder publishes it through go-package-registry under its Go module path (the
|
||||
// name the forge's Go seat takes, the lead's ruling 3 on A3k) and that version; a candidate's publishes nothing. The
|
||||
// zip is made in this process, after nothing ran: packing a tree runs no code of it.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/mod/modfile"
|
||||
"golang.org/x/mod/module"
|
||||
modzip "golang.org/x/mod/zip"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
// GoPackageSeat is the registry seat a Go package is published on.
|
||||
const GoPackageSeat = "go-package-registry"
|
||||
|
||||
// candidateVersion is the version a candidate's zip is laid out under: no version was given, and nothing is published.
|
||||
const candidateVersion = "v0.0.0"
|
||||
|
||||
func (m *Module) buildGoPackage(ctx context.Context, workspace, dir string, art catalogue.Artifact, version, seat string) (BuildResult, error) {
|
||||
root := dir
|
||||
switch len(art.Paths) {
|
||||
case 0:
|
||||
case 1:
|
||||
root = filepath.Join(dir, filepath.FromSlash(strings.TrimSuffix(art.Paths[0], "/")))
|
||||
default:
|
||||
return BuildResult{}, fmt.Errorf("the Go package %s names %d paths; a Go package is one directory holding its go.mod", art.Name, len(art.Paths))
|
||||
}
|
||||
if err := m.insideModule(workspace, dir, root); err != nil {
|
||||
return BuildResult{}, fmt.Errorf("the directory of %s: %w", art.Name, err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(root, "go.mod"))
|
||||
if err != nil {
|
||||
return BuildResult{}, fmt.Errorf("the Go package %s has no go.mod in %s: %w", art.Name, art.Paths, err)
|
||||
}
|
||||
path := modfile.ModulePath(raw)
|
||||
if path == "" {
|
||||
return BuildResult{}, fmt.Errorf("the go.mod of the Go package %s names no module", art.Name)
|
||||
}
|
||||
if version != "" && seat != GoPackageSeat {
|
||||
return BuildResult{}, fmt.Errorf("the Go package %s is given the version %s and the seat %q: a Go package is published through %s", art.Name, version, seat, GoPackageSeat)
|
||||
}
|
||||
zipVersion := candidateVersion
|
||||
if version != "" {
|
||||
zipVersion = "v" + strings.TrimPrefix(version, "v")
|
||||
}
|
||||
file, err := os.CreateTemp(filepath.Join(m.Work, workspace), "gopackage-*.zip")
|
||||
if err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
defer os.Remove(file.Name()) // the packed file never stays on the node (the lead's decision L9)
|
||||
defer file.Close()
|
||||
if err := modzip.CreateFromDir(file, module.Version{Path: path, Version: zipVersion}, root); err != nil {
|
||||
return BuildResult{}, fmt.Errorf("packing the Go package %s (%s@%s): %w", art.Name, path, zipVersion, err)
|
||||
}
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
body, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
d := sha256.Sum256(body)
|
||||
digest := "sha256:" + hex.EncodeToString(d[:])
|
||||
res := BuildResult{Artifact: art.Name, Digest: digest, Size: len(body)}
|
||||
if version == "" {
|
||||
return res, nil
|
||||
}
|
||||
if err := m.publishOn(ctx, seat, path, "package", version, digest, transferName(path, version, digest), body); err != nil {
|
||||
return BuildResult{}, fmt.Errorf("%s%s: %v", delivery.NotStored, art.Name, err)
|
||||
}
|
||||
res.Reference = path + "@" + version
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
// The late publish (CAT-BG2): a numbered bundle or archive's held digest published under its version, by the build
|
||||
// modules' one late publish (buildstep/latepublish.go).
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// NumberedPattern is the event type this module consumes for the late publish, as its manifest's `consumes` names it.
|
||||
const NumberedPattern = buildstep.NumberedPattern
|
||||
|
||||
// LatePublish publishes a numbered bundle or archive's held digest under its version on the artifact seat; a Go package
|
||||
// publishes at its build, an image is mesh-build-image's.
|
||||
func (m *Module) LatePublish(ctx context.Context, body []byte) (bool, error) {
|
||||
call := m.Call
|
||||
if call == nil {
|
||||
call = stdio.Ask
|
||||
}
|
||||
return buildstep.LatePublish(ctx, call, body, ArtifactSeat, "bundle", "archive")
|
||||
}
|
||||
|
||||
// hearNumbered hears the builder's version.numbered for the late publish.
|
||||
func (m *Module) hearNumbered(ctx context.Context) { buildstep.HearNumbered(ctx, m.LatePublish) }
|
||||
@@ -72,6 +72,9 @@ type TestResult struct {
|
||||
// JudgedBy is the program that ran the level (ADR 0535 §5): "installed", or "candidate <merge commit>" under the
|
||||
// runner workspace.
|
||||
JudgedBy string `json:"judged_by,omitempty"`
|
||||
// OutOfStep are the generated files of a contracts module in the workspace out of step with what the generator writes
|
||||
// (CAT-BG5, buildstep.OutOfStep): the unit level fails on any, Why naming each. Absent when none is.
|
||||
OutOfStep []string `json:"out-of-step,omitempty"`
|
||||
// By is the build module and the SDK it was built with (sdkstep.By): the checker names it when a failure hides
|
||||
// its cause.
|
||||
By string `json:"by,omitempty"`
|
||||
|
||||
@@ -54,7 +54,7 @@ func main() {
|
||||
m.Home = u.HomeDir
|
||||
}
|
||||
m.Run = StepRunner(m.Home)
|
||||
m.RegistryFile = m.Home + "/registry"
|
||||
m.GoSeatFile = m.Home + "/go-package-registry.json"
|
||||
m.Settings = m.Home + "/settings.json"
|
||||
m.ReadKept = readOf(stdio.State(KeptState)).Get
|
||||
m.ReadManifest = askManifest
|
||||
@@ -82,6 +82,8 @@ func main() {
|
||||
if m.Node != "" {
|
||||
// The seat's asks, pulled once Serve has the runtime's channel; a pull before it is said and tried again.
|
||||
go func() { _ = puller.Pull(ctx) }()
|
||||
// The builder's version.numbered, for the late publish of a held digest (latepublish.go).
|
||||
go m.hearNumbered(ctx)
|
||||
}
|
||||
if err := stdio.Serve("", append(m.Tools(steps), m.SeatTools(puller)...)); err != nil {
|
||||
logf("%v", err)
|
||||
|
||||
@@ -75,6 +75,17 @@ func TestManifestDeclaresTheAccountTheCapabilityAndThePackages(t *testing.T) {
|
||||
if want := []string{"bubblewrap", "git", "openssh", "postgresql"}; !slices.Equal(packages, want) {
|
||||
t.Errorf("packages = %v, want %v", packages, want)
|
||||
}
|
||||
// buildstep, which mesh-build-node and mesh-build-image require, is a Go package of this module, numbered in
|
||||
// series 0.1 (CAT-BG6; ADR 0606): its users accept a series, never a commit.
|
||||
declared := false
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a.Name == "buildstep" {
|
||||
declared = a.Kind == "package" && a.Language == "go" && slices.Equal(a.Paths, []string{"buildstep"}) && a.Series == "0.1"
|
||||
}
|
||||
}
|
||||
if !declared {
|
||||
t.Errorf("artifacts %+v declare no Go package buildstep in series 0.1", m.Build.Artifacts)
|
||||
}
|
||||
}
|
||||
|
||||
// The work and cache directories are outside the home (ADR 0466 §1), owned by the account.
|
||||
@@ -159,21 +170,32 @@ func TestTheModuleDeclaresBubblewrapAndTheCapabilityItNeeds(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 1587-S1 (ADR 0498 §2): the module requires the artifact store and is told its address in a file of its home, which no
|
||||
// run step is given (a run step has no network either, ADR 0448).
|
||||
func TestTheModuleRequiresTheArtifactStoreAndIsToldItsAddress(t *testing.T) {
|
||||
// 1587-S1, CAT-BG1 (design 51 *Publishing*, ADR 0614 §2): the module publishes a done archive through the seat
|
||||
// oci-artifact-registry's verbs, which it invokes (the served-verb edge orders it after the holder), and no longer
|
||||
// requires the artifact store or is told its address: nothing writes into the store but its holder.
|
||||
func TestTheModuleInvokesTheArtifactSeatsVerbsAndWritesNoStore(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if !slices.Contains(m.Requires, "artifact-store") {
|
||||
t.Errorf("requires %v lack artifact-store", m.Requires)
|
||||
if slices.Contains(m.Requires, "artifact-store") {
|
||||
t.Errorf("requires %v still name artifact-store", m.Requires)
|
||||
}
|
||||
r := resource(t, m, "registry")
|
||||
// The template (files/registry) is read below; decoding leaves it unread in the resource.
|
||||
if r["type"] != "file" || r["path"] != "${dir:state}/registry" || r["template"] != "files/registry" {
|
||||
t.Errorf("the registry resource is %v", r)
|
||||
for _, seat := range []string{ArtifactSeat, GoPackageSeat} { // a Go package's too (CAT-BG2)
|
||||
for _, verb := range []string{"publish", "publish-part"} {
|
||||
if !slices.Contains(m.Invokes, "seat:"+seat+"."+verb) {
|
||||
t.Errorf("invokes %v lack the seat %s's %s", m.Invokes, seat, verb)
|
||||
}
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(moduleDir, "files", "registry"))
|
||||
if err != nil || strings.TrimSpace(string(raw)) != "${seat:mesh-artifact-store:reach}" {
|
||||
t.Errorf("files/registry is %q (%v), want the store seat's reach", raw, err)
|
||||
// The late publish hears the builder's version.numbered (latepublish.go).
|
||||
if !slices.Contains(m.Consumes, NumberedPattern) {
|
||||
t.Errorf("consumes %v lack %s", m.Consumes, NumberedPattern)
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == "registry" {
|
||||
t.Errorf("the store's address is still placed: %v", r)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(moduleDir, "files", "registry")); err == nil {
|
||||
t.Error("files/registry is still shipped")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,10 +67,13 @@ type Module struct {
|
||||
// Inside is the integration level's own process, started shut off in bubblewrap by a test step (level.go): its
|
||||
// commands run as they are, never shut off a second time.
|
||||
Inside bool
|
||||
// RegistryFile holds the artifact store's address (host:port), placed by the manifest; Push puts a blob there
|
||||
// (buildstep.PushBlob when nil; a test's fake store).
|
||||
RegistryFile string
|
||||
Push func(ctx context.Context, registry, repository, digest string, body []byte) error
|
||||
// GoSeatFile is the binding of the provision go-package-registry, the Go seat's read side (design 51 *Go
|
||||
// packages*): bound, the mesh's Go modules are fetched through it first, Go's public proxy second, and the forge's
|
||||
// git over the account's ssh last (Go's direct, kept for this milestone only); unbound, as before, directly.
|
||||
GoSeatFile string
|
||||
// Call asks a seat's verb over the bus: the publish of a done archive (publish.go). stdio.Ask when nil; a test's
|
||||
// fake holder.
|
||||
Call callFunc
|
||||
// Executable is this program's path, which the integration level starts again shut off; os.Executable when empty.
|
||||
Executable string
|
||||
// NodeToolchains is where the Node build module keeps its installed toolchains, bound read-only into the
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
// The publish of a done build's archive (novox/hq design 51 *Publishing*, ADR 0611; CAT-BG1): from this module's own
|
||||
// process, after the build step ended, through the seat oci-artifact-registry's verbs publish and publish-part, which
|
||||
// the manifest `invokes`, with the build modules' one sender (buildstep.PublishOne): the archive in chunks, only what the holder
|
||||
// lacks. No build step reaches the store, and this module no longer writes into it directly (push.go is gone): the
|
||||
// holder checks the build with the builder and says published or refused on the seat's events.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep"
|
||||
)
|
||||
|
||||
// ArtifactSeat is the registry seat a bundle's or an archive's archive is published on.
|
||||
const ArtifactSeat = buildstep.ArtifactSeat
|
||||
|
||||
// transferName is the transfer's name, this module's own (buildstep.TransferName).
|
||||
func transferName(module, artifact, digest string) string {
|
||||
return buildstep.TransferName(module, artifact, digest)
|
||||
}
|
||||
|
||||
// publishArchive publishes body, of digest, as <module>/<artifact> of kind (bundle or archive) on the artifact seat.
|
||||
func (m *Module) publishArchive(ctx context.Context, module, artifact, kind, digest string, body []byte) error {
|
||||
return m.publishOn(ctx, ArtifactSeat, module+"/"+artifact, kind, "", digest, transferName(module, artifact, digest), body)
|
||||
}
|
||||
|
||||
// publishOn publishes body through buildstep.PublishOne: through Call when a test set it, else the runtime's request
|
||||
// over the bus (stdio.Ask).
|
||||
func (m *Module) publishOn(ctx context.Context, seat, name, kind, version, digest, transfer string, body []byte) error {
|
||||
call := m.Call
|
||||
if call == nil {
|
||||
call = stdio.Ask
|
||||
}
|
||||
return buildstep.PublishOne(ctx, call, seat, name, kind, version, digest, transfer, body)
|
||||
}
|
||||
|
||||
// callFunc is the runtime's request and reply over the bus, as stdio.Ask makes it.
|
||||
type callFunc = func(key string, body any) (json.RawMessage, error)
|
||||
@@ -0,0 +1,286 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
registry "git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
// pushed are the blobs the fake artifact store took, by digest, for the tests that read an archive back.
|
||||
var pushed sync.Map
|
||||
|
||||
// fakeStore is the seat oci-artifact-registry's holder as m's publish meets it (publish.go): publish opens a transfer
|
||||
// and answers the part it lacks, publish-part takes the chunks in sequence, and the last one stores the whole part
|
||||
// when it hashes to its digest. Each blob is kept by name and digest; fail, when set, is the holder's refusal at the
|
||||
// last chunk; asked are the addresses m called.
|
||||
type fakeStore struct {
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte // "<name>@<digest>"
|
||||
fail error
|
||||
open map[string]registry.PublishInput
|
||||
chunks map[string][]byte
|
||||
asked []string
|
||||
// published are the publishes whose last chunk was stored, in order.
|
||||
published []registry.PublishInput
|
||||
}
|
||||
|
||||
func withStore(t *testing.T, m *Module) *fakeStore {
|
||||
t.Helper()
|
||||
s := &fakeStore{blobs: map[string][]byte{}, open: map[string]registry.PublishInput{}, chunks: map[string][]byte{}}
|
||||
m.Call = func(key string, body any) (json.RawMessage, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.asked = append(s.asked, key)
|
||||
raw, _ := json.Marshal(body)
|
||||
seat, verb, _ := strings.Cut(strings.TrimPrefix(key, "seat:"), ".")
|
||||
if seat != ArtifactSeat && seat != GoPackageSeat {
|
||||
return nil, errors.New("nats: no responders available for request")
|
||||
}
|
||||
switch verb {
|
||||
case "publish":
|
||||
var in registry.PublishInput
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
if (seat == ArtifactSeat) != (in.Kind == "bundle" || in.Kind == "archive") || in.Transfer == "" || strings.ContainsAny(in.Transfer, "/. *>") {
|
||||
t.Errorf("publish of kind %q, transfer %q", in.Kind, in.Transfer)
|
||||
}
|
||||
s.open[in.Transfer] = in
|
||||
// A digest held under the name already travels no more (the late publish, CAT-BG2).
|
||||
if _, held := s.blobs[in.Name+"@"+in.Digest]; held {
|
||||
s.published = append(s.published, in)
|
||||
return json.Marshal(registry.PublishAnswer{Transfer: in.Transfer, Held: true})
|
||||
}
|
||||
return json.Marshal(registry.PublishAnswer{Transfer: in.Transfer, Lacks: []string{in.Digest}})
|
||||
case "publish-part":
|
||||
var c registry.PublishPartInput
|
||||
_ = json.Unmarshal(raw, &c)
|
||||
data, _ := base64.StdEncoding.DecodeString(c.Data)
|
||||
s.chunks[c.Transfer] = append(s.chunks[c.Transfer], data...)
|
||||
if !c.Last {
|
||||
return json.Marshal(registry.PublishPartAnswer{Transfer: c.Transfer, Part: c.Part})
|
||||
}
|
||||
in, whole := s.open[c.Transfer], s.chunks[c.Transfer]
|
||||
delete(s.chunks, c.Transfer)
|
||||
if s.fail != nil {
|
||||
return nil, s.fail
|
||||
}
|
||||
sum := sha256.Sum256(whole)
|
||||
if "sha256:"+hex.EncodeToString(sum[:]) != in.Digest {
|
||||
t.Errorf("published %s with bytes of another digest", in.Digest)
|
||||
}
|
||||
s.blobs[in.Name+"@"+in.Digest] = whole
|
||||
s.published = append(s.published, in)
|
||||
pushed.Store(in.Digest, whole)
|
||||
return json.Marshal(registry.PublishPartAnswer{Transfer: c.Transfer, Part: c.Part, Complete: true})
|
||||
}
|
||||
return nil, errors.New("nats: no responders available for request")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// archiveOf is the archive a build pushed, by its digest.
|
||||
func archiveOf(t *testing.T, res BuildResult) []byte {
|
||||
t.Helper()
|
||||
raw, ok := pushed.Load(res.Digest)
|
||||
if !ok {
|
||||
t.Fatalf("nothing was pushed under %s", res.Digest)
|
||||
}
|
||||
return raw.([]byte)
|
||||
}
|
||||
|
||||
// 1587-S2 (ADR 0498 §1): a done build answers a reference of the stated form whose tail is the build's digest, and the
|
||||
// store holds the archive there; a bundle and an archive alike.
|
||||
func TestADoneBuildAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
store := withStore(t, m)
|
||||
res, st := runBuild(t, m, states, "tools")
|
||||
if st.State != delivery.StepPassed {
|
||||
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
||||
}
|
||||
if want := "oci-artifact-registry/demo/tools@" + res.Digest; res.Reference != want {
|
||||
t.Errorf("reference %q, want %q", res.Reference, want)
|
||||
}
|
||||
if store.blobs["demo/tools@"+res.Digest] == nil || store.asked[0] != "seat:oci-artifact-registry.publish" {
|
||||
t.Errorf("the seat was asked %v and holds %d blobs, not demo/tools@%s", store.asked, len(store.blobs), res.Digest)
|
||||
}
|
||||
a, states2, _ := archiveModule(t, "")
|
||||
withStore(t, a)
|
||||
arch, st := runBuild(t, a, states2, "files")
|
||||
if st.State != delivery.StepPassed || arch.Reference != "oci-artifact-registry/demo/files@"+arch.Digest {
|
||||
t.Errorf("the archive artifact: %s %q, reference %q", st.State, st.Reason, arch.Reference)
|
||||
}
|
||||
}
|
||||
|
||||
// 1587-S3 (ADR 0498 §2), CAT-BG1: a publish the seat's holder refuses fails the step `not stored: <artifact>: <the
|
||||
// holder's words>`, and so does a seat nothing holds.
|
||||
func TestARefusedPushFailsTheStepNotStored(t *testing.T) {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
store := withStore(t, m)
|
||||
store.fail = errors.New("refused: the forge did not take it: disk full")
|
||||
if _, st := runBuild(t, m, states, "tools"); st.State != delivery.StepFailed || !strings.HasPrefix(st.Reason, delivery.NotStored+"tools: ") || !strings.Contains(st.Reason, "disk full") {
|
||||
t.Errorf("the step ended %s: %q", st.State, st.Reason)
|
||||
}
|
||||
m.Call = func(string, any) (json.RawMessage, error) {
|
||||
return nil, errors.New("nats: no responders available for request")
|
||||
}
|
||||
if _, st := runBuild(t, m, states, "tools"); st.State != delivery.StepFailed || !strings.HasPrefix(st.Reason, delivery.NotStored+"tools: ") ||
|
||||
!strings.Contains(st.Reason, "oci-artifact-registry") {
|
||||
t.Errorf("no holder: the step ended %s: %q", st.State, st.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
// 1587-S4 (the lead's decision L9): the packed file is not left on the node once its push answered, a candidate's
|
||||
// included: the workspace holds no archive, pushed or refused.
|
||||
func TestThePackedFileLeavesTheNodeOnceItsPushAnswered(t *testing.T) {
|
||||
for _, fail := range []error{nil, errors.New("refused")} {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
withStore(t, m).fail = fail
|
||||
runBuild(t, m, states, "tools")
|
||||
var archives []string
|
||||
filepath.WalkDir(m.Work, func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && strings.HasSuffix(p, ".tar.gz") {
|
||||
archives = append(archives, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if len(archives) != 0 {
|
||||
t.Errorf("push answered %v: archives left on the node: %v", fail, archives)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CAT-BG2 (REG S23, ADR 0605 §3, §9; the lead's ruling 3 on A3k): a Go package is built as Go's module zip of the
|
||||
// directory its artifact names, every file under <module path>@<version>/, its digest the zip's.
|
||||
// A trunk build given a version publishes it through go-package-registry under its Go module path and that version,
|
||||
// and answers <module path>@<version>; a candidate's (no version) publishes nothing and answers its digest alone. A
|
||||
// directory with no go.mod fails the step naming it.
|
||||
func TestAGoPackageIsBuiltAsAModuleZipAndPublishedUnderItsModulePath(t *testing.T) {
|
||||
const pkg = `{"name":"go","kind":"package","language":"go","paths":["go"],"series":"0.1"}`
|
||||
m, states, _ := buildModule(t, manifestWith(pkg), "unused")
|
||||
src := filepath.Join(m.Work, "ws1", "tree", "modules", "demo", "go")
|
||||
for name, body := range map[string]string{"go.mod": "module git.example/demo/go\n\ngo 1.26\n", "a.go": "package demo\n",
|
||||
"vendor/x/x.go": "package x\n"} {
|
||||
if err := os.MkdirAll(filepath.Dir(filepath.Join(src, name)), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(src, name), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
run := func(args map[string]any) (BuildResult, delivery.Step) {
|
||||
t.Helper()
|
||||
for _, tool := range m.Tools(m.StepTools()) {
|
||||
if tool.Name == "build_go_build" {
|
||||
if _, err := tool.Run(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
st := states.waitEnd(t)
|
||||
var res BuildResult
|
||||
if st.State == delivery.StepPassed {
|
||||
_ = json.Unmarshal(st.Result, &res)
|
||||
}
|
||||
return res, st
|
||||
}
|
||||
store := withStore(t, m)
|
||||
args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": "go"}
|
||||
cand, st := run(args)
|
||||
if st.State != delivery.StepPassed || !strings.HasPrefix(cand.Digest, "sha256:") || cand.Reference != "" || len(store.asked) != 0 {
|
||||
t.Fatalf("a candidate's Go package: %s %q, %+v, asked %v", st.State, st.Reason, cand, store.asked)
|
||||
}
|
||||
args["version"], args["seat"] = "v0.1.15", GoPackageSeat
|
||||
res, st := run(args)
|
||||
if st.State != delivery.StepPassed || res.Reference != "git.example/demo/go@v0.1.15" {
|
||||
t.Fatalf("a trunk Go package: %s %q, %+v", st.State, st.Reason, res)
|
||||
}
|
||||
if len(store.published) != 1 {
|
||||
t.Fatalf("published %+v", store.published)
|
||||
}
|
||||
in := store.published[0]
|
||||
if in.Name != "git.example/demo/go" || in.Version != "v0.1.15" || in.Kind != "package" || in.Digest != res.Digest {
|
||||
t.Errorf("the publish: %+v", in)
|
||||
}
|
||||
z, err := zip.NewReader(bytes.NewReader(store.blobs[in.Name+"@"+in.Digest]), int64(len(store.blobs[in.Name+"@"+in.Digest])))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, f := range z.File {
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
if strings.Join(names, " ") != "git.example/demo/go@v0.1.15/a.go git.example/demo/go@v0.1.15/go.mod" {
|
||||
t.Errorf("the zip holds %v", names)
|
||||
}
|
||||
if err := os.Remove(filepath.Join(src, "go.mod")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, st := run(args); st.State != delivery.StepFailed || !strings.Contains(st.Reason, "go.mod") {
|
||||
t.Errorf("no go.mod: %s %q", st.State, st.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
// CAT-BG2 (design 51 *The versions*): the builder's version.numbered for a bundle or an archive publishes the held
|
||||
// digest under its version, sending nothing; a digest the holder no longer holds fails the event (offered again),
|
||||
// and what is not this module's to publish is let pass.
|
||||
func TestTheNumberedEventPublishesAHeldDigestUnderItsVersion(t *testing.T) {
|
||||
digest := "sha256:" + strings.Repeat("ab", 32)
|
||||
other := "sha256:" + strings.Repeat("cd", 32)
|
||||
numbered := func(kind, seat, digest string) []byte {
|
||||
raw, err := delivery.EncodeVersionNumbered(delivery.VersionNumbered{Name: "mod/tools", Kind: kind, Version: "0.1.4",
|
||||
Module: "mod", Fingerprint: "fp", Commit: "c0", Digest: digest, Seat: seat})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
body []byte
|
||||
did, fail bool
|
||||
}{
|
||||
{"a held bundle is tagged", numbered("bundle", ArtifactSeat, digest), true, false},
|
||||
{"an archive with no seat named goes to the artifact seat", numbered("archive", "", digest), true, false},
|
||||
{"a digest the holder lacks fails, sending nothing", numbered("bundle", ArtifactSeat, other), false, true},
|
||||
{"a Go package is not published late", numbered("package", GoPackageSeat, digest), false, false},
|
||||
{"an image is mesh-build-image's", numbered("image", "container-image-registry", digest), false, false},
|
||||
{"no digest, nothing to publish", numbered("bundle", ArtifactSeat, ""), false, false},
|
||||
{"an unreadable body fails", []byte(`{"name":"mod/tools"}`), false, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
m := &Module{}
|
||||
s := withStore(t, m)
|
||||
s.blobs["mod/tools@"+digest] = []byte("held")
|
||||
did, err := m.LatePublish(t.Context(), c.body)
|
||||
if did != c.did || (err != nil) != c.fail {
|
||||
t.Fatalf("did %v, err %v; want did %v, fail %v", did, err, c.did, c.fail)
|
||||
}
|
||||
for _, k := range s.asked {
|
||||
if strings.HasSuffix(k, ".publish-part") {
|
||||
t.Errorf("a late publish sent a part: %v", s.asked)
|
||||
}
|
||||
}
|
||||
if !c.did {
|
||||
return
|
||||
}
|
||||
if len(s.published) != 1 {
|
||||
t.Fatalf("published %v", s.published)
|
||||
}
|
||||
p := s.published[0]
|
||||
if p.Name != "mod/tools" || p.Version != "0.1.4" || p.Digest != digest || p.Fingerprint != "fp" || p.Commit != "c0" {
|
||||
t.Errorf("published %+v", p)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package main
|
||||
|
||||
// The push of a done build's archive (novox/hq ADR 0498 §1 §2; issue 1587): from this module's own process, after the
|
||||
// build step ended, with mesh-sdk's one client (buildstep.PushBlob), to the artifact store whose address the manifest
|
||||
// binds into RegistryFile. No build step reaches the store: a run step has no network (ADR 0448).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep"
|
||||
)
|
||||
|
||||
// registry is the artifact store's address, host:port, as the manifest bound it into RegistryFile.
|
||||
func (m *Module) registry() (string, error) {
|
||||
raw, err := os.ReadFile(m.RegistryFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the artifact store's address cannot be read: %w", err)
|
||||
}
|
||||
addr := strings.TrimSpace(string(raw))
|
||||
if addr == "" || strings.Contains(addr, "${") || strings.HasPrefix(addr, ":") || strings.HasSuffix(addr, ":") {
|
||||
return "", fmt.Errorf("the artifact store's address in %s is %q, not host:port", m.RegistryFile, addr)
|
||||
}
|
||||
return addr, nil
|
||||
}
|
||||
|
||||
// push puts body into the artifact store as a blob of repository (<module>/<artifact>) by its digest: Push when a test
|
||||
// set it, else buildstep.PushBlob.
|
||||
func (m *Module) push(ctx context.Context, repository, digest string, body []byte) error {
|
||||
addr, err := m.registry()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.Push != nil {
|
||||
return m.Push(ctx, addr, repository, digest, body)
|
||||
}
|
||||
return buildstep.PushBlob(ctx, &http.Client{Timeout: 10 * time.Minute}, addr, repository, digest, body)
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
// pushed are the blobs the fake artifact store took, by digest, for the tests that read an archive back.
|
||||
var pushed sync.Map
|
||||
|
||||
// fakeStore makes m push to a store of the test's own: its address in RegistryFile, each blob kept by repository and
|
||||
// digest; fail, when set, is the store's refusal.
|
||||
type fakeStore struct {
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte // "<repository>@<digest>"
|
||||
fail error
|
||||
addr string
|
||||
}
|
||||
|
||||
func withStore(t *testing.T, m *Module) *fakeStore {
|
||||
t.Helper()
|
||||
s := &fakeStore{blobs: map[string][]byte{}}
|
||||
m.RegistryFile = filepath.Join(t.TempDir(), "registry")
|
||||
if err := os.WriteFile(m.RegistryFile, []byte("store.test:5000\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Push = func(ctx context.Context, registry, repository, digest string, body []byte) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.addr = registry
|
||||
if s.fail != nil {
|
||||
return s.fail
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
if "sha256:"+hex.EncodeToString(sum[:]) != digest {
|
||||
t.Errorf("pushed %s with bytes of another digest", digest)
|
||||
}
|
||||
s.blobs[repository+"@"+digest] = append([]byte(nil), body...)
|
||||
pushed.Store(digest, s.blobs[repository+"@"+digest])
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// archiveOf is the archive a build pushed, by its digest.
|
||||
func archiveOf(t *testing.T, res BuildResult) []byte {
|
||||
t.Helper()
|
||||
raw, ok := pushed.Load(res.Digest)
|
||||
if !ok {
|
||||
t.Fatalf("nothing was pushed under %s", res.Digest)
|
||||
}
|
||||
return raw.([]byte)
|
||||
}
|
||||
|
||||
// 1587-S2 (ADR 0498 §1): a done build answers a reference of the stated form whose tail is the build's digest, and the
|
||||
// store holds the archive there; a bundle and an archive alike.
|
||||
func TestADoneBuildAnswersTheReferenceOfTheArchiveItPushed(t *testing.T) {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
store := withStore(t, m)
|
||||
res, st := runBuild(t, m, states, "tools")
|
||||
if st.State != delivery.StepPassed {
|
||||
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
||||
}
|
||||
if want := "artifact-store://demo/tools/blobs/" + res.Digest; res.Reference != want {
|
||||
t.Errorf("reference %q, want %q", res.Reference, want)
|
||||
}
|
||||
if store.addr != "store.test:5000" || store.blobs["demo/tools@"+res.Digest] == nil {
|
||||
t.Errorf("the store at %q holds %d blobs, not demo/tools@%s", store.addr, len(store.blobs), res.Digest)
|
||||
}
|
||||
a, states2, _ := archiveModule(t, "")
|
||||
withStore(t, a)
|
||||
arch, st := runBuild(t, a, states2, "files")
|
||||
if st.State != delivery.StepPassed || arch.Reference != "artifact-store://demo/files/blobs/"+arch.Digest {
|
||||
t.Errorf("the archive artifact: %s %q, reference %q", st.State, st.Reason, arch.Reference)
|
||||
}
|
||||
}
|
||||
|
||||
// 1587-S3 (ADR 0498 §2): a push the store refuses fails the step `not stored: <artifact>: <the store's words>`, and so
|
||||
// does a store whose address the manifest did not place.
|
||||
func TestARefusedPushFailsTheStepNotStored(t *testing.T) {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
store := withStore(t, m)
|
||||
store.fail = errors.New("store.test:5000 refused the blob: 500 Internal Server Error disk full")
|
||||
if _, st := runBuild(t, m, states, "tools"); st.State != delivery.StepFailed || !strings.HasPrefix(st.Reason, delivery.NotStored+"tools: ") || !strings.Contains(st.Reason, "disk full") {
|
||||
t.Errorf("the step ended %s: %q", st.State, st.Reason)
|
||||
}
|
||||
m.RegistryFile = filepath.Join(t.TempDir(), "absent")
|
||||
if _, st := runBuild(t, m, states, "tools"); st.State != delivery.StepFailed || !strings.HasPrefix(st.Reason, delivery.NotStored+"tools: ") {
|
||||
t.Errorf("no address: the step ended %s: %q", st.State, st.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
// 1587-S4 (the lead's decision L9): the packed file is not left on the node once its push answered, a candidate's
|
||||
// included: the workspace holds no archive, pushed or refused.
|
||||
func TestThePackedFileLeavesTheNodeOnceItsPushAnswered(t *testing.T) {
|
||||
for _, fail := range []error{nil, errors.New("refused")} {
|
||||
m, states, _ := buildModule(t, manifestWith(goBundle), "the program")
|
||||
withStore(t, m).fail = fail
|
||||
runBuild(t, m, states, "tools")
|
||||
var archives []string
|
||||
filepath.WalkDir(m.Work, func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && strings.HasSuffix(p, ".tar.gz") {
|
||||
archives = append(archives, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if len(archives) != 0 {
|
||||
t.Errorf("push answered %v: archives left on the node: %v", fail, archives)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -19,6 +23,8 @@ import (
|
||||
"github.com/distribution/distribution/v3/registry/handlers"
|
||||
_ "github.com/distribution/distribution/v3/registry/storage/driver/inmemory"
|
||||
|
||||
registry "git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
)
|
||||
|
||||
@@ -34,23 +40,68 @@ func realStore(t *testing.T, m *Module) string {
|
||||
srv := httptest.NewServer(handlers.NewApp(context.Background(), config))
|
||||
t.Cleanup(srv.Close)
|
||||
addr := strings.TrimPrefix(srv.URL, "http://")
|
||||
m.RegistryFile = filepath.Join(t.TempDir(), "registry")
|
||||
if err := os.WriteFile(m.RegistryFile, []byte(addr+"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
// The seat's holder as distribution holds it: the publish through the seat's verbs (publish.go, played by withStore),
|
||||
// each whole part then stored in the store under <module>/<artifact> by its digest.
|
||||
s := withStore(t, m)
|
||||
inner := m.Call
|
||||
m.Call = func(key string, body any) (json.RawMessage, error) {
|
||||
raw, err := inner(key, body)
|
||||
var a registry.PublishPartAnswer
|
||||
if err != nil || !strings.HasSuffix(key, ".publish-part") || json.Unmarshal(raw, &a) != nil || !a.Complete {
|
||||
return raw, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for k, b := range s.blobs {
|
||||
name, digest, _ := strings.Cut(k, "@")
|
||||
if err := uploadBlob(srv.URL, name, digest, b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
delete(s.blobs, k)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
m.Push = nil
|
||||
return addr
|
||||
}
|
||||
|
||||
// resolve reads a done artifact's reference from the store, as the controller will: artifact-store://<module>/
|
||||
// <artifact>/blobs/<digest> is <store>/v2/<module>/<artifact>/blobs/<digest>.
|
||||
// uploadBlob is the holder's own write into its store: an upload opened, then its bytes put by their digest (the
|
||||
// distribution protocol's two requests), as distribution stores a part it took whole.
|
||||
func uploadBlob(base, name, digest string, body []byte) error {
|
||||
resp, err := http.Post(base+"/v2/"+name+"/blobs/uploads/", "", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
loc, err := url.Parse(resp.Header.Get("Location"))
|
||||
if err != nil || resp.StatusCode != http.StatusAccepted {
|
||||
return fmt.Errorf("the store opened no upload of %s: %s %v", digest, resp.Status, err)
|
||||
}
|
||||
b, _ := url.Parse(base)
|
||||
u := b.ResolveReference(loc)
|
||||
q := u.Query()
|
||||
q.Set("digest", digest)
|
||||
u.RawQuery = q.Encode()
|
||||
req, _ := http.NewRequest(http.MethodPut, u.String(), bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
put, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
put.Body.Close()
|
||||
if put.StatusCode != http.StatusCreated {
|
||||
return fmt.Errorf("the store did not take %s: %s", digest, put.Status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolve reads a done artifact's reference from the store as a node-engine does (catalogue.Routed): the seat's form
|
||||
// oci-artifact-registry/<module>/<artifact>@<digest> is <store>/v2/<module>/<artifact>/blobs/<digest> (ADR 0605 §9).
|
||||
func resolve(t *testing.T, addr string, a delivery.BuiltArtifact) []byte {
|
||||
t.Helper()
|
||||
path, ok := strings.CutPrefix(a.Reference, "artifact-store://")
|
||||
if !ok {
|
||||
t.Fatalf("%s's reference %q is not the artifact store's", a.Name, a.Reference)
|
||||
if _, _, ok := catalogue.InRegistrySeat(a.Reference); !ok {
|
||||
t.Fatalf("%s's reference %q is not in the form a registry seat answers", a.Name, a.Reference)
|
||||
}
|
||||
resp, err := http.Get("http://" + addr + "/v2/" + path)
|
||||
resp, err := http.Get(catalogue.Routed(a.Reference, addr))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -101,7 +152,7 @@ func TestADoneBuildsArtifactsResolveInARealArtifactStore(t *testing.T) {
|
||||
t.Errorf("the done key is not deliverable, missing %v", missing)
|
||||
}
|
||||
for _, a := range done.Artifacts {
|
||||
if !strings.HasSuffix(a.Reference, "/blobs/"+a.Digest) {
|
||||
if !strings.HasSuffix(a.Reference, "@"+a.Digest) {
|
||||
t.Errorf("%s: the reference %q does not end in its digest %s", a.Name, a.Reference, a.Digest)
|
||||
}
|
||||
sum := sha256.Sum256(resolve(t, addr, a))
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-catalog/modules/mesh-build-go/buildstep"
|
||||
sdkstep "git.novox.be/novox/mesh-sdk/go/buildstep"
|
||||
"git.novox.be/novox/mesh-sdk/go/delivery"
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
@@ -100,9 +101,42 @@ func (m *Module) test(ctx context.Context, args map[string]any) (any, error) {
|
||||
return nil, err
|
||||
}
|
||||
res.JudgedBy = RunnerInstalled
|
||||
if level == LevelUnit {
|
||||
if err := compareGenerated(tree, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// compareGenerated regenerates the generated Go files of each contracts module in the tree (the tree's own manifest and
|
||||
// each modules/<m>/module.json; CAT-BG5) and fails the level on any out of step, Why naming each path.
|
||||
func compareGenerated(tree string, res *TestResult) error {
|
||||
manifests, _ := filepath.Glob(filepath.Join(tree, "modules", "*", "module.json"))
|
||||
if _, err := os.Stat(filepath.Join(tree, "module.json")); err == nil {
|
||||
manifests = append([]string{filepath.Join(tree, "module.json")}, manifests...)
|
||||
}
|
||||
for _, mf := range manifests {
|
||||
dir := filepath.Dir(mf)
|
||||
paths, err := buildstep.OutOfStep(dir, buildstep.GeneratedRootGo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(tree, dir)
|
||||
for _, p := range paths {
|
||||
res.OutOfStep = append(res.OutOfStep, filepath.ToSlash(filepath.Join(rel, p)))
|
||||
}
|
||||
}
|
||||
if len(res.OutOfStep) > 0 {
|
||||
why := "generated files out of step with the seat generator (regenerate them): " + strings.Join(res.OutOfStep, ", ")
|
||||
if res.Why != "" {
|
||||
why = res.Why + "; " + why
|
||||
}
|
||||
res.Passed, res.Why = false, why
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// testAsCandidate runs a level as the candidate's program (ADR 0535 §1): the integration level is refused first as the
|
||||
// installed program would refuse it (no postgres), then the whole level runs in the candidate's one shut-off process.
|
||||
func (m *Module) testAsCandidate(ctx context.Context, workspace, level string, packages []string, pattern string, names []string) (*TestResult, error) {
|
||||
|
||||
@@ -178,6 +178,40 @@ func TestUnitLevelOfAFixtureWithNoTestsSaysSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// CAT-BG5: a contracts module (a package artifact naming generated-from) whose generated Go files are out of step with
|
||||
// the seat generator fails the unit level, each path named in its out-of-step and its why; its TypeScript is not this
|
||||
// module's to compare.
|
||||
func TestUnitLevelOfAContractsModuleOutOfStepFailsNamingEachPath(t *testing.T) {
|
||||
m, states, ws, _ := workspaceFor(t, "empty")
|
||||
tree := filepath.Join(m.Work, ws, "tree")
|
||||
for p, text := range map[string]string{
|
||||
"module.json": `{"module":"c","build":{"artifacts":[{"name":"go","kind":"package","language":"go","paths":["go"],"generated-from":"."}]}}`,
|
||||
"seats/index.json": `{"format":1,"seats":["one-store"]}`,
|
||||
"seats/one-store/seat.json": `{"format":1,"seat":"one-store","scope":"mesh","grain":"seat-list","decision":"ADR 1","verbs":[{"name":"query","input":{"type":"object"}}]}`,
|
||||
"go/go.mod": "module example.org/c/go\n",
|
||||
"go/stray.go": "package stray\n",
|
||||
"ts/package.json": `{"name":"@example/c"}`,
|
||||
"ts/stray.ts": "// not this module's\n",
|
||||
} {
|
||||
full := filepath.Join(tree, filepath.FromSlash(p))
|
||||
_ = os.MkdirAll(filepath.Dir(full), 0o755)
|
||||
if err := os.WriteFile(full, []byte(text), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
res, st := runUnit(t, m, states, ws)
|
||||
stray := false
|
||||
for _, p := range res.OutOfStep {
|
||||
stray = stray || p == "go/stray.go"
|
||||
if !strings.HasPrefix(p, "go/") {
|
||||
t.Errorf("%s is not under the Go root", p)
|
||||
}
|
||||
}
|
||||
if st.State != delivery.StepPassed || res.Passed || !stray || !strings.Contains(res.Why, "go/stray.go") {
|
||||
t.Errorf("result = %+v (%s %s)", res, st.State, st.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
// A package that does not build fails the level with the compiler's words.
|
||||
func TestUnitLevelOfAPackageThatDoesNotBuildFailsWithTheCompilersLine(t *testing.T) {
|
||||
m, states, ws, _ := workspaceFor(t, "broken")
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
${seat:mesh-artifact-store:reach}
|
||||
@@ -9,9 +9,18 @@ require (
|
||||
github.com/nats-io/nats-server/v2 v2.11.17
|
||||
github.com/nats-io/nats.go v1.54.0
|
||||
github.com/therootcompany/xz v1.0.1
|
||||
golang.org/x/mod v0.42.0
|
||||
)
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/gopackageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/npmpackageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
|
||||
@@ -178,3 +178,5 @@ google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
|
||||
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
"serves": ["current", "pause", "resume"]
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"mesh-delivery-builder.version.numbered"
|
||||
],
|
||||
"reads": [
|
||||
"mesh-delivery-checker.kept"
|
||||
],
|
||||
@@ -68,9 +71,18 @@
|
||||
"requires": [
|
||||
"forge-account",
|
||||
"go-toolchain",
|
||||
"artifact-store",
|
||||
"go-package-registry",
|
||||
"node-tools"
|
||||
],
|
||||
"binds": {
|
||||
"go-package-registry": "${dir:state}/go-package-registry.json"
|
||||
},
|
||||
"invokes": [
|
||||
"seat:oci-artifact-registry.publish",
|
||||
"seat:oci-artifact-registry.publish-part",
|
||||
"seat:go-package-registry.publish",
|
||||
"seat:go-package-registry.publish-part"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:state}/broker"
|
||||
},
|
||||
@@ -158,14 +170,6 @@
|
||||
"mode": "0644",
|
||||
"template": "files/gitconfig"
|
||||
},
|
||||
{
|
||||
"id": "registry",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/registry",
|
||||
"owner": "mesh-build-go",
|
||||
"mode": "0644",
|
||||
"template": "files/registry"
|
||||
},
|
||||
{
|
||||
"id": "git",
|
||||
"type": "package",
|
||||
@@ -204,6 +208,15 @@
|
||||
"name": "files",
|
||||
"kind": "archive",
|
||||
"from": "files"
|
||||
},
|
||||
{
|
||||
"name": "buildstep",
|
||||
"kind": "package",
|
||||
"language": "go",
|
||||
"paths": [
|
||||
"buildstep"
|
||||
],
|
||||
"series": "0.1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user