Files
mesh-catalog/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/bus_test.go
T
2026-11-25 18:55:23 +01:00

644 lines
21 KiB
Go

//go:build integration
package main
import (
"git.novox.be/novox/mesh-sdk/go/buscalls"
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshdelivery "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
stdio "git.novox.be/novox/mesh-sdk/go"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
// **The acceptance of acting on events** (novox/hq ADR 0406, design 47 milestone 2, ADR 0391 phase 3, issue 975; ADR
// 0421, issue 1022): a pull request whose verdict passes is asked of the operator within seconds of the verdict's event,
// with no label, comment or mark written by anyone, and the merge is asked within five seconds of the Approve's event —
// with no tick, no poll and no reconcile to find it.
// Proved over a real bus: a JetStream server is linked into the test and started for it alone; the module is this
// test binary started again as the bundle, speaking MCP on its standard streams to a runtime played here, which does
// what the tool runner does for a bundle — its state on the buckets the controller would make from the manifest, its
// events delivered from the bus's streams, the controller's verbs and the forge's tools answered by the test (the
// pattern of mesh-issues' bus_test).
const bundleVar = "MESH_DELIVERY_TEST_BUNDLE"
func TestMain(m *testing.M) {
if os.Getenv(bundleVar) == "1" {
main()
os.Exit(0)
}
os.Exit(m.Run())
}
type testBus struct {
nc *nats.Conn
js jetstream.JetStream
kvs map[string]jetstream.KeyValue
// the teller's answers, as its tool teller_answers says them, and the delivery view's reach as view_reach says it.
mu sync.Mutex
answers map[string][]byte
// the gate's ledger `records`, as the tool runner keeps it: it outlives one run of the gate, as the bus's does.
ledger *ledgerFake
// registrations are what the seat mesh-catalog's verb registrations answers, and heads what the seat git's verb branch
// answers, by `<repository>@<branch>` (the start pass and the seed read them, design 47 H §768).
registrations []meshcatalog.Registration
heads map[string]string
}
func newTestBus(t *testing.T) *testBus {
t.Helper()
opts := &server.Options{Host: "127.0.0.1", Port: server.RANDOM_PORT, JetStream: true, StoreDir: t.TempDir(),
NoLog: true, NoSigs: true}
s, err := server.NewServer(opts)
if err != nil {
t.Fatalf("a bus for this test could not be made: %v", err)
}
go s.Start()
if !s.ReadyForConnections(30 * time.Second) {
s.Shutdown()
t.Fatal("a bus for this test did not come up within 30s")
}
t.Cleanup(func() { s.Shutdown(); s.WaitForShutdown() })
nc, err := nats.Connect(s.ClientURL())
if err != nil {
t.Fatal(err)
}
t.Cleanup(nc.Close)
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
b := &testBus{nc: nc, js: js, kvs: map[string]jetstream.KeyValue{}, answers: map[string][]byte{}}
// The controller's job: a bucket per state the manifest declares.
m, _ := readManifest(t)
for _, name := range m.withTemplateStates() {
kv, err := js.CreateKeyValue(context.Background(), jetstream.KeyValueConfig{Bucket: m.Module + "_" + name, History: 10})
if err != nil {
t.Fatal(err)
}
b.kvs[name] = kv
}
// The buckets of other modules the manifest reads (`<module>.<name>` is the bucket `<module>_<name>`): the checker's verdicts.
// The teller's answers and the view's reach are heard as events and asked of their tools (ADR 0596).
for _, name := range m.Reads {
kv, err := js.CreateKeyValue(context.Background(), jetstream.KeyValueConfig{Bucket: strings.Replace(name, ".", "_", 1), History: 10})
if err != nil {
t.Fatal(err)
}
b.kvs[name] = kv
}
// The streams the events are on (mesh.mod.<module>.event.<name>, mesh.seat.<seat>.event.<name>).
if _, err := js.CreateStream(context.Background(), jetstream.StreamConfig{Name: "EVENTS",
Subjects: []string{"mesh.seat.git.event.>", "mesh.seat." + oc.Seat + ".event.>",
"mesh.mod.mesh-delivery-forge-bridge.event.>", "mesh.mod.mesh-delivery-indexer.event.>",
"mesh.seat.mesh-pipeline-runner.event.>", "mesh.seat.mesh-wants.event.>", "mesh.seat.node-engine.event.>"}}); err != nil {
t.Fatal(err)
}
return b
}
// runtime is the half of the conversation the tool runner plays for one running bundle.
type runtime struct {
t *testing.T
b *testBus
cmd *exec.Cmd
in io.WriteCloser
mu sync.Mutex
next int
wait map[string]chan json.RawMessage
// what the bundle subscribed to, and asked of the mesh.
subs []string
asked []askedOfMesh
notify chan struct{}
// the asks the operator was asked, and the controller's walks and the forge's open pull requests as the test plays
// them.
operatorAsks []oc.Ask
// operatorCancels are the ids of the asks taken back from the router, in order (issue 1079).
operatorCancels []string
// owedSaid are the subjects of the seat events owed the gate said, in order (W11.17).
owedSaid []string
// endedSaid are the bodies of the record-ended events the gate said, in order (AC-G4a, AC-G4b).
endedSaid []json.RawMessage
// logs is what the bundle said in its journal.
logs *testLog
}
// endedSays are the end counts the gate said record-ended with for a record, in order.
func (r *runtime) endedSays(record string) []int64 {
r.mu.Lock()
defer r.mu.Unlock()
var out []int64
for _, raw := range r.endedSaid {
var e struct {
Record string `json:"record"`
Ends int64 `json:"ends"`
}
if json.Unmarshal(raw, &e) == nil && e.Record == record {
out = append(out, e.Ends)
}
}
return out
}
// journalHas is whether the bundle said a line in its journal holding every one of words.
func (r *runtime) journalHas(words ...string) bool {
r.logs.mu.Lock()
defer r.logs.mu.Unlock()
for _, l := range r.logs.said {
all := true
for _, w := range words {
all = all && strings.Contains(l, w)
}
if all {
return true
}
}
return false
}
type askedOfMesh struct {
Key string
Body map[string]any
At time.Time
}
func (b *testBus) start(t *testing.T) *runtime {
t.Helper()
cmd := exec.Command(os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), bundleVar+"=1", "MESH_SERVED_MODULE=mesh-delivery-gate", "MESH_MODULE=mesh-delivery-gate", "MESH_NODE=test")
in, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
out, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
logs := &testLog{t: t}
cmd.Stderr = logs
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64), logs: logs}
go r.read(out)
t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() })
return r
}
// testLog is the bundle's journal: said in the test's log, and kept for journalHas.
type testLog struct {
t *testing.T
mu sync.Mutex
said []string
}
func (w *testLog) Write(p []byte) (int, error) {
w.mu.Lock()
w.said = append(w.said, string(p))
w.mu.Unlock()
defer func() { _ = recover() }() // the bundle may speak after the test ended
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
// Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once
// to one record lost its delivery time).
if strings.Contains(string(p), "WARNING: DATA RACE") {
w.t.Error("the bundle reports a data race, above")
}
return len(p), nil
}
type rpcMessage struct {
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
func (r *runtime) say(m map[string]any) {
m["jsonrpc"] = "2.0"
raw, _ := json.Marshal(m)
r.mu.Lock()
defer r.mu.Unlock()
_, _ = r.in.Write(append(raw, '\n'))
}
func (r *runtime) read(out io.Reader) {
sc := bufio.NewScanner(out)
sc.Buffer(make([]byte, 1<<20), 1<<24)
for sc.Scan() {
var m rpcMessage
if json.Unmarshal(sc.Bytes(), &m) != nil {
continue
}
if m.Method == "" {
var id string
_ = json.Unmarshal(m.ID, &id)
r.mu.Lock()
ch := r.wait[id]
delete(r.wait, id)
r.mu.Unlock()
if ch != nil {
ch <- sc.Bytes()
}
continue
}
go r.answer(m)
}
}
// untilListening waits for the gate to have read its kept state back and subscribed to every event it follows: it takes no
// event before (loadKept), so a subscription is its word that it is ready.
func (r *runtime) untilListening() {
r.t.Helper()
r.until("the gate to listen to every event it follows", 20*time.Second, func() bool {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.subs) >= len(followed)
})
}
// noControllerAsk fails the test when the gate asked the controller anything: it asks it nothing (ADR 0539 §17, R6-C3).
func (r *runtime) noControllerAsk() {
r.t.Helper()
r.mu.Lock()
defer r.mu.Unlock()
for _, a := range r.asked {
if strings.HasPrefix(a.Key, "seat:mesh-controller.") {
r.t.Fatalf("the gate asked the controller %s: it asks it nothing", a.Key)
}
}
}
func (r *runtime) ping() {
select {
case r.notify <- struct{}{}:
default:
}
}
// asksOf are the asks of the mesh made so far under a key.
func (r *runtime) asksOf(key string) []askedOfMesh {
r.mu.Lock()
defer r.mu.Unlock()
var out []askedOfMesh
for _, a := range r.asked {
if a.Key == key {
out = append(out, a)
}
}
return out
}
// until waits for what the test needs to be true, woken by every message of the bundle.
func (r *runtime) until(what string, within time.Duration, ok func() bool) {
r.t.Helper()
deadline := time.After(within)
for {
if ok() {
return
}
select {
case <-r.notify:
case <-time.After(50 * time.Millisecond):
case <-deadline:
if ok() {
return
}
r.t.Fatalf("within %s: %s did not happen", within, what)
}
}
}
// toolAnswer is a tool's or a verb's answer as the runtime hands it over.
func toolAnswer(answer any) any {
return map[string]any{"ok": true, "output": "", "answer": answer}
}
func (r *runtime) answer(m rpcMessage) {
var p struct {
State string `json:"state"`
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Revision uint64 `json:"revision"`
Pattern string `json:"pattern"`
Subject string `json:"subject"`
Body json.RawMessage `json:"body"`
}
_ = json.Unmarshal(m.Params, &p)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
defer r.ping()
result, err := func() (any, error) {
switch m.Method {
case "mesh/subscribe":
r.mu.Lock()
r.subs = append(r.subs, p.Pattern)
r.mu.Unlock()
return map[string]any{}, nil
case "mesh/publish":
return map[string]any{}, nil // the module's own events: not needed here
case "mesh/seat.publish":
// The ask for the operator, published under the module's name.
if strings.Contains(p.Subject, ".accept.ask.") {
var a oc.Ask
if err := json.Unmarshal(p.Body, &a); err != nil {
return nil, err
}
r.mu.Lock()
r.operatorAsks = append(r.operatorAsks, a)
r.mu.Unlock()
}
if p.Subject == meshdelivery.SubjectRecordEnded {
r.mu.Lock()
r.endedSaid = append(r.endedSaid, p.Body)
r.mu.Unlock()
}
if strings.HasPrefix(p.Subject, "mesh.seat.mesh-delivery.event.owed.") {
r.mu.Lock()
r.owedSaid = append(r.owedSaid, p.Subject)
r.mu.Unlock()
}
if strings.Contains(p.Subject, ".accept.cancel.") {
var c struct {
ID string `json:"id"`
}
if err := json.Unmarshal(p.Body, &c); err != nil {
return nil, err
}
r.mu.Lock()
r.operatorCancels = append(r.operatorCancels, c.ID)
r.mu.Unlock()
}
return map[string]any{}, nil
case "mesh/seat.record":
return nil, nil
case "mesh/state.watch":
// The runtime's watch (ADR 0201): each current value, then each change, handed to the bundle as mesh/state under the
// id the watch was asked with.
var id string
_ = json.Unmarshal(m.ID, &id)
kv := r.b.kvs[p.State]
if kv == nil {
return nil, fmt.Errorf("the state %q is not declared", p.State)
}
go r.watch(kv, id, p.State)
return map[string]any{}, nil
case "mesh/ask":
var a struct {
Key string `json:"key"`
Body map[string]any `json:"body"`
}
if err := json.Unmarshal(m.Params, &a); err != nil {
return nil, err
}
r.mu.Lock()
r.asked = append(r.asked, askedOfMesh{Key: a.Key, Body: a.Body, At: time.Now()})
r.mu.Unlock()
switch a.Key {
case "":
return nil, errors.New("an ask with no key")
case "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbRegistrations:
r.b.mu.Lock()
defer r.b.mu.Unlock()
return toolAnswer(meshcatalog.RegistrationsAnswer{Registrations: append([]meshcatalog.Registration{}, r.b.registrations...)}), nil
case "seat:git.branch":
repository, _ := a.Body["repository"].(string)
branch, _ := a.Body["branch"].(string)
r.b.mu.Lock()
defer r.b.mu.Unlock()
head, ok := r.b.heads[repository+"@"+branch]
if !ok {
return nil, fmt.Errorf("the forge of this test holds no %s@%s", repository, branch)
}
return toolAnswer(map[string]any{"repository": repository, "branch": branch, "head": head}), nil
case "seat:mesh-hand-acts.hand-act":
return toolAnswer(map[string]any{"id": "hand-act-1"}), nil
case "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbEntry:
// A mover's catalog entry, read once for its class (design 47 H2 §810): a fingerprint of this test opening with
// "core" is a core module's, every other a leaf's.
if fp, _ := a.Body["fingerprint"].(string); strings.HasPrefix(fp, "core") {
return toolAnswer(map[string]any{"entry": map[string]any{"manifest": map[string]any{"class": "core"}}}), nil
}
return toolAnswer(map[string]any{"entry": map[string]any{"manifest": map[string]any{}}}), nil
case "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status", "gitea.gitea_merge_pull_request",
"gitea.gitea_add_comment":
return toolAnswer(map[string]any{}), nil
}
if strings.HasPrefix(a.Key, "seat:mesh-controller.") {
// The fake controller of this test fails on any call: the gate has no business with it.
return nil, fmt.Errorf("the controller is not to be called by the gate: %s", a.Key)
}
return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key)
}
switch m.Method {
case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove, buscalls.LedgerWatch:
// The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory.
r.b.mu.Lock()
defer r.b.mu.Unlock()
if r.b.ledger == nil {
r.b.ledger = newLedgerFake(r.t)
}
if m.Method == buscalls.LedgerWatch {
// The tool runner's ledger watch (design 47 H2 H-A-706): the current states first, each handed to the bundle as a
// `mesh/ledger` call named by the watch's id, then each change the ledger makes; answered once the current are sent.
var in buscalls.LedgerWatchRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
err := r.b.ledger.Watch(in.Instances, func(instance string, state json.RawMessage) error {
r.mu.Lock()
n := r.next
r.next++
r.mu.Unlock()
r.say(map[string]any{"id": fmt.Sprintf("ledger-%d", n), "method": buscalls.LedgerWatched,
"params": buscalls.InstanceChange{Watch: in.Watch, Instance: instance, State: state}})
return nil
})
return map[string]any{}, err
}
if m.Method == buscalls.LedgerQuery {
var in buscalls.QueryRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
insts, err := r.b.ledger.Query(in.Index, in.Key)
var a buscalls.QueryAnswer
for _, inst := range insts {
a.Entries = append(a.Entries, buscalls.IndexEntry{Instance: inst})
}
return a, err
}
if m.Method == buscalls.LedgerRemove {
// An act performed is removed (design 47 H2 §809, H-A-455 (1)), as the tool runner's ledger removal does.
var in buscalls.LedgerRemoveRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
return buscalls.LedgerRemoved{}, r.b.ledger.Remove(in.Instance)
}
if m.Method == buscalls.LedgerGet {
var in buscalls.InstanceRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
state, seq, err := r.b.ledger.Get(in.Instance)
return buscalls.InstanceState{Instance: in.Instance, State: state, Sequence: seq}, err
}
var in buscalls.ApplyRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
seq, err := r.b.ledger.Apply(in.Instance, in.Operation, in.Body)
return buscalls.Applied{Taken: err == nil, Sequence: seq}, err
}
kv := r.b.kvs[p.State]
if kv == nil {
return nil, fmt.Errorf("the state %q is not declared", p.State)
}
switch m.Method {
case "mesh/state.get":
e, err := kv.Get(ctx, p.Key)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return map[string]any{"key": p.Key, "value": json.RawMessage(e.Value()), "revision": e.Revision()}, nil
case "mesh/state.create":
rev, err := kv.Create(ctx, p.Key, p.Value)
return map[string]any{"revision": rev}, err
case "mesh/state.update":
rev, err := kv.Update(ctx, p.Key, p.Value, p.Revision)
return map[string]any{"revision": rev}, err
case "mesh/state.put":
rev, err := kv.Put(ctx, p.Key, p.Value)
return map[string]any{"revision": rev}, err
case "mesh/state.delete":
return map[string]any{}, kv.Delete(ctx, p.Key)
case "mesh/state.keys":
keys, err := kv.Keys(ctx)
if errors.Is(err, jetstream.ErrNoKeysFound) {
return []string{}, nil
}
return keys, err
}
return nil, fmt.Errorf("the runtime offers no %s to this bundle", m.Method)
}()
if err != nil {
code := -32000
var api *jetstream.APIError
if errors.Is(err, jetstream.ErrKeyExists) || errors.As(err, &api) && api.ErrorCode == jetstream.JSErrCodeStreamWrongLastSequence {
code = -32010
}
r.say(map[string]any{"id": m.ID, "error": map[string]any{"code": code, "message": err.Error()}})
return
}
r.say(map[string]any{"id": m.ID, "result": result})
}
// watch hands the bundle each key of a bucket and each change of it, as the runtime does for a state watch.
func (r *runtime) watch(kv jetstream.KeyValue, id, state string) {
ctx, cancel := context.WithCancel(context.Background())
r.t.Cleanup(cancel)
w, err := kv.Watch(ctx, ">")
if err != nil {
return
}
defer w.Stop()
current := true
for {
select {
case <-ctx.Done():
return
case e, ok := <-w.Updates():
if !ok {
return
}
if e == nil {
current = false
continue
}
op := "put"
if e.Operation() != jetstream.KeyValuePut {
op = "delete"
}
r.mu.Lock()
n := r.next
r.next++
r.mu.Unlock()
r.say(map[string]any{"id": fmt.Sprintf("watch-%d", n), "method": "mesh/state", "params": map[string]any{"watch": id,
"change": stdio.StateChange{State: state, Key: e.Key(), Op: op, Value: e.Value(), Revision: e.Revision(), Current: current}}})
}
}
}
// deliverEvents is the runtime reading the events streams and handing each event to the bundle, once, as
// `mesh/event`, the way the tool runner does for a module's consumer.
func (r *runtime) deliverEvents(ctx context.Context) {
stream, err := r.b.js.Stream(ctx, "EVENTS")
if err != nil {
r.t.Fatal(err)
}
cons, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{})
if err != nil {
r.t.Fatal(err)
}
cc, err := cons.Consume(func(msg jetstream.Msg) {
key := keyOfSubject(msg.Subject())
r.mu.Lock()
id := fmt.Sprintf("event-%d", r.next)
r.next++
r.mu.Unlock()
r.say(map[string]any{"id": id, "method": "mesh/event", "params": map[string]any{"envelope": stdio.Envelope{
Key: key, Node: "test", Body: msg.Data(), Headers: map[string]string{"x-source": strings.SplitN(key, ".", 2)[0]}}}})
})
if err != nil {
r.t.Fatal(err)
}
r.t.Cleanup(cc.Stop)
}
// keyOfSubject is an event's key, as the runtime gives it to a module: mesh.mod.<module>.event.<name> is
// <module>.<name>, and mesh.seat.<seat>.event.<name> is <seat>.<name>.
func keyOfSubject(subject string) string {
parts := strings.Split(subject, ".")
if len(parts) < 5 || parts[3] != "event" {
return subject
}
return parts[2] + "." + strings.Join(parts[4:], ".")
}
func (b *testBus) publish(t *testing.T, subject string, body any) time.Time {
t.Helper()
raw, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
if _, err := b.js.Publish(context.Background(), subject, raw); err != nil {
t.Fatal(err)
}
return time.Now()
}