Compare commits
239
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
474f68b34c | ||
|
|
1a724f20fe | ||
|
|
0da0bb2157 | ||
|
|
118e333ff8 | ||
|
|
c1334f3f85 | ||
|
|
70d379816c | ||
|
|
d8e7c13f6d | ||
|
|
1851a15e57 | ||
|
|
d9dbc9a59a | ||
|
|
d5e1332dda | ||
|
|
5ea0e87059 | ||
|
|
8e81266cdc | ||
|
|
70705ffe45 | ||
|
|
91c4da8a82 | ||
|
|
e9df5dccab | ||
|
|
990ef27cd2 | ||
|
|
0a17a9a2eb | ||
|
|
23907984a3 | ||
|
|
f0634e11f4 | ||
|
|
542ce76c0a | ||
|
|
2882b5fcb1 | ||
|
|
481b1a7b05 | ||
|
|
b58578f88d | ||
|
|
6cb285dd5c | ||
|
|
46f324b10b | ||
|
|
d188eec318 | ||
|
|
c978aa7d64 | ||
|
|
0c7f42a18a | ||
|
|
9a5584b1b6 | ||
|
|
1bc099a2db | ||
|
|
3fc1feff38 | ||
|
|
ffe176f6d1 | ||
|
|
8057cc4888 | ||
|
|
9d6dad37c5 | ||
|
|
7f84ddecc5 | ||
|
|
94ab9f665e | ||
|
|
3600f2cf16 | ||
|
|
005bc16c24 | ||
|
|
985e2008ba | ||
|
|
bd7ee12938 | ||
|
|
0983b00284 | ||
|
|
8ee2e4d441 | ||
|
|
1d9c102889 | ||
|
|
2542aa67b0 | ||
|
|
1da96e8803 | ||
|
|
cf2f62cf14 | ||
|
|
7683ba8b5b | ||
|
|
a0d7d72a26 | ||
|
|
bfd983e3f8 | ||
|
|
e7da39de57 | ||
|
|
e6ddc59cde | ||
|
|
6c5dfd0c25 | ||
|
|
775df79893 | ||
|
|
3fbf658c16 | ||
|
|
bc31745607 | ||
|
|
e5c2eb20f2 | ||
|
|
05fb7fb5eb | ||
|
|
2c1733de8d | ||
|
|
e51c94dcb5 | ||
|
|
07c07902ff | ||
|
|
864cdea4c6 | ||
|
|
6e810907b2 | ||
|
|
2b20a12c4a | ||
|
|
9c83dacfce | ||
|
|
64ba053f3b | ||
|
|
96416bd8a7 | ||
|
|
4d2003d77b | ||
|
|
aaad02fd38 | ||
|
|
c68d3a7432 | ||
|
|
a5209bd849 | ||
|
|
bdf965dab6 | ||
|
|
b4da20ecc0 | ||
|
|
4b33b72160 | ||
|
|
d5505fe3d4 | ||
|
|
264c9e41e9 | ||
|
|
76ac3c99bd | ||
|
|
fe5988c536 | ||
|
|
ed5d467d90 | ||
|
|
228d0226dd | ||
|
|
6215ff0760 | ||
|
|
54812306be | ||
|
|
ce9e20fbbc | ||
|
|
878690697e | ||
|
|
ad97297576 | ||
|
|
683b1ed693 | ||
|
|
04f9f378b0 | ||
|
|
1c3f44a526 | ||
|
|
89e152dfe2 | ||
|
|
1ebad3786c | ||
|
|
f2f526a60a | ||
|
|
4b4c7e0e0d | ||
|
|
cec792ce9d | ||
|
|
338d033632 | ||
|
|
1be926cec4 | ||
|
|
2134768dfe | ||
|
|
ef825688ee | ||
|
|
77a14360df | ||
|
|
9be2fb4750 | ||
|
|
5a963aec10 | ||
|
|
45d1c28a28 | ||
|
|
a3e7683c63 | ||
|
|
da394b45e6 | ||
|
|
2f3bfda8c0 | ||
|
|
208388978a | ||
|
|
aa771616bb | ||
|
|
1513bbaac9 | ||
|
|
0014984116 | ||
|
|
d6e49dbd68 | ||
|
|
3756bb3460 | ||
|
|
60be9c5360 | ||
|
|
da31bcb11e | ||
|
|
f03e7b33c9 | ||
|
|
0baf727f36 | ||
|
|
94dd49a968 | ||
|
|
83a298e7e0 | ||
|
|
220b79f5cd | ||
|
|
e62201e227 | ||
|
|
0ab9b86f0a | ||
|
|
c7aabd3037 | ||
|
|
c74d990cee | ||
|
|
35252af665 | ||
|
|
aab6ded41b | ||
|
|
aecac5bda2 | ||
|
|
30362118a1 | ||
|
|
81e76fa485 | ||
|
|
12ed35e87d | ||
|
|
525f10b858 | ||
|
|
0547316cf2 | ||
|
|
9fe9b5349c | ||
|
|
d1e488efaf | ||
|
|
c5dc7e732a | ||
|
|
7efcccd013 | ||
|
|
964285f08c | ||
|
|
5698dda11f | ||
|
|
6005a8471f | ||
|
|
e2ee0dfe98 | ||
|
|
70341cfbc7 | ||
|
|
77643aa3f4 | ||
|
|
1fd6194ff8 | ||
|
|
c37018fdd2 | ||
|
|
3907ea0db0 | ||
|
|
40f5e9a41c | ||
|
|
2c2eb51878 | ||
|
|
aa2d0b51ea | ||
|
|
64d154d9d7 | ||
|
|
ffa390f916 | ||
|
|
4d62e6caf1 | ||
|
|
386ae676ca | ||
|
|
f8a9c3d6bc | ||
|
|
83671fae5f | ||
|
|
9b715524a2 | ||
|
|
e06fc1ed16 | ||
|
|
13d7c5c5dd | ||
|
|
7b02feaebb | ||
|
|
bd10e2c695 | ||
|
|
4b209d944d | ||
|
|
84024cbdb6 | ||
|
|
ad2eed2f71 | ||
|
|
e8aa7ed9e7 | ||
|
|
337aaea123 | ||
|
|
4c41628b20 | ||
|
|
ae7fb520d7 | ||
|
|
f325073982 | ||
|
|
33c4e4be34 | ||
|
|
585a6abbdd | ||
|
|
8d52a2cfb0 | ||
|
|
1cfe6be9c4 | ||
|
|
4e4481b6f2 | ||
|
|
63ca073938 | ||
|
|
b244a768a3 | ||
|
|
81d52719f4 | ||
|
|
f6a93fe74c | ||
|
|
497f8ea567 | ||
|
|
dded086b54 | ||
|
|
e7b5100324 | ||
|
|
8ceec32692 | ||
|
|
5fcde512bc | ||
|
|
e5007a7daa | ||
|
|
cb77f35a27 | ||
|
|
71dbca6392 | ||
|
|
47d412e13f | ||
|
|
53e8f5bdd8 | ||
|
|
6ecd631b3e | ||
|
|
19d2725c13 | ||
|
|
8e2824201a | ||
|
|
75dab209d7 | ||
|
|
6da9a5478b | ||
|
|
ff51b329f6 | ||
|
|
2ec0fd218b | ||
|
|
e4e960ec1c | ||
|
|
cc69737934 | ||
|
|
0c83ecf1b5 | ||
|
|
05ff6065d0 | ||
|
|
a7df0fc62f | ||
|
|
1c56210530 | ||
|
|
d65c37caad | ||
|
|
eb72ec36ba | ||
|
|
4de10e32e3 | ||
|
|
f8ab9f2dcf | ||
|
|
ccf50b1269 | ||
|
|
a6d89e3f73 | ||
|
|
ee1b8ffe24 | ||
|
|
0560c792d8 | ||
|
|
966c5ddad3 | ||
|
|
b36f822cb6 | ||
|
|
7180a273a2 | ||
|
|
e65b3950cc | ||
|
|
a0e09695e5 | ||
|
|
88bef39952 | ||
|
|
06cf3c04e5 | ||
|
|
7a8a19b11b | ||
|
|
ce6ac057f6 | ||
|
|
abce68fdf0 | ||
|
|
cc019908c2 | ||
|
|
d0a9abcb1c | ||
|
|
63ba2d178f | ||
|
|
6c12780abe | ||
|
|
92d87b0082 | ||
|
|
2fad32767e | ||
|
|
51163b9f14 | ||
|
|
6557aca750 | ||
|
|
1801f1178e | ||
|
|
f21a84c510 | ||
|
|
e14b02991e | ||
|
|
bf82805cfd | ||
|
|
08ebb8c999 | ||
|
|
0a8a592ef4 | ||
|
|
173c8c7c21 | ||
|
|
98d348d5b9 | ||
|
|
7fc5fd02fd | ||
|
|
50878a9d98 | ||
|
|
aa74bd86ca | ||
|
|
7232d6df4b | ||
|
|
112cbd294d | ||
|
|
553814b6eb | ||
|
|
eeb0560fc2 | ||
|
|
1f36787d75 | ||
|
|
c753f9d5c0 | ||
|
|
fb87f9f7d6 |
@@ -27,8 +27,18 @@ build:
|
||||
IMAGE ?= mesh-controller:$(VERSION)
|
||||
DEV_TAG ?= mesh-controller:development
|
||||
|
||||
# The base the module declares, read from the manifest rather than written here twice.
|
||||
#
|
||||
# **`make image` was broken and stayed broken**, because the Dockerfile's fallback base was a Go
|
||||
# older than go.mod asks for: every build died at `go mod download` with "go.mod requires go >=
|
||||
# 1.26.0", and the pipeline never saw it because the pipeline passes the declared base in. Anybody
|
||||
# building the image by hand hit it and had to find the digest themselves (novox/hq 04-ISSUES/146,
|
||||
# what it cost).
|
||||
GO_BASE ?= $(shell python3 -c "import json;print(next(o['image'] for o in json.load(open('module.json'))['build']['on'] if o['arg']=='GO_BASE'))" 2>/dev/null)
|
||||
|
||||
image:
|
||||
docker build --build-arg VERSION=$(VERSION) -t $(IMAGE) -t $(DEV_TAG) .
|
||||
@test -n "$(GO_BASE)" || { echo "module.json declares no GO_BASE; pass GO_BASE=<image> or fix the manifest"; exit 1; }
|
||||
docker build --build-arg GO_BASE=$(GO_BASE) --build-arg VERSION=$(VERSION) -t $(IMAGE) -t $(DEV_TAG) .
|
||||
@echo
|
||||
@docker image inspect $(IMAGE) --format 'built {{.RepoTags}} {{.Size}} bytes'
|
||||
|
||||
@@ -38,7 +48,8 @@ BUILDER_IMAGE ?= mesh-builder:$(VERSION)
|
||||
BUILDER_DEV_TAG ?= mesh-builder:development
|
||||
|
||||
builder-image:
|
||||
docker build -f cmd/mesh-builder/Dockerfile -t $(BUILDER_IMAGE) -t $(BUILDER_DEV_TAG) .
|
||||
@test -n "$(GO_BASE)" || { echo "module.json declares no GO_BASE; pass GO_BASE=<image> or fix the manifest"; exit 1; }
|
||||
docker build --build-arg GO_BASE=$(GO_BASE) -f cmd/mesh-builder/Dockerfile -t $(BUILDER_IMAGE) -t $(BUILDER_DEV_TAG) .
|
||||
@echo
|
||||
@docker image inspect $(BUILDER_IMAGE) --format 'built {{.RepoTags}} {{.Size}} bytes'
|
||||
|
||||
@@ -86,13 +97,19 @@ proxy-image:
|
||||
|
||||
# The whole gate. Raises a database, runs everything against it, and takes it down again --
|
||||
# including when the tests fail, which is why the teardown is not conditional.
|
||||
#
|
||||
# **One package at a time (-p 1), and it is not about speed.** The live tests reach one bus, and on
|
||||
# it they assert, read and remove the mesh's own objects -- streams and consumers with fixed names,
|
||||
# because those names are the mesh's and a test cannot choose others. Two packages doing that at once
|
||||
# is one deleting a consumer the other is reading through, and the failure lands in whichever test
|
||||
# was reading, as "no response from stream". That reads as a bug in the code under test.
|
||||
check: fmt vet postgres
|
||||
@go test ./... ; status=$$? ; $(MAKE) postgres-stop ; exit $$status
|
||||
@go test -p 1 ./... ; status=$$? ; $(MAKE) postgres-stop ; exit $$status
|
||||
|
||||
# Without a database the live tests skip rather than fail, so this is the honest subset and not
|
||||
# the gate.
|
||||
# the gate. Serialised for the same reason check is: a bus may be configured even when a store is not.
|
||||
test:
|
||||
go test ./...
|
||||
go test -p 1 ./...
|
||||
|
||||
vet:
|
||||
go vet ./...
|
||||
|
||||
+64
-171
@@ -17,22 +17,15 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/builder"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
@@ -52,7 +45,6 @@ const usage = `mesh-builder — builds modules for the mesh
|
||||
It consumes build requests and answers with what it made. Nothing is listened on and nothing
|
||||
is dialled except the broker.
|
||||
|
||||
MESH_BROKER_AMQP where the broker is, with this builder's own credential
|
||||
MESH_BROKER_FILE a file the mesh sealed to this machine holding the same
|
||||
MESH_REGISTRY host:port to publish artifacts to, when the mesh has not said
|
||||
MESH_BINDING a file the mesh wrote saying where the artifact store is
|
||||
@@ -115,72 +107,48 @@ func run() error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
conn, err := dial(credential)
|
||||
if err != nil {
|
||||
// Not quoted back: the URL carries this builder's broker password.
|
||||
return fmt.Errorf("cannot reach the broker: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
channel, err := conn.Channel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
if _, err := channel.QueueDeclare(link.BuildQueue, true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
// One at a time. A build machine that took five requests at once would run five container
|
||||
// builds against one runtime and finish all of them slower than it would have finished the
|
||||
// first — and the queue is what shares work between machines, so nothing is lost by it.
|
||||
if err := channel.Qos(1, 0, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Not auto-acknowledged. A request acknowledged on arrival is a build that vanishes if this
|
||||
// process dies mid-way, with nobody waiting on it ever hearing why.
|
||||
requests, err := channel.ConsumeWithContext(ctx, link.BuildQueue, "mesh-builder",
|
||||
false, false, false, false, nil)
|
||||
machine, err := takeWorkFrom(credential, on)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer machine.Close()
|
||||
|
||||
fmt.Fprintf(os.Stderr, "building for the mesh, publishing to %s\n", registry)
|
||||
publisher := builder.Registry{Address: registry, Run: builder.Command}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
fmt.Println("stopping")
|
||||
return nil
|
||||
case delivery, ok := <-requests:
|
||||
if !ok {
|
||||
return fmt.Errorf("the broker closed the connection")
|
||||
}
|
||||
answer(ctx, channel, publisher, on, workspace, delivery)
|
||||
}
|
||||
return machine.Take(ctx, func(ctx context.Context, work link.Build) {
|
||||
answer(ctx, publisher, on, workspace, work)
|
||||
})
|
||||
}
|
||||
|
||||
// takeWorkFrom opens this machine's link to whichever bus the mesh is on.
|
||||
//
|
||||
// **One place chooses**, as everywhere else the bus change went (novox/hq ADR 0116 step 5): a build
|
||||
// machine told about both would take work from one and answer on the other, and every log line would
|
||||
// say it was fine.
|
||||
func takeWorkFrom(credential Credential, on string) (link.BuildMachine, error) {
|
||||
// **The credential names the bus, and there is one** (novox/hq ADR 0131, design 28 task 5.5).
|
||||
// A credential for the mesh's bus carries user, password and fingerprint beside the address,
|
||||
// and that is enough to dial it, pinned.
|
||||
if !credential.onTheNewBus() {
|
||||
return nil, fmt.Errorf("the credential at hand names %q, which is not the mesh's bus", credential.URL)
|
||||
}
|
||||
js, err := broker.DialPinned(credential.natsURL(), credential.Fingerprint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return link.MachineOverNATS(js, on), nil
|
||||
}
|
||||
|
||||
// answer does one build and says what happened, whichever way it went.
|
||||
func answer(ctx context.Context, channel *amqp.Channel, publisher builder.Publisher,
|
||||
on, workspace string, delivery amqp.Delivery) {
|
||||
func answer(ctx context.Context, publisher builder.Publisher, on, workspace string, work link.Build) {
|
||||
request := work.Request()
|
||||
|
||||
// **First thing, and to stdout.** A build request that arrives and produces no visible line
|
||||
// until it either finishes or fails is indistinguishable from one that never arrived — which
|
||||
// cost a long diagnosis against a running mesh, chasing "the handler never fired" when the
|
||||
// truth was only that the handler said nothing until the end.
|
||||
fmt.Fprintf(os.Stderr, "a build request arrived (%d bytes)\n", len(delivery.Body))
|
||||
|
||||
var request link.BuildRequest
|
||||
if err := json.Unmarshal(delivery.Body, &request); err != nil {
|
||||
// Unreadable. Acknowledged and dropped rather than requeued: a message this builder
|
||||
// cannot parse will not become parseable by being delivered again, and requeueing it
|
||||
// would put it in front of every real request for ever.
|
||||
fmt.Fprintf(os.Stderr, "a request could not be read and was dropped: %v\n", err)
|
||||
_ = delivery.Ack(false)
|
||||
return
|
||||
}
|
||||
// **First thing, and to stdout.** A build request that arrives and produces no visible line until
|
||||
// it either finishes or fails is indistinguishable from one that never arrived — which cost a long
|
||||
// diagnosis against a running mesh, chasing "the handler never fired" when the truth was only that
|
||||
// the handler said nothing until the end.
|
||||
fmt.Fprintf(os.Stderr, "a build request arrived for %s\n", request.Repository)
|
||||
|
||||
result := link.BuildResult{
|
||||
ID: request.ID, Repository: request.Repository, Path: request.Path,
|
||||
@@ -199,14 +167,13 @@ func answer(ctx context.Context, channel *amqp.Channel, publisher builder.Publis
|
||||
var built builder.Result
|
||||
if err == nil {
|
||||
// The package-registry credential is a build input, so it is resolved before the clone: a
|
||||
// build that could not have resolved its dependencies is refused in front of the reason,
|
||||
// not after a clone that then fails at npm ci.
|
||||
// build that could not have resolved its dependencies is refused in front of the reason, not
|
||||
// after a clone that then fails at npm ci.
|
||||
built, err = builder.Build(ctx, builder.Command, publisher,
|
||||
request.Repository, request.Path, request.Ref, workspace, request.Held, npmrc,
|
||||
forgeFrom(),
|
||||
func(step, message string) {
|
||||
forgeFrom(), func(step, message string) {
|
||||
fmt.Fprintf(os.Stderr, " [%s] %s\n", step, message)
|
||||
})
|
||||
}, request.Seats)
|
||||
}
|
||||
if err != nil {
|
||||
// A failure is a result. A build that fails and says nothing is indistinguishable from a
|
||||
@@ -226,71 +193,26 @@ func answer(ctx context.Context, channel *amqp.Channel, publisher builder.Publis
|
||||
})
|
||||
}
|
||||
result.Against = built.Against
|
||||
for _, r := range built.Read {
|
||||
result.Read = append(result.Read, link.ReadRepository{Repository: r.Repository, Ref: r.Ref})
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, " built %s from %s\n", built.Manifest.Module, short(built.Commit))
|
||||
}
|
||||
}
|
||||
|
||||
body, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cannot report a build: %v\n", err)
|
||||
_ = delivery.Ack(false)
|
||||
if err := work.Announce(ctx, result); err != nil {
|
||||
// Said, not fatal: the build happened. A build reported as failed because announcing it
|
||||
// failed is a lie about work that was done — and the request stays unsettled below only if
|
||||
// nothing was said at all, so another machine can try.
|
||||
fmt.Fprintf(os.Stderr, "cannot say what came of a build: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Always through the exchange, whether or not somebody is waiting.
|
||||
//
|
||||
// **Never the default exchange.** Permission there is granted per exchange rather than per
|
||||
// queue, so a builder allowed to use it could publish into any node's queue — the privilege a
|
||||
// build machine most obviously should not have. An asker binds its own reply queue to this
|
||||
// key and filters by correlation; a control plane that records builds is bound to it too, so
|
||||
// a result nobody asked for is still kept rather than reported into the void.
|
||||
publishCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if err := channel.PublishWithContext(publishCtx, link.Exchange, link.KeyBuilt, false, false,
|
||||
amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
CorrelationId: result.ID,
|
||||
Body: body,
|
||||
}); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cannot answer a build request: %v\n", err)
|
||||
// Settled only once the outcome is away, so a machine that dies before answering leaves the work
|
||||
// for another rather than losing it.
|
||||
if err := work.Done(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "the outcome is away and the request could not be settled: %v\n", err)
|
||||
}
|
||||
// **And announced, which is a different act from answering.** The reply goes to whoever asked
|
||||
// and is correlated to their request; this says to the whole mesh that a module now exists at
|
||||
// a commit, and the catalogue places it in the module graph (novox/hq ADR 0072). A build
|
||||
// nobody asked for still has to be announced, or the graph knows less than the registry does.
|
||||
//
|
||||
// Only on success: a failed build produced no module-version, and announcing one would put
|
||||
// something in the graph that was never made.
|
||||
if result.Failed == "" && result.Commit != "" {
|
||||
announced := map[string]any{
|
||||
"module": moduleOf(result.Manifest), "commit": result.Commit,
|
||||
"repository": result.Repository, "path": result.Path, "ref": result.Ref,
|
||||
"manifest": json.RawMessage(result.Manifest), "against": result.Against,
|
||||
"made": result.Made,
|
||||
}
|
||||
if err := link.EmitEvent(publishCtx, channel, link.KeyModuleBuilt, "builder", on, announced); err != nil {
|
||||
// Said, not fatal: the build happened and was answered. A module the catalogue has not
|
||||
// heard of is a gap somebody can close; a build reported as failed because announcing
|
||||
// it failed is a lie about work that was done.
|
||||
fmt.Fprintf(os.Stderr, " built, but could not announce it: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Acknowledged only once the answer is away, so a builder that dies before answering leaves
|
||||
// the request for another machine rather than losing it.
|
||||
_ = delivery.Ack(false)
|
||||
}
|
||||
|
||||
// moduleOf reads the module's name out of the manifest it just built, which is the only place it is
|
||||
// authoritative — the request named a repository and a path, not a module.
|
||||
func moduleOf(manifest json.RawMessage) string {
|
||||
var named struct {
|
||||
Module string `json:"module"`
|
||||
}
|
||||
if err := json.Unmarshal(manifest, &named); err != nil {
|
||||
return ""
|
||||
}
|
||||
return named.Module
|
||||
}
|
||||
|
||||
// packagesFrom is where a build resolves the mesh's own published packages — the SDK above all
|
||||
@@ -499,13 +421,8 @@ func brokerFrom() (Credential, error) {
|
||||
// broker is then verified against whatever this machine already trusts.
|
||||
return Credential{URL: said}, nil
|
||||
}
|
||||
url := strings.TrimSpace(os.Getenv("MESH_BROKER_AMQP"))
|
||||
if url == "" {
|
||||
return Credential{}, fmt.Errorf(
|
||||
"neither MESH_BROKER_FILE nor MESH_BROKER_AMQP: a builder with no broker has " +
|
||||
"nothing to build")
|
||||
}
|
||||
return Credential{URL: url}, nil
|
||||
return Credential{}, fmt.Errorf(
|
||||
"no MESH_BROKER_FILE: a build machine with no credential for the bus has nothing to build")
|
||||
}
|
||||
|
||||
// Credential is what a build machine is given so it can reach the broker.
|
||||
@@ -517,48 +434,24 @@ func brokerFrom() (Credential, error) {
|
||||
// **The same shape a node gets, for the same reason** (novox/hq ADR 0004): the fingerprint travels
|
||||
// out of band — here, sealed with the credential — and the endpoint is verified once at connect.
|
||||
type Credential struct {
|
||||
URL string `json:"url"`
|
||||
// Fingerprint is SHA-256 over the broker certificate's DER bytes, or empty to verify the
|
||||
// ordinary way.
|
||||
URL string `json:"url"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
// User and Password ride beside the address on the bus being built (design 25): a credential
|
||||
// embedded in a URL leaks into every log line that prints a connection, so the mesh seals them
|
||||
// as two fields and this machine joins them once, here, to dial.
|
||||
User string `json:"user,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
}
|
||||
|
||||
// dial opens the connection, pinning the broker's certificate when there is one to pin.
|
||||
func dial(held Credential) (*amqp.Connection, error) {
|
||||
if held.Fingerprint == "" {
|
||||
return amqp.Dial(held.URL)
|
||||
}
|
||||
return amqp.DialTLS(held.URL, pinning(held.Fingerprint))
|
||||
}
|
||||
// onTheNewBus is whether a credential is for the bus being built: its address says so, and the
|
||||
// mesh only ever seals such a credential with the user and password beside it.
|
||||
func (c Credential) onTheNewBus() bool { return strings.HasPrefix(strings.TrimSpace(c.URL), "nats://") }
|
||||
|
||||
// pinning is a TLS configuration that trusts exactly one certificate.
|
||||
//
|
||||
// InsecureSkipVerify with a VerifyPeerCertificate is **pinning, not skipping**: the standard chain
|
||||
// check is replaced, not removed, and what replaces it is stricter — one certificate is accepted
|
||||
// rather than every certificate a public authority would sign.
|
||||
//
|
||||
// Its own function so a test can drive it against a real handshake. A pin check that is only ever
|
||||
// exercised through a broker is a pin check nothing tests.
|
||||
func pinning(fingerprint string) *tls.Config {
|
||||
return &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
VerifyPeerCertificate: func(raw [][]byte, _ [][]*x509.Certificate) error {
|
||||
if len(raw) == 0 {
|
||||
return errors.New("the broker presented no certificate")
|
||||
}
|
||||
// The leaf, and in the same spelling the mesh writes it — `sha256:` and 64 hex
|
||||
// characters. Comparing a bare digest against a written fingerprint never matches,
|
||||
// and the failure is indistinguishable from being pointed at the wrong broker.
|
||||
sum := sha256.Sum256(raw[0])
|
||||
got := "sha256:" + hex.EncodeToString(sum[:])
|
||||
if got != fingerprint {
|
||||
return fmt.Errorf(
|
||||
"this is not the broker this builder was told about\n expected %s\n "+
|
||||
"got %s\nEither this mesh's broker was replaced, or this builder is "+
|
||||
"being pointed at something else. Retrying will not help",
|
||||
fingerprint, got)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
// natsURL is the address with this machine's credential in it, for the one dial that needs it.
|
||||
func (c Credential) natsURL() string {
|
||||
rest := strings.TrimPrefix(strings.TrimSpace(c.URL), "nats://")
|
||||
if c.User == "" {
|
||||
return "nats://" + rest
|
||||
}
|
||||
return "nats://" + c.User + ":" + c.Password + "@" + rest
|
||||
}
|
||||
|
||||
@@ -106,6 +106,9 @@ func buildOnce(ctx context.Context, args []string) error {
|
||||
Manifest: built.Manifest,
|
||||
Against: built.Against,
|
||||
}
|
||||
for _, r := range built.Read {
|
||||
out.Read = append(out.Read, readRepository{Repository: r.Repository, Ref: r.Ref})
|
||||
}
|
||||
for _, made := range built.Built {
|
||||
out.Made = append(out.Made, madeArtifact{Name: made.Name, Kind: made.Kind, Reference: made.Reference})
|
||||
}
|
||||
@@ -123,14 +126,21 @@ func buildOnce(ctx context.Context, args []string) error {
|
||||
// The same fields the mesh records for a build, so a reader comparing a genesis build against an
|
||||
// ordinary one is comparing the same thing said the same way.
|
||||
type onceResult struct {
|
||||
Module string `json:"module"`
|
||||
Commit string `json:"commit"`
|
||||
Repository string `json:"repository"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Ref string `json:"ref,omitempty"`
|
||||
Manifest any `json:"manifest"`
|
||||
Made []madeArtifact `json:"made"`
|
||||
Against []string `json:"against,omitempty"`
|
||||
Module string `json:"module"`
|
||||
Commit string `json:"commit"`
|
||||
Repository string `json:"repository"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Ref string `json:"ref,omitempty"`
|
||||
Manifest any `json:"manifest"`
|
||||
Made []madeArtifact `json:"made"`
|
||||
Against []string `json:"against,omitempty"`
|
||||
Read []readRepository `json:"read,omitempty"`
|
||||
}
|
||||
|
||||
// readRepository is a repository this build read source from besides the module's own.
|
||||
type readRepository struct {
|
||||
Repository string `json:"repository"`
|
||||
Ref string `json:"ref,omitempty"`
|
||||
}
|
||||
|
||||
type madeArtifact struct {
|
||||
|
||||
@@ -14,8 +14,8 @@ func TestBuilderDiagnosticsStayOffStdout(t *testing.T) {
|
||||
allowed := map[string]bool{
|
||||
"string(body)": true, // once.go: the result JSON, which IS stdout
|
||||
"version)": true, // --version
|
||||
`"stopping")`: true, // the loop.s shutdown line
|
||||
"usage)": true, // --help text, for a human
|
||||
`"stopping")`: true, // the loop.s shutdown line
|
||||
"usage)": true, // --help text, for a human
|
||||
}
|
||||
for _, file := range []string{"once.go", "main.go"} {
|
||||
src, err := os.ReadFile(file)
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
)
|
||||
|
||||
// Where a builder publishes.
|
||||
@@ -193,9 +195,9 @@ func TestThePinIsComparedInTheSpellingTheMeshWritesIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// handshakeWith runs the builder's own pin check against an address.
|
||||
// handshakeWith runs the pin check the builder dials with against an address.
|
||||
func handshakeWith(address, pin string) error {
|
||||
conn, err := tls.Dial("tcp", address, pinning(pin))
|
||||
conn, err := tls.Dial("tcp", address, broker.PinnedToFingerprint(pin))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -46,6 +46,13 @@ func assign(ctx context.Context, open *stores, node, module string) (string, err
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
// **Before the new assignment can unsettle a seat somebody holds only by being alone**
|
||||
// (novox/hq 04-ISSUES/170): what the mesh derived so far is written down, and then the
|
||||
// assignment resolves against a record rather than against a coincidence.
|
||||
settled, err := recordDerivedHolders(ctx, open)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
fresh, err := open.inventory.Assign(ctx, node, module)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -57,6 +64,9 @@ func assign(ctx context.Context, open *stores, node, module string) (string, err
|
||||
node, module), nil
|
||||
}
|
||||
said := fmt.Sprintf("%s is assigned %s", node, module)
|
||||
for _, line := range settled {
|
||||
said += "\n " + line
|
||||
}
|
||||
plan, _, err := planFor(ctx, open, node)
|
||||
if err != nil {
|
||||
// Kept, and still refused. Both halves are the answer, and the rest of the mesh is still
|
||||
|
||||
@@ -17,8 +17,8 @@ import (
|
||||
|
||||
var aDigest = "sha256:" + strings.Repeat("e", 64)
|
||||
|
||||
// **A build is recorded by digest and path**, whatever address the builder pushed to — and only
|
||||
// what the build made is rewritten: an image the module runs from elsewhere is left where it says.
|
||||
// **A build is recorded by digest and path**, whatever address the builder pushed to — what it
|
||||
// made and what it stood on both; an image the module runs from elsewhere is left where it says.
|
||||
func TestABuildIsRecordedWithoutTheStoresAddress(t *testing.T) {
|
||||
manifest, _ := json.Marshal(map[string]any{
|
||||
"module": "gitea", "version": "1",
|
||||
@@ -65,8 +65,11 @@ func TestABuildIsRecordedWithoutTheStoresAddress(t *testing.T) {
|
||||
if strings.Contains(string(kept.Manifest), "anchor.internal:5100") {
|
||||
t.Errorf("the recorded manifest still carries the store's address:\n%s", kept.Manifest)
|
||||
}
|
||||
if kept.Against[0] != "anchor.internal:5100/mesh-tools/runtime@"+aDigest {
|
||||
t.Errorf("what the build stood on was rewritten: %v", kept.Against)
|
||||
// What the build stood on is an edge to another module's artifact, and it is recorded the way
|
||||
// that artifact is: by path in the store, so the edge still names the same thing when the
|
||||
// store answers at another address.
|
||||
if kept.Against[0] != catalogue.ArtifactStoreScheme+"mesh-tools/runtime@"+aDigest {
|
||||
t.Errorf("what the build stood on was recorded by address: %v", kept.Against)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ func reportsReaching(t *testing.T, open *stores, reachable []link.Reach, held ..
|
||||
if err := open.inventory.RecordSent(ctx, record.ID, digestOf(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (link.Enrolment{Inventory: open.inventory}).Heard(ctx, link.Report{
|
||||
if _, err := (link.Enrolment{Inventory: open.inventory}).Heard(ctx, link.Report{
|
||||
Node: "anchor", Applied: []string{"hello-web.x"}, Declared: digestOf(body),
|
||||
Firewall: "ufw", Held: held, Reachable: reachable,
|
||||
}); err != nil {
|
||||
|
||||
@@ -309,7 +309,7 @@ func converge(ctx context.Context, open *stores, node string, yes bool, digest s
|
||||
return "", err
|
||||
}
|
||||
derived := derivedFilter{rules: rules, foundation: with.Foundation, mesh: with.Mesh,
|
||||
outward: plan.PublicDomain != ""}
|
||||
outward: plan.PublicDomain != "", outwardLinks: with.OutwardLinks}
|
||||
preview, saw := previewOf(node, reported, derived, plan, taken, filter, runs[filter])
|
||||
preview += "\n\n preview " + saw
|
||||
if !yes {
|
||||
@@ -414,6 +414,18 @@ func previewOf(node string, reported inventory.Adoption, derived derivedFilter,
|
||||
b.WriteString(" not previewed: traffic the machine routes that is not a published port " +
|
||||
"(a tunnel, NAT in the found firewall) — the derived filter drops it unless a module " +
|
||||
"declares it\n")
|
||||
// Which links the filter constrains, said rather than left to the sentence above (novox/hq ADR
|
||||
// 0140). Everything arriving anywhere else is this machine's own guest and keeps working — which
|
||||
// is what a reader most wants to know, because the previous shape of this filter cut a machine's
|
||||
// guests off at the flip without saying so, and that is how this was found.
|
||||
if len(derived.outwardLinks) > 0 {
|
||||
b.WriteString(fmt.Sprintf(" it filters what arrives on: %s, and on the private network "+
|
||||
"— everything its own guests send keeps working\n",
|
||||
strings.Join(derived.outwardLinks, ", ")))
|
||||
} else {
|
||||
b.WriteString(" it has reported no link facing outside, so no filter can be composed " +
|
||||
"for it — the flip is refused until it reports one\n")
|
||||
}
|
||||
|
||||
isTaken := map[string]bool{}
|
||||
for _, m := range taken {
|
||||
@@ -473,6 +485,10 @@ type derivedFilter struct {
|
||||
// mesh is every address on the private network; outward says the machine faces outside.
|
||||
mesh []string
|
||||
outward bool
|
||||
// outwardLinks is the links this machine reported as facing outside it (novox/hq ADR 0140).
|
||||
// The filter constrains what arrives on them; everything arriving elsewhere is this machine's
|
||||
// own guest and is not filtered.
|
||||
outwardLinks []string
|
||||
}
|
||||
|
||||
// closesOutside is what a narrowing from everywhere to the private network is called: it closes.
|
||||
@@ -498,6 +514,12 @@ func (d derivedFilter) fate(r inventory.Reach) string {
|
||||
return "stays open — the mesh's own, from anywhere"
|
||||
}
|
||||
}
|
||||
// This machine's own guests ask it for an address and for names, and those two arrive here
|
||||
// (novox/hq ADR 0140). Admitted by the link they arrive on, so a listener bound anywhere but an
|
||||
// outward link keeps answering them.
|
||||
if (r.Protocol == "udp" && (r.Port == 53 || r.Port == 67)) || (r.Protocol == "tcp" && r.Port == 53) {
|
||||
return "stays open — this machine's own guests asking it for an address and for names"
|
||||
}
|
||||
for _, rule := range d.rules {
|
||||
if rule.Port != r.Port || rule.Protocol != r.Protocol {
|
||||
continue
|
||||
|
||||
@@ -37,13 +37,13 @@ func askCommand(ctx context.Context, args []string) error {
|
||||
arguments = json.RawMessage(positionals[2])
|
||||
}
|
||||
|
||||
server, err := link.Connect(nil, nil)
|
||||
server, err := connectLink(ctx, nil, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
answer, err := link.Ask(ctx, server.Channel(), module, tool, arguments, *wait)
|
||||
answer, err := link.Ask(ctx, server.Bus(), module, tool, arguments, *wait)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+145
-83
@@ -2,8 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
@@ -31,6 +29,51 @@ import (
|
||||
// control plane may send a machine is bounded by the declaration language. This is the shape the
|
||||
// builder module will take when it is given work over the broker; today a person runs it, and the
|
||||
// mesh records the result the same way either way.
|
||||
// buildOn rebuilds every module the mesh holds that stands on the named module's artifacts — the
|
||||
// rebuild a changed base needs, which nothing else asks for: their sources did not move, and
|
||||
// "behind" does not see a base that did (novox/hq 04-ISSUES/131). Bases first among them too.
|
||||
func buildOn(ctx context.Context, base string, wait time.Duration) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
held, err := open.inventory.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
against, err := open.inventory.BuiltAgainst(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var on []inventory.Entry
|
||||
for _, e := range held {
|
||||
if standsOnModule(e, base, against) {
|
||||
on = append(on, e)
|
||||
}
|
||||
}
|
||||
if len(on) == 0 {
|
||||
fmt.Printf("nothing the mesh holds stands on %s\n", base)
|
||||
return nil
|
||||
}
|
||||
on = orderByBases(on, against)
|
||||
fmt.Printf("%d module(s) stand on %s:\n", len(on), base)
|
||||
var failed []string
|
||||
for _, e := range on {
|
||||
fmt.Printf("--- %s\n", e.Manifest.Module)
|
||||
source := buildSource{Repository: e.Source.Repository, Seat: e.Source.Seat}
|
||||
if err := buildOne(ctx, source, e.Source.Path, e.Source.Ref, wait); err != nil {
|
||||
fmt.Printf(" %v\n", err)
|
||||
failed = append(failed, e.Manifest.Module)
|
||||
}
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
return fmt.Errorf("%d of %d could not be built: %s", len(failed), len(on), strings.Join(failed, ", "))
|
||||
}
|
||||
fmt.Printf("\n%d module(s) rebuilt on %s. `push --behind` sends them on\n", len(on), base)
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildCommand(ctx context.Context, args []string) error {
|
||||
set := flag.NewFlagSet("build", flag.ContinueOnError)
|
||||
ref := set.String("ref", "", "the branch, tag or commit to build")
|
||||
@@ -46,6 +89,7 @@ func buildCommand(ctx context.Context, args []string) error {
|
||||
// retype each repository is asking them to be the loop. Naming a repository and asking which
|
||||
// ones need building are different requests, so they are not combined.
|
||||
behind := set.Bool("behind", false, "every module the mesh holds older than its source has")
|
||||
on := set.String("on", "", "rebuild every module that stands on this module's artifacts — the rebuild a changed base needs")
|
||||
// A repository on the mesh's own forge, named by its path there (novox/hq ADR 0111). Without it
|
||||
// the repository is external, cloned exactly as given — see source.go.
|
||||
self := set.Bool("self", false, "the repository is a path on the forge holding the git seat")
|
||||
@@ -53,6 +97,13 @@ func buildCommand(ctx context.Context, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *on != "" {
|
||||
if len(positionals) != 0 || *behind || *self {
|
||||
return errors.New("build --on <module> names a base and nothing else")
|
||||
}
|
||||
return buildOn(ctx, *on, *wait)
|
||||
}
|
||||
|
||||
if *behind {
|
||||
if len(positionals) != 0 || *self {
|
||||
return errors.New("build <repository> or build --behind, not both: one names a " +
|
||||
@@ -61,7 +112,7 @@ func buildCommand(ctx context.Context, args []string) error {
|
||||
return buildBehind(ctx, *wait)
|
||||
}
|
||||
if len(positionals) != 1 {
|
||||
return errors.New("build <repository> [--self] [--path P] [--ref R] [--wait D] [--dry-run]")
|
||||
return errors.New("build <repository> [--self] [--path P] [--ref R] [--wait D] [--dry-run] | build --behind | build --on <module>")
|
||||
}
|
||||
source := buildSource{Repository: positionals[0]}
|
||||
if *self {
|
||||
@@ -81,8 +132,9 @@ func buildCommand(ctx context.Context, args []string) error {
|
||||
//
|
||||
// **By digest and path, never by where it was pushed** (novox/hq 04-ISSUES/102). The builder
|
||||
// says `<registry>:<port>/<module>/<artifact>@sha256:…`; the mesh records the artifact-store
|
||||
// reference and composes the store's address back in where a reference is used. `against` is kept
|
||||
// as announced: it is what the build stood on as the builder saw it, and the catalogue's edge.
|
||||
// reference and composes the store's address back in where a reference is used. `against` — what
|
||||
// the build stood on, the catalogue's edge — is recorded the same way, so an edge names a module's
|
||||
// artifact and not the machine it was pulled from.
|
||||
func buildFrom(result link.BuildResult) inventory.Build {
|
||||
kept := inventory.Build{
|
||||
ID: result.ID, Repository: result.Repository, Ref: result.Ref,
|
||||
@@ -92,7 +144,13 @@ func buildFrom(result link.BuildResult) inventory.Build {
|
||||
// edges, and it is not always listening when a build happens — on a fresh mesh it cannot
|
||||
// be, for exactly the modules it needs most. Keeping them is what makes a replay able to
|
||||
// rebuild the graph rather than a list of names.
|
||||
Path: result.Path, Against: result.Against,
|
||||
Path: result.Path,
|
||||
}
|
||||
for _, ref := range result.Against {
|
||||
kept.Against = append(kept.Against, catalogue.Recorded(ref))
|
||||
}
|
||||
for _, r := range result.Read {
|
||||
kept.Read = append(kept.Read, inventory.ReadRepository{Repository: r.Repository, Ref: r.Ref})
|
||||
}
|
||||
var announced []inventory.Artifact
|
||||
for _, made := range result.Made {
|
||||
@@ -206,85 +264,45 @@ func builderCommand(ctx context.Context, args []string) error {
|
||||
}
|
||||
name := positionals[1]
|
||||
|
||||
management, err := broker.ManagementFromEnvironment()
|
||||
// **The build machine's credential is a module's credential** (novox/hq ADR 0131, design 28
|
||||
// task 5.5): minted into the mesh's records and sealed to the machine as the builder module's
|
||||
// broker secret, usable at the next push — the same act `module issue` performs, and the same
|
||||
// account the composed user list carries. Nothing is created on a server; the bus reads the list.
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The same shape of secret a token carries: enough entropy that guessing is not a strategy,
|
||||
// and safe to put in a URL because that is where it goes.
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
shelf, err := inv.Catalogue(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
password := base64.RawURLEncoding.EncodeToString(raw)
|
||||
if err := management.CreateBuilderAccount(ctx, name, password); err != nil {
|
||||
m, known := shelf[*module]
|
||||
if !known {
|
||||
return fmt.Errorf("%s is not in the catalogue; `module add` it first", *module)
|
||||
}
|
||||
fmt.Printf("build machine %s: ", name)
|
||||
node := *forNode
|
||||
if node == "" {
|
||||
entries, err := inv.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Manifest.Module == *module && len(e.On) > 0 {
|
||||
node = e.On[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
if node == "" {
|
||||
return fmt.Errorf("%s is assigned nowhere; `assign <machine> %s` first, or say --node", *module, *module)
|
||||
}
|
||||
address, err := broker.BusAddress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("broker account %s created, scoped to the %s queue and the %s exchange\n\n",
|
||||
name, link.BuildQueue, link.Exchange)
|
||||
|
||||
if *forNode != "" {
|
||||
known, err := broker.FromEnvironment()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot deliver a credential without knowing where the broker is: %w", err)
|
||||
}
|
||||
inv, err := openInventory(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer inv.Close()
|
||||
|
||||
brokerAddr, err := brokerReachableAt(ctx, inv, known, *forNode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The URL and what verifies the broker, together. A mesh's broker presents a certificate
|
||||
// of the mesh's own, which is in no public trust store — so a URL on its own reaches only
|
||||
// a broker somebody else vouches for, and the connection fails at TLS with an error about
|
||||
// an unknown authority rather than about a missing pin.
|
||||
//
|
||||
// **The same two facts a node's token carries** (novox/hq ADR 0004), delivered the same
|
||||
// way: out of band relative to the broker, so what is trusted does not come from the thing
|
||||
// being trusted.
|
||||
held, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
}{
|
||||
URL: fmt.Sprintf("amqps://%s:%s@%s/", name, password, brokerAddr),
|
||||
Fingerprint: known.Fingerprint,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.AcceptSecretForModule(ctx, *forNode, *module, "broker", string(held)); err != nil {
|
||||
return err
|
||||
}
|
||||
// Not printed. It is sealed to that machine and the mesh cannot read it back, which is
|
||||
// the whole point — printing it here would put the one copy that matters on a terminal.
|
||||
fmt.Printf(" sealed to %s, for the %s module. It arrives with the next push.\n",
|
||||
*forNode, *module)
|
||||
fmt.Printf(" run `push %s` to send it\n", *forNode)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The whole line only when the address is known. A URL with a placeholder where the host
|
||||
// should be is a URL somebody pastes and then debugs, and the placeholder is the last thing
|
||||
// they look at.
|
||||
if known, err := broker.FromEnvironment(); err == nil {
|
||||
fmt.Printf(" MESH_BROKER_AMQP=amqps://%s:%s@%s/\n\n", name, password, known.Address)
|
||||
} else {
|
||||
fmt.Printf(" the password is %s\n\n", password)
|
||||
fmt.Printf(" This control plane has no %s, so it cannot say where the broker is.\n"+
|
||||
" Put the password in MESH_BROKER_AMQP on the build machine.\n\n",
|
||||
broker.AddressVar)
|
||||
}
|
||||
// Shown once, like a token, and for the same reason: what is stored is the broker's own hash
|
||||
// of it, and a control plane that could show it back would be a control plane that holds it.
|
||||
fmt.Println("This is the only time it is shown.")
|
||||
return nil
|
||||
return issueOnTheNewBus(ctx, inv, m, node, address)
|
||||
}
|
||||
|
||||
// buildBehind builds every module the mesh holds older than its source has.
|
||||
@@ -329,6 +347,14 @@ func buildBehind(ctx context.Context, wait time.Duration) error {
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
// Bases first: a module built before the module it stands on is built against the old one
|
||||
// and reports success (novox/hq 04-ISSUES/131).
|
||||
against, err := inv.BuiltAgainst(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stale = orderByBases(stale, against)
|
||||
|
||||
var failed []string
|
||||
for _, e := range stale {
|
||||
fmt.Printf("--- %s\n", e.Manifest.Module)
|
||||
@@ -368,7 +394,7 @@ func buildOne(ctx context.Context, source buildSource, path, ref string, wait ti
|
||||
}
|
||||
defer ident.Close()
|
||||
|
||||
server, err := link.Connect(nil, nil)
|
||||
server, err := connectLink(ctx, nil, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -382,6 +408,7 @@ func buildOne(ctx context.Context, source buildSource, path, ref string, wait ti
|
||||
Path: path,
|
||||
Ref: ref,
|
||||
Held: heldBy(ctx),
|
||||
Seats: seatBases(ctx),
|
||||
}
|
||||
fmt.Printf("asked for %s", source)
|
||||
if source.Seat != "" {
|
||||
@@ -395,7 +422,13 @@ func buildOne(ctx context.Context, source buildSource, path, ref string, wait ti
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
result, err := link.RequestBuild(ctx, server.Channel(), request, wait)
|
||||
ask, err := askOver(server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer ask.Close()
|
||||
|
||||
result, err := ask.Submit(ctx, request, wait)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -466,16 +499,22 @@ func buildAndShow(ctx context.Context, source buildSource, path, ref string, wai
|
||||
return err
|
||||
}
|
||||
defer ident.Close()
|
||||
server, err := link.Connect(nil, nil)
|
||||
server, err := connectLink(ctx, nil, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
result, err := link.RequestBuild(ctx, server.Channel(), link.BuildRequest{
|
||||
ask, err := askOver(server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer ask.Close()
|
||||
|
||||
result, err := ask.Submit(ctx, link.BuildRequest{
|
||||
ID: fmt.Sprintf("%s-%d", "build", time.Now().UnixNano()),
|
||||
Repository: repository, Path: path, Ref: ref,
|
||||
Held: heldBy(ctx),
|
||||
Held: heldBy(ctx), Seats: seatBases(ctx),
|
||||
}, wait)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -518,6 +557,16 @@ type answers struct {
|
||||
// a consequence of the refusals above: a node that does not resolve is not on the network, and
|
||||
// a mesh whose hub is that node has no hub.
|
||||
network string
|
||||
// untaken is, per machine, each assigned module whose resources the machine is holding as it
|
||||
// found them, and how many — a module that was assigned, sent, and is running none of what it
|
||||
// declares because nothing has taken it (novox/hq ADR 0100, 04-ISSUES/125).
|
||||
//
|
||||
// **Its absence cost an outage.** The module was assigned, the push reported success, this
|
||||
// command said the machine was doing everything it was told, and the module's three containers
|
||||
// did not exist. On the strength of those reports the predecessor's proxy was stopped and every
|
||||
// public name on the machine went dark. The holds were correct; they were recorded only in the
|
||||
// machine's own state file, and the one visible symptom was a count that did not add up.
|
||||
untaken map[string]map[string]int
|
||||
}
|
||||
|
||||
// heldBy is every artifact this mesh has built, for a build that may need one as its base.
|
||||
@@ -557,3 +606,16 @@ func heldBy(ctx context.Context) map[string]string {
|
||||
}
|
||||
return routed
|
||||
}
|
||||
|
||||
// askOver opens the way a build is asked for, on whichever bus the mesh is on.
|
||||
//
|
||||
// **One place chooses**, as everywhere else the bus change went (novox/hq ADR 0116 step 5). On the bus
|
||||
// the mesh runs on today this needs the controller's own connection, so it is handed one; on the bus
|
||||
// being built it dials, because a build request is a one-shot and holds nothing else.
|
||||
func askOver(_ *link.Server) (link.Builders, error) {
|
||||
address, err := broker.BusAddress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return link.BuildsOverNATS(address)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
)
|
||||
|
||||
// The bus's own certificate, made by the mesh rather than borrowed from an image.
|
||||
//
|
||||
// **The foundation asked a third-party image for a tool it never said must be there** (novox/hq
|
||||
// 04-ISSUES/146). The bootstrap made this certificate by running `openssl` inside the broker's
|
||||
// image, which worked while the broker was one that happened to carry it and stopped the day the
|
||||
// bus changed: the new one has a shell and no openssl, so the step exited 127 and no mesh could be
|
||||
// raised. Substituting another image the bundle names does not help — none of them carry it
|
||||
// either.
|
||||
//
|
||||
// So the program that needs a certificate makes one. It is the mesh's own binary, already on the
|
||||
// machine at this point in the bootstrap (the schema step ran it), and it needs nothing from the
|
||||
// image it writes into but a mounted directory.
|
||||
//
|
||||
// **Self-signed, and that is the design** — a host pins this server's exact certificate and
|
||||
// authenticates with a password (novox/hq ADR 0004). There is no authority above it to ask, and at
|
||||
// this moment in a bootstrap there is no mesh to ask one of.
|
||||
//
|
||||
// Idempotent, because the step is applied again on every reconcile and a second certificate would
|
||||
// be one the hosts that pinned the first no longer believe.
|
||||
|
||||
// busCertificateNames is what the bus is reached by: the container name on a mesh network, and the
|
||||
// loopback address the machine's own foundation dials.
|
||||
var busCertificateNames = []string{"mesh-broker"}
|
||||
|
||||
const busCertificateLife = 10 * 365 * 24 * time.Hour
|
||||
|
||||
// busCertificate makes the bus's certificate in a directory, or says whether one is there.
|
||||
//
|
||||
// broker certificate --into /tls make it if it is not there
|
||||
// broker certificate --check --into /tls exit non-zero unless a usable pair is
|
||||
func busCertificate(args []string) error {
|
||||
into, check := "", false
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--check":
|
||||
check = true
|
||||
case "--into":
|
||||
if i+1 >= len(args) {
|
||||
return errors.New("--into needs a directory")
|
||||
}
|
||||
into = args[i+1]
|
||||
i++
|
||||
default:
|
||||
return fmt.Errorf("broker certificate [--check] --into <directory>: %q", args[i])
|
||||
}
|
||||
}
|
||||
if into == "" {
|
||||
return errors.New("broker certificate [--check] --into <directory>")
|
||||
}
|
||||
crt, key := filepath.Join(into, "tls.crt"), filepath.Join(into, "tls.key")
|
||||
|
||||
if usable, err := busCertificateUsable(crt, key); err != nil {
|
||||
return err
|
||||
} else if usable {
|
||||
fmt.Printf("the bus already has a certificate at %s, and it was left alone\n", crt)
|
||||
return nil
|
||||
}
|
||||
if check {
|
||||
// Said as a failure, because that is what the caller asked: a bootstrap's verify runs
|
||||
// this and a false answer is what makes the step run.
|
||||
return fmt.Errorf("no usable certificate and key at %s", into)
|
||||
}
|
||||
return writeBusCertificate(crt, key)
|
||||
}
|
||||
|
||||
// busCertificateUsable says whether a certificate and its key are both there and parse.
|
||||
//
|
||||
// Both, and parsed rather than stat'ed: a half-written pair is the state a bootstrap interrupted
|
||||
// between the two files leaves behind, and a step that treated it as done would hand the server a
|
||||
// certificate with no key and report success.
|
||||
func busCertificateUsable(crt, key string) (bool, error) {
|
||||
certPEM, err := os.ReadFile(crt)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
keyPEM, err := os.ReadFile(key)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tlsPairParses(certPEM, keyPEM); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func tlsPairParses(certPEM, keyPEM []byte) (*x509.Certificate, error) {
|
||||
block, _ := pem.Decode(certPEM)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return nil, errors.New("not a certificate")
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyBlock, _ := pem.Decode(keyPEM)
|
||||
if keyBlock == nil {
|
||||
return nil, errors.New("not a key")
|
||||
}
|
||||
if _, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes); err != nil {
|
||||
if _, err := x509.ParsePKCS1PrivateKey(keyBlock.Bytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return certificate, nil
|
||||
}
|
||||
|
||||
func writeBusCertificate(crt, key string) error {
|
||||
private, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: busCertificateNames[0]},
|
||||
DNSNames: busCertificateNames,
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(busCertificateLife),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &private.PublicKey, private)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pkcs8, err := x509.MarshalPKCS8PrivateKey(private)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// **The key first, and only then the certificate**, so the pair a reader finds is never a
|
||||
// certificate whose key has not been written yet — the one order in which an interruption
|
||||
// leaves something that looks finished (novox/hq 04-ISSUES/014, a key present and unusable).
|
||||
if err := os.WriteFile(key, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(crt, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("made the bus a certificate for %v, valid until %s\n %s\n %s\n",
|
||||
busCertificateNames, template.NotAfter.Format(time.RFC3339), crt, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// busAccounts writes the mesh's composed user list to a file.
|
||||
//
|
||||
// **For genesis, where no declaration can deliver it** (novox/hq 04-ISSUES/146). Everywhere else
|
||||
// the list reaches the machine running the bus as a resource of the module that holds it — which
|
||||
// requires that machine to be an enrolled node, and at genesis it is not: the first node cannot
|
||||
// enrol because the account it would enrol with cannot be composed onto a bus it has no declaration
|
||||
// for. The installer breaks that circle by placing the file itself, once, and the module takes the
|
||||
// file over from its first push.
|
||||
//
|
||||
// The same composition, not a second one: this asks the store for the same records and renders them
|
||||
// with the same composer the declaration uses. A genesis that hand-wrote an account would be a
|
||||
// second statement of who may say what, able to disagree with the first.
|
||||
//
|
||||
// **It writes to standard output unless told a file**, and that is the point: the control plane
|
||||
// composes and says what it composed, and whoever is raising the machine puts it where that
|
||||
// machine's bus reads it. A control plane that wrote into the bus's own directory would have to
|
||||
// know where that is and how to make the server re-read it — which is the module's knowledge, and
|
||||
// the module is what takes this over on the first push.
|
||||
//
|
||||
// broker accounts > /var/lib/mesh-bus-conf/accounts.conf
|
||||
func busAccounts(ctx context.Context, args []string) error {
|
||||
into := ""
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--into":
|
||||
if i+1 >= len(args) {
|
||||
return errors.New("--into needs a file")
|
||||
}
|
||||
into = args[i+1]
|
||||
i++
|
||||
default:
|
||||
return fmt.Errorf("broker accounts --into <file>: %q", args[i])
|
||||
}
|
||||
}
|
||||
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
|
||||
records, err := open.inventory.BusRecords(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
users, err := broker.Users(records)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kept, err := open.inventory.BusUsers(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hashes := make(map[string]string, len(kept))
|
||||
for name, u := range kept {
|
||||
hashes[name] = u.PasswordHash
|
||||
}
|
||||
filled, missing := broker.WithPasswords(users, hashes)
|
||||
if len(missing) > 0 {
|
||||
// To standard error, always: the composed file may be going to standard output, and a
|
||||
// remark in the middle of it is a configuration the server refuses to parse.
|
||||
fmt.Fprintf(os.Stderr, "leaving out %d user(s) the mesh has minted no credential for: %s\n",
|
||||
len(missing), strings.Join(missing, ", "))
|
||||
}
|
||||
if len(filled) == 0 {
|
||||
return errors.New("not one user has a credential, so this list would refuse every " +
|
||||
"connection in the mesh")
|
||||
}
|
||||
accounts, err := broker.ComposeAccounts(filled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if into == "" {
|
||||
fmt.Print(accounts)
|
||||
return nil
|
||||
}
|
||||
if err := os.WriteFile(into, []byte(accounts), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("wrote %d user(s) to %s\n", len(filled), into)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// novox/hq 04-ISSUES/146. The bootstrap could not make the bus a certificate: it asked an image for
|
||||
// `openssl` and the image it asks has none. What replaces it is this command, so what is checked is
|
||||
// what the bootstrap needs from it — a pair a TLS server can actually load, made once and only once.
|
||||
|
||||
func TestTheBusCertificateLoadsAsAServersWould(t *testing.T) {
|
||||
into := t.TempDir()
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatalf("the bus could not be given a certificate: %v", err)
|
||||
}
|
||||
|
||||
// The check a cheaper test would not make. The key was present and valid and the server could
|
||||
// not start, once, because nothing loaded the pair the way a server loads it
|
||||
// (novox/hq 04-ISSUES/014).
|
||||
pair, err := tls.LoadX509KeyPair(filepath.Join(into, "tls.crt"), filepath.Join(into, "tls.key"))
|
||||
if err != nil {
|
||||
t.Fatalf("a TLS server cannot load what was written: %v", err)
|
||||
}
|
||||
leaf := pair.Leaf
|
||||
if leaf == nil {
|
||||
if leaf, err = x509.ParseCertificate(pair.Certificate[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := leaf.VerifyHostname("mesh-broker"); err != nil {
|
||||
t.Errorf("the certificate is not for the name the bus is reached by: %v", err)
|
||||
}
|
||||
if len(leaf.IPAddresses) == 0 || leaf.IPAddresses[0].String() != "127.0.0.1" {
|
||||
t.Errorf("the certificate does not cover the loopback address the foundation dials: %v", leaf.IPAddresses)
|
||||
}
|
||||
|
||||
// The key is not readable by anything else on the machine; the certificate is public and is.
|
||||
key, err := os.Stat(filepath.Join(into, "tls.key"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if key.Mode().Perm() != 0o600 {
|
||||
t.Errorf("the key is %v", key.Mode().Perm())
|
||||
}
|
||||
crt, err := os.Stat(filepath.Join(into, "tls.crt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if crt.Mode().Perm() != 0o644 {
|
||||
t.Errorf("the certificate is %v, which the server runs as another user cannot read", crt.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// **Made once.** The step is applied again on every reconcile, and a second certificate is one the
|
||||
// hosts that pinned the first no longer believe (novox/hq ADR 0004).
|
||||
func TestTheBusCertificateIsMadeOnce(t *testing.T) {
|
||||
into := t.TempDir()
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := os.ReadFile(filepath.Join(into, "tls.crt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := os.ReadFile(filepath.Join(into, "tls.crt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(first) != string(again) {
|
||||
t.Fatal("running it twice replaced the certificate every host had pinned")
|
||||
}
|
||||
}
|
||||
|
||||
// The verify half: false before, true after, which is what makes the bootstrap run the step at all.
|
||||
func TestTheCheckIsFalseUntilThereIsAPair(t *testing.T) {
|
||||
into := t.TempDir()
|
||||
if err := busCertificate([]string{"--check", "--into", into}); err == nil {
|
||||
t.Fatal("an empty directory reported a usable certificate")
|
||||
}
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := busCertificate([]string{"--check", "--into", into}); err != nil {
|
||||
t.Fatalf("the certificate it just made does not satisfy its own check: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A half-written pair is not a pair. An interrupted bootstrap leaves exactly this, and a step that
|
||||
// called it done would hand the server a certificate with no key and report success.
|
||||
func TestACertificateWithoutItsKeyIsNotUsable(t *testing.T) {
|
||||
into := t.TempDir()
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(filepath.Join(into, "tls.key")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := busCertificate([]string{"--check", "--into", into}); err == nil {
|
||||
t.Fatal("a certificate with no key passed the check")
|
||||
}
|
||||
if err := busCertificate([]string{"--into", into}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tls.LoadX509KeyPair(filepath.Join(into, "tls.crt"), filepath.Join(into, "tls.key")); err != nil {
|
||||
t.Fatalf("it did not replace the unusable pair: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhereToWriteIsRequired(t *testing.T) {
|
||||
if err := busCertificate(nil); err == nil || !strings.Contains(err.Error(), "--into") {
|
||||
t.Fatalf("it did not ask where to write: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// moduleCheck judges manifests where they are written, with no mesh (novox/hq ADR 0037, issue 148).
|
||||
//
|
||||
// **The same functions registration runs, and nothing the command line adds** (ADR 0035): the strict
|
||||
// parse with every per-manifest problem, then the rules no single manifest can be judged against,
|
||||
// over exactly the manifests given. Somebody describing their own application in their own
|
||||
// repository runs this before pushing and finds out there, rather than when a running mesh refuses
|
||||
// the registration or, later, when a machine applies something that resolved and should not have.
|
||||
//
|
||||
// **What it cannot know without a store, it says.** The mesh's own seat set is the store's (ADR
|
||||
// 0122); this binary carries a compiled copy that the store overrides when loaded, so a claim on a
|
||||
// mesh seat is judged fully only at registration. A seat another module declares is unknown unless
|
||||
// that module's manifest is passed too. Both are printed as a note, not as a problem — a check that
|
||||
// refused what it could not see would teach people to ignore it.
|
||||
func moduleCheck(paths []string, out io.Writer) error {
|
||||
if len(paths) == 0 {
|
||||
return errors.New("module check <manifest.json>... — one file per module; pass every " +
|
||||
"manifest of a repository together so the rules between them are checked too")
|
||||
}
|
||||
shelf := catalogue.Shelf{}
|
||||
faulted := map[string]bool{}
|
||||
failed := 0
|
||||
for _, path := range paths {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(out, "%s: %v\n", path, err)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
m, err := catalogue.ParseManifest(raw)
|
||||
if err != nil {
|
||||
fmt.Fprintf(out, "%s: %v\n", path, err)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
if first, twice := shelf[m.Module]; twice {
|
||||
_ = first
|
||||
fmt.Fprintf(out, "%s: %s was already given; two manifests name one module\n", path, m.Module)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
// A definition names no installation (novox/hq ADR 0112, ADR 0155): judged here and in the
|
||||
// catalogue-wide test, not yet at registration, while the declared exceptions shrink.
|
||||
if named := catalogue.InstallationProblems(m); len(named) > 0 {
|
||||
for _, p := range named {
|
||||
fmt.Fprintf(out, "%s: %s\n", path, p)
|
||||
}
|
||||
failed += len(named)
|
||||
faulted[m.Module] = true
|
||||
}
|
||||
shelf[m.Module] = m
|
||||
}
|
||||
|
||||
// Between the manifests: a seat declared twice, a use of a seat nothing declares, a claim on
|
||||
// a seat that does not exist. Run only over what parsed, because a problem inside one manifest
|
||||
// has already been said and would be said again here in a worse form.
|
||||
problems := catalogue.CatalogueProblems(shelf)
|
||||
sort.Strings(problems)
|
||||
for _, p := range problems {
|
||||
fmt.Fprintln(out, p)
|
||||
}
|
||||
failed += len(problems)
|
||||
|
||||
var names []string
|
||||
for name := range shelf {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
m := shelf[name]
|
||||
if faulted[name] {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(out, "%s: ok", name)
|
||||
if n := len(m.Tools); n > 0 {
|
||||
fmt.Fprintf(out, ", %d tool(s)", n)
|
||||
}
|
||||
if len(m.Invokes) > 0 {
|
||||
fmt.Fprintf(out, ", invokes %s", joinInvokes(m.Invokes))
|
||||
}
|
||||
fmt.Fprintln(out)
|
||||
}
|
||||
if failed > 0 {
|
||||
return fmt.Errorf("%d problem(s) in %d manifest(s)", failed, len(paths))
|
||||
}
|
||||
fmt.Fprintf(out, "%d manifest(s) checked. Judged against the seats this binary carries; a claim on "+
|
||||
"one of the mesh's own seats is judged fully at registration, and a seat declared by a "+
|
||||
"module not given here reads as unknown\n", len(paths))
|
||||
return nil
|
||||
}
|
||||
|
||||
func joinInvokes(invokes []string) string {
|
||||
if len(invokes) == 1 && invokes[0] == "*" {
|
||||
return "every tool"
|
||||
}
|
||||
s := ""
|
||||
for i, t := range invokes {
|
||||
if i > 0 {
|
||||
s += ", "
|
||||
}
|
||||
s += t
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// manifestsUnder lists every module.json below a directory, for `module check <dir>`.
|
||||
func manifestsUnder(dir string) ([]string, error) {
|
||||
var found []string
|
||||
err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() && (d.Name() == "node_modules" || d.Name() == ".git" || d.Name() == "dist") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if !d.IsDir() && d.Name() == "module.json" {
|
||||
found = append(found, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Strings(found)
|
||||
return found, err
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The check anybody can run is the check registration runs (novox/hq issue 148, ADR 0037): a manifest
|
||||
// with a known fault is named, and one without passes, with no store opened.
|
||||
func TestModuleCheckNamesAFaultAndNeedsNoMesh(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
good := filepath.Join(dir, "good.json")
|
||||
bad := filepath.Join(dir, "bad.json")
|
||||
os.WriteFile(good, []byte(`{"module":"shop","version":"1","tools":["price"],"invokes":["mesh-catalog.catalog_modules"]}`), 0o600)
|
||||
os.WriteFile(bad, []byte(`{"module":"till","version":"1","invokes":["shop"]}`), 0o600)
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := moduleCheck([]string{good}, &out); err != nil {
|
||||
t.Fatalf("a sound manifest was refused: %v\n%s", err, out.String())
|
||||
}
|
||||
if !strings.Contains(out.String(), "shop: ok, 1 tool(s), invokes mesh-catalog.catalog_modules") {
|
||||
t.Fatalf("the report does not say what it checked:\n%s", out.String())
|
||||
}
|
||||
|
||||
out.Reset()
|
||||
err := moduleCheck([]string{good, bad}, &out)
|
||||
if err == nil {
|
||||
t.Fatal("a manifest invoking a module and no tool passed")
|
||||
}
|
||||
if !strings.Contains(out.String(), `till invokes "shop", which does not name a tool`) {
|
||||
t.Fatalf("the fault is not named in the manifest's words:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The rules between manifests run over what was given together: a seat two modules declare is
|
||||
// refused, which no single-manifest check can see.
|
||||
func TestModuleCheckJudgesBetweenTheManifestsGiven(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := filepath.Join(dir, "a.json")
|
||||
b := filepath.Join(dir, "b.json")
|
||||
os.WriteFile(a, []byte(`{"module":"a","version":"1","seats":[{"name":"printer","scope":"mesh"}]}`), 0o600)
|
||||
os.WriteFile(b, []byte(`{"module":"b","version":"1","seats":[{"name":"printer","scope":"mesh"}]}`), 0o600)
|
||||
var out bytes.Buffer
|
||||
if err := moduleCheck([]string{a, b}, &out); err == nil {
|
||||
t.Fatalf("two declarations of one seat passed:\n%s", out.String())
|
||||
}
|
||||
if !strings.Contains(out.String(), "a seat name means one protocol") {
|
||||
t.Fatalf("the cross-manifest rule was not the one named:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The real catalogue passes the command, the way it passes the test that used to be the only check.
|
||||
func TestModuleCheckPassesTheCatalogue(t *testing.T) {
|
||||
root := filepath.Join("..", "..", "..", "mesh-catalog", "modules")
|
||||
if _, err := os.Stat(root); err != nil {
|
||||
t.Skipf("catalogue sibling not present: %v", err)
|
||||
}
|
||||
paths, err := manifestsUnder(root)
|
||||
if err != nil || len(paths) == 0 {
|
||||
t.Fatalf("no manifests under %s: %v", root, err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := moduleCheck(paths, &out); err != nil {
|
||||
t.Fatalf("the catalogue does not pass its own check: %v\n%s", err, out.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// recordDerivedHolders writes down who holds each mesh-scoped seat that nobody was ever recorded
|
||||
// as holding.
|
||||
//
|
||||
// **A seat held by derivation is a seat held by accident of being alone** (novox/hq
|
||||
// 04-ISSUES/170). ADR 0131 lets a holder on record settle a seat, and lets any other assignment
|
||||
// whose module could hold it stand beside the holder, eligible and silent. But a seat nobody
|
||||
// ever handed over has no record, so its holder is whichever assignment happened to be the sole
|
||||
// claimant — and the day a second one is assigned, both claim, both are refused, and the first
|
||||
// one's whole machine stops resolving. That is what assigning a second postgres did to the
|
||||
// control plane's own store.
|
||||
//
|
||||
// So the mesh writes the derived answer down before it acts on an assignment: for every
|
||||
// mesh-scoped seat with exactly one resolved holder and nothing on record, that holder is
|
||||
// recorded as the standing one — the same record `seat <name> --to <node>/<module>` makes by
|
||||
// hand, made from what the mesh already resolved. A seat with two derived claimants is left
|
||||
// alone: that is the ambiguity a person settles, and recording either would be guessing.
|
||||
//
|
||||
// Node-scoped seats are untouched: a record is one holder per seat, and a node-scoped seat has
|
||||
// one holder per machine (ADR 0121), so there is nothing for a record to settle there.
|
||||
func recordDerivedHolders(ctx context.Context, open *stores) ([]string, error) {
|
||||
inv := open.inventory
|
||||
shelf, err := inv.Catalogue(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// exclude nobody: every node's claims, resolved with the holdings on record.
|
||||
world, err := theRestOfTheMesh(ctx, inv, shelf, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recorded, err := inv.Holdings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A record is a row against a seat the store knows. A seat it does not — a mesh whose seats
|
||||
// were never seeded, a seat a module declares for itself — stays held by derivation, as it
|
||||
// always was; a missing row is not a reason an assignment fails.
|
||||
known, err := inv.Seats(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recordable := map[string]bool{}
|
||||
for _, s := range known {
|
||||
recordable[s.Name] = true
|
||||
}
|
||||
onRecord := map[string]bool{}
|
||||
for _, h := range recorded {
|
||||
if s, ok := catalogue.SeatNamed(h.Claim); ok {
|
||||
onRecord[s.Name] = true
|
||||
}
|
||||
}
|
||||
holders := map[string][]catalogue.Held{}
|
||||
for _, h := range world.Held {
|
||||
if h.Scope != catalogue.ScopeMesh {
|
||||
continue
|
||||
}
|
||||
s, ok := catalogue.SeatNamed(h.Claim)
|
||||
if !ok || onRecord[s.Name] || !recordable[s.Name] {
|
||||
continue
|
||||
}
|
||||
holders[s.Name] = append(holders[s.Name], h)
|
||||
}
|
||||
names := make([]string, 0, len(holders))
|
||||
for name := range holders {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
var said []string
|
||||
for _, name := range names {
|
||||
if len(holders[name]) != 1 {
|
||||
continue
|
||||
}
|
||||
h := holders[name][0]
|
||||
if err := inv.HoldSeat(ctx, name, catalogue.ScopeMesh, h.Node, h.Module); err != nil {
|
||||
return said, err
|
||||
}
|
||||
said = append(said, fmt.Sprintf(
|
||||
"recorded %s on %s as the standing holder of %s, which it held only by being alone",
|
||||
h.Module, h.Node, name))
|
||||
}
|
||||
return said, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// A seat nobody ever handed over is held by whichever assignment happened to be alone — and the
|
||||
// day a second module able to hold it is assigned, both claimed, both were refused, and the first
|
||||
// one's machine stopped resolving (novox/hq 04-ISSUES/170). The mesh now writes the derived holder
|
||||
// down before it acts, so the second assignment stands beside the holder on record.
|
||||
|
||||
func aSeatedStore() catalogue.Manifest {
|
||||
return catalogue.Manifest{Module: "store", Version: "1",
|
||||
Provides: []catalogue.Offer{{Name: "postgres-database", Scope: catalogue.ScopeMesh}},
|
||||
Serves: map[string]map[string]any{"postgres-database": {"port": 5432}},
|
||||
Claims: []catalogue.Claim{{Name: "mesh-store", Scope: catalogue.ScopeMesh}}}
|
||||
}
|
||||
|
||||
func TestASecondEligibleHolderStandsBesideTheOneHeldByBeingAlone(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
ctx := t.Context()
|
||||
// Every deploy seeds the mesh's own seats; a record is a row against one of them.
|
||||
if _, err := open.inventory.SeedSeats(ctx, catalogue.DefaultSeats()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
register(t, open, aSeatedStore())
|
||||
|
||||
if _, err := assign(ctx, open, "anchor", "store"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
said, err := assign(ctx, open, "laptop", "store")
|
||||
if err != nil {
|
||||
t.Fatalf("a second store, eligible for the seat, was refused:\n%s\n%v", said, err)
|
||||
}
|
||||
if strings.Contains(said, "cannot be worked out") {
|
||||
t.Fatalf("assigning a second store unsettled the first one's machine:\n%s", said)
|
||||
}
|
||||
if !strings.Contains(said, "recorded store on anchor as the standing holder of mesh-store") {
|
||||
t.Fatalf("the holder by derivation was not written down:\n%s", said)
|
||||
}
|
||||
|
||||
holdings, err := open.inventory.Holdings(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var found bool
|
||||
for _, h := range holdings {
|
||||
if h.Claim == "mesh-store" {
|
||||
found = true
|
||||
if h.Node != "anchor" || h.Module != "store" {
|
||||
t.Fatalf("mesh-store is recorded on %s/%s, not on the one that held it", h.Node, h.Module)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("mesh-store has no holder on record after assigning: %v", holdings)
|
||||
}
|
||||
|
||||
// And the record decides from here: the anchor's plan holds the seat, the laptop's does not.
|
||||
for node, holds := range map[string]bool{"anchor": true, "laptop": false} {
|
||||
plan, _, err := planFor(ctx, open, node)
|
||||
if err != nil {
|
||||
t.Fatalf("%s no longer resolves: %v", node, err)
|
||||
}
|
||||
var claimed bool
|
||||
for _, c := range plan.Claims {
|
||||
if c.Claim == "mesh-store" {
|
||||
claimed = true
|
||||
}
|
||||
}
|
||||
if claimed != holds {
|
||||
t.Fatalf("%s holds mesh-store: %v, want %v", node, claimed, holds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHolderOnRecordIsNotRewrittenByDerivation(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
ctx := t.Context()
|
||||
if _, err := open.inventory.SeedSeats(ctx, catalogue.DefaultSeats()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
register(t, open, aSeatedStore())
|
||||
for _, node := range []string{"anchor", "laptop"} {
|
||||
if _, err := assign(ctx, open, node, "store"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// A person hands the seat to the laptop. From here the record decides, and what the mesh
|
||||
// derives must never write over it.
|
||||
if err := open.inventory.HoldSeat(ctx, "mesh-store", catalogue.ScopeMesh, "laptop", "store"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
said, err := recordDerivedHolders(ctx, open)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(said) != 0 {
|
||||
t.Fatalf("a seat on record was written again from derivation: %v", said)
|
||||
}
|
||||
holdings, _ := open.inventory.Holdings(ctx)
|
||||
for _, h := range holdings {
|
||||
if h.Claim == "mesh-store" && h.Node != "laptop" {
|
||||
t.Fatalf("the record moved to %s", h.Node)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
)
|
||||
|
||||
// A host refuses a declaration carrying a field it does not know, and refuses it whole — so every new
|
||||
// field is a flag day, and the mesh had no record of which host any machine ran (novox/hq
|
||||
// 04-ISSUES/087). The order was kept by somebody remembering it.
|
||||
|
||||
func TestTheMeshNamesWhichMachinesRunWhichHost(t *testing.T) {
|
||||
split := hostSplit([]inventory.Node{
|
||||
{Name: "anchor", HostVersion: "04a27ca"},
|
||||
{Name: "laptop", HostVersion: "ced54d4"},
|
||||
{Name: "spare", HostVersion: "04a27ca"},
|
||||
})
|
||||
if len(split) != 2 {
|
||||
t.Fatalf("two versions were reported and the split has %d: %v", len(split), split)
|
||||
}
|
||||
if got := strings.Join(split["04a27ca"], ","); got != "anchor,spare" && got != "spare,anchor" {
|
||||
t.Fatalf("04a27ca is held by %q", got)
|
||||
}
|
||||
if got := strings.Join(split["ced54d4"], ","); got != "laptop" {
|
||||
t.Fatalf("ced54d4 is held by %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMeshDoesNotClaimWhichHostIsNewer(t *testing.T) {
|
||||
// **The fault this replaced.** A host reports its version as a commit, and commits have no order.
|
||||
// The first version compared them as strings and, on the live mesh, named the three machines
|
||||
// running the NEWER host as the ones behind: `ced54d4` sorts above `04a27ca` and means nothing.
|
||||
//
|
||||
// There is no assertion to make about which is newer, and that is the point — the type says so.
|
||||
// hostSplit returns who runs what, and nothing that could be read as an ordering.
|
||||
split := hostSplit([]inventory.Node{
|
||||
{Name: "old-but-sorts-high", HostVersion: "ced54d4"},
|
||||
{Name: "new-but-sorts-low", HostVersion: "04a27ca"},
|
||||
})
|
||||
for version, machines := range split {
|
||||
if len(machines) != 1 {
|
||||
t.Fatalf("%s is held by %v", version, machines)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMachineThatHasNotSaidIsNotAVersion(t *testing.T) {
|
||||
// It may be running anything. Counting it as a version would invent a disagreement; `node show`
|
||||
// says per machine that it has not said.
|
||||
split := hostSplit([]inventory.Node{
|
||||
{Name: "anchor", HostVersion: "04a27ca"},
|
||||
{Name: "quiet"},
|
||||
})
|
||||
if split != nil {
|
||||
t.Fatalf("one reported version and one silence read as a disagreement: %v", split)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMachinesAgreeingOnTheirHostAreNotADisagreement(t *testing.T) {
|
||||
if split := hostSplit([]inventory.Node{
|
||||
{Name: "anchor", HostVersion: "v2"},
|
||||
{Name: "laptop", HostVersion: "v2"},
|
||||
}); split != nil {
|
||||
t.Fatalf("machines agreeing reported a split: %v", split)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMeshWhereNothingReportedAHostStatesNoDisagreement(t *testing.T) {
|
||||
if split := hostSplit([]inventory.Node{{Name: "anchor"}, {Name: "laptop"}}); split != nil {
|
||||
t.Fatalf("a mesh told no host version reported a split: %v", split)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAReportedHostVersionIsKeptAndReadBack(t *testing.T) {
|
||||
// The machine has sent this since ADR 0141 and the controller's own copy of the report did not
|
||||
// have the field, so it was unmarshalled into nothing. End to end through the store, because the
|
||||
// fault was a field that existed on one side of the wire only.
|
||||
open := aMesh(t)
|
||||
record, err := open.inventory.NodeByName(t.Context(), "anchor")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.HostVersion != "" {
|
||||
t.Fatalf("a machine that never reported one has host version %q", record.HostVersion)
|
||||
}
|
||||
if err := open.inventory.RecordHostVersion(t.Context(), record.ID, "ced54d4"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := open.inventory.NodeByName(t.Context(), "anchor")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again.HostVersion != "ced54d4" {
|
||||
t.Fatalf("the reported host version read back as %q", again.HostVersion)
|
||||
}
|
||||
// An empty report never clears what a machine last said: a bare word that the node is there says
|
||||
// nothing about its host.
|
||||
if err := open.inventory.RecordHostVersion(t.Context(), record.ID, " "); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, err := open.inventory.NodeByName(t.Context(), "anchor")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept.HostVersion != "ced54d4" {
|
||||
t.Fatalf("a report carrying no host version cleared what the machine had said: %q",
|
||||
kept.HostVersion)
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,10 @@ func run() error {
|
||||
return pinCommand(ctx, args[1:], true)
|
||||
case "unpin":
|
||||
return pinCommand(ctx, args[1:], false)
|
||||
case "migrate":
|
||||
// `prepare` is how the mesh asks any module to bring its state to the shape this version needs
|
||||
// (novox/hq ADR 0135), and the control plane answers it the same way as everything else — its
|
||||
// own schema is not a special case. `migrate` remains the word a person types.
|
||||
case "prepare", "migrate":
|
||||
return migrate(ctx)
|
||||
case "node":
|
||||
return nodeCommand(ctx, args[1:])
|
||||
@@ -85,7 +88,7 @@ func run() error {
|
||||
case "identity":
|
||||
return identityCommand(ctx, args[1:])
|
||||
case "broker":
|
||||
return brokerCommand(args[1:])
|
||||
return brokerCommand(ctx, args[1:])
|
||||
case "serve":
|
||||
return serve(ctx)
|
||||
case "upgrade":
|
||||
@@ -114,8 +117,12 @@ func run() error {
|
||||
return planCommand(ctx, args[1:])
|
||||
case "push":
|
||||
return pushCommand(ctx, args[1:])
|
||||
case "rollout":
|
||||
return rolloutCommand(ctx, args[1:])
|
||||
case "seats":
|
||||
return seatsCommand(ctx, args[1:])
|
||||
case "seat":
|
||||
return seatCommand(ctx, args[1:])
|
||||
case "status":
|
||||
return statusCommand(ctx, args[1:])
|
||||
case "version":
|
||||
@@ -134,12 +141,16 @@ func usage() {
|
||||
fmt.Fprint(os.Stderr, `mesh-controller — the control plane
|
||||
|
||||
migrate bring each context's schema up to date
|
||||
prepare the same, asked the way the mesh asks any module (ADR 0135)
|
||||
node add <name> [--adopted] create a node record; --adopted: the machine is in use
|
||||
node list the nodes this mesh knows about
|
||||
node show <name> what one machine reported it can do, and why
|
||||
node public-domain <name> the domain it composes its routed names under
|
||||
node public-domain <name> <d> ...set it to d
|
||||
node public-domain <name> --clear ...it faces the outside no longer
|
||||
node networks <name> the networks it routes for what it hosts
|
||||
node networks <name> <cidr>... ...set them; its filter forwards these too
|
||||
node networks <name> --clear ...only the container runtime's own
|
||||
token issue --node <name> a one-time right to join, for an existing record
|
||||
token issue --new <name> create the record and issue for it
|
||||
token issue ... --adopted ...for a machine in use, which joins adopted
|
||||
@@ -150,6 +161,7 @@ func usage() {
|
||||
overlay place <node> [flags] say where a node is and how it is reached
|
||||
overlay show the private network, as the mesh computes it
|
||||
module add <file> register a module from its manifest
|
||||
module check <file|dir>... judge manifests where they are written, with no mesh (exit 1 on any problem)
|
||||
module list what modules this mesh knows about
|
||||
module moved <name> <commit> the source has a newer commit than the mesh built
|
||||
module forget <name> remove one, unless a node runs it or the mesh holds things for it
|
||||
@@ -180,6 +192,7 @@ func usage() {
|
||||
operator key show the operator key, and what it can recover
|
||||
build <repository> [--ref R] have a build machine build it, and record what came out
|
||||
build --behind build every module the mesh holds older than its source
|
||||
build --on <module> rebuild every module that stands on this module's artifacts, bases first
|
||||
builds [<module>] what has been built lately, and what came of it
|
||||
builder issue <name> a broker account for a build machine, scoped to build work,
|
||||
delivered as the builder module's broker secret (module add it first)
|
||||
|
||||
+167
-72
@@ -2,8 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
@@ -56,7 +54,24 @@ var provided = providedModules()
|
||||
|
||||
func moduleCommand(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errors.New("module add <file>, module list, or module forget <name>")
|
||||
return errors.New("module add <file>, module check <file>..., module list, or module forget <name>")
|
||||
}
|
||||
// `check` needs no mesh, and must not: it is what somebody runs in their own repository before
|
||||
// there is a mesh in reach (novox/hq issue 148). A directory expands to every manifest under it.
|
||||
if args[0] == "check" {
|
||||
var paths []string
|
||||
for _, a := range args[1:] {
|
||||
if info, err := os.Stat(a); err == nil && info.IsDir() {
|
||||
under, err := manifestsUnder(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
paths = append(paths, under...)
|
||||
continue
|
||||
}
|
||||
paths = append(paths, a)
|
||||
}
|
||||
return moduleCheck(paths, os.Stdout)
|
||||
}
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
@@ -71,12 +86,20 @@ func moduleCommand(ctx context.Context, args []string) error {
|
||||
repo := set.String("source", "", "where this module comes from")
|
||||
ref := set.String("ref", "", "the branch followed there")
|
||||
commit := set.String("commit", "", "the commit this manifest was read at")
|
||||
// **Where inside the repository the module is** (novox/hq ADR 0069). A module is a
|
||||
// repository *and* a directory, and a record that carries only the repository names a
|
||||
// module.json at its root — so every later build of it looks in the wrong place and fails
|
||||
// with "no module.json at its root". Nine modules on this mesh were registered that way
|
||||
// and none of them could be rebuilt (2026-09-28).
|
||||
path := set.String("path", "", "the module's directory inside that repository")
|
||||
self := set.Bool("self", false, "the source is a path on the forge holding the git seat")
|
||||
positionals, err := parseAround(set, args[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(positionals) != 1 {
|
||||
return errors.New("module add <manifest.json> [--source <repo> --ref <branch> --commit <sha>]")
|
||||
return errors.New("module add <manifest.json> [--source <repo> [--self] [--path P] " +
|
||||
"--ref <branch> --commit <sha>]")
|
||||
}
|
||||
raw, err := os.ReadFile(positionals[0])
|
||||
if err != nil {
|
||||
@@ -86,23 +109,24 @@ func moduleCommand(ctx context.Context, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Provenance together or not at all. A source with no commit cannot be compared against
|
||||
// anything, so it would record where the module came from and still never be able to say
|
||||
// the mesh is behind it — which is the one thing recording it is for.
|
||||
if (*repo == "") != (*commit == "") {
|
||||
return errors.New("--source and --commit go together: a source with no commit " +
|
||||
"cannot be compared against anything, and a commit with no source has nothing " +
|
||||
"to be compared with")
|
||||
from, err := whereItComesFrom(*repo, *ref, *commit, *path, *self)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.RegisterModule(ctx, m, inventory.Source{
|
||||
Repository: *repo, Ref: *ref, BuiltFrom: *commit,
|
||||
}); err != nil {
|
||||
if err := inv.RegisterModule(ctx, m, from); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s registered", m.Module)
|
||||
if *commit != "" {
|
||||
fmt.Printf(" from %s", short(*commit))
|
||||
}
|
||||
if *repo != "" && *path == "" {
|
||||
// Said, not refused: a module really at the root is the ordinary case for a repository
|
||||
// of its own. But a repository holding many modules and a record naming none of them is
|
||||
// a module nothing can rebuild, and the person adding it is the one who knows which.
|
||||
fmt.Printf("\n no directory inside %s, so it is built from that repository's root — "+
|
||||
"`--path` if the module lives in a directory there", *repo)
|
||||
}
|
||||
if len(m.Provides) > 0 {
|
||||
fmt.Printf(", providing %s", describeOffers(m.Provides))
|
||||
}
|
||||
@@ -257,69 +281,18 @@ func moduleCommand(ctx context.Context, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
management, err := broker.ManagementFromEnvironment()
|
||||
// Which bus this mesh is on. A module gets a credential for exactly one, and the two are
|
||||
// made in entirely different ways: on the bus the mesh runs on today an account is a
|
||||
// management call, and on the bus being built it is a row the next composition writes into
|
||||
// the server's user list (novox/hq design 25 §4).
|
||||
busAddress, err := broker.BusAddress()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The foundation owns the bus; make sure it exists before a module binds onto it.
|
||||
if err := management.EnsureEventExchanges(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
secret := make([]byte, 32)
|
||||
if _, err := rand.Read(secret); err != nil {
|
||||
return err
|
||||
}
|
||||
password := base64.RawURLEncoding.EncodeToString(secret)
|
||||
account, err := management.CreateModuleAccount(ctx, *forNode, module, password, m.Emits, m.Consumes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// A consumer's queue, with its dead-letter, is the foundation's to declare — its own account
|
||||
// may not (ADR 0043). Made now, so it exists before the module binds onto it.
|
||||
if len(m.Consumes) > 0 {
|
||||
if err := management.EnsureModuleQueue(ctx, *forNode, module); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
known, err := broker.FromEnvironment()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot deliver a credential without knowing where the broker is: %w", err)
|
||||
}
|
||||
brokerAddr, err := brokerReachableAt(ctx, inv, known, *forNode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The URL and what verifies the broker, together — a mesh's broker presents its own
|
||||
// certificate, in no public trust store, so a URL alone fails at TLS (as `builder issue`).
|
||||
held, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
Node string `json:"node"`
|
||||
Module string `json:"module"`
|
||||
}{
|
||||
URL: fmt.Sprintf("amqps://%s:%s@%s/", account, password, brokerAddr),
|
||||
Fingerprint: known.Fingerprint,
|
||||
// The node and module the account is for, so the runtime names its queue as the mesh
|
||||
// scoped it (<node>.<module>.events) without a manifest having to interpolate a node.
|
||||
Node: *forNode,
|
||||
Module: module,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.AcceptSecretForModule(ctx, *forNode, module, "broker", string(held)); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("broker account %s created for %s, scoped to what it emits and consumes\n",
|
||||
account, module)
|
||||
fmt.Printf(" sealed to %s. It arrives with the next push — `push %s` to send it\n",
|
||||
*forNode, *forNode)
|
||||
return nil
|
||||
return issueOnTheNewBus(ctx, inv, m, *forNode, busAddress)
|
||||
|
||||
default:
|
||||
return fmt.Errorf("module has no %q; it has add, list, moved, forget and issue", args[0])
|
||||
return fmt.Errorf("module has no %q; it has add, check, list, moved, forget and issue", args[0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,3 +540,125 @@ func mayIssue(m catalogue.Manifest) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// issueOnTheNewBus gives an assigned module its credential on the bus being built.
|
||||
//
|
||||
// **Three things differ from a management call, and each is the point of the move.** The credential
|
||||
// is minted into the mesh's records and becomes usable at the next composition, so there is no
|
||||
// server to be reachable for this to work. The password travels beside the address rather than inside
|
||||
// it, because the runtime's contract already separates them and a credential embedded in a URL is one
|
||||
// that leaks into every log line that prints a connection. And the module's durable consumer is
|
||||
// derived from what it declared rather than declared by name, so a module cannot ask for delivery of
|
||||
// something it did not say it consumes.
|
||||
func issueOnTheNewBus(ctx context.Context, inv *inventory.Inventory, m catalogue.Manifest,
|
||||
node, busAddress string) error {
|
||||
|
||||
user := broker.Principal{Kind: broker.KindModule, Node: node, Module: m.Module}.Username()
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{
|
||||
Username: user, Kind: inventory.BusModule, Node: node, Module: m.Module,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Where the module is told to find the bus, and what certificate it must present. The same pair
|
||||
// a node is told, for the same reason: a mesh's bus presents its own certificate, in no public
|
||||
// trust store, so an address alone fails at TLS.
|
||||
known, err := broker.FromEnvironment()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot deliver a credential without knowing where the bus is: %w", err)
|
||||
}
|
||||
reachable, err := brokerReachableAt(ctx, inv, known, node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return issueWith(ctx, inv, m, node, busAddress, known, reachable, user, password)
|
||||
}
|
||||
|
||||
// issueWith is the delivery half: the minted password sealed to the machine as the module's broker
|
||||
// secret, and the module's consumer created where the bus can be reached. Split from the minting
|
||||
// so the move can issue every module against a bus whose address it worked out itself
|
||||
// (`rollout mint`, design 28 task 5.2) rather than the one in this process's environment.
|
||||
func issueWith(ctx context.Context, inv *inventory.Inventory, m catalogue.Manifest,
|
||||
node, busAddress string, known broker.Broker, reachable, user, password string) error {
|
||||
held, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
Node string `json:"node"`
|
||||
Module string `json:"module"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
}{
|
||||
URL: "nats://" + reachable, Fingerprint: known.Fingerprint,
|
||||
Node: node, Module: m.Module, User: user, Password: password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.AcceptSecretForModule(ctx, node, m.Module, "broker", string(held)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// And how it hears what it consumes. Derived from its declaration, and only when it declared
|
||||
// something: a module that consumes nothing needs no consumer, and creating one would be a
|
||||
// durable subscription nobody reads.
|
||||
if consumer, needed := broker.ConsumerFor(broker.Principal{
|
||||
Kind: broker.KindModule, Node: node, Module: m.Module,
|
||||
Emits: m.Emits, Consumes: m.Consumes, Serves: m.Tools,
|
||||
}); needed {
|
||||
if busAddress == "" {
|
||||
fmt.Printf(" %s consumes; its consumer is created when the bus is reachable (`push`, then "+
|
||||
"`rollout mint` again is harmless)\n", m.Module)
|
||||
} else {
|
||||
js, err := broker.Dial(busAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the credential is minted and the mesh cannot reach the bus to create "+
|
||||
"how %s hears what it consumes: %w", m.Module, err)
|
||||
}
|
||||
defer js.Close()
|
||||
if err := js.EnsureConsumer(consumer); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("bus user %s minted for %s, scoped to what it emits and consumes\n", user, m.Module)
|
||||
fmt.Printf(" sealed to %s. It arrives with the next push — `push %s` to send it\n", node, node)
|
||||
fmt.Printf(" and it works once the bus has been told: the user list is composed into the " +
|
||||
"machine holding mesh-broker\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
// whereItComesFrom is the provenance a module handed over by hand records, and what a record must
|
||||
// say to be worth anything later.
|
||||
//
|
||||
// **A module is a repository and a directory inside it** (novox/hq ADR 0069). A record carrying only
|
||||
// the repository names a module.json at its root, so every later build of it looks in the wrong
|
||||
// place — nine modules on this mesh were registered that way and none of them could be rebuilt
|
||||
// (2026-09-28). The directory cannot be checked from here, because the control plane does not clone;
|
||||
// what can be checked is that the record is whole.
|
||||
func whereItComesFrom(repository, ref, commit, path string, self bool) (inventory.Source, error) {
|
||||
// Provenance together or not at all. A source with no commit cannot be compared against
|
||||
// anything, so it would record where the module came from and still never be able to say the
|
||||
// mesh is behind it — which is the one thing recording it is for.
|
||||
if (repository == "") != (commit == "") {
|
||||
return inventory.Source{}, errors.New("--source and --commit go together: a source with " +
|
||||
"no commit cannot be compared against anything, and a commit with no source has " +
|
||||
"nothing to be compared with")
|
||||
}
|
||||
// A directory or a forge with no repository is half a location, and the half it keeps is the
|
||||
// half nothing can be found with.
|
||||
if repository == "" && (path != "" || self) {
|
||||
return inventory.Source{}, errors.New("--path and --self say where inside a source and " +
|
||||
"which forge holds it, so they need --source: without one there is nothing for them " +
|
||||
"to be part of")
|
||||
}
|
||||
from := inventory.Source{Repository: repository, Ref: ref, BuiltFrom: commit, Path: path}
|
||||
if self {
|
||||
if err := onASeat(repository); err != nil {
|
||||
return inventory.Source{}, err
|
||||
}
|
||||
from.Seat = gitSeat
|
||||
}
|
||||
return from, nil
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ func network(ctx context.Context, inv *inventory.Inventory, on map[string]bool,
|
||||
"Re-place it — `overlay place %s --hub --endpoint <host>:%d …` — and push again; "+
|
||||
"nothing was composed", p.Name, t.Interface, wrong, p.Name, t.Port)
|
||||
}
|
||||
n.TakesOver = &overlay.TakeOver{Interface: t.Interface, Unit: t.Unit, Config: t.Config, Port: t.Port}
|
||||
n.TakesOver = &overlay.TakeOver{Interface: t.Interface, Unit: t.Unit, Config: t.Config, Port: t.Port, MTU: t.MTU}
|
||||
}
|
||||
if p.Hub {
|
||||
for _, c := range carried {
|
||||
@@ -346,9 +346,16 @@ func whoResolves(ctx context.Context, open *stores, requirement string) (
|
||||
refused := map[string]string{}
|
||||
for _, n := range nodes {
|
||||
plan, _, err := planFor(ctx, open, n.Name)
|
||||
if err != nil {
|
||||
switch {
|
||||
case unresolvable(err):
|
||||
refused[n.Name] = err.Error()
|
||||
continue
|
||||
case err != nil:
|
||||
// Not a node that does not resolve — a question that went unanswered. Recording it as a
|
||||
// refusal would take the machine off the private network, and the generator that reads
|
||||
// this would then write a roster and a filter without it (novox/hq 04-ISSUES/152).
|
||||
return nil, nil, fmt.Errorf("whether %s answers %q cannot be read: %w",
|
||||
n.Name, requirement, err)
|
||||
}
|
||||
for _, m := range plan.Modules {
|
||||
for _, offered := range m.Offers() {
|
||||
@@ -537,6 +544,15 @@ func onTheNetwork(ctx context.Context, inv *inventory.Inventory,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// **With the seat holders on record**, or a machine running the next holder of a seat beside
|
||||
// the current one resolves as two holders, is refused, and drops out of the map — taking the
|
||||
// address every other machine composes for what it offers (novox/hq ADR 0131). Found live:
|
||||
// the control node vanished from the private network the moment the new bus was assigned
|
||||
// beside the old one.
|
||||
holdings, err := inv.Holdings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []inventory.Overlay
|
||||
for _, p := range places {
|
||||
if p.Address == "" {
|
||||
@@ -549,7 +565,7 @@ func onTheNetwork(ctx context.Context, inv *inventory.Inventory,
|
||||
caps, _ := inv.ProfileOf(ctx, p.Name)
|
||||
got, err := catalogue.Resolve(shelf, assigned,
|
||||
catalogue.Node{Name: p.Name, Site: p.Site, Capabilities: caps},
|
||||
catalogue.World{Unchecked: true})
|
||||
catalogue.World{Unchecked: true, Holdings: holdings})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
"github.com/novox/mesh-controller/internal/token"
|
||||
)
|
||||
|
||||
@@ -67,8 +66,26 @@ func nodeCommand(ctx context.Context, args []string) error {
|
||||
// because the damage is already done by the time it prints.
|
||||
return publicDomain(ctx, inv, args[1:])
|
||||
|
||||
case "networks":
|
||||
// Removed by novox/hq ADR 0140, which superseded the record that added it. The filter no
|
||||
// longer names any network: it constrains what arrives from outside the machine and says
|
||||
// nothing about what did not, so there is no list to keep. Answered rather than met with
|
||||
// "unknown command", because this was the documented way to stop a flip cutting a machine's
|
||||
// containers off and somebody will reasonably still type it.
|
||||
return errors.New("`node networks` is gone (novox/hq ADR 0140). The filter constrains what " +
|
||||
"arrives from outside this machine and says nothing about traffic that did not, so no " +
|
||||
"network is named anywhere and nothing needs to be said to keep a machine's own " +
|
||||
"containers reaching outward. The machine reports which of its links face outside; see " +
|
||||
"`node show <name>`")
|
||||
|
||||
case "account":
|
||||
// The operator's login on this machine (novox/hq to-be 29): what a home-scoped file is
|
||||
// owned by and which account `ssh <node>` uses. Reports with no argument; sets with one;
|
||||
// an optional second argument is the home when it is not /home/<account>.
|
||||
return nodeAccount(ctx, inv, args[1:])
|
||||
|
||||
default:
|
||||
return fmt.Errorf("node has no %q; it has add, list, show and public-domain", args[0])
|
||||
return fmt.Errorf("node has no %q; it has add, list, show, public-domain and account", args[0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +123,39 @@ func modeOf(n inventory.Node) string {
|
||||
}
|
||||
|
||||
// publicDomainUsage is the one description of the three forms, so a refusal and the help agree.
|
||||
// nodeAccount reports or sets a node's operator account (novox/hq to-be 29). Read-shaped with no
|
||||
// argument, like public-domain: `node account novox` answers, it does not change anything.
|
||||
func nodeAccount(ctx context.Context, inv *inventory.Inventory, positionals []string) error {
|
||||
if len(positionals) == 0 || len(positionals) > 3 {
|
||||
return errors.New("node account <name> — what it is now; " +
|
||||
"node account <name> <account> [home] — set it (home defaults to /home/<account>)")
|
||||
}
|
||||
node := positionals[0]
|
||||
if len(positionals) == 1 {
|
||||
who, err := inv.NodeByName(ctx, node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if who.Account == "" {
|
||||
fmt.Printf("%s has no operator account known\n", node)
|
||||
fmt.Printf(" `node account %s <account>` sets it\n", node)
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%s logs a person in as %s (home %s)\n", node, who.Account, who.Home())
|
||||
return nil
|
||||
}
|
||||
home := ""
|
||||
if len(positionals) == 3 {
|
||||
home = positionals[2]
|
||||
}
|
||||
if err := inv.SetAccount(ctx, node, positionals[1], home); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s logs a person in as %s\n", node, positionals[1])
|
||||
fmt.Printf(" run `push %s` once ssh-client is assigned, to send its operator config\n", node)
|
||||
return nil
|
||||
}
|
||||
|
||||
const publicDomainUsage = "node public-domain <name> — what it is now; " +
|
||||
"<name> <domain> to set it; <name> --clear to take it away"
|
||||
|
||||
@@ -219,15 +269,6 @@ func tokenCommand(ctx context.Context, args []string) error {
|
||||
// chicken-and-egg entirely: the mesh runs the broker, so a joining node's credentials can
|
||||
// exist before it does. The one-time secret IS the password, so a node's first connection is
|
||||
// already authenticated and enrolment is what happens over it.
|
||||
if management, err := broker.ManagementFromEnvironment(); err == nil {
|
||||
if err := management.CreateNodeAccount(ctx, issued.Node.Name, issued.Secret); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("broker account %s created, scoped to %s and the %s exchange\n\n",
|
||||
issued.Node.Name, link.QueueFor(issued.Node.Name), link.Exchange)
|
||||
} else if !errors.Is(err, broker.ErrNotConfigured) {
|
||||
return err
|
||||
}
|
||||
|
||||
made := token.Token{Node: issued.Node.Name, Signer: key.Public, Secret: issued.Secret,
|
||||
Adopted: issued.Node.Adopted}
|
||||
@@ -322,9 +363,15 @@ func identityCommand(ctx context.Context, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func brokerCommand(args []string) error {
|
||||
func brokerCommand(ctx context.Context, args []string) error {
|
||||
if len(args) > 0 && args[0] == "certificate" {
|
||||
return busCertificate(args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "accounts" {
|
||||
return busAccounts(ctx, args[1:])
|
||||
}
|
||||
if len(args) == 0 || args[0] != "show" {
|
||||
return errors.New("broker show")
|
||||
return errors.New("broker show | broker certificate [--check] --into <directory> | broker accounts --into <file>")
|
||||
}
|
||||
known, err := broker.FromEnvironment()
|
||||
if errors.Is(err, broker.ErrNotConfigured) {
|
||||
@@ -389,6 +436,12 @@ func showNode(ctx context.Context, inv *inventory.Inventory, name string) error
|
||||
}
|
||||
fmt.Printf("%s\n", node.Name)
|
||||
fmt.Printf(" last heard from %s\n", heardFrom(node))
|
||||
// Which host runs it, as it reported (novox/hq 04-ISSUES/087). Said whenever known, because a
|
||||
// host refuses a declaration carrying a field it does not understand and refuses it WHOLE — so
|
||||
// which host a machine runs is what decides whether the mesh can send it anything new, and
|
||||
// nothing could say it. "not reported" rather than blank: a machine that has not said is a
|
||||
// different thing from one running nothing.
|
||||
fmt.Printf(" host %s\n", orNotReported(node.HostVersion))
|
||||
if err := showMode(ctx, inv, node); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -439,3 +492,11 @@ func showNode(ctx context.Context, inv *inventory.Inventory, name string) error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// orNotReported is a fact a machine states about itself, or the fact that it has not.
|
||||
func orNotReported(s string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return "not reported — this machine has not said since the mesh began keeping it"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/secrets"
|
||||
)
|
||||
|
||||
@@ -26,9 +29,25 @@ import (
|
||||
// operator key make [--out <file>] make a keypair: private half to the file, public half printed
|
||||
// operator key set <public> tell the mesh which key to seal to
|
||||
// operator key show the public key, its fingerprint, and what it can recover
|
||||
const operatorUsage = "operator key make [--out <file>] | operator key set <public> [--replace] | operator key show"
|
||||
const operatorUsage = "operator key make [--out <file>] | operator key set <public> [--replace] | " +
|
||||
"operator key show | operator issue <name> --invokes <tool,tool|*> | operator revoke <name> | " +
|
||||
"operator list"
|
||||
|
||||
func operatorCommand(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errors.New(operatorUsage)
|
||||
}
|
||||
// The people who may reach the mesh's tools (design 25 §7). Beside the operator's key because
|
||||
// both answer "who, other than a machine, may do something here" — and a person reading this
|
||||
// command's usage is asking exactly that.
|
||||
switch args[0] {
|
||||
case "issue":
|
||||
return personIssue(ctx, args[1:])
|
||||
case "revoke":
|
||||
return personRevoke(ctx, args[1:])
|
||||
case "list":
|
||||
return personList(ctx)
|
||||
}
|
||||
if len(args) < 2 || args[0] != "key" {
|
||||
return errors.New(operatorUsage)
|
||||
}
|
||||
@@ -160,3 +179,129 @@ func readPrivateKey(path string) (string, error) {
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), nil
|
||||
}
|
||||
|
||||
// personIssue gives somebody a credential for the mesh's tools, and prints it once.
|
||||
//
|
||||
// **Printed, not stored.** The mesh keeps a hash and nothing else, so this is the only moment the
|
||||
// credential exists anywhere but on the workstation that will use it — the same contract a token has,
|
||||
// and for the same reason: a credential recoverable from the mesh's store has the store's blast
|
||||
// radius.
|
||||
func personIssue(ctx context.Context, args []string) error {
|
||||
set := flag.NewFlagSet("operator issue", flag.ContinueOnError)
|
||||
invokes := set.String("invokes", "", "the tools this person may call, comma-separated, or * for every one")
|
||||
// Flags on either side of the name, because the usage this command prints puts them after it —
|
||||
// and the standard parser stops at the first thing that is not a flag, so the order the command
|
||||
// documents was the one order it refused (2026-09-28).
|
||||
positionals, err := parseAround(set, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(positionals) != 1 {
|
||||
return errors.New("operator issue <name> --invokes <tool,tool|*>")
|
||||
}
|
||||
name := positionals[0]
|
||||
if *invokes == "" {
|
||||
return errors.New(
|
||||
"say what this person may call: --invokes mesh-catalog.catalog_tools,gitea.repo_create, " +
|
||||
"or --invokes '*' for an administrator")
|
||||
}
|
||||
var tools []string
|
||||
for _, t := range strings.Split(*invokes, ",") {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
tools = append(tools, t)
|
||||
}
|
||||
}
|
||||
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
|
||||
if err := inv.RecordPerson(ctx, inventory.Person{Name: name, Invokes: tools}); err != nil {
|
||||
return err
|
||||
}
|
||||
// Refused here rather than at the next composition, where it would stop the whole file being
|
||||
// written for everybody. A name that cannot be part of a subject is one the server would read as
|
||||
// a wider permission than anybody granted.
|
||||
if _, err := broker.PermissionsFor(broker.Principal{
|
||||
Kind: broker.KindPerson, Module: name, Invokes: tools, PasswordHash: "x",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user := broker.Principal{Kind: broker.KindPerson, Module: name}.Username()
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{Username: user, Kind: inventory.BusPerson})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
where, err := broker.FromEnvironment()
|
||||
if err != nil && !errors.Is(err, broker.ErrNotConfigured) {
|
||||
return err
|
||||
}
|
||||
held, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
Person string `json:"person"`
|
||||
Invokes []string `json:"invokes"`
|
||||
}{
|
||||
URL: "nats://" + where.Address, Fingerprint: where.Fingerprint,
|
||||
User: user, Password: password, Person: name, Invokes: tools,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("issued %s, who may call %s\n", name, strings.Join(tools, ", "))
|
||||
fmt.Println(" this is the only time the credential is printed; the mesh keeps a hash")
|
||||
fmt.Println(" it works once the bus has been told, which is the next push to the machine holding mesh-broker")
|
||||
fmt.Println()
|
||||
fmt.Println(string(held))
|
||||
return nil
|
||||
}
|
||||
|
||||
func personRevoke(ctx context.Context, args []string) error {
|
||||
if len(args) != 1 {
|
||||
return errors.New("operator revoke <name>")
|
||||
}
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
|
||||
if err := open.inventory.ForgetPerson(ctx, args[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
// **Revoked at the next composition, not now.** The bus's users are a file, so a credential stops
|
||||
// working when the file no longer names it. Said plainly, because "revoked" that still works for
|
||||
// another minute is worth knowing about.
|
||||
fmt.Printf("%s is forgotten, and their credential stops working at the next composition — "+
|
||||
"push the machine holding mesh-broker to make it so\n", args[0])
|
||||
return nil
|
||||
}
|
||||
|
||||
func personList(ctx context.Context) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
|
||||
people, err := open.inventory.People(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(people) == 0 {
|
||||
fmt.Println("nobody but machines reaches this mesh")
|
||||
return nil
|
||||
}
|
||||
for _, p := range people {
|
||||
fmt.Printf("%-20s %s\n", p.Name, strings.Join(p.Invokes, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
|
||||
// entry is a module as the catalogue holds it: built, so its manifest carries no `build` any more.
|
||||
func entry(module string, _ ...string) inventory.Entry {
|
||||
return inventory.Entry{Manifest: catalogue.Manifest{Module: module}}
|
||||
}
|
||||
|
||||
// stoodOn is what each module's newest build recorded it was handed.
|
||||
func stoodOn(edges map[string][]string) map[string][]string {
|
||||
out := map[string][]string{}
|
||||
for module, bases := range edges {
|
||||
for _, b := range bases {
|
||||
out[module] = append(out[module], catalogue.ArtifactStoreScheme+b+"/runtime@sha256:"+strings.Repeat("0", 64))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A module built before the module it stands on is built against the old one and reports success
|
||||
// (novox/hq 04-ISSUES/131). So bases come first, however the set arrived.
|
||||
func TestBasesAreBuiltBeforeWhatStandsOnThem(t *testing.T) {
|
||||
in := []inventory.Entry{entry("app"), entry("runtime"), entry("other"), entry("base")}
|
||||
edges := stoodOn(map[string][]string{"app": {"runtime"}, "runtime": {"base"}})
|
||||
got := orderByBases(in, edges)
|
||||
pos := map[string]int{}
|
||||
for i, e := range got {
|
||||
pos[e.Manifest.Module] = i
|
||||
}
|
||||
if !(pos["base"] < pos["runtime"] && pos["runtime"] < pos["app"]) {
|
||||
t.Fatalf("bases not first: %v", pos)
|
||||
}
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("an entry was lost or doubled: %d", len(got))
|
||||
}
|
||||
// A base outside the set is not waited for: it is not being rebuilt.
|
||||
got = orderByBases([]inventory.Entry{entry("app")}, stoodOn(map[string][]string{"app": {"elsewhere"}}))
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("a dependency outside the set changed the set: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A module registered from its manifest and never built still names its bases there; once built,
|
||||
// the recorded edge is what says so. Both are read, and a module never stands on itself.
|
||||
func TestWhatStandsOnAModuleIsReadFromItsBuildOrItsManifest(t *testing.T) {
|
||||
built := entry("gitea")
|
||||
edges := stoodOn(map[string][]string{"gitea": {"mesh-tools"}})
|
||||
if !standsOnModule(built, "mesh-tools", edges) {
|
||||
t.Fatal("a recorded edge was not read")
|
||||
}
|
||||
if standsOnModule(built, "gitea", edges) || standsOnModule(built, "postgres", edges) {
|
||||
t.Fatal("an edge was invented")
|
||||
}
|
||||
fresh := inventory.Entry{Manifest: catalogue.Manifest{Module: "plex", Build: &catalogue.Build{
|
||||
On: []catalogue.BuildsOn{{Arg: "RUNTIME_BASE", Module: "mesh-tools", Artifact: "runtime"}},
|
||||
}}}
|
||||
if !standsOnModule(fresh, "mesh-tools", nil) {
|
||||
t.Fatal("a manifest's own base was not read")
|
||||
}
|
||||
}
|
||||
|
||||
// A merge names a repository the way the forge does; a source is recorded the way a build was
|
||||
// asked for. The two meet on owner/repo and branch, whichever form the record took.
|
||||
func TestAMergeMatchesTheSourcesBuiltFromIt(t *testing.T) {
|
||||
m := link.SourceMoved{Owner: "novox", Repo: "mesh-controller", Base: "main",
|
||||
CloneURL: "http://forge.internal:20000/novox/mesh-controller.git"}
|
||||
for _, s := range []inventory.Source{
|
||||
{Repository: "http://forge.internal:20000/novox/mesh-controller.git", Ref: "main"},
|
||||
{Repository: "novox/mesh-controller", Seat: "git", Ref: ""},
|
||||
{Repository: "https://elsewhere.example/novox/mesh-controller", Ref: "main"},
|
||||
} {
|
||||
if !sourceIs(s, m) {
|
||||
t.Errorf("%+v was not matched by the merge", s)
|
||||
}
|
||||
}
|
||||
for _, s := range []inventory.Source{
|
||||
{Repository: "novox/mesh-host", Seat: "git"},
|
||||
{Repository: "http://forge.internal:20000/novox/mesh-controller.git", Ref: "release"},
|
||||
} {
|
||||
if sourceIs(s, m) {
|
||||
t.Errorf("%+v was matched by a merge that is not its", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A merge made before the source was last seen is history: it does not move the source, and a
|
||||
// merge that says nothing about when it was made is taken as news.
|
||||
func TestAMergeOlderThanTheLastLookIsHistory(t *testing.T) {
|
||||
seen := time.Date(2026, 9, 28, 3, 0, 0, 0, time.UTC)
|
||||
if !isHistory("2026-09-28T02:00:00Z", seen) {
|
||||
t.Fatal("an older merge was taken as news")
|
||||
}
|
||||
if isHistory("2026-09-28T04:00:00Z", seen) {
|
||||
t.Fatal("a newer merge was taken as history")
|
||||
}
|
||||
if isHistory("", seen) || isHistory("2026-09-28T02:00:00Z", time.Time{}) {
|
||||
t.Fatal("a merge or a source with no time on it was refused")
|
||||
}
|
||||
}
|
||||
|
||||
// A module as the catalogue holds it: built from a repository, at a directory inside it.
|
||||
func fromRepo(module, repository, path string) inventory.Entry {
|
||||
return inventory.Entry{
|
||||
Manifest: catalogue.Manifest{Module: module},
|
||||
Source: inventory.Source{Repository: repository, Path: path, Ref: "main"},
|
||||
}
|
||||
}
|
||||
|
||||
// A merge rebuilds the modules whose own directories it changed, and everything when what it changed
|
||||
// is shared. One repository holding many modules is the ordinary case here, and rebuilding all of
|
||||
// them for a change to one is what exhausted a registry's pull limit the first night this ran.
|
||||
func TestAMergeRebuildsTheModulesItChanged(t *testing.T) {
|
||||
const repo = "http://forge.internal:20000/novox/mesh-catalog.git"
|
||||
gitea := fromRepo("gitea", repo, "modules/gitea")
|
||||
keycloak := fromRepo("keycloak", repo, "modules/keycloak")
|
||||
known := []inventory.Entry{gitea, keycloak, fromRepo("plex", repo, "modules/plex")}
|
||||
candidates := []inventory.Entry{gitea, keycloak}
|
||||
merge := func(paths []string, truncated bool) link.SourceMoved {
|
||||
return link.SourceMoved{Owner: "novox", Repo: "mesh-catalog", Base: "main",
|
||||
Paths: paths, PathsTruncated: truncated}
|
||||
}
|
||||
named := func(entries []inventory.Entry) string {
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Manifest.Module)
|
||||
}
|
||||
return strings.Join(names, ",")
|
||||
}
|
||||
for _, c := range []struct {
|
||||
what string
|
||||
m link.SourceMoved
|
||||
want string
|
||||
}{
|
||||
{"one module's own files", merge([]string{"modules/gitea/index.ts", "modules/gitea/client.ts"}, false), "gitea"},
|
||||
{"two modules' files", merge([]string{"modules/gitea/index.ts", "modules/keycloak/module.json"}, false), "gitea,keycloak"},
|
||||
{"a file they share", merge([]string{"tsconfig.json"}, false), "gitea,keycloak"},
|
||||
{"a module the mesh does not hold", merge([]string{"modules/plex/index.ts"}, false), ""},
|
||||
{"nothing said about the files", merge(nil, false), "gitea,keycloak"},
|
||||
{"more files than were listed", merge([]string{"modules/gitea/index.ts"}, true), "gitea,keycloak"},
|
||||
} {
|
||||
if got := named(whatTheMergeTouched(candidates, known, c.m)); got != c.want {
|
||||
t.Errorf("%s: rebuilt %q, wanted %q", c.what, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A module whose recipe packages source from another repository is affected when that repository
|
||||
// moves — the manifest the mesh keeps says nothing about it, so the record of what the build read is
|
||||
// the only thing that can say so.
|
||||
func TestAModuleIsAffectedByTheRepositoryItPackages(t *testing.T) {
|
||||
m := link.SourceMoved{Owner: "novox", Repo: "mesh-controller", Base: "main",
|
||||
CloneURL: "http://forge.internal:20000/novox/mesh-controller.git"}
|
||||
for _, read := range [][]inventory.ReadRepository{
|
||||
{{Repository: "http://forge.internal:20000/novox/mesh-controller.git", Ref: "main"}},
|
||||
{{Repository: "novox/mesh-controller"}},
|
||||
{{Repository: "https://elsewhere.example/novox/other"}, {Repository: "novox/mesh-controller.git", Ref: "main"}},
|
||||
} {
|
||||
if !readsFrom(read, m) {
|
||||
t.Errorf("%+v was not matched by the merge", read)
|
||||
}
|
||||
}
|
||||
for _, read := range [][]inventory.ReadRepository{
|
||||
nil,
|
||||
{{Repository: "novox/mesh-host", Ref: "main"}},
|
||||
{{Repository: "novox/mesh-controller", Ref: "release"}},
|
||||
} {
|
||||
if readsFrom(read, m) {
|
||||
t.Errorf("%+v was matched by a merge that is not its", read)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What a module handed over by hand records about where it came from, and what is refused.
|
||||
func TestWhatAHandedOverModuleRecordsAboutItsSource(t *testing.T) {
|
||||
// The whole location: a repository on the mesh's own forge, the directory inside it, the branch
|
||||
// and the commit the manifest was read at.
|
||||
from, err := whereItComesFrom("novox/mesh-catalog", "main", "c0ffee", "modules/gitea", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if from.Path != "modules/gitea" || from.Seat != "git" || from.Repository != "novox/mesh-catalog" {
|
||||
t.Fatalf("the source records as %+v", from)
|
||||
}
|
||||
// A manifest with no provenance at all is legitimate: fixing something in a hurry.
|
||||
if from, err := whereItComesFrom("", "", "", "", false); err != nil || from != (inventory.Source{}) {
|
||||
t.Fatalf("a manifest handed over with no provenance was refused: %+v, %v", from, err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
what string
|
||||
repository, ref, commit, path string
|
||||
self bool
|
||||
}{
|
||||
{what: "a source with no commit", repository: "novox/mesh-catalog", commit: ""},
|
||||
{what: "a commit with no source", commit: "c0ffee"},
|
||||
{what: "a directory inside nothing", path: "modules/gitea"},
|
||||
{what: "a forge holding nothing", self: true},
|
||||
{what: "an address given as a path on the forge", repository: "http://forge.internal:20000/novox/x.git", commit: "c0ffee", self: true},
|
||||
} {
|
||||
if _, err := whereItComesFrom(c.repository, c.ref, c.commit, c.path, c.self); err == nil {
|
||||
t.Errorf("%s was recorded as a source", c.what)
|
||||
}
|
||||
}
|
||||
}
|
||||
+210
-14
@@ -25,7 +25,36 @@ import (
|
||||
// cheapest next step. That is how novox/hq ADR 0001 records `hal/sdk` reaching 34,636:
|
||||
// nothing in it was wrong, and no one edit was the one that should have been a new file.
|
||||
|
||||
// notResolvable marks the one failure in planFor that is a statement about the node: its assigned
|
||||
// modules do not compose. Every other failure means the mesh could not be *asked* — the store was
|
||||
// unreachable, a key could not be read — and says nothing about the node at all.
|
||||
//
|
||||
// The distinction exists because three callers gather something across every machine and must carry
|
||||
// on when one machine's set is broken. Each of them read a plain error as "their set does not
|
||||
// resolve", and so read a store that was briefly unreachable as a machine that runs nothing. On the
|
||||
// roster of routed names that is not a degraded answer but a false one: it states, to every machine
|
||||
// at once, that another machine's names do not exist. A control node spent hours replacing every
|
||||
// container it ran, on a six-minute cycle, because each pass restarted the store this is read from,
|
||||
// the read failed, one name left the roster, and the roster is part of every container's identity
|
||||
// (novox/hq 04-ISSUES/152, and 04-ISSUES/151 for why a changed roster is a changed container).
|
||||
//
|
||||
// So: skip a node that cannot resolve, and never a node that could not be read.
|
||||
type notResolvable struct{ err error }
|
||||
|
||||
func (n notResolvable) Error() string { return n.err.Error() }
|
||||
func (n notResolvable) Unwrap() error { return n.err }
|
||||
|
||||
// unresolvable reports whether err is a node's own set failing to compose, rather than the mesh
|
||||
// being unable to answer.
|
||||
func unresolvable(err error) bool {
|
||||
var n notResolvable
|
||||
return errors.As(err, &n)
|
||||
}
|
||||
|
||||
// planFor works out everything a node should run, from what was assigned to it.
|
||||
//
|
||||
// A failure to compose the node's own modules is wrapped as notResolvable; every other failure is
|
||||
// returned as it is. Callers gathering across the mesh must tell them apart — see notResolvable.
|
||||
func planFor(ctx context.Context, open *stores, nodeName string) (catalogue.Resolution, catalogue.SettingsBy, error) {
|
||||
inv := open.inventory
|
||||
shelf, err := inv.Catalogue(ctx)
|
||||
@@ -83,13 +112,23 @@ func planFor(ctx context.Context, open *stores, nodeName string) (catalogue.Reso
|
||||
return catalogue.Resolution{}, nil, err
|
||||
}
|
||||
|
||||
resolved, err := catalogue.Resolve(shelf, assigned,
|
||||
catalogue.Node{Name: nodeName, Site: site, Capabilities: capabilities,
|
||||
At: onNetwork[nodeName], PublicDomain: publicDomain}, world)
|
||||
// The operator account this node logs a person in as, and where its home is (novox/hq to-be
|
||||
// 29) — carried so a home-scoped file's owner and path resolve for this machine.
|
||||
who, err := inv.NodeByName(ctx, nodeName)
|
||||
if err != nil {
|
||||
return catalogue.Resolution{}, nil, err
|
||||
}
|
||||
|
||||
resolved, err := catalogue.Resolve(shelf, assigned,
|
||||
catalogue.Node{Name: nodeName, Site: site, Capabilities: capabilities,
|
||||
At: onNetwork[nodeName], PublicDomain: publicDomain,
|
||||
Account: who.Account, AccountHome: who.AccountHome}, world)
|
||||
if err != nil {
|
||||
// The node's own set does not compose. Marked, because this is the only failure here that
|
||||
// a mesh-wide gatherer may pass over — see notResolvable.
|
||||
return catalogue.Resolution{}, nil, notResolvable{err}
|
||||
}
|
||||
|
||||
// The credential for each thing this node takes from elsewhere. Made once and kept, so the
|
||||
// password a provider is told to create is the one its consumer was given — and sealed to
|
||||
// this node before it was ever written down, so nothing between here and there can read it.
|
||||
@@ -155,8 +194,13 @@ func planFor(ctx context.Context, open *stores, nodeName string) (catalogue.Reso
|
||||
if len(stray) > 0 {
|
||||
// Somebody set something that reaches no file. Said here rather than discovered by the
|
||||
// machine not behaving differently, which is the slowest way there is.
|
||||
return catalogue.Resolution{}, nil, fmt.Errorf(
|
||||
"these settings reach nothing:\n - %s", strings.Join(stray, "\n - "))
|
||||
//
|
||||
// Marked like a set that will not compose, and for the same reason: it is a standing fact
|
||||
// about this node's own configuration, not a question the mesh could not answer. A gatherer
|
||||
// passes over it as it always did — one node's stray setting must not stop every other node
|
||||
// being described (novox/hq 04-ISSUES/152).
|
||||
return catalogue.Resolution{}, nil, notResolvable{fmt.Errorf(
|
||||
"these settings reach nothing:\n - %s", strings.Join(stray, "\n - "))}
|
||||
}
|
||||
return resolved, settings, nil
|
||||
}
|
||||
@@ -177,6 +221,15 @@ func theRestOfTheMesh(ctx context.Context, inv *inventory.Inventory,
|
||||
|
||||
// Every node, not only the placed ones. A machine that was never put on the private network
|
||||
// still runs modules, still holds claims, and still offers whatever it offers.
|
||||
// **Who holds each seat on record, before anything is resolved** (novox/hq ADR 0131). Both
|
||||
// passes below need it: without it, the assignment standing beside a seat's holder — the next
|
||||
// holder, waiting for the handover — is refused as a second holder, and its node's whole set
|
||||
// with it.
|
||||
holdings, err := inv.Holdings(ctx)
|
||||
if err != nil {
|
||||
return catalogue.World{}, err
|
||||
}
|
||||
|
||||
nodes, err := inv.Nodes(ctx)
|
||||
if err != nil {
|
||||
return catalogue.World{}, err
|
||||
@@ -219,7 +272,7 @@ func theRestOfTheMesh(ctx context.Context, inv *inventory.Inventory,
|
||||
offered := map[string][]catalogue.Provider{}
|
||||
var firstHeld []catalogue.Held
|
||||
for _, o := range others {
|
||||
got, err := catalogue.Resolve(shelf, o.assigned, o.node, catalogue.World{Unchecked: true})
|
||||
got, err := catalogue.Resolve(shelf, o.assigned, o.node, catalogue.World{Unchecked: true, Holdings: holdings})
|
||||
if err != nil {
|
||||
// Their set does not resolve for some other reason. Not this node's problem to
|
||||
// report, and nothing of theirs is running, so it offers nothing.
|
||||
@@ -250,7 +303,7 @@ func theRestOfTheMesh(ctx context.Context, inv *inventory.Inventory,
|
||||
// with several providers (novox/hq ADR 0110), so a node consuming one resolves only once the
|
||||
// holder is known. Without them its set is refused here, and a refused node's own claims drop
|
||||
// out of what the mesh holds — so a second holder of one of its seats would pass unrefused.
|
||||
world := catalogue.World{Offered: offered, Held: firstHeld}
|
||||
world := catalogue.World{Offered: offered, Held: firstHeld, Holdings: holdings}
|
||||
var held []catalogue.Held
|
||||
for _, o := range others {
|
||||
got, err := catalogue.Resolve(shelf, o.assigned, o.node, world)
|
||||
@@ -488,6 +541,13 @@ func renderingFor(ctx context.Context, open *stores, node string,
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
// The private network's range, offered to a module as ${machine:mesh-range} — a module that must
|
||||
// name the whole mesh (an intrusion filter that must never ban a tunnel peer) names it here
|
||||
// rather than hardcoding a value it cannot know.
|
||||
meshRange, err := overlayRange(ctx, inv)
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
|
||||
// The artifact store as this node reaches it now — the address every image and archive the
|
||||
// mesh built is fetched through, composed here and recorded nowhere — with what the mesh has
|
||||
@@ -513,6 +573,19 @@ func renderingFor(ctx context.Context, open *stores, node string,
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
|
||||
// Each machine's operator account, so an ssh Host block can name the login for every node
|
||||
// (novox/hq to-be 29). Keyed by the bare node name, which entriesFrom falls back to.
|
||||
allNodes, err := inv.Nodes(ctx)
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
accounts := map[string]string{}
|
||||
for _, n := range allNodes {
|
||||
if n.Account != "" {
|
||||
accounts[n.Name] = n.Account
|
||||
}
|
||||
}
|
||||
|
||||
// And every routed name → the node that serves it (novox/hq ADR 0066). Alongside the
|
||||
// `<node>.internal` names above, so a container — or an internal ACME validator — resolves a
|
||||
// routed name to the proxy that serves it, mesh-wide. The mesh publishes the names it was told
|
||||
@@ -593,12 +666,31 @@ func renderingFor(ctx context.Context, open *stores, node string,
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
// The bus's user list, for the machine that runs the bus. Composed per push rather than kept,
|
||||
// because it is a function of the mesh's records and a kept copy could disagree with them.
|
||||
busUsers, err := composeBusUsers(ctx, inv, plan.Modules)
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
memberships, err := inv.BusMemberships(ctx)
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
// Which of this machine's links face outside, which is what the derived filter is written
|
||||
// around (novox/hq ADR 0140). Reported by the machine, never set.
|
||||
outwardLinks, err := inv.OutwardLinksOf(ctx, node)
|
||||
if err != nil {
|
||||
return catalogue.Rendering{}, inventory.Node{}, err
|
||||
}
|
||||
return catalogue.Rendering{
|
||||
Settings: settings, Generators: gens, Grants: grants, Needed: needed, Ports: ports,
|
||||
BusMembership: memberships[node],
|
||||
Settings: settings, Generators: gens, Grants: grants, Needed: needed, Ports: ports,
|
||||
Certificate: certificate, Authority: authority, Mesh: private, Names: names,
|
||||
Machines: machines,
|
||||
Suffix: overlay.Suffix(), Foundation: foundation, Kept: kept, Adopted: record.Adopted,
|
||||
Suffix: overlay.Suffix(), MeshRange: meshRange, TunnelInterface: overlay.Interface, Accounts: accounts, Foundation: foundation,
|
||||
Kept: kept, Adopted: record.Adopted, OutwardLinks: outwardLinks,
|
||||
Given: given, Taken: taken, Seats: seats, ArtifactStore: artifactStore, Built: built,
|
||||
BusUsers: busUsers,
|
||||
}, record, nil
|
||||
}
|
||||
|
||||
@@ -615,11 +707,17 @@ func renderingFor(ctx context.Context, open *stores, node string,
|
||||
// routed name only because it carried a label the mesh composed, never because the mesh knows what
|
||||
// "route" means. A node that does not resolve is skipped, so one machine's broken set does not cost
|
||||
// the rest their names.
|
||||
//
|
||||
// **A node that could not be READ is a different matter and is raised.** Skipping one states, to
|
||||
// every machine at once, that its names do not exist — and since the roster is part of every
|
||||
// container's identity, that withdraws them and replaces every container (novox/hq 04-ISSUES/152,
|
||||
// 151). So every failure here says which machine and which read, because the alternative is a
|
||||
// mesh-wide refusal with nothing named in it.
|
||||
func routeNamesInTheMesh(ctx context.Context, open *stores) (map[string]string, error) {
|
||||
inv := open.inventory
|
||||
places, err := inv.Overlays(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("where the machines are cannot be read: %w", err)
|
||||
}
|
||||
address := map[string]string{}
|
||||
for _, p := range places {
|
||||
@@ -630,14 +728,22 @@ func routeNamesInTheMesh(ctx context.Context, open *stores) (map[string]string,
|
||||
|
||||
nodes, err := inv.Nodes(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("which machines the mesh has cannot be read: %w", err)
|
||||
}
|
||||
|
||||
out := map[string]string{}
|
||||
for _, n := range nodes {
|
||||
plan, settings, err := planFor(ctx, open, n.Name)
|
||||
if err != nil {
|
||||
switch {
|
||||
case unresolvable(err):
|
||||
// Their set does not compose, so they serve no names. Passed over, so one machine's
|
||||
// broken set does not cost the rest theirs.
|
||||
continue
|
||||
case err != nil:
|
||||
// The mesh could not be asked. Returning the roster without this machine's names would
|
||||
// state that they do not exist — to every machine, and indistinguishably from the
|
||||
// operator having withdrawn them (novox/hq 04-ISSUES/152).
|
||||
return nil, fmt.Errorf("the names %s serves cannot be read: %w", n.Name, err)
|
||||
}
|
||||
for _, m := range plan.Modules {
|
||||
for to := range m.Contributes {
|
||||
@@ -767,11 +873,17 @@ func grantsFor(ctx context.Context, open *stores, node string) ([]catalogue.Gran
|
||||
out := make([]catalogue.Grant, 0, len(issued))
|
||||
for _, s := range issued {
|
||||
plan, settings, err := planFor(ctx, open, s.Consumer)
|
||||
if err != nil {
|
||||
switch {
|
||||
case unresolvable(err):
|
||||
// Their set does not resolve. Skipped rather than fatal: this node is not the place
|
||||
// to report another machine's problem, and a grant for something that is not going to
|
||||
// run would have the provider create a user nothing uses.
|
||||
continue
|
||||
case err != nil:
|
||||
// The mesh could not be asked what they wanted, which is not the same as their wanting
|
||||
// nothing — and withholding a grant on that reading takes a consumer's access away
|
||||
// (novox/hq 04-ISSUES/152).
|
||||
return nil, fmt.Errorf("what %s asked of %s cannot be read: %w", s.Consumer, s.Name, err)
|
||||
}
|
||||
values, asks, err := plan.ContributionsFrom(s.Name, s.ConsumerModule, settings)
|
||||
if err != nil {
|
||||
@@ -923,12 +1035,26 @@ func planCommand(ctx context.Context, args []string) error {
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
fmt.Printf("\n--- %v %v ---\n%s", r["id"], r["path"], content)
|
||||
fmt.Printf("\n--- %s ---\n%s", shownAs(r), content)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// shownAs is the heading `plan --show` puts over a resource's content.
|
||||
//
|
||||
// **A file written into says so.** Its content is the mesh's part of a file that is otherwise the
|
||||
// machine's — the keys of a JSON document (novox/hq ADR 0102), the region of a hosts file (issue
|
||||
// 128). Shown under a bare path it reads as the whole file, and a person checking what a take
|
||||
// replaces would see a hosts file of a dozen lines where the machine keeps thirty.
|
||||
func shownAs(r map[string]any) string {
|
||||
heading := fmt.Sprintf("%v %v", r["id"], r["path"])
|
||||
if into, ok := r["into"].(string); ok && into != "" {
|
||||
heading += fmt.Sprintf(" (written into, %s)", into)
|
||||
}
|
||||
return heading
|
||||
}
|
||||
|
||||
// licencesFor is what this node can be answered with by record, and what it was put on.
|
||||
//
|
||||
// A mesh with no licences at all is the ordinary case and must not be an error: every existing
|
||||
@@ -1144,6 +1270,76 @@ func portsOn(
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// composeBusUsers is the bus's user list, for a push to the machine that runs the bus.
|
||||
//
|
||||
// Empty for every other machine, and for every machine while the mesh is on the bus it runs on
|
||||
// today — where accounts are a management call and there is no file to write.
|
||||
//
|
||||
// **Composed on each push, never kept.** The list is a function of the mesh's records (who exists,
|
||||
// what runs where, what each declares), and a stored copy would be a second account of who may reach
|
||||
// the bus, able to disagree with the records while both looked internally consistent (ADR 0043).
|
||||
//
|
||||
// A user the mesh has never minted a password for is **left out and said**, not written as a user
|
||||
// without one — the composer refuses that, because a user with no password is a user anybody is. That
|
||||
// is an ordinary situation with an obvious remedy (`module issue`, or enrolling), so the push carries
|
||||
// the rest rather than failing: a bus that is missing one module's user is a mesh where that module
|
||||
// cannot connect, and a bus with no file at all is a mesh where nothing can.
|
||||
func composeBusUsers(ctx context.Context, inv *inventory.Inventory,
|
||||
onThisNode []catalogue.Manifest) (string, error) {
|
||||
|
||||
// **Not gated on which bus the controller is on, and that was a bug.** It read "compose this only
|
||||
// once the mesh is on the new bus" — which cannot work, because the server needs its user list
|
||||
// *before* anything moves onto it. Step 2 of the change is exactly that: the server stands in the
|
||||
// mesh carrying nothing, on its own ports, while every node is still on the old bus (novox/hq
|
||||
// ADR 0116). Under the old gating that step could not happen: the module would come up, find no
|
||||
// accounts file, and its entrypoint would wait for one the controller had decided not to write.
|
||||
//
|
||||
// So the question is only whether this machine runs the module that asked for the file. A mesh
|
||||
// that never moves has written a user list nothing reads, which costs a few hundred bytes on one
|
||||
// node; the reverse cost a step that cannot be taken.
|
||||
//
|
||||
// Asked of what this push resolves to rather than of the seat's holder mesh-wide: the file is a
|
||||
// resource of that module, so the question is whether it is here.
|
||||
holdsTheBus := false
|
||||
for _, m := range onThisNode {
|
||||
if m.BusUsers != "" && m.ClaimsSeat("mesh-broker") {
|
||||
holdsTheBus = true
|
||||
}
|
||||
}
|
||||
if !holdsTheBus {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
records, err := inv.BusRecords(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
users, err := broker.Users(records)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
kept, err := inv.BusUsers(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hashes := make(map[string]string, len(kept))
|
||||
for name, u := range kept {
|
||||
hashes[name] = u.PasswordHash
|
||||
}
|
||||
filled, missing := broker.WithPasswords(users, hashes)
|
||||
if len(missing) > 0 {
|
||||
fmt.Printf("the bus's user list leaves out %d user(s) the mesh has minted no credential "+
|
||||
"for: %s. Each is a user that cannot connect until one is issued\n",
|
||||
len(missing), strings.Join(missing, ", "))
|
||||
}
|
||||
if len(filled) == 0 {
|
||||
return "", fmt.Errorf(
|
||||
"this machine runs the bus and not one user has a credential, so the composed list " +
|
||||
"would refuse every connection in the mesh")
|
||||
}
|
||||
return broker.ComposeAccounts(filled)
|
||||
}
|
||||
|
||||
// foundationPortsFor is the broker port, kept only when a module resolved onto this node listens
|
||||
// on it (novox/hq issue: the broker opening leaked onto every node). The foundation opening
|
||||
// exists to WIDEN the broker's `from: mesh` port to from-anywhere, because a machine enrolling is
|
||||
|
||||
@@ -35,3 +35,17 @@ func TestListensLinesAreEmptyForAModuleWithNothingToListenOn(t *testing.T) {
|
||||
t.Errorf("a module with no listens should print nothing, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// `plan --show` says when a file is written into rather than over (novox/hq issue 128), or the
|
||||
// mesh's region of a hosts file reads as the whole file.
|
||||
func TestAFileWrittenIntoIsShownAsSuch(t *testing.T) {
|
||||
region := shownAs(map[string]any{
|
||||
"id": "mesh-wireguard.fact-node-names", "path": "/etc/hosts", "into": "block"})
|
||||
if region != "mesh-wireguard.fact-node-names /etc/hosts (written into, block)" {
|
||||
t.Errorf("the region is shown as %q", region)
|
||||
}
|
||||
whole := shownAs(map[string]any{"id": "dnsmasq.fact-node-zones", "path": "/etc/mesh-resolver/nodes.conf"})
|
||||
if strings.Contains(whole, "written into") {
|
||||
t.Errorf("a whole file is shown as written into: %q", whole)
|
||||
}
|
||||
}
|
||||
|
||||
+228
-16
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -38,6 +39,27 @@ func reportUnhostable(node string, plan catalogue.Resolution) {
|
||||
// nothing in it was wrong, and no one edit was the one that should have been a new file.
|
||||
|
||||
// serve is the control plane running: one connection to the broker, one queue, one consumer.
|
||||
// connectLink opens the controller's link over whichever bus this process is on (design 25: one
|
||||
// variable moves it). The streams and this controller's consumers are raised first on the new bus,
|
||||
// so nothing served here finds them missing.
|
||||
func connectLink(ctx context.Context, inv *inventory.Inventory, enroller link.Enroller, listener link.Listener) (*link.Server, error) {
|
||||
busAddress, err := broker.BusAddress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if inv != nil {
|
||||
if err := raiseTheBus(ctx, inv, busAddress); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
js, err := broker.Dial(busAddress)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the mesh is on the bus at %s and this control plane cannot reach it: %w",
|
||||
broker.BareAddress(busAddress), err)
|
||||
}
|
||||
return link.ConnectNats(js, enroller, listener), nil
|
||||
}
|
||||
|
||||
func serve(ctx context.Context) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
@@ -61,11 +83,6 @@ func serve(ctx context.Context) error {
|
||||
}
|
||||
fmt.Printf("signing as %s\n", key.Fingerprint()[:16])
|
||||
|
||||
management, err := broker.ManagementFromEnvironment()
|
||||
if err != nil && !errors.Is(err, broker.ErrNotConfigured) {
|
||||
return err
|
||||
}
|
||||
|
||||
// Where the broker is and what to expect there, so a node can be told how to come back
|
||||
// without a person and a new token.
|
||||
known, err := broker.FromEnvironment()
|
||||
@@ -77,12 +94,22 @@ func serve(ctx context.Context) error {
|
||||
"reconnect. Set %s and %s.\n", broker.AddressVar, broker.CertificateVar)
|
||||
}
|
||||
|
||||
work := link.Enrolment{Inventory: inv, Identity: ident, Management: management, Broker: known}
|
||||
server, err := link.Connect(work, work)
|
||||
// **Which bus this mesh is on, read once** (novox/hq ADR 0116 step 5). Both clients ship; both
|
||||
// being live is refused, because a mesh half on each is one where a declaration goes out on one
|
||||
// and the report comes back on the other, and every component logs success while it happens.
|
||||
|
||||
work := link.Enrolment{Inventory: inv, Identity: ident, Broker: known,
|
||||
OnNATS: true}
|
||||
server, err := connectLink(ctx, inv, work, work)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
// The bus's own objects, asserted on every start. **Not created once at genesis**: a stream
|
||||
// somebody deleted, a mesh raised from a restored backup, or a bus whose data directory was
|
||||
// replaced all have records and no objects — and a node whose consumer is missing hears nothing
|
||||
// while everything else about it looks correct.
|
||||
// And build results nobody was waiting for. A build triggered any other way than `build`
|
||||
// would otherwise be reported into the void, which is the same as not reporting it.
|
||||
server.Records(builds{inv})
|
||||
@@ -98,6 +125,22 @@ func serve(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// And the mesh's own verbs, as the seat this control plane holds (novox/hq ADR 0154). Served
|
||||
// from the store's row, so what the seat declares is what is answered.
|
||||
handlers, err := seatToolHandlers()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bus, isNATS := server.Bus().(link.OverNATS)
|
||||
if !isNATS {
|
||||
return errors.New("the mesh's verbs are served over the bus, and this control plane is not on it")
|
||||
}
|
||||
stopServing, err := bus.ServeSeatTools(catalogue.ControllerSeatName, handlers, log.New(os.Stdout, "", log.LstdFlags))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stopServing()
|
||||
|
||||
return server.Serve(ctx)
|
||||
}
|
||||
|
||||
@@ -136,13 +179,19 @@ func declare(ctx context.Context, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
server, err := link.Connect(nil, nil)
|
||||
// **With the inventory, so the bus is raised** (novox/hq ADR 0134, design 30). A module's
|
||||
// declaration and how it hears what it consumes move together: its consumer is derived from the
|
||||
// same records this declaration is composed from. Raised only when the control plane started
|
||||
// serving, a module that gained a `consumes` was sent a declaration it could act on and a
|
||||
// consumer that never delivered the event — and nothing anywhere said the two disagreed
|
||||
// (found on review, 2026-09-28). Everything the raise does is idempotent.
|
||||
server, err := connectLink(ctx, inv, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
if err := link.Declare(ctx, server.Channel(), ident, node, raw, 15*time.Second); err != nil {
|
||||
if err := link.Declare(ctx, server.Bus(), ident, node, raw, 15*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("sent %s a signed declaration (%d bytes)\n", node, len(raw))
|
||||
@@ -249,7 +298,7 @@ func pushCommand(ctx context.Context, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
server, err := link.Connect(nil, nil)
|
||||
server, err := connectLink(ctx, nil, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -306,11 +355,17 @@ func pushCommand(ctx context.Context, args []string) error {
|
||||
sentDigest := map[string]string{}
|
||||
defer release()
|
||||
for _, s := range sending {
|
||||
// Numbered under the hold, one higher than the last, before the body exists — the number is
|
||||
// inside the signed bytes, so a replayed older declaration cannot borrow a newer one's
|
||||
// (novox/hq 04-ISSUES/107).
|
||||
if err := number(ctx, inv, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := s.declared.Body()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := link.Declare(ctx, server.Channel(), ident, s.node, body, 15*time.Second); err != nil {
|
||||
if err := link.Declare(ctx, server.Bus(), ident, s.node, body, 15*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
// After it is away, not before. A digest recorded for something that failed to send would
|
||||
@@ -393,7 +448,7 @@ func pushCommand(ctx context.Context, args []string) error {
|
||||
return declarationWith(held, open, node, plan, settings, gens, Allocating)
|
||||
},
|
||||
func(s readyNode, body []byte) error {
|
||||
if err := link.Declare(ctx, server.Channel(), ident, s.node, body,
|
||||
if err := link.Declare(ctx, server.Bus(), ident, s.node, body,
|
||||
15*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -502,8 +557,14 @@ func composeEach(names []string,
|
||||
continue
|
||||
}
|
||||
if len(declared.Resources) == 0 {
|
||||
fmt.Printf("%s is assigned nothing — skipped\n", name)
|
||||
continue
|
||||
// Sent, not skipped (novox/hq issue 127). A node whose declaration composes to
|
||||
// nothing may have HELD something before — the broker opening a placement gave it,
|
||||
// say — and skipping the empty declaration leaves that last resource in force
|
||||
// forever, re-applied by the node's own heartbeat, with no way for the mesh to say
|
||||
// it is gone. An empty declaration is the correction: the host drops what the mesh
|
||||
// owned and keeps what it found (the adoption envelope still rides along). A node
|
||||
// that never held anything applies it as the no-op it is.
|
||||
fmt.Printf("%s owns nothing now — sent so it drops what it last held\n", name)
|
||||
}
|
||||
sending = append(sending, readyNode{name, declared})
|
||||
}
|
||||
@@ -526,6 +587,9 @@ func sendRound(ctx context.Context, open *stores, names []string,
|
||||
return compose(held, node)
|
||||
})
|
||||
for _, s := range sending {
|
||||
if err := number(ctx, open.inventory, &s); err != nil {
|
||||
return refused, err
|
||||
}
|
||||
body, err := s.declared.Body()
|
||||
if err != nil {
|
||||
return refused, err
|
||||
@@ -600,18 +664,21 @@ func sendTo(ctx context.Context, open *stores, names []string) error {
|
||||
len(refusals), strings.Join(refusals, "\n\n"))
|
||||
}
|
||||
|
||||
server, err := link.Connect(nil, nil)
|
||||
server, err := connectLink(ctx, nil, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer server.Close()
|
||||
|
||||
for _, s := range sending {
|
||||
if err := number(ctx, inv, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := s.declared.Body()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := link.Declare(ctx, server.Channel(), ident, s.node, body, 15*time.Second); err != nil {
|
||||
if err := link.Declare(ctx, server.Bus(), ident, s.node, body, 15*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
record, err := inv.NodeByName(ctx, s.node)
|
||||
@@ -656,6 +723,12 @@ func wouldSend(ctx context.Context, open *stores,
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// Composed with the number the machine was LAST sent, so this is byte for byte what it was
|
||||
// sent when nothing else changed. A fresh number here would make every machine read as
|
||||
// behind for ever (novox/hq 04-ISSUES/107).
|
||||
if declared.Sequence, err = open.inventory.Sequence(ctx, n.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := declared.Body()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -664,3 +737,142 @@ func wouldSend(ctx context.Context, open *stores,
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// raiseTheBus asserts the streams and consumers the mesh's own traffic needs.
|
||||
//
|
||||
// **Every start, and it says what it did.** The objects are the mesh's, created by nothing else —
|
||||
// the controller is their only writer (design 25 §3) — so a mesh that came up without them is one
|
||||
// where nodes connect, authenticate, and hear nothing. Said rather than silent for the reason the
|
||||
// first line of `serve` is said: a log that is quiet on success and loud on failure reads as broken
|
||||
// when it is working.
|
||||
func raiseTheBus(ctx context.Context, inv *inventory.Inventory, address string) error {
|
||||
js, err := broker.Dial(address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the mesh is on the bus at %s and this control plane cannot reach it: %w",
|
||||
broker.BareAddress(address), err)
|
||||
}
|
||||
defer js.Close()
|
||||
// What the raise decided not to fail over. Said, for the reason everything else here is said:
|
||||
// a consumer kept as it was is a difference between what the mesh asked for and what the bus
|
||||
// holds, and one nobody would find by reading either (novox/hq 04-ISSUES/156).
|
||||
js.Note = func(format string, args ...any) {
|
||||
fmt.Printf(" "+format+"\n", args...)
|
||||
}
|
||||
|
||||
// **Its own user, before anything else.** The controller's account is created by the installer at
|
||||
// a bootstrap password, before there is a controller to mint one — so nothing recorded a hash for
|
||||
// it, and the first composition would leave the writer out of the file it was writing. Recorded
|
||||
// only if absent: a credential the mesh minted since is the one that counts.
|
||||
// **Its own user, before anything else it does here.** The controller's account is created by the
|
||||
// installer at a bootstrap password, before there is a controller to mint one — so nothing
|
||||
// recorded a hash for it, and the first composition would leave the writer out of the file it was
|
||||
// writing: a bus nothing can connect to, produced by the thing connected to it. Recorded only if
|
||||
// absent, so a restart cannot put the bootstrap credential back over a rotated one.
|
||||
if user, password, _ := broker.CredentialIn(address); user != "" && password != "" {
|
||||
if err := inv.SeedBusUser(ctx, inventory.BusUser{
|
||||
Username: user, Kind: inventory.BusController,
|
||||
}, password); err != nil {
|
||||
return fmt.Errorf("cannot record the credential this control plane is using: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
nodes, err := inv.Nodes(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names := make([]string, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
names = append(names, n.Name)
|
||||
}
|
||||
if err := broker.Raise(js, names); err != nil {
|
||||
return err
|
||||
}
|
||||
// The work queues of the mesh's own roles (novox/hq ADR 0121). The queue before the holder,
|
||||
// deliberately: work queues until somebody arrives to do it, so assigning a build machine a week
|
||||
// after something started asking for builds flushes the backlog instead of having lost it.
|
||||
// With the seats' holders, so each role's work queue gets the consumer its holder takes
|
||||
// work from. Passed as nil until the first live raise, which left the build machine bound to a
|
||||
// consumer nothing had created (2026-09-28).
|
||||
holders, err := seatHolders(ctx, inv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := broker.RaiseSeats(js, inventory.MeshSeats(), holders); err != nil {
|
||||
return err
|
||||
}
|
||||
// And how every module hears what it consumes. Derived from the same records the user list is
|
||||
// composed from, so a module the mesh grants a consumer's subjects has that consumer waiting.
|
||||
// Done on every raise, not only when a credential is issued: every module moved onto this bus
|
||||
// by the rollout was issued on the old one, and came up with nothing to bind to (2026-09-28).
|
||||
records, err := inv.BusRecords(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
users, err := broker.Users(records)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hearing := 0
|
||||
for _, p := range users {
|
||||
consumer, needed := broker.ConsumerFor(p)
|
||||
if !needed {
|
||||
continue
|
||||
}
|
||||
if err := js.EnsureConsumer(consumer); err != nil {
|
||||
return fmt.Errorf("how %s on %s hears what it consumes: %w", p.Module, p.Node, err)
|
||||
}
|
||||
hearing++
|
||||
}
|
||||
fmt.Printf("the bus at %s has its streams, %d machine(s) can hear a declaration, and %d module(s) "+
|
||||
"can hear what they consume\n", broker.BareAddress(address), len(names), hearing)
|
||||
return nil
|
||||
}
|
||||
|
||||
// seatHolders is who holds each of the mesh's seats, by seat name: the record where a handover
|
||||
// wrote one, and the assigned module claiming the seat otherwise — the same derivation the
|
||||
// resolver makes, read from the catalogue rather than re-resolved.
|
||||
func seatHolders(ctx context.Context, inv *inventory.Inventory) (map[string]broker.Holder, error) {
|
||||
out := map[string]broker.Holder{}
|
||||
entries, err := inv.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if len(e.On) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, c := range e.Manifest.Claims {
|
||||
seat, known := catalogue.SeatNamed(c.Name)
|
||||
if !known {
|
||||
continue
|
||||
}
|
||||
if _, taken := out[seat.Name]; !taken {
|
||||
out[seat.Name] = broker.Holder{Node: e.On[0], Module: e.Manifest.Module}
|
||||
}
|
||||
}
|
||||
}
|
||||
recorded, err := inv.Holdings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, h := range recorded {
|
||||
if seat, known := catalogue.SeatNamed(h.Claim); known {
|
||||
out[seat.Name] = broker.Holder{Node: h.Node, Module: h.Module}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// number gives one send the next sequence for its node (novox/hq 04-ISSUES/107).
|
||||
func number(ctx context.Context, inv *inventory.Inventory, s *readyNode) error {
|
||||
record, err := inv.NodeByName(ctx, s.node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
seq, err := inv.NextSequence(ctx, record.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.declared.Sequence = seq
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -39,12 +39,14 @@ func TestOneUnresolvableNodeStillLetsTheRestBeSent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// And a machine assigned nothing is neither sent nor a refusal — it is nothing to say.
|
||||
func TestAMachineAssignedNothingIsNotARefusal(t *testing.T) {
|
||||
// A machine whose declaration composes to nothing is SENT the empty declaration, not skipped
|
||||
// (novox/hq issue 127): it may have held something before, and only sending the empty
|
||||
// declaration tells it to drop what the mesh owned. It is never a refusal.
|
||||
func TestAnEmptyDeclarationIsSentSoTheNodeDropsWhatItHeld(t *testing.T) {
|
||||
sending, refusals := composeEach([]string{"spare"},
|
||||
func(string) (sendable, error) { return sendable{}, nil })
|
||||
if len(sending) != 0 || len(refusals) != 0 {
|
||||
t.Errorf("a machine assigned nothing was treated as something: %v / %v", sending, refusals)
|
||||
if len(sending) != 1 || len(refusals) != 0 {
|
||||
t.Errorf("an empty declaration must be sent, not skipped or refused: %v / %v", sending, refusals)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,23 @@ type meshStatus struct {
|
||||
Machines int `json:"machines"`
|
||||
// Adopted is every node still adopted (novox/hq ADR 0100); absent when none is.
|
||||
Adopted []string `json:"adopted,omitempty"`
|
||||
// Untaken is every module assigned to a machine that is holding what it found rather than
|
||||
// running what the module declares, because nothing took it (novox/hq 04-ISSUES/125). Absent
|
||||
// when nothing is held.
|
||||
//
|
||||
// **A document without this said an outage was a well mesh.** Read from what each machine
|
||||
// reported, so it is the machine's account and not the mesh's take-time listing.
|
||||
Untaken []machineUntaken `json:"untaken,omitempty"`
|
||||
}
|
||||
|
||||
// machineUntaken is one module a machine is holding rather than running, and how many resources of
|
||||
// it are held.
|
||||
type machineUntaken struct {
|
||||
Node string `json:"node"`
|
||||
Module string `json:"module"`
|
||||
// Held is how many of the module's resources the machine is keeping as it found them. Zero is
|
||||
// impossible here: a module with nothing held is not in this list.
|
||||
Held int `json:"held"`
|
||||
}
|
||||
|
||||
type machineUnresolved struct {
|
||||
@@ -136,6 +153,23 @@ func statusAsJSON(asked answers) ([]byte, error) {
|
||||
Quiet: []machineQuiet{}, Behind: []moduleBehind{}, Waiting: []machineWaiting{},
|
||||
Reported: []machineReported{}, Unresolved: []machineUnresolved{},
|
||||
Network: asked.network, Adopted: adoptedNodes(nodes)}
|
||||
// In a stated order, so two readings of an unchanged mesh are the same document.
|
||||
untakenNodes := make([]string, 0, len(asked.untaken))
|
||||
for name := range asked.untaken {
|
||||
untakenNodes = append(untakenNodes, name)
|
||||
}
|
||||
sort.Strings(untakenNodes)
|
||||
for _, name := range untakenNodes {
|
||||
modules := make([]string, 0, len(asked.untaken[name]))
|
||||
for m := range asked.untaken[name] {
|
||||
modules = append(modules, m)
|
||||
}
|
||||
sort.Strings(modules)
|
||||
for _, m := range modules {
|
||||
out.Untaken = append(out.Untaken,
|
||||
machineUntaken{Node: name, Module: m, Held: asked.untaken[name][m]})
|
||||
}
|
||||
}
|
||||
for name := range asked.refused {
|
||||
out.Unresolved = append(out.Unresolved, machineUnresolved{
|
||||
Node: name, Problem: asked.refused[name]})
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/secrets"
|
||||
)
|
||||
|
||||
// Moving the mesh's own traffic to the bus being built (novox/hq ADR 0116 step 5).
|
||||
//
|
||||
// **The whole mesh moves at once, so there is nothing to inspect afterwards.** Every seam ships both
|
||||
// transports and every one of them chooses by a single fact; this is the step that flips it. That
|
||||
// shape is deliberate — steps 1 to 4 leave every node where it is, so the cost of being wrong stays
|
||||
// bounded until here — and it means the useful work is almost all in the checking.
|
||||
//
|
||||
// So `rollout check` is the command that matters and the one that can be run any number of times
|
||||
// against a mesh that is serving. It answers from records: what is missing, and what would happen.
|
||||
// `rollout` itself refuses unless the check is clean.
|
||||
//
|
||||
// **The old broker goes with the move, and goes last** (novox/hq ADR 0131): AMQP is not a provision,
|
||||
// so once every machine reports on the new bus its module is unassigned. Only the mesh's own traffic
|
||||
// is what moves, which is why this is survivable at all: what breaks if it goes wrong is the mesh's
|
||||
// ability to change things, not the services its modules are serving — measured on 2026-09-27, when
|
||||
// a seat emptied mid-change and the control plane looped for two hours while every service stayed up.
|
||||
|
||||
const rolloutUsage = "rollout check | rollout mint [--again] | rollout hand <node> | rollout --confirm"
|
||||
|
||||
func rolloutCommand(ctx context.Context, args []string) error {
|
||||
switch {
|
||||
case len(args) == 1 && args[0] == "check":
|
||||
return rolloutCheck(ctx)
|
||||
case len(args) == 1 && args[0] == "mint":
|
||||
return rolloutMint(ctx, false)
|
||||
case len(args) == 2 && args[0] == "hand":
|
||||
return rolloutHand(ctx, args[1])
|
||||
case len(args) == 2 && args[0] == "mint" && args[1] == "--again":
|
||||
// Every credential minted afresh, whether or not one exists — for a mint that was wrong
|
||||
// before anything was pushed. Afterwards nothing that received the old one still works,
|
||||
// which is fine exactly when nothing received it.
|
||||
return rolloutMint(ctx, true)
|
||||
case len(args) == 1 && args[0] == "--confirm":
|
||||
return errors.New(
|
||||
"the rollout itself is not built yet: `rollout check` answers whether it could run, and " +
|
||||
"what is missing. Moving every node at once is the one step with nothing to inspect " +
|
||||
"afterwards, so it is not being written before the check it depends on has been run " +
|
||||
"against a real mesh")
|
||||
default:
|
||||
return errors.New(rolloutUsage)
|
||||
}
|
||||
}
|
||||
|
||||
// rolloutCheck says whether the mesh could move, and what would happen if it did.
|
||||
func rolloutCheck(ctx context.Context) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
|
||||
state, err := readinessOf(ctx, inv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("the bus this mesh would move to")
|
||||
if state.TheBus == "" {
|
||||
fmt.Printf(" nothing names one (%s is unset)\n", broker.NATSVar)
|
||||
} else {
|
||||
standing := "not answering"
|
||||
if state.ServerStanding {
|
||||
standing = "answering"
|
||||
}
|
||||
fmt.Printf(" %s — %s\n", state.TheBus, standing)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
fmt.Println("what would move")
|
||||
for _, step := range broker.WhatMoves(state) {
|
||||
fmt.Printf(" %s\n", step)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
why := notReadyOf(state)
|
||||
if len(why) == 0 {
|
||||
fmt.Println("nothing is missing: this mesh could move its bus.")
|
||||
fmt.Println()
|
||||
fmt.Println("Read `what would move` above once more before running it. Every node moves at the")
|
||||
fmt.Println("same moment and there is no half-moved state to look at afterwards.")
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("not ready — %d thing(s) to do first:\n", len(why))
|
||||
for i, w := range why {
|
||||
fmt.Printf(" %d. %s\n", i+1, w)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readinessOf gathers what the mesh knows about its own ability to move.
|
||||
//
|
||||
// Reads and one dial, and nothing is written. Safe to run on a mesh that is serving, which is the
|
||||
// point: the answer is only useful if it can be had without committing to anything.
|
||||
func readinessOf(ctx context.Context, inv *inventory.Inventory) (broker.Readiness, error) {
|
||||
state := broker.Readiness{
|
||||
Credentialled: map[string]bool{},
|
||||
ModuleCredentialled: map[string]bool{},
|
||||
// The old broker keeps its other clients on this installation, and saying so is how the plan
|
||||
// stops reading as a retirement.
|
||||
}
|
||||
|
||||
address, _, err := broker.OnNATS()
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.TheBus = address
|
||||
if address != "" {
|
||||
// One dial, briefly. "Is it answering" is the one fact records cannot hold, and a mesh about
|
||||
// to move onto a server that is not there should hear it here rather than afterwards.
|
||||
//
|
||||
// **Dialled the way the mesh dials it** — credential and pin — because a bare connect to a
|
||||
// bus that requires TLS and a user fails at the handshake, and the check then reported a
|
||||
// standing server as absent (seen live, 2026-09-28).
|
||||
if js, err := broker.Dial(address, nats.Timeout(5*time.Second)); err == nil {
|
||||
state.ServerStanding = true
|
||||
js.Close()
|
||||
}
|
||||
}
|
||||
|
||||
nodes, err := inv.Nodes(ctx)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
kept, err := inv.BusUsers(ctx)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
shelf, err := inv.Catalogue(ctx)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
|
||||
for _, n := range nodes {
|
||||
state.Nodes = append(state.Nodes, n.Name)
|
||||
_, has := kept[broker.Principal{Kind: broker.KindNode, Node: n.Name}.Username()]
|
||||
state.Credentialled[n.Name] = has
|
||||
|
||||
assigned, err := inv.Assigned(ctx, n.Name)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
for _, module := range assigned {
|
||||
m, known := shelf[module]
|
||||
if !known {
|
||||
continue
|
||||
}
|
||||
// The machine that holds the bus seat is the one that would be sent the user list.
|
||||
if m.BusUsers != "" && m.ClaimsSeat("mesh-broker") {
|
||||
state.Holder = n.Name
|
||||
state.AccountsComposed = wasSentTheUserList(ctx, inv, n.Name)
|
||||
}
|
||||
// A module that never speaks needs no credential, so it is not counted as missing one.
|
||||
if !speaksOnTheBus(m) {
|
||||
continue
|
||||
}
|
||||
named := n.Name + "/" + module
|
||||
state.Modules = append(state.Modules, named)
|
||||
_, hasOne := kept[broker.Principal{
|
||||
Kind: broker.KindModule, Node: n.Name, Module: module,
|
||||
}.Username()]
|
||||
state.ModuleCredentialled[named] = hasOne
|
||||
}
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// speaksOnTheBus says whether a module reaches the bus at all.
|
||||
//
|
||||
// A third of the catalogue never does (novox/hq ADR 0120), and counting those as missing a credential
|
||||
// would bury the ones that matter under a list nobody can act on.
|
||||
func speaksOnTheBus(m catalogue.Manifest) bool {
|
||||
return len(m.Emits) > 0 || len(m.Consumes) > 0 || len(m.Tools) > 0 ||
|
||||
len(m.DefinesSeats) > 0 || len(m.Uses) > 0 || len(m.Claims) > 0
|
||||
}
|
||||
|
||||
// wasSentTheUserList says whether the machine holding the bus has had a declaration since the user
|
||||
// list became part of one.
|
||||
//
|
||||
// Read from what the mesh recorded sending rather than asked of the machine: a machine that is away
|
||||
// has still been sent it, and this question is about whether the mesh did its part.
|
||||
func wasSentTheUserList(ctx context.Context, inv *inventory.Inventory, node string) bool {
|
||||
digest, err := inv.Outstanding(ctx, node)
|
||||
return err == nil && strings.TrimSpace(digest) != ""
|
||||
}
|
||||
|
||||
// notReadyOf is the readiness reasoning, named here so a test can reach it without the command's
|
||||
// printing. The reasoning itself is the broker package's, where it is pure.
|
||||
func notReadyOf(state broker.Readiness) []string { return broker.NotReady(state) }
|
||||
|
||||
// rolloutMint gives every principal the new bus will have a credential it does not yet have, and
|
||||
// puts each where its owner reads it (novox/hq design 28, task 5.2): a machine's as a membership
|
||||
// sealed into its declaration, a module's as its broker secret, the control plane's own as its
|
||||
// `bus` secret. Idempotent: what already has a hash is left alone, so running it again is harmless.
|
||||
//
|
||||
// **Before anything moves, and it is what makes moving possible.** A machine moved without a
|
||||
// credential cannot come back, and afterwards there is no bus to tell it anything over — which is
|
||||
// why `rollout check` refuses until this has run. The bus's address is worked out here, from where
|
||||
// the module that provides it is assigned, rather than read from this process's environment: this
|
||||
// process is still on the old bus when this runs, and must be.
|
||||
func rolloutMint(ctx context.Context, again bool) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
|
||||
known, err := broker.FromEnvironment()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the bus's certificate is not known to this process, and every membership "+
|
||||
"must carry its fingerprint: %w", err)
|
||||
}
|
||||
shelf, err := inv.Catalogue(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := inv.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var busNode, controllerNode string
|
||||
for _, e := range entries {
|
||||
switch {
|
||||
case e.Manifest.ClaimsSeat("mesh-broker") && providesBus(e.Manifest) && len(e.On) > 0:
|
||||
busNode = e.On[0]
|
||||
case e.Manifest.Module == "mesh-controller" && len(e.On) > 0:
|
||||
controllerNode = e.On[0]
|
||||
}
|
||||
}
|
||||
if busNode == "" {
|
||||
return errors.New("no assigned module provides mesh-bus and claims mesh-broker, so there is no " +
|
||||
"bus to mint credentials for — register and assign it first")
|
||||
}
|
||||
onNetwork, err := whereEveryoneIs(ctx, inv, shelf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
busHost := onNetwork[busNode]
|
||||
if busHost == "" {
|
||||
// **The hub is not in that map.** The machine that took over the tunnel is where the current
|
||||
// bus already answers, and every machine dials it at the address the mesh handed them — so
|
||||
// when the new bus runs on the same machine, that address is the one to tell them, with the
|
||||
// new port. Found live: the control node is the hub, and the map lists the machines placed
|
||||
// around it.
|
||||
// The host alone: no scheme (BareAddress adds one where none was, which is the wrong
|
||||
// direction here — every URL built below adds its own) and no port.
|
||||
_, _, host := broker.CredentialIn(known.Address)
|
||||
if host == "" {
|
||||
host = known.Address
|
||||
}
|
||||
if _, after, hasScheme := strings.Cut(host, "://"); hasScheme {
|
||||
host = after
|
||||
}
|
||||
host = strings.TrimSpace(host)
|
||||
if i := strings.LastIndex(host, ":"); i > 0 && !strings.Contains(host[i:], "]") {
|
||||
host = host[:i]
|
||||
}
|
||||
if host == "" {
|
||||
return fmt.Errorf("%s runs the new bus and has no address on the private network, and the "+
|
||||
"current bus's address is unknown too, so no machine could be told where it is", busNode)
|
||||
}
|
||||
busHost = host
|
||||
}
|
||||
busAddress := busHost + ":4222"
|
||||
|
||||
records, err := inv.BusRecords(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
users, err := broker.Users(records)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kept, err := inv.BusUsers(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hashes := make(map[string]string, len(kept))
|
||||
for name, u := range kept {
|
||||
hashes[name] = u.PasswordHash
|
||||
}
|
||||
_, missing := broker.WithPasswords(users, hashes)
|
||||
wanted := map[string]bool{}
|
||||
for _, m := range missing {
|
||||
wanted[m] = true
|
||||
}
|
||||
|
||||
var machines, modules, skipped int
|
||||
for _, p := range users {
|
||||
if !again && !wanted[p.Username()] {
|
||||
continue
|
||||
}
|
||||
switch p.Kind {
|
||||
case broker.KindController:
|
||||
if controllerNode == "" {
|
||||
return errors.New("the control plane is not assigned anywhere, so its credential has nowhere to go")
|
||||
}
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{Username: p.Username(), Kind: inventory.BusController})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
url := "nats://" + p.Username() + ":" + password + "@" + busAddress
|
||||
if err := inv.AcceptSecretForModule(ctx, controllerNode, "mesh-controller", "bus", url); err != nil {
|
||||
return fmt.Errorf("the control plane's credential is minted and could not be sealed to %s: %w", controllerNode, err)
|
||||
}
|
||||
fmt.Printf("control plane: credential minted, sealed to %s as its `bus` secret\n", controllerNode)
|
||||
|
||||
case broker.KindNode:
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{Username: p.Username(), Kind: inventory.BusNode, Node: p.Node})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
membership, _ := json.Marshal(map[string]string{
|
||||
"broker": busAddress, "fingerprint": known.Fingerprint, "password": password, "transport": "nats",
|
||||
})
|
||||
key, err := inv.SealingKeyOf(ctx, p.Node)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s has no sealing key, so its membership cannot be sealed to it: %w", p.Node, err)
|
||||
}
|
||||
sealed, err := secrets.Seal(key, membership)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.PutBusMembership(ctx, p.Node, sealed); err != nil {
|
||||
return err
|
||||
}
|
||||
machines++
|
||||
|
||||
case broker.KindModule:
|
||||
if p.Module == "mesh-controller" {
|
||||
// The control plane is a module too, and its `broker` secret is the old bus's
|
||||
// credential it is still using while this runs. Writing the new bus's blob there
|
||||
// cut the mesh off from its own old bus mid-move (2026-09-28). Its new-bus credential
|
||||
// is the controller principal's `bus` secret above; nothing else is needed here.
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
m, inShelf := shelf[p.Module]
|
||||
if !inShelf {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
if _, reads := m.OwnSecrets["broker"]; !reads {
|
||||
fmt.Printf(" %s on %s speaks on the bus but declares no `broker` secret to receive a credential in; skipped\n", p.Module, p.Node)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{Username: p.Username(), Kind: inventory.BusModule, Node: p.Node, Module: p.Module})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := issueWith(ctx, inv, m, p.Node, "", known, busAddress, p.Username(), password); err != nil {
|
||||
return err
|
||||
}
|
||||
modules++
|
||||
|
||||
default:
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
fmt.Printf("minted for %d machine(s) and %d module runtime(s); %d skipped; the bus is at %s\n",
|
||||
machines, modules, skipped, busAddress)
|
||||
fmt.Println(" each machine's membership and each module's credential arrive with the next push of its machine;")
|
||||
fmt.Println(" push the machine running the bus first, so the bus stands with its user list before anything dials it")
|
||||
return nil
|
||||
}
|
||||
|
||||
// providesBus is whether a manifest provides the mesh's bus.
|
||||
func providesBus(m catalogue.Manifest) bool {
|
||||
for _, o := range m.Provides {
|
||||
if o.Name == "mesh-bus" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// rolloutHand mints a machine its credential for the new bus afresh and prints its membership
|
||||
// once, for an operator to carry by hand — the rescue for a machine that cannot be reached over
|
||||
// any bus: rotated while it still held the old password, or reachable only by ssh. The plaintext
|
||||
// exists on this terminal and then only where it is written; the store keeps the hash, and the
|
||||
// sealed copy in the machine's declaration is replaced too, so the next push says the same.
|
||||
func rolloutHand(ctx context.Context, node string) error {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
|
||||
known, err := broker.FromEnvironment()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the bus's certificate is not known to this process: %w", err)
|
||||
}
|
||||
busAddress, _, err := broker.OnNATS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if busAddress == "" {
|
||||
return errors.New("this control plane is not on the new bus, so there is no membership to hand out")
|
||||
}
|
||||
_, _, bare := broker.CredentialIn(busAddress)
|
||||
if _, after, has := strings.Cut(bare, "://"); has {
|
||||
bare = after
|
||||
}
|
||||
if _, err := inv.NodeByName(ctx, node); err != nil {
|
||||
return err
|
||||
}
|
||||
p := broker.Principal{Kind: broker.KindNode, Node: node}
|
||||
password, err := inv.MintBusPassword(ctx, inventory.BusUser{Username: p.Username(), Kind: inventory.BusNode, Node: node})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
membership, _ := json.Marshal(map[string]string{
|
||||
"broker": bare, "fingerprint": known.Fingerprint, "password": password, "transport": "nats",
|
||||
})
|
||||
key, err := inv.SealingKeyOf(ctx, node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sealed, err := secrets.Seal(key, membership)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := inv.PutBusMembership(ctx, node, sealed); err != nil {
|
||||
return err
|
||||
}
|
||||
// The one line of output is the membership itself, so it can be piped to the machine without
|
||||
// being read on the way. Everything else goes to stderr.
|
||||
fmt.Fprintf(os.Stderr, "%s's credential is minted afresh. Write this to %s on it and restart its host; "+
|
||||
"then push the machine running the bus so the user list carries the new hash.\n",
|
||||
node, catalogue.BusMembershipPath)
|
||||
fmt.Println(string(membership))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
)
|
||||
|
||||
// Whether a mesh could move its bus, read from a real store.
|
||||
//
|
||||
// The readiness reasoning has its own tests; this is about the gathering — that the question is
|
||||
// answered from what the mesh actually holds, on a store with machines and modules in it, without
|
||||
// writing anything.
|
||||
|
||||
func TestReadinessIsGatheredFromWhatTheMeshHolds(t *testing.T) {
|
||||
inv := inventory.ForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// A mesh mid-change: two machines, the bus module on one of them, a module that speaks and a
|
||||
// module that never does.
|
||||
for _, m := range []catalogue.Manifest{
|
||||
{Module: "nats", Version: "1", BusUsers: "/var/lib/nats-module/conf/accounts.conf",
|
||||
Claims: []catalogue.Claim{{Name: "mesh-broker", Scope: catalogue.ScopeMesh}}},
|
||||
{Module: "gitea", Version: "1", Tools: []string{"repo_create"}},
|
||||
{Module: "wallpaper", Version: "1"},
|
||||
} {
|
||||
if err := inv.RegisterModule(ctx, m, inventory.Source{Repository: "/r"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"anchor", "laptop"} {
|
||||
if _, err := inv.AddNode(ctx, n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, a := range [][2]string{{"anchor", "nats"}, {"anchor", "gitea"}, {"laptop", "wallpaper"}} {
|
||||
if _, err := inv.Assign(ctx, a[0], a[1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
state, err := readinessOf(ctx, inv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if state.Holder != "anchor" {
|
||||
t.Errorf("the machine holding the bus reads as %q", state.Holder)
|
||||
}
|
||||
if len(state.Nodes) != 2 {
|
||||
t.Errorf("machines read as %v", state.Nodes)
|
||||
}
|
||||
// **A module that never speaks is not counted as missing a credential.** A third of the catalogue
|
||||
// never reaches the bus, and listing those would bury the ones that matter.
|
||||
for _, m := range state.Modules {
|
||||
if strings.HasSuffix(m, "/wallpaper") {
|
||||
t.Errorf("a module that never speaks was counted: %v", state.Modules)
|
||||
}
|
||||
}
|
||||
if len(state.Modules) != 2 {
|
||||
t.Errorf("modules that speak read as %v; expected the bus module and the one with a tool",
|
||||
state.Modules)
|
||||
}
|
||||
|
||||
// Nothing has been minted, so it is not ready — and it says so about each machine by name.
|
||||
why := notReadyOf(state)
|
||||
if len(why) == 0 {
|
||||
t.Fatal("a mesh where nothing has a credential was reported ready to move")
|
||||
}
|
||||
said := strings.Join(why, "\n")
|
||||
for _, name := range []string{"anchor", "laptop"} {
|
||||
if !strings.Contains(said, name) {
|
||||
t.Errorf("the refusal does not name %s: %s", name, said)
|
||||
}
|
||||
}
|
||||
|
||||
// Mint for one machine and it drops out of the complaint, which is how somebody works through it.
|
||||
if _, err := inv.MintBusPassword(ctx, inventory.BusUser{
|
||||
Username: "node.laptop", Kind: inventory.BusNode, Node: "laptop",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err = readinessOf(ctx, inv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !state.Credentialled["laptop"] {
|
||||
t.Error("a machine that was minted a credential still reads as having none")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A node's own set failing to compose, and the mesh being unable to answer at all, are different
|
||||
// things, and only the first may be passed over when something is gathered across every machine
|
||||
// (novox/hq 04-ISSUES/152). These pin that distinction where the three gatherers rely on it.
|
||||
|
||||
func TestASetThatDoesNotComposeIsMarkedAsTheNodesOwnProblem(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
one, two := rivals()
|
||||
register(t, open, one)
|
||||
register(t, open, two)
|
||||
for _, m := range []string{one.Module, two.Module} {
|
||||
if _, err := open.inventory.Assign(t.Context(), "laptop", m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
_, _, err := planFor(t.Context(), open, "laptop")
|
||||
if err == nil {
|
||||
t.Fatal("two modules claiming one seat composed anyway")
|
||||
}
|
||||
if !unresolvable(err) {
|
||||
t.Fatalf("a set that cannot compose was not marked as the node's own problem: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStoreThatCannotBeReadIsNotANodeThatDoesNotCompose(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
|
||||
// Nothing is wrong with anchor. The question simply cannot be asked.
|
||||
stopped, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
_, _, err := planFor(stopped, open, "anchor")
|
||||
if err == nil {
|
||||
t.Fatal("a plan composed against a store that could not be read")
|
||||
}
|
||||
if unresolvable(err) {
|
||||
t.Fatalf("a question the mesh could not answer was read as a node that runs nothing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOneIncoherentNodeDoesNotCostTheRestTheirNames(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
one, two := rivals()
|
||||
register(t, open, one)
|
||||
register(t, open, two)
|
||||
for _, m := range []string{one.Module, two.Module} {
|
||||
if _, err := open.inventory.Assign(t.Context(), "laptop", m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// laptop cannot compose. That is laptop's problem and nobody else's: the roster is still
|
||||
// answerable, and anchor keeps whatever it serves.
|
||||
if _, err := routeNamesInTheMesh(t.Context(), open); err != nil {
|
||||
t.Fatalf("one node's broken set cost the whole mesh its roster: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARosterIsNeverReturnedWithNamesItCouldNotRead(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
|
||||
stopped, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
names, err := routeNamesInTheMesh(stopped, open)
|
||||
if err == nil {
|
||||
t.Fatalf("a roster was composed from a store that could not be read: %v", names)
|
||||
}
|
||||
// The failure must be raised, not turned into an absence. A roster missing a machine's names
|
||||
// is indistinguishable, on every machine that receives it, from the operator withdrawing them —
|
||||
// and because the roster is part of every container's identity, it replaces all of them.
|
||||
if names != nil {
|
||||
t.Fatalf("a partial roster was returned beside the error: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Kept so the reason survives the next person reading it: the message the gatherer raises must say
|
||||
// which machine could not be read, or the operator is left with a mesh-wide failure and no name.
|
||||
func TestTheRaisedFailureNamesTheMachineItCouldNotRead(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
stopped, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
_, err := routeNamesInTheMesh(stopped, open)
|
||||
if err == nil {
|
||||
t.Fatal("no failure was raised")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cannot be read") {
|
||||
t.Fatalf("the failure does not say the mesh could not be read: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
@@ -43,15 +44,16 @@ type seatRow struct {
|
||||
// overview would make the one thing the overview is for — what does this mesh have — quietly
|
||||
// incomplete.
|
||||
func seatsHeld(seats []catalogue.Seat, held []catalogue.Held) ([]seatRow, []catalogue.Held) {
|
||||
defined := map[string]bool{}
|
||||
rows := make([]seatRow, 0, len(seats))
|
||||
for _, s := range seats {
|
||||
defined[s.Name] = true
|
||||
row := seatRow{Seat: s.Name, Scope: s.Scope, Delivers: s.Delivers, Decision: s.Decision,
|
||||
Holders: []seatHolder{}}
|
||||
seen := map[seatHolder]bool{}
|
||||
for _, h := range held {
|
||||
if h.Claim != s.Name || h.Scope != s.Scope {
|
||||
// Resolve the held claim to a seat rather than comparing names, so a record naming a
|
||||
// seat's former name groups under it after a rename (novox/hq ADR 0122).
|
||||
hs, ok := catalogue.SeatNamed(h.Claim)
|
||||
if !ok || hs.Name != s.Name || h.Scope != s.Scope {
|
||||
continue
|
||||
}
|
||||
holder := seatHolder{Node: h.Node, Module: h.Module}
|
||||
@@ -70,7 +72,8 @@ func seatsHeld(seats []catalogue.Seat, held []catalogue.Held) ([]seatRow, []cata
|
||||
}
|
||||
var outside []catalogue.Held
|
||||
for _, h := range held {
|
||||
if !defined[h.Claim] {
|
||||
// Outside the set only if it resolves to no seat at all — a former name still resolves.
|
||||
if _, ok := catalogue.SeatNamed(h.Claim); !ok {
|
||||
outside = append(outside, h)
|
||||
}
|
||||
}
|
||||
@@ -83,6 +86,120 @@ func seatsHeld(seats []catalogue.Seat, held []catalogue.Held) ([]seatRow, []cata
|
||||
return rows, outside
|
||||
}
|
||||
|
||||
// seatCommand changes the set — the whole point of it being data (novox/hq ADR 0122) — and, since
|
||||
// ADR 0131, changes who holds a seat.
|
||||
func seatCommand(ctx context.Context, args []string) error {
|
||||
if len(args) == 3 && args[0] == "rename" {
|
||||
from, to := args[1], args[2]
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
if err := open.inventory.RenameSeat(ctx, from, to); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s is now %s — its former name still resolves, so nothing is rebuilt, "+
|
||||
"re-registered or frozen (novox/hq ADR 0122)\n", from, to)
|
||||
return nil
|
||||
}
|
||||
if len(args) == 3 && args[1] == "--to" {
|
||||
return handOver(ctx, args[0], args[2])
|
||||
}
|
||||
return fmt.Errorf("seat rename <from> <to> | seat <name> --to <node>/<module>")
|
||||
}
|
||||
|
||||
// handOver makes one assignment the holder of a seat, as one act, so the seat is never without a
|
||||
// holder in between (novox/hq ADR 0131, design 28 task 5.3). The control plane finds its own bus
|
||||
// through one of these seats; the day it was left empty mid-change is why this exists.
|
||||
//
|
||||
// Everything that could make the new holder wrong is refused here, before the row is written: the
|
||||
// seat must exist, the assignment must exist, and the module must be able to hold the seat —
|
||||
// claim it at its scope and provide what it delivers, judged against the store's row. What is
|
||||
// **not** checked is whether the module is running yet: that is what `push` confirms afterwards,
|
||||
// and refusing to record a handover to a module the node has not started would make the handover
|
||||
// impossible to do before the switch instead of as the switch.
|
||||
func handOver(ctx context.Context, seatName, to string) error {
|
||||
nodeName, module, ok := strings.Cut(to, "/")
|
||||
if !ok || nodeName == "" || module == "" {
|
||||
return fmt.Errorf("the new holder is named <node>/<module>, not %q", to)
|
||||
}
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
inv := open.inventory
|
||||
|
||||
seat, known := catalogue.SeatNamed(seatName)
|
||||
if !known {
|
||||
return fmt.Errorf("%q is not a seat this mesh defines — `seats` lists them", seatName)
|
||||
}
|
||||
assigned, err := inv.Assigned(ctx, nodeName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !slices.Contains(assigned, module) {
|
||||
return fmt.Errorf("%s is not assigned to %s, so it cannot hold anything there — "+
|
||||
"`assign %s %s` first", module, nodeName, nodeName, module)
|
||||
}
|
||||
entries, err := inv.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var m *catalogue.Manifest
|
||||
for i := range entries {
|
||||
if entries[i].Manifest.Module == module {
|
||||
m = &entries[i].Manifest
|
||||
}
|
||||
}
|
||||
if m == nil {
|
||||
return fmt.Errorf("%s is assigned but not in the catalogue, which should not happen", module)
|
||||
}
|
||||
var was string
|
||||
holdings, err := inv.Holdings(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, h := range holdings {
|
||||
if hs, ok := catalogue.SeatNamed(h.Claim); ok && hs.Name == seat.Name {
|
||||
was = h.Node
|
||||
}
|
||||
}
|
||||
|
||||
// **Recording who already holds the seat is not making a new holder, and is not judged like
|
||||
// one.** On a mesh that predates the record, the first handover has to begin by writing down
|
||||
// the standing holder — otherwise the next holder cannot be assigned beside it, because two
|
||||
// eligible claimants with nothing on record are refused. That standing holder may no longer
|
||||
// satisfy what the seat delivers (the row moved under it, on purpose, as ADR 0131's first step),
|
||||
// and it holds regardless: derivation never read that column. So when nothing is on record and
|
||||
// the named assignment is the one holding by derivation, only the claim itself is checked here.
|
||||
// Every *change* of holder is judged in full.
|
||||
claimsIt := false
|
||||
for _, c := range m.Claims {
|
||||
if cs, ok := catalogue.SeatNamed(c.Name); ok && cs.Name == seat.Name && c.At() == seat.Scope {
|
||||
claimsIt = true
|
||||
}
|
||||
}
|
||||
if was == "" && claimsIt {
|
||||
fmt.Printf("nothing was on record for %s; recording %s on %s as its standing holder\n",
|
||||
seat.Name, module, nodeName)
|
||||
} else if err := catalogue.CanHold(*m, seat); err != nil {
|
||||
return fmt.Errorf("%s cannot hold %s: %w", module, seat.Name, err)
|
||||
}
|
||||
if err := inv.HoldSeat(ctx, seat.Name, seat.Scope, nodeName, module); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("%s is held by %s on %s\n", seat.Name, module, nodeName)
|
||||
if was != "" && was != nodeName {
|
||||
fmt.Printf(" `push %s` and `push %s` send both machines what changed\n", was, nodeName)
|
||||
} else {
|
||||
fmt.Printf(" `push %s` sends the machine what changed; every other machine that reads the "+
|
||||
"seat is re-declared by `push --behind`\n", nodeName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func seatsCommand(ctx context.Context, args []string) error {
|
||||
set := flag.NewFlagSet("seats", flag.ContinueOnError)
|
||||
asJSON := set.Bool("json", false, "the same, as JSON")
|
||||
|
||||
@@ -35,13 +35,13 @@ func TestEverySeatIsListedIncludingTheOnesNobodyHolds(t *testing.T) {
|
||||
|
||||
func TestANodeSeatListsEveryMachineHoldingIt(t *testing.T) {
|
||||
rows, _ := seatsHeld(catalogue.Seats(), []catalogue.Held{
|
||||
{Claim: "the-packet-filter", Scope: catalogue.ScopeNode, Node: "node2", Module: "nftables"},
|
||||
{Claim: "the-packet-filter", Scope: catalogue.ScopeNode, Node: "anchor", Module: "nftables"},
|
||||
{Claim: "node-packet-filter", Scope: catalogue.ScopeNode, Node: "node2", Module: "nftables"},
|
||||
{Claim: "node-packet-filter", Scope: catalogue.ScopeNode, Node: "anchor", Module: "nftables"},
|
||||
// Resolved twice, reported once: a machine is one holder however many passes saw it.
|
||||
{Claim: "the-packet-filter", Scope: catalogue.ScopeNode, Node: "anchor", Module: "nftables"},
|
||||
{Claim: "node-packet-filter", Scope: catalogue.ScopeNode, Node: "anchor", Module: "nftables"},
|
||||
})
|
||||
for _, r := range rows {
|
||||
if r.Seat != "the-packet-filter" {
|
||||
if r.Seat != "node-packet-filter" {
|
||||
continue
|
||||
}
|
||||
if len(r.Holders) != 2 || r.Holders[0].Node != "anchor" || r.Holders[1].Node != "node2" {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
|
||||
// The mesh's own verbs, served as the mesh-controller seat's tools (novox/hq ADR 0154, design 33).
|
||||
//
|
||||
// **Each tool runs the command it names, in this same binary, and answers what it printed.** That is
|
||||
// ADR 0035 taken literally: the logic lives once, in the command, and a surface is an adapter with no
|
||||
// decisions in it. Running a fresh process rather than calling the function keeps two things true
|
||||
// that calling it would not — every command opens and closes its own stores the way it does from a
|
||||
// shell, and nothing a command prints to the process's standard output can leak into another call's
|
||||
// answer. It also means a refusal is the same refusal in the same words, because it is the same
|
||||
// output.
|
||||
|
||||
// verbAnswer is what a verb answers: what the command printed, whether it succeeded, and — where the
|
||||
// command speaks JSON — the same as data.
|
||||
type verbAnswer struct {
|
||||
Output string `json:"output"`
|
||||
OK bool `json:"ok"`
|
||||
Answer any `json:"answer,omitempty"`
|
||||
}
|
||||
|
||||
// argvFor is the command line a verb and its arguments become. Only the verbs the seat declares, and
|
||||
// only the arguments each declares: a caller cannot reach a flag the schema did not name.
|
||||
func argvFor(verb string, args map[string]any) ([]string, error) {
|
||||
str := func(key string) string {
|
||||
v, _ := args[key].(string)
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
need := func(keys ...string) error {
|
||||
for _, k := range keys {
|
||||
if str(k) == "" {
|
||||
return fmt.Errorf("%s needs %q", verb, k)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
switch verb {
|
||||
case "status":
|
||||
return []string{"status", "--json"}, nil
|
||||
case "nodes":
|
||||
return []string{"node", "list"}, nil
|
||||
case "node":
|
||||
if err := need("node"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"node", "show", str("node")}, nil
|
||||
case "modules":
|
||||
return []string{"module", "list"}, nil
|
||||
case "seats":
|
||||
return []string{"seats", "--json"}, nil
|
||||
case "builds":
|
||||
if m := str("module"); m != "" {
|
||||
return []string{"builds", m}, nil
|
||||
}
|
||||
return []string{"builds"}, nil
|
||||
case "plan":
|
||||
if err := need("node"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"plan", str("node"), "--json"}, nil
|
||||
case "assign", "unassign":
|
||||
if err := need("node", "module"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{verb, str("node"), str("module")}, nil
|
||||
case "push":
|
||||
// Sent and not waited for: the asker reads `status` for what the machine did, which is
|
||||
// what a person at a shell does too. A tool call that blocked for a push's whole apply would
|
||||
// time out on every machine that takes a minute, and say nothing about the ones that did not.
|
||||
if n := str("node"); n != "" {
|
||||
return []string{"push", n, "--wait", "0"}, nil
|
||||
}
|
||||
return []string{"push", "--behind", "--wait", "0"}, nil
|
||||
case "build":
|
||||
if err := need("repository"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
argv := []string{"build", str("repository"), "--wait", "0"}
|
||||
if p := str("path"); p != "" {
|
||||
argv = append(argv, "--path", p)
|
||||
}
|
||||
if r := str("ref"); r != "" {
|
||||
argv = append(argv, "--ref", r)
|
||||
}
|
||||
return argv, nil
|
||||
}
|
||||
return nil, fmt.Errorf("%q is not a verb the %s seat serves", verb, catalogue.ControllerSeatName)
|
||||
}
|
||||
|
||||
// jsonVerbs are the verbs whose command speaks JSON, so the answer carries it as data as well.
|
||||
var jsonVerbs = map[string]bool{"status": true, "seats": true, "plan": true}
|
||||
|
||||
// runVerb runs this binary with the given command line and gathers what it said.
|
||||
func runVerb(ctx context.Context, argv []string) (verbAnswer, error) {
|
||||
self, err := os.Executable()
|
||||
if err != nil {
|
||||
return verbAnswer{}, err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, self, argv...)
|
||||
// The same environment: the stores' credentials, the bus, the broker — everything a command run
|
||||
// from a shell in this container would have, because it is that.
|
||||
cmd.Env = os.Environ()
|
||||
// Two buffers, one answer. What the command *says* is both streams, in the order a person at
|
||||
// a shell would read them; what it *answers as data* is standard output alone — `status --json`
|
||||
// prints its warnings beside the document, and a JSON parsed from the two together parsed
|
||||
// nothing (2026-09-30, the first status asked through the console had no `answer`).
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
runErr := cmd.Run()
|
||||
answer := verbAnswer{Output: stdout.String() + stderr.String(), OK: runErr == nil}
|
||||
if jsonVerbs[argv[0]] && runErr == nil {
|
||||
var parsed any
|
||||
if json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &parsed) == nil {
|
||||
answer.Answer = parsed
|
||||
}
|
||||
}
|
||||
var exit *exec.ExitError
|
||||
if runErr != nil && !errors.As(runErr, &exit) {
|
||||
// Not the command refusing — the command not running at all, which is this process's fault.
|
||||
return answer, fmt.Errorf("could not run %s: %w", strings.Join(argv, " "), runErr)
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
// seatToolHandlers are the handlers for every verb the mesh-controller seat declares, from the
|
||||
// store's row, so a verb the row does not carry is not served and a verb it carries that this binary
|
||||
// cannot run is said at start rather than at the first call.
|
||||
func seatToolHandlers() (map[string]link.ToolHandler, error) {
|
||||
seat, known := catalogue.SeatNamed(catalogue.ControllerSeatName)
|
||||
if !known {
|
||||
return nil, fmt.Errorf("this mesh defines no %s seat", catalogue.ControllerSeatName)
|
||||
}
|
||||
handlers := map[string]link.ToolHandler{}
|
||||
for _, v := range seat.Serves {
|
||||
verb := v.Name
|
||||
if verb == "tools" {
|
||||
handlers[verb] = func(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
return seatTools(), nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := argvFor(verb, map[string]any{"node": "x", "module": "x", "repository": "x"}); err != nil {
|
||||
return nil, fmt.Errorf("the %s seat's row declares %q, which this control plane cannot run: %w",
|
||||
catalogue.ControllerSeatName, verb, err)
|
||||
}
|
||||
handlers[verb] = func(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
args := map[string]any{}
|
||||
if len(raw) > 0 {
|
||||
if err := json.Unmarshal(raw, &args); err != nil {
|
||||
return nil, fmt.Errorf("the arguments are not a JSON object: %w", err)
|
||||
}
|
||||
}
|
||||
argv, err := argvFor(verb, args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return runVerb(ctx, argv)
|
||||
}
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
// seatTools is what `tools` answers: every seat with a protocol, and the tools each serves, from the
|
||||
// mesh's own records — no holder in the path, so it is true while a holder restarts (design 33 §5).
|
||||
func seatTools() map[string]any {
|
||||
var seats []map[string]any
|
||||
for _, s := range catalogue.SeatsWithAProtocol() {
|
||||
if len(s.Serves) == 0 {
|
||||
continue
|
||||
}
|
||||
var tools []map[string]any
|
||||
for _, v := range s.Serves {
|
||||
tools = append(tools, map[string]any{
|
||||
"name": v.Name, "description": v.Description, "input": v.Input, "output": v.Output,
|
||||
})
|
||||
}
|
||||
seats = append(seats, map[string]any{"seat": s.Name, "scope": s.Scope, "tools": tools})
|
||||
}
|
||||
return map[string]any{"seats": seats}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// Every verb the mesh-controller seat declares is one this binary can run, with the arguments the
|
||||
// schema names and no other (novox/hq ADR 0154, ADR 0035).
|
||||
func TestEveryDeclaredVerbHasACommandLine(t *testing.T) {
|
||||
for _, v := range catalogue.ControllerVerbs {
|
||||
if v.Name == "tools" {
|
||||
continue
|
||||
}
|
||||
args := map[string]any{}
|
||||
props, _ := v.Input["properties"].(map[string]any)
|
||||
for name := range props {
|
||||
args[name] = "x"
|
||||
}
|
||||
argv, err := argvFor(v.Name, args)
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", v.Name, err)
|
||||
continue
|
||||
}
|
||||
if argv[0] == "" {
|
||||
t.Errorf("%s: empty command", v.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A required argument missing is refused in the verb's own words, before anything runs.
|
||||
func TestAVerbMissingWhatItNeedsIsRefused(t *testing.T) {
|
||||
if _, err := argvFor("node", map[string]any{}); err == nil || !strings.Contains(err.Error(), `node needs "node"`) {
|
||||
t.Fatalf("node without a machine was accepted: %v", err)
|
||||
}
|
||||
if _, err := argvFor("upgrade", map[string]any{}); err == nil {
|
||||
t.Fatal("a verb the seat does not serve was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// A push and a build are sent, not waited for: the asker reads status for what happened.
|
||||
func TestActsDoNotBlockTheCall(t *testing.T) {
|
||||
argv, _ := argvFor("push", map[string]any{"node": "one"})
|
||||
if strings.Join(argv, " ") != "push one --wait 0" {
|
||||
t.Fatalf("push waits: %v", argv)
|
||||
}
|
||||
argv, _ = argvFor("build", map[string]any{"repository": "novox/x", "path": "modules/x"})
|
||||
if strings.Join(argv, " ") != "build novox/x --wait 0 --path modules/x" {
|
||||
t.Fatalf("build: %v", argv)
|
||||
}
|
||||
}
|
||||
|
||||
// What `tools` answers is the seats' records, with each verb's schema.
|
||||
func TestToolsAnswersTheSeatsRecords(t *testing.T) {
|
||||
handlers, err := seatToolHandlers()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(handlers) != len(catalogue.ControllerVerbs) {
|
||||
t.Fatalf("%d handlers for %d verbs", len(handlers), len(catalogue.ControllerVerbs))
|
||||
}
|
||||
answer := seatTools()
|
||||
seats, _ := answer["seats"].([]map[string]any)
|
||||
var found bool
|
||||
for _, s := range seats {
|
||||
if s["seat"] == catalogue.ControllerSeatName {
|
||||
found = true
|
||||
tools, _ := s["tools"].([]map[string]any)
|
||||
if len(tools) != len(catalogue.ControllerVerbs) || tools[0]["input"] == nil {
|
||||
t.Fatalf("the controller seat's tools are not listed in full: %v", tools)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("the mesh-controller seat is not in the listing")
|
||||
}
|
||||
}
|
||||
|
||||
// A JSON verb's answer is parsed from what the command wrote to standard output alone; a warning it
|
||||
// printed beside the document does not take the document away. The test binary stands in for the
|
||||
// controller: `-test.run` with a name that matches nothing prints `ok` and a warning about no tests.
|
||||
func TestAJSONVerbsAnswerIsItsStandardOutput(t *testing.T) {
|
||||
jsonVerbs["-test.run"] = true
|
||||
t.Cleanup(func() { delete(jsonVerbs, "-test.run") })
|
||||
answer, err := runVerb(t.Context(), []string{"-test.run", "TestAnswerEcho", "-test.v"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !answer.OK {
|
||||
t.Fatalf("the command failed: %s", answer.Output)
|
||||
}
|
||||
if !strings.Contains(answer.Output, "PASS") {
|
||||
t.Fatalf("stderr and stdout are both what the command said: %s", answer.Output)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ import (
|
||||
// make a machine look out of date for ever, or send something `plan` never showed.
|
||||
type sendable struct {
|
||||
Resources []map[string]any
|
||||
// Sequence orders this send against every other to the same node: one higher each time, taken
|
||||
// under the node's hold just before the body is made (novox/hq 04-ISSUES/107). Zero is not sent
|
||||
// at all, which a host reads as "no order claimed" — the shape of every declaration before this.
|
||||
Sequence int64
|
||||
// Adoption is nil for a converged node, and then the body is byte for byte what it was before
|
||||
// adoption existed: an older host parses the envelope strictly and would refuse the key.
|
||||
Adoption *adoptionEnvelope
|
||||
@@ -38,6 +42,15 @@ func (s sendable) Body() ([]byte, error) {
|
||||
if s.Adoption != nil {
|
||||
envelope["adoption"] = s.Adoption
|
||||
}
|
||||
if s.Sequence > 0 {
|
||||
envelope["sequence"] = s.Sequence
|
||||
}
|
||||
// An empty declaration is deliberate here — the node owns nothing the mesh put there
|
||||
// (novox/hq issue 127) — and the host refuses an empty body unless it is told the emptiness
|
||||
// is meant, so a truncated or mis-composed body is never mistaken for "own nothing".
|
||||
if len(s.Resources) == 0 {
|
||||
envelope["owns_nothing"] = true
|
||||
}
|
||||
return json.Marshal(envelope)
|
||||
}
|
||||
|
||||
|
||||
@@ -355,3 +355,25 @@ func TestTheMachineSideOfAMappingIsMovedEverywhereTheNumberIsUsed(t *testing.T)
|
||||
t.Fatalf("the consumer is told the forge answers on %v", told)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnEmptyDeclarationSaysOwnsNothing(t *testing.T) {
|
||||
// The host refuses an empty body unless told the emptiness is meant (novox/hq issue 127).
|
||||
body, err := sendable{}.Body()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var env map[string]any
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env["owns_nothing"] != true {
|
||||
t.Fatalf("an empty declaration must mark owns_nothing; got %v", env)
|
||||
}
|
||||
// A declaration with resources does not carry the marker.
|
||||
body, _ = sendable{Resources: []map[string]any{{"id": "x"}}}.Body()
|
||||
var env2 map[string]any
|
||||
_ = json.Unmarshal(body, &env2)
|
||||
if _, present := env2["owns_nothing"]; present {
|
||||
t.Fatalf("a non-empty declaration must not mark owns_nothing; got %v", env)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A declaration's only identity was the digest of its bytes; the controller already held a per-node
|
||||
// lock and recorded each send, so the order existed and was thrown away at the wire (novox/hq
|
||||
// 04-ISSUES/107).
|
||||
|
||||
func TestASendCarriesItsNumberInsideTheSignedBytes(t *testing.T) {
|
||||
body, err := sendable{Resources: []map[string]any{{"id": "x", "type": "file"}}, Sequence: 7}.Body()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var env map[string]any
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := env["sequence"].(float64); got != 7 {
|
||||
t.Fatalf("the body carries sequence %v, wanted 7", env["sequence"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnnumberedSendIsByteForByteWhatItWasBefore(t *testing.T) {
|
||||
// Zero is not sent at all. A host reads absence as "no order claimed" — the shape of every
|
||||
// declaration before this — so an older host, or the read-only comparison against a machine
|
||||
// sent nothing since sends were numbered, sees exactly the bytes it always saw.
|
||||
body, err := sendable{Resources: []map[string]any{{"id": "x", "type": "file"}}}.Body()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var env map[string]any
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, present := env["sequence"]; present {
|
||||
t.Fatalf("a send numbered zero put a sequence on the wire: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEachSendToANodeIsOneHigherAndReadable(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
record, err := open.inventory.NodeByName(t.Context(), "anchor")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Sent nothing since numbering existed: what it would be sent is composed with zero, which is
|
||||
// not on the wire, which is what it was actually sent.
|
||||
if n, err := open.inventory.Sequence(t.Context(), record.ID); err != nil || n != 0 {
|
||||
t.Fatalf("a fresh node reads sequence %d, %v", n, err)
|
||||
}
|
||||
first, err := open.inventory.NextSequence(t.Context(), record.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := open.inventory.NextSequence(t.Context(), record.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first != 1 || second != 2 {
|
||||
t.Fatalf("two sends were numbered %d and %d", first, second)
|
||||
}
|
||||
// And the read path sees the last one taken, so the comparison composes what was sent.
|
||||
if n, err := open.inventory.Sequence(t.Context(), record.ID); err != nil || n != 2 {
|
||||
t.Fatalf("after two sends the node reads sequence %d, %v", n, err)
|
||||
}
|
||||
// Another node counts on its own.
|
||||
other, err := open.inventory.NodeByName(t.Context(), "laptop")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := open.inventory.NextSequence(t.Context(), other.ID); err != nil || n != 1 {
|
||||
t.Fatalf("a second node's first send was numbered %d, %v", n, err)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,16 @@ func cloneFrom(ctx context.Context, source buildSource) (string, error) {
|
||||
// serves no scheme or port has nothing to compose from — a default port here would be the forge's
|
||||
// address guessed, which is the thing this exists to stop.
|
||||
func clonedFromSeat(world catalogue.World, seatName, repository string) (string, error) {
|
||||
base, err := seatBase(world, seatName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := strings.TrimSuffix(strings.Trim(repository, "/"), ".git")
|
||||
return fmt.Sprintf("%s/%s.git", base, path), nil
|
||||
}
|
||||
|
||||
// seatBase is `scheme://host:port` of a seat's holder as the mesh reaches it, for cloning.
|
||||
func seatBase(world catalogue.World, seatName string) (string, error) {
|
||||
seat, known := catalogue.SeatNamed(seatName)
|
||||
if !known || seat.Delivers == "" {
|
||||
return "", fmt.Errorf("%q is not a seat a repository can live on", seatName)
|
||||
@@ -94,9 +104,9 @@ func clonedFromSeat(world catalogue.World, seatName, repository string) (string,
|
||||
}
|
||||
}
|
||||
if holder == nil {
|
||||
return "", fmt.Errorf("nobody holds the %s seat, so %s cannot be cloned from this mesh's "+
|
||||
return "", fmt.Errorf("nobody holds the %s seat, so nothing can be cloned from this mesh's "+
|
||||
"forge — assign a module that claims it, or build from the repository's URL without --self",
|
||||
seat.Name, repository)
|
||||
seat.Name)
|
||||
}
|
||||
var provider *catalogue.Provider
|
||||
for i, p := range world.Offered[seat.Delivers] {
|
||||
@@ -118,8 +128,33 @@ func clonedFromSeat(world catalogue.World, seatName, repository string) (string,
|
||||
return "", fmt.Errorf("%s on %s holds the %s seat and does not serve a scheme and a port for %q",
|
||||
holder.Module, holder.Node, seat.Name, seat.Delivers)
|
||||
}
|
||||
path := strings.TrimSuffix(strings.Trim(repository, "/"), ".git")
|
||||
return fmt.Sprintf("%s://%s:%s/%s.git", scheme, provider.At, port, path), nil
|
||||
return fmt.Sprintf("%s://%s:%s", scheme, provider.At, port), nil
|
||||
}
|
||||
|
||||
// seatBases is the clone base of every seat a recipe's context may name, for a build request
|
||||
// (novox/hq ADR 0155). A seat nobody holds is left out rather than refused here: the build may not
|
||||
// name it at all, and if it does the builder refuses with the seat's name.
|
||||
func seatBases(ctx context.Context) map[string]string {
|
||||
open, err := openStores(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer open.Close()
|
||||
shelf, err := open.inventory.Catalogue(ctx)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
world, err := theRestOfTheMesh(ctx, open.inventory, shelf, "")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
bases := map[string]string{}
|
||||
for _, seatName := range []string{gitSeat} {
|
||||
if base, err := seatBase(world, seatName); err == nil {
|
||||
bases[seatName] = base
|
||||
}
|
||||
}
|
||||
return bases
|
||||
}
|
||||
|
||||
// servedPort is a served port as text, however the manifest and the node's settings carried it.
|
||||
|
||||
@@ -46,15 +46,21 @@ func statusCommand(ctx context.Context, args []string) error {
|
||||
return err
|
||||
}
|
||||
defer open.Close()
|
||||
return statusFor(ctx, open, *asJSON)
|
||||
}
|
||||
|
||||
// statusFor asks and answers, against stores somebody else opened.
|
||||
//
|
||||
// Split from the command so what it prints can be read by a test. The sentence it prints when nothing
|
||||
// is wrong has been acted on and been misleading (novox/hq 04-ISSUES/145, 125), which makes its exact
|
||||
// words the thing worth holding still.
|
||||
func statusFor(ctx context.Context, open *stores, asJSON bool) error {
|
||||
asked, err := theThreeQuestions(ctx, open)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wrong, nodes, quiet := asked.wrong, asked.nodes, asked.quiet
|
||||
behind, sources := asked.behind, asked.sources
|
||||
|
||||
if *asJSON {
|
||||
if asJSON {
|
||||
body, err := statusAsJSON(asked)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -62,6 +68,18 @@ func statusCommand(ctx context.Context, args []string) error {
|
||||
fmt.Println(string(body))
|
||||
return nil
|
||||
}
|
||||
return printStatus(asked)
|
||||
}
|
||||
|
||||
// printStatus is the words, separated from the questions.
|
||||
//
|
||||
// **Its exact sentences have been acted on and been misleading twice** — a held module reading as a
|
||||
// machine doing what it was told (novox/hq 04-ISSUES/125), and "all doing what they were told" being
|
||||
// true of a mesh in which no module could reach another (04-ISSUES/145). So they are written where a
|
||||
// test can read them without a store, a bus or a machine.
|
||||
func printStatus(asked answers) error {
|
||||
wrong, nodes, quiet := asked.wrong, asked.nodes, asked.quiet
|
||||
behind, sources := asked.behind, asked.sources
|
||||
|
||||
if len(asked.refused) > 0 {
|
||||
// First, above everything else. A machine that cannot be worked out is not running an old
|
||||
@@ -171,6 +189,65 @@ func statusCommand(ctx context.Context, args []string) error {
|
||||
fmt.Printf("\n `push --behind` sends them\n\n")
|
||||
}
|
||||
|
||||
if split := hostSplit(nodes); len(split) > 1 {
|
||||
// **Before a declaration gains a field, every machine has to understand it** (novox/hq
|
||||
// 04-ISSUES/087). A host refuses a declaration carrying a field it does not know, and refuses
|
||||
// it whole, so every new field is a flag day: hosts first, then the controller. The mesh had
|
||||
// no record of which host any machine ran, so that order was kept by somebody remembering it.
|
||||
//
|
||||
// **Disagreement, and deliberately not "behind".** A host reports its version as a commit, and
|
||||
// commits have no order — the first version of this said "N machines run an older host" and
|
||||
// named the three that were newer, because it compared two hashes as strings. What the mesh
|
||||
// can say truthfully is that the machines do not all run the same host, and which machines
|
||||
// hold which. Ordering needs a version that is ordered, and that is the host's to report.
|
||||
versions := make([]string, 0, len(split))
|
||||
for v := range split {
|
||||
versions = append(versions, v)
|
||||
}
|
||||
sort.Strings(versions)
|
||||
fmt.Printf("%d machine(s) do not all run the same host:\n", len(nodes))
|
||||
for _, v := range versions {
|
||||
sort.Strings(split[v])
|
||||
fmt.Printf(" %-12s %s\n", v, strings.Join(split[v], ", "))
|
||||
}
|
||||
fmt.Printf("\n a host refuses a declaration carrying a field it does not know, whole — so the\n" +
|
||||
" mesh may send only what every one of these understands. Which of them is newer is\n" +
|
||||
" not readable from a commit; that needs a version the host reports as ordered\n\n")
|
||||
}
|
||||
|
||||
if len(asked.untaken) > 0 {
|
||||
// **Before the adopted line, and it breaks "all well".** An adopted machine is a state
|
||||
// somebody chose and can leave alone; a module assigned to one and never taken is work
|
||||
// outstanding that reads exactly like work finished. That reading is what stopped a
|
||||
// predecessor's proxy on the strength of four green surfaces (novox/hq 04-ISSUES/125).
|
||||
machines := make([]string, 0, len(asked.untaken))
|
||||
for name := range asked.untaken {
|
||||
machines = append(machines, name)
|
||||
}
|
||||
sort.Strings(machines)
|
||||
total := 0
|
||||
for _, held := range asked.untaken {
|
||||
for _, n := range held {
|
||||
total += n
|
||||
}
|
||||
}
|
||||
fmt.Printf("%d resource(s) are held as found, because their module was assigned and never "+
|
||||
"taken — so it is running none of what it declares:\n", total)
|
||||
for _, name := range machines {
|
||||
modules := make([]string, 0, len(asked.untaken[name]))
|
||||
for m := range asked.untaken[name] {
|
||||
modules = append(modules, m)
|
||||
}
|
||||
sort.Strings(modules)
|
||||
parts := make([]string, 0, len(modules))
|
||||
for _, m := range modules {
|
||||
parts = append(parts, fmt.Sprintf("%s (%d)", m, asked.untaken[name][m]))
|
||||
}
|
||||
fmt.Printf(" %-12s %s\n", name, strings.Join(parts, ", "))
|
||||
}
|
||||
fmt.Printf("\n `take <node> <module>` compares what runs against what it declares, and runs it\n\n")
|
||||
}
|
||||
|
||||
if adopted := adoptedNodes(nodes); len(adopted) > 0 {
|
||||
// Said, because nothing forces the flip: a node left adopted is visible here rather than
|
||||
// read as converged (novox/hq ADR 0100). Not a fault, so it does not break "all well".
|
||||
@@ -178,12 +255,23 @@ func statusCommand(ctx context.Context, args []string) error {
|
||||
fmt.Printf("\n `converge <node>` previews the flip\n\n")
|
||||
}
|
||||
|
||||
if len(wrong) == 0 && len(quiet) == 0 && len(behind) == 0 && len(asked.waiting) == 0 &&
|
||||
len(asked.refused) == 0 && asked.network == "" {
|
||||
if asked.well() {
|
||||
// Said plainly. "Nothing to report" and "nothing was checked" must never look the same,
|
||||
// and getting here means every question was asked and answered.
|
||||
fmt.Printf("%d machine(s), all doing what they were told, all heard from, running what "+
|
||||
"the mesh would send them, and every module current with its source\n", len(nodes))
|
||||
// **And what that sentence does not cover**, because for eleven hours it was true of a mesh
|
||||
// in which no module could reach another (novox/hq 04-ISSUES/145). Every question above is
|
||||
// about the relationship between the mesh and a machine — applied what it was sent, matches
|
||||
// what would be sent, built from what the source has. None of them asks whether a module can
|
||||
// reach what it requires, and the mesh composes every one of those grants itself.
|
||||
//
|
||||
// Said here rather than left to be inferred. A reader who acts on the line above is acting on
|
||||
// "the machines are as the mesh described them", and the distance between that and "it works"
|
||||
// is where the eleven hours went.
|
||||
fmt.Printf("\n That is the mesh and the machines agreeing. Nothing here dials a provision:\n" +
|
||||
" no grant the mesh composed has been tested, so a module unable to reach what it\n" +
|
||||
" requires would not appear above (04-ISSUES/145)\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -247,6 +335,13 @@ func theThreeQuestions(ctx context.Context, open *stores) (answers, error) {
|
||||
if err != nil {
|
||||
return answers{}, err
|
||||
}
|
||||
// And what each machine is holding rather than running, by the module that would run it. Read
|
||||
// from what the machine itself last reported, not from what take-time computed: the machine is
|
||||
// the only thing that knows what it found (novox/hq 04-ISSUES/125).
|
||||
out.untaken, err = untakenModules(ctx, inv, out.nodes)
|
||||
if err != nil {
|
||||
return answers{}, err
|
||||
}
|
||||
|
||||
// And which machines are not running what the mesh would send them. The same question as a
|
||||
// module being behind its source, one level down: that one says the catalogue is out of date,
|
||||
@@ -281,3 +376,82 @@ func theThreeQuestions(ctx context.Context, open *stores) (answers, error) {
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// untakenModules is, per machine, each module whose resources that machine is holding as found, and
|
||||
// how many.
|
||||
//
|
||||
// **The machine's own account, not the mesh's.** An adopted node decides at apply time what it found
|
||||
// and reports it; the mesh's take-time listing is a different thing and was the one this command used
|
||||
// to have, which is why a module assigned after the listing showed nothing at all
|
||||
// (novox/hq 04-ISSUES/125).
|
||||
//
|
||||
// A machine that reports no holds contributes nothing, so a converged mesh answers an empty map and
|
||||
// the caller prints nothing.
|
||||
func untakenModules(ctx context.Context, inv *inventory.Inventory, nodes []inventory.Node) (
|
||||
map[string]map[string]int, error) {
|
||||
|
||||
out := map[string]map[string]int{}
|
||||
for _, n := range nodes {
|
||||
said, err := inv.AdoptionOf(ctx, n.Name)
|
||||
if err != nil {
|
||||
// A machine whose record cannot be read is not a machine holding nothing. Said, because
|
||||
// answering "nothing held" from a failed read is the shape this whole issue is about.
|
||||
return nil, fmt.Errorf("what %s is holding cannot be read: %w", n.Name, err)
|
||||
}
|
||||
for _, h := range said.Held {
|
||||
if h.Module == "" {
|
||||
continue // a hold the mesh cannot attribute to a module has nothing to take
|
||||
}
|
||||
if out[n.Name] == nil {
|
||||
out[n.Name] = map[string]int{}
|
||||
}
|
||||
out[n.Name][h.Module]++
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// well is whether every question this command asks came back with nothing to say.
|
||||
//
|
||||
// Named, and in one place, because it is the sentence an operator acts on and it has been wrong
|
||||
// twice. It is deliberately NOT "nothing is broken": a machine holding what it found is not broken
|
||||
// and is not doing what it was told either.
|
||||
//
|
||||
// **A hold suppresses it; being adopted does not.** Adopted is a mode somebody chose and can leave
|
||||
// alone. A module assigned to a machine and never taken is a half-finished action with nothing left
|
||||
// to finish it — it runs none of what it declares, and "all doing what they were told" was true and
|
||||
// read as success for the whole of the edge cut-over outage (novox/hq 04-ISSUES/125).
|
||||
func (a answers) well() bool {
|
||||
return len(a.wrong) == 0 && len(a.quiet) == 0 && len(a.behind) == 0 &&
|
||||
len(a.waiting) == 0 && len(a.refused) == 0 && a.network == "" && len(a.untaken) == 0
|
||||
}
|
||||
|
||||
// hostSplit is which machines report which host version, for every version more than one machine
|
||||
// could disagree about.
|
||||
//
|
||||
// **It does not say which is newer, because it cannot.** A host reports its version as a commit, and
|
||||
// commits have no order. The first version of this returned "the machines behind the newest" by
|
||||
// comparing versions as strings, and on the live mesh it named the three machines running the NEWER
|
||||
// host as the ones behind — an arbitrary lexicographic result presented as a fact
|
||||
// (novox/hq 04-ISSUES/087). A report that confidently says the opposite of the truth is worse than one
|
||||
// that says less, which is the whole subject of 04-ISSUES/145.
|
||||
//
|
||||
// So this answers what is checkable: who runs what. The reader sees the split and the mesh claims no
|
||||
// ordering. Ordering wants an ordered version, and that is the host's to report rather than this
|
||||
// function's to infer.
|
||||
//
|
||||
// Machines that have not reported a version are left out entirely: they are not a version, and
|
||||
// counting them as one would invent a disagreement. `node show` says per machine that it has not said.
|
||||
func hostSplit(nodes []inventory.Node) map[string][]string {
|
||||
out := map[string][]string{}
|
||||
for _, n := range nodes {
|
||||
if n.HostVersion == "" {
|
||||
continue
|
||||
}
|
||||
out[n.HostVersion] = append(out[n.HostVersion], n.Name)
|
||||
}
|
||||
if len(out) < 2 {
|
||||
return nil // one version, or none reported: nothing to disagree about
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/identity"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/licences"
|
||||
@@ -72,6 +73,14 @@ func migrate(ctx context.Context) error {
|
||||
}
|
||||
fmt.Printf("provided %s\n", m.Module)
|
||||
}
|
||||
// The seats the mesh ships with, into the table that now holds the set (novox/hq ADR 0122).
|
||||
// Idempotent: fills an empty table on first boot, adds a seat a release ships, and leaves an
|
||||
// operator's changes in the table as they are.
|
||||
added, err := inv.SeedSeats(ctx, catalogue.DefaultSeats())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("seeded %d seat(s)\n", added)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -85,6 +94,18 @@ func openInventory(ctx context.Context) (*inventory.Inventory, error) {
|
||||
inv.Close()
|
||||
return nil, err
|
||||
}
|
||||
// Load the seat set from the store, so the control plane reads the set as data rather than as
|
||||
// the slice it was compiled with (novox/hq ADR 0122). A store not yet seeded — or one whose
|
||||
// seat table a migration has not reached — returns nothing, and UseSeats leaves the compiled
|
||||
// defaults in force: the set is never emptied by a read that found nothing, which would refuse
|
||||
// every claim. So this can only ever replace the defaults with what the mesh actually holds.
|
||||
if seats, err := inv.Seats(ctx); err == nil {
|
||||
catalogue.UseSeats(seats)
|
||||
}
|
||||
// And the former names, so a reference to a seat's old name resolves after a rename (ADR 0122).
|
||||
if aliases, err := inv.Aliases(ctx); err == nil {
|
||||
catalogue.UseAliases(aliases)
|
||||
}
|
||||
return inv, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
)
|
||||
|
||||
// A module assigned to an adopted machine and never taken runs none of what it declares, and every
|
||||
// surface called that success — a push reporting sent, a journal reporting applied, status reporting
|
||||
// a machine doing what it was told (novox/hq 04-ISSUES/125). The holds were only ever in the
|
||||
// machine's own state file.
|
||||
|
||||
// heldOn makes a machine report that it is holding resources for a module, the way an adopted node
|
||||
// does after an apply.
|
||||
func heldOn(t *testing.T, open *stores, node, module string, ids ...string) {
|
||||
t.Helper()
|
||||
record, err := open.inventory.NodeByName(t.Context(), node)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held := make([]inventory.Held, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
held = append(held, inventory.Held{ID: id, Module: module, Kind: "container", Target: id})
|
||||
}
|
||||
if err := open.inventory.RecordAdoption(t.Context(), record.ID, held, "ufw", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusNamesAModuleHeldBecauseNothingTookIt(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
heldOn(t, open, "anchor", "route-proxy", "ca", "certs", "server")
|
||||
|
||||
asked, err := theThreeQuestions(t.Context(), open)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := asked.untaken["anchor"]["route-proxy"]; got != 3 {
|
||||
t.Fatalf("status counted %d resources held for route-proxy, wanted 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHeldModuleStopsTheMeshReadingAsWell(t *testing.T) {
|
||||
// The whole of the fault. "all doing what they were told" was true throughout the outage, and
|
||||
// true is not the same as safe to act on: the machine was doing what it was told, and what it
|
||||
// was told had not started. Asserted against the production condition, not a copy of it.
|
||||
quiet := answers{}
|
||||
if !quiet.well() {
|
||||
t.Fatal("a mesh with nothing to say does not read as well, so nothing below means anything")
|
||||
}
|
||||
holding := answers{untaken: map[string]map[string]int{"anchor": {"route-proxy": 3}}}
|
||||
if holding.well() {
|
||||
t.Fatal("a machine holding a module's resources still reads as doing what it was told, " +
|
||||
"which is the sentence that cost every public name on the machine")
|
||||
}
|
||||
// And being adopted does not suppress it: that is a mode somebody chose, not work outstanding.
|
||||
// Kept as an assertion so the difference between the two is deliberate rather than incidental.
|
||||
if !quiet.well() {
|
||||
t.Fatal("the well condition is not stable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHeldModuleIsFoundFromWhatTheMachineReported(t *testing.T) {
|
||||
// End to end through the store, so the condition above is reached by real data and not only by
|
||||
// a constructed value: the machine reports, the mesh records, status asks.
|
||||
open := aMesh(t)
|
||||
heldOn(t, open, "anchor", "route-proxy", "ca", "server")
|
||||
|
||||
asked, err := theThreeQuestions(t.Context(), open)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(asked.untaken) == 0 {
|
||||
t.Fatal("what the machine reported holding did not reach status")
|
||||
}
|
||||
if asked.well() {
|
||||
t.Fatal("a mesh whose machine reported holds reads as well")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheJSONStatusCarriesWhatIsHeldAndForWhichModule(t *testing.T) {
|
||||
open := aMesh(t)
|
||||
heldOn(t, open, "anchor", "route-proxy", "ca", "certs")
|
||||
|
||||
asked, err := theThreeQuestions(t.Context(), open)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := statusAsJSON(asked)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc struct {
|
||||
Untaken []struct {
|
||||
Node string `json:"node"`
|
||||
Module string `json:"module"`
|
||||
Held int `json:"held"`
|
||||
} `json:"untaken"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(doc.Untaken) != 1 {
|
||||
t.Fatalf("the document carries %d untaken rows, wanted 1: %s", len(doc.Untaken), body)
|
||||
}
|
||||
row := doc.Untaken[0]
|
||||
if row.Node != "anchor" || row.Module != "route-proxy" || row.Held != 2 {
|
||||
t.Fatalf("the row is %+v, wanted anchor/route-proxy/2", row)
|
||||
}
|
||||
// Absent rather than empty when nothing is held, so a well mesh's document does not carry a
|
||||
// field a reader has to interpret.
|
||||
clean, err := statusAsJSON(answers{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(clean), "untaken") {
|
||||
t.Fatalf("a mesh holding nothing still names untaken: %s", clean)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
@@ -218,3 +220,305 @@ func notNow(err error) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// SourceMoved is the forge announcing a merge: every module recorded as built from that
|
||||
// repository and branch is marked as moved to the merge commit, and built — bases first, so a
|
||||
// module that stands on another's artifact is built after it and not against the old one
|
||||
// (novox/hq 04-ISSUES/131). Nothing is pushed here: what a finished build does to the machines
|
||||
// running the module is the upgrade's decision, taken when the catalogue announces it.
|
||||
func (f following) SourceMoved(ctx context.Context, m link.SourceMoved) error {
|
||||
inv := f.open.inventory
|
||||
entries, err := inv.Catalogued(ctx)
|
||||
if err != nil {
|
||||
return notNow(err)
|
||||
}
|
||||
read, err := inv.ReadRepositories(ctx)
|
||||
if err != nil {
|
||||
return notNow(err)
|
||||
}
|
||||
|
||||
// Two kinds of module are affected by one merge, and they are affected differently.
|
||||
//
|
||||
// A module **built from** this repository and branch has moved: the mesh records the new commit
|
||||
// as what its source now has, and only what the merge actually changed is rebuilt. A module that
|
||||
// only **packages source from** it has not moved — its own source is somewhere else, at the
|
||||
// commit it already records — so it is rebuilt and its record left alone. Writing this commit as
|
||||
// its source would make it permanently behind a repository its manifest does not come from.
|
||||
var from, packaging []inventory.Entry
|
||||
already := 0
|
||||
for _, e := range entries {
|
||||
switch {
|
||||
case sourceIs(e.Source, m):
|
||||
if e.Source.BuiltFrom == m.Commit {
|
||||
already++
|
||||
continue
|
||||
}
|
||||
// **A merge older than the last look at the source is history, not a move.** The forge
|
||||
// announces what it finds merged, and an old merge surfacing late would otherwise move
|
||||
// the recorded head backwards and rebuild everything built from that repository, once
|
||||
// per old merge (2026-09-28).
|
||||
if isHistory(m.MergedAt, e.Source.Seen) {
|
||||
continue
|
||||
}
|
||||
from = append(from, e)
|
||||
case readsFrom(read[e.Manifest.Module], m):
|
||||
packaging = append(packaging, e)
|
||||
}
|
||||
}
|
||||
if len(from) == 0 && len(packaging) == 0 {
|
||||
// "Already built from it" and "nothing reads it" are different facts, and reading the first
|
||||
// as the second sends somebody looking for a broken trigger when the mesh is up to date.
|
||||
if already > 0 {
|
||||
fmt.Printf("%s/%s merged into %s (%.8s); %d module(s) the mesh holds are already built "+
|
||||
"from it\n", m.Owner, m.Repo, m.Base, m.Commit, already)
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("%s/%s merged into %s (%.8s); nothing the mesh holds reads it\n",
|
||||
m.Owner, m.Repo, m.Base, m.Commit)
|
||||
return nil
|
||||
}
|
||||
// The same judgement for the packaging kind, against the newest look at that repository by
|
||||
// anything built from it: they keep no record of it themselves, and a replayed old merge should
|
||||
// not rebuild them either.
|
||||
if isHistory(m.MergedAt, lastLookAt(entries, m)) {
|
||||
packaging = nil
|
||||
}
|
||||
touched := whatTheMergeTouched(from, entries, m)
|
||||
for _, e := range touched {
|
||||
if err := inv.SourceMoved(ctx, e.Manifest.Module, m.Commit); err != nil {
|
||||
return notNow(err)
|
||||
}
|
||||
}
|
||||
moved := append(append([]inventory.Entry{}, touched...), packaging...)
|
||||
if len(moved) == 0 {
|
||||
fmt.Printf("%s/%s merged into %s (%.8s); it changed nothing any module the mesh holds is "+
|
||||
"built from\n", m.Owner, m.Repo, m.Base, m.Commit)
|
||||
return nil
|
||||
}
|
||||
against, err := inv.BuiltAgainst(ctx)
|
||||
if err != nil {
|
||||
return notNow(err)
|
||||
}
|
||||
ordered := orderByBases(moved, against)
|
||||
names := make([]string, 0, len(ordered))
|
||||
for _, e := range ordered {
|
||||
names = append(names, e.Manifest.Module)
|
||||
}
|
||||
fmt.Printf("%s/%s merged into %s (%.8s); building %s\n",
|
||||
m.Owner, m.Repo, m.Base, m.Commit, strings.Join(names, ", "))
|
||||
if len(packaging) > 0 {
|
||||
var also []string
|
||||
for _, e := range packaging {
|
||||
also = append(also, e.Manifest.Module)
|
||||
}
|
||||
fmt.Printf(" %s package source from it, so they are rebuilt and their own source record "+
|
||||
"is left where it is\n", strings.Join(also, ", "))
|
||||
}
|
||||
var failed []string
|
||||
for _, e := range ordered {
|
||||
source := buildSource{Repository: e.Source.Repository, Seat: e.Source.Seat}
|
||||
if err := buildOne(ctx, source, e.Source.Path, e.Source.Ref, 20*time.Minute); err != nil {
|
||||
fmt.Printf(" %s: %v\n", e.Manifest.Module, err)
|
||||
failed = append(failed, e.Manifest.Module)
|
||||
// A base that failed is a reason to stop: what stands on it would be built against
|
||||
// the old one, and report success (novox/hq 04-ISSUES/131).
|
||||
if standsOn(ordered, e.Manifest.Module, against) {
|
||||
fmt.Printf(" stopping: %s is a base of what was still to build\n", e.Manifest.Module)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
fmt.Printf("%d of %d not built: %s\n", len(failed), len(ordered), strings.Join(failed, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sourceIs is whether a recorded source is the repository and branch a merge announced. A source on
|
||||
// the git seat is recorded as its path on the forge; one elsewhere as the URL it was cloned from.
|
||||
// An empty recorded ref is the repository's default branch, which is what a merge into the base
|
||||
// branch of the forge's default means.
|
||||
func sourceIs(s inventory.Source, m link.SourceMoved) bool {
|
||||
if !sameRepository(s.Repository, m) {
|
||||
return false
|
||||
}
|
||||
return s.Ref == "" || s.Ref == m.Base
|
||||
}
|
||||
|
||||
// sameRepository is whether a recorded repository is the one a merge names, in either spelling it
|
||||
// may have been recorded in: a path on the git seat, or the URL it was cloned from.
|
||||
func sameRepository(repository string, m link.SourceMoved) bool {
|
||||
want := strings.ToLower(m.Owner + "/" + m.Repo)
|
||||
repo := strings.ToLower(strings.TrimSuffix(repository, ".git"))
|
||||
return repo == want || strings.HasSuffix(repo, "/"+want) ||
|
||||
(m.CloneURL != "" && repo == strings.ToLower(strings.TrimSuffix(m.CloneURL, ".git")))
|
||||
}
|
||||
|
||||
// readsFrom is whether a module's build read the repository a merge names: the second repository its
|
||||
// recipe packages source from. Its ref must be the branch that moved, or unset — the same rule a
|
||||
// module's own source follows.
|
||||
func readsFrom(read []inventory.ReadRepository, m link.SourceMoved) bool {
|
||||
for _, r := range read {
|
||||
if sameRepository(r.Repository, m) && (r.Ref == "" || r.Ref == m.Base) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// lastLookAt is the most recent look at this repository by anything built from it.
|
||||
func lastLookAt(entries []inventory.Entry, m link.SourceMoved) time.Time {
|
||||
var newest time.Time
|
||||
for _, e := range entries {
|
||||
if sameRepository(e.Source.Repository, m) && e.Source.Seen.After(newest) {
|
||||
newest = e.Source.Seen
|
||||
}
|
||||
}
|
||||
return newest
|
||||
}
|
||||
|
||||
// whatTheMergeTouched narrows the modules built from a repository to the ones the merge changed.
|
||||
//
|
||||
// **A change inside no module's own directory is a change to what they share.** The forge lists the
|
||||
// files a merge changed; a module is affected when one of them is inside its own directory, when it
|
||||
// is built from the repository's root — everything there is its source — or when some changed file
|
||||
// belongs to no module's directory at all, which is how a shared file, a build recipe or a
|
||||
// dependency at the root rebuilds everything built from that repository.
|
||||
//
|
||||
// A change inside *another* module's directory is that module's business and not this one's, even
|
||||
// when the mesh does not hold that module: `known` is every module this repository is known to hold,
|
||||
// whatever branch it was registered from. That is also the limit of this — a repository whose shared
|
||||
// code sits inside a directory the mesh has never seen a module in reads as shared, and everything
|
||||
// is rebuilt. Rebuilding too much is the safe direction: the fault this whole path exists for is a
|
||||
// mesh that believes it is current and is not (novox/hq 04-ISSUES/131).
|
||||
func whatTheMergeTouched(candidates, known []inventory.Entry, m link.SourceMoved) []inventory.Entry {
|
||||
// Nothing said about the files, or not all of them said: everything built from it is affected.
|
||||
if len(m.Paths) == 0 || m.PathsTruncated {
|
||||
return candidates
|
||||
}
|
||||
var dirs []string
|
||||
for _, e := range known {
|
||||
if e.Source.Path != "" && sameRepository(e.Source.Repository, m) {
|
||||
dirs = append(dirs, e.Source.Path)
|
||||
}
|
||||
}
|
||||
for _, p := range m.Paths {
|
||||
if !insideAny(p, dirs) {
|
||||
return candidates
|
||||
}
|
||||
}
|
||||
var out []inventory.Entry
|
||||
for _, e := range candidates {
|
||||
if e.Source.Path == "" || anyInside(m.Paths, e.Source.Path) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// inside is whether a changed file is in a directory: that directory itself, or under it.
|
||||
func inside(path, dir string) bool {
|
||||
dir = strings.Trim(dir, "/")
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
return path == dir || strings.HasPrefix(path, dir+"/")
|
||||
}
|
||||
|
||||
// insideAny is whether a changed file is in any of these directories.
|
||||
func insideAny(path string, dirs []string) bool {
|
||||
for _, dir := range dirs {
|
||||
if inside(path, dir) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// anyInside is whether any of these changed files is in a directory.
|
||||
func anyInside(paths []string, dir string) bool {
|
||||
for _, p := range paths {
|
||||
if inside(p, dir) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// orderByBases is the entries with every base before what stands on it: a module whose build stood
|
||||
// on another's artifact comes after that module. Entries outside the set are not waited for — they
|
||||
// are not being rebuilt. Stable for what has no order between it.
|
||||
//
|
||||
// `against` is what each module's newest build stood on (inventory.BuiltAgainst): the edges are
|
||||
// derived from builds, not declared, because a recorded manifest no longer carries `build.on`.
|
||||
func orderByBases(entries []inventory.Entry, against map[string][]string) []inventory.Entry {
|
||||
inSet := map[string]bool{}
|
||||
for _, e := range entries {
|
||||
inSet[e.Manifest.Module] = true
|
||||
}
|
||||
var out []inventory.Entry
|
||||
placed := map[string]bool{}
|
||||
var place func(e inventory.Entry, seen map[string]bool)
|
||||
place = func(e inventory.Entry, seen map[string]bool) {
|
||||
name := e.Manifest.Module
|
||||
if placed[name] || seen[name] {
|
||||
return
|
||||
}
|
||||
seen[name] = true
|
||||
for _, base := range entries {
|
||||
if base.Manifest.Module != name && inSet[base.Manifest.Module] && standsOnModule(e, base.Manifest.Module, against) {
|
||||
place(base, seen)
|
||||
}
|
||||
}
|
||||
placed[name] = true
|
||||
out = append(out, e)
|
||||
}
|
||||
for _, e := range entries {
|
||||
place(e, map[string]bool{})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// standsOn is whether anything in the set is built on the named module's artifacts.
|
||||
func standsOn(entries []inventory.Entry, module string, against map[string][]string) bool {
|
||||
for _, e := range entries {
|
||||
if standsOnModule(e, module, against) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// standsOnModule is whether an entry's build stood on the named module: by what its newest build
|
||||
// recorded it was handed (`artifact-store://<module>/<artifact>@…`, the module's own artifact), or
|
||||
// — for a module registered from a manifest and not yet built — by the base its manifest names.
|
||||
func standsOnModule(e inventory.Entry, module string, against map[string][]string) bool {
|
||||
if e.Manifest.Module == module {
|
||||
return false
|
||||
}
|
||||
if e.Manifest.Build != nil {
|
||||
for _, on := range e.Manifest.Build.On {
|
||||
if on.Module == module {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
prefix := catalogue.ArtifactStoreScheme + module + "/"
|
||||
for _, ref := range against[e.Manifest.Module] {
|
||||
if strings.HasPrefix(ref, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isHistory is whether a merge made at mergedAt predates the last time the source was seen. A merge
|
||||
// with no time on it is taken as news: refusing it would silence a forge that says less.
|
||||
func isHistory(mergedAt string, seen time.Time) bool {
|
||||
if mergedAt == "" || seen.IsZero() {
|
||||
return false
|
||||
}
|
||||
at, err := time.Parse(time.RFC3339, mergedAt)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return at.Before(seen)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/inventory"
|
||||
)
|
||||
|
||||
// "4 machine(s), all doing what they were told, all heard from, running what the mesh would send
|
||||
// them, and every module current with its source" was true for eleven hours of a mesh in which no
|
||||
// module could reach another (novox/hq 04-ISSUES/145). Every question it answers is about the mesh
|
||||
// and a machine agreeing; none of them dials anything.
|
||||
|
||||
// printed captures what a function writes to stdout.
|
||||
func printed(t *testing.T, f func() error) string {
|
||||
t.Helper()
|
||||
old := os.Stdout
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Stdout = w
|
||||
runErr := f()
|
||||
_ = w.Close()
|
||||
os.Stdout = old
|
||||
var buf bytes.Buffer
|
||||
if _, err := io.Copy(&buf, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if runErr != nil {
|
||||
t.Fatal(runErr)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestTheAllWellSentenceSaysWhatItDoesNotCover(t *testing.T) {
|
||||
// A mesh with nothing to say. The sentence below was true of a mesh in which no module could
|
||||
// reach another, for eleven hours.
|
||||
got := printed(t, func() error {
|
||||
return printStatus(answers{nodes: []inventory.Node{{Name: "anchor"}, {Name: "laptop"}}})
|
||||
})
|
||||
if !strings.Contains(got, "all doing what they were told") {
|
||||
t.Fatalf("a mesh with nothing to say did not print the all-well sentence:\n%s", got)
|
||||
}
|
||||
// And now says what it is not a claim about.
|
||||
for _, want := range []string{"Nothing here dials a provision", "04-ISSUES/145"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("the all-well sentence does not say %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMeshWithSomethingToSayDoesNotPrintTheScopeLine(t *testing.T) {
|
||||
// The scope belongs to the all-well sentence. A mesh with something wrong has specific things to
|
||||
// read, and appending a caveat to those is noise.
|
||||
got := printed(t, func() error {
|
||||
return printStatus(answers{
|
||||
nodes: []inventory.Node{{Name: "anchor"}},
|
||||
untaken: map[string]map[string]int{"anchor": {"route-proxy": 3}},
|
||||
})
|
||||
})
|
||||
if strings.Contains(got, "Nothing here dials a provision") {
|
||||
t.Fatalf("a mesh with a held module printed the all-well scope line:\n%s", got)
|
||||
}
|
||||
if strings.Contains(got, "all doing what they were told") {
|
||||
t.Fatalf("a mesh with a held module printed the all-well sentence:\n%s", got)
|
||||
}
|
||||
if !strings.Contains(got, "route-proxy") {
|
||||
t.Fatalf("the held module is not named:\n%s", got)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,22 @@
|
||||
module github.com/novox/mesh-controller
|
||||
|
||||
go 1.25.0
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/rabbitmq/amqp091-go v1.14.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
github.com/nats-io/nats.go v1.54.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.16 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
|
||||
@@ -9,27 +9,31 @@ github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
|
||||
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Do the emitters and the consumers of a catalogue agree?
|
||||
//
|
||||
// **The check that was missing** (novox/hq 04-ISSUES/127). Every manifest was individually
|
||||
// well-formed and every derivation individually correct, and no cross-module subscription in the
|
||||
// mesh matched anything: a consumer's declaration derived into a namespace nobody publishes to.
|
||||
// Nothing failed, because a subscription that matches nothing is not an error — it is silence.
|
||||
//
|
||||
// The comparison has to be over the whole catalogue, because the two halves live in different
|
||||
// manifests, and it cannot simply demand that every consumed event have a live emitter: a module
|
||||
// may be installed long before the one whose events it wants. So the rule is narrower and still
|
||||
// catches this: **where the emitter is present, it must emit what the consumer asked for.**
|
||||
|
||||
// AConsumer is one module's interest in another's events, as this check needs it.
|
||||
type AConsumer struct {
|
||||
Module string
|
||||
Consumes []string
|
||||
}
|
||||
|
||||
// AnEmitter is one module's events.
|
||||
type AnEmitter struct {
|
||||
Module string
|
||||
Emits []string
|
||||
}
|
||||
|
||||
// Disagreements are the consumed events whose emitter is in the catalogue and does not emit them.
|
||||
//
|
||||
// Returned as sentences rather than as structs: every one of them is read by a person deciding
|
||||
// whether a manifest or a catalogue is wrong, and a pair of names without the reason is a puzzle.
|
||||
func Disagreements(emitters []AnEmitter, consumers []AConsumer, seats []DeclaredSeat) []string {
|
||||
emits := map[string]map[string]bool{}
|
||||
for _, e := range emitters {
|
||||
if emits[e.Module] == nil {
|
||||
emits[e.Module] = map[string]bool{}
|
||||
}
|
||||
for _, name := range e.Emits {
|
||||
emits[e.Module][name] = true
|
||||
}
|
||||
}
|
||||
// A seat's events are published by its holder under the seat's name, so a consumer naming the
|
||||
// seat is naming something real even though no module declares it as its own.
|
||||
for _, s := range seats {
|
||||
if len(s.Emits) == 0 {
|
||||
continue
|
||||
}
|
||||
if emits[s.Name] == nil {
|
||||
emits[s.Name] = map[string]bool{}
|
||||
}
|
||||
for _, name := range s.Emits {
|
||||
emits[s.Name][name] = true
|
||||
}
|
||||
}
|
||||
|
||||
var out []string
|
||||
for _, c := range consumers {
|
||||
for _, pattern := range c.Consumes {
|
||||
emitter, event, named := strings.Cut(pattern, ".")
|
||||
// Every event from everyone, or every event from one module: both are deliberate and
|
||||
// neither names a particular event to check.
|
||||
if !named || emitter == "*" || emitter == catalogueTheRest || event == catalogueTheRest {
|
||||
continue
|
||||
}
|
||||
known, present := emits[emitter]
|
||||
if !present {
|
||||
// Not installed here, which is ordinary: a module lives in its own repository and
|
||||
// may be registered later. Nothing to compare, so nothing to say.
|
||||
continue
|
||||
}
|
||||
if matchesAny(event, known) {
|
||||
continue
|
||||
}
|
||||
out = append(out, fmt.Sprintf(
|
||||
"%s consumes %q and %s emits %s — so that subscription would match nothing, and "+
|
||||
"nothing would report it",
|
||||
c.Module, pattern, emitter, listOf(known)))
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// matchesAny says whether one of an emitter's event names satisfies a consumer's pattern.
|
||||
func matchesAny(pattern string, emitted map[string]bool) bool {
|
||||
want := strings.Split(pattern, ".")
|
||||
for name := range emitted {
|
||||
if matches(want, strings.Split(name, ".")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func matches(pattern, name []string) bool {
|
||||
for i, part := range pattern {
|
||||
if part == catalogueTheRest {
|
||||
return i < len(name)
|
||||
}
|
||||
if i >= len(name) {
|
||||
return false
|
||||
}
|
||||
if part != "*" && part != name[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(pattern) == len(name)
|
||||
}
|
||||
|
||||
func listOf(names map[string]bool) string {
|
||||
if len(names) == 0 {
|
||||
return "nothing"
|
||||
}
|
||||
out := make([]string, 0, len(names))
|
||||
for n := range names {
|
||||
out = append(out, n)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// **Do the catalogue's emitters and consumers agree?**
|
||||
//
|
||||
// This is the check whose absence let issue 127 stand: every manifest was individually well-formed,
|
||||
// every derivation individually correct, and no cross-module subscription in the mesh matched
|
||||
// anything. A subscription that matches nothing is not an error — it is silence — so nothing
|
||||
// anywhere reported it.
|
||||
//
|
||||
// It compares what one manifest asks to hear against what another says it emits. It cannot demand
|
||||
// that every consumed event have a live emitter, because a module lives in its own repository and
|
||||
// may be registered long before the one whose events it wants. Where the emitter *is* here, it must
|
||||
// emit what the consumer asked for.
|
||||
func TestTheCataloguesEmittersAndConsumersAgree(t *testing.T) {
|
||||
emitters, consumers, seats := theCataloguesEvents(t)
|
||||
|
||||
if bad := Disagreements(emitters, consumers, seats); len(bad) > 0 {
|
||||
t.Fatalf("%d subscription(s) in the catalogue would match nothing:\n %s",
|
||||
len(bad), strings.Join(bad, "\n "))
|
||||
}
|
||||
}
|
||||
|
||||
// And the check itself catches the thing it exists for, so it cannot pass by doing nothing.
|
||||
func TestTheAgreementCheckCatchesASubscriptionThatMatchesNothing(t *testing.T) {
|
||||
bad := Disagreements(
|
||||
[]AnEmitter{{Module: "builder", Emits: []string{"built"}}},
|
||||
[]AConsumer{{Module: "mesh-catalog", Consumes: []string{"builder.finished"}}},
|
||||
nil)
|
||||
if len(bad) != 1 {
|
||||
t.Fatalf("a consumer asking for an event its emitter does not emit was not caught: %v", bad)
|
||||
}
|
||||
if !strings.Contains(bad[0], "builder.finished") || !strings.Contains(bad[0], "built") {
|
||||
t.Fatalf("the report names neither what was asked for nor what is emitted: %s", bad[0])
|
||||
}
|
||||
|
||||
// A module that is not here is not a disagreement: it may be registered later.
|
||||
if bad := Disagreements(nil,
|
||||
[]AConsumer{{Module: "plex", Consumes: []string{"sonarr.download.completed"}}}, nil); len(bad) != 0 {
|
||||
t.Fatalf("a consumer whose emitter is not installed was reported: %v", bad)
|
||||
}
|
||||
|
||||
// A wildcard over emitters is deliberate and names no particular event to check.
|
||||
if bad := Disagreements([]AnEmitter{{Module: "sonarr", Emits: []string{"download.completed"}}},
|
||||
[]AConsumer{{Module: "plex", Consumes: []string{"*.download.completed"}}}, nil); len(bad) != 0 {
|
||||
t.Fatalf("a wildcard over emitters was reported: %v", bad)
|
||||
}
|
||||
|
||||
// A consumer of a role's event whose role does not emit it is caught, which is what stops the
|
||||
// catalogue check above from passing by knowing nothing about roles.
|
||||
if bad := Disagreements(nil,
|
||||
[]AConsumer{{Module: "mesh-catalog", Consumes: []string{"mesh-build-machine.finished"}}},
|
||||
[]DeclaredSeat{{Name: "mesh-build-machine", Emits: []string{"built"}}}); len(bad) != 1 {
|
||||
t.Fatalf("a consumer of a role event the role does not emit was not caught: %v", bad)
|
||||
}
|
||||
|
||||
// An event published under a seat's name is real even though no module declares it as its own.
|
||||
if bad := Disagreements(nil,
|
||||
[]AConsumer{{Module: "watcher", Consumes: []string{"mesh-artifact-store.image.pushed"}}},
|
||||
[]DeclaredSeat{{Name: "mesh-artifact-store", Emits: []string{"image.pushed"}}}); len(bad) != 0 {
|
||||
t.Fatalf("an event a seat emits was reported as matching nothing: %v", bad)
|
||||
}
|
||||
}
|
||||
|
||||
func theCataloguesEvents(t *testing.T) ([]AnEmitter, []AConsumer, []DeclaredSeat) {
|
||||
t.Helper()
|
||||
root := filepath.Join("..", "..", "..", "mesh-catalog", "modules")
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
t.Skipf("catalogue sibling not present: %v", err)
|
||||
}
|
||||
var emitters []AnEmitter
|
||||
var consumers []AConsumer
|
||||
// The mesh's own roles, which emit under the seat's name rather than any module's (novox/hq
|
||||
// ADR 0121). Without these the check skips every consumer of a role's event as "the emitter is
|
||||
// not installed" — which is how it passed vacuously the first time one existed.
|
||||
var seats []DeclaredSeat
|
||||
for _, own := range catalogue.SeatsWithAProtocol() {
|
||||
seats = append(seats, DeclaredSeat{Name: own.Name, Accepts: own.Accepts, Emits: own.Emits})
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(root, e.Name(), "module.json"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var m struct {
|
||||
Module string `json:"module"`
|
||||
Emits []string `json:"emits"`
|
||||
Consumes []string `json:"consumes"`
|
||||
Seats []struct {
|
||||
Name string `json:"name"`
|
||||
Emits []string `json:"emits"`
|
||||
} `json:"seats"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatalf("%s: %v", e.Name(), err)
|
||||
}
|
||||
if len(m.Emits) > 0 {
|
||||
emitters = append(emitters, AnEmitter{Module: m.Module, Emits: m.Emits})
|
||||
}
|
||||
if len(m.Consumes) > 0 {
|
||||
consumers = append(consumers, AConsumer{Module: m.Module, Consumes: m.Consumes})
|
||||
}
|
||||
for _, s := range m.Seats {
|
||||
seats = append(seats, DeclaredSeat{Name: s.Name, Emits: s.Emits})
|
||||
}
|
||||
}
|
||||
if len(emitters) == 0 {
|
||||
t.Skip("no manifests found beside this checkout")
|
||||
}
|
||||
return emitters, consumers, seats
|
||||
}
|
||||
|
||||
// **Do the derived subjects meet, not just the names?**
|
||||
//
|
||||
// The check above compares what a consumer asks for against what an emitter says it emits, by name. It
|
||||
// passed while the catalogue's subscription pointed at `mesh.mod.mesh-build-machine.event.built` — a
|
||||
// module namespace for a role's event, which no emitter owns. The names agreed; the subjects did not,
|
||||
// and the graph stayed empty.
|
||||
//
|
||||
// So this compares the thing that actually has to match: the subject a consumer subscribes against the
|
||||
// subject an emitter publishes. It is the last place the two halves can be held together, because
|
||||
// after this the server is the only thing that knows and it says nothing — a subscription that matches
|
||||
// nothing is silence.
|
||||
func TestTheCataloguesDerivedSubjectsMeet(t *testing.T) {
|
||||
emitters, consumers, seats := theCataloguesEvents(t)
|
||||
|
||||
// Every subject something publishes: a module's own events, and the events of every role.
|
||||
published := map[string]bool{}
|
||||
for _, e := range emitters {
|
||||
for _, name := range e.Emits {
|
||||
published["mesh.mod."+e.Module+".event."+name] = true
|
||||
}
|
||||
}
|
||||
for _, s := range seats {
|
||||
for _, name := range s.Emits {
|
||||
published["mesh.seat."+s.Name+".event."+name] = true
|
||||
}
|
||||
}
|
||||
|
||||
byName := map[string]DeclaredSeat{}
|
||||
for _, s := range seats {
|
||||
byName[s.Name] = s
|
||||
}
|
||||
|
||||
var lonely []string
|
||||
for _, c := range consumers {
|
||||
principal := Principal{Kind: KindModule, Node: "one", Module: c.Module, PasswordHash: "x"}
|
||||
for _, want := range c.Consumes {
|
||||
emitter, event, named := strings.Cut(want, ".")
|
||||
if named {
|
||||
if s, isASeat := byName[emitter]; isASeat {
|
||||
principal.Watches = append(principal.Watches,
|
||||
Seat{Name: s.Name, Emits: []string{event}})
|
||||
continue
|
||||
}
|
||||
}
|
||||
principal.Consumes = append(principal.Consumes, want)
|
||||
}
|
||||
perms, err := PermissionsFor(principal)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", c.Module, err)
|
||||
}
|
||||
for _, subject := range perms.Subscribe {
|
||||
if !strings.Contains(subject, ".event.") {
|
||||
continue
|
||||
}
|
||||
if reaches(subject, published) {
|
||||
continue
|
||||
}
|
||||
// A wildcard over emitters reaches whatever arrives later, and an emitter that is not
|
||||
// installed is ordinary — both are already excused by the check above, so only a subject
|
||||
// that can never match anything gets here.
|
||||
if strings.Contains(subject, "*") || strings.Contains(subject, ">") {
|
||||
continue
|
||||
}
|
||||
lonely = append(lonely, c.Module+" subscribes "+subject+", which nothing publishes")
|
||||
}
|
||||
}
|
||||
if len(lonely) > 0 {
|
||||
sort.Strings(lonely)
|
||||
t.Fatalf("%d subscription(s) derive to a subject no emitter owns:\n %s",
|
||||
len(lonely), strings.Join(lonely, "\n "))
|
||||
}
|
||||
}
|
||||
|
||||
// And it catches the thing it exists for: a role's event read as a module's.
|
||||
func TestTheDerivedSubjectCheckCatchesARolesEventReadAsAModules(t *testing.T) {
|
||||
published := map[string]bool{"mesh.seat.mesh-build-machine.event.built": true}
|
||||
// What the derivation produced before a consumed seat name was resolved as one.
|
||||
if reaches("mesh.mod.mesh-build-machine.event.built", published) {
|
||||
t.Fatal("a module namespace was treated as reaching a role's event, which is the bug")
|
||||
}
|
||||
// And the corrected one does reach it.
|
||||
if !reaches("mesh.seat.mesh-build-machine.event.built", published) {
|
||||
t.Fatal("the role's own subject does not reach the role's event")
|
||||
}
|
||||
}
|
||||
|
||||
// reaches says whether a subscribed subject admits any published one.
|
||||
func reaches(subject string, published map[string]bool) bool {
|
||||
for p := range published {
|
||||
if admitsSubject(strings.Split(subject, "."), strings.Split(p, ".")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func admitsSubject(pattern, subject []string) bool {
|
||||
for i, token := range pattern {
|
||||
if token == ">" {
|
||||
return i < len(subject)
|
||||
}
|
||||
if i >= len(subject) {
|
||||
return false
|
||||
}
|
||||
if token != "*" && token != subject[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(pattern) == len(subject)
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package broker_test
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
|
||||
// The names are written twice, so a test keeps them agreeing.
|
||||
//
|
||||
// `link` imports `broker`, so `broker` cannot import `link` — the queue and exchange names
|
||||
// therefore exist in both. A scoped account naming a queue nothing publishes to produces a
|
||||
// builder that takes no work and says nothing about why, which is the worst kind of silence.
|
||||
//
|
||||
// An external test package, because it may import both without either importing the other.
|
||||
func TestTheNamesTheBrokerScopesAreTheNamesTheLinkUses(t *testing.T) {
|
||||
for _, agreed := range []struct {
|
||||
what string
|
||||
scoped string
|
||||
actually string
|
||||
}{
|
||||
{"the build queue", broker.BuildQueueName, link.BuildQueue},
|
||||
{"the exchange", broker.ExchangeName, link.Exchange},
|
||||
{"a node's queue", broker.QueueFor("somewhere"), link.QueueFor("somewhere")},
|
||||
} {
|
||||
if agreed.scoped != agreed.actually {
|
||||
t.Errorf("%s: the broker scopes %q and the link uses %q",
|
||||
agreed.what, agreed.scoped, agreed.actually)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestABuilderMayWriteToAReplyQueueAndReadNoNodesDeclarations(t *testing.T) {
|
||||
// The scoping, checked as patterns rather than by connecting: what it may write must include
|
||||
// the queue an asker actually waits on, and what it may read must not include any node's.
|
||||
//
|
||||
// This exists because the first version scoped writes to `amq.gen-*` — the name one broker
|
||||
// happens to generate — and the builder built, could not answer, and the connection simply
|
||||
// closed saying only "not allowed to publish to exchange \'\'". Answering through the
|
||||
// exchange is what removed the need for any of that.
|
||||
write := regexp.MustCompile("^" + regexp.QuoteMeta(broker.ExchangeName) + "$")
|
||||
if !write.MatchString(broker.ExchangeName) {
|
||||
t.Error("a builder may not write to the exchange, so it can take work and never answer")
|
||||
}
|
||||
// And not the default exchange, where permission is per exchange rather than per queue — a
|
||||
// builder allowed to use it could publish into any node's queue.
|
||||
//
|
||||
// Confirmed against a real broker as well, and worth recording how that nearly went wrong:
|
||||
// an unconfirmed publish is asynchronous, so a refusal arrives as a channel close afterwards
|
||||
// and a naive check reports success. With publisher confirms the broker's refusal is
|
||||
// immediate. **A negative security assertion made against an asynchronous call is not an
|
||||
// assertion.**
|
||||
if write.MatchString("") {
|
||||
t.Error("a builder may publish to the default exchange, and so into any node's queue")
|
||||
}
|
||||
|
||||
read := regexp.MustCompile("^" + regexp.QuoteMeta(broker.BuildQueueName) + "$")
|
||||
if !read.MatchString(broker.BuildQueueName) {
|
||||
t.Error("a builder may not read the build queue")
|
||||
}
|
||||
if read.MatchString(link.QueueFor("someone-else")) {
|
||||
// A build machine is not a node, and a node's queue carries its declarations.
|
||||
t.Error("a builder may read another machine's declarations")
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,19 @@ func FromEnvironment() (Broker, error) {
|
||||
if err != nil {
|
||||
return Broker{}, err
|
||||
}
|
||||
// **One bus, one address** (novox/hq ADR 0131). Everything the mesh hands out — a token, a
|
||||
// machine's membership, a person's credential — must name the bus the control plane itself is
|
||||
// connected to; the setting above predates the move and, on a mesh that has moved, still names
|
||||
// the broker it moved from. The first person issued after the move was handed the retired
|
||||
// broker's port and could not connect to anything (2026-09-28).
|
||||
//
|
||||
// Read from the credential rather than from a second setting somebody keeps in step: the
|
||||
// control plane cannot be wrong about where it is connected.
|
||||
if bus, on, err := OnNATS(); err == nil && on {
|
||||
if where := strings.TrimPrefix(BareAddress(bus), "nats://"); where != "" {
|
||||
address = where
|
||||
}
|
||||
}
|
||||
return Broker{Address: address, Fingerprint: fingerprint}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -194,16 +194,3 @@ func TestTheAddressPortFollowsThePortTwin(t *testing.T) {
|
||||
t.Fatalf("the address is %q; the node put the bus on 5679", b.Address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheManagementPortFollowsThePortTwin(t *testing.T) {
|
||||
t.Setenv(ManagementVar, "http://guest:guest@127.0.0.1:15672")
|
||||
t.Setenv(ManagementVar+"_FILE", "")
|
||||
t.Setenv(ManagementVar+"_PORT", "15673")
|
||||
m, err := ManagementFromEnvironment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.base.Host != "127.0.0.1:15673" {
|
||||
t.Fatalf("the management API is at %q; the node put it on 15673", m.base.Host)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
const twoSeconds = 2 * time.Second
|
||||
|
||||
// A running mesh already holds consumers made before the delivery subject carried the stream
|
||||
// (novox/hq 04-ISSUES/146). The server will not change a push consumer's delivery subject in place,
|
||||
// so bringing one to match must replace it — and must not replay what it already acknowledged
|
||||
// (novox/hq 04-ISSUES/156).
|
||||
//
|
||||
// docker run -d --rm --name t -p 14231:4222 nats:2.10-alpine -js
|
||||
// MESH_TEST_NATS=nats://127.0.0.1:14231 go test ./internal/broker/ -run TestUpgrading
|
||||
func TestUpgradingAConsumerWhoseDeliverySubjectMoved(t *testing.T) {
|
||||
url := os.Getenv("MESH_TEST_NATS")
|
||||
if url == "" {
|
||||
t.Skip("MESH_TEST_NATS unset")
|
||||
}
|
||||
js, err := Dial(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer js.Close()
|
||||
|
||||
// The stream exactly as the mesh's own is — one declaration per node, always the newest.
|
||||
// Reproduced rather than approximated: the first version of this test used a plain stream and
|
||||
// a plain consumer, and the server accepted the update it refuses in a running mesh, so the
|
||||
// test passed against the very code that was crash-looping on the control node.
|
||||
const stream, name = "NODES", "novox"
|
||||
subject := "mesh.node." + name + ".declare"
|
||||
_ = js.js.DeleteStream(stream)
|
||||
if _, err := js.js.AddStream(&nats.StreamConfig{
|
||||
Name: stream, Subjects: []string{"mesh.node.*.declare"},
|
||||
MaxMsgsPerSubject: 1, Storage: nats.MemoryStorage,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = js.js.DeleteStream(stream) }()
|
||||
|
||||
for i := 0; i < 6; i++ {
|
||||
if _, err := js.js.Publish(subject, []byte(fmt.Sprint(i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The consumer as a running mesh holds it: made before the subject carried the stream, and
|
||||
// otherwise exactly what NodeConsumer asks for.
|
||||
if _, err := js.js.AddConsumer(stream, &nats.ConsumerConfig{
|
||||
Durable: name, AckPolicy: nats.AckExplicitPolicy,
|
||||
AckWait: 300 * time.Second, MaxDeliver: -1,
|
||||
FilterSubject: subject,
|
||||
DeliverSubject: "_DELIVER." + name,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// It acknowledged the first four. Those must not come back.
|
||||
sub, err := js.js.SubscribeSync(subject, nats.Bind(stream, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 1; i++ {
|
||||
m, err := sub.NextMsg(twoSeconds)
|
||||
if err != nil {
|
||||
t.Fatalf("message %d never arrived: %v", i, err)
|
||||
}
|
||||
if err := m.AckSync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// **The subscription stays up.** In a running mesh the machine is attached to this consumer
|
||||
// the whole time — that is what a node listening for its declaration IS. The first version of
|
||||
// this test unsubscribed first, and the server then accepted an update it refuses while a
|
||||
// subscriber is bound, so the test passed against the code that was crash-looping.
|
||||
defer func() { _ = sub.Unsubscribe() }()
|
||||
|
||||
// Now the upgrade: the consumer the controller asserts on every start, with the subject that
|
||||
// carries the stream.
|
||||
want := NodeConsumer(name)
|
||||
var notes []string
|
||||
js.Note = func(f string, a ...any) { notes = append(notes, fmt.Sprintf(f, a...)) }
|
||||
|
||||
if err := js.EnsureConsumer(want); err != nil {
|
||||
t.Fatalf("a consumer the mesh already held could not be brought to match, which is the "+
|
||||
"control plane failing to start: %v", err)
|
||||
}
|
||||
|
||||
info, err := js.js.ConsumerInfo(stream, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// It KEEPS the subject it had. Moving it would need the holder's grant to have widened first,
|
||||
// and that grant travels in the bus's user list, which a machine applies minutes later.
|
||||
if got := info.Config.DeliverSubject; got != "_DELIVER."+name {
|
||||
t.Fatalf("the consumer a machine is bound to was moved to %q; a machine not yet allowed "+
|
||||
"to subscribe there is a machine that hears nothing", got)
|
||||
}
|
||||
if len(notes) != 1 {
|
||||
t.Fatalf("keeping it was not reported, so it would be invisible: %v", notes)
|
||||
}
|
||||
if !strings.Contains(notes[0], "keeps working") {
|
||||
t.Fatalf("the note does not say the consumer still works: %q", notes[0])
|
||||
}
|
||||
|
||||
// And the machine bound to it is still being delivered to — the point of keeping it.
|
||||
if _, err := js.js.Publish(subject, []byte("after the assertion")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, err := sub.NextMsg(twoSeconds)
|
||||
if err != nil {
|
||||
t.Fatalf("the machine stopped hearing its declarations after the assertion: %v", err)
|
||||
}
|
||||
if string(m.Data) != "after the assertion" {
|
||||
t.Fatalf("delivered %q", m.Data)
|
||||
}
|
||||
|
||||
// Asserting again is a no-op, or the controller crash-loops on its own restart.
|
||||
if err := js.EnsureConsumer(want); err != nil {
|
||||
t.Fatalf("the second assertion failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// And where nothing is bound, the subject DOES move — that is 04-ISSUES/146's fix, which this must
|
||||
// not undo. The controller's own two consumers are in exactly this position: it asserts them before
|
||||
// it subscribes.
|
||||
func TestAConsumerNothingIsBoundToDoesMove(t *testing.T) {
|
||||
url := os.Getenv("MESH_TEST_NATS")
|
||||
if url == "" {
|
||||
t.Skip("MESH_TEST_NATS unset")
|
||||
}
|
||||
js, err := Dial(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer js.Close()
|
||||
|
||||
const stream, name = "NODES", "shanks"
|
||||
subject := "mesh.node." + name + ".declare"
|
||||
_ = js.js.DeleteStream(stream)
|
||||
if _, err := js.js.AddStream(&nats.StreamConfig{
|
||||
Name: stream, Subjects: []string{"mesh.node.*.declare"},
|
||||
MaxMsgsPerSubject: 1, Storage: nats.MemoryStorage,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = js.js.DeleteStream(stream) }()
|
||||
|
||||
if _, err := js.js.AddConsumer(stream, &nats.ConsumerConfig{
|
||||
Durable: name, AckPolicy: nats.AckExplicitPolicy,
|
||||
AckWait: 300 * time.Second, MaxDeliver: -1,
|
||||
FilterSubject: subject,
|
||||
DeliverSubject: "_DELIVER." + name,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := NodeConsumer(name)
|
||||
if err := js.EnsureConsumer(want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := js.js.ConsumerInfo(stream, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := info.Config.DeliverSubject; got != DeliverSubjectFor(want) {
|
||||
t.Fatalf("delivery subject is %q, wanted %q -- issue 146's fix no longer applies to a "+
|
||||
"consumer nothing is holding", got, DeliverSubjectFor(want))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Streams and consumers derived from what modules declare.
|
||||
//
|
||||
// The mesh's own four exist before any module does (streams.go). Everything here is the other
|
||||
// half: a seat's stream comes into being when the module declaring it is **registered**, and a
|
||||
// consumer when a module is **assigned** — which is why ADR 0116's task 1.4 had to be narrowed to
|
||||
// the foundation set. Neither has happened at genesis.
|
||||
//
|
||||
// All of it is a pure function of declarations. The controller is still the only writer; this is
|
||||
// only what it writes.
|
||||
|
||||
// A Consumer is a durable subscription the controller creates on a module's behalf. A module
|
||||
// declares what it reacts to, never how delivery works, so it does not name these and cannot
|
||||
// misconfigure them.
|
||||
type Consumer struct {
|
||||
Name string
|
||||
Stream string
|
||||
// Filters are the subjects this consumer receives. One consumer per module with several
|
||||
// filters, rather than one per consumed event: its ack subject is derived from its name, and
|
||||
// a module with five consumers would need five ack permissions to ack its own deliveries.
|
||||
Filters []string
|
||||
// Queue is the queue group, set for a seat's worker so that "exactly one holder" survives a
|
||||
// seat later being relaxed to several. Authority and delivery are kept separate on purpose.
|
||||
Queue string
|
||||
// Push asks the server to deliver to a subject rather than wait to be pulled.
|
||||
//
|
||||
// For the mesh's own consumer, where the controller wants every message to arrive in the one
|
||||
// loop it already runs: pulling would mean a second goroutine fetching batches and handing
|
||||
// them over, and a loop that acts on one message at a time is the property the store window
|
||||
// depends on. A queue group implies this, because a group has nothing to pull from.
|
||||
Push bool
|
||||
// AckWaitSeconds before an unacknowledged delivery is redelivered.
|
||||
AckWaitSeconds int
|
||||
// MaxDeliver before the message is dead-lettered; zero for the mesh's default.
|
||||
MaxDeliver int
|
||||
// MaxAckPending is how many deliveries the server lets stand unacknowledged at once; zero for
|
||||
// the server's default, which is many. **One, for a consumer handled one at a time**
|
||||
// (novox/hq issue 175): a handler that builds for minutes keeps its own message alive with a
|
||||
// heartbeat, but everything handed over behind it times out unacknowledged and comes back —
|
||||
// and a merge that came back rebuilt what it had just built, five times over on 2026-09-30.
|
||||
// With one outstanding, the server holds the rest, and the heartbeat is keeping the message.
|
||||
MaxAckPending int
|
||||
Why string
|
||||
}
|
||||
|
||||
// seatStreamName is the stream holding a seat's inbound work. Named after the seat rather than
|
||||
// the module holding it, because the holder can change and the queued work must not care — which
|
||||
// is the whole reason a caller addresses a seat instead of a module.
|
||||
func seatStreamName(seat string) string { return "SEAT_" + upperSnake(seat) }
|
||||
|
||||
// SeatStreams is one work queue per declared seat, created when the declaring module is
|
||||
// registered rather than when it is assigned.
|
||||
//
|
||||
// **The stream exists before anyone holds the seat, and that is the point.** Work queues until a
|
||||
// holder appears, so installing the telegram module a week after something started sending to it
|
||||
// flushes the backlog instead of having lost it. A stream created at assignment would make "the
|
||||
// holder is not here yet" mean "your messages are gone".
|
||||
func SeatStreams(seats []DeclaredSeat) []Stream {
|
||||
sorted := append([]DeclaredSeat(nil), seats...)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name })
|
||||
|
||||
var out []Stream
|
||||
for _, s := range sorted {
|
||||
if len(s.Accepts) == 0 {
|
||||
// A seat that only emits and serves needs no stream: its events ride EVENTS and its
|
||||
// tools are core request/reply, which is never persisted.
|
||||
continue
|
||||
}
|
||||
retain := s.RetainSeconds
|
||||
if retain == 0 {
|
||||
retain = 7 * 24 * 60 * 60
|
||||
}
|
||||
out = append(out, Stream{
|
||||
Name: seatStreamName(s.Name),
|
||||
Subjects: []string{"mesh.seat." + s.Name + ".accept.>"},
|
||||
Retention: RetentionWorkQueue,
|
||||
MaxAge: retain,
|
||||
Why: fmt.Sprintf("work submitted to the %s seat; one holder consumes it, and it "+
|
||||
"queues while nobody does", s.Name),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A DeclaredSeat is a seat as the catalogue knows it. Mirrored here rather than imported so this
|
||||
// package stays free of the catalogue's own types — the same reason the host mirrors the
|
||||
// contracts instead of importing the sdk.
|
||||
type DeclaredSeat struct {
|
||||
Name string
|
||||
Accepts []string
|
||||
// Emits are the verbs the seat's holder publishes under the seat's own name. An event about a
|
||||
// role belongs here rather than in the holder's namespace, because the name then outlives
|
||||
// whoever fills it (novox/hq ADR 0121, 04-ISSUES/127).
|
||||
Emits []string
|
||||
// Serves are the verbs the holder answers, request and reply.
|
||||
Serves []string
|
||||
RetainSeconds int
|
||||
}
|
||||
|
||||
// ConsumerFor is the durable consumer a module's declarations imply, or false when it subscribes
|
||||
// to nothing and needs none.
|
||||
//
|
||||
// One per module, with every consumed subject as a filter, because its ack permission is derived
|
||||
// from its name: a module with a consumer per event would need an ack permission per consumer,
|
||||
// and the permission list would stop being derivable from the declaration.
|
||||
func ConsumerFor(p Principal) (Consumer, bool) {
|
||||
// A module that reacts to anything — a module's events or a role's (novox/hq ADR 0121). Watching
|
||||
// a role was missing here, so the one module that does it got no consumer at all: it started,
|
||||
// connected, and its graph stayed empty with nothing anywhere reporting why.
|
||||
if p.Kind != KindModule || (len(p.Consumes) == 0 && len(p.Watches) == 0) {
|
||||
return Consumer{}, false
|
||||
}
|
||||
perms, err := PermissionsFor(p)
|
||||
if err != nil {
|
||||
return Consumer{}, false
|
||||
}
|
||||
// Events, wherever they live: a module's own namespace, and the namespace of any role it watches
|
||||
// (novox/hq ADR 0121). Tool subjects and inboxes are subscribed directly and are not a consumer's
|
||||
// business, which is why this is a filter and not the whole list.
|
||||
var filters []string
|
||||
for _, s := range perms.Subscribe {
|
||||
if strings.Contains(s, ".event.") {
|
||||
filters = append(filters, s)
|
||||
}
|
||||
}
|
||||
if len(filters) == 0 {
|
||||
return Consumer{}, false
|
||||
}
|
||||
sort.Strings(filters)
|
||||
return Consumer{
|
||||
Name: consumerDurable(p),
|
||||
Stream: consumerStream(p),
|
||||
Filters: filters,
|
||||
AckWaitSeconds: 30,
|
||||
MaxDeliver: 5,
|
||||
Why: "what " + p.Module + " declared it consumes; after max-deliver it dead-letters",
|
||||
}, true
|
||||
}
|
||||
|
||||
// HolderConsumerFor is the worker a seat's holder gets on that seat's work queue.
|
||||
//
|
||||
// **A queue group even though the seat guarantees one holder.** The seat is *authority* — who may
|
||||
// be the telegram sender — and the queue group is *delivery*. Tie delivery to the seat and the
|
||||
// day somebody allows two holders for throughput, every message is processed twice with nothing
|
||||
// reporting it. Kept separate, relaxing one changes nothing about the other.
|
||||
func HolderConsumerFor(node, module string, seat DeclaredSeat) (Consumer, bool) {
|
||||
if len(seat.Accepts) == 0 {
|
||||
return Consumer{}, false
|
||||
}
|
||||
return Consumer{
|
||||
Name: "SEAT_" + upperSnake(seat.Name) + "_worker",
|
||||
Stream: seatStreamName(seat.Name),
|
||||
Filters: []string{"mesh.seat." + seat.Name + ".accept.>"},
|
||||
Queue: "holders",
|
||||
AckWaitSeconds: 60,
|
||||
MaxDeliver: 5,
|
||||
Why: fmt.Sprintf("%s on %s holds %s; it acknowledges after the work is done, so a "+
|
||||
"crash mid-work redelivers rather than loses", module, node, seat.Name),
|
||||
}, true
|
||||
}
|
||||
|
||||
// NodeConsumer is the durable consumer a node reads its own declaration through.
|
||||
//
|
||||
// **Derived from a node existing, and created by the controller, because a host cannot create it.**
|
||||
// A host's account may subscribe its own declaration subject and publish its own ack subject, and
|
||||
// reaches no part of the JetStream API — which is correct (the controller is the only writer of
|
||||
// consumer definitions, design 25 §3) and means the consumer must be waiting before the host binds
|
||||
// to it. Named after the node, because the node's ack grant is `$JS.ACK.NODES.<node>.>` and a
|
||||
// consumer named anything else is one the host cannot acknowledge a delivery from.
|
||||
//
|
||||
// **No max-deliver, and a long ack wait.** A declaration is settled only after the node has applied
|
||||
// it and reported, which is minutes on a machine pulling images; and a declaration the mesh cannot
|
||||
// get a node to accept is not one to dead-letter, because the stream keeps only the newest per node
|
||||
// anyway — so there is exactly one message per node to redeliver, for as long as that node is away.
|
||||
func NodeConsumer(node string) Consumer {
|
||||
return Consumer{
|
||||
Name: node,
|
||||
Stream: "NODES",
|
||||
Filters: []string{"mesh.node." + node + ".declare"},
|
||||
Push: true,
|
||||
AckWaitSeconds: 300,
|
||||
Why: "how " + node + " hears what it should be; last-per-subject, so a node that was away " +
|
||||
"gets exactly the current declaration and nothing older",
|
||||
}
|
||||
}
|
||||
|
||||
// AssertNodeConsumers brings every known node's declaration consumer into being.
|
||||
//
|
||||
// Asserted on start as well as created at enrolment, for the reason the streams are: a mesh raised
|
||||
// from a restored backup, or one whose bus was recreated, has node records and no consumers, and a
|
||||
// node whose consumer is missing hears nothing while everything else about it looks correct.
|
||||
func AssertNodeConsumers(e Ensurer, nodes []string) error {
|
||||
for _, n := range nodes {
|
||||
if err := e.EnsureConsumer(NodeConsumer(n)); err != nil {
|
||||
return fmt.Errorf("asserting how %s hears its declaration: %w", n, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AllOverlaps reports subject filters claimed by more than one stream, across the mesh's own and
|
||||
// every derived one.
|
||||
//
|
||||
// NATS refuses an overlapping stream rather than merging it (verified against nats-server 2.10:
|
||||
// "subjects overlap with an existing stream"), so this is not a subtle divergence — it is a
|
||||
// registration that fails. Catching it here names both streams, before a half-applied mesh does.
|
||||
func AllOverlaps(seats []DeclaredSeat) []string {
|
||||
all := append(MeshStreams(), SeatStreams(seats)...)
|
||||
seen := map[string]string{}
|
||||
var clashes []string
|
||||
for _, s := range all {
|
||||
for _, subject := range s.Subjects {
|
||||
if first, ok := seen[subject]; ok {
|
||||
clashes = append(clashes, fmt.Sprintf("%s and %s both claim %s", first, s.Name, subject))
|
||||
continue
|
||||
}
|
||||
seen[subject] = s.Name
|
||||
}
|
||||
}
|
||||
sort.Strings(clashes)
|
||||
return clashes
|
||||
}
|
||||
|
||||
// upperSnake makes a stream name from a seat name. NATS stream names may not contain a dot,
|
||||
// a space or a wildcard, and a hyphen is legal but reads badly beside the mesh's own.
|
||||
func upperSnake(s string) string {
|
||||
out := []rune(s)
|
||||
for i, r := range out {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z':
|
||||
out[i] = r - 32
|
||||
case r == '-' || r == '.':
|
||||
out[i] = '_'
|
||||
}
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func telegramSeat() DeclaredSeat {
|
||||
return DeclaredSeat{Name: "telegram-sender", Accepts: []string{"send"}}
|
||||
}
|
||||
|
||||
// The stream exists from registration, not assignment: work queues until a holder appears, so
|
||||
// installing the module a week later flushes the backlog rather than having lost it.
|
||||
func TestASeatGetsAWorkQueueOfItsOwn(t *testing.T) {
|
||||
got := SeatStreams([]DeclaredSeat{telegramSeat()})
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("expected one stream, got %d", len(got))
|
||||
}
|
||||
s := got[0]
|
||||
if s.Retention != RetentionWorkQueue {
|
||||
t.Fatalf("a seat's inbound queue retains as %q; one holder must take each message once", s.Retention)
|
||||
}
|
||||
if s.Subjects[0] != "mesh.seat.telegram-sender.accept.>" {
|
||||
t.Fatalf("filters on %v", s.Subjects)
|
||||
}
|
||||
}
|
||||
|
||||
// A seat that only emits and serves needs no stream: its events ride EVENTS and its tools are
|
||||
// core request/reply, which is never persisted.
|
||||
func TestASeatThatAcceptsNothingGetsNoStream(t *testing.T) {
|
||||
if got := SeatStreams([]DeclaredSeat{{Name: "announcer"}}); len(got) != 0 {
|
||||
t.Fatalf("a seat with no inbound work got %d stream(s)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// Retention belongs to whoever owns the namespace, and a seat owns its own.
|
||||
func TestASeatsRetentionIsItsOwn(t *testing.T) {
|
||||
s := SeatStreams([]DeclaredSeat{{Name: "slow", Accepts: []string{"work"}, RetainSeconds: 30 * 24 * 60 * 60}})
|
||||
if s[0].MaxAge != 30*24*60*60 {
|
||||
t.Fatalf("the seat's declared retention was not used: %d", s[0].MaxAge)
|
||||
}
|
||||
d := SeatStreams([]DeclaredSeat{telegramSeat()})
|
||||
if d[0].MaxAge == 0 {
|
||||
t.Fatal("a seat that declares no retention got an unbounded queue")
|
||||
}
|
||||
}
|
||||
|
||||
// NATS refuses an overlapping stream outright, so a clash here is a registration that fails.
|
||||
func TestNoDerivedStreamOverlapsTheMeshsOwn(t *testing.T) {
|
||||
seats := []DeclaredSeat{telegramSeat(), {Name: "licensing-master", Accepts: []string{"report"}}}
|
||||
if c := AllOverlaps(seats); len(c) != 0 {
|
||||
t.Fatalf("overlapping filters: %v", c)
|
||||
}
|
||||
}
|
||||
|
||||
// One consumer per module, with every consumed subject as a filter — because its ack permission
|
||||
// is derived from its name, and a consumer per event would need an ack permission per consumer.
|
||||
func TestAModuleGetsOneConsumerCarryingEveryFilter(t *testing.T) {
|
||||
c, ok := ConsumerFor(Principal{Kind: KindModule, Node: "one", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed", "billing.invoice.sent"}, PasswordHash: "x"})
|
||||
if !ok {
|
||||
t.Fatal("a module that consumes got no consumer")
|
||||
}
|
||||
if len(c.Filters) != 2 {
|
||||
t.Fatalf("expected both subjects as filters, got %v", c.Filters)
|
||||
}
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed"}, PasswordHash: "x"})
|
||||
ack := "$JS.ACK." + c.Stream + "." + c.Name + ".>"
|
||||
found := false
|
||||
for _, p := range perms.Publish {
|
||||
if p == ack {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("the consumer is named %q but the ack permission is %v; a module could not ack "+
|
||||
"its own deliveries", c.Name, perms.Publish)
|
||||
}
|
||||
}
|
||||
|
||||
// A module that subscribes to nothing needs no consumer, and creating one would leave an object
|
||||
// nothing reads and everything has to maintain.
|
||||
func TestAModuleThatConsumesNothingGetsNoConsumer(t *testing.T) {
|
||||
if _, ok := ConsumerFor(Principal{Kind: KindModule, Node: "one", Module: "shop",
|
||||
Emits: []string{"order.placed"}, PasswordHash: "x"}); ok {
|
||||
t.Fatal("a pure emitter got a consumer")
|
||||
}
|
||||
}
|
||||
|
||||
// The seat is authority and the queue group is delivery. Tie them together and the day somebody
|
||||
// allows two holders, every message is processed twice with nothing reporting it.
|
||||
func TestAHoldersWorkerUsesAQueueGroupAnyway(t *testing.T) {
|
||||
c, ok := HolderConsumerFor("one", "telegram", telegramSeat())
|
||||
if !ok {
|
||||
t.Fatal("the holder of a seat with inbound work got no worker")
|
||||
}
|
||||
if c.Queue == "" {
|
||||
t.Fatal("the worker is not in a queue group, so a second holder would double-process")
|
||||
}
|
||||
if c.Stream != "SEAT_TELEGRAM_SENDER" {
|
||||
t.Fatalf("the worker reads %q, not the seat's own stream", c.Stream)
|
||||
}
|
||||
if c.MaxDeliver == 0 {
|
||||
t.Fatal("a failing worker would redeliver forever rather than dead-letter")
|
||||
}
|
||||
}
|
||||
|
||||
// The stream is named after the seat, not its holder: the holder can change and the queued work
|
||||
// must not care.
|
||||
func TestASeatsStreamIsNamedAfterTheSeat(t *testing.T) {
|
||||
name := seatStreamName("telegram-sender")
|
||||
if strings.Contains(name, "telegram-sender") {
|
||||
t.Fatalf("%q keeps characters a stream name may not hold", name)
|
||||
}
|
||||
if name != "SEAT_TELEGRAM_SENDER" {
|
||||
t.Fatalf("unexpected stream name %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
// A node hears its declaration through a consumer only the controller can make.
|
||||
//
|
||||
// The three things that would each break it silently: a name other than the node's is one the host
|
||||
// cannot acknowledge a delivery from, because its ack grant is derived from the node's name; a
|
||||
// filter other than its own declaration subject is a node reading another's; and a pull consumer is
|
||||
// one the host cannot bind a channel to without creating something, which it has no authority for.
|
||||
func TestANodesDeclarationConsumerIsWhatItsOwnGrantAllows(t *testing.T) {
|
||||
c := NodeConsumer("anchor")
|
||||
if c.Name != "anchor" {
|
||||
t.Fatalf("named %q, so the node cannot ack from it: its grant is $JS.ACK.NODES.anchor.>", c.Name)
|
||||
}
|
||||
if c.Stream != "NODES" {
|
||||
t.Fatalf("on stream %q rather than the one declarations live in", c.Stream)
|
||||
}
|
||||
if len(c.Filters) != 1 || c.Filters[0] != "mesh.node.anchor.declare" {
|
||||
t.Fatalf("filters %v, which is not this node's own declaration and nothing else", c.Filters)
|
||||
}
|
||||
if !c.Push {
|
||||
t.Fatal("pulled, which a host cannot do: pulling needs the JetStream API and a host reaches none of it")
|
||||
}
|
||||
if c.MaxDeliver != 0 {
|
||||
t.Fatalf("max-deliver %d: a declaration a node has not taken yet is not one to dead-letter, "+
|
||||
"because the stream holds exactly one per node", c.MaxDeliver)
|
||||
}
|
||||
|
||||
// And the grant the node actually gets has to match, or none of the above matters.
|
||||
perms, err := PermissionsFor(Principal{Kind: KindNode, Node: "anchor"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Without the ack grant every declaration a node receives is redelivered for ever; without the
|
||||
// subscribe grant its consumer delivers to nobody.
|
||||
has(t, perms.Publish, "$JS.ACK.NODES."+c.Name+".>")
|
||||
has(t, perms.Subscribe, c.Filters[0])
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// **The first user list the installer carries must be the one the controller would compose.**
|
||||
//
|
||||
// At genesis there is no mesh to write the bus's user list, so the installer carries one: the
|
||||
// controller's own account, at a bootstrap password, the way the store is reached at
|
||||
// `postgres:bootstrap` (novox/hq design 25 §4, task 1.7). It is written by hand in a template and
|
||||
// derived in code here, which is two statements of one fact — so this compares them.
|
||||
//
|
||||
// Getting it wrong is the worst kind of silent: a controller whose carried permissions are narrower
|
||||
// than the ones it derives comes up, connects, and is refused on the first thing it tries, with an
|
||||
// authorisation error that names a subject and not the template that forgot it. And a mesh cannot be
|
||||
// raised twice to find out.
|
||||
func TestTheInstallersFirstUserListIsWhatTheControllerWouldCompose(t *testing.T) {
|
||||
accounts := theCarriedAccounts(t)
|
||||
|
||||
want, err := PermissionsFor(Principal{Kind: KindController, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
carriedPub := subjectsIn(accounts, "publish")
|
||||
carriedSub := subjectsIn(accounts, "subscribe")
|
||||
|
||||
if diff := missing(want.Publish, carriedPub); len(diff) > 0 {
|
||||
t.Errorf("the installer's user list does not let the controller publish %v — it would come up "+
|
||||
"and be refused on the first thing it tried", diff)
|
||||
}
|
||||
if diff := missing(want.Subscribe, carriedSub); len(diff) > 0 {
|
||||
t.Errorf("the installer's user list does not let the controller subscribe %v", diff)
|
||||
}
|
||||
// And nothing wider than what it derives, or genesis quietly grants a privilege the composition
|
||||
// takes away again on the first push.
|
||||
if diff := missing(carriedPub, want.Publish); len(diff) > 0 {
|
||||
t.Errorf("the installer's user list lets the controller publish %v, which it does not derive", diff)
|
||||
}
|
||||
if diff := missing(carriedSub, want.Subscribe); len(diff) > 0 {
|
||||
t.Errorf("the installer's user list lets the controller subscribe %v, which it does not derive", diff)
|
||||
}
|
||||
|
||||
// The credential is the bootstrap one and the hash really is of it, because a hash of something
|
||||
// else is a controller that cannot log in to the bus it was just given.
|
||||
hash := regexp.MustCompile(`\$2[aby]?\$[0-9]+\$[A-Za-z0-9./]{53}`).FindString(accounts)
|
||||
if hash == "" {
|
||||
t.Fatal("the installer's user list carries no password hash")
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte("bootstrap")); err != nil {
|
||||
t.Fatalf("the carried hash does not verify the bootstrap credential the template also carries: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// theCarriedAccounts is the accounts file the installer's template writes at genesis.
|
||||
func theCarriedAccounts(t *testing.T) string {
|
||||
t.Helper()
|
||||
for _, r := range theTemplate(t) {
|
||||
if r["id"] == "bus-accounts" {
|
||||
content, _ := r["content"].(string)
|
||||
if content == "" {
|
||||
t.Fatal("the template's accounts file is empty, so the bus would refuse every connection")
|
||||
}
|
||||
return content
|
||||
}
|
||||
}
|
||||
t.Fatal("the template carries no accounts file, so a mesh raised from it has a bus nobody may use")
|
||||
return ""
|
||||
}
|
||||
|
||||
// theTemplate is the installer's bundle, as resources.
|
||||
func theTemplate(t *testing.T) []map[string]any {
|
||||
t.Helper()
|
||||
path := filepath.Join("..", "..", "..", "mesh-host", "examples", "foundation-first-node-nats.lock")
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Skipf("the host's checkout is not beside this one: %v", err)
|
||||
}
|
||||
// The template is JSON with line comments, which is how every one of them is written.
|
||||
var lines []string
|
||||
for _, l := range strings.Split(string(raw), "\n") {
|
||||
if !strings.HasPrefix(strings.TrimSpace(l), "//") {
|
||||
lines = append(lines, l)
|
||||
}
|
||||
}
|
||||
var bundle struct {
|
||||
Resources []map[string]any `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.Join(lines, "\n")), &bundle); err != nil {
|
||||
t.Fatalf("the template is not readable: %v", err)
|
||||
}
|
||||
return bundle.Resources
|
||||
}
|
||||
|
||||
// subjectsIn reads one allow-list out of a composed accounts file.
|
||||
func subjectsIn(accounts, which string) []string {
|
||||
found := regexp.MustCompile(which + `: \{ allow: \[([^\]]*)\]`).FindStringSubmatch(accounts)
|
||||
if len(found) != 2 {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, part := range strings.Split(found[1], ",") {
|
||||
if s := strings.Trim(strings.TrimSpace(part), `"`); s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// missing is what is in want and not in got.
|
||||
func missing(want, got []string) []string {
|
||||
have := map[string]bool{}
|
||||
for _, g := range got {
|
||||
have[g] = true
|
||||
}
|
||||
var out []string
|
||||
for _, w := range want {
|
||||
if !have[w] {
|
||||
out = append(out, w)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A module that says it calls a tool may publish exactly that subject (novox/hq ADR 0152): the same
|
||||
// grant a person gets, derived the same way, so one list answers "what may this ask" for everybody.
|
||||
func TestAModuleMayAskOnlyTheToolsItInvokes(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindModule, Node: "desk", Module: "mesh-console",
|
||||
Invokes: []string{"shop.price"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.shop.tool.price")
|
||||
hasNot(t, perms.Publish, "mesh.mod.shop.tool.refund")
|
||||
hasNot(t, perms.Publish, "mesh.mod.*.tool.>")
|
||||
}
|
||||
|
||||
// The console's grant: every tool, as one subject, and it reads as one.
|
||||
func TestAModuleInvokingEverythingMayAskAnyTool(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindModule, Node: "desk", Module: "mesh-console",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.*.tool.>")
|
||||
}
|
||||
|
||||
// **A grant to call widens nothing else.** A module that invokes may not publish an event it did not
|
||||
// declare, may not answer as another module, and subscribes nothing it did not consume — the
|
||||
// difference between the console and a person is that the console is on a machine, not that it may
|
||||
// do more.
|
||||
func TestInvokingGrantsNothingButTheCall(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindModule, Node: "desk", Module: "mesh-console",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range perms.Publish {
|
||||
if strings.Contains(p, ".event.") {
|
||||
t.Errorf("a module that only invokes may publish %q, an event it never declared", p)
|
||||
}
|
||||
// A role's tools are tools (ADR 0132); a role's work queue and events are not.
|
||||
if strings.HasPrefix(p, "mesh.seat.") && !strings.Contains(p, ".tool.") {
|
||||
t.Errorf("a module that only invokes may publish %q, a seat it neither holds nor uses", p)
|
||||
}
|
||||
}
|
||||
for _, s := range perms.Subscribe {
|
||||
if strings.Contains(s, ".tool.") && !strings.HasPrefix(s, "mesh.mod.mesh-console.") {
|
||||
t.Errorf("a module that invokes may subscribe %q, another module's tools", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A module that declares no invokes calls nothing, which is every module but the console.
|
||||
func TestAModuleThatInvokesNothingCallsNothing(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "shop",
|
||||
Emits: []string{"order.placed"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range perms.Publish {
|
||||
if strings.Contains(p, ".tool.") {
|
||||
t.Errorf("a module with no invokes may publish %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The malformed entry is refused for a module as it is for a person, and in the same words.
|
||||
func TestAModulesToolGrantThatNamesNoToolIsRefused(t *testing.T) {
|
||||
if _, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "shop",
|
||||
Invokes: []string{"telegram"}, PasswordHash: "x"}); err == nil {
|
||||
t.Fatal("a grant naming a module but no tool was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// What a declaration says reaches the composed user, so a manifest's `invokes` is the grant.
|
||||
func TestADeclaredInvokeReachesTheComposedUser(t *testing.T) {
|
||||
users, err := Users(Records{
|
||||
Nodes: []string{"desk"},
|
||||
Assigned: map[string][]Declared{"desk": {{Module: "mesh-console", Invokes: []string{"*"}}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
perms, err := PermissionsFor(users[len(users)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.*.tool.>")
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// The JetStream side of the controller: the one place the mesh's streams and consumers are
|
||||
// actually created.
|
||||
//
|
||||
// Everything that decides *what* they are is pure and lives beside this (streams.go, derived.go).
|
||||
// This is only the part that talks to a server, kept small on purpose: a bug in a subject filter
|
||||
// should be findable in a unit test, and only a bug in "did the server accept it" should need one
|
||||
// running.
|
||||
|
||||
// A JetStream is a connection to the bus, as the controller uses it.
|
||||
type JetStream struct {
|
||||
conn *nats.Conn
|
||||
js nats.JetStreamContext
|
||||
// Note is how this says something it decided not to fail over. Nil is silent, which is only
|
||||
// right for a caller that has no way to report; the controller sets it.
|
||||
Note func(string, ...any)
|
||||
}
|
||||
|
||||
// note reports without requiring a caller to have set one.
|
||||
func (j *JetStream) note(format string, args ...any) {
|
||||
if j.Note != nil {
|
||||
j.Note(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// Dial connects and returns the controller's JetStream handle.
|
||||
func Dial(url string, opts ...nats.Option) (*JetStream, error) {
|
||||
opts = append(opts, nats.Name("mesh-controller"), nats.Timeout(10*time.Second))
|
||||
// **Pinned, not named.** The bus presents the mesh's own certificate, which names nothing a
|
||||
// public verifier would accept (design 25 §4: a host pins the server's exact certificate and
|
||||
// checks nothing else, and so does this). Without this, the first connection failed with
|
||||
// "certificate is not valid for any names" against a bus that was answering (2026-09-28).
|
||||
if path := strings.TrimSpace(os.Getenv(CertificateVar)); path != "" {
|
||||
pinned, err := pinnedTo(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts = append(opts, nats.Secure(pinned))
|
||||
}
|
||||
// **Its own inbox, and nothing wider.** Every principal is granted `_INBOX.<its user>.>` and
|
||||
// no other inbox; the client's default prefix is random, and the server refused the first
|
||||
// subscription to it (2026-09-28). The user is in the URL, so the prefix follows from it.
|
||||
if user, _, _ := CredentialIn(url); user != "" {
|
||||
opts = append(opts, nats.CustomInboxPrefix("_INBOX."+user))
|
||||
}
|
||||
// The address in an error is the address alone. The URL carries this controller's password,
|
||||
// and an error here is written on the assumption it will be logged.
|
||||
where := BareAddress(url)
|
||||
conn, err := nats.Connect(url, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connecting to the bus at %s: %w", where, err)
|
||||
}
|
||||
js, err := conn.JetStream()
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("the bus at %s has no JetStream: %w", where, err)
|
||||
}
|
||||
return &JetStream{conn: conn, js: js}, nil
|
||||
}
|
||||
|
||||
// pinnedTo is a TLS configuration that accepts exactly the certificate in the file and no other:
|
||||
// the leaf's SHA-256, compared on every handshake, with the name and the chain deliberately not
|
||||
// consulted — a self-signed certificate with no names is the ordinary case for a mesh's bus.
|
||||
func pinnedTo(path string) (*tls.Config, error) {
|
||||
want, err := FingerprintOf(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return PinnedToFingerprint(want), nil
|
||||
}
|
||||
|
||||
// DialPinned is Dial with the server's certificate pinned by a fingerprint the caller already holds
|
||||
// — a module or a build machine that was handed one beside its credential, and has no file.
|
||||
func DialPinned(url, fingerprint string, opts ...nats.Option) (*JetStream, error) {
|
||||
if strings.TrimSpace(fingerprint) != "" {
|
||||
opts = append(opts, nats.Secure(PinnedToFingerprint(fingerprint)))
|
||||
}
|
||||
return Dial(url, opts...)
|
||||
}
|
||||
|
||||
// PinnedToFingerprint accepts exactly the certificate with this SHA-256 and no other.
|
||||
func PinnedToFingerprint(want string) *tls.Config {
|
||||
return &tls.Config{
|
||||
InsecureSkipVerify: true, //nolint:gosec // replaced by the pin below, which is stricter
|
||||
MinVersion: tls.VersionTLS12,
|
||||
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
|
||||
if len(rawCerts) == 0 {
|
||||
return errors.New("the bus presented no certificate")
|
||||
}
|
||||
sum := sha256.Sum256(rawCerts[0])
|
||||
got := "sha256:" + hex.EncodeToString(sum[:])
|
||||
if got != want {
|
||||
return fmt.Errorf("the bus presented a certificate this mesh does not know (%s…), expected %s…", got[:23], want[:23])
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Conn is the connection itself, for what the mesh keeps off JetStream on purpose — a heartbeat,
|
||||
// a tool call — where a lost message is answered by the next one or by a timeout the caller
|
||||
// already handles (design 25 §3).
|
||||
func (j *JetStream) Conn() *nats.Conn { return j.conn }
|
||||
|
||||
// Context is the JetStream handle, for subscribing to what the consumers above define.
|
||||
func (j *JetStream) Context() nats.JetStreamContext { return j.js }
|
||||
|
||||
func (j *JetStream) Close() {
|
||||
if j.conn != nil {
|
||||
j.conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// EnsureStream creates the stream if it is absent and brings it to match if it is present.
|
||||
//
|
||||
// **Idempotent, because the controller asserts on every start** rather than creating once at
|
||||
// genesis: a stream somebody deleted, or a mesh raised from a restored backup, has to converge
|
||||
// rather than run without the guarantee its messages assume.
|
||||
//
|
||||
// An update, not a delete and recreate. Recreating would discard every message the stream holds
|
||||
// and every consumer's position in it — which for CONTROL means the pushes being held through a
|
||||
// store restart, exactly the guarantee the stream exists for.
|
||||
func (j *JetStream) EnsureStream(s Stream) error {
|
||||
want := &nats.StreamConfig{
|
||||
Name: s.Name,
|
||||
Subjects: s.Subjects,
|
||||
Retention: retentionOf(s.Retention),
|
||||
MaxAge: time.Duration(s.MaxAge) * time.Second,
|
||||
MaxMsgsPerSubject: int64(s.MaxMsgsPerSubject),
|
||||
Description: s.Why,
|
||||
}
|
||||
if s.Retention == RetentionLastPerSubject {
|
||||
// Last-per-subject is a limits stream with one message kept per subject, not a
|
||||
// retention policy of its own — the state shape, spelled the way the server spells it.
|
||||
want.Retention = nats.LimitsPolicy
|
||||
want.MaxMsgsPerSubject = 1
|
||||
want.MaxAge = 0
|
||||
}
|
||||
|
||||
switch _, err := j.js.StreamInfo(s.Name); {
|
||||
case err == nil:
|
||||
if _, err := j.js.UpdateStream(want); err != nil {
|
||||
return fmt.Errorf("bringing stream %s to match: %w", s.Name, err)
|
||||
}
|
||||
return nil
|
||||
case errors.Is(err, nats.ErrStreamNotFound):
|
||||
if _, err := j.js.AddStream(want); err != nil {
|
||||
return fmt.Errorf("creating stream %s: %w", s.Name, err)
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("asking about stream %s: %w", s.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// EnsureConsumer creates or updates one durable consumer.
|
||||
//
|
||||
// Explicit acknowledgement throughout: a consumer that acknowledges on delivery cannot redeliver
|
||||
// work its holder died in the middle of, which is the whole difference between a queue and a
|
||||
// firehose.
|
||||
func (j *JetStream) EnsureConsumer(c Consumer) error {
|
||||
want := &nats.ConsumerConfig{
|
||||
Durable: c.Name,
|
||||
AckPolicy: nats.AckExplicitPolicy,
|
||||
AckWait: time.Duration(c.AckWaitSeconds) * time.Second,
|
||||
MaxDeliver: c.MaxDeliver,
|
||||
MaxAckPending: c.MaxAckPending,
|
||||
DeliverGroup: c.Queue,
|
||||
DeliverSubject: "",
|
||||
Description: c.Why,
|
||||
}
|
||||
switch len(c.Filters) {
|
||||
case 0:
|
||||
case 1:
|
||||
want.FilterSubject = c.Filters[0]
|
||||
default:
|
||||
want.FilterSubjects = c.Filters
|
||||
}
|
||||
// A queue group needs a delivery subject: a pull consumer has no group, and declaring one
|
||||
// without the other is refused by the server with a message that does not say which half is
|
||||
// missing.
|
||||
if c.Queue != "" || c.Push {
|
||||
// **Per consumer, which means per stream as well as per name** (novox/hq 04-ISSUES/146).
|
||||
// A push consumer delivers onto an ordinary subject, and everything subscribed to that
|
||||
// subject gets a copy. The controller holds a consumer called `controller` on CONTROL and
|
||||
// another called `controller` on EVENTS, and both were given `_DELIVER.controller` — so the
|
||||
// one process, holding both subscriptions, acted on every message twice. It enrolled a
|
||||
// joining machine twice from one request, minting a second credential that replaced the one
|
||||
// the machine had just been given; the same doubling applied to every report and every
|
||||
// event the controller follows.
|
||||
//
|
||||
// The stream is in the name because the pair is what identifies a consumer — the server
|
||||
// scopes a durable's name to its stream, and this subject is the only place that scoping
|
||||
// was dropped. Already within what the controller may subscribe (`_DELIVER.controller.>`),
|
||||
// so no permission moves.
|
||||
want.DeliverSubject = DeliverSubjectFor(c)
|
||||
}
|
||||
|
||||
switch have, err := j.js.ConsumerInfo(c.Stream, c.Name); {
|
||||
case err == nil:
|
||||
// Where an existing consumer starts is its history, not something an assertion may move:
|
||||
// the server refuses a changed deliver policy outright. Carried across, so asserting twice
|
||||
// is the no-op a restart depends on.
|
||||
want.DeliverPolicy = have.Config.DeliverPolicy
|
||||
want.OptStartSeq = have.Config.OptStartSeq
|
||||
want.OptStartTime = have.Config.OptStartTime
|
||||
|
||||
if _, err := j.js.UpdateConsumer(c.Stream, want); err != nil {
|
||||
// **A consumer that works is not replaced to make its name tidier**
|
||||
// (novox/hq 04-ISSUES/156).
|
||||
//
|
||||
// The server will not move a push consumer's delivery subject while a subscriber is
|
||||
// bound to it, and answers `consumer name already in use` — a message about the name,
|
||||
// for a conflict about the subject. A node is bound to its declaration consumer the
|
||||
// whole time it is up; that IS a node listening. So when 04-ISSUES/146 put the stream
|
||||
// into the subject, every node consumer in a running mesh became one this could not
|
||||
// bring to match, and the control plane crash-looped on the assertion it makes before
|
||||
// it serves. A fresh mesh showed nothing: nothing was bound.
|
||||
//
|
||||
// Kept rather than deleted and re-made. Re-making moves the subject, and a holder may
|
||||
// not be allowed to subscribe to the new one yet — the wider grant travels in the bus's
|
||||
// user list, which this same control plane composes and a machine applies minutes
|
||||
// later. Re-making here would have silenced every machine in the mesh, which is worse
|
||||
// than the collision it was fixing and harder to undo.
|
||||
//
|
||||
// Kept rather than fatal, which is what 146's change intended and did not do: the bare
|
||||
// subject it replaces still delivers, and it collides only where one holder has two
|
||||
// consumers of one name. That is the controller's own pair, and the controller is not
|
||||
// bound to them while it asserts, so those do move. A node has one consumer and nothing
|
||||
// to collide with.
|
||||
if have.Config.DeliverSubject != want.DeliverSubject {
|
||||
j.note("consumer %s on %s still delivers to %q and not %q: %v. It keeps working; "+
|
||||
"the subject moves on an assertion made while nothing is bound to it",
|
||||
c.Name, c.Stream, have.Config.DeliverSubject, want.DeliverSubject, err)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("bringing consumer %s on %s to match: %w", c.Name, c.Stream, err)
|
||||
}
|
||||
return nil
|
||||
case errors.Is(err, nats.ErrConsumerNotFound):
|
||||
if _, err := j.js.AddConsumer(c.Stream, want); err != nil {
|
||||
return fmt.Errorf("creating consumer %s on %s: %w", c.Name, c.Stream, err)
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("asking about consumer %s on %s: %w", c.Name, c.Stream, err)
|
||||
}
|
||||
}
|
||||
|
||||
func retentionOf(r Retention) nats.RetentionPolicy {
|
||||
switch r {
|
||||
case RetentionWorkQueue:
|
||||
return nats.WorkQueuePolicy
|
||||
default:
|
||||
return nats.LimitsPolicy
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Against a real server, because the questions here are all "does the server accept this" —
|
||||
// which a mock would answer by agreeing with whatever this file already believes.
|
||||
//
|
||||
// Skipped unless MESH_TEST_NATS names one, so the ordinary suite stays fast and offline:
|
||||
//
|
||||
// docker run -d --rm --name t -p 14222:4222 nats:2.10-alpine -js
|
||||
// MESH_TEST_NATS=nats://127.0.0.1:14222 go test ./internal/broker/ -run TestAgainstARealServer
|
||||
func TestAgainstARealServer(t *testing.T) {
|
||||
url := os.Getenv("MESH_TEST_NATS")
|
||||
if url == "" {
|
||||
t.Skip("MESH_TEST_NATS unset")
|
||||
}
|
||||
js, err := Dial(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer js.Close()
|
||||
|
||||
t.Run("the mesh's own streams are accepted", func(t *testing.T) {
|
||||
if err := AssertMeshStreams(js); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("asserting again changes nothing and fails nothing", func(t *testing.T) {
|
||||
if err := AssertMeshStreams(js); err != nil {
|
||||
t.Fatalf("the second assertion failed, so the controller cannot restart: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a seat's work queue is accepted beside them", func(t *testing.T) {
|
||||
seats := []DeclaredSeat{{Name: "telegram-sender", Accepts: []string{"send"}}}
|
||||
for _, s := range SeatStreams(seats) {
|
||||
if err := js.EnsureStream(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if c := AllOverlaps(seats); len(c) != 0 {
|
||||
t.Fatalf("overlaps the server would refuse: %v", c)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a module's consumer is accepted and is idempotent", func(t *testing.T) {
|
||||
c, ok := ConsumerFor(Principal{Kind: KindModule, Node: "one", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed", "billing.invoice.sent"}, PasswordHash: "x"})
|
||||
if !ok {
|
||||
t.Fatal("no consumer derived")
|
||||
}
|
||||
if err := js.EnsureConsumer(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := js.EnsureConsumer(c); err != nil {
|
||||
t.Fatalf("the second assertion failed: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a holder's worker is accepted with its queue group", func(t *testing.T) {
|
||||
c, _ := HolderConsumerFor("one", "telegram",
|
||||
DeclaredSeat{Name: "telegram-sender", Accepts: []string{"send"}})
|
||||
if err := js.EnsureConsumer(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/novox/mesh-controller/internal/envfile"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The mesh runs the broker, so there is no chicken-and-egg in a node needing an account before it
|
||||
// can connect: the account is created when the token is issued, and the one-time secret in that
|
||||
// token IS the password. A node's first connection is already authenticated, and enrolment is
|
||||
// what happens over it.
|
||||
//
|
||||
// novox/hq ADR 0004's *a node holds its own identity and nothing else* is why the account is per
|
||||
// node rather than shared. A shared enrolment account would let any node consume another's queue,
|
||||
// which is the shared-credential fault that record exists to remove, reappearing at the transport.
|
||||
|
||||
// ManagementVar holds the broker's management API, credentials included.
|
||||
const ManagementVar = "MESH_BROKER_MANAGEMENT"
|
||||
|
||||
// safeName is what a node may be called at the broker.
|
||||
//
|
||||
// The name goes into a URL path and into permission patterns, which are regular expressions. A
|
||||
// name carrying a `.` or a `*` would silently widen what that node may reach — so it is
|
||||
// constrained here rather than escaped later, because an escape that is forgotten once is a node
|
||||
// reading everybody's queues.
|
||||
var safeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
|
||||
|
||||
// Management is the broker's administrative interface.
|
||||
type Management struct {
|
||||
base *url.URL
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// ManagementFromEnvironment reads where the management API is, if it is configured.
|
||||
//
|
||||
// On the port MESH_BROKER_MANAGEMENT_PORT names when the node moved it (novox/hq 04-ISSUES/102);
|
||||
// the URL's own port otherwise.
|
||||
func ManagementFromEnvironment() (*Management, error) {
|
||||
raw, err := envfile.Placed(ManagementVar)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if raw == "" {
|
||||
return nil, ErrNotConfigured
|
||||
}
|
||||
base, err := url.Parse(raw)
|
||||
if err != nil || base.Host == "" {
|
||||
// The value carries a password, so it is not quoted back.
|
||||
return nil, fmt.Errorf("%s is not a usable URL", ManagementVar)
|
||||
}
|
||||
return &Management{base: base, client: &http.Client{Timeout: 15 * time.Second}}, nil
|
||||
}
|
||||
|
||||
// QueueFor is the queue a node consumes from. One per node, named after it.
|
||||
func QueueFor(node string) string { return "node." + node }
|
||||
|
||||
// ExchangeName is where nodes publish what they have to say. One exchange, and the control plane
|
||||
// is the only consumer behind it (novox/hq ADR 0006 — one consumer, so two cannot silently split
|
||||
// the traffic between them).
|
||||
const ExchangeName = "mesh"
|
||||
|
||||
// BuildQueueName is where build work waits. Duplicated from `link` rather than imported, for the
|
||||
// same reason QueueFor above is: this package must not depend on the one that uses it, and a
|
||||
// constant that differed would be caught by the test that asserts they agree.
|
||||
const BuildQueueName = "builds"
|
||||
|
||||
// The events bus (novox/hq ADR 0042): one topic exchange every event rides, a second for tool
|
||||
// RPC kept apart, and a dead-letter home for a poison event. The foundation owns these — a module's
|
||||
// account cannot declare them, only bind its own queue to the events one.
|
||||
const (
|
||||
EventsExchangeName = "mesh.events"
|
||||
RPCExchangeName = "mesh.rpc"
|
||||
DeadExchangeName = "mesh.events.dead"
|
||||
)
|
||||
|
||||
// ModuleQueueFor is the durable queue a module consumes its events from — one per module per node
|
||||
// (novox/hq ADR 0042), named so the account that may read it is exactly this module's.
|
||||
func ModuleQueueFor(node, module string) string { return node + "." + module + ".events" }
|
||||
|
||||
// modulePermissions is a module's authority on the bus, derived from its manifest (novox/hq
|
||||
// ADR 0043): what it consumes and what it emits, and nothing else. Pure, so the scope is tested as
|
||||
// patterns without a broker — the way a builder's is.
|
||||
//
|
||||
// A note on the limit: the broker's write permission is per exchange, not per routing key (LavinMQ
|
||||
// has no topic permissions), so an emitting module is granted the events exchange whole. ADR 0042's
|
||||
// origin reservation — a module publishes only under `module.<self>.*` — is stamped by the sdk, not
|
||||
// enforced here; that gap is the broker's, and is recorded rather than hidden. A pure consumer like
|
||||
// the audit logger is unaffected: it is granted no write to the exchange at all.
|
||||
func modulePermissions(node, module string, emits, consumes []string) (configure, write, read string) {
|
||||
queue := regexp.QuoteMeta(ModuleQueueFor(node, module))
|
||||
events := regexp.QuoteMeta(EventsExchangeName)
|
||||
rpc := regexp.QuoteMeta(RPCExchangeName)
|
||||
// A module serves each of its tools on its own queue, namespaced by the module (novox/hq
|
||||
// ADR 0047) — serve.<module>.<tool> — so the account may declare, bind and read exactly its own,
|
||||
// and no other module's.
|
||||
serve := "serve\\." + regexp.QuoteMeta(module) + "\\..*"
|
||||
|
||||
// Declare its own events queue and its own tool serve queues.
|
||||
configure = "^(" + queue + "|" + serve + ")$"
|
||||
|
||||
// Write to bind its queue and serve queues (binding is a write on the queue), and to the RPC
|
||||
// exchange to publish replies (ADR 0047: replies ride mesh.rpc, never the default exchange, which
|
||||
// would let it publish into any queue). To the events exchange only if it emits.
|
||||
writes := []string{queue, serve, rpc}
|
||||
if len(emits) > 0 {
|
||||
writes = append(writes, events)
|
||||
}
|
||||
write = "^(" + strings.Join(writes, "|") + ")$"
|
||||
|
||||
// Read its own queue and serve queues to consume them, and the RPC exchange to bind its serve
|
||||
// queues onto. The events exchange to bind onto only if it consumes.
|
||||
reads := []string{queue, serve, rpc}
|
||||
if len(consumes) > 0 {
|
||||
reads = append(reads, events)
|
||||
}
|
||||
read = "^(" + strings.Join(reads, "|") + ")$"
|
||||
return configure, write, read
|
||||
}
|
||||
|
||||
// CreateModuleAccount gives an assigned module its own broker account, scoped by what it emits and
|
||||
// consumes (novox/hq ADR 0043). The account name carries the node so the same module on two machines
|
||||
// holds two accounts, each sealed to its own; the permissions carry the module so one module cannot
|
||||
// read another's queue. Generic — the builder is one instance of this rule, not a separate kind.
|
||||
func (m *Management) CreateModuleAccount(ctx context.Context, node, module, password string, emits, consumes []string) (string, error) {
|
||||
if !safeName.MatchString(node) {
|
||||
return "", fmt.Errorf("%q cannot be part of a broker account: it is a permission pattern", node)
|
||||
}
|
||||
if !safeName.MatchString(module) {
|
||||
return "", fmt.Errorf("%q cannot be part of a broker account: it is a permission pattern", module)
|
||||
}
|
||||
account := node + "-" + module
|
||||
if !safeName.MatchString(account) {
|
||||
return "", fmt.Errorf("%q is not a usable broker account name", account)
|
||||
}
|
||||
|
||||
if err := m.put(ctx, "/api/users/"+url.PathEscape(account),
|
||||
map[string]string{"password": password, "tags": ""}); err != nil {
|
||||
return "", fmt.Errorf("cannot create the broker account for %s on %s: %w", module, node, err)
|
||||
}
|
||||
|
||||
configure, write, read := modulePermissions(node, module, emits, consumes)
|
||||
if err := m.put(ctx, "/api/permissions/%2f/"+url.PathEscape(account), map[string]string{
|
||||
"configure": configure, "write": write, "read": read,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("cannot scope the broker account for %s on %s: %w", module, node, err)
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
// EnsureModuleQueue declares a consuming module's queue with its dead-letter exchange, idempotently.
|
||||
// The foundation declares it because a scoped module account may not: the broker refuses a queue with
|
||||
// a dead-letter exchange to a non-administrator (novox/hq ADR 0043), so a consumer passively checks
|
||||
// the queue the mesh made rather than declaring its own.
|
||||
func (m *Management) EnsureModuleQueue(ctx context.Context, node, module string) error {
|
||||
queue := ModuleQueueFor(node, module)
|
||||
if err := m.put(ctx, "/api/queues/%2f/"+url.PathEscape(queue), map[string]any{
|
||||
"durable": true,
|
||||
"arguments": map[string]any{"x-dead-letter-exchange": DeadExchangeName},
|
||||
}); err != nil {
|
||||
return fmt.Errorf("cannot declare the queue for %s on %s: %w", module, node, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureEventExchanges declares the bus's exchanges and the dead-letter home, idempotently. The
|
||||
// foundation owns them (a module's account may not declare an exchange), and a dead-letter exchange
|
||||
// with no queue behind it drops what it receives — so a durable queue bound to `#` retains a poison
|
||||
// event for inspection, which is the whole reason the trail exists.
|
||||
func (m *Management) EnsureEventExchanges(ctx context.Context) error {
|
||||
for _, exchange := range []string{EventsExchangeName, RPCExchangeName, DeadExchangeName} {
|
||||
if err := m.put(ctx, "/api/exchanges/%2f/"+url.PathEscape(exchange),
|
||||
map[string]any{"type": "topic", "durable": true}); err != nil {
|
||||
return fmt.Errorf("cannot declare the %s exchange: %w", exchange, err)
|
||||
}
|
||||
}
|
||||
if err := m.put(ctx, "/api/queues/%2f/"+url.PathEscape(DeadExchangeName),
|
||||
map[string]any{"durable": true}); err != nil {
|
||||
return fmt.Errorf("cannot declare the dead-letter queue: %w", err)
|
||||
}
|
||||
if err := m.post(ctx, "/api/bindings/%2f/e/"+url.PathEscape(DeadExchangeName)+
|
||||
"/q/"+url.PathEscape(DeadExchangeName), map[string]string{"routing_key": "#"}); err != nil {
|
||||
return fmt.Errorf("cannot bind the dead-letter queue: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateNodeAccount gives a node its own broker account, with the token's secret as the password.
|
||||
//
|
||||
// Scoped so a node can reach its own queue and the one exchange, and nothing else. The patterns
|
||||
// are anchored: a node called `laptop` must not be able to read `laptop-of-somebody-else`.
|
||||
func (m *Management) CreateNodeAccount(ctx context.Context, node, password string) error {
|
||||
if !safeName.MatchString(node) {
|
||||
return fmt.Errorf(
|
||||
"%q cannot be a broker account name: it becomes part of a permission pattern, so it "+
|
||||
"is lower-case letters, digits and dashes", node)
|
||||
}
|
||||
|
||||
if err := m.put(ctx, "/api/users/"+url.PathEscape(node),
|
||||
map[string]string{"password": password, "tags": ""}); err != nil {
|
||||
return fmt.Errorf("cannot create the broker account for %s: %w", node, err)
|
||||
}
|
||||
|
||||
queue := regexp.QuoteMeta(QueueFor(node))
|
||||
if err := m.put(ctx, "/api/permissions/%2f/"+url.PathEscape(node), map[string]string{
|
||||
"configure": "^" + queue + "$",
|
||||
"write": "^(" + regexp.QuoteMeta(ExchangeName) + "|" + queue + ")$",
|
||||
"read": "^" + queue + "$",
|
||||
}); err != nil {
|
||||
return fmt.Errorf("cannot scope the broker account for %s: %w", node, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateBuilderAccount scopes an account to taking build work and answering it.
|
||||
//
|
||||
// **A build machine is not a node**, and giving it a node's account would let it read another
|
||||
// machine's declarations. What it needs is narrower and different: read the build queue, and
|
||||
// write to the exchange and to whatever temporary queue an asker is waiting on.
|
||||
//
|
||||
// The reply queues are the reason `write` is not simply the exchange. `RequestBuild` declares an
|
||||
// exclusive queue with a generated name and waits on it, so a builder that could not write to it
|
||||
// could take work and never answer — which is the failure that looks like a builder that is not
|
||||
// running.
|
||||
func (m *Management) CreateBuilderAccount(ctx context.Context, name, password string) error {
|
||||
if !safeName.MatchString(name) {
|
||||
return fmt.Errorf(
|
||||
"%q cannot be a broker account name: it becomes part of a permission pattern, so it "+
|
||||
"is lower-case letters, digits and dashes", name)
|
||||
}
|
||||
|
||||
if err := m.put(ctx, "/api/users/"+url.PathEscape(name),
|
||||
map[string]string{"password": password, "tags": ""}); err != nil {
|
||||
return fmt.Errorf("cannot create the broker account for %s: %w", name, err)
|
||||
}
|
||||
|
||||
builds := regexp.QuoteMeta(BuildQueueName)
|
||||
if err := m.put(ctx, "/api/permissions/%2f/"+url.PathEscape(name), map[string]string{
|
||||
// It declares the build queue, because whichever builder starts first must be able to —
|
||||
// and a queue nobody may declare is a queue that exists only if the control plane has
|
||||
// already run, which makes the order they start in matter.
|
||||
"configure": "^" + builds + "$",
|
||||
// Two exchanges, and nothing else. **Not the default exchange**: permission there is
|
||||
// granted per exchange rather than per queue, so a builder allowed to use it could
|
||||
// publish into any node's queue — the privilege a build machine most obviously should
|
||||
// not have. Answers go through the node exchange; announcing what was built goes through
|
||||
// the events exchange, which is a different act with a different audience (novox/hq
|
||||
// ADR 0072). A builder that could answer and not announce would leave the module graph
|
||||
// knowing less than the registry does.
|
||||
"write": "^(" + regexp.QuoteMeta(ExchangeName) + "|" + regexp.QuoteMeta(EventsExchangeName) + ")$",
|
||||
// The build queue and nothing else. Not another machine's declarations.
|
||||
"read": "^" + builds + "$",
|
||||
}); err != nil {
|
||||
return fmt.Errorf("cannot scope the broker account for %s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveNodeAccount withdraws a node's access.
|
||||
func (m *Management) RemoveNodeAccount(ctx context.Context, node string) error {
|
||||
if !safeName.MatchString(node) {
|
||||
return fmt.Errorf("%q is not a broker account name", node)
|
||||
}
|
||||
return m.do(ctx, http.MethodDelete, "/api/users/"+url.PathEscape(node), nil)
|
||||
}
|
||||
|
||||
// Accounts lists the broker's users, so a picture can be read from the system rather than assumed
|
||||
// (novox/hq ADR 0018).
|
||||
func (m *Management) Accounts(ctx context.Context) ([]string, error) {
|
||||
body, err := m.get(ctx, "/api/users")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var users []struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &users); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, 0, len(users))
|
||||
for _, u := range users {
|
||||
names = append(names, u.Name)
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (m *Management) put(ctx context.Context, path string, body any) error {
|
||||
return m.do(ctx, http.MethodPut, path, body)
|
||||
}
|
||||
|
||||
func (m *Management) post(ctx context.Context, path string, body any) error {
|
||||
return m.do(ctx, http.MethodPost, path, body)
|
||||
}
|
||||
|
||||
func (m *Management) get(ctx context.Context, path string) ([]byte, error) {
|
||||
request, err := m.request(ctx, http.MethodGet, path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response, err := m.client.Do(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("the broker's management API answered %s to GET %s",
|
||||
response.Status, path)
|
||||
}
|
||||
return io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
}
|
||||
|
||||
func (m *Management) do(ctx context.Context, method, path string, body any) error {
|
||||
request, err := m.request(ctx, method, path, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := m.client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode >= 300 {
|
||||
detail, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||
return fmt.Errorf("the broker's management API answered %s to %s %s: %s",
|
||||
response.Status, method, path, strings.TrimSpace(string(detail)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Management) request(ctx context.Context, method, path string, body any) (*http.Request, error) {
|
||||
var payload io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload = bytes.NewReader(raw)
|
||||
}
|
||||
|
||||
// Path joined by hand rather than through url.Parse: %2f is the default vhost and must reach
|
||||
// the broker still encoded. Parsing would decode it to a slash and address a different route.
|
||||
target := strings.TrimSuffix(m.base.String(), "/")
|
||||
if user := m.base.User; user != nil {
|
||||
target = strings.TrimSuffix(m.base.Scheme+"://"+m.base.Host, "/")
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, method, target+path, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user := m.base.User; user != nil {
|
||||
password, _ := user.Password()
|
||||
request.SetBasicAuth(user.Username(), password)
|
||||
}
|
||||
if body != nil {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package broker_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
)
|
||||
|
||||
// The audit logger consumes everything and emits nothing. Its account must let it declare and read
|
||||
// its own queue and read the events exchange to bind onto — and must not reach another module's
|
||||
// queue, nor grant any write to the events exchange (novox/hq ADR 0043).
|
||||
func TestAConsumerReadsItsOwnQueueAndTheEventsExchangeAndNoOthers(t *testing.T) {
|
||||
// Rebuilt through CreateModuleAccount's own path by asking for the same scope it would apply.
|
||||
// The queue this module reads:
|
||||
mine := broker.ModuleQueueFor("anchor", "audit-logger")
|
||||
other := broker.ModuleQueueFor("anchor", "plex")
|
||||
|
||||
read := scope(t, "read", "anchor", "audit-logger", nil, []string{"#"})
|
||||
if !read.MatchString(mine) {
|
||||
t.Error("the audit logger may not read its own queue, so it consumes nothing")
|
||||
}
|
||||
if !read.MatchString(broker.EventsExchangeName) {
|
||||
t.Error("the audit logger may not read the events exchange, so it cannot bind onto it")
|
||||
}
|
||||
if read.MatchString(other) {
|
||||
t.Error("the audit logger may read another module's queue")
|
||||
}
|
||||
|
||||
// It emits nothing, so it is granted no write to the events exchange — only its own queue, to bind.
|
||||
write := scope(t, "write", "anchor", "audit-logger", nil, []string{"#"})
|
||||
if write.MatchString(broker.EventsExchangeName) {
|
||||
t.Error("a pure consumer was granted write to the events exchange")
|
||||
}
|
||||
if !write.MatchString(mine) {
|
||||
t.Error("the audit logger may not write to its own queue, so it cannot bind it")
|
||||
}
|
||||
}
|
||||
|
||||
// An emitter is granted the events exchange to write; a consumer is not.
|
||||
func TestAnEmitterMayWriteTheEventsExchangeAndAConsumerMayNot(t *testing.T) {
|
||||
emitter := scope(t, "write", "anchor", "umami", []string{"module.umami.site.created"}, nil)
|
||||
if !emitter.MatchString(broker.EventsExchangeName) {
|
||||
t.Error("an emitting module may not write the events exchange, so it cannot emit")
|
||||
}
|
||||
}
|
||||
|
||||
// scope reconstructs one of the three permission patterns CreateModuleAccount would apply, by
|
||||
// reading it back from a captured request against a stub management API.
|
||||
func scope(t *testing.T, which, node, module string, emits, consumes []string) *regexp.Regexp {
|
||||
t.Helper()
|
||||
pat := capturePermission(t, which, node, module, emits, consumes)
|
||||
re, err := regexp.Compile(pat)
|
||||
if err != nil {
|
||||
t.Fatalf("the %s pattern does not compile: %v", which, err)
|
||||
}
|
||||
return re
|
||||
}
|
||||
|
||||
// capturePermission runs CreateModuleAccount against a stub management API and returns the pattern
|
||||
// it set for `which` ("configure"/"write"/"read"). The scope is tested where it is applied, not
|
||||
// reconstructed by the test — so a change to the mapping cannot pass a test that hard-codes the old
|
||||
// one.
|
||||
func capturePermission(t *testing.T, which, node, module string, emits, consumes []string) string {
|
||||
t.Helper()
|
||||
var captured map[string]string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/permissions/") {
|
||||
_ = json.NewDecoder(r.Body).Decode(&captured)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
t.Setenv(broker.ManagementVar, server.URL)
|
||||
m, err := broker.ManagementFromEnvironment()
|
||||
if err != nil {
|
||||
t.Fatalf("stub management not usable: %v", err)
|
||||
}
|
||||
if _, err := m.CreateModuleAccount(context.Background(), node, module, "pw", emits, consumes); err != nil {
|
||||
t.Fatalf("CreateModuleAccount: %v", err)
|
||||
}
|
||||
if captured == nil {
|
||||
t.Fatal("no permissions were set")
|
||||
}
|
||||
pattern, ok := captured[which]
|
||||
if !ok {
|
||||
t.Fatalf("no %s permission was set; got %v", which, captured)
|
||||
}
|
||||
return pattern
|
||||
}
|
||||
@@ -0,0 +1,666 @@
|
||||
// Composing the bus's own configuration.
|
||||
//
|
||||
// An account is *composed*, never called for: the controller writes accounts, users and
|
||||
// per-subject permissions into one file the host keeps current, and the server reloads it in
|
||||
// place (novox/hq ADR 0106 — never through a management API; design 25 §4).
|
||||
//
|
||||
// Everything here is pure. Given the principals, it returns the file's text — so the whole of the
|
||||
// mesh's authority model is testable as strings, with no server.
|
||||
//
|
||||
// **Permissions are per subject, so a module's own name is the server's to enforce.** ADR 0042
|
||||
// reserves a module's origin — it publishes only under its own name — and here that is a refusal
|
||||
// rather than something a library promises.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A Kind is what a principal is, which decides the shape of its authority rather than its
|
||||
// contents: a module's comes from its declaration, a host's from its node, and the controller's
|
||||
// and the enrolment user's are fixed.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindModule Kind = "module"
|
||||
KindNode Kind = "node"
|
||||
KindController Kind = "controller"
|
||||
KindEnrolment Kind = "enrolment"
|
||||
// KindPerson is somebody reaching the mesh's tools from a workstation (design 25 §7). Its
|
||||
// authority is a list of tools and nothing else — not control, not declarations, not builds,
|
||||
// and no ability to answer anything, because a person asks.
|
||||
KindPerson Kind = "person"
|
||||
)
|
||||
|
||||
// Seat is a role on the bus as a principal relates to it: the subjects it accepts, and those it
|
||||
// emits (novox/hq ADR 0118, design 29 §5).
|
||||
type Seat struct {
|
||||
Name string
|
||||
// Scope is where the seat has one holder. A node-scoped seat's tool carries the node in its
|
||||
// subject, because one subject reaching six machines' holders is not an address
|
||||
// (novox/hq ADR 0132, design 33 §4). Empty reads as mesh.
|
||||
Scope string
|
||||
Accepts []string
|
||||
Emits []string
|
||||
Serves []string
|
||||
Versions []string // protocol versions served beside the current one; empty for v1 only
|
||||
}
|
||||
|
||||
// A Principal is one user of the bus. Its permissions are derived from what it declares and
|
||||
// nothing else (novox/hq ADR 0043), over the three namespaces of design 29 §2: its own, the seats
|
||||
// it holds, and the seats it uses.
|
||||
type Principal struct {
|
||||
Kind Kind
|
||||
Node string
|
||||
Module string
|
||||
|
||||
Emits []string
|
||||
Consumes []string
|
||||
Serves []string
|
||||
|
||||
Holds []Seat
|
||||
Uses []Seat
|
||||
// Watches are seats whose events this principal consumes. Separate from Consumes because a
|
||||
// role's event lives under the seat's namespace and not a module's, and this package cannot tell
|
||||
// a seat's name from a module's by looking at it — whoever resolved the declaration can, and
|
||||
// does (novox/hq ADR 0121).
|
||||
//
|
||||
// **Found by a consumer reading nothing.** The catalogue consumes the build machine's outcome;
|
||||
// with that name read as a module's, its subscription pointed at `mesh.mod.mesh-build-machine.…`,
|
||||
// a namespace no such module owns. Every service started and the graph stayed empty.
|
||||
Watches []Seat
|
||||
|
||||
// Invokes are the tools this principal may call, as `<module>.<tool>`; a single `*` is every
|
||||
// tool. A person's whole authority (design 25 §7), and a module's only if its manifest says so
|
||||
// (novox/hq ADR 0152) — the console's does, and nothing else's.
|
||||
//
|
||||
// **A list, not a role.** A person is not a module and holds no seat: nothing is addressed
|
||||
// to them, nothing is delivered to them, and they have no durable consumer to acknowledge.
|
||||
// What they have is permission to ask. A module that invokes gains exactly the same
|
||||
// permission and nothing beside it.
|
||||
Invokes []string
|
||||
|
||||
// PasswordHash is the bcrypt hash the mesh minted. The plaintext is sealed to the principal
|
||||
// and never appears here: this file is written to a node's disk and read by a server, and a
|
||||
// secret that can be read from a configuration file is a secret with a wider blast radius
|
||||
// than the one it protects (novox/hq design 29 §10).
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
// meshSeatsTheControllerUses are the roles the mesh's own flows submit work to. Named rather than
|
||||
// derived from the seat set: the controller is not a module and declares no `uses`, so its side of a
|
||||
// seat has to be stated, and a list is what makes "which roles does the mesh itself talk to" answerable.
|
||||
var meshSeatsTheControllerUses = []string{"mesh-build-machine"}
|
||||
|
||||
// enrolmentPrefix is the space every enrolling node's user and inbox live under, so the one place the
|
||||
// controller may answer an enrolment is derived from the same constant the user is named from.
|
||||
const enrolmentPrefix = "enrol"
|
||||
|
||||
// safeSubject refuses anything that would change the meaning of a subject rather than sit inside
|
||||
// one. A name carrying a dot would silently widen a permission by adding a token; a name carrying
|
||||
// `>` or `*` would widen it to a wildcard, which is the whole authority model gone.
|
||||
var safeSubject = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
|
||||
// Username is how a principal is named to the server. The node is part of it, so the same module
|
||||
// on two machines holds two users, each sealed to its own — the rule management.go already
|
||||
// applies, kept.
|
||||
func (p Principal) Username() string {
|
||||
switch p.Kind {
|
||||
case KindPerson:
|
||||
return "person." + p.Module
|
||||
case KindModule:
|
||||
return p.Node + "." + p.Module
|
||||
case KindNode:
|
||||
return "node." + p.Node
|
||||
case KindController:
|
||||
return "controller"
|
||||
case KindEnrolment:
|
||||
// Per token, not one shared user. **The inbox is the reason**: with a single `enrolment`
|
||||
// user every machine enrolling at once could read every other's answer, and an answer
|
||||
// carries that node's credentials sealed to it. Design 25 §6 says the inbox a token
|
||||
// derives, and a permission belongs to a user, so the user is per token.
|
||||
//
|
||||
// Named after the node, which **is** the token's id: a token is issued for a node record,
|
||||
// the mesh holds one live claim per record, and the node's name is the one identifier both
|
||||
// sides already have before anything else is agreed. It is also exactly what the other
|
||||
// transport does, where the account is named after the node and the secret is its password.
|
||||
return enrolmentPrefix + "." + p.Node
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// inbox is a principal's own reply space. No user is ever granted a bare `_INBOX.>` (design 25
|
||||
// §4): with one account, inbox privacy is the permission list or it is nothing, so each user's
|
||||
// inbox is derived from its own identity and its permissions name that prefix and no other.
|
||||
func (p Principal) inbox() string { return "_INBOX." + p.Username() + ".>" }
|
||||
|
||||
// Permissions is what a principal may publish and subscribe, and whether it may answer.
|
||||
type Permissions struct {
|
||||
Publish []string
|
||||
Subscribe []string
|
||||
// AllowResponses lets a principal reply to a request it received, on the reply subject that
|
||||
// request carried, once.
|
||||
//
|
||||
// **This is what makes scoped inboxes possible at all**, and design 25 §4 did not say it. If
|
||||
// every user's inbox is private to it, a module serving a tool cannot publish the answer —
|
||||
// the answer goes to the *caller's* inbox, which the responder has no permission for. The two
|
||||
// ways out are granting responders `_INBOX.>`, which is precisely the blanket grant §4
|
||||
// refuses, or this: the server itself permits one reply to the subject of a message the user
|
||||
// actually received, and nothing else. The authority is bounded by having been asked.
|
||||
AllowResponses bool
|
||||
}
|
||||
|
||||
// PermissionsFor derives a principal's authority. Pure, and the only place authority is decided:
|
||||
// a permission that cannot be derived from a declaration is a permission nobody can explain.
|
||||
func PermissionsFor(p Principal) (Permissions, error) {
|
||||
for _, part := range []struct{ what, value string }{
|
||||
{"node", p.Node}, {"module", p.Module},
|
||||
} {
|
||||
if part.value == "" {
|
||||
continue
|
||||
}
|
||||
if !safeSubject.MatchString(part.value) {
|
||||
return Permissions{}, fmt.Errorf(
|
||||
"%q cannot be part of a subject: a permission is a subject pattern, and this would widen it", part.value)
|
||||
}
|
||||
}
|
||||
|
||||
var pub, sub []string
|
||||
switch p.Kind {
|
||||
case KindController:
|
||||
// The controller owns the mesh's own traffic and the streams. It is the only writer of
|
||||
// stream definitions (design 25 §3), so it alone reaches the JetStream API.
|
||||
pub = []string{"mesh.control.>", "mesh.node.>", "$JS.API.>"}
|
||||
// **And where its consumers deliver.** A push consumer delivers on `_DELIVER.<its name>`,
|
||||
// and a client bound to it subscribes exactly that; the server refused it for every
|
||||
// principal the first time one bound a consumer (2026-09-28). Each kind below is granted
|
||||
// its own consumers' delivery subjects and no other's.
|
||||
sub = []string{"mesh.control.>", "$JS.API.>", "_DELIVER." + ControllerName, "_DELIVER." + ControllerName + ".>"}
|
||||
|
||||
// Work the mesh's own flows submit to a role, and the outcomes they wait on (ADR 0121). A
|
||||
// build is the one today: the controller asks, and reads the answer from the seat's event
|
||||
// like the catalogue does — which is why no holder needs to publish into anybody's inbox.
|
||||
for _, seat := range meshSeatsTheControllerUses {
|
||||
pub = append(pub, "mesh.seat."+seat+".accept.>")
|
||||
}
|
||||
// **And what the mesh says it did** (novox/hq ADR 0134). The control plane states its own
|
||||
// facts under the seat it holds, because a role's events belong to the role and keep their
|
||||
// address while the holder is replaced. Named one by one rather than as a whole namespace:
|
||||
// least authority, and a fact nothing states is authority nobody uses.
|
||||
for _, event := range ControllerStates {
|
||||
pub = append(pub, seatEventSubject(ControllerSeat, event))
|
||||
}
|
||||
|
||||
// Every module's tools: **the control plane is the way in** (novox/hq ADR 0095). A person
|
||||
// or an agent asks through it and every question passes one process where an audit
|
||||
// belongs — so it, alone among principals, may call any tool by name. The first `ask` on
|
||||
// the new bus was refused the publish (2026-09-28).
|
||||
pub = append(pub, "mesh.mod.*.tool.>")
|
||||
|
||||
// **And the mesh's own verbs, as the seat it holds** (novox/hq ADR 0132, ADR 0154):
|
||||
// `status`, `push`, `assign` are the mesh-controller seat's tools, served by its holder. The
|
||||
// whole verb namespace of its own seat rather than a list: the list is the seat's protocol,
|
||||
// which this package mirrors rather than reads, and a verb the seat does not declare is a
|
||||
// subject nothing publishes.
|
||||
sub = append(sub, "mesh.seat."+ControllerSeat+".tool.>")
|
||||
|
||||
// The two events it reacts to, and its ack subject on the stream they arrive from
|
||||
// (streams.go). **Each named, not a pattern**: `mesh.mod.*.event.>` would make the
|
||||
// controller a subscriber to every event in the mesh, and its permission list would stop
|
||||
// saying what it is for. The ack grant below is scoped per stream because the controller's
|
||||
// consumer name is the same on both and `$JS.ACK.CONTROL.controller.>` does not cover a
|
||||
// delivery from EVENTS — a consumer that cannot ack has every message redelivered for
|
||||
// ever, refused by the list it already has.
|
||||
sub = append(sub, ControllerFollows...)
|
||||
pub = append(pub, "$JS.ACK.EVENTS."+ControllerName+".>")
|
||||
|
||||
// **Where an enrolment's answer goes**, and `allow_responses` does not cover it. That
|
||||
// permits one reply to the reply subject of a message the user received — and a message a
|
||||
// JetStream consumer delivers has had that field claimed for the consumer's own ack address
|
||||
// (design 25 §2), so the address the controller actually answers is the one the request
|
||||
// carried in its payload, which is not a reply subject as the server understands it.
|
||||
//
|
||||
// Verified against a real server before this line existed: the answer was refused with
|
||||
// "Permissions Violation for Publish to _INBOX.enrol.anchor…", and every enrolment on the
|
||||
// mesh would have timed out while the controller logged success.
|
||||
//
|
||||
// **The enrolment inbox space, not a blanket `_INBOX.>`.** Design 25 §4 refuses that, and
|
||||
// this is not it: nothing but an enrolling node ever subscribes under this prefix, each
|
||||
// scoped to its own token's, so the controller publishing here is the mesh answering
|
||||
// enrolments and can reach nothing else.
|
||||
pub = append(pub, "_INBOX."+enrolmentPrefix+".>")
|
||||
|
||||
case KindPerson:
|
||||
// Tools, and nothing else. Every subject a person may publish is a tool call; a person
|
||||
// who could publish an event would be able to claim a module said something.
|
||||
invoked, err := invokedSubjects(p.Invokes)
|
||||
if err != nil {
|
||||
return Permissions{}, err
|
||||
}
|
||||
pub = append(pub, invoked...)
|
||||
|
||||
case KindEnrolment:
|
||||
// A leaked token is useless for anything but enrolling: it cannot read a declaration, hear
|
||||
// an event, or subscribe any inbox but the one its own token derives (design 25 §6).
|
||||
//
|
||||
// **The inbox was missing and the handshake could not have completed without it.** An
|
||||
// enrolling node publishes its request and waits on an address it states in the payload;
|
||||
// with nothing to subscribe it waits out its timeout against a mesh that answered. Its own
|
||||
// and no wider: `_INBOX.enrol.<node>.>`, so what is sealed to one machine cannot be read by
|
||||
// another enrolling beside it.
|
||||
if p.Node == "" {
|
||||
// Refused rather than composed into `_INBOX.enrol..>`, which is a subject with an empty
|
||||
// token in it — and worse, one every nameless enrolment user would share. A shared
|
||||
// enrolment inbox is one machine able to read the credentials sealed to another.
|
||||
return Permissions{}, errors.New(
|
||||
"an enrolment user names no node, so its inbox would be shared with every other " +
|
||||
"enrolment: a token is issued for a node record, and that record's name is " +
|
||||
"the token's id")
|
||||
}
|
||||
pub = []string{"mesh.control.enrol"}
|
||||
sub = []string{p.inbox()}
|
||||
|
||||
case KindNode:
|
||||
// A host publishes its own node's control traffic and subscribes its own declaration —
|
||||
// and nothing of any other node's.
|
||||
// And binding to its consumer, which asks the server about it (CONSUMER.INFO) — the one
|
||||
// thing the host does that nothing granted. Found the first time a machine dialled a
|
||||
// permissioned server: "this node cannot read its declarations" (2026-09-28). The ack and
|
||||
// the inbox are granted below with every principal's.
|
||||
pub = []string{
|
||||
"mesh.control." + p.Node + ".>",
|
||||
"$JS.API.CONSUMER.INFO.NODES." + p.Node,
|
||||
}
|
||||
// The deliver subject carries the stream as well as the consumer's name, so what a
|
||||
// subscriber is permitted has to carry it too (novox/hq 04-ISSUES/146). The bare name
|
||||
// stays: an existing consumer keeps delivering where it always did until the controller's
|
||||
// next assertion moves it, and a permission that only allowed the new shape would refuse
|
||||
// every node in the mesh for exactly as long as that took.
|
||||
sub = []string{"mesh.node." + p.Node + ".declare",
|
||||
"_DELIVER." + p.Node, "_DELIVER." + p.Node + ".>"}
|
||||
|
||||
case KindModule:
|
||||
// 1. Its own namespace: it publishes its events there and serves its tools there. Nothing
|
||||
// else may publish into it, so an event's source is a fact the server enforces rather
|
||||
// than a claim in the body (design 29 §2).
|
||||
own := "mesh.mod." + p.Module
|
||||
for _, e := range p.Emits {
|
||||
pub = append(pub, own+".event."+e)
|
||||
}
|
||||
// Every tool under its own name, not a list: the tools a module serves are what its code
|
||||
// answers, and a second copy of that list in the manifest would be a second source of
|
||||
// truth for the mesh to keep in step (2026-09-28: every module that served a tool was
|
||||
// refused the subscription, because none had written the list twice). Nothing is given
|
||||
// away — no other principal may subscribe this namespace, and a caller's authority is
|
||||
// still granted per tool, by name, on the publish side.
|
||||
sub = append(sub, own+".tool.>")
|
||||
|
||||
// 1b. The tools it calls, if its manifest says it calls any (novox/hq ADR 0152). The same
|
||||
// grant a person gets and derived the same way, so "what may this module ask" is
|
||||
// answered by the one list that answers it for everybody. Publish only: an answer
|
||||
// arrives on its own inbox, which every principal has below.
|
||||
invoked, err := invokedSubjects(p.Invokes)
|
||||
if err != nil {
|
||||
return Permissions{}, err
|
||||
}
|
||||
pub = append(pub, invoked...)
|
||||
|
||||
// 2. What it consumes, by the emitter's own subject — an event is addressed to its
|
||||
// emitter, because the emitter's identity is the meaning (ADR 0118).
|
||||
for _, c := range p.Consumes {
|
||||
subject, err := consumedSubject(c)
|
||||
if err != nil {
|
||||
return Permissions{}, err
|
||||
}
|
||||
sub = append(sub, subject)
|
||||
}
|
||||
|
||||
// 2b. Events of a role it watches, under the seat's own namespace. Subscribe only: watching a
|
||||
// role is hearing what it announced, not taking part in it.
|
||||
for _, w := range p.Watches {
|
||||
for _, e := range w.Emits {
|
||||
sub = append(sub, seatSubject(w, "event", e))
|
||||
}
|
||||
}
|
||||
|
||||
// 2c. Its own consumer, which it **pulls**: the runtime asks for the next message and is
|
||||
// answered on its own inbox, so what it needs is to ask about the consumer and to ask it
|
||||
// for messages — its own consumer's name, and no other's. Pulled rather than pushed
|
||||
// because that is the one shape a runtime's client binds without creating anything; the
|
||||
// controller and the hosts are pushed to. Named here rather than through ConsumerFor,
|
||||
// which asks for these permissions to build the consumer and would ask forever. A
|
||||
// subject for a consumer that turns out not to exist grants nothing anybody can use.
|
||||
pub = append(pub,
|
||||
"$JS.API.CONSUMER.INFO."+consumerStream(p)+"."+consumerDurable(p),
|
||||
"$JS.API.CONSUMER.MSG.NEXT."+consumerStream(p)+"."+consumerDurable(p))
|
||||
|
||||
// 3. Seats it holds: full participation.
|
||||
for _, s := range p.Holds {
|
||||
// Taking work from the role's queue: the worker consumer it binds (asked about,
|
||||
// delivered on, acknowledged), each on the seat's own stream. The first machine to
|
||||
// take work over the new bus was refused the asking (2026-09-28).
|
||||
worker := "SEAT_" + upperSnake(s.Name) + "_worker"
|
||||
stream := seatStreamName(s.Name)
|
||||
sub = append(sub, "_DELIVER."+worker, "_DELIVER."+worker+".>")
|
||||
pub = append(pub, "$JS.API.CONSUMER.INFO."+stream+"."+worker, "$JS.ACK."+stream+"."+worker+".>")
|
||||
for _, a := range s.Accepts {
|
||||
sub = append(sub, seatSubject(s, "accept", a))
|
||||
}
|
||||
for _, e := range s.Emits {
|
||||
pub = append(pub, seatSubject(s, "event", e))
|
||||
}
|
||||
for _, t := range s.Serves {
|
||||
sub = append(sub, seatToolSubject(s, t, p.Node))
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Seats it uses: publish only, and only the accepts half. A caller cannot subscribe a
|
||||
// seat's inbound subject and watch other modules' traffic, nor publish its outbound
|
||||
// events and lie about outcomes (design 29 §2).
|
||||
for _, s := range p.Uses {
|
||||
for _, a := range s.Accepts {
|
||||
pub = append(pub, seatSubject(s, "accept", a))
|
||||
}
|
||||
for _, t := range s.Serves {
|
||||
pub = append(pub, seatToolSubject(s, t, "*"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if p.Kind == KindPerson {
|
||||
// An inbox to hear answers in, and nothing else. No ack subject: a person has no durable
|
||||
// consumer, because nothing is delivered to a person — they ask and are answered.
|
||||
sub = append(sub, p.inbox())
|
||||
}
|
||||
|
||||
if p.Kind == KindModule || p.Kind == KindNode || p.Kind == KindController {
|
||||
// Its own reply space, and nothing wider.
|
||||
sub = append(sub, p.inbox())
|
||||
|
||||
// Acking a JetStream delivery is a publish to that consumer's own ack address — a
|
||||
// different subject from anything the consumer subscribes. Without it every message a
|
||||
// module received would be redelivered forever, refused by the permission list it already
|
||||
// has (design 25 §4). Scoped to this principal's own consumer name, so it can ack its own
|
||||
// deliveries and no other's.
|
||||
pub = append(pub, "$JS.ACK."+consumerStream(p)+"."+consumerDurable(p)+".>")
|
||||
}
|
||||
|
||||
sort.Strings(pub)
|
||||
sort.Strings(sub)
|
||||
return Permissions{
|
||||
Publish: pub,
|
||||
Subscribe: sub,
|
||||
// A module answers what it was asked — a tool call reaches it on its own namespace, so the
|
||||
// authority is bounded by having been asked — and so does the controller. A node and a
|
||||
// person are never asked anything, and are granted nothing here.
|
||||
AllowResponses: p.Kind == KindModule || p.Kind == KindController,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// seatSubject places a seat's verb under the kind of traffic it is.
|
||||
//
|
||||
// **The kind token is load-bearing, not decoration.** A stream is defined by a subject filter, so
|
||||
// without it a stream over a seat or a module's namespace would capture that namespace's *tool*
|
||||
// traffic too — and a tool call must never be persisted (design 25 §3: tools stay on core NATS).
|
||||
// Found while defining the streams: the first draft of design 29 had one namespace per module
|
||||
// with no kind, which reads well and cannot be filtered.
|
||||
//
|
||||
// A seat serving more than its current protocol version carries the version as a token
|
||||
// (design 29 §8): the seat stays one role, and v1 and v2 run beside each other until nothing is
|
||||
// bound to the old one.
|
||||
func seatSubject(s Seat, kind, verb string) string {
|
||||
return "mesh.seat." + s.Name + "." + kind + "." + verb
|
||||
}
|
||||
|
||||
// seatToolSubject is where a role's tool is asked. Mesh-wide for a mesh-scoped seat; a node-scoped
|
||||
// seat carries the node it is asked of, because a flat subject would reach every machine's holder
|
||||
// and the queue group would silently pick a winner (novox/hq ADR 0132, design 33 §4). A holder
|
||||
// subscribes its own node's; a user publishes any node's (`*`) and names the machine in the subject.
|
||||
func seatToolSubject(s Seat, verb, node string) string {
|
||||
base := seatSubject(s, "tool", verb)
|
||||
if s.Scope == "node" && node != "" {
|
||||
return base + "." + node
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// consumerStream and consumerDurable are the two halves of a consumer's identity, and they are
|
||||
// two functions because conflating them was a real bug.
|
||||
//
|
||||
// **A durable name may not contain a dot; an ack subject is built from two names that do.** The
|
||||
// server acknowledges on `$JS.ACK.<stream>.<consumer>.…`, so a single string "EVENTS.one_audit"
|
||||
// reads correctly inside the permission and is rejected as a consumer name — *nats: invalid
|
||||
// consumer name*. Caught against a running server, and worth the comment because the shape of
|
||||
// the failure if it had not been is the one design 25 §4 warns about: a consumer that cannot ack
|
||||
// has every message redelivered forever, and its permission list looks right while it happens.
|
||||
//
|
||||
// They are derived here, beside the permission that must match them, because two places deriving
|
||||
// the same name is how a module ends up unable to ack its own deliveries.
|
||||
// consumedSubject is where a consumed event lands, from the local pattern a module declared.
|
||||
//
|
||||
// **The mesh's wildcards become this transport's** (design 29 §1): `*` is one name on both, and `**`
|
||||
// — the rest — is `>` here. A module writes neither transport's spelling, so a manifest stays correct
|
||||
// when the wire changes, which is the whole reason names are local.
|
||||
//
|
||||
// `**` on its own is every event from every module: the emitter is any, the event is anything. An
|
||||
// audit logger wants exactly that and says so in one token.
|
||||
func consumedSubject(pattern string) (string, error) {
|
||||
if pattern == catalogueTheRest {
|
||||
return "mesh.mod.*.event.>", nil
|
||||
}
|
||||
emitter, event, named := strings.Cut(pattern, ".")
|
||||
if !named || emitter == "" || event == "" {
|
||||
return "", fmt.Errorf(
|
||||
"%q does not name an emitter and an event: a consumed event is <emitter>.<event>, or "+
|
||||
"%q for every event", pattern, catalogueTheRest)
|
||||
}
|
||||
if emitter == catalogueTheRest {
|
||||
return "", fmt.Errorf("%q stands for the rest of a name, so it cannot name the emitter", catalogueTheRest)
|
||||
}
|
||||
// Each name is checked before it becomes a subject: a name carrying a dot would add a token and
|
||||
// silently widen the permission, which is the whole reason safeSubject exists.
|
||||
var out []string
|
||||
for _, part := range strings.Split(event, ".") {
|
||||
switch part {
|
||||
case catalogueTheRest:
|
||||
out = append(out, ">")
|
||||
case "*":
|
||||
out = append(out, "*")
|
||||
default:
|
||||
if !safeSubject.MatchString(part) {
|
||||
return "", fmt.Errorf("%q cannot be part of a subject: it would widen the permission", part)
|
||||
}
|
||||
out = append(out, part)
|
||||
}
|
||||
}
|
||||
if emitter != "*" && !safeSubject.MatchString(emitter) {
|
||||
return "", fmt.Errorf("%q cannot name an emitter: it would widen the permission", emitter)
|
||||
}
|
||||
return "mesh.mod." + emitter + ".event." + strings.Join(out, "."), nil
|
||||
}
|
||||
|
||||
// catalogueTheRest is the mesh's wildcard for "the rest of a name", duplicated from the catalogue
|
||||
// package for the one direction of dependency the build queue's name is duplicated for.
|
||||
const catalogueTheRest = "**"
|
||||
|
||||
func consumerStream(p Principal) string {
|
||||
switch p.Kind {
|
||||
case KindModule:
|
||||
return "EVENTS"
|
||||
case KindNode:
|
||||
return "NODES"
|
||||
case KindController:
|
||||
return "CONTROL"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func consumerDurable(p Principal) string {
|
||||
switch p.Kind {
|
||||
case KindModule:
|
||||
return p.Node + "_" + p.Module
|
||||
case KindNode:
|
||||
return p.Node
|
||||
case KindController:
|
||||
return "controller"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Server is everything the composed file needs that is not a principal.
|
||||
type Server struct {
|
||||
// ClientPort carries TLS itself. There is no plaintext port beside it: a bus reachable
|
||||
// without TLS is one a module can reach without TLS by mistake.
|
||||
ClientPort int
|
||||
MonitoringPort int
|
||||
TLSCert string
|
||||
TLSKey string
|
||||
TLSCA string
|
||||
// StoreDir is a host directory bind, not a named volume — issue 115 is resolved and converted
|
||||
// four modules away from named volumes; the bus's own data is not the place to bring one back.
|
||||
StoreDir string
|
||||
}
|
||||
|
||||
// Compose renders the server's whole configuration. The order is stable and the output is
|
||||
// deterministic, because the file's digest is what the module's entrypoint watches to decide
|
||||
// whether to reload: a composer that reordered a map on each run would signal a reload every time
|
||||
// the controller restarted, for a file that had not changed.
|
||||
func Compose(s Server, principals []Principal) (string, error) {
|
||||
sorted := append([]Principal(nil), principals...)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Username() < sorted[j].Username() })
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("# Composed by the mesh controller. Do not edit: the next composition overwrites it.\n")
|
||||
b.WriteString("# Accounts and permissions are derived from what each module declares and nothing\n")
|
||||
b.WriteString("# else (novox/hq ADR 0043, design 29 §2).\n\n")
|
||||
|
||||
fmt.Fprintf(&b, "port: %d\n", s.ClientPort)
|
||||
fmt.Fprintf(&b, "http: 127.0.0.1:%d\n\n", s.MonitoringPort)
|
||||
|
||||
// **No `verify`, and it said `verify: true` until this configuration was run.** That setting
|
||||
// makes the server demand a *client* certificate, and nothing in the mesh presents one: a host
|
||||
// pins this server's exact certificate and authenticates with the password the mesh minted
|
||||
// (ADR 0004, design 25 §4), and so does a module's runtime. With it on, every connection in the
|
||||
// mesh is refused at the TLS handshake before any password is looked at, and the error —
|
||||
// "client didn't provide a certificate" — reads as a fault in the client.
|
||||
//
|
||||
// TLS is still required: the block is what requires it, and verify only decides whether client
|
||||
// certificates are checked.
|
||||
b.WriteString("tls {\n")
|
||||
fmt.Fprintf(&b, " cert_file: %q\n", s.TLSCert)
|
||||
fmt.Fprintf(&b, " key_file: %q\n", s.TLSKey)
|
||||
fmt.Fprintf(&b, " ca_file: %q\n", s.TLSCA)
|
||||
b.WriteString("}\n\n")
|
||||
|
||||
b.WriteString("jetstream {\n")
|
||||
fmt.Fprintf(&b, " store_dir: %q\n", s.StoreDir)
|
||||
b.WriteString("}\n\n")
|
||||
|
||||
accounts, err := ComposeAccounts(sorted)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
b.WriteString(accounts)
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// ComposeAccounts is the accounts block alone — every user, and nothing about the server.
|
||||
//
|
||||
// **This is the only part of the configuration the mesh writes, and the split is deliberate.** A
|
||||
// server's ports, its TLS paths and its store directory are properties of the container the module
|
||||
// raises: they live in its image and its mounts, and they change when it does. The controller has no
|
||||
// business knowing them, and a controller that did would have to be kept in step with a Dockerfile
|
||||
// it never sees. What only the mesh knows is *who may connect*, so that is what it writes, and the
|
||||
// module's own configuration includes it.
|
||||
//
|
||||
// Four things checked against a running server before this shape was committed to: a user in an
|
||||
// included file authenticates; an unknown user is refused, so the include is the whole authority
|
||||
// rather than an addition to something; a publish outside a user's grant is refused; and rewriting
|
||||
// this file alone and signalling a reload makes a new user appear **without dropping the connection
|
||||
// the mesh already has** — which is what makes every later account, permission or person change cost
|
||||
// nothing (task 1.2's payoff).
|
||||
func ComposeAccounts(principals []Principal) (string, error) {
|
||||
sorted := append([]Principal(nil), principals...)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Username() < sorted[j].Username() })
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("# The mesh's users, composed by the controller. Do not edit: the next\n")
|
||||
b.WriteString("# composition overwrites it. Permissions are derived from what each module\n")
|
||||
b.WriteString("# declares and nothing else (novox/hq ADR 0043, design 29 §2).\n\n")
|
||||
|
||||
// One account for the mesh: accounts in NATS isolate subject spaces entirely, and the mesh is
|
||||
// one space (design 25 §4). The cost of that — that permissions are the only isolation — is
|
||||
// paid in the scoping of every inbox and every ack subject.
|
||||
// JetStream is enabled per account once accounts exist at all: with only the global block set,
|
||||
// a user in MESH is told "JetStream not enabled for account" the first time it binds a
|
||||
// consumer, which is the first thing every host does (2026-09-28).
|
||||
b.WriteString("accounts {\n MESH {\n jetstream: enabled\n users = [\n")
|
||||
for _, p := range sorted {
|
||||
perms, err := PermissionsFor(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if p.PasswordHash == "" {
|
||||
return "", fmt.Errorf("%s has no password hash: a user without one is a user anybody is", p.Username())
|
||||
}
|
||||
fmt.Fprintf(&b, " { user: %q, password: %q, permissions: {\n", p.Username(), p.PasswordHash)
|
||||
fmt.Fprintf(&b, " publish: { allow: [%s] }\n", quoted(perms.Publish))
|
||||
fmt.Fprintf(&b, " subscribe: { allow: [%s] }\n", quoted(perms.Subscribe))
|
||||
if perms.AllowResponses {
|
||||
b.WriteString(" allow_responses: { max: 1, ttl: \"1m\" }\n")
|
||||
}
|
||||
b.WriteString(" } }\n")
|
||||
}
|
||||
b.WriteString(" ]\n }\n}\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func quoted(values []string) string {
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
out := make([]string, len(values))
|
||||
for i, v := range values {
|
||||
out[i] = fmt.Sprintf("%q", v)
|
||||
}
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
// invokedSubjects is the publish side of a grant to call tools: one subject per `<module>.<tool>`,
|
||||
// or the whole tool namespace for `*`. A person's authority and a module's `invokes` are both this
|
||||
// (novox/hq ADR 0152), so a malformed entry is refused in one place, before it could be widened into
|
||||
// something that happens to parse.
|
||||
func invokedSubjects(invokes []string) ([]string, error) {
|
||||
var out []string
|
||||
for _, t := range invokes {
|
||||
if t == "*" {
|
||||
// Every module's tools and every role's (novox/hq ADR 0132): a role's verb is a tool
|
||||
// like any other, addressed to the seat instead of a module.
|
||||
out = append(out, "mesh.mod.*.tool.>", "mesh.seat.*.tool.>")
|
||||
continue
|
||||
}
|
||||
if rest, isSeat := strings.CutPrefix(t, "seat:"); isSeat {
|
||||
// A role's tool, `seat:<seat>.<verb>`. Both address shapes, because the grant is
|
||||
// written without knowing the seat's scope: a mesh seat's verb is flat and a node
|
||||
// seat's carries the machine (design 33 §4).
|
||||
seat, verb, ok := strings.Cut(rest, ".")
|
||||
if !ok || seat == "" || verb == "" {
|
||||
return nil, fmt.Errorf(
|
||||
"%q does not name a role's tool: one invokes seat:<seat>.<verb>", t)
|
||||
}
|
||||
out = append(out, "mesh.seat."+seat+".tool."+verb, "mesh.seat."+seat+".tool."+verb+".*")
|
||||
continue
|
||||
}
|
||||
module, tool, ok := strings.Cut(t, ".")
|
||||
if !ok || module == "" || tool == "" {
|
||||
return nil, fmt.Errorf(
|
||||
"%q does not name a tool: one invokes <module>.<tool>, seat:<seat>.<verb>, or * for every one", t)
|
||||
}
|
||||
out = append(out, "mesh.mod."+module+".tool."+tool)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var update = flag.Bool("update", false, "rewrite the golden composition")
|
||||
|
||||
// The composed file is the mesh's whole authority model, so a change to it should be visible in a
|
||||
// review rather than inferred from a diff of Go. The fixture is also the exact text checked
|
||||
// against the real server's parser (`nats-server -t`), which is what says this syntax is the
|
||||
// server's and not one we invented.
|
||||
func TestTheComposedConfigMatchesTheGolden(t *testing.T) {
|
||||
seat := Seat{Name: "telegram-sender", Accepts: []string{"send"}, Emits: []string{"delivered", "failed"}}
|
||||
got, err := Compose(
|
||||
Server{ClientPort: 4222, MonitoringPort: 8222, StoreDir: "/data",
|
||||
TLSCert: "/tls/tls.crt", TLSKey: "/tls/tls.key", TLSCA: "/tls/ca.crt"},
|
||||
[]Principal{
|
||||
{Kind: KindController, PasswordHash: "$2a$11$cccccccccccccccccccccc"},
|
||||
{Kind: KindEnrolment, Node: "one", PasswordHash: "$2a$11$eeeeeeeeeeeeeeeeeeeeee"},
|
||||
{Kind: KindNode, Node: "one", PasswordHash: "$2a$11$nnnnnnnnnnnnnnnnnnnnnn"},
|
||||
{Kind: KindModule, Node: "one", Module: "telegram", Holds: []Seat{seat},
|
||||
Serves: []string{"status"}, PasswordHash: "$2a$11$tttttttttttttttttttttt"},
|
||||
{Kind: KindModule, Node: "two", Module: "shop", Uses: []Seat{seat},
|
||||
Emits: []string{"order.placed"}, PasswordHash: "$2a$11$ssssssssssssssssssssss"},
|
||||
{Kind: KindModule, Node: "two", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed"}, PasswordHash: "$2a$11$aaaaaaaaaaaaaaaaaaaaaa"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
golden := filepath.Join("testdata", "composed.conf")
|
||||
if *update {
|
||||
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
want, err := os.ReadFile(golden)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != string(want) {
|
||||
t.Errorf("composition changed; re-run with -update and read the diff:\n%s", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func has(t *testing.T, subjects []string, want string) {
|
||||
t.Helper()
|
||||
for _, s := range subjects {
|
||||
if s == want {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("expected %q among %v", want, subjects)
|
||||
}
|
||||
|
||||
func hasNot(t *testing.T, subjects []string, unwanted string) {
|
||||
t.Helper()
|
||||
for _, s := range subjects {
|
||||
if s == unwanted {
|
||||
t.Fatalf("did not expect %q among %v", unwanted, subjects)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A module's authority comes from its declaration and nothing else (novox/hq ADR 0043).
|
||||
func TestAModulePublishesOnlyWhatItEmits(t *testing.T) {
|
||||
p := Principal{Kind: KindModule, Node: "one", Module: "billing",
|
||||
Emits: []string{"order.placed"}, PasswordHash: "x"}
|
||||
perms, err := PermissionsFor(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.billing.event.order.placed")
|
||||
hasNot(t, perms.Publish, "mesh.mod.billing.>")
|
||||
hasNot(t, perms.Publish, "mesh.mod.shipping.event.order.placed")
|
||||
}
|
||||
|
||||
// The gap AMQP left open — an emitter granted the events exchange whole — is closed by per-subject
|
||||
// permissions. A module cannot publish under another module's name.
|
||||
func TestAModuleCannotPublishUnderAnothersName(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "billing",
|
||||
Emits: []string{"order.placed"}, PasswordHash: "x"})
|
||||
for _, p := range perms.Publish {
|
||||
if strings.HasPrefix(p, "mesh.mod.") && !strings.HasPrefix(p, "mesh.mod.billing.") {
|
||||
t.Fatalf("billing may publish %q, which is not its own namespace", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A caller of a seat may publish what the seat accepts, and nothing else of it: not its outbound
|
||||
// events, and not a subscription to its inbound queue (design 29 §2).
|
||||
func TestUsingASeatIsPublishOnlyAndInboundOnly(t *testing.T) {
|
||||
seat := Seat{Name: "telegram-sender", Accepts: []string{"send"}, Emits: []string{"delivered", "failed"}}
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "shop",
|
||||
Uses: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, perms.Publish, "mesh.seat.telegram-sender.accept.send")
|
||||
hasNot(t, perms.Publish, "mesh.seat.telegram-sender.event.delivered")
|
||||
hasNot(t, perms.Subscribe, "mesh.seat.telegram-sender.accept.send")
|
||||
}
|
||||
|
||||
// The holder is the mirror image: it consumes what the seat accepts and publishes what it emits.
|
||||
func TestHoldingASeatIsTheMirrorOfUsingIt(t *testing.T) {
|
||||
seat := Seat{Name: "telegram-sender", Accepts: []string{"send"}, Emits: []string{"delivered", "failed"}}
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "telegram",
|
||||
Holds: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, perms.Subscribe, "mesh.seat.telegram-sender.accept.send")
|
||||
has(t, perms.Publish, "mesh.seat.telegram-sender.event.delivered")
|
||||
hasNot(t, perms.Publish, "mesh.seat.telegram-sender.accept.send")
|
||||
}
|
||||
|
||||
// Without an ack permission a durable consumer never really consumes: every message it receives is
|
||||
// redelivered forever, refused by the permission list it already has (design 25 §4).
|
||||
func TestAModuleMayAckItsOwnDeliveriesAndNoOthers(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "billing",
|
||||
Consumes: []string{"shop.order.placed"}, PasswordHash: "x"})
|
||||
has(t, perms.Publish, "$JS.ACK.EVENTS.one_billing.>")
|
||||
hasNot(t, perms.Publish, "$JS.ACK.>")
|
||||
hasNot(t, perms.Publish, "$JS.ACK.EVENTS.one_shop.>")
|
||||
}
|
||||
|
||||
// With one account, inbox privacy is the permission list or it is nothing.
|
||||
func TestAnInboxIsScopedToItsOwner(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "billing", PasswordHash: "x"})
|
||||
has(t, perms.Subscribe, "_INBOX.one.billing.>")
|
||||
hasNot(t, perms.Subscribe, "_INBOX.>")
|
||||
hasNot(t, perms.Subscribe, "_INBOX.one.shop.>")
|
||||
}
|
||||
|
||||
// A responder answers on the caller's inbox, which it has no permission for. allow_responses is
|
||||
// what makes a scoped inbox workable at all — the authority is bounded by having been asked. A
|
||||
// module is asked on its own namespace and may answer; a node and a person are never asked.
|
||||
func TestOnlyWhatCanBeAskedMayAnswer(t *testing.T) {
|
||||
module, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed"}, PasswordHash: "x"})
|
||||
if !module.AllowResponses {
|
||||
t.Fatal("a module cannot answer a tool call on its own namespace")
|
||||
}
|
||||
node, _ := PermissionsFor(Principal{Kind: KindNode, Node: "one", PasswordHash: "x"})
|
||||
if node.AllowResponses {
|
||||
t.Fatal("a node was granted the right to answer, and nothing asks a node anything")
|
||||
}
|
||||
}
|
||||
|
||||
// A module serves every tool under its own name, and no other module's.
|
||||
func TestAModuleServesItsOwnNamespaceAndNoOthers(t *testing.T) {
|
||||
p, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "gitea", PasswordHash: "x"})
|
||||
if !slices.Contains(p.Subscribe, "mesh.mod.gitea.tool.>") {
|
||||
t.Fatalf("a module may not serve its own tools: %v", p.Subscribe)
|
||||
}
|
||||
for _, s := range p.Subscribe {
|
||||
if strings.HasPrefix(s, "mesh.mod.") && !strings.HasPrefix(s, "mesh.mod.gitea.") {
|
||||
t.Fatalf("a module may subscribe another's namespace: %s", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A host reaches its own node's control traffic and its own declaration, and nothing of any
|
||||
// other node's.
|
||||
func TestAHostIsConfinedToItsOwnNode(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindNode, Node: "one", PasswordHash: "x"})
|
||||
has(t, perms.Publish, "mesh.control.one.>")
|
||||
has(t, perms.Subscribe, "mesh.node.one.declare")
|
||||
hasNot(t, perms.Subscribe, "mesh.node.two.declare")
|
||||
hasNot(t, perms.Subscribe, "mesh.node.>")
|
||||
}
|
||||
|
||||
// A leaked enrolment token is useless for anything but enrolling (design 25 §6).
|
||||
func TestTheEnrolmentUserCanOnlyEnrol(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindEnrolment, Node: "anchor", PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(perms.Publish) != 1 || perms.Publish[0] != "mesh.control.enrol" {
|
||||
t.Fatalf("enrolment may publish %v", perms.Publish)
|
||||
}
|
||||
// Its own inbox and nothing else. **Nothing else** is the point: no declaration, no event, and
|
||||
// no other machine's answer — and the inbox itself is needed, because a node that cannot
|
||||
// subscribe one waits out its timeout against a mesh that answered.
|
||||
if len(perms.Subscribe) != 1 || perms.Subscribe[0] != "_INBOX.enrol.anchor.>" {
|
||||
t.Fatalf("enrolment may subscribe %v, which is not its own inbox alone", perms.Subscribe)
|
||||
}
|
||||
}
|
||||
|
||||
// An enrolment user that names no node is refused: its inbox would be an empty subject token, and
|
||||
// one that every nameless enrolment user shared — which is one machine reading the credentials
|
||||
// sealed to another.
|
||||
func TestAnEnrolmentUserWithoutANodeIsRefused(t *testing.T) {
|
||||
if _, err := PermissionsFor(Principal{Kind: KindEnrolment, PasswordHash: "x"}); err == nil {
|
||||
t.Fatal("an enrolment user with no node was composed, so its inbox is shared")
|
||||
}
|
||||
}
|
||||
|
||||
// A name that would widen a permission is refused rather than quietly stretching one.
|
||||
func TestANameThatWouldWidenAPermissionIsRefused(t *testing.T) {
|
||||
for _, bad := range []string{"bill.ing", "billing.>", "*", "bil>ling"} {
|
||||
if _, err := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: bad, PasswordHash: "x"}); err == nil {
|
||||
t.Fatalf("%q was accepted as part of a subject", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The entrypoint reloads on the file's digest changing, so an unchanged mesh must compose an
|
||||
// identical file — otherwise every controller restart signals a reload of the whole bus.
|
||||
func TestComposingTwiceGivesTheSameBytes(t *testing.T) {
|
||||
s := Server{ClientPort: 4222, MonitoringPort: 8222, StoreDir: "/data",
|
||||
TLSCert: "/tls/tls.crt", TLSKey: "/tls/tls.key", TLSCA: "/tls/ca.crt"}
|
||||
ps := []Principal{
|
||||
{Kind: KindModule, Node: "two", Module: "shop", Emits: []string{"order.placed"}, PasswordHash: "b"},
|
||||
{Kind: KindController, PasswordHash: "c"},
|
||||
{Kind: KindModule, Node: "one", Module: "billing", Consumes: []string{"shop.order.placed"}, PasswordHash: "a"},
|
||||
}
|
||||
first, err := Compose(s, ps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shuffled := []Principal{ps[2], ps[0], ps[1]}
|
||||
second, err := Compose(s, shuffled)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatal("composition is order-dependent; every controller restart would reload the bus")
|
||||
}
|
||||
}
|
||||
|
||||
// A user without a password is a user anybody is.
|
||||
func TestAUserWithoutAPasswordIsRefused(t *testing.T) {
|
||||
_, err := Compose(Server{ClientPort: 4222}, []Principal{{Kind: KindController}})
|
||||
if err == nil {
|
||||
t.Fatal("composed a user with no password hash")
|
||||
}
|
||||
}
|
||||
|
||||
// A person reaches the mesh's tools from a workstation (design 25 §7). Their authority is a list
|
||||
// of tools and nothing else.
|
||||
func TestAPersonMayAskOnlyTheToolsTheyWereGiven(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"shop.price", "telegram.status"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.shop.tool.price")
|
||||
has(t, perms.Publish, "mesh.mod.telegram.tool.status")
|
||||
hasNot(t, perms.Publish, "mesh.mod.shop.tool.refund")
|
||||
hasNot(t, perms.Publish, "mesh.mod.*.tool.>")
|
||||
}
|
||||
|
||||
// An administrator gets every tool, which is a different grant and looks like one.
|
||||
func TestAnAdministratorMayAskAnyTool(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
has(t, perms.Publish, "mesh.mod.*.tool.>")
|
||||
}
|
||||
|
||||
// **Nothing but tools.** A person who could publish an event would be able to claim a module
|
||||
// said something; one who could publish control traffic would be a second controller.
|
||||
func TestAPersonReachesNothingButTools(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
for _, p := range perms.Publish {
|
||||
if !strings.Contains(p, ".tool.") {
|
||||
t.Errorf("a person may publish %q, which is not a tool call", p)
|
||||
}
|
||||
}
|
||||
for _, s := range perms.Subscribe {
|
||||
if !strings.HasPrefix(s, "_INBOX.person.") {
|
||||
t.Errorf("a person may subscribe %q; only their own inbox should be reachable", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A person has no durable consumer, because nothing is delivered to a person — so no ack
|
||||
// subject, and an ack permission would be authority over something that does not exist.
|
||||
func TestAPersonHasNoAckSubject(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
for _, p := range perms.Publish {
|
||||
if strings.HasPrefix(p, "$JS.ACK") {
|
||||
t.Errorf("a person was granted %q, and has no consumer to acknowledge", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A person asks and is answered; they never answer. allow_responses would let a person reply to
|
||||
// a request — which, on a bus where anyone may serve a tool, is somebody impersonating a module.
|
||||
func TestAPersonMayNotAnswer(t *testing.T) {
|
||||
perms, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
if perms.AllowResponses {
|
||||
t.Fatal("a person may answer a request, which is impersonating a module")
|
||||
}
|
||||
}
|
||||
|
||||
// Two people do not share an inbox, or one would read the other's answers.
|
||||
func TestTwoPeopleDoNotShareAnInbox(t *testing.T) {
|
||||
a, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "jo", Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
b, _ := PermissionsFor(Principal{Kind: KindPerson, Module: "sam", Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
if a.Subscribe[0] == b.Subscribe[0] {
|
||||
t.Fatalf("both read %s", a.Subscribe[0])
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed grant is refused rather than widened into something that happens to parse.
|
||||
func TestAToolGrantThatNamesNoToolIsRefused(t *testing.T) {
|
||||
if _, err := PermissionsFor(Principal{Kind: KindPerson, Module: "jo",
|
||||
Invokes: []string{"shop"}, PasswordHash: "x"}); err == nil {
|
||||
t.Fatal("a grant naming a module but no tool was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// The controller can answer an enrolment, and reach no other inbox.
|
||||
//
|
||||
// **`allow_responses` does not cover this and that is the trap.** It permits one reply to the reply
|
||||
// subject of a message the user received — and a message a JetStream consumer delivers has had that
|
||||
// field claimed for the consumer's own ack address, so the address the controller actually answers is
|
||||
// the one the request carried in its payload, which the server does not recognise as a reply subject
|
||||
// at all.
|
||||
//
|
||||
// Found against a real server, after a live test on an *unpermissioned* one had passed: every
|
||||
// enrolment on the mesh would have timed out while the controller logged success.
|
||||
func TestTheControllerCanAnswerAnEnrolmentAndReachNoOtherInbox(t *testing.T) {
|
||||
ctl, err := PermissionsFor(Principal{Kind: KindController, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
enrolling, err := PermissionsFor(Principal{Kind: KindEnrolment, Node: "anchor", PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Whatever the enrolling node waits on, the controller must be able to publish to.
|
||||
if len(enrolling.Subscribe) != 1 {
|
||||
t.Fatalf("an enrolling node subscribes %v, and this test knows only how to check one",
|
||||
enrolling.Subscribe)
|
||||
}
|
||||
waitsOn := enrolling.Subscribe[0]
|
||||
if !covers(ctl.Publish, waitsOn) {
|
||||
t.Fatalf("the controller may publish %v, none of which reaches %s — so every enrolment on "+
|
||||
"the mesh times out while the controller logs success", ctl.Publish, waitsOn)
|
||||
}
|
||||
|
||||
// And nothing wider. A node's own inbox and a module's are not the controller's to write into:
|
||||
// that is the blanket grant design 25 §4 refuses.
|
||||
for _, other := range []string{"_INBOX.node.anchor.x", "_INBOX.one.shop.x", "_INBOX.person.ada.x"} {
|
||||
if covers(ctl.Publish, other) {
|
||||
t.Errorf("the controller can publish to %s, which is an inbox privacy the permission "+
|
||||
"list is the only thing protecting", other)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// covers says whether any granted subject pattern admits one concrete subject, with NATS's own
|
||||
// wildcard meanings: `*` is one token, `>` is the rest.
|
||||
func covers(granted []string, subject string) bool {
|
||||
want := strings.Split(subject, ".")
|
||||
for _, pattern := range granted {
|
||||
if admits(strings.Split(pattern, "."), want) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func admits(pattern, subject []string) bool {
|
||||
for i, token := range pattern {
|
||||
if token == ">" {
|
||||
return i < len(subject)
|
||||
}
|
||||
if i >= len(subject) {
|
||||
return false
|
||||
}
|
||||
if token != "*" && token != subject[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(pattern) == len(subject)
|
||||
}
|
||||
|
||||
// A module pulls its own consumer — asks about it, asks it for messages — and no other module's.
|
||||
func TestAModulePullsItsOwnConsumerAndNoOthers(t *testing.T) {
|
||||
p, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "audit",
|
||||
Consumes: []string{"shop.order.placed"}, PasswordHash: "x"})
|
||||
for _, want := range []string{"$JS.API.CONSUMER.INFO.EVENTS.one_audit", "$JS.API.CONSUMER.MSG.NEXT.EVENTS.one_audit"} {
|
||||
if !slices.Contains(p.Publish, want) {
|
||||
t.Errorf("a module cannot bind its own consumer: %v lacks %s", p.Publish, want)
|
||||
}
|
||||
}
|
||||
for _, s := range p.Publish {
|
||||
if strings.Contains(s, "CONSUMER.") && !strings.HasSuffix(s, ".one_audit") {
|
||||
t.Errorf("a module may reach another consumer: %s", s)
|
||||
}
|
||||
}
|
||||
for _, s := range p.Subscribe {
|
||||
if strings.HasPrefix(s, "_DELIVER.") {
|
||||
t.Errorf("a module is granted a push delivery it never binds: %s", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/envfile"
|
||||
)
|
||||
|
||||
// Whether this mesh's own traffic is on the bus being built.
|
||||
//
|
||||
// **One switch, read in one place** (novox/hq ADR 0116 step 5). Every seam the bus change went
|
||||
// behind ships both implementations, and until the rollout every one of them chooses the bus the
|
||||
// mesh runs on today. This is what the rollout flips, and it is deliberately a single fact rather
|
||||
// than a fact per component: a controller whose outbound is on one bus and whose inbound is on the
|
||||
// other is a mesh that hears nothing, and no test of either half would catch it.
|
||||
|
||||
// NATSVar is where the controller finds the bus being built. Unset is the ordinary case and means
|
||||
// the mesh runs on the bus it has always run on.
|
||||
const NATSVar = "MESH_BUS_NATS"
|
||||
|
||||
// OnNATS is the address of the bus being built, and whether the mesh is on it.
|
||||
//
|
||||
// Read from the node's own settings rather than baked in, for the reason the broker's address is
|
||||
// (novox/hq 04-ISSUES/102): an address recorded once does not follow a node's ports.
|
||||
func OnNATS() (address string, on bool, err error) {
|
||||
address, err = envfile.Placed(NATSVar)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
address = strings.TrimSpace(address)
|
||||
if address == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
return address, true, nil
|
||||
}
|
||||
|
||||
// CredentialIn reads the user and password out of a bus address, and the address without them.
|
||||
//
|
||||
// The controller's own credential arrives in its address, the way the old bus's does. Split out so the
|
||||
// controller can record a hash of what it is actually using: its user is created by the installer at a
|
||||
// bootstrap password, before the controller exists to mint one, and a composition that left itself out
|
||||
// would produce a bus the writer cannot connect to.
|
||||
func CredentialIn(address string) (user, password, bare string) {
|
||||
at := strings.LastIndex(address, "@")
|
||||
if at < 0 {
|
||||
return "", "", address
|
||||
}
|
||||
scheme := ""
|
||||
rest := address[:at]
|
||||
if i := strings.Index(rest, "://"); i >= 0 {
|
||||
scheme, rest = rest[:i+3], rest[i+3:]
|
||||
}
|
||||
user, password, _ = strings.Cut(rest, ":")
|
||||
return user, password, scheme + address[at+1:]
|
||||
}
|
||||
|
||||
// BareAddress is a bus address with any credential stripped, for something that only needs to know
|
||||
// whether a server is answering there.
|
||||
func BareAddress(address string) string {
|
||||
_, _, bare := CredentialIn(address)
|
||||
if bare == "" {
|
||||
return address
|
||||
}
|
||||
if strings.Contains(bare, "://") {
|
||||
return bare
|
||||
}
|
||||
return "nats://" + bare
|
||||
}
|
||||
|
||||
// BusAddress is where the mesh's bus is, with this process's credential, and refuses to be empty:
|
||||
// there is one bus, and a control plane without it can hold records and answer nothing (novox/hq
|
||||
// ADR 0131, design 28 task 5.5).
|
||||
func BusAddress() (string, error) {
|
||||
address, _, err := OnNATS()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if address == "" {
|
||||
return "", fmt.Errorf("this control plane has no %s, so it cannot reach the mesh's bus", NATSVar)
|
||||
}
|
||||
return address, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Which bus the mesh is on is one fact, and being told about both is refused.
|
||||
//
|
||||
|
||||
// The controller's own credential arrives in its address, and has to be readable out of it — its user
|
||||
// is created by the installer at a bootstrap password, before the controller exists to mint one.
|
||||
func TestACredentialIsReadOutOfABusAddress(t *testing.T) {
|
||||
for _, c := range []struct{ in, user, password, bare string }{
|
||||
{"nats://controller:secret@127.0.0.1:4222", "controller", "secret", "nats://127.0.0.1:4222"},
|
||||
{"controller:secret@127.0.0.1:4222", "controller", "secret", "127.0.0.1:4222"},
|
||||
{"nats://127.0.0.1:4222", "", "", "nats://127.0.0.1:4222"},
|
||||
{"127.0.0.1:4222", "", "", "127.0.0.1:4222"},
|
||||
// A password containing an at-sign: split on the last one, or the address becomes part of the
|
||||
// credential and the connection goes somewhere nobody named.
|
||||
{"nats://controller:a@b@127.0.0.1:4222", "controller", "a@b", "nats://127.0.0.1:4222"},
|
||||
} {
|
||||
user, password, bare := CredentialIn(c.in)
|
||||
if user != c.user || password != c.password || bare != c.bare {
|
||||
t.Errorf("%q read as %q/%q at %q; wanted %q/%q at %q",
|
||||
c.in, user, password, bare, c.user, c.password, c.bare)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package broker
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Bringing the bus's own objects into being, in the one order that works.
|
||||
//
|
||||
// **Asserted on every start rather than created once at genesis.** A stream somebody deleted, a mesh
|
||||
// raised from a restored backup, or a bus whose data directory was replaced all have records and no
|
||||
// objects — and a node whose consumer is missing hears nothing while everything else about it looks
|
||||
// correct. Idempotence is the whole requirement, and the parts are already idempotent; this is the
|
||||
// order they have to be asked in.
|
||||
|
||||
// Raiser is everything asserting the bus's objects needs of a connection to it.
|
||||
type Raiser interface {
|
||||
Asserter
|
||||
Ensurer
|
||||
}
|
||||
|
||||
// Raise asserts the mesh's streams, the controller's own consumers, and one consumer per node.
|
||||
//
|
||||
// **The order is not a preference.** A consumer on a stream that does not exist is refused, and the
|
||||
// refusal names the stream rather than the order — so somebody reading it goes looking for a deleted
|
||||
// stream instead of a reversed pair of lines. Nodes last, because the one a node reads lives on a
|
||||
// stream the mesh's own set defines.
|
||||
func Raise(r Raiser, nodes []string) error {
|
||||
if err := AssertMeshStreams(r); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := AssertMeshConsumers(r); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := AssertNodeConsumers(r, nodes); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RaiseSeats asserts one work queue per declared seat, and the worker of whoever holds it.
|
||||
//
|
||||
// Separate from Raise because it is answered by a different question: the mesh's own objects exist
|
||||
// because the mesh does, and a seat's exist because a module declaring one was registered. Kept
|
||||
// beside it so the order is visible — a holder's worker needs the seat's stream, and a seat's stream
|
||||
// needs nothing.
|
||||
func RaiseSeats(r Raiser, seats []DeclaredSeat, holders map[string]Holder) error {
|
||||
for _, s := range SeatStreams(seats) {
|
||||
if err := r.EnsureStream(s); err != nil {
|
||||
return fmt.Errorf("asserting the work queue for %s: %w", s.Name, err)
|
||||
}
|
||||
}
|
||||
for _, s := range seats {
|
||||
h, held := holders[s.Name]
|
||||
if !held {
|
||||
// **The stream exists and the consumer does not, on purpose.** Work queues until a
|
||||
// holder appears, so installing the module a week after something started sending to it
|
||||
// flushes the backlog instead of having lost it.
|
||||
continue
|
||||
}
|
||||
c, needed := HolderConsumerFor(h.Node, h.Module, s)
|
||||
if !needed {
|
||||
continue
|
||||
}
|
||||
if err := r.EnsureConsumer(c); err != nil {
|
||||
return fmt.Errorf("asserting how %s on %s works %s: %w", h.Module, h.Node, s.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Holder is which module on which machine holds a seat.
|
||||
type Holder struct {
|
||||
Node string
|
||||
Module string
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// Raising the bus's objects against a real server.
|
||||
//
|
||||
// The pure tests above say what is asked for and in what order. Only a server can say whether it
|
||||
// accepts them — and two of these are claims about the server's own behaviour that nothing else
|
||||
// could answer: that asserting twice changes nothing, and that a consumer really is bound to the one
|
||||
// subject its node is allowed to read.
|
||||
//
|
||||
// docker run -d --rm --name t -p 14227:4222 nats:2.10-alpine -js
|
||||
// MESH_TEST_NATS=nats://127.0.0.1:14227 go test ./internal/broker/ -run TestRaising
|
||||
|
||||
func aLiveBus(t *testing.T) *JetStream {
|
||||
t.Helper()
|
||||
url := os.Getenv("MESH_TEST_NATS")
|
||||
if url == "" {
|
||||
t.Skip("MESH_TEST_NATS unset")
|
||||
}
|
||||
js, err := Dial(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(js.Close)
|
||||
// **Nothing is deleted here, deliberately.** These objects are the mesh's own and every live
|
||||
// test in every package shares one server: a test that deleted a stream to get a clean slate
|
||||
// took it out from under whatever was running beside it, and the failure landed in the other
|
||||
// test as "stream not found" — which reads as a bug in the code under test. Raise is idempotent
|
||||
// by requirement, so asserting against whatever is already there is both safe and the realistic
|
||||
// case.
|
||||
return js
|
||||
}
|
||||
|
||||
// Every object the mesh's own traffic needs, accepted by a real server, and asserting again changes
|
||||
// nothing — which is the whole requirement, because this runs on every start.
|
||||
func TestRaisingTheBusIsAcceptedAndIdempotent(t *testing.T) {
|
||||
js := aLiveBus(t)
|
||||
|
||||
if err := Raise(js, []string{"anchor", "laptop"}); err != nil {
|
||||
t.Fatalf("a real server refused the mesh's own objects: %v", err)
|
||||
}
|
||||
// Twice, with nothing in between. A start that failed the second time is a controller that
|
||||
// cannot restart.
|
||||
if err := Raise(js, []string{"anchor", "laptop"}); err != nil {
|
||||
t.Fatalf("asserting the bus's objects a second time failed, so a restart would: %v", err)
|
||||
}
|
||||
// And again with a machine that was not there before, which is what enrolling one is.
|
||||
if err := Raise(js, []string{"anchor", "laptop", "workstation"}); err != nil {
|
||||
t.Fatalf("a machine joining an already-raised bus was refused: %v", err)
|
||||
}
|
||||
|
||||
for _, s := range MeshStreams() {
|
||||
if _, err := js.Context().StreamInfo(s.Name); err != nil {
|
||||
t.Errorf("stream %s is not there: %v", s.Name, err)
|
||||
}
|
||||
}
|
||||
for _, c := range MeshConsumers() {
|
||||
if _, err := js.Context().ConsumerInfo(c.Stream, c.Name); err != nil {
|
||||
t.Errorf("the controller's consumer on %s is not there: %v", c.Stream, err)
|
||||
}
|
||||
}
|
||||
for _, node := range []string{"anchor", "laptop", "workstation"} {
|
||||
info, err := js.Context().ConsumerInfo("NODES", node)
|
||||
if err != nil {
|
||||
t.Errorf("%s has no way to hear its declaration: %v", node, err)
|
||||
continue
|
||||
}
|
||||
// **Its own subject and no other node's.** A consumer filtered on anything wider is a node
|
||||
// reading another machine's declaration, and its own ack grant would not cover it either.
|
||||
if info.Config.FilterSubject != "mesh.node."+node+".declare" {
|
||||
t.Errorf("%s's consumer reads %q", node, info.Config.FilterSubject)
|
||||
}
|
||||
if info.Config.AckPolicy != nats.AckExplicitPolicy {
|
||||
t.Errorf("%s's consumer acknowledges on delivery, so a declaration it died applying is "+
|
||||
"never sent again", node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The store window needs unlimited redelivery on CONTROL: the bound belongs to the controller, and a
|
||||
// server that dead-lettered first would discard the push the stream exists to protect.
|
||||
func TestTheControlConsumerDoesNotDeadLetterBeforeTheControllerGivesUp(t *testing.T) {
|
||||
js := aLiveBus(t)
|
||||
if err := Raise(js, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := js.Context().ConsumerInfo("CONTROL", ControllerName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.MaxDeliver > 0 {
|
||||
t.Fatalf("max-deliver is %d: a push held through a store restart would be dead-lettered "+
|
||||
"before the controller finished deciding about it", info.Config.MaxDeliver)
|
||||
}
|
||||
}
|
||||
|
||||
// A role's work queue exists before anybody holds it, against a real server.
|
||||
//
|
||||
// **The queue before the holder is the point** (novox/hq ADR 0121): work queues until somebody arrives
|
||||
// to do it, so assigning a build machine a week after something started asking for builds flushes the
|
||||
// backlog instead of having lost it. A stream created at assignment would make "the holder is not here
|
||||
// yet" mean "your requests are gone".
|
||||
func TestRaisingAMeshRolesWorkQueue(t *testing.T) {
|
||||
js := aLiveBus(t)
|
||||
seats := []DeclaredSeat{{Name: "mesh-build-machine", Accepts: []string{"build"},
|
||||
Emits: []string{"built"}}}
|
||||
t.Cleanup(func() { _ = js.Context().DeleteStream("SEAT_MESH_BUILD_MACHINE") })
|
||||
|
||||
if err := RaiseSeats(js, seats, nil); err != nil {
|
||||
t.Fatalf("a real server refused a role's work queue: %v", err)
|
||||
}
|
||||
info, err := js.Context().StreamInfo("SEAT_MESH_BUILD_MACHINE")
|
||||
if err != nil {
|
||||
t.Fatalf("the role has no work queue: %v", err)
|
||||
}
|
||||
if info.Config.Retention != nats.WorkQueuePolicy {
|
||||
t.Errorf("the queue retains as %v: work a holder took must leave it, or the next holder does "+
|
||||
"it again", info.Config.Retention)
|
||||
}
|
||||
if len(info.Config.Subjects) != 1 || info.Config.Subjects[0] != "mesh.seat.mesh-build-machine.accept.>" {
|
||||
t.Errorf("it carries %v rather than the role's own inbound subjects", info.Config.Subjects)
|
||||
}
|
||||
// Nobody holds it, so there is no worker — and asserting again changes nothing, because this runs
|
||||
// on every start.
|
||||
if err := RaiseSeats(js, seats, nil); err != nil {
|
||||
t.Fatalf("asserting a role's queue a second time failed, so a restart would: %v", err)
|
||||
}
|
||||
|
||||
// And once somebody holds it, the worker appears on that same queue.
|
||||
if err := RaiseSeats(js, seats, map[string]Holder{
|
||||
"mesh-build-machine": {Node: "anchor", Module: "builder"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := js.Context().ConsumerInfo("SEAT_MESH_BUILD_MACHINE",
|
||||
"SEAT_MESH_BUILD_MACHINE_worker"); err != nil {
|
||||
t.Fatalf("the holder got no worker on the role's queue: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// **A consumer created after the fact still sees what came before it**, which is why the mesh needs no
|
||||
// catch-up at all on this bus (novox/hq 04-ISSUES/050).
|
||||
//
|
||||
// On the bus the mesh runs on today a queue receives only what is published after it is bound, so
|
||||
// everything built before the catalogue existed was announced to nobody — and on a fresh mesh that is
|
||||
// always the foundation, because those are the things the catalogue needed in order to exist. A whole
|
||||
// mechanism was built for it: the catalogue asks, the controller re-publishes.
|
||||
//
|
||||
// A stream is a log and a consumer is a position in it. A consumer created later starts at the
|
||||
// beginning by default, so the builds are simply there. Asked of a real server rather than assumed,
|
||||
// because the whole decision about whether to keep that mechanism rests on it.
|
||||
func TestAConsumerCreatedAfterwardsStillSeesWhatCameBefore(t *testing.T) {
|
||||
js := aLiveBus(t)
|
||||
if err := AssertMeshStreams(js); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := js.Context().PurgeStream("EVENTS"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Genesis: things are built before anything is listening.
|
||||
built := []string{"base", "store", "mesh-catalog"}
|
||||
for _, m := range built {
|
||||
if _, err := js.Context().Publish("mesh.seat.mesh-build-machine.event.built",
|
||||
[]byte(`{"module":"`+m+`"}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Now the catalogue is installed and the controller creates its consumer.
|
||||
c, ok := ConsumerFor(Principal{Kind: KindModule, Node: "one", Module: "mesh-catalog",
|
||||
Watches: []Seat{{Name: "mesh-build-machine", Emits: []string{"built"}}}, PasswordHash: "x"})
|
||||
if !ok {
|
||||
t.Fatal("a module that watches a role got no consumer")
|
||||
}
|
||||
t.Cleanup(func() { _ = js.Context().DeleteConsumer(c.Stream, c.Name) })
|
||||
if err := js.EnsureConsumer(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := js.Context().ConsumerInfo(c.Stream, c.Name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.NumPending != uint64(len(built)) {
|
||||
t.Fatalf("a consumer created after %d builds has %d waiting for it — if this is 0 the mesh "+
|
||||
"does need a catch-up after all, and the reasoning for deleting it is wrong",
|
||||
len(built), info.NumPending)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Whether a mesh could move its bus, and what is missing if not.
|
||||
//
|
||||
// **Asked before anything moves, and answerable from records alone.** The rollout moves every node at
|
||||
// once (novox/hq ADR 0116 step 5), so there is no partial state to inspect afterwards and no half to
|
||||
// roll back: either the mesh was ready or it was not. That makes a readiness question the most
|
||||
// valuable thing here — it costs nothing, it can be asked of a running mesh any number of times, and
|
||||
// every answer is a thing somebody can go and fix.
|
||||
//
|
||||
// Deliberately pure. It is handed what the mesh knows and returns sentences; nothing here connects to
|
||||
// anything, so it can be asked on a workstation about a mesh it has never reached.
|
||||
|
||||
// Readiness is what the mesh knows about its own ability to move.
|
||||
type Readiness struct {
|
||||
// TheBus is the address the mesh's own traffic would move to, empty when nothing names one.
|
||||
TheBus string
|
||||
// ServerStanding is whether a bus is reachable at that address, as somebody checked.
|
||||
ServerStanding bool
|
||||
// Holder is the node running the module that holds the bus seat, empty when nothing does.
|
||||
Holder string
|
||||
// AccountsComposed is whether that node has been sent the composed user list.
|
||||
AccountsComposed bool
|
||||
// Nodes is every machine the mesh knows.
|
||||
Nodes []string
|
||||
// Credentialled is which of them has a credential for the new bus.
|
||||
Credentialled map[string]bool
|
||||
// Modules is every assigned module, as `<node>/<module>`.
|
||||
Modules []string
|
||||
// ModuleCredentialled is which of those has one.
|
||||
ModuleCredentialled map[string]bool
|
||||
}
|
||||
|
||||
// NotReady is every reason this mesh cannot move its bus yet, in the order somebody would fix them.
|
||||
//
|
||||
// Empty means ready. **Each entry names one thing and what to do about it**, because a readiness check
|
||||
// that says "not ready" is a check nobody can act on — and this is read at the point where the next
|
||||
// step is irreversible.
|
||||
func NotReady(r Readiness) []string {
|
||||
var why []string
|
||||
|
||||
if strings.TrimSpace(r.TheBus) == "" {
|
||||
why = append(why, "nothing names the bus to move to: set "+NATSVar+" on the control node "+
|
||||
"to the address the new server answers on")
|
||||
}
|
||||
if !r.ServerStanding {
|
||||
why = append(why, "no bus is answering at that address. Step 2 of the change raises it beside "+
|
||||
"the one the mesh is on, carrying nothing — assign the module that holds "+
|
||||
"mesh-broker and push the machine that runs it")
|
||||
}
|
||||
if r.Holder == "" {
|
||||
why = append(why, "no machine holds mesh-broker, so nothing would compose the bus's user "+
|
||||
"list. Assign the module that claims it")
|
||||
} else if !r.AccountsComposed {
|
||||
why = append(why, fmt.Sprintf(
|
||||
"%s holds mesh-broker and has not been sent the composed user list, so the bus would "+
|
||||
"refuse every connection. `push %s`", r.Holder, r.Holder))
|
||||
}
|
||||
|
||||
// A node with no credential cannot come back after the move, and a node that cannot come back is
|
||||
// a machine the mesh has lost until somebody goes to it.
|
||||
var missing []string
|
||||
for _, n := range r.Nodes {
|
||||
if !r.Credentialled[n] {
|
||||
missing = append(missing, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(missing)
|
||||
if len(missing) > 0 {
|
||||
why = append(why, fmt.Sprintf(
|
||||
"%d machine(s) have no credential for the new bus and would not come back: %s. Each needs "+
|
||||
"one minted before the move, not after — after, there is no bus to ask over",
|
||||
len(missing), strings.Join(missing, ", ")))
|
||||
}
|
||||
|
||||
// A module without one keeps running and stops being reachable, which is a smaller fault and still
|
||||
// one somebody should choose rather than discover.
|
||||
var quiet []string
|
||||
for _, m := range r.Modules {
|
||||
if !r.ModuleCredentialled[m] {
|
||||
quiet = append(quiet, m)
|
||||
}
|
||||
}
|
||||
sort.Strings(quiet)
|
||||
if len(quiet) > 0 {
|
||||
why = append(why, fmt.Sprintf(
|
||||
"%d module(s) have no credential for the new bus: %s. Each keeps serving and stops "+
|
||||
"answering tools and hearing events until it is issued one",
|
||||
len(quiet), strings.Join(quiet, ", ")))
|
||||
}
|
||||
|
||||
return why
|
||||
}
|
||||
|
||||
// WhatMoves is what the rollout would do, in order, for somebody reading before they commit.
|
||||
//
|
||||
// **Written out rather than summarised.** This is the one step with nothing to inspect afterwards, so
|
||||
// the last useful moment to disagree with it is while reading this.
|
||||
func WhatMoves(r Readiness) []string {
|
||||
out := []string{
|
||||
fmt.Sprintf("compose the bus's user list and send it to %s", holderOr(r.Holder)),
|
||||
fmt.Sprintf("move this control plane to %s, and confirm it is heard", busOr(r.TheBus)),
|
||||
}
|
||||
nodes := append([]string(nil), r.Nodes...)
|
||||
sort.Strings(nodes)
|
||||
for _, n := range nodes {
|
||||
out = append(out, fmt.Sprintf("move %s, and confirm it reports", n))
|
||||
}
|
||||
if len(r.Modules) > 0 {
|
||||
out = append(out, fmt.Sprintf("move %d module runtime(s), and confirm each answers",
|
||||
len(r.Modules)))
|
||||
}
|
||||
// **The old broker goes, and it goes last** (novox/hq ADR 0131). AMQP is not a provision, so once
|
||||
// every machine reports on the new bus nothing of the mesh is left speaking to it, and its module
|
||||
// is unassigned. Said as a step so nobody reads the move as leaving a second bus behind.
|
||||
out = append(out, "then unassign the old broker's module: AMQP is not a provision (ADR 0131), and "+
|
||||
"once every machine reports on the new bus nothing of the mesh speaks to it")
|
||||
return out
|
||||
}
|
||||
|
||||
func holderOr(node string) string {
|
||||
if node == "" {
|
||||
return "whichever machine holds mesh-broker"
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
func busOr(address string) string {
|
||||
if address == "" {
|
||||
return "the new bus"
|
||||
}
|
||||
return address
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Whether a mesh could move its bus.
|
||||
//
|
||||
// Every case here is a way of moving that leaves something behind, and the one that matters most is a
|
||||
// machine with no credential: after the move there is no bus to ask it over, so it is lost until
|
||||
// somebody walks to it.
|
||||
|
||||
func aMeshReadyToMove() Readiness {
|
||||
return Readiness{
|
||||
TheBus: "nats://127.0.0.1:5671", ServerStanding: true,
|
||||
Holder: "anchor", AccountsComposed: true,
|
||||
Nodes: []string{"anchor", "laptop"},
|
||||
Credentialled: map[string]bool{"anchor": true, "laptop": true},
|
||||
Modules: []string{"anchor/gitea"},
|
||||
ModuleCredentialled: map[string]bool{"anchor/gitea": true},
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMeshWithEverythingInPlaceIsReady(t *testing.T) {
|
||||
if why := NotReady(aMeshReadyToMove()); len(why) != 0 {
|
||||
t.Fatalf("a mesh with everything in place was refused: %v", why)
|
||||
}
|
||||
}
|
||||
|
||||
// **A machine with no credential is the one that must stop this.** It keeps running and cannot come
|
||||
// back, and there is no bus left to tell it anything over — so the remedy has to happen before, and
|
||||
// the message says so.
|
||||
func TestAMachineWithNoCredentialStopsTheMove(t *testing.T) {
|
||||
r := aMeshReadyToMove()
|
||||
r.Credentialled = map[string]bool{"anchor": true}
|
||||
|
||||
why := NotReady(r)
|
||||
if len(why) == 0 {
|
||||
t.Fatal("a machine that could not come back did not stop the move")
|
||||
}
|
||||
said := strings.Join(why, "\n")
|
||||
if !strings.Contains(said, "laptop") {
|
||||
t.Errorf("the refusal does not name the machine: %s", said)
|
||||
}
|
||||
if !strings.Contains(said, "before the move") {
|
||||
t.Errorf("the refusal does not say the remedy comes first: %s", said)
|
||||
}
|
||||
}
|
||||
|
||||
// A bus nobody has raised, a seat nobody holds, and a user list nobody has been sent: each stops it,
|
||||
// and each names its own next step, because "not ready" that cannot be acted on is not an answer.
|
||||
func TestEachThingMissingNamesItsOwnRemedy(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
what string
|
||||
break_ func(*Readiness)
|
||||
says string
|
||||
}{
|
||||
{"no address", func(r *Readiness) { r.TheBus = "" }, NATSVar},
|
||||
{"no server", func(r *Readiness) { r.ServerStanding = false }, "carrying nothing"},
|
||||
{"no holder", func(r *Readiness) { r.Holder = "" }, "mesh-broker"},
|
||||
{"no user list", func(r *Readiness) { r.AccountsComposed = false }, "push anchor"},
|
||||
{"a module with none", func(r *Readiness) {
|
||||
r.ModuleCredentialled = map[string]bool{}
|
||||
}, "anchor/gitea"},
|
||||
} {
|
||||
r := aMeshReadyToMove()
|
||||
c.break_(&r)
|
||||
why := NotReady(r)
|
||||
if len(why) == 0 {
|
||||
t.Errorf("%s did not stop the move", c.what)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(strings.Join(why, "\n"), c.says) {
|
||||
t.Errorf("%s: the refusal does not mention %q: %v", c.what, c.says, why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What the move would do is written out rather than summarised, because this is the one step with
|
||||
// nothing to inspect afterwards — so reading it is the last chance to disagree.
|
||||
func TestWhatMovesNamesEveryMachineAndEndsWithTheOldBrokerGoing(t *testing.T) {
|
||||
r := aMeshReadyToMove()
|
||||
steps := strings.Join(WhatMoves(r), "\n")
|
||||
|
||||
for _, want := range []string{"anchor", "laptop", "user list", "module runtime"} {
|
||||
if !strings.Contains(steps, want) {
|
||||
t.Errorf("the plan does not mention %q:\n%s", want, steps)
|
||||
}
|
||||
}
|
||||
// Said explicitly, and last: AMQP is not a provision (novox/hq ADR 0131), so the move ends with
|
||||
// the old broker's module unassigned, not left behind as a second bus. An earlier version of this
|
||||
// test pinned the opposite, under a record 0131 superseded.
|
||||
lines := WhatMoves(r)
|
||||
if last := lines[len(lines)-1]; !strings.Contains(last, "unassign the old broker") {
|
||||
t.Errorf("the plan does not end with the old broker going:\n%s", steps)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package broker
|
||||
|
||||
import "testing"
|
||||
|
||||
// A node-scoped seat's tool carries the node (novox/hq ADR 0132, design 33 §4): two nodes holding one
|
||||
// node-scoped seat derive two addresses, and a user of the seat may publish any node's.
|
||||
func TestTwoNodesHoldingOneNodeSeatDeriveTwoToolAddresses(t *testing.T) {
|
||||
seat := Seat{Name: "node-dns-resolver", Scope: "node", Serves: []string{"lookup"}}
|
||||
one, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "dnsmasq", Holds: []Seat{seat}, PasswordHash: "x"})
|
||||
two, _ := PermissionsFor(Principal{Kind: KindModule, Node: "two", Module: "dnsmasq", Holds: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, one.Subscribe, "mesh.seat.node-dns-resolver.tool.lookup.one")
|
||||
has(t, two.Subscribe, "mesh.seat.node-dns-resolver.tool.lookup.two")
|
||||
hasNot(t, one.Subscribe, "mesh.seat.node-dns-resolver.tool.lookup")
|
||||
hasNot(t, one.Subscribe, "mesh.seat.node-dns-resolver.tool.lookup.two")
|
||||
|
||||
user, _ := PermissionsFor(Principal{Kind: KindModule, Node: "three", Module: "asker", Uses: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, user.Publish, "mesh.seat.node-dns-resolver.tool.lookup.*")
|
||||
}
|
||||
|
||||
// A mesh-scoped seat's tool stays flat: nothing about it changes.
|
||||
func TestAMeshSeatsToolIsAddressedToTheSeatAlone(t *testing.T) {
|
||||
seat := Seat{Name: "git", Scope: "mesh", Serves: []string{"list_repos"}}
|
||||
holder, _ := PermissionsFor(Principal{Kind: KindModule, Node: "one", Module: "gitea", Holds: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, holder.Subscribe, "mesh.seat.git.tool.list_repos")
|
||||
user, _ := PermissionsFor(Principal{Kind: KindModule, Node: "two", Module: "asker", Uses: []Seat{seat}, PasswordHash: "x"})
|
||||
has(t, user.Publish, "mesh.seat.git.tool.list_repos")
|
||||
}
|
||||
|
||||
// The controller serves its own seat's verbs and may answer them (novox/hq ADR 0154).
|
||||
func TestTheControllerServesItsSeatsToolsAndMayAnswer(t *testing.T) {
|
||||
perms, err := PermissionsFor(Principal{Kind: KindController, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Subscribe, "mesh.seat.mesh-controller.tool.>")
|
||||
if !perms.AllowResponses {
|
||||
t.Fatal("the controller serves tools and may not answer one")
|
||||
}
|
||||
}
|
||||
|
||||
// A grant to every tool reaches a role's tools too, and a role's tool is granted by name.
|
||||
func TestAGrantReachesARolesTools(t *testing.T) {
|
||||
all, _ := PermissionsFor(Principal{Kind: KindModule, Node: "desk", Module: "mesh-console", Invokes: []string{"*"}, PasswordHash: "x"})
|
||||
has(t, all.Publish, "mesh.seat.*.tool.>")
|
||||
|
||||
one, err := PermissionsFor(Principal{Kind: KindPerson, Module: "jo", Invokes: []string{"seat:mesh-controller.status"}, PasswordHash: "x"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, one.Publish, "mesh.seat.mesh-controller.tool.status")
|
||||
hasNot(t, one.Publish, "mesh.seat.mesh-controller.tool.push")
|
||||
hasNot(t, one.Publish, "mesh.mod.*.tool.>")
|
||||
|
||||
if _, err := PermissionsFor(Principal{Kind: KindPerson, Module: "jo", Invokes: []string{"seat:mesh-controller"}, PasswordHash: "x"}); err == nil {
|
||||
t.Fatal("a role grant naming no verb was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package broker_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/broker"
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
"github.com/novox/mesh-controller/internal/link"
|
||||
)
|
||||
|
||||
// The facts the control plane states are named twice — in the grant that permits them and in the code
|
||||
// that states them — because `link` imports `broker` and the dependency cannot go the other way. So a
|
||||
// test keeps them agreeing: a subject the grant omits is refused at the moment the mesh has something
|
||||
// to say, and one the grant adds that nothing states is authority nobody uses.
|
||||
//
|
||||
// An external test package, because it may import both while neither imports the other.
|
||||
func TestTheFactsTheGrantPermitsAreTheFactsTheMeshStates(t *testing.T) {
|
||||
if broker.ControllerSeat != link.MeshControllerSeat {
|
||||
t.Fatalf("the grant is written for the %q seat and the mesh states its facts under %q",
|
||||
broker.ControllerSeat, link.MeshControllerSeat)
|
||||
}
|
||||
for _, event := range []string{link.KeyApplied, link.KeyRefused, link.KeyBuiltBefore} {
|
||||
if !slices.Contains(broker.ControllerStates, event) {
|
||||
t.Errorf("the mesh states %q and its account may not publish it", event)
|
||||
}
|
||||
}
|
||||
if len(broker.ControllerStates) != 3 {
|
||||
t.Errorf("the grant permits %v, which is more than the mesh states", broker.ControllerStates)
|
||||
}
|
||||
// **And the seat says it.** A seat carries the protocol of its role (novox/hq ADR 0129), so the
|
||||
// facts the control plane states are the seat's `emits` — which is what lets anything else declare
|
||||
// that it consumes them, and what the subject-agreement check reads to know they have an owner.
|
||||
var declared []string
|
||||
for _, seat := range catalogue.SeatsWithAProtocol() {
|
||||
if seat.Name == broker.ControllerSeat {
|
||||
declared = seat.Emits
|
||||
}
|
||||
}
|
||||
if !slices.Equal(declared, broker.ControllerStates) {
|
||||
t.Errorf("the %s seat emits %v and the grant permits %v", broker.ControllerSeat,
|
||||
declared, broker.ControllerStates)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// The mesh's own streams.
|
||||
//
|
||||
// **These four and no more** (novox/hq ADR 0116 task 1.4, as revised by ADR 0118). An earlier
|
||||
// reading had the controller create *every* stream at genesis, from a fixed set. That is only the
|
||||
// mesh's own half: a seat's streams are created when the module declaring it is registered, and a
|
||||
// module's durable consumers when it is assigned — neither of which has happened at genesis. What
|
||||
// is here is the foundation, which exists before any module does.
|
||||
//
|
||||
// The controller is the only writer of stream definitions (design 25 §3). A module declares
|
||||
// nothing about them and cannot reach the JetStream API to make one.
|
||||
|
||||
// Retention is how a stream decides what to keep, which is the whole of what distinguishes the
|
||||
// mesh's four relationships on the wire (design 29 §4).
|
||||
type Retention string
|
||||
|
||||
const (
|
||||
// RetentionWorkQueue: a message is removed once a consumer acknowledges it. Exactly one
|
||||
// worker does the work, and a worker that dies has its message redelivered.
|
||||
RetentionWorkQueue Retention = "workqueue"
|
||||
// RetentionLastPerSubject: only the newest message on each subject survives. This is the
|
||||
// state shape — a node that was away gets exactly the current declaration and nothing older.
|
||||
RetentionLastPerSubject Retention = "last_per_subject"
|
||||
// RetentionLimits: kept until it ages or the stream fills. Events, where a subscriber that
|
||||
// was down catches up and nobody is obliged to act.
|
||||
RetentionLimits Retention = "limits"
|
||||
)
|
||||
|
||||
// A Stream is one of the mesh's own, as the controller asserts it.
|
||||
type Stream struct {
|
||||
Name string
|
||||
Subjects []string
|
||||
Retention Retention
|
||||
// MaxAge in seconds, zero for unbounded. Per stream — JetStream has no per-subject age,
|
||||
// which is why differing retention between modules would mean a stream each.
|
||||
MaxAge int
|
||||
// MaxMsgsPerSubject caps each subject independently, so one noisy emitter cannot push
|
||||
// another's events out of a shared stream. Verified: with a cap of 3, ten messages on one
|
||||
// subject and one on another leave four in the stream, not three.
|
||||
MaxMsgsPerSubject int
|
||||
// Why is carried into the assertion so an operator reading the server's own state finds the
|
||||
// reason there, rather than only in a repository they may not have.
|
||||
Why string
|
||||
}
|
||||
|
||||
// MeshStreams is the foundation set, in the order a person reads it.
|
||||
//
|
||||
// **CONTROL names its subjects rather than taking `mesh.control.>`**, because heartbeats live
|
||||
// under that prefix and must not be persisted: a lost heartbeat is the next heartbeat, and a
|
||||
// stream of them is a stream of the least valuable messages the mesh sends, competing for the
|
||||
// same retention as the ones that matter.
|
||||
//
|
||||
// **EVENTS filters on the `event` token**, which is the reason that token exists. A module's
|
||||
// namespace carries both its events and its tool calls; a filter of `mesh.mod.*.>` would persist
|
||||
// every tool invocation in the mesh, and a tool call must never be persisted (design 25 §3 keeps
|
||||
// tools on core NATS, where a lost call is a timeout the caller already handles).
|
||||
func MeshStreams() []Stream {
|
||||
return []Stream{
|
||||
{
|
||||
Name: "CONTROL",
|
||||
// A build's outcome is no longer here: it is the build-machine seat's own event, so one
|
||||
// publish reaches whoever asked, the controller and the catalogue (novox/hq ADR 0121).
|
||||
Subjects: []string{"mesh.control.*.report", "mesh.control.enrol"},
|
||||
Retention: RetentionWorkQueue,
|
||||
Why: "the store-window guarantee (ADR 0083): the controller naks with a delay while its " +
|
||||
"store is away and the message is redelivered; nothing is dropped",
|
||||
},
|
||||
{
|
||||
Name: "NODES",
|
||||
Subjects: []string{"mesh.node.*.declare"},
|
||||
Retention: RetentionLastPerSubject,
|
||||
Why: "one declaration per node, always the newest; a node that sees sequence n refuses " +
|
||||
"n-1 by construction (issue 107)",
|
||||
},
|
||||
{
|
||||
Name: "EVENTS",
|
||||
// A seat's own events ride here too: they are 1:many like any event, and the
|
||||
// `event` token keeps them clear of both the seat's work queue (`accept`) and its
|
||||
// tools (`tool`), which must not be persisted.
|
||||
Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.*.event.>"},
|
||||
Retention: RetentionLimits,
|
||||
MaxAge: 7 * 24 * 60 * 60,
|
||||
MaxMsgsPerSubject: 10000,
|
||||
Why: "a subscriber that was down catches up; tool traffic under the same prefix is " +
|
||||
"excluded by the event token; per-subject caps keep a noisy emitter from " +
|
||||
"evicting a quiet one without splitting the stream",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// DeliverSubjectFor is where a push consumer's messages land.
|
||||
//
|
||||
// **Per consumer, which means per stream as well as per name** (novox/hq 04-ISSUES/146). A push
|
||||
// consumer delivers onto an ordinary subject, and everything subscribed to that subject gets a
|
||||
// copy. The controller holds a consumer called `controller` on CONTROL and another called
|
||||
// `controller` on EVENTS; while both were given `_DELIVER.controller`, the one process holding
|
||||
// both subscriptions acted on every message twice — a joining machine was enrolled twice from one
|
||||
// request, and the second enrolment minted a credential that replaced the one the machine had just
|
||||
// been handed. Every report and every followed event doubled the same way, silently: nothing is
|
||||
// redelivered, no count is wrong, the work simply happens twice.
|
||||
//
|
||||
// The stream belongs in it because the pair is what identifies a consumer — the server scopes a
|
||||
// durable's name to its stream, and this subject was the one place that scoping was dropped. It
|
||||
// stays inside what a controller may already subscribe (`_DELIVER.controller.>`).
|
||||
func DeliverSubjectFor(c Consumer) string {
|
||||
return "_DELIVER." + c.Name + "." + c.Stream
|
||||
}
|
||||
|
||||
// An Asserter is the part of a JetStream connection stream assertion needs. Narrow on purpose: it
|
||||
// keeps this testable without a server, and keeps the client library out of everything that only
|
||||
// wants to know what the streams are.
|
||||
type Asserter interface {
|
||||
// EnsureStream creates the stream if absent and updates it to match if present. It must be
|
||||
// idempotent: the controller asserts on every start, not only at genesis.
|
||||
EnsureStream(s Stream) error
|
||||
}
|
||||
|
||||
// AssertMeshStreams brings the foundation set into being, in order, and says which one failed
|
||||
// rather than that something did.
|
||||
//
|
||||
// Asserted on every start rather than created once at genesis, because a stream that was deleted,
|
||||
// or a mesh raised from a restored backup, must converge rather than run without the guarantee
|
||||
// its messages assume. Idempotence is the whole requirement.
|
||||
func AssertMeshStreams(a Asserter) error {
|
||||
for _, s := range MeshStreams() {
|
||||
if err := a.EnsureStream(s); err != nil {
|
||||
return fmt.Errorf("asserting stream %s: %w", s.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Overlaps reports subject filters claimed by more than one stream.
|
||||
//
|
||||
// **Corrected against the server**: an earlier version of this comment said NATS accepts
|
||||
// overlapping streams and stores the message twice. It does not — it refuses the second stream
|
||||
// with "subjects overlap with an existing stream" (verified against nats-server 2.10). The check
|
||||
// still earns its place, for a different reason: the server's refusal arrives when the controller
|
||||
// is applying, naming one stream, at a moment when the mesh is half-configured. This one arrives
|
||||
// where the set is written, names both, and cannot reach a running mesh.
|
||||
//
|
||||
// It also decides a design question. Because overlap is refused rather than merged, a shared
|
||||
// EVENTS stream and a per-module stream cannot coexist — the module's would be refused — so
|
||||
// "one stream for most, its own for a module that wants different retention" is not an option
|
||||
// the server allows. It is all of one or all of the other.
|
||||
func Overlaps() []string {
|
||||
seen := map[string]string{}
|
||||
var clashes []string
|
||||
for _, s := range MeshStreams() {
|
||||
for _, subject := range s.Subjects {
|
||||
if first, ok := seen[subject]; ok {
|
||||
clashes = append(clashes, fmt.Sprintf("%s and %s both claim %s", first, s.Name, subject))
|
||||
continue
|
||||
}
|
||||
seen[subject] = s.Name
|
||||
}
|
||||
}
|
||||
sort.Strings(clashes)
|
||||
return clashes
|
||||
}
|
||||
|
||||
// The mesh's own consumers.
|
||||
//
|
||||
// A seat's streams and a module's consumers are derived from declarations (derived.go). These two
|
||||
// are not: **the controller is not a module and files no manifest**, so its authority and its
|
||||
// subscriptions cannot come from a declaration that does not exist. They are named here, where the
|
||||
// mesh's own streams are named, and narrowly — a controller subscribing `mesh.mod.*.event.>` would
|
||||
// hear every event in the mesh, which it has no business doing and which would make its permission
|
||||
// list stop explaining anything.
|
||||
|
||||
// ControllerName is the controller's durable consumer on each stream it reads, and the name its
|
||||
// ack subject is derived from (nats.go: `$JS.ACK.<stream>.controller.>`).
|
||||
const ControllerName = "controller"
|
||||
|
||||
// ControllerSeat is the role the control plane holds, and ControllerStates are the facts it states
|
||||
// under it (novox/hq ADR 0134).
|
||||
//
|
||||
// **Written here as well as in `link`, and a test keeps them agreeing.** `link` imports `broker`, so
|
||||
// `broker` cannot import `link`; a grant naming a subject the controller never publishes is authority
|
||||
// nobody uses, and a controller publishing one the grant omits is refused at the moment it has
|
||||
// something to say.
|
||||
const ControllerSeat = "mesh-controller"
|
||||
|
||||
var ControllerStates = []string{"applied", "refused", "built-before"}
|
||||
|
||||
// ControllerFollows are the events the controller reacts to: the catalogue saying a module's
|
||||
// current version moved, and a catalogue that has just started saying it may have missed builds.
|
||||
//
|
||||
// **Derived the same way a module's subscription is**, from the emitter and the bare local event
|
||||
// name, rather than written out. They were written out while the catalogue still spelled its events
|
||||
// as the old bus's routing keys, and the moment those were converted (novox/hq 04-ISSUES/127) a
|
||||
// hard-coded pair became a controller listening to a subject nothing publishes — the same fault, from
|
||||
// the other side. Deriving them means the conversion could not leave these behind.
|
||||
var ControllerFollows = []string{
|
||||
moduleEventSubject("mesh-catalog", "upgraded"),
|
||||
moduleEventSubject("mesh-catalog", "catching-up"),
|
||||
// A build's outcome, which is the build-machine role's own event now (ADR 0121) rather than a
|
||||
// message on the control branch. Same three audiences, one publish: whoever asked, this, and the
|
||||
// catalogue.
|
||||
seatEventSubject("mesh-build-machine", "built"),
|
||||
// The forge's merges: what moved a source, so the mesh builds what that source produces
|
||||
// without anybody telling it (novox/hq 04-ISSUES/131). Appended, because the index is a name.
|
||||
moduleEventSubject("gitea", "pull.merged"),
|
||||
}
|
||||
|
||||
// moduleEventSubject is where one module's event lands. The same derivation PermissionsFor uses, so
|
||||
// what the controller subscribes and what the emitter is permitted to publish cannot drift apart.
|
||||
func moduleEventSubject(module, event string) string {
|
||||
return "mesh.mod." + module + ".event." + event
|
||||
}
|
||||
|
||||
// seatEventSubject is where a role's own event lands, derived the same way a holder's permission is.
|
||||
func seatEventSubject(seat, verb string) string {
|
||||
return "mesh.seat." + seat + ".event." + verb
|
||||
}
|
||||
|
||||
// MeshConsumers is what the controller consumes, in the order a person reads it.
|
||||
//
|
||||
// **Unlimited redelivery on CONTROL, deliberately.** The store window's bound is the controller's,
|
||||
// not the server's (window.go): a message is held with a nak-and-delay until the controller either
|
||||
// takes it or gives up and says so. A max-deliver here would dead-letter a push that was being
|
||||
// held through a store restart — the exact message the stream exists to protect — some minutes
|
||||
// before the controller had finished deciding about it.
|
||||
func MeshConsumers() []Consumer {
|
||||
return []Consumer{
|
||||
{
|
||||
Name: ControllerName,
|
||||
Stream: "CONTROL",
|
||||
Push: true,
|
||||
AckWaitSeconds: 30,
|
||||
Why: "the controller is the single consumer of what nodes say; explicit ack and no " +
|
||||
"max-deliver, because the store window's bound is the controller's own",
|
||||
},
|
||||
{
|
||||
Name: ControllerName,
|
||||
Stream: "EVENTS",
|
||||
Filters: ControllerFollows,
|
||||
Push: true,
|
||||
AckWaitSeconds: 30,
|
||||
MaxDeliver: 5,
|
||||
// One at a time (novox/hq issue 175): acting on a merge builds for minutes, and an
|
||||
// announcement handed over behind it must wait on the server, not time out on the
|
||||
// client and come back to be acted on again.
|
||||
MaxAckPending: 1,
|
||||
Why: "the two events the mesh's own controller reacts to, one at a time; after " +
|
||||
"max-deliver it dead-letters, because an announcement it cannot act on will not " +
|
||||
"become actionable",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Ensurer is the part of a JetStream connection consumer assertion needs, narrow for the reason
|
||||
// Asserter is.
|
||||
type Ensurer interface {
|
||||
EnsureConsumer(c Consumer) error
|
||||
}
|
||||
|
||||
// AssertMeshConsumers brings the controller's own consumers into being, and says which one failed.
|
||||
//
|
||||
// After the streams, necessarily: a consumer on a stream that does not exist is refused, and the
|
||||
// refusal names the stream rather than the order.
|
||||
func AssertMeshConsumers(e Ensurer) error {
|
||||
for _, c := range MeshConsumers() {
|
||||
if err := e.EnsureConsumer(c); err != nil {
|
||||
return fmt.Errorf("asserting consumer %s on %s: %w", c.Name, c.Stream, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type recorder struct {
|
||||
seen []Stream
|
||||
fail string
|
||||
}
|
||||
|
||||
func (r *recorder) EnsureStream(s Stream) error {
|
||||
if s.Name == r.fail {
|
||||
return errors.New("refused")
|
||||
}
|
||||
r.seen = append(r.seen, s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The controller asserts on every start, not only at genesis: a stream that was deleted, or a mesh
|
||||
// raised from a backup, must converge rather than run without the guarantee its messages assume.
|
||||
func TestAssertingTwiceIsTheSameAsOnce(t *testing.T) {
|
||||
a, b := &recorder{}, &recorder{}
|
||||
if err := AssertMeshStreams(a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := AssertMeshStreams(a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := AssertMeshStreams(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(a.seen) != 2*len(b.seen) {
|
||||
t.Fatalf("asserted %d then %d; assertion is not repeatable", len(a.seen), len(b.seen))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailedAssertionNamesItsStream(t *testing.T) {
|
||||
err := AssertMeshStreams(&recorder{fail: "NODES"})
|
||||
if err == nil || !strings.Contains(err.Error(), "NODES") {
|
||||
t.Fatalf("got %v, which does not say which stream failed", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Two streams matching one subject is accepted by NATS and stores the message twice under two
|
||||
// retentions. Nothing reports that, so it is refused where the set is written.
|
||||
func TestNoTwoStreamsClaimTheSameSubject(t *testing.T) {
|
||||
if clashes := Overlaps(); len(clashes) != 0 {
|
||||
t.Fatalf("overlapping subject filters: %v", clashes)
|
||||
}
|
||||
}
|
||||
|
||||
// A heartbeat under mesh.control.> must not be persisted: a lost one is the next one, and a
|
||||
// stream of them competes for retention with the messages that matter.
|
||||
func TestHeartbeatsAreNotInTheControlStream(t *testing.T) {
|
||||
for _, s := range MeshStreams() {
|
||||
for _, subject := range s.Subjects {
|
||||
if subject == "mesh.control.>" || strings.Contains(subject, "alive") {
|
||||
t.Fatalf("stream %s claims %q, which captures heartbeats", s.Name, subject)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The reason the kind token exists: a filter over a module's whole namespace would persist every
|
||||
// tool call in the mesh.
|
||||
func TestTheEventsStreamDoesNotCaptureToolCalls(t *testing.T) {
|
||||
var events Stream
|
||||
for _, s := range MeshStreams() {
|
||||
if s.Name == "EVENTS" {
|
||||
events = s
|
||||
}
|
||||
}
|
||||
// Nothing a tool call rides may match any of the filters — a module's or a seat's.
|
||||
for _, tool := range []string{
|
||||
"mesh.mod.billing.tool.status",
|
||||
"mesh.seat.telegram-sender.tool.status",
|
||||
"mesh.seat.telegram-sender.accept.send", // work, not an event: its own stream
|
||||
} {
|
||||
for _, f := range events.Subjects {
|
||||
if subjectMatches(f, tool) {
|
||||
t.Fatalf("%q matches the events filter %q, so it would be persisted here", tool, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
// And both kinds of event do match.
|
||||
for _, event := range []string{
|
||||
"mesh.mod.billing.event.order.placed",
|
||||
"mesh.seat.telegram-sender.event.delivered",
|
||||
} {
|
||||
matched := false
|
||||
for _, f := range events.Subjects {
|
||||
if subjectMatches(f, event) {
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
t.Fatalf("%q matches no events filter, so nothing would keep it", event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// subjectMatches is NATS subject matching, enough for these filters: `*` is one token, `>` is the
|
||||
// rest.
|
||||
func subjectMatches(filter, subject string) bool {
|
||||
f, s := strings.Split(filter, "."), strings.Split(subject, ".")
|
||||
for i, tok := range f {
|
||||
if tok == ">" {
|
||||
return i <= len(s)
|
||||
}
|
||||
if i >= len(s) {
|
||||
return false
|
||||
}
|
||||
if tok != "*" && tok != s[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(f) == len(s)
|
||||
}
|
||||
|
||||
// Each relationship's retention is the thing that makes it what it is (design 29 §4).
|
||||
func TestEachStreamCarriesTheRetentionItsShapeNeeds(t *testing.T) {
|
||||
want := map[string]Retention{
|
||||
"CONTROL": RetentionWorkQueue,
|
||||
"NODES": RetentionLastPerSubject,
|
||||
"EVENTS": RetentionLimits,
|
||||
}
|
||||
got := map[string]Retention{}
|
||||
for _, s := range MeshStreams() {
|
||||
got[s.Name] = s.Retention
|
||||
if s.Why == "" {
|
||||
t.Errorf("stream %s says no reason it exists", s.Name)
|
||||
}
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("the foundation set is %v", got)
|
||||
}
|
||||
for name, r := range want {
|
||||
if got[name] != r {
|
||||
t.Errorf("%s retains as %q, expected %q", name, got[name], r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The order the bus's objects are asserted in, because getting it wrong is a refusal that names the
|
||||
// wrong thing: a consumer on a stream that does not exist is refused naming the *stream*, so
|
||||
// somebody reading it goes looking for a deletion instead of a reversed pair of lines.
|
||||
func TestTheBusesObjectsAreAssertedStreamsBeforeConsumers(t *testing.T) {
|
||||
r := &recording{}
|
||||
if err := Raise(r, []string{"anchor", "laptop"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Every stream before every consumer.
|
||||
firstConsumer := -1
|
||||
for i, step := range r.steps {
|
||||
if strings.HasPrefix(step, "consumer ") && firstConsumer < 0 {
|
||||
firstConsumer = i
|
||||
}
|
||||
if strings.HasPrefix(step, "stream ") && firstConsumer >= 0 {
|
||||
t.Fatalf("a stream was asserted after a consumer: %v", r.steps)
|
||||
}
|
||||
}
|
||||
if firstConsumer < 0 {
|
||||
t.Fatalf("no consumer was asserted: %v", r.steps)
|
||||
}
|
||||
|
||||
// And every node got one, named after it — without which that node hears nothing while
|
||||
// everything else about it looks correct.
|
||||
for _, node := range []string{"anchor", "laptop"} {
|
||||
if !containsStep(r.steps, "consumer NODES/"+node) {
|
||||
t.Errorf("%s was given no way to hear its declaration: %v", node, r.steps)
|
||||
}
|
||||
}
|
||||
// And the controller its own, on both streams it reads.
|
||||
for _, want := range []string{"consumer CONTROL/controller", "consumer EVENTS/controller"} {
|
||||
if !containsStep(r.steps, want) {
|
||||
t.Errorf("the controller is missing %s: %v", want, r.steps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A seat's work queue is asserted whether or not anybody holds it; the holder's worker only when
|
||||
// somebody does. **The stream without the consumer is the point**: work queues until a holder
|
||||
// appears, so installing the module later flushes the backlog instead of having lost it.
|
||||
func TestASeatsQueueExistsBeforeItsHolderDoes(t *testing.T) {
|
||||
seats := []DeclaredSeat{{Name: "telegram-sender", Accepts: []string{"send"}}}
|
||||
|
||||
unheld := &recording{}
|
||||
if err := RaiseSeats(unheld, seats, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !containsStep(unheld.steps, "stream SEAT_TELEGRAM_SENDER") {
|
||||
t.Fatalf("a declared seat got no work queue: %v", unheld.steps)
|
||||
}
|
||||
for _, step := range unheld.steps {
|
||||
if strings.HasPrefix(step, "consumer ") {
|
||||
t.Fatalf("a seat nobody holds got a worker: %v", unheld.steps)
|
||||
}
|
||||
}
|
||||
|
||||
held := &recording{}
|
||||
if err := RaiseSeats(held, seats, map[string]Holder{
|
||||
"telegram-sender": {Node: "anchor", Module: "telegram"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !containsStep(held.steps, "consumer SEAT_TELEGRAM_SENDER/SEAT_TELEGRAM_SENDER_worker") {
|
||||
t.Fatalf("the seat's holder got no worker: %v", held.steps)
|
||||
}
|
||||
}
|
||||
|
||||
// recording is a connection to the bus that writes down what it was asked for.
|
||||
type recording struct{ steps []string }
|
||||
|
||||
func (r *recording) EnsureStream(s Stream) error {
|
||||
r.steps = append(r.steps, "stream "+s.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *recording) EnsureConsumer(c Consumer) error {
|
||||
r.steps = append(r.steps, "consumer "+c.Stream+"/"+c.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func containsStep(steps []string, want string) bool {
|
||||
for _, s := range steps {
|
||||
if s == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// **Two consumers may share a name, and must not share a delivery subject** (novox/hq
|
||||
// 04-ISSUES/146).
|
||||
//
|
||||
// A push consumer delivers onto an ordinary subject and everything subscribed to it gets a copy.
|
||||
// The controller holds a consumer called `controller` on CONTROL and another called `controller` on
|
||||
// EVENTS; while both were given `_DELIVER.controller`, the one process holding both subscriptions
|
||||
// acted on every message twice — a joining machine enrolled twice from one request, with the second
|
||||
// enrolment minting a credential that replaced the one the machine had just been handed.
|
||||
//
|
||||
// Checked here rather than against a server because it is a property of what the mesh asks for, and
|
||||
// because the failure it produces is silent: every count is right, nothing is redelivered, and the
|
||||
// work simply happens twice.
|
||||
func TestNoTwoConsumersDeliverOntoTheSameSubject(t *testing.T) {
|
||||
seen := map[string]string{}
|
||||
for _, c := range MeshConsumers() {
|
||||
if !c.Push && c.Queue == "" {
|
||||
continue
|
||||
}
|
||||
subject := DeliverSubjectFor(c)
|
||||
if other, taken := seen[subject]; taken {
|
||||
t.Errorf("%s on %s and %s deliver onto %s, so whoever holds both acts on every "+
|
||||
"message twice", c.Name, c.Stream, other, subject)
|
||||
}
|
||||
seen[subject] = c.Name + " on " + c.Stream
|
||||
}
|
||||
}
|
||||
|
||||
// The controller's events consumer is handed one announcement at a time (novox/hq issue 175): a
|
||||
// merge's handler builds for minutes, and what is queued behind it must wait on the server rather
|
||||
// than time out on the client and be acted on twice.
|
||||
func TestTheControllerTakesOneAnnouncementAtATime(t *testing.T) {
|
||||
for _, c := range MeshConsumers() {
|
||||
if c.Stream == "EVENTS" && c.Name == ControllerName && c.MaxAckPending != 1 {
|
||||
t.Fatalf("the events consumer may have %d outstanding; one announcement at a time", c.MaxAckPending)
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# Composed by the mesh controller. Do not edit: the next composition overwrites it.
|
||||
# Accounts and permissions are derived from what each module declares and nothing
|
||||
# else (novox/hq ADR 0043, design 29 §2).
|
||||
|
||||
port: 4222
|
||||
http: 127.0.0.1:8222
|
||||
|
||||
tls {
|
||||
cert_file: "/tls/tls.crt"
|
||||
key_file: "/tls/tls.key"
|
||||
ca_file: "/tls/ca.crt"
|
||||
}
|
||||
|
||||
jetstream {
|
||||
store_dir: "/data"
|
||||
}
|
||||
|
||||
# The mesh's users, composed by the controller. Do not edit: the next
|
||||
# composition overwrites it. Permissions are derived from what each module
|
||||
# declares and nothing else (novox/hq ADR 0043, design 29 §2).
|
||||
|
||||
accounts {
|
||||
MESH {
|
||||
jetstream: enabled
|
||||
users = [
|
||||
{ user: "controller", password: "$2a$11$cccccccccccccccccccccc", permissions: {
|
||||
publish: { allow: ["$JS.ACK.CONTROL.controller.>", "$JS.ACK.EVENTS.controller.>", "$JS.API.>", "_INBOX.enrol.>", "mesh.control.>", "mesh.mod.*.tool.>", "mesh.node.>", "mesh.seat.mesh-build-machine.accept.>", "mesh.seat.mesh-controller.event.applied", "mesh.seat.mesh-controller.event.built-before", "mesh.seat.mesh-controller.event.refused"] }
|
||||
subscribe: { allow: ["$JS.API.>", "_DELIVER.controller", "_DELIVER.controller.>", "_INBOX.controller.>", "mesh.control.>", "mesh.mod.gitea.event.pull.merged", "mesh.mod.mesh-catalog.event.catching-up", "mesh.mod.mesh-catalog.event.upgraded", "mesh.seat.mesh-build-machine.event.built", "mesh.seat.mesh-controller.tool.>"] }
|
||||
allow_responses: { max: 1, ttl: "1m" }
|
||||
} }
|
||||
{ user: "enrol.one", password: "$2a$11$eeeeeeeeeeeeeeeeeeeeee", permissions: {
|
||||
publish: { allow: ["mesh.control.enrol"] }
|
||||
subscribe: { allow: ["_INBOX.enrol.one.>"] }
|
||||
} }
|
||||
{ user: "node.one", password: "$2a$11$nnnnnnnnnnnnnnnnnnnnnn", permissions: {
|
||||
publish: { allow: ["$JS.ACK.NODES.one.>", "$JS.API.CONSUMER.INFO.NODES.one", "mesh.control.one.>"] }
|
||||
subscribe: { allow: ["_DELIVER.one", "_DELIVER.one.>", "_INBOX.node.one.>", "mesh.node.one.declare"] }
|
||||
} }
|
||||
{ user: "one.telegram", password: "$2a$11$tttttttttttttttttttttt", permissions: {
|
||||
publish: { allow: ["$JS.ACK.EVENTS.one_telegram.>", "$JS.ACK.SEAT_TELEGRAM_SENDER.SEAT_TELEGRAM_SENDER_worker.>", "$JS.API.CONSUMER.INFO.EVENTS.one_telegram", "$JS.API.CONSUMER.INFO.SEAT_TELEGRAM_SENDER.SEAT_TELEGRAM_SENDER_worker", "$JS.API.CONSUMER.MSG.NEXT.EVENTS.one_telegram", "mesh.seat.telegram-sender.event.delivered", "mesh.seat.telegram-sender.event.failed"] }
|
||||
subscribe: { allow: ["_DELIVER.SEAT_TELEGRAM_SENDER_worker", "_DELIVER.SEAT_TELEGRAM_SENDER_worker.>", "_INBOX.one.telegram.>", "mesh.mod.telegram.tool.>", "mesh.seat.telegram-sender.accept.send"] }
|
||||
allow_responses: { max: 1, ttl: "1m" }
|
||||
} }
|
||||
{ user: "two.audit", password: "$2a$11$aaaaaaaaaaaaaaaaaaaaaa", permissions: {
|
||||
publish: { allow: ["$JS.ACK.EVENTS.two_audit.>", "$JS.API.CONSUMER.INFO.EVENTS.two_audit", "$JS.API.CONSUMER.MSG.NEXT.EVENTS.two_audit"] }
|
||||
subscribe: { allow: ["_INBOX.two.audit.>", "mesh.mod.audit.tool.>", "mesh.mod.shop.event.order.placed"] }
|
||||
allow_responses: { max: 1, ttl: "1m" }
|
||||
} }
|
||||
{ user: "two.shop", password: "$2a$11$ssssssssssssssssssssss", permissions: {
|
||||
publish: { allow: ["$JS.ACK.EVENTS.two_shop.>", "$JS.API.CONSUMER.INFO.EVENTS.two_shop", "$JS.API.CONSUMER.MSG.NEXT.EVENTS.two_shop", "mesh.mod.shop.event.order.placed", "mesh.seat.telegram-sender.accept.send"] }
|
||||
subscribe: { allow: ["_INBOX.two.shop.>", "mesh.mod.shop.tool.>"] }
|
||||
allow_responses: { max: 1, ttl: "1m" }
|
||||
} }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Every user the composed file should contain, derived from what the mesh knows.
|
||||
//
|
||||
// **The list is derived, never kept.** A stored user list would be a second account of who may
|
||||
// reach the bus, able to disagree with the records it came from — and the disagreement would be
|
||||
// invisible, because both would look internally consistent. So this is a pure function of the
|
||||
// mesh's records, run again every time the file is written.
|
||||
//
|
||||
// Records are mirrored into this package's own types rather than imported from the catalogue, for
|
||||
// the reason DeclaredSeat is: composing authority is a different job from parsing a manifest, and
|
||||
// this package stays free of the other's types so a change to a manifest field cannot quietly widen
|
||||
// a permission.
|
||||
|
||||
// Declared is one module on one node, as composing its authority needs it.
|
||||
type Declared struct {
|
||||
Module string
|
||||
Emits []string
|
||||
Consumes []string
|
||||
Serves []string
|
||||
// Holds are the seats this module claims, with the protocol each seat declares. A seat the
|
||||
// mesh defines for itself declares no protocol, so holding one grants nothing on the bus —
|
||||
// which is right: those seats are about who does a job, not about who may say what.
|
||||
Holds []Seat
|
||||
// Uses are the seats this module sends to.
|
||||
Uses []Seat
|
||||
// Watches are the seats whose events it consumes.
|
||||
Watches []Seat
|
||||
// Invokes are the tools it calls, `<module>.<tool>` or `*` (novox/hq ADR 0152).
|
||||
Invokes []string
|
||||
}
|
||||
|
||||
// Records is what composing a user list needs to know about the mesh, and nothing more.
|
||||
type Records struct {
|
||||
// Nodes is every machine the mesh knows. Each gets a host user.
|
||||
Nodes []string
|
||||
// Assigned is the modules on each node, as they declare themselves.
|
||||
Assigned map[string][]Declared
|
||||
// Enrolling is every node with a live token — one enrolment user each, because the inbox an
|
||||
// answer goes to is scoped to the token and a shared one is one machine reading another's
|
||||
// sealed credentials (design 25 §6).
|
||||
Enrolling []string
|
||||
// People is each person's name against the tools they may invoke, `*` for an administrator.
|
||||
People map[string][]string
|
||||
}
|
||||
|
||||
// Users is every user the composed file should contain, in the order it will be written.
|
||||
//
|
||||
// The controller is always first and always present: a mesh whose own controller is not in the file
|
||||
// is a mesh that cannot be told anything, and there is no state of the records in which that is
|
||||
// correct.
|
||||
func Users(r Records) ([]Principal, error) {
|
||||
out := []Principal{{Kind: KindController}}
|
||||
|
||||
for _, node := range sortedCopy(r.Nodes) {
|
||||
out = append(out, Principal{Kind: KindNode, Node: node})
|
||||
for _, d := range r.Assigned[node] {
|
||||
out = append(out, Principal{
|
||||
Kind: KindModule, Node: node, Module: d.Module,
|
||||
Emits: d.Emits, Consumes: d.Consumes, Serves: d.Serves,
|
||||
Holds: d.Holds, Uses: d.Uses, Watches: d.Watches, Invokes: d.Invokes,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, node := range sortedCopy(r.Enrolling) {
|
||||
out = append(out, Principal{Kind: KindEnrolment, Node: node})
|
||||
}
|
||||
for _, person := range sortedNames(r.People) {
|
||||
out = append(out, Principal{Kind: KindPerson, Module: person, Invokes: r.People[person]})
|
||||
}
|
||||
|
||||
// Refused here rather than discovered by the server. Two users with one name is a file the
|
||||
// server reads as one of them, and which one depends on the order — so a module assigned to a
|
||||
// node twice, or a person named after nothing, is a composition that must not be written.
|
||||
seen := map[string]string{}
|
||||
for _, p := range out {
|
||||
name := p.Username()
|
||||
if name == "" || name == "." {
|
||||
return nil, fmt.Errorf("a %s user has no name, so nothing could authenticate as it", p.Kind)
|
||||
}
|
||||
if first, already := seen[name]; already {
|
||||
return nil, fmt.Errorf(
|
||||
"two users would be called %q (a %s and a %s): the server would read the file as "+
|
||||
"one of them, and which one depends on the order", name, first, p.Kind)
|
||||
}
|
||||
seen[name] = string(p.Kind)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WithPasswords fills each user's hash from what the mesh minted, and says which users have none.
|
||||
//
|
||||
// **Separated from Users because they fail differently.** A user missing from the records is a bug
|
||||
// in deriving them; a user with no password is a step that has not happened yet — a module assigned
|
||||
// but never given a credential, a node enrolled before this existed. The second is ordinary and its
|
||||
// remedy is to mint one, so it is named rather than returned as an error, and the caller decides
|
||||
// whether a partial composition is worth writing.
|
||||
func WithPasswords(principals []Principal, hashes map[string]string) (filled []Principal, missing []string) {
|
||||
for _, p := range principals {
|
||||
hash, ok := hashes[p.Username()]
|
||||
if !ok || hash == "" {
|
||||
missing = append(missing, p.Username())
|
||||
continue
|
||||
}
|
||||
p.PasswordHash = hash
|
||||
filled = append(filled, p)
|
||||
}
|
||||
return filled, missing
|
||||
}
|
||||
|
||||
func sortedCopy(in []string) []string {
|
||||
out := append([]string(nil), in...)
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func sortedNames(in map[string][]string) []string {
|
||||
out := make([]string, 0, len(in))
|
||||
for k := range in {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Deriving the bus's user list from the mesh's records.
|
||||
//
|
||||
// Every test here is about a way the list could be wrong that the server would not tell anybody
|
||||
// about: a user missing, a user named twice, a user with authority it did not declare.
|
||||
|
||||
func someRecords() Records {
|
||||
return Records{
|
||||
Nodes: []string{"two", "one"},
|
||||
Assigned: map[string][]Declared{
|
||||
"one": {{Module: "telegram", Serves: []string{"status"}}},
|
||||
"two": {{Module: "shop", Emits: []string{"order.placed"}}},
|
||||
},
|
||||
Enrolling: []string{"three"},
|
||||
People: map[string][]string{"ada": {"mesh-catalog.catalog_tools"}},
|
||||
}
|
||||
}
|
||||
|
||||
func namesOf(t *testing.T, r Records) []string {
|
||||
t.Helper()
|
||||
users, err := Users(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := make([]string, 0, len(users))
|
||||
for _, u := range users {
|
||||
out = append(out, u.Username())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The controller is always there. A mesh whose own controller is not in the file is a mesh that
|
||||
// cannot be told anything, and there is no state of the records in which that is correct.
|
||||
func TestTheControllerIsAlwaysInTheList(t *testing.T) {
|
||||
for _, r := range []Records{{}, someRecords()} {
|
||||
names := namesOf(t, r)
|
||||
if len(names) == 0 || names[0] != "controller" {
|
||||
t.Fatalf("the controller is not first in %v", names)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One user per node, one per module per node, one per live token and one per person — and nothing
|
||||
// else, because a user nobody derived is a user nobody can explain.
|
||||
func TestEveryRecordBecomesExactlyOneUser(t *testing.T) {
|
||||
names := namesOf(t, someRecords())
|
||||
want := []string{
|
||||
"controller",
|
||||
"node.one", "one.telegram",
|
||||
"node.two", "two.shop",
|
||||
"enrol.three",
|
||||
"person.ada",
|
||||
}
|
||||
if strings.Join(names, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("derived %v\n want %v", names, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Two users with one name is a file the server reads as one of them, and which one depends on the
|
||||
// order. Refused here, where both can be named, rather than left to be whichever the server picked.
|
||||
func TestTwoUsersWithOneNameAreRefused(t *testing.T) {
|
||||
r := someRecords()
|
||||
r.Assigned["one"] = append(r.Assigned["one"], Declared{Module: "telegram"})
|
||||
_, err := Users(r)
|
||||
if err == nil {
|
||||
t.Fatal("a module assigned twice to one node composed two users with one name")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "one.telegram") {
|
||||
t.Fatalf("the refusal does not name the user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A module's authority is what it declared and nothing more, carried through the derivation intact —
|
||||
// because this is the step where a mistake would grant something no manifest asked for.
|
||||
func TestAModulesAuthorityIsWhatItDeclared(t *testing.T) {
|
||||
seat := Seat{Name: "telegram-sender", Accepts: []string{"send"}, Emits: []string{"delivered"}}
|
||||
users, err := Users(Records{
|
||||
Nodes: []string{"one"},
|
||||
Assigned: map[string][]Declared{"one": {{
|
||||
Module: "shop", Emits: []string{"order.placed"}, Uses: []Seat{seat},
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
perms, err := PermissionsFor(users[len(users)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
has(t, perms.Publish, "mesh.mod.shop.event.order.placed")
|
||||
has(t, perms.Publish, "mesh.seat.telegram-sender.accept.send")
|
||||
// A seat it uses, not one it holds: it may submit work and may not publish the seat's own
|
||||
// events, or it could lie about outcomes on a role somebody else fills.
|
||||
hasNot(t, perms.Publish, "mesh.seat.telegram-sender.event.delivered")
|
||||
hasNot(t, perms.Subscribe, "mesh.seat.telegram-sender.accept.send")
|
||||
}
|
||||
|
||||
// A user the mesh has never minted a password for is named rather than silently dropped or
|
||||
// composed as a user anybody is. It is an ordinary situation — a module assigned a moment ago — and
|
||||
// the remedy is to mint one, so the caller decides whether to write a partial file.
|
||||
func TestAUserWithNoPasswordIsNamedRatherThanWritten(t *testing.T) {
|
||||
users, err := Users(someRecords())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filled, missing := WithPasswords(users, map[string]string{
|
||||
"controller": "$2a$hash", "node.one": "$2a$hash",
|
||||
})
|
||||
if len(filled) != 2 {
|
||||
t.Fatalf("composed %d users from two hashes", len(filled))
|
||||
}
|
||||
if len(missing) != len(users)-2 {
|
||||
t.Fatalf("%d users are missing a password, of %d: %v", len(missing), len(users), missing)
|
||||
}
|
||||
for _, p := range filled {
|
||||
if p.PasswordHash == "" {
|
||||
t.Fatalf("%s was kept with no password, which is a user anybody is", p.Username())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// And the whole thing composes: records in, a file the server would read out.
|
||||
func TestRecordsComposeIntoAFile(t *testing.T) {
|
||||
users, err := Users(someRecords())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hashes := map[string]string{}
|
||||
for _, u := range users {
|
||||
hashes[u.Username()] = "$2a$11$" + strings.Repeat("x", 22)
|
||||
}
|
||||
filled, missing := WithPasswords(users, hashes)
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("users with no password: %v", missing)
|
||||
}
|
||||
got, err := Compose(Server{ClientPort: 4222, MonitoringPort: 8222, StoreDir: "/data",
|
||||
TLSCert: "/tls/tls.crt", TLSKey: "/tls/tls.key", TLSCA: "/tls/ca.crt"}, filled)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`user: "controller"`, `user: "node.one"`, `user: "one.telegram"`,
|
||||
`user: "enrol.three"`, `user: "person.ada"`,
|
||||
`"_INBOX.enrol.three.>"`, `"mesh.mod.mesh-catalog.tool.catalog_tools"`,
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("the composed file does not contain %s", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The accounts block alone is what the mesh writes, and it holds nothing about the server.
|
||||
//
|
||||
// **The split is the whole design decision** (ComposeAccounts): ports, TLS paths and a store
|
||||
// directory are properties of the container the module raises, and a controller that wrote them
|
||||
// would have to be kept in step with a Dockerfile it never sees. So this test says what must not be
|
||||
// in the file as plainly as what must.
|
||||
func TestWhatTheMeshWritesIsUsersAndNothingAboutTheServer(t *testing.T) {
|
||||
users, err := Users(someRecords())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hashes := map[string]string{}
|
||||
for _, u := range users {
|
||||
hashes[u.Username()] = "$2a$11$" + strings.Repeat("x", 22)
|
||||
}
|
||||
filled, missing := WithPasswords(users, hashes)
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("users with no password: %v", missing)
|
||||
}
|
||||
got, err := ComposeAccounts(filled)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, want := range []string{"accounts {", `user: "controller"`, `user: "one.telegram"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("the accounts file does not contain %s", want)
|
||||
}
|
||||
}
|
||||
// None of the server's own settings. Each of these in the mesh's file is a value the controller
|
||||
// would then own, and the module could no longer change its own image without the mesh agreeing.
|
||||
// `jetstream {` is the server's block (its store, its limits); `jetstream: enabled` inside the
|
||||
// account is the account's, and the mesh owns the account — a user in it is told "JetStream
|
||||
// not enabled for account" without it (2026-09-28).
|
||||
if !strings.Contains(got, "jetstream: enabled") {
|
||||
t.Errorf("the account does not enable JetStream, so no user in it can bind a consumer")
|
||||
}
|
||||
for _, absent := range []string{"port:", "http:", "jetstream {", "tls {", "store_dir", "cert_file"} {
|
||||
if strings.Contains(got, absent) {
|
||||
t.Errorf("the accounts file contains %q, which belongs to the module that raises the "+
|
||||
"server, not to the mesh", absent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A user with no password is refused here too, not only by the whole-file composition: this is the
|
||||
// function the controller actually calls, and a user without a password is a user anybody is.
|
||||
func TestTheAccountsFileRefusesAUserWithNoPassword(t *testing.T) {
|
||||
if _, err := ComposeAccounts([]Principal{{Kind: KindController}}); err == nil {
|
||||
t.Fatal("a user with no password hash was written")
|
||||
}
|
||||
}
|
||||
|
||||
// **A user list is composed for a bus the mesh has not moved onto yet**, and that is the whole of
|
||||
// step 2 (novox/hq ADR 0116): the server stands in the mesh carrying nothing, on its own ports, while
|
||||
// every node is still on the bus it was on.
|
||||
//
|
||||
// Pinned because the first version of the composing step got it backwards — it wrote the list only
|
||||
// once the controller was already on the new bus, which is a step that cannot be taken: the module
|
||||
// comes up, finds no accounts file, and waits for one the controller had decided not to write.
|
||||
func TestAUserListIsComposedBeforeAnythingMovesOntoTheBus(t *testing.T) {
|
||||
// Exactly the records of a mesh mid-change: everything running, nothing on the new bus.
|
||||
users, err := Users(Records{
|
||||
Nodes: []string{"anchor"},
|
||||
Assigned: map[string][]Declared{"anchor": {{Module: "nats"}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hashes := map[string]string{}
|
||||
for _, u := range users {
|
||||
hashes[u.Username()] = "$2a$11$" + strings.Repeat("x", 22)
|
||||
}
|
||||
filled, missing := WithPasswords(users, hashes)
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("users with no credential: %v", missing)
|
||||
}
|
||||
accounts, err := ComposeAccounts(filled)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The controller's own user above all: a file without it is a bus its writer cannot connect to,
|
||||
// which is what the server would be left holding the moment it starts.
|
||||
if !strings.Contains(accounts, `user: "controller"`) {
|
||||
t.Fatalf("the composed list does not contain the controller:\n%s", accounts)
|
||||
}
|
||||
if !strings.Contains(accounts, `user: "node.anchor"`) {
|
||||
t.Errorf("the composed list does not contain the machine running the bus")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package builder
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// The name a machine runs a binary by is not always the name of the package that built it. The host's
|
||||
// command is cmd/mesh-host and every machine runs it as nox-mesh-host — the path it is installed at,
|
||||
// the name in its unit, and the name its launcher looks for inside a delivered version.
|
||||
//
|
||||
// A bundle carrying the package's name was delivered to a machine correctly, reported "created … 1
|
||||
// file(s)", and was invisible to the launcher (novox/hq 04-ISSUES/142). Found by reading the delivered
|
||||
// directory rather than by trusting the line that said it worked.
|
||||
|
||||
func TestACompiledArtifactNamesTheBinaryAMachineWillRun(t *testing.T) {
|
||||
got := binaryName(catalogue.Artifact{
|
||||
Name: "host-arch", From: "cmd/mesh-host", Binary: "nox-mesh-host",
|
||||
})
|
||||
if got != "nox-mesh-host" {
|
||||
t.Fatalf("the binary is named %q, and the launcher looks for nox-mesh-host", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSayingNothingKeepsWhatTheCompilerWouldHaveChosen(t *testing.T) {
|
||||
// go build names its output after the package, so an artifact that says nothing gets the same
|
||||
// thing it got before this existed.
|
||||
if got := binaryName(catalogue.Artifact{Name: "host-arch", From: "cmd/mesh-host"}); got != "mesh-host" {
|
||||
t.Fatalf("an artifact naming no binary produced %q", got)
|
||||
}
|
||||
if got := binaryName(catalogue.Artifact{Name: "host-arch", From: "./cmd/agent/"}); got != "agent" {
|
||||
t.Fatalf("a from with slashes produced %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestABundleBuiltFromTheModuleRootFallsBackToItsArtifactName(t *testing.T) {
|
||||
// A single-command repository names no package, and `go build -o <dir>` would then write a file
|
||||
// named after the module directory — which is not something the manifest states. The artifact's
|
||||
// own name is what the manifest does state.
|
||||
if got := binaryName(catalogue.Artifact{Name: "tool"}); got != "tool" {
|
||||
t.Fatalf("a bundle built from the root produced %q", got)
|
||||
}
|
||||
}
|
||||
+163
-29
@@ -61,6 +61,12 @@ type Result struct {
|
||||
Commit string
|
||||
// Built is each artifact, for reporting.
|
||||
Built []catalogue.Built
|
||||
|
||||
// Read is every repository this build read source from besides the module's own — the second
|
||||
// repository an artifact's recipe names (ArtifactContext). Reported because the manifest the
|
||||
// mesh keeps carries no build section, so nothing else could say that a merge there is a
|
||||
// change to this module (novox/hq 04-ISSUES/131).
|
||||
Read []catalogue.ArtifactContext
|
||||
}
|
||||
|
||||
// GitCredential is the forge credential a clone may present when the server asks for one.
|
||||
@@ -84,7 +90,13 @@ type GitCredential struct {
|
||||
// records — reachable, unreferenced, and indistinguishable from something in use.
|
||||
func Build(ctx context.Context, run Runner, publish Publisher,
|
||||
repository, path, ref, workspace string, held map[string]string, npmrc Npmrc,
|
||||
forge GitCredential, log Log) (Result, error) {
|
||||
forge GitCredential, log Log, seats ...map[string]string) (Result, error) {
|
||||
// The clone base of each seat a context may name (novox/hq ADR 0155); variadic so the callers
|
||||
// that hand none — tests of everything but contexts — read as they did.
|
||||
var seatBases map[string]string
|
||||
if len(seats) > 0 {
|
||||
seatBases = seats[0]
|
||||
}
|
||||
|
||||
say := logging(log)
|
||||
say("clone", "%s%s at %s", repository, describePath(path), refOrHead(ref))
|
||||
@@ -169,6 +181,8 @@ func Build(ctx context.Context, run Runner, publish Publisher,
|
||||
}
|
||||
|
||||
var built []catalogue.Built
|
||||
// stoodOn is every base the build was handed, as resolved — the edges the catalogue derives.
|
||||
var stoodOn []string
|
||||
if manifest.Build != nil {
|
||||
// What this module said it stands on, answered with what this mesh actually holds. Done
|
||||
// before anything is built, so a missing base is refused in front of the person who can
|
||||
@@ -186,11 +200,12 @@ func Build(ctx context.Context, run Runner, publish Publisher,
|
||||
}
|
||||
return from, nil
|
||||
}
|
||||
args, err := standingOn(ctx, manifest, held, mirror)
|
||||
args, bases, err := standingOn(ctx, manifest, held, mirror)
|
||||
if err != nil {
|
||||
say("bases", "UNMET: %v", err)
|
||||
return Result{}, err
|
||||
}
|
||||
stoodOn = bases
|
||||
if len(args) > 0 {
|
||||
say("bases", "%d resolved from what the mesh holds", len(args)/2)
|
||||
}
|
||||
@@ -200,7 +215,7 @@ func Build(ctx context.Context, run Runner, publish Publisher,
|
||||
sort.Slice(artifacts, func(i, j int) bool { return artifacts[i].Name < artifacts[j].Name })
|
||||
for _, a := range artifacts {
|
||||
say("artifact", "%s (%s%s) — starting", a.Name, a.Kind, langSuffix(a))
|
||||
made, err := one(ctx, run, publish, manifest.Module, within, workspace, commit, credentials, a, args, held, npmrcPath, say)
|
||||
made, err := one(ctx, run, publish, manifest.Module, within, workspace, commit, credentials, a, args, held, npmrcPath, seatBases, say)
|
||||
if err != nil {
|
||||
say("artifact", "%s FAILED: %v", a.Name, err)
|
||||
return Result{}, err
|
||||
@@ -217,7 +232,7 @@ func Build(ctx context.Context, run Runner, publish Publisher,
|
||||
}
|
||||
say("done", "%s at %s — %d artifact(s) pinned", manifest.Module, short(commit), len(built))
|
||||
return Result{Manifest: resolved, Commit: commit, Built: built,
|
||||
Against: against(within, manifest)}, nil
|
||||
Against: against(within, manifest, stoodOn), Read: readBy(manifest)}, nil
|
||||
}
|
||||
|
||||
// Log is where a build says what it is doing, step by step. Nil is silent — the tests pass none,
|
||||
@@ -237,14 +252,18 @@ func logging(log Log) func(step, format string, args ...any) {
|
||||
// module's own repository — a fresh tree, the same way the module's own is, keyed by artifact
|
||||
// name so two artifacts of one module naming different contexts do not collide.
|
||||
func contextFrom(ctx context.Context, run Runner, workspace, artifact, credentials string,
|
||||
from catalogue.ArtifactContext, say func(step, format string, args ...any)) (string, error) {
|
||||
say("context", "cloning %s at %s for %s", from.Repository, refOrHead(from.Ref), artifact)
|
||||
from catalogue.ArtifactContext, seats map[string]string, say func(step, format string, args ...any)) (string, error) {
|
||||
url, err := contextURL(from, seats)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
say("context", "cloning %s at %s for %s", url, refOrHead(from.Ref), artifact)
|
||||
dir := filepath.Join(workspace, "context-"+artifact)
|
||||
if err := os.RemoveAll(dir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := run(ctx, workspace, "git", cloneWith(credentials, "clone", "--quiet", from.Repository, dir)...); err != nil {
|
||||
return "", fmt.Errorf("cannot clone %s: %w", from.Repository, err)
|
||||
if _, err := run(ctx, workspace, "git", cloneWith(credentials, "clone", "--quiet", url, dir)...); err != nil {
|
||||
return "", fmt.Errorf("cannot clone %s: %w", url, err)
|
||||
}
|
||||
if from.Ref != "" {
|
||||
if _, err := run(ctx, dir, "git", "checkout", "--quiet", from.Ref); err != nil {
|
||||
@@ -255,6 +274,23 @@ func contextFrom(ctx context.Context, run Runner, workspace, artifact, credentia
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
// contextURL is what a context is cloned from: its URL, or — for a context on a seat — the seat's
|
||||
// clone base the mesh sent with the request joined to the repository's path (novox/hq ADR 0155).
|
||||
// Refused, never guessed, when the mesh sent no base for that seat: a builder that guessed a forge
|
||||
// would be the literal this removes, one layer down.
|
||||
func contextURL(from catalogue.ArtifactContext, seats map[string]string) (string, error) {
|
||||
if from.Seat == "" {
|
||||
return from.Repository, nil
|
||||
}
|
||||
base, told := seats[from.Seat]
|
||||
if !told || base == "" {
|
||||
return "", fmt.Errorf("the context is %s on the %s seat, and this build was told no clone "+
|
||||
"base for that seat — nothing holds it in this mesh, or the control plane predates the word",
|
||||
from.Repository, from.Seat)
|
||||
}
|
||||
return strings.TrimRight(base, "/") + "/" + strings.TrimSuffix(strings.Trim(from.Repository, "/"), ".git") + ".git", nil
|
||||
}
|
||||
|
||||
// cloneWith is a git invocation that may offer a stored credential.
|
||||
//
|
||||
// The first `-c credential.helper=` clears every helper the environment might carry, so exactly
|
||||
@@ -339,14 +375,27 @@ func describe(path string) string {
|
||||
// allowed to name — a tag is something somebody else can move under you.
|
||||
var pinnedImage = regexp.MustCompile(`[A-Za-z0-9][A-Za-z0-9._/:-]*@sha256:[0-9a-f]{64}`)
|
||||
|
||||
// against reads what this module's image artifacts are built on top of, out of the files that
|
||||
// build them. Nothing is guessed: a reference that is not written down is not reported.
|
||||
func against(within string, manifest catalogue.Manifest) []string {
|
||||
// against is what this module's image artifacts are built on top of: every base the mesh resolved
|
||||
// and handed the recipe as a build argument (`build.on`), and any image a recipe pins by digest
|
||||
// itself. Nothing is guessed: a reference that was neither resolved nor written down is not
|
||||
// reported.
|
||||
//
|
||||
// **The resolved bases are the edges.** A recipe reads its base from an argument (`FROM
|
||||
// ${RUNTIME_BASE}`), so the digest is never in the file, and a derivation that read files alone
|
||||
// recorded no edge for any module on the mesh — which is why nothing knew what a changed base
|
||||
// meant to rebuild (novox/hq 04-ISSUES/131).
|
||||
func against(within string, manifest catalogue.Manifest, resolved []string) []string {
|
||||
if manifest.Build == nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, r := range resolved {
|
||||
if r != "" && !seen[r] {
|
||||
seen[r] = true
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
for _, a := range manifest.Build.Artifacts {
|
||||
if a.Kind != catalogue.ArtifactImage || a.From == "" {
|
||||
continue
|
||||
@@ -394,7 +443,8 @@ func wantsPackages(manifest catalogue.Manifest, within string) bool {
|
||||
|
||||
func one(ctx context.Context, run Runner, publish Publisher,
|
||||
module, tree, workspace, commit, credentials string, a catalogue.Artifact, args []string,
|
||||
held map[string]string, npmrc string, say func(step, format string, args ...any)) (catalogue.Built, error) {
|
||||
held map[string]string, npmrc string, seats map[string]string,
|
||||
say func(step, format string, args ...any)) (catalogue.Built, error) {
|
||||
|
||||
switch a.Kind {
|
||||
case catalogue.ArtifactUpstream:
|
||||
@@ -471,7 +521,7 @@ func one(ctx context.Context, run Runner, publish Publisher,
|
||||
recipePath := a.From
|
||||
buildDir := tree
|
||||
if a.Context != nil {
|
||||
cloned, err := contextFrom(ctx, run, workspace, a.Name, credentials, *a.Context, say)
|
||||
cloned, err := contextFrom(ctx, run, workspace, a.Name, credentials, *a.Context, seats, say)
|
||||
if err != nil {
|
||||
return catalogue.Built{}, fmt.Errorf("%s: %s's context: %w", module, a.Name, err)
|
||||
}
|
||||
@@ -704,40 +754,42 @@ var _ io.Writer = (*stringWriter)(nil)
|
||||
// built cannot be built here yet, and the useful sentence names which module is missing — not the
|
||||
// one a container runtime produces when a recipe's first line refers to an image nobody has.
|
||||
//
|
||||
// The order is fixed so two builds of one commit invoke the same command.
|
||||
// The order is fixed so two builds of one commit invoke the same command. Returned alongside the
|
||||
// arguments is every reference they resolved to, which is what the build stood on.
|
||||
func standingOn(ctx context.Context, manifest catalogue.Manifest, held map[string]string,
|
||||
mirror func(ctx context.Context, from, repository string) (string, error)) ([]string, error) {
|
||||
mirror func(ctx context.Context, from, repository string) (string, error)) ([]string, []string, error) {
|
||||
if manifest.Build == nil || len(manifest.Build.On) == 0 {
|
||||
return nil, nil
|
||||
return nil, nil, nil
|
||||
}
|
||||
on := append([]catalogue.BuildsOn{}, manifest.Build.On...)
|
||||
sort.Slice(on, func(i, j int) bool { return on[i].Arg < on[j].Arg })
|
||||
|
||||
var args []string
|
||||
var args, resolved []string
|
||||
for _, base := range on {
|
||||
if base.Image != "" {
|
||||
// A vendor's image, declared (novox/hq 04-ISSUES/064, ADR 0097). Pinned, because a tag
|
||||
// is what somebody else can move; copied into the mesh's registry, because a build
|
||||
// that reaches a public registry on its own is a build that works sometimes.
|
||||
if base.Arg == "" || base.Module != "" || base.Artifact != "" {
|
||||
return nil, fmt.Errorf(
|
||||
return nil, nil, fmt.Errorf(
|
||||
"%s stands on the image %s, and a base is either a module's artifact or an "+
|
||||
"image — never both — read from one build argument", manifest.Module, base.Image)
|
||||
}
|
||||
if !strings.Contains(base.Image, "@sha256:") {
|
||||
return nil, fmt.Errorf(
|
||||
return nil, nil, fmt.Errorf(
|
||||
"%s stands on the image %q, which is not pinned by digest. A tag is what "+
|
||||
"somebody else can move; name it as <image>@sha256:…", manifest.Module, base.Image)
|
||||
}
|
||||
reference, err := mirror(ctx, base.Image, manifest.Module+"/on-"+strings.ToLower(base.Arg))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s stands on %s: %w", manifest.Module, base.Image, err)
|
||||
return nil, nil, fmt.Errorf("%s stands on %s: %w", manifest.Module, base.Image, err)
|
||||
}
|
||||
args = append(args, "--build-arg", base.Arg+"="+reference)
|
||||
resolved = append(resolved, reference)
|
||||
continue
|
||||
}
|
||||
if base.Arg == "" || base.Module == "" || base.Artifact == "" {
|
||||
return nil, fmt.Errorf(
|
||||
return nil, nil, fmt.Errorf(
|
||||
"%s says its build stands on something, and does not say all of what: a base "+
|
||||
"needs the module, the artifact, and the build argument the recipe reads it "+
|
||||
"from", manifest.Module)
|
||||
@@ -745,14 +797,15 @@ func standingOn(ctx context.Context, manifest catalogue.Manifest, held map[strin
|
||||
key := base.Module + "/" + base.Artifact
|
||||
reference, has := held[key]
|
||||
if !has {
|
||||
return nil, fmt.Errorf(
|
||||
return nil, nil, fmt.Errorf(
|
||||
"%s builds on %s, and this mesh has not built it. Build %s first — every module "+
|
||||
"in this toolchain stands on it, so it is the thing to have before anything "+
|
||||
"else", manifest.Module, key, base.Module)
|
||||
}
|
||||
args = append(args, "--build-arg", base.Arg+"="+reference)
|
||||
resolved = append(resolved, reference)
|
||||
}
|
||||
return args, nil
|
||||
return args, resolved, nil
|
||||
}
|
||||
|
||||
// compile runs a module's own code through its toolchain, and says where the result is.
|
||||
@@ -836,6 +889,15 @@ func compile(ctx context.Context, run Runner, tree string, chain Toolchain,
|
||||
// each other and then be packed together, so each bundle compiles and packs alone.
|
||||
out := Out(a.Name)
|
||||
|
||||
// **The output directory exists before the compiler is told about it.** `tsc --outDir` makes
|
||||
// one; `go build -o` writes a file into a directory and does not create it, failing with a
|
||||
// message about a path rather than about a build. Made here for every toolchain, because which
|
||||
// compilers happen to be forgiving is not a thing a reader should have to know
|
||||
// (novox/hq 04-ISSUES/142).
|
||||
if err := os.MkdirAll(filepath.Join(tree, out), 0o755); err != nil {
|
||||
return "", fmt.Errorf("making the output directory for %s: %w", a.Name, err)
|
||||
}
|
||||
|
||||
invocation := []string{
|
||||
"run", "--rm",
|
||||
"--volume", tree + ":" + within,
|
||||
@@ -843,13 +905,43 @@ func compile(ctx context.Context, run Runner, tree string, chain Toolchain,
|
||||
base,
|
||||
}
|
||||
invocation = append(invocation, chain.Compile...)
|
||||
// **One `-ldflags`, composed here.** A repeated flag is not a merged one: the Go command takes
|
||||
// the last and drops the first, so passing the toolchain's flags and then the system stamp as a
|
||||
// second `-ldflags` produced a binary that knew its system and had lost `-s -w` — half again the
|
||||
// size, with its debug info (novox/hq 04-ISSUES/161).
|
||||
//
|
||||
// What it was built for is the one thing taken from the artifact, and ADR 0142 says why: the
|
||||
// target is a property of the artifact rather than of the recipe. A host with no system refuses
|
||||
// every declaration before it applies anything.
|
||||
linker := append([]string(nil), chain.LinkerFlags...)
|
||||
if chain.SystemStamp != "" && strings.TrimSpace(a.System) != "" {
|
||||
linker = append(linker, "-X", chain.SystemStamp+"="+strings.TrimSpace(a.System))
|
||||
}
|
||||
if len(linker) > 0 {
|
||||
invocation = append(invocation, "-ldflags", strings.Join(linker, " "))
|
||||
}
|
||||
if chain.OutputFlag != "" {
|
||||
invocation = append(invocation, chain.OutputFlag, out)
|
||||
// A compiler pointed at a package is told the file to write, not the directory: the name a
|
||||
// machine runs it by is not always the name of the package that built it. The host's command
|
||||
// is `cmd/mesh-host` and every machine runs it as `nox-mesh-host` — so a bundle carrying the
|
||||
// package's name lands correctly, reports success, and is invisible to whatever looks for it
|
||||
// (novox/hq 04-ISSUES/142).
|
||||
target := out
|
||||
if chain.Unit == UnitPackage {
|
||||
target = filepath.Join(out, binaryName(a))
|
||||
}
|
||||
invocation = append(invocation, chain.OutputFlag, target)
|
||||
}
|
||||
// What to compile. Named by the module rather than discovered, so adding a file does not
|
||||
// silently change what a build produces.
|
||||
if len(a.Entrypoints) > 0 {
|
||||
invocation = append(invocation, sourcesFor(a.Entrypoints, out)...)
|
||||
switch {
|
||||
case chain.Unit == UnitPackage:
|
||||
// One directory, compiled whole: the thing the artifact is built `from`. Relative, because
|
||||
// the compiler runs with the module's own root as its working directory and a package path
|
||||
// that looked absolute would name one inside the toolchain image.
|
||||
invocation = append(invocation, "./"+strings.Trim(a.From, "./"))
|
||||
case len(a.Entrypoints) > 0:
|
||||
invocation = append(invocation, sourcesFor(a.Entrypoints, out, chain.SourceExt)...)
|
||||
}
|
||||
if _, err := run(ctx, tree, "docker", invocation...); err != nil {
|
||||
return "", err
|
||||
@@ -862,14 +954,16 @@ func compile(ctx context.Context, run Runner, tree string, chain Toolchain,
|
||||
// A module names what a tool host should LOAD — compiled paths under the bundle's root — because
|
||||
// that is the thing anything else needs to know. What to compile is the same list with the
|
||||
// language's own extension, which is the toolchain's business rather than the module's.
|
||||
func sourcesFor(entrypoints []string, out string) []string {
|
||||
func sourcesFor(entrypoints []string, out, ext string) []string {
|
||||
sources := make([]string, 0, len(entrypoints))
|
||||
for _, e := range entrypoints {
|
||||
// An entrypoint is named as it will be FOUND — a path inside the unpacked bundle — so the
|
||||
// source is the same path with the output directory taken off the front and the language's
|
||||
// own extension on the end.
|
||||
// own extension on the end. **The extension is the toolchain's**, where it used to be the
|
||||
// literal `.ts`: one language's file extension written into the code that serves every
|
||||
// language is a wall the next one hits (novox/hq 04-ISSUES/142).
|
||||
at := strings.TrimPrefix(strings.TrimPrefix(e, out), "/")
|
||||
sources = append(sources, strings.TrimSuffix(at, filepath.Ext(at))+".ts")
|
||||
sources = append(sources, strings.TrimSuffix(at, filepath.Ext(at))+ext)
|
||||
}
|
||||
return sources
|
||||
}
|
||||
@@ -997,3 +1091,43 @@ func instructions(recipe string) []string {
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
// readBy is every repository other than the module's own that this build's recipes read source from,
|
||||
// each once and in a fixed order, so two builds of one commit report the same thing the same way.
|
||||
func readBy(manifest catalogue.Manifest) []catalogue.ArtifactContext {
|
||||
if manifest.Build == nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []catalogue.ArtifactContext
|
||||
for _, a := range manifest.Build.Artifacts {
|
||||
if a.Context == nil || a.Context.Repository == "" {
|
||||
continue
|
||||
}
|
||||
key := a.Context.Repository + "#" + a.Context.Ref
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, *a.Context)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Repository != out[j].Repository {
|
||||
return out[i].Repository < out[j].Repository
|
||||
}
|
||||
return out[i].Ref < out[j].Ref
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// binaryName is what a compiled bundle's executable is called: what the artifact says, or the name of
|
||||
// the package it is built from, which is what a compiler would have chosen anyway.
|
||||
func binaryName(a catalogue.Artifact) string {
|
||||
if name := strings.TrimSpace(a.Binary); name != "" {
|
||||
return name
|
||||
}
|
||||
if from := strings.Trim(a.From, "./"); from != "" {
|
||||
return filepath.Base(from)
|
||||
}
|
||||
return a.Name
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package builder
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/novox/mesh-controller/internal/catalogue"
|
||||
)
|
||||
|
||||
// A context on a seat is cloned from the base the mesh sent, joined to the repository's path; a
|
||||
// context by URL is itself; a seat the mesh sent no base for is refused by name (novox/hq ADR 0155).
|
||||
func TestAContextOnASeatIsClonedFromTheBaseTheMeshSent(t *testing.T) {
|
||||
seats := map[string]string{"git": "http://forge.example.tld:3000"}
|
||||
got, err := contextURL(catalogue.ArtifactContext{Seat: "git", Repository: "org/controller"}, seats)
|
||||
if err != nil || got != "http://forge.example.tld:3000/org/controller.git" {
|
||||
t.Fatalf("got %q, %v", got, err)
|
||||
}
|
||||
got, err = contextURL(catalogue.ArtifactContext{Repository: "https://elsewhere.example/x.git"}, seats)
|
||||
if err != nil || got != "https://elsewhere.example/x.git" {
|
||||
t.Fatalf("a URL context was changed: %q, %v", got, err)
|
||||
}
|
||||
_, err = contextURL(catalogue.ArtifactContext{Seat: "git", Repository: "org/controller"}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "git seat") {
|
||||
t.Fatalf("a seat with no base was not refused by name: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package builder
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Nothing could compile the mesh's own components, which is why nothing delivers the host
|
||||
// (novox/hq 04-ISSUES/142, and ADR 0141's own insight naming it). The toolchain list was a closed
|
||||
// set of typescript and python, and two things in the path beyond it assumed TypeScript.
|
||||
|
||||
func TestTheMeshCanCompileGo(t *testing.T) {
|
||||
chain, err := ToolchainFor("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Named, not pinned: the mesh answers with the copy it holds, so moving compiler is a build
|
||||
// rather than an edit to this source (ADR 0044, 0142).
|
||||
if chain.Base != "mesh-tools-go" || chain.Artifact != "build" {
|
||||
t.Fatalf("the go toolchain is based on %s/%s", chain.Base, chain.Artifact)
|
||||
}
|
||||
joined := strings.Join(chain.Compile, " ")
|
||||
// Static, because what a machine holds is a file and not a container: a binary needing a libc
|
||||
// it did not bring is a delivery that works until a machine differs.
|
||||
if !strings.Contains(joined, "CGO_ENABLED=0") {
|
||||
t.Fatalf("the go toolchain does not build statically: %q", joined)
|
||||
}
|
||||
// Reproducible: a version comes from where a component sits, not from its linker (ADR 0142),
|
||||
// so two builds of one commit should produce the same bytes.
|
||||
if !strings.Contains(joined, "-trimpath") {
|
||||
t.Fatalf("the go toolchain leaves build paths in the binary: %q", joined)
|
||||
}
|
||||
if chain.Unit != UnitPackage {
|
||||
t.Fatalf("the go toolchain compiles %q, wanted a package", chain.Unit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryToolchainSaysWhatItIsPointedAt(t *testing.T) {
|
||||
// The field exists because the compile path used to assume one language. A toolchain that says
|
||||
// nothing would fall through to the entrypoint branch and compile a file list, which for a
|
||||
// compiled language builds a program out of exactly those files and ignores the rest of the
|
||||
// package — a missing symbol rather than a legible refusal.
|
||||
for _, chain := range toolchains {
|
||||
switch chain.Unit {
|
||||
case UnitPackage:
|
||||
case UnitSources:
|
||||
if chain.SourceExt == "" {
|
||||
t.Fatalf("%s compiles a file list and names no source extension", chain.Language)
|
||||
}
|
||||
if !strings.HasPrefix(chain.SourceExt, ".") {
|
||||
t.Fatalf("%s's source extension %q is not an extension", chain.Language, chain.SourceExt)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s says it is pointed at %q, which is neither sources nor a package",
|
||||
chain.Language, chain.Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnEntrypointBecomesASourceInItsOwnLanguage(t *testing.T) {
|
||||
// It used to become a `.ts` whatever the language was.
|
||||
out := Out("build")
|
||||
got := sourcesFor([]string{out + "/tools/index.js"}, out, ".ts")
|
||||
if len(got) != 1 || got[0] != "tools/index.ts" {
|
||||
t.Fatalf("a typescript entrypoint became %v", got)
|
||||
}
|
||||
got = sourcesFor([]string{out + "/tools/index.js"}, out, ".py")
|
||||
if len(got) != 1 || got[0] != "tools/index.py" {
|
||||
t.Fatalf("a python entrypoint became %v", got)
|
||||
}
|
||||
}
|
||||
@@ -180,6 +180,20 @@ func (r Registry) MirrorImage(ctx context.Context, from, repository string) (str
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// **Already held is already mirrored.** A base is named by digest, and a digest this registry
|
||||
// holds under the module's repository is the same bytes whatever upstream would say — so
|
||||
// upstream is not asked. Asked every build, the public hub's anonymous pull limit was reached
|
||||
// on the first merge that rebuilt a whole catalogue (2026-09-28), and every module whose base
|
||||
// lives there failed on a copy it did not need.
|
||||
if strings.HasPrefix(where.reference, "sha256:") {
|
||||
held, err := r.has(ctx, "http://"+r.Address+"/v2/"+repository+"/manifests/"+where.reference, manifestAccept)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("asking %s whether it holds %s: %w", r.Address, from, err)
|
||||
}
|
||||
if held {
|
||||
return r.Address + "/" + repository + "@" + where.reference, nil
|
||||
}
|
||||
}
|
||||
src := &source{client: r.client()}
|
||||
digest, err := r.copyManifest(ctx, src, where, where.reference, repository)
|
||||
if err != nil {
|
||||
|
||||
@@ -103,6 +103,20 @@ func (m *theMeshsRegistry) handler() http.Handler {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
switch {
|
||||
case r.Method == http.MethodHead && strings.Contains(r.URL.Path, "/manifests/"):
|
||||
// **As strictly as a real registry.** A manifest is answered only in a media type the
|
||||
// caller named; a request with no Accept is answered as if nothing were there. The fake
|
||||
// used to answer regardless, which is why it could not catch a check that asked without
|
||||
// one — and the mesh copied every base again (2026-09-28).
|
||||
if !strings.Contains(r.Header.Get("Accept"), "manifest") && !strings.Contains(r.Header.Get("Accept"), "index") {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if _, ok := m.manifests[r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]]; ok {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
case r.Method == http.MethodHead && strings.Contains(r.URL.Path, "/blobs/"):
|
||||
if _, ok := m.blobs[r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]]; ok {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
@@ -219,3 +233,27 @@ func TestATagBeforeTheDigestIsNotPartOfTheRepository(t *testing.T) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A base this registry already holds by digest is not asked of upstream at all: the public hub
|
||||
// limits anonymous pulls, and a catalogue rebuilt on one merge asked it once per module.
|
||||
func TestABaseAlreadyHeldIsNotAskedOfUpstream(t *testing.T) {
|
||||
src, indexDigest, _ := anUpstreamRegistry(t)
|
||||
dst := &theMeshsRegistry{blobs: map[string][]byte{}, manifests: map[string][]byte{}}
|
||||
dstServer := httptest.NewServer(dst.handler())
|
||||
defer dstServer.Close()
|
||||
address := strings.TrimPrefix(dstServer.URL, "http://")
|
||||
r := Registry{Address: address, HTTP: src.Client()}
|
||||
host := strings.TrimPrefix(src.URL, "http://")
|
||||
if _, err := r.MirrorImage(context.Background(), host+"/library/thing:latest", "hello-web/server"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Upstream gone: the pinned base is answered from what the mesh holds.
|
||||
src.Close()
|
||||
reference, err := r.MirrorImage(context.Background(), host+"/library/thing@"+indexDigest, "hello-web/server")
|
||||
if err != nil {
|
||||
t.Fatalf("a base the registry holds was asked of an upstream that is gone: %v", err)
|
||||
}
|
||||
if reference != address+"/hello-web/server@"+indexDigest {
|
||||
t.Fatalf("pinned as %q", reference)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,11 +122,23 @@ func (r Registry) PublishArchive(ctx context.Context, repository string, body []
|
||||
return final, nil
|
||||
}
|
||||
|
||||
func (r Registry) has(ctx context.Context, url string) (bool, error) {
|
||||
// has is whether this registry already holds what is at that URL.
|
||||
//
|
||||
// **A manifest HEAD must say what it accepts.** A registry answers a manifest request only in a media
|
||||
// type the caller named, and a bare HEAD — no Accept at all — is answered 404 for a manifest it holds
|
||||
// perfectly well. Measured against the mesh's own registry (2026-09-28): the same digest answered 200
|
||||
// with the manifest media types and 404 without them, so a check written without them concluded the
|
||||
// registry held nothing, copied every base again, and exhausted the public hub's pull limit. A blob
|
||||
// needs no Accept, which is why this went unnoticed: the same helper was right for blobs and wrong
|
||||
// for manifests.
|
||||
func (r Registry) has(ctx context.Context, url string, accept ...string) (bool, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, media := range accept {
|
||||
request.Header.Add("Accept", media)
|
||||
}
|
||||
response, err := r.client().Do(request)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("cannot reach the registry at %s: %w", r.Address, err)
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestABaseTheMeshHasNotBuiltIsRefused(t *testing.T) {
|
||||
On: []catalogue.BuildsOn{{Arg: "RUNTIME_BASE", Module: "mesh-tools", Artifact: "runtime"}},
|
||||
},
|
||||
}
|
||||
_, err := standingOn(context.Background(), manifest, map[string]string{}, noMirror)
|
||||
_, _, err := standingOn(context.Background(), manifest, map[string]string{}, noMirror)
|
||||
if err == nil {
|
||||
t.Fatal("a base nothing has built was accepted; the build would have failed on its first line")
|
||||
}
|
||||
@@ -42,7 +42,7 @@ func TestABaseTheMeshHoldsBecomesABuildArgument(t *testing.T) {
|
||||
},
|
||||
}
|
||||
held := map[string]string{"mesh-tools/runtime": "127.0.0.1:5000/mesh-tools/runtime@sha256:" + strings.Repeat("a", 64)}
|
||||
args, err := standingOn(context.Background(), manifest, held, noMirror)
|
||||
args, _, err := standingOn(context.Background(), manifest, held, noMirror)
|
||||
if err != nil {
|
||||
t.Fatalf("a base this mesh holds was refused: %v", err)
|
||||
}
|
||||
@@ -54,7 +54,7 @@ func TestABaseTheMeshHoldsBecomesABuildArgument(t *testing.T) {
|
||||
|
||||
// A module naming no base asks for nothing, which is most modules.
|
||||
func TestAModuleNamingNoBaseAddsNoArguments(t *testing.T) {
|
||||
args, err := standingOn(context.Background(), catalogue.Manifest{Module: "hello-web", Build: &catalogue.Build{}}, nil, noMirror)
|
||||
args, _, err := standingOn(context.Background(), catalogue.Manifest{Module: "hello-web", Build: &catalogue.Build{}}, nil, noMirror)
|
||||
if err != nil || args != nil {
|
||||
t.Fatalf("a module naming no base produced %v, %v", args, err)
|
||||
}
|
||||
@@ -66,7 +66,7 @@ func TestAnIncompleteBaseIsRefused(t *testing.T) {
|
||||
Module: "postgres",
|
||||
Build: &catalogue.Build{On: []catalogue.BuildsOn{{Module: "mesh-tools", Artifact: "runtime"}}},
|
||||
}
|
||||
if _, err := standingOn(context.Background(), manifest, map[string]string{"mesh-tools/runtime": "x"}, noMirror); err == nil {
|
||||
if _, _, err := standingOn(context.Background(), manifest, map[string]string{"mesh-tools/runtime": "x"}, noMirror); err == nil {
|
||||
t.Fatal("a base with no build argument was accepted; nothing would have read it")
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ func TestADeclaredVendorImageIsCopiedInAndHandedToTheRecipe(t *testing.T) {
|
||||
},
|
||||
}
|
||||
var asked []string
|
||||
args, err := standingOn(context.Background(), manifest, nil, func(_ context.Context, from, repository string) (string, error) {
|
||||
args, _, err := standingOn(context.Background(), manifest, nil, func(_ context.Context, from, repository string) (string, error) {
|
||||
asked = append(asked, from+" -> "+repository)
|
||||
return "127.0.0.1:5000/" + repository + "@sha256:" + strings.Repeat("d", 64), nil
|
||||
})
|
||||
@@ -101,7 +101,7 @@ func TestADeclaredVendorImageIsCopiedInAndHandedToTheRecipe(t *testing.T) {
|
||||
}
|
||||
// Unpinned, it is refused: a tag is what somebody else can move.
|
||||
manifest.Build.On[0].Image = "quay.io/minio/mc:latest"
|
||||
if _, err := standingOn(context.Background(), manifest, nil, noMirror); err == nil || !strings.Contains(err.Error(), "not pinned") {
|
||||
if _, _, err := standingOn(context.Background(), manifest, nil, noMirror); err == nil || !strings.Contains(err.Error(), "not pinned") {
|
||||
t.Fatalf("an unpinned vendor image was accepted: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -151,3 +151,52 @@ func TestARecipeIsReadAsInstructions(t *testing.T) {
|
||||
t.Fatalf("a heredoc line or a continued stage was read as a base: %v", bases)
|
||||
}
|
||||
}
|
||||
|
||||
// What a build was handed as its bases is what it stood on — recorded, so a changed base knows what
|
||||
// to rebuild (novox/hq 04-ISSUES/131). A recipe reads the base from an argument, so nothing else
|
||||
// could know.
|
||||
func TestTheBasesABuildWasHandedAreWhatItStoodOn(t *testing.T) {
|
||||
manifest := catalogue.Manifest{
|
||||
Module: "gitea",
|
||||
Build: &catalogue.Build{
|
||||
On: []catalogue.BuildsOn{
|
||||
{Arg: "RUNTIME_BASE", Module: "mesh-tools", Artifact: "runtime"},
|
||||
{Arg: "BUILD_BASE", Module: "mesh-tools", Artifact: "build"},
|
||||
},
|
||||
Artifacts: []catalogue.Artifact{{Name: "runtime", Kind: catalogue.ArtifactImage, From: "Dockerfile"}},
|
||||
},
|
||||
}
|
||||
held := map[string]string{
|
||||
"mesh-tools/runtime": "127.0.0.1:5000/mesh-tools/runtime@sha256:" + strings.Repeat("a", 64),
|
||||
"mesh-tools/build": "127.0.0.1:5000/mesh-tools/build@sha256:" + strings.Repeat("b", 64),
|
||||
}
|
||||
_, resolved, err := standingOn(context.Background(), manifest, held, noMirror)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := against(t.TempDir(), manifest, resolved)
|
||||
if len(got) != 2 || got[0] != held["mesh-tools/build"] || got[1] != held["mesh-tools/runtime"] {
|
||||
t.Fatalf("the bases the build was handed were not what it stood on: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// What a build read besides its module's own repository is the second repository its recipes name,
|
||||
// each once: a module that packages source living elsewhere is affected when that source moves.
|
||||
func TestWhatABuildReadIsTheRepositoriesItsRecipesName(t *testing.T) {
|
||||
elsewhere := catalogue.ArtifactContext{Repository: "http://forge.internal:20000/novox/mesh-controller.git", Ref: "main"}
|
||||
manifest := catalogue.Manifest{
|
||||
Module: "builder",
|
||||
Build: &catalogue.Build{Artifacts: []catalogue.Artifact{
|
||||
{Name: "server", Kind: catalogue.ArtifactImage, From: "Dockerfile", Context: &elsewhere},
|
||||
{Name: "tools", Kind: catalogue.ArtifactImage, From: "Dockerfile", Context: &elsewhere},
|
||||
{Name: "config", Kind: catalogue.ArtifactArchive, From: "etc"},
|
||||
}},
|
||||
}
|
||||
read := readBy(manifest)
|
||||
if len(read) != 1 || read[0] != elsewhere {
|
||||
t.Fatalf("the repositories this build read are %+v", read)
|
||||
}
|
||||
if readBy(catalogue.Manifest{Module: "gitea", Build: &catalogue.Build{}}) != nil {
|
||||
t.Fatal("a module whose recipes name no other repository read one")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package builder
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A host built without knowing its system refuses every declaration before applying anything —
|
||||
// safely, totally, and with nothing reporting it. The mesh built one, delivered it, started it, and
|
||||
// it would have refused the first thing it was asked to do (novox/hq 04-ISSUES/161).
|
||||
|
||||
func TestTheGoToolchainStampsTheArtifactsSystem(t *testing.T) {
|
||||
chain, err := ToolchainFor("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chain.SystemStamp != "main.builtFor" {
|
||||
t.Fatalf("the go toolchain fills %q", chain.SystemStamp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestALanguageWithNoPinnedSystemStampsNothing(t *testing.T) {
|
||||
// Interpreted output is not pinned to a system, and a manifest declaring one for it is already
|
||||
// refused. Nothing to fill.
|
||||
for _, language := range []string{"typescript", "python"} {
|
||||
chain, err := ToolchainFor(language)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chain.SystemStamp != "" {
|
||||
t.Fatalf("%s fills %q, and its output is not pinned to a system",
|
||||
language, chain.SystemStamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheStampIsTheOneThingTakenFromTheArtifact(t *testing.T) {
|
||||
// The toolchain accepts nothing else from the module — anything it could override it would be
|
||||
// writing a Dockerfile to override. The system is the stated exception, because a compiled
|
||||
// binary is per system and the artifact is what declares one (ADR 0142).
|
||||
chain, err := ToolchainFor("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined := strings.Join(chain.Compile, " ")
|
||||
if strings.Contains(joined, "${") || strings.Contains(joined, "%s") {
|
||||
t.Fatalf("the compile line takes something from the module: %q", joined)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheLinkerIsToldOnceNotTwice(t *testing.T) {
|
||||
// A repeated flag is not a merged one: the Go command takes the last -ldflags and drops the
|
||||
// first. Passing the toolchain's flags and then the stamp separately produced a binary that knew
|
||||
// its system and had lost -s -w — 12.2MB against 8.5MB, with its debug info (04-ISSUES/161).
|
||||
chain, err := ToolchainFor("go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, arg := range chain.Compile {
|
||||
if arg == "-ldflags" {
|
||||
t.Fatal("the compile line carries -ldflags, so composing one here makes two")
|
||||
}
|
||||
}
|
||||
if len(chain.LinkerFlags) == 0 {
|
||||
t.Fatal("the go toolchain passes no linker flags, so the binary keeps its debug info")
|
||||
}
|
||||
var stripped bool
|
||||
for _, f := range chain.LinkerFlags {
|
||||
if f == "-s" {
|
||||
stripped = true
|
||||
}
|
||||
}
|
||||
if !stripped {
|
||||
t.Fatalf("the go toolchain does not strip: %v", chain.LinkerFlags)
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,50 @@ type Toolchain struct {
|
||||
Compile []string
|
||||
// OutputFlag is how this compiler is told where to put its output.
|
||||
OutputFlag string
|
||||
// Unit is what this compiler is pointed at: UnitSources, the entrypoint files the module named,
|
||||
// or UnitPackage, the one directory the artifact is built `from`.
|
||||
//
|
||||
// **The difference is the language and not the module.** A TypeScript bundle is a set of files
|
||||
// compiled into a set of files, so what to compile is the module's entrypoints with their source
|
||||
// extension. A Go bundle is a package compiled into one binary, and there is no per-file
|
||||
// compilation to name — pointing `go build` at a file list builds a program out of exactly those
|
||||
// files and ignores the rest of the package, which fails as a missing symbol rather than as a
|
||||
// wrong instruction.
|
||||
Unit string
|
||||
// SourceExt is the extension an entrypoint has in the repository, for UnitSources. An entrypoint
|
||||
// is named as it will be FOUND, inside the unpacked bundle, so the source is the same path with
|
||||
// the output directory taken off the front and this on the end.
|
||||
SourceExt string
|
||||
// LinkerFlags are passed to the linker as one flag, together with the system stamp below.
|
||||
//
|
||||
// **Separate from Compile because a repeated flag is not a merged one.** They were in the compile
|
||||
// line, and appending the stamp as a second `-ldflags` meant the Go command took the last and
|
||||
// dropped the first — so the binary gained its system and lost `-s -w`, growing by half and
|
||||
// carrying its debug info. The mistake was believing a comment rather than reading the file it
|
||||
// produced (novox/hq 04-ISSUES/161).
|
||||
LinkerFlags []string
|
||||
// SystemStamp is the variable this language's linker fills with the artifact's declared system,
|
||||
// for a language whose binaries are pinned to one at link time (novox/hq ADR 0005).
|
||||
//
|
||||
// **The one thing a toolchain takes from the artifact, and 0142 says why**: the target is a
|
||||
// property of the artifact rather than of the recipe, because a compiled binary is per system
|
||||
// and a toolchain that accepted it from the module would be accepting a build instruction. This
|
||||
// is the narrow exception, named here rather than inferred.
|
||||
//
|
||||
// Empty for a language that compiles to nothing pinned. A host built without it refuses every
|
||||
// declaration before applying anything — safely, totally, and with nothing reporting it
|
||||
// (novox/hq 04-ISSUES/161).
|
||||
SystemStamp string
|
||||
}
|
||||
|
||||
// What a toolchain is pointed at.
|
||||
const (
|
||||
// UnitSources is a list of files, derived from the module's entrypoints.
|
||||
UnitSources = "sources"
|
||||
// UnitPackage is the single directory the artifact is built `from`, compiled whole.
|
||||
UnitPackage = "package"
|
||||
)
|
||||
|
||||
// Out is where one artifact's compiled output lands, inside the module's own directory.
|
||||
//
|
||||
// **Per artifact, never per toolchain.** A module is one piece of software and may still be
|
||||
@@ -71,6 +113,41 @@ var toolchains = []Toolchain{
|
||||
"--target", "ES2022",
|
||||
},
|
||||
OutputFlag: "--outDir",
|
||||
Unit: UnitSources,
|
||||
SourceExt: ".ts",
|
||||
},
|
||||
{
|
||||
Language: "go",
|
||||
Base: "mesh-tools-go",
|
||||
Artifact: "build",
|
||||
// **The mesh's own components, and not modules.** The warning above this list — that every
|
||||
// language is another implementation of the contracts modules share, so adding one commits
|
||||
// to keeping N implementations in step — does not attach here. Go is how the host, the
|
||||
// control plane and the builder are written, and none of them is a module in that sense:
|
||||
// the host is what APPLIES modules. So there is no SDK obligation, and the reason this
|
||||
// entry did not exist was that nothing needed to compile the mesh itself
|
||||
// (novox/hq ADR 0142, and 04-ISSUES/142 where that is why nothing delivers the host).
|
||||
//
|
||||
// Static, because what a machine ends up holding is a file rather than a container, and a
|
||||
// binary that needs a libc it did not bring is a delivery that works until a machine
|
||||
// differs. Trimmed of its own paths for the same reason a version comes from where it sits
|
||||
// rather than from the linker: two builds of one commit produce the same bytes.
|
||||
Compile: []string{
|
||||
"env", "CGO_ENABLED=0", "GOFLAGS=-trimpath",
|
||||
"go", "build",
|
||||
},
|
||||
// Stripped of symbols and debug info: what a machine holds is a file it runs, not one it
|
||||
// debugs, and the difference measured 12.2MB against 8.5MB.
|
||||
LinkerFlags: []string{"-s", "-w"},
|
||||
OutputFlag: "-o",
|
||||
// Pointed at the package the artifact is built `from`, compiled whole. Go writes the binary
|
||||
// into the output directory, named after the package — so the bundle a machine unpacks is a
|
||||
// directory holding one executable, which is what the delivery mechanism expects
|
||||
// (novox/hq ADR 0141).
|
||||
Unit: UnitPackage,
|
||||
// The mesh's own Go components read the system they were built for from this variable, and
|
||||
// refuse to touch a machine without one.
|
||||
SystemStamp: "main.builtFor",
|
||||
},
|
||||
{
|
||||
Language: "python",
|
||||
@@ -82,6 +159,8 @@ var toolchains = []Toolchain{
|
||||
// each actually does.
|
||||
Compile: []string{"python", "-m", "pip", "install", "--no-compile", "--target"},
|
||||
OutputFlag: "",
|
||||
Unit: UnitSources,
|
||||
SourceExt: ".py",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,11 @@ func anchorRendering(adopted bool) Rendering {
|
||||
Values: map[string]any{ExposeSetting: map[string]any{"5000": FromEverywhere}}}}},
|
||||
Mesh: []string{"10.42.0.1"},
|
||||
Foundation: []int{5671},
|
||||
Adopted: adopted,
|
||||
// What the machine reported faces outside, which every rule in the filter is written
|
||||
// around (novox/hq ADR 0140).
|
||||
OutwardLinks: []string{"eth0"},
|
||||
TunnelInterface: "mesh0",
|
||||
Adopted: adopted,
|
||||
// Genesis takes the foundation's modules.
|
||||
Taken: map[string]bool{"postgres": true, "lavinmq": true},
|
||||
}
|
||||
@@ -575,11 +579,13 @@ func TestAGivenMachineSideReachesTheFilterTheOpeningAndTheConsumer(t *testing.T)
|
||||
}
|
||||
r := Resolution{Node: "anchor", Modules: []Manifest{forge}}
|
||||
with := Rendering{
|
||||
Ports: map[string]map[int]int{"forge": portsAsThePlanWould(forge, given)},
|
||||
Given: map[string]map[int]int{"forge": given},
|
||||
Mesh: []string{"10.77.0.1"},
|
||||
Adopted: true,
|
||||
Taken: map[string]bool{"forge": true},
|
||||
Ports: map[string]map[int]int{"forge": portsAsThePlanWould(forge, given)},
|
||||
Given: map[string]map[int]int{"forge": given},
|
||||
Mesh: []string{"10.77.0.1"},
|
||||
Adopted: true,
|
||||
OutwardLinks: []string{"eth0"},
|
||||
TunnelInterface: "mesh0",
|
||||
Taken: map[string]bool{"forge": true},
|
||||
}
|
||||
|
||||
// What the runtime is handed: the machine's own port on the outside, the container's within.
|
||||
@@ -660,9 +666,11 @@ func TestALongFormPortIsOpenedWhereTheManifestPublishesIt(t *testing.T) {
|
||||
forge := aForge()
|
||||
r := Resolution{Node: "anchor", Modules: []Manifest{forge}}
|
||||
composed, err := r.Compose(Rendering{
|
||||
Ports: map[string]map[int]int{"forge": portsAsThePlanWould(forge, nil)},
|
||||
Mesh: []string{"10.77.0.1"},
|
||||
Adopted: true,
|
||||
Ports: map[string]map[int]int{"forge": portsAsThePlanWould(forge, nil)},
|
||||
Mesh: []string{"10.77.0.1"},
|
||||
Adopted: true,
|
||||
OutwardLinks: []string{"eth0"},
|
||||
TunnelInterface: "mesh0",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// **The word does not come back through a manifest** (novox/hq ADR 0131). A module that wants
|
||||
// messaging wants the mesh's bus, reached through the sdk and named by the `mesh-broker` seat. Naming
|
||||
// the old wire protocol asks for the one server being retired, so both directions are refused at the
|
||||
// parser — this is judged from the manifest alone, no store needed.
|
||||
|
||||
func TestAManifestProvidingAmqpIsRefused(t *testing.T) {
|
||||
raw := []byte(`{"module":"old-broker","version":"1","provides":[{"name":"amqp","scope":"mesh"}]}`)
|
||||
_, err := ParseManifest(raw)
|
||||
if err == nil || !strings.Contains(err.Error(), `provides "amqp", which is not a provision`) {
|
||||
t.Fatalf("a module providing amqp was not refused, or not for the reason: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAManifestRequiringAmqpIsRefused(t *testing.T) {
|
||||
raw := []byte(`{"module":"forwarder","version":"1","requires":["amqp"]}`)
|
||||
_, err := ParseManifest(raw)
|
||||
if err == nil || !strings.Contains(err.Error(), `requires "amqp", which is not a provision`) {
|
||||
t.Fatalf("a module requiring amqp was not refused, or not for the reason: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// And the catalogue as checked out beside this repository names it nowhere — the three modules that
|
||||
// did are removed under design 28 task 5.4, not converted.
|
||||
func TestNoCatalogueManifestNamesAmqp(t *testing.T) {
|
||||
modules, err := filepath.Glob("../../../mesh-catalog/modules/*/module.json")
|
||||
if err != nil || len(modules) == 0 {
|
||||
t.Skip("the catalogue is not checked out beside this repository")
|
||||
}
|
||||
for _, path := range modules {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(raw), `"amqp"`) {
|
||||
t.Errorf("%s names amqp, which is not a provision (novox/hq ADR 0131)",
|
||||
filepath.Base(filepath.Dir(path)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package catalogue
|
||||
|
||||
import "testing"
|
||||
|
||||
// A claim written before the rename still holds (novox/hq ADR 0122, ADR 0156): with the store's
|
||||
// aliases loaded, the former name resolves to the seat.
|
||||
func TestTheArtifactStoresFormerNameResolvesToIt(t *testing.T) {
|
||||
was := aliases
|
||||
t.Cleanup(func() { aliases = was })
|
||||
UseAliases(map[string]string{"the-artifact-store": "mesh-artifact-store"})
|
||||
seat, known := SeatNamed("the-artifact-store")
|
||||
if !known || seat.Name != "mesh-artifact-store" || seat.Delivers != "artifact-store" {
|
||||
t.Fatalf("the former name did not resolve: %+v %v", seat, known)
|
||||
}
|
||||
if _, known := SeatNamed("mesh-artifact-store"); !known {
|
||||
t.Fatal("the seat is not in the set under its name")
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ func TestASecondArtifactStoreAnywhereIsRefusedByName(t *testing.T) {
|
||||
}
|
||||
|
||||
// A second one, on any other machine, is refused — and the refusal names the seat.
|
||||
elsewhere := World{Held: []Held{{Claim: "the-artifact-store", Scope: ScopeMesh,
|
||||
elsewhere := World{Held: []Held{{Claim: "mesh-artifact-store", Scope: ScopeMesh,
|
||||
Node: "anchor", Module: "distribution"}}}
|
||||
other := workstation()
|
||||
other.Name = "laptop"
|
||||
@@ -32,7 +32,7 @@ func TestASecondArtifactStoreAnywhereIsRefusedByName(t *testing.T) {
|
||||
t.Fatal("a second store was accepted on another machine; it would offer artifact-store a " +
|
||||
"second time and every consumer elsewhere would refuse to choose")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "the-artifact-store") || !strings.Contains(err.Error(), "one per mesh") {
|
||||
if !strings.Contains(err.Error(), "mesh-artifact-store") || !strings.Contains(err.Error(), "one per mesh") {
|
||||
t.Fatalf("refused without naming the seat: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,27 @@ func knownFor(m Manifest, needs []Needed, node string) map[string]map[string]str
|
||||
return out
|
||||
}
|
||||
|
||||
// withOwnNames adds a module's own composed names to what it may name from one binding:
|
||||
// `${bound:<provision>:name}` and `:internal-name`, and for several contributions to one requirement
|
||||
// `:name-<local>` / `:internal-name-<local>`. Set over anything the provider serves under those keys:
|
||||
// what the module is called is the mesh's statement, not the provider's.
|
||||
func withOwnNames(values map[string]string, own map[string]any) {
|
||||
for _, key := range []string{"name", "internal-name"} {
|
||||
if v, ok := own[key].(string); ok {
|
||||
values[key] = v
|
||||
}
|
||||
}
|
||||
many, _ := own["names"].(map[string]any)
|
||||
for local, raw := range many {
|
||||
names, _ := raw.(map[string]any)
|
||||
for _, key := range []string{"name", "internal-name"} {
|
||||
if v, ok := names[key].(string); ok {
|
||||
values[key+"-"+local] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// plainly renders a served value as a program would expect to read it.
|
||||
func plainly(value any) string {
|
||||
switch v := value.(type) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The mesh's bus is one per mesh, read from the catalogue beside this checkout.
|
||||
//
|
||||
// **This is step 2's claim, and it is checked here rather than in a bed** (novox/hq ADR 0116):
|
||||
// adoption puts the NATS server into the `mesh-broker` seat on a mesh that is already running,
|
||||
// and the property that matters is that a second one anywhere is refused *when it is assigned*,
|
||||
// not discovered later as two servers holding different halves of the mesh's traffic. A second
|
||||
// bus is not a degraded mesh; it is two meshes that both believe they are the one.
|
||||
func TestASecondMeshBusAnywhereIsRefusedByName(t *testing.T) {
|
||||
nats := catalogueManifest(t, "nats")
|
||||
|
||||
if _, err := Resolve(shelf(nats), []string{"nats"}, workstation(), World{}); err != nil {
|
||||
t.Fatalf("the bus alone does not resolve: %v", err)
|
||||
}
|
||||
|
||||
elsewhere := World{Held: []Held{{Claim: "mesh-broker", Scope: ScopeMesh,
|
||||
Node: "anchor", Module: "nats"}}}
|
||||
other := workstation()
|
||||
other.Name = "laptop"
|
||||
_, err := Resolve(shelf(nats), []string{"nats"}, other, elsewhere)
|
||||
if err == nil {
|
||||
t.Fatal("a second bus was accepted on another machine")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "mesh-broker") || !strings.Contains(err.Error(), "one per mesh") {
|
||||
t.Fatalf("refused without naming the seat: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The seat is the server's role, not the product's name (novox/hq ADR 0079). A different
|
||||
// implementation of the bus claims the same seat, and the mesh refuses it for the same reason —
|
||||
// which is the property that lets the bus be replaced at all.
|
||||
func TestTheSeatRefusesADifferentBusToo(t *testing.T) {
|
||||
nats := catalogueManifest(t, "nats")
|
||||
held := World{Held: []Held{{Claim: "mesh-broker", Scope: ScopeMesh,
|
||||
Node: "anchor", Module: "some-other-broker"}}}
|
||||
other := workstation()
|
||||
other.Name = "laptop"
|
||||
if _, err := Resolve(shelf(nats), []string{"nats"}, other, held); err == nil {
|
||||
t.Fatal("the seat admitted a second holder because the module's name differed")
|
||||
}
|
||||
}
|
||||
|
||||
// The old broker is gone from the catalogue (novox/hq ADR 0131, design 28 task 5.4), so it is no
|
||||
// longer a fixture here. That two eligible holders stand beside each other with one on record is
|
||||
// pinned in holdings_test.go against manifests this package owns.
|
||||
|
||||
// **A seat and the interface it delivers are different names, and renaming one must not rename
|
||||
// the other** (novox/hq ADR 0118). This nearly went wrong: the seats were renamed to the `mesh-*`
|
||||
// prefix, and a blanket search-and-replace also renamed `npm-package-registry` and `git` where
|
||||
// they are *provisions* — which a consumer requires and a provider offers. The tests failed with
|
||||
// "the package registry is served on <nil>", which does not say "you renamed an interface".
|
||||
func TestRenamingASeatDidNotRenameTheInterfaceItDelivers(t *testing.T) {
|
||||
for _, pair := range []struct{ seat, delivers string }{
|
||||
{"git", "git"},
|
||||
{"npm-package-registry", "npm-package-registry"},
|
||||
{"mesh-artifact-store", "artifact-store"},
|
||||
{"mesh-store", "postgres-database"},
|
||||
{"mesh-broker", "mesh-bus"},
|
||||
} {
|
||||
s, known := SeatNamed(pair.seat)
|
||||
if !known {
|
||||
t.Fatalf("%q is not a seat", pair.seat)
|
||||
}
|
||||
if s.Delivers != pair.delivers {
|
||||
t.Errorf("the %s seat delivers %q, expected %q — renaming the seat moved the "+
|
||||
"interface with it, and every consumer requiring it would stop resolving",
|
||||
pair.seat, s.Delivers, pair.delivers)
|
||||
}
|
||||
// **Three of these deliberately share a name with what they deliver**, and that is not an
|
||||
// incomplete rename. Renaming a seat that delivers a provision cascades to every consumer
|
||||
// requiring it, with a mesh-wide window where a holder stops resolving mid-flight — so the
|
||||
// trunk deferred exactly those three (novox/hq ADR 0121) while renaming the node-scoped ones.
|
||||
// What this test is for is the other direction: that renaming a seat never moves the
|
||||
// interface, which once produced "the package registry is served on <nil>".
|
||||
}
|
||||
}
|
||||
|
||||
// A manifest written against an old seat name is told what it became rather than refused as
|
||||
// unknown. **That map is the controller's store now, not this package** (novox/hq ADR 0122): a
|
||||
// rename is a row, so the courtesy survives a rename nobody recompiled for. Checked where the
|
||||
// table is read, not here, where there is no longer a hardcoded list to check against.
|
||||
+123
-1
@@ -94,12 +94,43 @@ func (m Manifest) Resolve(built []Built) (Manifest, error) {
|
||||
m.Module, r["id"], named)
|
||||
case ArtifactImage, ArtifactUpstream:
|
||||
filled["image"] = artifact.Reference
|
||||
// An image is not unpacked anywhere, so it has no directory to be named for its
|
||||
// version and `${version}` has nothing to mean. Refused rather than left as literal
|
||||
// text in a path, which is how it would reach a machine and be created as a directory
|
||||
// called `${version}`.
|
||||
for key, value := range filled {
|
||||
if text, isText := value.(string); isText && strings.Contains(text, versionRef) {
|
||||
return Manifest{}, fmt.Errorf(
|
||||
"%s: %v says %s in %q, and %q is an image — an image is not unpacked, so "+
|
||||
"it has no versioned place. %s is for an archive or a bundle",
|
||||
m.Module, r["id"], versionRef, key, named, versionRef)
|
||||
}
|
||||
}
|
||||
case ArtifactArchive, ArtifactBundle:
|
||||
// The same on the wire: both are bytes fetched by digest and unpacked. They differ in
|
||||
// how they were made — one packed as it stood, the other compiled first — and a
|
||||
// machine has no reason to care which.
|
||||
filled["source"] = artifact.Reference
|
||||
filled["digest"] = artifact.Digest
|
||||
// **And `${version}`, so a resource can name a place that is this build's alone**
|
||||
// (novox/hq ADR 0141, 04-ISSUES/142). A component is unpacked into a directory named
|
||||
// for its version so it can read its own version from its path — and until this,
|
||||
// nothing could compose that path: an archive named a fixed one in the manifest and
|
||||
// nothing interpolated the build into it, so nothing could ask for
|
||||
// `…/versions/<version>/` and every machine took a hand-placed fallback.
|
||||
//
|
||||
// The version is the artifact's own digest, short. Not the commit: two builds of one
|
||||
// commit are meant to be the same bytes (the toolchains are `-trimpath` for this), and
|
||||
// a content-addressed version means an unchanged build resolves to the path it already
|
||||
// had — so re-composing a declaration moves nothing, where a commit would move the
|
||||
// path of an identical binary and recreate everything that reads it.
|
||||
for key, value := range filled {
|
||||
text, isText := value.(string)
|
||||
if !isText || !strings.Contains(text, versionRef) {
|
||||
continue
|
||||
}
|
||||
filled[key] = strings.ReplaceAll(text, versionRef, versionOf(artifact.Digest))
|
||||
}
|
||||
default:
|
||||
return Manifest{}, fmt.Errorf("%s: %q is a %q, and an artifact is %q, %q, %q or %q",
|
||||
m.Module, named, artifact.Kind, ArtifactImage, ArtifactArchive, ArtifactUpstream,
|
||||
@@ -142,7 +173,14 @@ func (b *Build) problems(module string) []string {
|
||||
// is which compiler — because the mesh chooses that, and cannot choose for a module that
|
||||
// has not said.
|
||||
if a.Kind == ArtifactBundle || a.Kind == ArtifactPackage {
|
||||
if a.From != "" {
|
||||
// **Except for a language that compiles to a binary, where it names which one**
|
||||
// (novox/hq 04-ISSUES/142). A bundle in an interpreted language is the module's own
|
||||
// directory compiled whole, and naming a source would be describing its own build. A
|
||||
// repository written in a compiled language holds several commands — the host and its
|
||||
// bootstrap live in one, and the mesh needs the host — and "the module's own directory"
|
||||
// is then not a package at all. So the compiled case may say which package, and says
|
||||
// the module root by saying nothing.
|
||||
if a.From != "" && !compilesToABinary(a.Language) {
|
||||
problems = append(problems, fmt.Sprintf(
|
||||
"%s: %q is a bundle and names what it is built from (%q). A bundle is built "+
|
||||
"from the module's own directory; what it says is the language",
|
||||
@@ -153,6 +191,26 @@ func (b *Build) problems(module string) []string {
|
||||
"%s: %q is a bundle and says no language, so nothing can choose a compiler "+
|
||||
"for it", module, a.Name))
|
||||
}
|
||||
// **A system, for a language that compiles to a binary** (novox/hq ADR 0142). A binary
|
||||
// is pinned to one operating system at link time so a host refuses to touch a machine
|
||||
// it was not built for (novox/hq ADR 0005); an artifact that says nothing would be
|
||||
// compiled for whatever the build machine happened to be, which reads as portable and
|
||||
// is not.
|
||||
if compiled := compilesToABinary(a.Language); compiled && strings.TrimSpace(a.System) == "" {
|
||||
problems = append(problems, fmt.Sprintf(
|
||||
"%s: %q is compiled to a binary and says no system, so it would be built for "+
|
||||
"whatever the build machine happens to be. Declare one artifact per "+
|
||||
"system: %s", module, a.Name, spokenSystems()))
|
||||
} else if !compiled && strings.TrimSpace(a.System) != "" {
|
||||
problems = append(problems, fmt.Sprintf(
|
||||
"%s: %q names the system %q and is written in %q, which compiles to code that "+
|
||||
"runs anywhere — a system that decides nothing reads as though it did",
|
||||
module, a.Name, a.System, a.Language))
|
||||
} else if compiled && !knownSystem(a.System) {
|
||||
problems = append(problems, fmt.Sprintf(
|
||||
"%s: %q is built for %q, and a system is %s",
|
||||
module, a.Name, a.System, spokenSystems()))
|
||||
}
|
||||
} else {
|
||||
if a.From == "" {
|
||||
problems = append(problems, fmt.Sprintf(
|
||||
@@ -193,3 +251,67 @@ func oneOrOther(n int) string {
|
||||
}
|
||||
return "them"
|
||||
}
|
||||
|
||||
// Systems the mesh builds binaries for, which is the set a host may be pinned to (novox/hq ADR 0005).
|
||||
//
|
||||
// **A closed list, and the host's own, not the compiler's.** These are not the values a Go toolchain
|
||||
// would call an operating system — the difference between two of them is a C library, not a kernel.
|
||||
// They are what a machine reports itself to be and what a host is linked to refuse, so the list that
|
||||
// matters is the one the host understands.
|
||||
var systems = []string{"alpine", "android", "arch"}
|
||||
|
||||
// knownSystem is whether the mesh builds for it.
|
||||
func knownSystem(system string) bool {
|
||||
want := strings.ToLower(strings.TrimSpace(system))
|
||||
for _, s := range systems {
|
||||
if s == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// spokenSystems is the list as a refusal says it, so a reader is one edit from right.
|
||||
func spokenSystems() string {
|
||||
return strings.Join(systems, ", ")
|
||||
}
|
||||
|
||||
// compilesToABinary is whether this language's bundle is a binary for one operating system rather
|
||||
// than code that runs wherever its interpreter does.
|
||||
//
|
||||
// **Asked of the language, not of the artifact.** A module says what it is written in; what that
|
||||
// implies is the mesh's to know, exactly as the compiler is (novox/hq ADR 0142). Asking the artifact
|
||||
// would let two artifacts in one language disagree about whether they are portable.
|
||||
func compilesToABinary(language string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(language)) {
|
||||
case "go":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// versionRef is how a resource names the version of the artifact it uses: ${version}.
|
||||
//
|
||||
// No artifact name in it, because the resource already says which artifact it is for — a second
|
||||
// name would be a second thing to keep in step with the first.
|
||||
const versionRef = "${version}"
|
||||
|
||||
// versionOf is an artifact's version as a path names it: its digest, short.
|
||||
//
|
||||
// **Content-addressed on purpose.** The alternative is the commit a build came from, and two builds
|
||||
// of one commit are meant to produce the same bytes — every toolchain here is `-trimpath` for that
|
||||
// reason. A commit-named path would move for an identical binary, and everything reading that path
|
||||
// would be recreated for a change that is not one. A digest-named path moves exactly when the bytes
|
||||
// do.
|
||||
//
|
||||
// Twelve hex characters: enough that two of this mesh's builds will not collide, short enough to
|
||||
// read in a path and in a journal line. The `sha256:` prefix goes, because a directory name carrying
|
||||
// a colon is a directory name people quote wrong.
|
||||
func versionOf(digest string) string {
|
||||
hex := strings.TrimPrefix(strings.TrimSpace(digest), "sha256:")
|
||||
if len(hex) > 12 {
|
||||
return hex[:12]
|
||||
}
|
||||
return hex
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// bundleFor is a manifest whose one artifact is a bundle in the given language and system.
|
||||
func bundleFor(language, system string) Manifest {
|
||||
return Manifest{Module: "a-component", Build: &Build{Artifacts: []Artifact{
|
||||
{Name: "binary", Kind: ArtifactBundle, Language: language, System: system},
|
||||
}}}
|
||||
}
|
||||
|
||||
func problemsOf(t *testing.T, m Manifest) string {
|
||||
t.Helper()
|
||||
return strings.Join(m.Build.problems(m.Module), "\n")
|
||||
}
|
||||
|
||||
// **A language that compiles to a binary must say which system.**
|
||||
//
|
||||
// A binary is pinned to one operating system at link time, so a host refuses to touch a machine it
|
||||
// was not built for. An artifact that says nothing would be compiled for whatever the build machine
|
||||
// happened to be — which reads as portable and is not, and is the fault this check exists for.
|
||||
func TestABinaryMustSayWhichSystemItIsFor(t *testing.T) {
|
||||
got := problemsOf(t, bundleFor("go", ""))
|
||||
if !strings.Contains(got, "says no system") {
|
||||
t.Fatalf("a compiled bundle with no system was accepted:\n%s", got)
|
||||
}
|
||||
// And the refusal names what it could have said, so a reader is one edit from right.
|
||||
for _, system := range []string{"alpine", "android", "arch"} {
|
||||
if !strings.Contains(got, system) {
|
||||
t.Fatalf("the refusal does not name %q as a choice:\n%s", system, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestABinaryThatNamesASystemIsAccepted(t *testing.T) {
|
||||
if got := problemsOf(t, bundleFor("go", "arch")); got != "" {
|
||||
t.Fatalf("a compiled bundle naming a system was refused:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A system the mesh does not build for is refused where it is written. These are the host's own
|
||||
// names, not a compiler's: the difference between two of them is a C library rather than a kernel,
|
||||
// so a value that looks like an operating system to a toolchain is still wrong here.
|
||||
func TestASystemTheMeshDoesNotBuildForIsRefused(t *testing.T) {
|
||||
for _, wrong := range []string{"linux", "debian", "darwin"} {
|
||||
got := problemsOf(t, bundleFor("go", wrong))
|
||||
if !strings.Contains(got, "and a system is") {
|
||||
t.Fatalf("%q was accepted as a system:\n%s", wrong, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// **And a language that runs anywhere must not name one.** A system that decides nothing reads as
|
||||
// though it did, which is the same fault as a restriction that restricts nothing (novox/hq ADR 0045).
|
||||
func TestAPortableBundleMayNotNameASystem(t *testing.T) {
|
||||
got := problemsOf(t, bundleFor("typescript", "arch"))
|
||||
if !strings.Contains(got, "runs anywhere") {
|
||||
t.Fatalf("a portable bundle was allowed to name a system:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPortableBundleNamingNoSystemIsAccepted(t *testing.T) {
|
||||
if got := problemsOf(t, bundleFor("typescript", "")); got != "" {
|
||||
t.Fatalf("an ordinary bundle was refused:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// One component, one artifact per system: the shape the mesh's own binaries are declared in, and the
|
||||
// reason the target is the artifact's rather than the recipe's.
|
||||
func TestOneArtifactPerSystemIsAccepted(t *testing.T) {
|
||||
m := Manifest{Module: "the-host", Build: &Build{Artifacts: []Artifact{
|
||||
{Name: "arch", Kind: ArtifactBundle, Language: "go", System: "arch"},
|
||||
{Name: "alpine", Kind: ArtifactBundle, Language: "go", System: "alpine"},
|
||||
{Name: "android", Kind: ArtifactBundle, Language: "go", System: "android"},
|
||||
}}}
|
||||
if got := problemsOf(t, m); got != "" {
|
||||
t.Fatalf("one artifact per system was refused:\n%s", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestEveryCatalogueManifestParses runs the real catalogue through the real gate.
|
||||
//
|
||||
// Not a fixture: the point is whether the manifests as written are accepted by the control plane that
|
||||
// will read them, and a copy of one manifest proves nothing about the other seventy-one.
|
||||
func TestEveryCatalogueManifestParses(t *testing.T) {
|
||||
root := os.Getenv("MESH_CATALOGUE")
|
||||
if root == "" {
|
||||
t.Skip("set MESH_CATALOGUE to a catalogue checkout to run this")
|
||||
}
|
||||
found, err := filepath.Glob(filepath.Join(root, "modules", "*", "module.json"))
|
||||
if err != nil || len(found) == 0 {
|
||||
t.Fatalf("no manifests under %s: %v", root, err)
|
||||
}
|
||||
named, routed := 0, 0
|
||||
for _, p := range found {
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", p, err)
|
||||
}
|
||||
m, err := ParseManifest(raw)
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", filepath.Base(filepath.Dir(p)), err)
|
||||
continue
|
||||
}
|
||||
for _, l := range m.Listens {
|
||||
if l.Name != "" {
|
||||
named++
|
||||
}
|
||||
}
|
||||
for port := range RoutedPorts(m) {
|
||||
_ = port
|
||||
routed++
|
||||
}
|
||||
}
|
||||
t.Logf("%d manifests, %d named endpoints, %d routed endpoints resolved", len(found), named, routed)
|
||||
if named == 0 {
|
||||
t.Fatal("no endpoint in the catalogue is named, so this proved nothing")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoCatalogueManifestNamesAnInstallation is ADR 0112's check, run over the real catalogue: no
|
||||
// definition names a domain or a public address the mesh acts on, and every value that must for now
|
||||
// carries its reason (novox/hq ADR 0155, issue 134). The list it prints is the one that shrinks.
|
||||
func TestNoCatalogueManifestNamesAnInstallation(t *testing.T) {
|
||||
root := os.Getenv("MESH_CATALOGUE")
|
||||
if root == "" {
|
||||
t.Skip("set MESH_CATALOGUE to a catalogue checkout to run this")
|
||||
}
|
||||
found, err := filepath.Glob(filepath.Join(root, "modules", "*", "module.json"))
|
||||
if err != nil || len(found) == 0 {
|
||||
t.Fatalf("no manifests under %s: %v", root, err)
|
||||
}
|
||||
var named []string
|
||||
for _, p := range found {
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", p, err)
|
||||
}
|
||||
m, err := ParseManifest(raw)
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", p, err)
|
||||
continue
|
||||
}
|
||||
named = append(named, InstallationProblems(m)...)
|
||||
}
|
||||
if len(named) > 0 {
|
||||
t.Fatalf("%d value(s) name an installation:\n %s", len(named), strings.Join(named, "\n "))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// **A machine trusts the mesh's authority because a module put its root there** (novox/hq ADR
|
||||
// 0147, issue 129). The module carries a shell script and a unit, and both are worthless unless
|
||||
// the mesh fills in where the authority is — which is the one thing about it the manifest cannot
|
||||
// state, because the authority's address is a fact about the mesh and not about the module.
|
||||
//
|
||||
// So what is checked here is the rendering, not the parsing: the script the machine will run
|
||||
// names the authority it was bound to, and the unit runs that script both ways. The verification
|
||||
// itself — a plain client trusting an internal name on a machine holding this, and failing on one
|
||||
// that does not — is the lab's, and cannot be had here.
|
||||
func TestCaTrustRendersTheAuthorityItWasBoundTo(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../../mesh-catalog/modules/ca-trust/module.json")
|
||||
if err != nil {
|
||||
t.Skipf("the catalogue is not beside this checkout: %v", err)
|
||||
}
|
||||
m, err := ParseManifest(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("the trust module does not parse:\n%v", err)
|
||||
}
|
||||
|
||||
r := Resolution{
|
||||
Node: "workstation",
|
||||
Modules: []Manifest{m},
|
||||
Needs: []Needed{{
|
||||
Name: "internal-acme-ca", From: "anchor", At: "anchor.internal", For: "ca-trust",
|
||||
Serves: map[string]any{
|
||||
"port": float64(9000), "path": "/acme/acme/directory", "roots": "/roots.pem",
|
||||
},
|
||||
}},
|
||||
}
|
||||
out, err := r.Declaration(Rendering{})
|
||||
if err != nil {
|
||||
t.Fatalf("the trust module could not be composed for a machine: %v", err)
|
||||
}
|
||||
|
||||
script := fileNamed(out, "ca-trust.anchor")
|
||||
if script == nil {
|
||||
t.Fatalf("nothing writes the script the unit runs: %v", out)
|
||||
}
|
||||
body, _ := script["content"].(string)
|
||||
if !strings.Contains(body, "https://anchor.internal:9000/roots.pem") {
|
||||
t.Errorf("the script does not fetch from the authority it was bound to:\n%s", body)
|
||||
}
|
||||
if script["mode"] != "0755" {
|
||||
t.Errorf("the script is written %v, which systemd cannot execute", script["mode"])
|
||||
}
|
||||
|
||||
unit := fileNamed(out, "ca-trust.unit")
|
||||
if unit == nil {
|
||||
t.Fatalf("no unit: %v", out)
|
||||
}
|
||||
text, _ := unit["content"].(string)
|
||||
// Both halves. A unit that only installs the anchor leaves a machine trusting an authority
|
||||
// nobody assigned it to any more, which is the half issue 129 asked for by name.
|
||||
for _, want := range []string{
|
||||
"ExecStart=" + script["path"].(string) + " install",
|
||||
"ExecStop=" + script["path"].(string) + " remove",
|
||||
"RemainAfterExit=yes",
|
||||
} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Errorf("the unit does not say %q:\n%s", want, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,10 +97,43 @@ type Rendering struct {
|
||||
// compose it a second time.
|
||||
Suffix string
|
||||
|
||||
// BusUsers is the mesh's composed user list, for the module holding `mesh-broker`. Empty on
|
||||
// every other node, and on this one until the controller has composed it.
|
||||
//
|
||||
// **Only the users, never the server's own settings**: those are the module's, in its image and
|
||||
// its mounts (Manifest.BusUsers).
|
||||
BusUsers string
|
||||
// BusMembership is this machine's membership for the bus the mesh is moving to, sealed to it
|
||||
// (design 28, task 5.2). Empty for a machine not being moved. Written as a file the host reads
|
||||
// after the declaration has applied, so the bus it names is standing before the machine leaves
|
||||
// the one it is on.
|
||||
BusMembership string
|
||||
|
||||
// MeshRange is the private network's CIDR (the range node addresses are allocated from), for a
|
||||
// module that must name the whole mesh rather than one machine — an intrusion filter that must
|
||||
// never ban a tunnel peer, say. A per-mesh value the module cannot know, so it is carried here
|
||||
// and offered as ${machine:mesh-range}, the same way one machine's address is.
|
||||
MeshRange string
|
||||
|
||||
// Accounts is each machine's operator account, by the same internal name Names uses (novox/hq
|
||||
// to-be 29). What an ssh Host block's `User` line is composed from; empty for a machine no
|
||||
// operator account is known on.
|
||||
Accounts map[string]string
|
||||
|
||||
// Kept is every operator-sealed secret in the mesh, for a module that `keeps` them. Nil when
|
||||
// nothing on this node keeps them, or the mesh has no operator key.
|
||||
Kept *KeptExport
|
||||
|
||||
// OutwardLinks is the links this machine reported as facing outside it, which the filter is
|
||||
// written around (novox/hq ADR 0140). Empty means the machine has not said, and the mesh
|
||||
// composes no filter for it rather than writing a rule around a link with no name.
|
||||
OutwardLinks []string
|
||||
|
||||
// TunnelInterface is the interface the mesh's private network runs on, named here rather than
|
||||
// imported because the overlay package rests on this one. Traffic arriving on it is the mesh's,
|
||||
// not this machine's own guest, so the filter admits it only by a rule.
|
||||
TunnelInterface string
|
||||
|
||||
// Foundation is the ports the mesh itself needs reachable on every machine, which no module
|
||||
// declares because the foundation is not a module (novox/hq 04-ISSUES/051 and 052). The broker
|
||||
// is the one that matters: a machine dials it to enrol, and a firewall derived only from
|
||||
@@ -220,9 +253,23 @@ func (r Resolution) Compose(with Rendering) (Composed, error) {
|
||||
if err != nil {
|
||||
return Composed{}, err
|
||||
}
|
||||
if with.BusMembership != "" {
|
||||
// The machine's own, not any module's: how it reaches the mesh from now on. Sealed like a
|
||||
// secret and placed where the host looks for exactly this (design 28, task 5.2).
|
||||
resources = append(resources, map[string]any{
|
||||
"id": BusMembershipID(), "type": "file", "path": BusMembershipPath,
|
||||
"sealed": with.BusMembership, "mode": "0600",
|
||||
})
|
||||
}
|
||||
return Composed{Resources: resources, Owner: owner}, nil
|
||||
}
|
||||
|
||||
// BusMembershipID names the resource carrying a machine's membership for the new bus, and
|
||||
// BusMembershipPath is where the host reads it — the same constant on both sides.
|
||||
func BusMembershipID() string { return "bus-membership" }
|
||||
|
||||
const BusMembershipPath = "/var/lib/mesh/membership-next.json"
|
||||
|
||||
func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[string]any, error) {
|
||||
// Every manifest is placed first (novox/hq ADR 0112): the maps naming where its bindings,
|
||||
// credentials and contributions land are resolved against this node's directories, so every
|
||||
@@ -308,7 +355,21 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filtering := AsNftables(rules, with.Mesh, r.PublicDomain != "", with.Foundation)
|
||||
// **A machine that has not said which links face outside is sent no filter** (novox/hq ADR
|
||||
// 0140). The whole chain is written around those links: with none, the rule that lets this
|
||||
// machine's own guests keep working would name an empty set, which nftables refuses, and a rule
|
||||
// set that does not load is a machine filtering nothing while its unit reports success. Refused
|
||||
// here, where a person reads it, rather than on the machine — and the machine keeps the filter
|
||||
// it already has.
|
||||
if filters := r.filtersHere(); filters != "" && len(with.OutwardLinks) == 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"%s cannot be sent a filter: it has not reported which of its links face outside, and "+
|
||||
"every rule in the chain is written around them. It reports that on each apply; "+
|
||||
"`node show %s` says whether it has. Until then %s is not sent, and the machine "+
|
||||
"keeps the filter it has", r.Node, r.Node, filters)
|
||||
}
|
||||
filtering := AsNftables(rules, with.Mesh, r.PublicDomain != "", with.Foundation,
|
||||
with.OutwardLinks, with.TunnelInterface)
|
||||
|
||||
var out []map[string]any
|
||||
for _, m := range r.Modules {
|
||||
@@ -339,6 +400,12 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
"content": filtering, "mode": "0600",
|
||||
})
|
||||
}
|
||||
// The node's fail2ban jails, composed from every module it runs (novox/hq to-be 31), written
|
||||
// where the intrusion-prevention holder owns them. Like the rule set above: gathered from all
|
||||
// modules, written by the one that holds the role.
|
||||
if j := m.Jailing; j != nil {
|
||||
first = append(first, jailsInto(r.Modules, j)...)
|
||||
}
|
||||
if c := m.Certificate; c != nil {
|
||||
if with.Certificate == "" {
|
||||
// Asked for and not issued. Refused rather than skipped: a module that serves TLS
|
||||
@@ -359,6 +426,35 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
})
|
||||
}
|
||||
}
|
||||
if m.BusUsers != "" {
|
||||
// **The claim authorises it, not the field.** This file holds every user's password
|
||||
// hash, so a module that could ask for it could read every credential on the bus.
|
||||
// Checked from this manifest alone, which is the cheapest check there is: whether some
|
||||
// other module also claims the seat is resolution's business elsewhere, and one holder
|
||||
// mesh-wide is already guaranteed.
|
||||
if !m.ClaimsSeat("mesh-broker") {
|
||||
return nil, fmt.Errorf(
|
||||
"%s asks for the mesh's user list and does not claim mesh-broker. That file "+
|
||||
"holds every user's password hash, so the seat is what authorises it",
|
||||
m.Module)
|
||||
}
|
||||
if with.BusUsers == "" {
|
||||
// Asked for and not composed. Refused rather than skipped, for the reason a
|
||||
// certificate is: a bus with no user list refuses every connection in the mesh, and
|
||||
// an empty file would look like a configuration problem on the machine.
|
||||
return nil, fmt.Errorf(
|
||||
"%s holds mesh-broker and the mesh composed no user list, so the bus would "+
|
||||
"refuse every connection", m.Module)
|
||||
}
|
||||
first = append(first, map[string]any{
|
||||
"id": BusUsersID(), "type": "file", "path": m.BusUsers,
|
||||
"content": with.BusUsers,
|
||||
// Readable by the server and nothing else. Hashes rather than passwords, so this is
|
||||
// not a set of working credentials — but a list of every user in the mesh is worth
|
||||
// keeping to the one process that needs it.
|
||||
"mode": "0600",
|
||||
})
|
||||
}
|
||||
for _, name := range sortedKeys(m.OwnSecrets) {
|
||||
sealed := with.Needed[m.Module][name]
|
||||
if sealed == "" {
|
||||
@@ -478,7 +574,11 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
}
|
||||
found = here
|
||||
}
|
||||
file, err := boundFile(*found, m.Binds[to], ConsumerIdentity(r.Node, IdentitySource(m.Slug, m.Module)))
|
||||
own, err := r.ownNames(m, to, with.Settings[m.Module])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := boundFile(*found, m.Binds[to], ConsumerIdentity(r.Node, IdentitySource(m.Slug, m.Module)), own)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -522,17 +622,15 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
// merging earlier would throw away the files it still needs.
|
||||
resources = append(append([]map[string]any{}, first...), resources...)
|
||||
|
||||
// Every container is given the mesh's names. Not a choice a module makes: a module that
|
||||
// listed them would go stale the day a machine joins, and one that did not would be a
|
||||
// module whose containers cannot reach anything by name.
|
||||
//
|
||||
// A container that was given names of its own keeps them and gets the mesh's beside them:
|
||||
// the mesh does not know what else a workload needs to reach, and taking something away
|
||||
// to add something is not what "also" means.
|
||||
if len(with.Names) > 0 {
|
||||
resources = withMeshNames(resources, with.Names)
|
||||
}
|
||||
|
||||
// No container is given the mesh's names (novox/hq ADR 0148). It used to be: every
|
||||
// container got the whole roster as `--add-host` entries at creation, and a name that
|
||||
// moved afterwards was wrong inside it for as long as it ran (issues 109, 135) — and once
|
||||
// the roster was made part of a container's identity so that could be caught, one name
|
||||
// moving anywhere replaced every container in the mesh (issue 151). A container resolves a
|
||||
// mesh name through its machine's resolver at the moment it asks, which the runtime is
|
||||
// told once per machine, as a file, by the resolver's own module. The names a module
|
||||
// declares for itself are its own and stay exactly as written: they are part of what the
|
||||
// module is, and the mesh does not know what they mean.
|
||||
// What this module may name from inside one of its own files. Gathered once per module
|
||||
// rather than per file, because it is a fact about the module.
|
||||
sealed, err := sealedFor(m, r.Needs, with)
|
||||
@@ -541,16 +639,48 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
}
|
||||
// And what its bindings say, for the half of a connection that is not secret.
|
||||
known := knownFor(m, r.Needs, r.Node)
|
||||
// A requirement answered on this same machine is not in r.Needs — its binding file is
|
||||
// written from `here` (above) — and so `${bound:…}` could not name it, though the file
|
||||
// beside it said the same facts. Filled from the same answer, so the two cannot disagree.
|
||||
for _, want := range m.Wants() {
|
||||
if _, has := known[want]; has {
|
||||
continue
|
||||
}
|
||||
answered, err := here(r, want, with)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if answered == nil {
|
||||
continue
|
||||
}
|
||||
local := *answered
|
||||
local.For = m.Module
|
||||
for provision, values := range knownFor(m, []Needed{local}, r.Node) {
|
||||
known[provision] = values
|
||||
}
|
||||
}
|
||||
// And what the module is called through each requirement it contributes to (novox/hq
|
||||
// 04-ISSUES/122) — the same composition its binding file carries.
|
||||
for provision, values := range known {
|
||||
own, err := r.ownNames(m, provision, with.Settings[m.Module])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
withOwnNames(values, own)
|
||||
}
|
||||
// And where this node places the directories the module declared without a path
|
||||
// (novox/hq ADR 0112) — resolved once per module, named by ${dir:…} from any resource.
|
||||
dirs := dirsFor(m, with)
|
||||
// And the machine underneath, which no binding of its own can tell it.
|
||||
thisMachine := machineFacts(r, with.Names)
|
||||
thisMachine := machineFacts(r, with.Names, with.MeshRange)
|
||||
|
||||
// Which of this module's files carry a secret, for the rule that a container may not read
|
||||
// one of them as its environment without saying so (ADR 0086, issue 041).
|
||||
secretFiles := secretFilesOf(resources)
|
||||
|
||||
// Which of this module's resources its preparation runs before, if it prepares anything.
|
||||
prepareBefore := preparationTarget(m)
|
||||
|
||||
for _, unsettled := range resources {
|
||||
resource, err := ApplySettings(unsettled, with.Settings[m.Module])
|
||||
if err != nil {
|
||||
@@ -566,6 +696,13 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
// Said in the catalogue, not on the machine: the host parses strictly and knows no
|
||||
// such field, and the reason is for a reader of the manifest.
|
||||
delete(copied, SecretsInEnvironment)
|
||||
delete(copied, NamesOnPurpose)
|
||||
// **An operator's value, from the assignment** (novox/hq ADR 0112, ADR 0155): what a
|
||||
// definition may not carry because it is true of one installation only. Filled from
|
||||
// the same layers a mergeable file takes, and refused when no layer set it.
|
||||
if err := settingInto(copied, with.Settings[m.Module], m.Module); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// **Placed before anything reads a path.** A pathless directory receives the path
|
||||
// this node resolves for it, and every ${dir:…} — in paths, mounts, content and
|
||||
// environment — becomes that path, so what follows sees only concrete places
|
||||
@@ -636,6 +773,18 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
if renamed := reflectsRenamed(m.Module, resource["reload-on"]); renamed != nil {
|
||||
copied["reload-on"] = renamed
|
||||
}
|
||||
// **A version prepares its state before it runs** (novox/hq ADR 0135). Derived from the
|
||||
// module's own resource rather than declared beside it: what prepares the state is the
|
||||
// module's own code, so what it is given has to be what that code is given — and a
|
||||
// second resource written by hand is a second copy to drift from the first. Placed
|
||||
// immediately before it, because a run-once step stops everything the declaration
|
||||
// places after it (ADR 0052), which is how a version whose preparation failed does not
|
||||
// serve.
|
||||
if prepareBefore != "" && fmt.Sprint(resource["id"]) == prepareBefore {
|
||||
step := prepared(copied)
|
||||
owner[fmt.Sprint(step["id"])] = m.Module
|
||||
out = append(out, step)
|
||||
}
|
||||
owner[fmt.Sprint(copied["id"])] = m.Module
|
||||
out = append(out, copied)
|
||||
}
|
||||
@@ -644,7 +793,7 @@ func (r Resolution) compose(with Rendering, owner map[string]string) ([]map[stri
|
||||
// plane's; making a name resolve is the module's software. Emitted as ordinary files under
|
||||
// this module's name, so they are applied, reported and removed exactly as anything else
|
||||
// it declares.
|
||||
given, err := FactsInto(m, r, with.Names, with.Machines, with.Suffix)
|
||||
given, err := FactsInto(m, r, with.Names, with.Machines, with.Accounts, with.Suffix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -765,6 +914,17 @@ func mapping(written string) (outer, inner int, address string, ok bool) {
|
||||
return outer, inner, strings.Join(parts[:len(parts)-2], ":"), true
|
||||
}
|
||||
|
||||
// filtersHere is the module on this node that loads the machine's packet filter, or empty when none
|
||||
// does. Named rather than counted: a refusal that says which module is one step from acted on.
|
||||
func (r Resolution) filtersHere() string {
|
||||
for _, m := range r.Modules {
|
||||
if m.Filtering != nil {
|
||||
return m.Module
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Rules is the rule set this node's filter is derived from: every module's listens, what was
|
||||
// computed for this machine, and each module's per-node exposure. The same answer whether the node
|
||||
// is adopted or converged — the one loads it as a filter, the other declares it as openings.
|
||||
@@ -775,6 +935,35 @@ func (r Resolution) Rules(with Rendering) ([]Rule, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// And how far each endpoint reaches, which says the same thing to the filter and more
|
||||
// besides (novox/hq ADR 0138). Folded in here rather than beside: the filter has one
|
||||
// question — from where — and a reach answers it, so giving it two inputs would let them
|
||||
// disagree. Reaches refuses a port that both name, so this cannot silently prefer one.
|
||||
reaches, err := Reaches(m, with.Settings[m.Module])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// **Only for an endpoint the proxy does not serve.** A routed endpoint's port is how the
|
||||
// proxy reaches it and nothing else (ADR 0045), so `public` there asks for a public name and
|
||||
// says nothing about the port — opening it to the world as well would undo the arrangement
|
||||
// the proxy exists for, and would silently reopen a port an operator had narrowed.
|
||||
//
|
||||
// Found by trying to express a real module: one whose routed name must be public and whose
|
||||
// machine-side port must not be. Under one value for both, there was no way to say it.
|
||||
routed := RoutedPorts(m)
|
||||
for port, reach := range reaches {
|
||||
if routed[port] {
|
||||
continue
|
||||
}
|
||||
source, ok := FilterSource(reach)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: %q is not a reach the filter can read", m.Module, reach)
|
||||
}
|
||||
if e == nil {
|
||||
e = map[int]string{}
|
||||
}
|
||||
e[port] = source
|
||||
}
|
||||
if e != nil {
|
||||
exposure[m.Module] = e
|
||||
}
|
||||
@@ -938,12 +1127,11 @@ func (r Resolution) contributions(settings SettingsBy, grants []Grant,
|
||||
// Settings reach a contribution the same way they reach a file. A route's hostname is
|
||||
// exactly the kind of thing that differs between one mesh and the next, and a module
|
||||
// that could not have it set would have to be edited to be reused.
|
||||
values, err := settle(m.Contributes[to], settings[m.Module], nil,
|
||||
values, err := r.composed(m, to, m.Contributes[to], settings[m.Module],
|
||||
m.Module+" contributing to "+to)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s contributing to %s: %w", m.Module, to, err)
|
||||
return nil, err
|
||||
}
|
||||
composeName(values, r.PublicDomain, r.At)
|
||||
out[to] = append(out[to], Contribution{From: m.Module, Values: values})
|
||||
}
|
||||
// Several contributions to one requirement (ADR 0094's sibling for `contributes`): an
|
||||
@@ -952,12 +1140,11 @@ func (r Resolution) contributions(settings SettingsBy, grants []Grant,
|
||||
// name always reaches the provider from here.
|
||||
for _, to := range sortedKeys(m.ContributesMany) {
|
||||
for _, local := range sortedKeys(m.ContributesMany[to]) {
|
||||
values, err := settle(m.ContributesMany[to][local], settings[m.Module], nil,
|
||||
values, err := r.composed(m, to, m.ContributesMany[to][local], settings[m.Module],
|
||||
m.Module+" contributing "+local+" to "+to)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s contributing %s to %s: %w", m.Module, local, to, err)
|
||||
return nil, err
|
||||
}
|
||||
composeName(values, r.PublicDomain, r.At)
|
||||
out[to] = append(out[to], Contribution{From: m.Module, Values: values})
|
||||
}
|
||||
}
|
||||
@@ -965,6 +1152,82 @@ func (r Resolution) contributions(settings SettingsBy, grants []Grant,
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// composed is one contribution as its provider receives it: settled with this node's settings, its
|
||||
// endpoint's port filled in, and its names composed from the label.
|
||||
//
|
||||
// **One function, because two readers must agree.** The provider is told the names in its received
|
||||
// file; the contributing module is told the same names in its own binding (novox/hq 04-ISSUES/122).
|
||||
// Composing them twice, in two places, is how the proxy would come to serve one name while the
|
||||
// module wrote another into its configuration.
|
||||
func (r Resolution) composed(m Manifest, to string, raw map[string]any, layers []Layer, what string) (
|
||||
map[string]any, error) {
|
||||
values, err := settle(raw, layers, nil, what)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
reaches, err := Reaches(m, layers)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
blocks, err := Endpoints(m, layers)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
portOfEndpoint(values, endpointPorts(m))
|
||||
composeName(values, r.PublicDomain, servingAt(r, to), reaches, endpointPorts(m), blocks)
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// ownNames is what a module is known by through what it contributes to one requirement — the names
|
||||
// the mesh composed for it, and nothing else of the contribution.
|
||||
//
|
||||
// **The half a module could not learn** (novox/hq 04-ISSUES/122). A module contributes a label, the
|
||||
// mesh joins it with this node's domains, and the provider serves the result — and the module itself
|
||||
// was never told. Software that must know its own address (a login redirect, a canonical URL, an
|
||||
// issuer) had it written into the manifest as a literal, which is a domain in a definition and wrong
|
||||
// on every other machine. `${bound:<requirement>:name}` is the answer, from the same composition the
|
||||
// provider receives.
|
||||
//
|
||||
// Several contributions to one requirement are keyed by their local name under `names`.
|
||||
func (r Resolution) ownNames(m Manifest, to string, layers []Layer) (map[string]any, error) {
|
||||
pick := func(values map[string]any) map[string]any {
|
||||
names := map[string]any{}
|
||||
for _, key := range []string{"name", "internal-name"} {
|
||||
if v, ok := values[key].(string); ok && v != "" {
|
||||
names[key] = v
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
out := map[string]any{}
|
||||
if raw, ok := m.Contributes[to]; ok {
|
||||
values, err := r.composed(m, to, raw, layers, m.Module+" contributing to "+to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range pick(values) {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
if locals := m.ContributesMany[to]; len(locals) > 0 {
|
||||
many := map[string]any{}
|
||||
for _, local := range sortedKeys(locals) {
|
||||
values, err := r.composed(m, to, locals[local], layers,
|
||||
m.Module+" contributing "+local+" to "+to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if names := pick(values); len(names) > 0 {
|
||||
many[local] = names
|
||||
}
|
||||
}
|
||||
if len(many) > 0 {
|
||||
out["names"] = many
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// composeName joins a contribution's label with a node's public domain, and separately with its
|
||||
// private one, in place (novox/hq ADR 0056).
|
||||
//
|
||||
@@ -988,10 +1251,44 @@ func (r Resolution) contributions(settings SettingsBy, grants []Grant,
|
||||
// the running mesh keeps serving the full names it has. And a labelled contribution on a node with
|
||||
// no public domain composes nothing — there is nothing to join it to — which reads downstream as a
|
||||
// route that named no host, the same as it would have before this existed.
|
||||
func composeName(values map[string]any, publicDomain, internalDomain string) {
|
||||
func composeName(values map[string]any, publicDomain, internalDomain string, reaches map[int]string,
|
||||
ports map[string]int, blocks map[string]Endpoint) {
|
||||
if values == nil {
|
||||
return
|
||||
}
|
||||
// **The subdomain an assignment gave this endpoint**, before the name is joined (novox/hq ADR
|
||||
// 0138). The module contributes a label because it names its own parts; an assignment may say a
|
||||
// different one, because where a thing lives under a domain is the operator's to choose and used
|
||||
// to require editing the module to change.
|
||||
if name, ok := values[RouteEndpoint].(string); ok {
|
||||
if ep, said := blocks[strings.TrimSpace(name)]; said && ep.Label != "" {
|
||||
values["label"] = ep.Label
|
||||
}
|
||||
}
|
||||
// **How far the endpoint this route serves reaches decides which names exist** (novox/hq ADR
|
||||
// 0138). Both were composed whenever the node had both domains, so every routed module got a
|
||||
// public name and an internal one whether anybody wanted them or not — and a certificate for
|
||||
// each, because the proxy certifies the names it is given.
|
||||
//
|
||||
// Joined by the port: a route entry names the port it serves and the module declares a listen on
|
||||
// it. An entry with no port is not an endpoint's route but a rule about a name — a path-level
|
||||
// refusal shadowing another route — and it inherits whatever that route's names turned out to
|
||||
// be, which is why it is left alone here.
|
||||
//
|
||||
// Nothing said is both names, as before. That is what keeps every mesh already running identical
|
||||
// until an assignment speaks.
|
||||
wantPublic, wantInternal := true, true
|
||||
if port, ok := endpointPortOf(values, ports); ok {
|
||||
if reach, said := reaches[port]; said {
|
||||
wantPublic, wantInternal = WantsPublicName(reach), WantsInternalName(reach)
|
||||
}
|
||||
}
|
||||
if !wantPublic {
|
||||
publicDomain = ""
|
||||
}
|
||||
if !wantInternal {
|
||||
internalDomain = ""
|
||||
}
|
||||
if _, already := values["name"]; already {
|
||||
// A full name was given rather than a label. Left as-is: this is the legacy shape, and the
|
||||
// point of the label is to not have to write the full name — a contribution that wrote both
|
||||
@@ -1023,6 +1320,24 @@ func composeName(values map[string]any, publicDomain, internalDomain string) {
|
||||
}
|
||||
}
|
||||
|
||||
// servingAt is the private-network name of the node a contribution to `to` arrives at: the
|
||||
// provider's, when the provision is answered elsewhere, and this machine's own when it is answered
|
||||
// here or not yet settled.
|
||||
//
|
||||
// A route's internal name is composed under it (novox/hq ADR 0151, issue 139). `<label>.<node>.internal`
|
||||
// is answered by every machine's resolver as *anything under that node's name goes to that node* —
|
||||
// so the node in the name has to be the one whose proxy answers, or the name sends a client to a
|
||||
// machine with nothing listening while the public name, published at the serving node's address,
|
||||
// works. Where the proxy runs beside the module the two are the same machine and nothing changes.
|
||||
func servingAt(r Resolution, to string) string {
|
||||
for _, n := range r.Needs {
|
||||
if n.Name == to && n.At != "" {
|
||||
return n.At
|
||||
}
|
||||
}
|
||||
return r.At
|
||||
}
|
||||
|
||||
// receivedFile is the file a provider is given its consumers' contributions in.
|
||||
func receivedFile(requirement, path string, given []Contribution) (map[string]any, error) {
|
||||
if given == nil {
|
||||
@@ -1127,14 +1442,14 @@ func sortedKeys[V any](m map[string]V) []string {
|
||||
// Where it is and what the providing module said about using it. **No credential**, and the file
|
||||
// says so rather than leaving a reader to wonder whether one was meant to be there — a missing
|
||||
// field looks like a bug, and a stated absence looks like a boundary.
|
||||
func boundFile(n Needed, path, as string) (map[string]any, error) {
|
||||
func boundFile(n Needed, path, as string, own map[string]any) (map[string]any, error) {
|
||||
// A record has no machine and no address. Saying so is the difference between a reader
|
||||
// concluding "somewhere with no address" and concluding the mesh failed to fill something in.
|
||||
where := any(n.At)
|
||||
if n.ByRecord {
|
||||
where = "a record in this mesh, not a machine"
|
||||
}
|
||||
body, err := json.MarshalIndent(map[string]any{
|
||||
doc := map[string]any{
|
||||
"binding": 1,
|
||||
"provision": n.Name,
|
||||
"from": n.From,
|
||||
@@ -1150,7 +1465,14 @@ func boundFile(n Needed, path, as string) (map[string]any, error) {
|
||||
"generated": "by the mesh — do not edit; replaced whenever this changes. " +
|
||||
"The credential is not here: it is sealed, in the file this module's manifest " +
|
||||
"names under `secrets`",
|
||||
}, "", " ")
|
||||
}
|
||||
// **What this module is called through what it contributes here** (novox/hq 04-ISSUES/122):
|
||||
// `name`, `internal-name`, or `names` by local name — composed exactly as the provider receives
|
||||
// them. Absent when the module contributes nothing named, rather than written empty.
|
||||
for key, value := range own {
|
||||
doc[key] = value
|
||||
}
|
||||
body, err := json.MarshalIndent(doc, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1279,43 +1601,6 @@ func (r Resolution) servedOnThisMachine(provision string, with Rendering) (map[s
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
// withMeshNames gives every container in a set the mesh's names.
|
||||
//
|
||||
// Copied rather than edited in place: these maps come from a module's manifest, and mutating one
|
||||
// would change what the catalogue holds for every other machine running that module.
|
||||
//
|
||||
// A host-network container gets the names too. It was once skipped, on the belief that it "shares
|
||||
// the machine's hosts file already" — but it does not: `docker run --network host` still gives the
|
||||
// container its own /etc/hosts (localhost and its own id only), so every `<node>.internal` name the
|
||||
// mesh wrote for the machine is invisible inside it, and a client that dials one gets EAI_AGAIN. The
|
||||
// remedy is the same `--add-host` every other container gets — the runtime accepts it with
|
||||
// `--network host` (verified), and without it a host-network consumer cannot reach a provider by the
|
||||
// `.internal` address the mesh hands it as `${bound:...:at}`.
|
||||
func withMeshNames(resources []map[string]any, names map[string]string) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(resources))
|
||||
for _, r := range resources {
|
||||
if r["type"] != "container" {
|
||||
out = append(out, r)
|
||||
continue
|
||||
}
|
||||
|
||||
copied := map[string]any{}
|
||||
for k, v := range r {
|
||||
copied[k] = v
|
||||
}
|
||||
var given []any
|
||||
if already, ok := copied["hosts"].([]any); ok {
|
||||
given = append(given, already...)
|
||||
}
|
||||
for _, name := range sortedKeys(names) {
|
||||
given = append(given, name+":"+names[name])
|
||||
}
|
||||
copied["hosts"] = given
|
||||
out = append(out, copied)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// pinned refuses an image that is not really pinned, on its way to a machine.
|
||||
//
|
||||
// **Here and not at parse** (novox/hq 04-ISSUES/025). A manifest in a repository names artifacts
|
||||
@@ -1394,14 +1679,23 @@ func publishedOn(resource map[string]any, module string, with Rendering) {
|
||||
out = append(out, givenOuter(written, with.Given[module]))
|
||||
continue
|
||||
}
|
||||
wanted, err := strconv.Atoi(strings.TrimSpace(written))
|
||||
// A short form may carry the protocol — `"3478/udp"` — and the number is what the mesh
|
||||
// assigns for; the protocol rides along. Read as one token, the `/udp` made the whole
|
||||
// entry "not a port", and passing it through let the runtime publish it wherever it
|
||||
// liked: unifi's STUN and discovery landed on random machine ports while every TCP pin
|
||||
// beside them held.
|
||||
mapping, protocol := written, ""
|
||||
if cut := strings.LastIndex(written, "/"); cut >= 0 {
|
||||
mapping, protocol = written[:cut], written[cut:]
|
||||
}
|
||||
wanted, err := strconv.Atoi(strings.TrimSpace(mapping))
|
||||
if err != nil {
|
||||
// Not a port at all. Passed through, so the host refuses it with its own words rather
|
||||
// than this quietly dropping something somebody meant.
|
||||
out = append(out, written)
|
||||
continue
|
||||
}
|
||||
out = append(out, fmt.Sprintf("%d:%d", with.machinePort(module, wanted), wanted))
|
||||
out = append(out, fmt.Sprintf("%d:%d%s", with.machinePort(module, wanted), wanted, protocol))
|
||||
}
|
||||
resource["ports"] = out
|
||||
}
|
||||
@@ -1538,3 +1832,130 @@ func atMachinePort(serves map[string]any, module string, ports map[string]map[in
|
||||
func AtPublishedPort(values map[string]any, module string, published map[int]int) map[string]any {
|
||||
return atMachinePort(values, module, map[string]map[int]int{module: published})
|
||||
}
|
||||
|
||||
// PreparationArgument is how the mesh asks a module to prepare its state: one word, to the module's
|
||||
// own program, whatever that program is (novox/hq ADR 0135).
|
||||
//
|
||||
// **One word for every kind of module.** A module built as a Go binary receives it as its argument;
|
||||
// one built as a bundle receives it through the runtime, whose entry takes the same word. So the
|
||||
// mesh has one way of asking and a module has one way of answering, and neither learns the other's
|
||||
// shape.
|
||||
const PreparationArgument = "prepare"
|
||||
|
||||
// preparationTarget is the resource a module's preparation runs before: its own workload.
|
||||
//
|
||||
// The first container carrying an artifact this module built, and not itself a step — that is the
|
||||
// thing that runs the module's code, and therefore the thing whose state must be ready. Empty when
|
||||
// the module prepares nothing, or when nothing it declares could run its code.
|
||||
//
|
||||
// **A module with two own workloads gates the first of them.** Five modules in the catalogue declare
|
||||
// more than one container of their own, none of them preparing anything today. If one ever does and
|
||||
// its second workload shares the state, the gate is in front of the first — stated here because the
|
||||
// alternative is a field asking an author to restate what the mesh can see.
|
||||
func preparationTarget(m Manifest) string {
|
||||
if !m.Prepares {
|
||||
return ""
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
if fmt.Sprint(r["type"]) != "container" || !ownArtifact(r, m.Module) {
|
||||
continue
|
||||
}
|
||||
if once, _ := r["run-once"].(bool); once {
|
||||
continue
|
||||
}
|
||||
return fmt.Sprint(r["id"])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ownArtifact is whether a resource runs something this module built, in either spelling a manifest
|
||||
// may be in: naming the artifact, before a build resolved it, or carrying the reference a build
|
||||
// recorded — this mesh's own store, under this module's name.
|
||||
func ownArtifact(resource map[string]any, module string) bool {
|
||||
if named, _ := resource["artifact"].(string); named != "" {
|
||||
return true
|
||||
}
|
||||
image, _ := resource["image"].(string)
|
||||
return strings.HasPrefix(image, ArtifactStoreScheme+module+"/")
|
||||
}
|
||||
|
||||
// prepared is the module's own resource as the step that prepares its state: the same image, the same
|
||||
// context, run to completion with the mesh's preparation argument.
|
||||
//
|
||||
// Three things are taken away rather than copied, each because the step runs while the version it
|
||||
// prepares for is still running. A published port cannot be bound twice, and a step that tried would
|
||||
// fail for a reason that has nothing to do with the state. A fixed address cannot be held twice, for
|
||||
// the same reason. And a cadence is what a step is the opposite of: a container runs once and gates,
|
||||
// or on a schedule, or stays up, never two (ADR 0053).
|
||||
func prepared(from map[string]any) map[string]any {
|
||||
step := map[string]any{}
|
||||
for k, v := range from {
|
||||
step[k] = v
|
||||
}
|
||||
// **A hyphen, not a dot.** A resource's id is `<module>.<its own id>`, and a module's name may
|
||||
// itself contain a dot (`novox.be`), so the module is everything before the *last* dot — which
|
||||
// only works if what the mesh derives adds no dot of its own.
|
||||
step["id"] = fmt.Sprint(from["id"]) + "-prepare"
|
||||
step["name"] = fmt.Sprint(from["name"]) + "-prepare"
|
||||
step["run-once"] = true
|
||||
step["args"] = []any{PreparationArgument}
|
||||
delete(step, "ports")
|
||||
delete(step, "ip")
|
||||
delete(step, "schedule")
|
||||
delete(step, "reload-on")
|
||||
return step
|
||||
}
|
||||
|
||||
// endpointPortOf is the port the endpoint a route serves listens on: looked up by the name the route
|
||||
// gives, or read from the port it repeats (novox/hq ADR 0138).
|
||||
//
|
||||
// `ports` maps this module's endpoint names to their ports, computed once per module rather than
|
||||
// re-scanned per contribution.
|
||||
func endpointPortOf(values map[string]any, ports map[string]int) (int, bool) {
|
||||
if name, ok := values[RouteEndpoint].(string); ok {
|
||||
if port, found := ports[strings.TrimSpace(name)]; found {
|
||||
return port, true
|
||||
}
|
||||
}
|
||||
return asPort(values["port"])
|
||||
}
|
||||
|
||||
// endpointPorts is a module's endpoint names against the ports they listen on.
|
||||
func endpointPorts(m Manifest) map[string]int {
|
||||
out := map[string]int{}
|
||||
for _, l := range m.Listens {
|
||||
if name := strings.TrimSpace(l.Name); name != "" {
|
||||
out[name] = l.Port
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// portOfEndpoint fills in the port of the endpoint a contribution names, in place.
|
||||
//
|
||||
// **A contribution that names an endpoint must still carry that endpoint's port**, because everything
|
||||
// downstream reads the port: the provider is told where to reach the consumer, and the machine-side
|
||||
// redirection that turns a declared port into the number the machine published is keyed on it
|
||||
// (atMachinePort). A route that named only its endpoint left the proxy with no port at all, and a
|
||||
// proxy with no port has nothing to dial.
|
||||
//
|
||||
// Found before it shipped and after the catalogue had already been changed to name endpoints — the
|
||||
// manifests were merged and the mesh had not yet picked them up, so nothing was broken yet. The
|
||||
// declared port, not the machine one: the redirection happens later and is keyed on the declared
|
||||
// number, so filling in the machine port here would be redirected a second time or not at all.
|
||||
func portOfEndpoint(values map[string]any, ports map[string]int) {
|
||||
if values == nil {
|
||||
return
|
||||
}
|
||||
if _, already := values["port"]; already {
|
||||
// A route that says both is its own answer; the older shape repeated the port and is still read.
|
||||
return
|
||||
}
|
||||
name, ok := values[RouteEndpoint].(string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if port, found := ports[strings.TrimSpace(name)]; found {
|
||||
values["port"] = port
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package catalogue
|
||||
|
||||
import "testing"
|
||||
|
||||
// The mesh's user list reaches the module holding the bus, and nothing else.
|
||||
//
|
||||
// Three refusals and one delivery, because each of the refusals would be silent in a different way:
|
||||
// a module that asked and was given it could read every credential on the bus; a bus given an empty
|
||||
// file refuses every connection in the mesh and looks like a machine problem; and a bus that never
|
||||
// asked gets nothing rather than a file it does not read.
|
||||
func TestTheMeshsUserListGoesOnlyToTheModuleHoldingTheBus(t *testing.T) {
|
||||
theBus := func() Manifest {
|
||||
return Manifest{
|
||||
Module: "nats", Version: "1",
|
||||
Claims: []Claim{{Name: "mesh-broker", Scope: ScopeMesh}},
|
||||
BusUsers: "/var/lib/nats-module/conf/accounts.conf",
|
||||
Resources: []map[string]any{},
|
||||
}
|
||||
}
|
||||
|
||||
on := func(t *testing.T, m Manifest, with Rendering) ([]map[string]any, error) {
|
||||
t.Helper()
|
||||
return Resolution{Node: "anchor", Modules: []Manifest{m}}.Declaration(with)
|
||||
}
|
||||
|
||||
t.Run("the holder is given it", func(t *testing.T) {
|
||||
resources, err := on(t, theBus(), Rendering{BusUsers: "accounts { MESH { users = [] } }"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Prefixed with the module it came from, like every resource: two modules may reasonably
|
||||
// both call something "config", and without the prefix the second would silently replace
|
||||
// the first.
|
||||
var found map[string]any
|
||||
for _, r := range resources {
|
||||
if r["id"] == "nats."+BusUsersID() {
|
||||
found = r
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("the bus was given no user list: %+v", resources)
|
||||
}
|
||||
if found["path"] != "/var/lib/nats-module/conf/accounts.conf" {
|
||||
t.Errorf("written to %v rather than where the module asked", found["path"])
|
||||
}
|
||||
if found["mode"] != "0600" {
|
||||
t.Errorf("mode %v: a list of every user in the mesh belongs to the one process that "+
|
||||
"needs it", found["mode"])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a module that does not claim the seat is refused", func(t *testing.T) {
|
||||
m := theBus()
|
||||
m.Claims = nil
|
||||
if _, err := on(t, m, Rendering{BusUsers: "accounts {}"}); err == nil {
|
||||
t.Fatal("a module that claims nothing was handed every user's password hash")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the holder with nothing composed is refused", func(t *testing.T) {
|
||||
if _, err := on(t, theBus(), Rendering{}); err == nil {
|
||||
t.Fatal("the bus was given an empty user list, so it would refuse every connection in " +
|
||||
"the mesh and look like a machine problem")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a module that did not ask gets nothing", func(t *testing.T) {
|
||||
m := theBus()
|
||||
m.BusUsers = ""
|
||||
resources, err := on(t, m, Rendering{BusUsers: "accounts {}"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, r := range resources {
|
||||
if r["id"] == "nats."+BusUsersID() {
|
||||
t.Fatal("a module that asked for no user list was given one")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package catalogue
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// aMediaServer is the shape one port number per key cannot express: two endpoints of different kinds.
|
||||
// A web surface a proxy serves under a subdomain, and a protocol port clients dial directly because
|
||||
// the client expects that number.
|
||||
func aMediaServer() Manifest {
|
||||
return Manifest{
|
||||
Module: "media",
|
||||
Listens: []Listening{
|
||||
{Name: "web", Port: 80, From: FromMesh, Why: "the app, behind the proxy"},
|
||||
{Name: "stream", Port: 32400, From: FromEverywhere, Fixed: true,
|
||||
Why: "the client dials this number; the protocol chose it"},
|
||||
},
|
||||
Contributes: map[string]map[string]any{
|
||||
"route": {"label": "media", RouteEndpoint: "web"},
|
||||
},
|
||||
// Both endpoints are published by its container, which is what lets a machine port be given
|
||||
// for either: the mesh moves a port the module publishes, never one it merely listens on.
|
||||
Resources: []map[string]any{
|
||||
{"id": "server", "type": "container", "name": "media",
|
||||
"ports": []any{"80", "32400"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// **A route names the endpoint it serves.** A route and a listen both carried a port and nothing said
|
||||
// they were the same thing; now one of them says so.
|
||||
func TestARouteNamesTheEndpointItServes(t *testing.T) {
|
||||
m := aMediaServer()
|
||||
if port, ok := EndpointPort(m, "web"); !ok || port != 80 {
|
||||
t.Fatalf("the web endpoint resolves to %d (%v), want 80", port, ok)
|
||||
}
|
||||
if port, ok := EndpointPort(m, "stream"); !ok || port != 32400 {
|
||||
t.Fatalf("the stream endpoint resolves to %d (%v), want 32400", port, ok)
|
||||
}
|
||||
if _, ok := EndpointPort(m, "absent"); ok {
|
||||
t.Fatal("an endpoint the module does not declare resolved to a port")
|
||||
}
|
||||
}
|
||||
|
||||
// And the routed set is read through the name, so the endpoint the proxy serves is known without a
|
||||
// reader joining two numbers.
|
||||
func TestTheRoutedEndpointIsFoundByName(t *testing.T) {
|
||||
routed := RoutedPorts(aMediaServer())
|
||||
if !routed[80] {
|
||||
t.Fatalf("the routed endpoint was not found by name: %v", routed)
|
||||
}
|
||||
// And the directly-dialled one is not routed, which is what lets its reach govern its port.
|
||||
if routed[32400] {
|
||||
t.Fatalf("the endpoint clients dial directly reads as routed: %v", routed)
|
||||
}
|
||||
}
|
||||
|
||||
// **Two endpoints of different shapes, configured as themselves.** The web endpoint's reach asks for
|
||||
// names and leaves its port to the proxy; the stream endpoint's reach governs its port, because
|
||||
// clients dial it and there is no name.
|
||||
func TestTwoEndpointsOfDifferentShapesAreConfiguredSeparately(t *testing.T) {
|
||||
m := aMediaServer()
|
||||
settings := SettingsBy{"media": {{From: "node anchor", Values: map[string]any{
|
||||
ReachSetting: map[string]any{"80": ReachBoth, "32400": ReachPublic},
|
||||
}}}}
|
||||
|
||||
r := Resolution{Node: "anchor", Modules: []Manifest{m},
|
||||
PublicDomain: "example.test", At: "anchor.internal"}
|
||||
rules, err := r.Rules(Rendering{Settings: settings})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rule := range rules {
|
||||
switch rule.Port {
|
||||
case 80:
|
||||
if rule.From != FromMesh {
|
||||
t.Fatalf("the routed endpoint's port opened to %q; the proxy is how it is reached",
|
||||
rule.From)
|
||||
}
|
||||
case 32400:
|
||||
if rule.From != FromEverywhere {
|
||||
t.Fatalf("the directly-dialled endpoint's port is %q, want anywhere", rule.From)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// And the routed one carries both names, asked for by the same statement.
|
||||
given, err := r.contributions(settings, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var public, internal string
|
||||
for _, c := range given["route"] {
|
||||
public, _ = c.Values["name"].(string)
|
||||
internal, _ = c.Values["internal-name"].(string)
|
||||
}
|
||||
if public != "media.example.test" || internal != "media.anchor.internal" {
|
||||
t.Fatalf("names are %q and %q, want both", public, internal)
|
||||
}
|
||||
}
|
||||
|
||||
// A route naming an endpoint the module does not declare reaches nothing, and is refused where it is
|
||||
// written rather than resolving to no port and serving nothing.
|
||||
func TestARouteNamingAnEndpointTheModuleLacksIsRefused(t *testing.T) {
|
||||
m := aMediaServer()
|
||||
m.Contributes["route"][RouteEndpoint] = "absent"
|
||||
got := strings.Join(RouteProblems(m), "\n")
|
||||
if !strings.Contains(got, "does not declare") {
|
||||
t.Fatalf("a route naming an absent endpoint was accepted:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// **Two endpoints called the same would make an assignment configure whichever was read last.** The
|
||||
// point of a name is that it identifies one thing.
|
||||
func TestTwoEndpointsWithOneNameAreRefused(t *testing.T) {
|
||||
m := Manifest{Module: "twice", Listens: []Listening{
|
||||
{Name: "web", Port: 80, From: FromMesh},
|
||||
{Name: "web", Port: 8080, From: FromMesh},
|
||||
}}
|
||||
got := strings.Join(endpointNameProblems(m), "\n")
|
||||
if !strings.Contains(got, "could mean either") {
|
||||
t.Fatalf("two endpoints with one name were accepted:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A name that is not a name is refused where it is written: it ends up in something a person types.
|
||||
func TestAnEndpointNameIsHeldToItsShape(t *testing.T) {
|
||||
for _, wrong := range []string{"Web", "web port", "3000", "-web", "web_surface"} {
|
||||
m := Manifest{Module: "odd", Listens: []Listening{{Name: wrong, Port: 80, From: FromMesh}}}
|
||||
if got := strings.Join(endpointNameProblems(m), "\n"); !strings.Contains(got, "a name is lowercase") {
|
||||
t.Fatalf("%q was accepted as an endpoint name:\n%s", wrong, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// **Every endpoint in the catalogue is unnamed today, and must stay valid.** The word ships one
|
||||
// release before anything uses it.
|
||||
func TestAnUnnamedEndpointIsStillValid(t *testing.T) {
|
||||
m := Manifest{Module: "ordinary", Listens: []Listening{{Port: 443, From: FromEverywhere}}}
|
||||
if got := endpointNameProblems(m); len(got) != 0 {
|
||||
t.Fatalf("an unnamed endpoint was refused: %v", got)
|
||||
}
|
||||
if got := RouteProblems(m); len(got) != 0 {
|
||||
t.Fatalf("a module with no route was refused: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// **A route that names an endpoint still carries that endpoint's port.**
|
||||
//
|
||||
// Everything downstream reads the port: the provider is told where to reach the consumer, and the
|
||||
// redirection that turns a declared port into the number the machine published is keyed on it. A route
|
||||
// naming only its endpoint left the proxy with no port, and a proxy with no port has nothing to dial.
|
||||
//
|
||||
// Caught after the catalogue had already been changed to name endpoints, and before the mesh picked
|
||||
// those manifests up — which is the only reason nothing broke.
|
||||
func TestARouteNamingAnEndpointStillCarriesItsPort(t *testing.T) {
|
||||
m := aMediaServer()
|
||||
r := Resolution{Node: "anchor", Modules: []Manifest{m},
|
||||
PublicDomain: "example.test", At: "anchor.internal"}
|
||||
given, err := r.contributions(nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var saw bool
|
||||
for _, c := range given["route"] {
|
||||
saw = true
|
||||
port, ok := asPort(c.Values["port"])
|
||||
if !ok {
|
||||
t.Fatalf("the route carries no port, so the proxy has nothing to dial: %v", c.Values)
|
||||
}
|
||||
if port != 80 {
|
||||
t.Fatalf("the route carries port %d, want the web endpoint's 80", port)
|
||||
}
|
||||
}
|
||||
if !saw {
|
||||
t.Fatal("the module contributed no route")
|
||||
}
|
||||
}
|
||||
|
||||
// And the declared port, not the machine one: the redirection to where the machine published it
|
||||
// happens later and is keyed on the declared number, so filling the machine port in here would be
|
||||
// redirected twice or not at all.
|
||||
func TestTheEndpointsDeclaredPortIsFilledInNotTheMachineOne(t *testing.T) {
|
||||
m := aMediaServer()
|
||||
values := map[string]any{RouteEndpoint: "web", "label": "media"}
|
||||
portOfEndpoint(values, endpointPorts(m))
|
||||
if got, _ := asPort(values["port"]); got != 80 {
|
||||
t.Fatalf("filled in port %d, want the declared 80", got)
|
||||
}
|
||||
// Then the ordinary redirection puts it where the machine published it.
|
||||
moved := atMachinePort(values, m.Module, map[string]map[int]int{"media": {80: 20009}})
|
||||
if got, _ := asPort(moved["port"]); got != 20009 {
|
||||
t.Fatalf("after redirection the port is %d, want the machine's 20009", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A route that repeats a port keeps it, because that is the older shape and still read.
|
||||
func TestARouteThatRepeatsItsPortKeepsIt(t *testing.T) {
|
||||
values := map[string]any{RouteEndpoint: "web", "port": 8080}
|
||||
portOfEndpoint(values, map[string]int{"web": 80})
|
||||
if got, _ := asPort(values["port"]); got != 8080 {
|
||||
t.Fatalf("the port it stated was overwritten with %d", got)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user