diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go index 9b246454..466eff29 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main.go @@ -1,6 +1,6 @@ // Command mesh-delivery-forge-bridge-tools serves the forge bridge's tools (design 51; design 47 *What the gate owes the // forge*): the runtime launches it for a call. bridge_tags reads a package's git tags through the seat git's verb tags, -// for the builder's floor; bridge_owed, bridge_owed_again and bridge_owed_drop write an ask into the bridge's state +// for the builder's floor; bridge_heads reads the head the bridge holds for each watched branch; bridge_owed, bridge_owed_again and bridge_owed_drop write an ask into the bridge's state // owed-asks and wait for the bridge's answer there, since the bridge is the other program and serves no request subject // (ADR 0437 §4). package main @@ -21,8 +21,36 @@ import ( "mesh-delivery-forge-bridge/internal/groups" ) -// Tools are the bridge's reading tools: forge calls the seat git. -func Tools(forge bridge.Caller) []stdio.Tool { +// HeadsTool reads the bridge's state heads (design 47 H §739, H-A-48, H-A-85). +const HeadsTool = "bridge_heads" + +// headState is the state heads as bridge_heads reads it (stdio.KeptState). +type headState interface { + Keys() ([]string, error) + Get(key string) (*stdio.StateEntry, error) +} + +// heads is the state heads: each key, branch..., with the head the bridge holds for it. +func heads(s headState) (map[string]string, error) { + keys, err := s.Keys() + if err != nil { + return nil, fmt.Errorf("the bridge's state heads cannot be listed: %w", err) + } + out := map[string]string{} + for _, k := range keys { + e, err := s.Get(k) + if err != nil { + return nil, fmt.Errorf("the bridge's state heads cannot be read at %s: %w", k, err) + } + if e != nil { + out[k] = strings.TrimSpace(string(e.Value)) + } + } + return out, nil +} + +// Tools are the bridge's reading tools: forge calls the seat git, held is the state heads. +func Tools(forge bridge.Caller, held headState) []stdio.Tool { str := func(args map[string]any, k string) string { s, _ := args[k].(string); return strings.TrimSpace(s) } return []stdio.Tool{ {Name: bridge.TagsTool, @@ -35,6 +63,18 @@ func Tools(forge bridge.Caller) []stdio.Tool { Run: func(args map[string]any) (any, error) { return bridge.Tags(context.Background(), forge, str(args, "repository"), str(args, "prefix")) }}, + {Name: HeadsTool, + Description: "The head the forge bridge holds for each watched branch, the one its last head-moved named (design 47 H §739): " + + "each key of its state heads, branch..., with its head. Read-only; an untaken head is " + + "recovered with the gate's gate_head_take, never said again here.", + Input: map[string]any{"type": "object", "properties": map[string]any{}}, + Run: func(map[string]any) (any, error) { + h, err := heads(held) + if err != nil { + return nil, err + } + return map[string]any{"heads": h}, nil + }}, } } @@ -95,7 +135,7 @@ func main() { // The module the runtime serves these tools as: the bridge's, whose states they ask (design 47 G A-296). served := os.Getenv(stdio.ServedAs) performed := stdio.State(groups.PerformedState) - tools := Tools(askCaller) + tools := Tools(askCaller, stdio.State("heads")) owedAsks := stdio.State(groups.OwedAsksState) recorder := meshhandactsclient.Recorder{Ask: stdio.Ask} tools = append(tools, OwedTools(askState(owedAsks, groups.OwedAsksBucket(served), 25*time.Second, func(v []byte) bool { diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go index ce28c7ed..2ed11529 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge-tools/main_test.go @@ -3,19 +3,82 @@ package main import ( "encoding/json" "errors" + "reflect" "testing" "time" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" + stdio "git.novox.be/novox/mesh-sdk/go" "mesh-delivery-forge-bridge/internal/groups" ) +// memState is a state in memory as bridge_heads reads it. +type memState struct { + vals map[string]string + err error +} + +func (m memState) Keys() ([]string, error) { + if m.err != nil { + return nil, m.err + } + var out []string + for k := range m.vals { + out = append(out, k) + } + return out, nil +} + +func (m memState) Get(key string) (*stdio.StateEntry, error) { + v, ok := m.vals[key] + if !ok { + return nil, nil + } + return &stdio.StateEntry{Value: []byte(v)}, nil +} + // Design 47 *What the gate owes the forge*: bridge_owed reads what the bridge performed and its consumer's backlog, // bridge_owed_again and bridge_owed_drop write an ask and answer what the bridge answered, a drop naming why and // recorded as a hand act first. func TestTheBridgeTools(t *testing.T) { + // Design 47 H §739, H-A-48, H-A-85: bridge_heads answers each key of the state heads with its head, and says a state + // it cannot read, never none. + t.Run("bridge_heads", func(t *testing.T) { + const h1 = "1111111111111111111111111111111111111111" + for _, c := range []struct { + name string + state memState + want map[string]string + fails bool + }{ + {"two branches held", memState{vals: map[string]string{"branch.novox.mesh-sdk.main": h1, "branch.novox.mesh-sdk.beta": h1}}, + map[string]string{"branch.novox.mesh-sdk.main": h1, "branch.novox.mesh-sdk.beta": h1}, false}, + {"none held", memState{vals: map[string]string{}}, map[string]string{}, false}, + {"a state that cannot be listed", memState{err: errors.New("no responders")}, nil, true}, + } { + var run func(map[string]any) (any, error) + for _, tl := range Tools(nil, c.state) { + if tl.Name == HeadsTool { + run = tl.Run + } + } + if run == nil { + t.Fatalf("no tool %s", HeadsTool) + } + out, err := run(map[string]any{}) + if c.fails { + if err == nil { + t.Errorf("%s: %v, want an error", c.name, out) + } + continue + } + if m, _ := out.(map[string]any); err != nil || !reflect.DeepEqual(m["heads"], c.want) { + t.Errorf("%s: %v %v, want %v", c.name, out, err, c.want) + } + } + }) t.Run("the owed tools", func(t *testing.T) { at := time.Date(2026, 11, 9, 21, 0, 0, 0, time.UTC) var asked []groups.OwedAsk diff --git a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go index 278ab6ad..5a1a1ec6 100644 --- a/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go +++ b/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go @@ -4,8 +4,6 @@ package main import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -23,9 +21,7 @@ import ( git "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git" seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery" - checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker" "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg" - "git.novox.be/novox/mesh-sdk/go/keys" "git.novox.be/novox/mesh-sdk/go/process" "mesh-delivery-forge-bridge/internal/gitfixture" @@ -36,13 +32,12 @@ import ( // controller's user, and the bridge's own principal . with the permissions composed for its manifest, and // no others, so a permission the bridge lacks fails a test here and not on the mesh (issue 1279). // -// From module.json: the seat git's events heard through its durable on EVENTS; what the gate and the checker owe heard -// through its durable on each seat's own stream owed (SEAT__owed); the seat git's verbs, the seat mesh-delivery's -// groups and the seat mesh-hand-acts' hand-act called on mesh.seat..call.. (or its plain fallback); -// its own states heads, inputs, end-asks and owed-asks, and performed under the name its binding gives (the seat -// mesh-broker's show); its stream forge. It reads no state of the gate's or -// the checker's (design 47, acceptance 49 and 53). `**` is written `>` on the wire. The controller's own user keeps all -// rights, as it has. +// From module.json: the registrations and the gate's source-moved heard through its durable on EVENTS; branch-moved and +// what the gate owes heard through its durable on each seat's own stream (SEAT__); the seat git's verbs, the +// seat mesh-catalog's registrations, the seat mesh-delivery's source, the seat mesh-broker's show and the seat +// mesh-hand-acts' hand-act called on mesh.seat..call.. (or its plain fallback); its own states heads +// and owed-asks, and performed under the name its binding gives; its stream forge. `**` is written `>` on the wire. The +// controller's own user keeps all rights, as it has. const busConf = ` listen: 127.0.0.1:-1 jetstream { store_dir: %q } @@ -66,31 +61,13 @@ accounts { "$JS.API.STREAM.INFO.KV_mod_mesh-delivery-forge-bridge_performed_b1" "$JS.FC.KV_mod_mesh-delivery-forge-bridge_performed_b1.>" "$KV.mod_mesh-delivery-forge-bridge_performed_b1.>" - "$JS.API.CONSUMER.CREATE.KV_mod_mesh-delivery-forge-bridge_findings_b1.>" - "$JS.API.CONSUMER.DELETE.KV_mod_mesh-delivery-forge-bridge_findings_b1.>" - "$JS.API.DIRECT.GET.KV_mod_mesh-delivery-forge-bridge_findings_b1.>" - "$JS.API.STREAM.INFO.KV_mod_mesh-delivery-forge-bridge_findings_b1" - "$JS.FC.KV_mod_mesh-delivery-forge-bridge_findings_b1.>" "$KV.mod_mesh-delivery-forge-bridge_findings_b1.>" "$JS.API.STREAM.NAMES" "$JS.API.CONSUMER.CREATE.EVENTS" "$JS.API.CONSUMER.CREATE.EVENTS.>" "$JS.API.CONSUMER.DELETE.EVENTS.>" "$JS.API.CONSUMER.MSG.NEXT.EVENTS.>" - "mesh.bus.mesh-delivery-forge-bridge.finding-events.finding-written.n1" - "mesh.bus.mesh-delivery-forge-bridge.finding-events.finding-cleared.n1" - "mesh.bus.mesh-delivery-forge-bridge.finding-events.findings-stated.n1" - "$JS.API.CONSUMER.CREATE.KV_mesh-delivery-forge-bridge_inputs.>" - "$JS.API.CONSUMER.DELETE.KV_mesh-delivery-forge-bridge_inputs.>" - "$JS.API.DIRECT.GET.KV_mesh-delivery-forge-bridge_inputs.>" - "$JS.API.STREAM.INFO.KV_mesh-delivery-forge-bridge_inputs" - "$JS.FC.KV_mesh-delivery-forge-bridge_inputs.>" "$KV.mesh-delivery-forge-bridge_inputs.>" - "$JS.API.CONSUMER.CREATE.KV_mesh-delivery-forge-bridge_end-asks.>" - "$JS.API.CONSUMER.DELETE.KV_mesh-delivery-forge-bridge_end-asks.>" - "$JS.API.DIRECT.GET.KV_mesh-delivery-forge-bridge_end-asks.>" - "$JS.API.STREAM.INFO.KV_mesh-delivery-forge-bridge_end-asks" - "$JS.FC.KV_mesh-delivery-forge-bridge_end-asks.>" "$KV.mesh-delivery-forge-bridge_end-asks.>" "$JS.API.CONSUMER.CREATE.KV_mesh-delivery-forge-bridge_owed-asks.>" "$JS.API.CONSUMER.DELETE.KV_mesh-delivery-forge-bridge_owed-asks.>" @@ -105,10 +82,6 @@ accounts { "$JS.ACK.SEAT_mesh-delivery_owed.n1_mesh-delivery-forge-bridge.>" "$JS.API.CONSUMER.INFO.SEAT_mesh-delivery_owed.n1_mesh-delivery-forge-bridge" "$JS.API.CONSUMER.MSG.NEXT.SEAT_mesh-delivery_owed.n1_mesh-delivery-forge-bridge" - "$JS.API.STREAM.INFO.SEAT_mesh-delivery-checker_owed" - "$JS.ACK.SEAT_mesh-delivery-checker_owed.n1_mesh-delivery-forge-bridge.>" - "$JS.API.CONSUMER.INFO.SEAT_mesh-delivery-checker_owed.n1_mesh-delivery-forge-bridge" - "$JS.API.CONSUMER.MSG.NEXT.SEAT_mesh-delivery-checker_owed.n1_mesh-delivery-forge-bridge" "mesh.seat.mesh-broker.call.show.n1~mesh-delivery-forge-bridge" "mesh.seat.mesh-broker.tool.show" "mesh.seat.mesh-catalog.call.registrations.n1~mesh-delivery-forge-bridge" @@ -129,20 +102,8 @@ accounts { "mesh.seat.git.tool.view" "mesh.seat.git.call.note.n1~mesh-delivery-forge-bridge" "mesh.seat.git.tool.note" - "mesh.seat.git.call.merge-pull.n1~mesh-delivery-forge-bridge" - "mesh.seat.git.tool.merge-pull" - "mesh.seat.git.call.open-pulls.n1~mesh-delivery-forge-bridge" - "mesh.seat.git.tool.open-pulls" - "mesh.seat.git.call.trees.n1~mesh-delivery-forge-bridge" - "mesh.seat.git.tool.trees" - "mesh.seat.git.call.file.n1~mesh-delivery-forge-bridge" - "mesh.seat.git.tool.file" - "mesh.seat.git.call.pull.n1~mesh-delivery-forge-bridge" - "mesh.seat.git.tool.pull" "mesh.seat.git.call.tags.n1~mesh-delivery-forge-bridge" "mesh.seat.git.tool.tags" - "mesh.seat.mesh-delivery.call.groups.n1~mesh-delivery-forge-bridge" - "mesh.seat.mesh-delivery.tool.groups" "mesh.seat.mesh-hand-acts.call.hand-act.n1~mesh-delivery-forge-bridge" "mesh.seat.mesh-hand-acts.tool.hand-act" "mesh.stream.mesh-delivery-forge-bridge.event.forge.>" @@ -190,25 +151,14 @@ func startBus(t *testing.T) *server.Server { return srv } -// startBridge runs the program against an embedded bus with the stream EVENTS, the bridge's stream FORGE and its durable -// consumer _ on EVENTS, as the controller makes them (mesh-control internal/broker streams.go:192, -// nats.go:1387-1396, modstreams.go). It returns a control connection, its JetStream and a context. -func startBridge(t *testing.T, openReply string) (*nats.Conn, jetstream.JetStream, context.Context, <-chan error) { - b := startBed(t, openReply, nil) - return b.ctl, b.js, b.ctx, b.done -} - // bed is a started bridge with the bus it runs against. type bed struct { - srv *server.Server - ctl *nats.Conn - js jetstream.JetStream - ctx context.Context - done <-chan error - reply func(string) - // files sets what the stand-in seat git answers to file from then on; it is asked with the verb's input. - files func(func(repository, path, ref string) (string, bool)) - // answer sets the stand-in's answer to one verb of a seat (`.`) from then on. + srv *server.Server + ctl *nats.Conn + js jetstream.JetStream + ctx context.Context + done <-chan error + // answer sets the stand-in's answer to one verb of a seat (`.`, or `. `) from then on. answer func(verb string, answer string) // calls are the verbs the stand-in was called with, in order, as `. `. calls func() []string @@ -219,33 +169,18 @@ type bed struct { // answerOf is a verb's answer in the reply envelope of mesh-sdk go/process/call.go ({result, error, node}). func answerOf(answer string) []byte { return []byte(`{"result":` + answer + `,"node":"n0"}`) } -// fileAnswer is the seat git's answer to file: the content, or absent. -func fileAnswer(path, ref, content string, found bool) string { - if !found { - return `{"absent":true}` - } - b, _ := json.Marshal(git.FileAnswer{Path: path, Ref: ref, Content: content, Size: int64(len(content))}) - return string(b) -} - // boundPerformed is the bus name the stand-in seat mesh-broker's show answers for the state performed. const boundPerformed = "mod_mesh-delivery-forge-bridge_performed_b1" -// boundFindings is the bus name the stand-in seat mesh-broker's show answers for the state findings. -const boundFindings = "mod_mesh-delivery-forge-bridge_findings_b1" +// catalog is the repository the stand-in registrations name, its branch main watched (the seat mesh-catalog's fixture). +const catalog = "novox/mesh-catalog" -// boundFindingEvents and boundFindingEventsSubject are the stream and subject the stand-in seat mesh-broker's show answers -// for the bridge's finding events (design 47 G §529, A-274). -const ( - boundFindingEvents = "mod_mesh-delivery-forge-bridge_finding-events_b1" - boundFindingEventsSubject = "mesh.bus.mesh-delivery-forge-bridge.finding-events" -) - -// startBed is startBridge with a step between the streams and the consumers: prepare writes what the streams hold before -// the bridge's consumers are made, as the grants part makes them, from now (ADR 0443 §1), and reply sets the answer of the -// seat git's open-pulls from then on. A stand-in holds the seats the bridge calls: git (every verb, trees r0 by default, -// a module.json of {} at every path), mesh-delivery's groups (none by default) and mesh-hand-acts' hand-act. -func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, js jetstream.JetStream)) *bed { +// startBed runs the program the way the node does (its entry, run, with MESH_BROKER_FILE) against an embedded bus with +// the stream EVENTS, the seats' streams owed and branch-moved, the bridge's stream forge, its states and its durable +// consumers, as the controller and the grants part make them. A stand-in holds the seats the bridge calls: git (branch at +// head for main of the catalog, the act verbs as their fixtures answer), mesh-catalog's registrations (the catalog's main), +// mesh-delivery's source, mesh-broker's show and mesh-hand-acts' hand-act. +func startBed(t *testing.T, head string) *bed { srv := startBus(t) ctl, err := nats.Connect(srv.ClientURL(), nats.UserInfo("ctl", "pw")) if err != nil { @@ -264,38 +199,26 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "FORGE", Subjects: []string{"mesh.stream.mesh-delivery-forge-bridge.event.forge.>", "mesh.stream.mesh-delivery-forge-bridge.event.owed.ended"}}); err != nil { t.Fatal(err) } - // The bridge's own stream of its findings' events, its requires entry finding-events under the names the seat - // mesh-broker's show answers (design 47 G §529, A-274), which its finding writer says into. - if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: boundFindingEvents, Subjects: []string{boundFindingEventsSubject + ".>"}}); err != nil { - t.Fatal(err) - } - // Each seat's own stream owed, as its contract keeps it (Stream, SEAT__owed), as the grants part makes it: no - // subjects of its own, sourced from EVENTS filtered by the event's subject. - for name, subjects := range map[string]string{seat.StreamOwed: seat.SubjectOwedAll, checker.StreamOwed: checker.SubjectOwedAll, git.StreamBranchMoved: git.SubjectBranchMoved} { + seats := map[string]string{seat.StreamOwed: seat.SubjectOwedAll, git.StreamBranchMoved: git.SubjectBranchMoved} + for name, subjects := range seats { if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: name, MaxAge: 7 * 24 * time.Hour, Sources: []*jetstream.StreamSource{{Name: "EVENTS", FilterSubject: subjects}}}); err != nil { t.Fatal(err) } } - // The bridge's states, made from the manifest's state entries and its requires before the process starts; the state - // performed under the bus name the seat mesh-broker's show answers for it (boundPerformed), never an old name (§577). - for _, name := range []string{headsBucket(forgeBridgeModule()), boundPerformed, boundFindings, inputsBucket(forgeBridgeModule()), groupkeys.EndAsksBucket(forgeBridgeModule()), groupkeys.OwedAsksBucket(forgeBridgeModule())} { + for _, name := range []string{headsBucket(forgeBridgeModule()), boundPerformed, groupkeys.OwedAsksBucket(forgeBridgeModule())} { if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1}); err != nil { t.Fatal(err) } } - if prepare != nil { - prepare(ctx, js) - } acct := process.Account{Node: "n1", Module: "mesh-delivery-forge-bridge"} if _, err := js.CreateOrUpdateConsumer(ctx, "EVENTS", jetstream.ConsumerConfig{ Durable: acct.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy, DeliverPolicy: jetstream.DeliverNewPolicy, - FilterSubjects: []string{git.SubjectPullUpdated, git.SubjectPullMerged, git.SubjectPullClosed, git.SubjectForgeDelete, - "mesh.seat.mesh-catalog.event.registration-changed", "mesh.seat.mesh-delivery.event.source-moved"}, + FilterSubjects: []string{"mesh.seat.mesh-catalog.event.registration-changed", "mesh.seat.mesh-delivery.event.source-moved"}, }); err != nil { t.Fatal(err) } - for name, subjects := range map[string]string{seat.StreamOwed: seat.SubjectOwedAll, checker.StreamOwed: checker.SubjectOwedAll, git.StreamBranchMoved: git.SubjectBranchMoved} { + for name, subjects := range seats { if _, err := js.CreateOrUpdateConsumer(ctx, name, acct.SeatEventConsumerConfig([]string{subjects}, false)); err != nil { t.Fatal(err) } @@ -304,20 +227,15 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, // The stand-in seats, answering on the caller-named subject and its plain fallback. var mu sync.Mutex answers := map[string]string{ - "git.open-pulls": openReply, "git.trees": `{"root":"r0","trees":{"":"t0","modules/a":"t1"}}`, - "mesh-delivery.groups": `{"groups":[]}`, "mesh-hand-acts.hand-act": `{"recorded":true}`, - // No registration yet: the watched branches are the gate's source's, main (design 47 G §507). - "mesh-catalog.registrations": `{"registrations":[]}`, "mesh-delivery.source": `{"branches":["main"]}`, - "git.pull": `{"error":"no pull request merged at that commit","error-kind":"not-found"}`, - "mesh-broker.show": `{"state":"created","binding":{"local":"performed","storage":"key-value","template":"state","bucket":"` + boundPerformed + `"}}`, - "mesh-broker.show findings": `{"state":"created","binding":{"local":"findings","storage":"key-value","template":"state","bucket":"` + boundFindings + `"}}`, - "mesh-broker.show finding-events": `{"state":"created","binding":{"local":"finding-events","storage":"stream","template":"events","stream":"` + - boundFindingEvents + `","subject":"` + boundFindingEventsSubject + `"}}`, + "mesh-hand-acts.hand-act": `{"recorded":true}`, + "mesh-catalog.registrations": string(gitfixture.Seat(t, "mesh-catalog", "verbs", "registrations answers one with its versions", "verb:registrations.answer")[0]), + "mesh-delivery.source": `{"branches":["main"]}`, + "mesh-broker.show": `{"state":"created","binding":{"local":"performed","storage":"key-value","template":"state","bucket":"` + boundPerformed + `"}}`, + "git.branch " + catalog: `{"repository":"` + catalog + `","branch":"main","head":"` + head + `","protected":true}`, } - for _, verb := range []string{"status", "comment", "view", "note", "merge-pull"} { + for _, verb := range []string{"status", "comment", "view", "note"} { answers["git."+verb] = string(gitfixture.Given(t, verb+" answers", "verb:"+verb+".answer")) } - filesOf := func(_, path, _ string) (string, bool) { return "{}", strings.HasSuffix(path, "module.json") } var called []string for _, subject := range []string{"mesh.seat.*.call.*.*", "mesh.seat.*.tool.*"} { sub, err := ctl.Subscribe(subject, func(m *nats.Msg) { @@ -325,23 +243,14 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, verb := parts[2] + "." + parts[4] mu.Lock() called = append(called, verb+" "+string(m.Data)) - answer, files := answers[verb], filesOf - var in struct { - Repository string - Local string `json:"local-name"` - } + answer := answers[verb] + var in struct{ Repository string } if json.Unmarshal(m.Data, &in) == nil && answers[verb+" "+in.Repository] != "" { - answer = answers[verb+" "+in.Repository] // a move's branch and pull, set per repository (landedOn) - } - if in.Local != "" && answers[verb+" "+in.Local] != "" { - answer = answers[verb+" "+in.Local] // show answers each entry of the module's requires by its local name + answer = answers[verb+" "+in.Repository] } mu.Unlock() - if verb == "git.file" { - var in git.FileInput - _ = json.Unmarshal(m.Data, &in) - content, found := files(in.Repository, in.Path, in.Ref) - answer = fileAnswer(in.Path, in.Ref, content, found) + if answer == "" { + answer = `{"error":"the stand-in holds no answer"}` } _ = m.Respond(answerOf(answer)) }) @@ -370,10 +279,8 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, start() t.Cleanup(func() { stop() }) set := func(verb, answer string) { mu.Lock(); answers[verb] = answer; mu.Unlock() } - return &bed{srv: srv, ctl: ctl, js: js, ctx: ctx, done: done, reply: func(s string) { set("git.open-pulls", s) }, - files: func(f func(repository, path, ref string) (string, bool)) { mu.Lock(); filesOf = f; mu.Unlock() }, - answer: set, - calls: func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), called...) }, + return &bed{srv: srv, ctl: ctl, js: js, ctx: ctx, done: done, answer: set, + calls: func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), called...) }, restart: func(between func()) { stop() <-done @@ -382,357 +289,98 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context, }} } -// landedOn sets the stand-in seat git so main of repository is protected at at, which the pull request number on branch -// at prHead merged. -func landedOn(b *bed, repository string, number int, branch, prHead, at string) { - b.answer("git.branch "+repository, `{"repository":"`+repository+`","branch":"main","head":"`+at+`","protected":true}`) - b.answer("git.pull "+repository, fmt.Sprintf(`{"pull":{"repository":%q,"number":%d,"branch":%q,"head":%q,"base":"main","state":"merged","merge-commit":%q}}`, - repository, number, branch, prHead, at)) +// headAt sets the stand-in seat git so main of the catalog is at head, protected or not. +func headAt(b *bed, head string, protected bool) { + p := "true" + if !protected { + p = "false" + } + b.answer("git.branch "+catalog, `{"repository":"`+catalog+`","branch":"main","head":"`+head+`","protected":`+p+`}`) } -// moveMain says main of repository moved, as the seat git says it, naming a head the bridge never takes (§11). -func moveMain(t *testing.T, b *bed, repository string) { +// move says branch of the catalog moved, as the seat git says it, naming a head the bridge never takes (§739). +func move(t *testing.T, b *bed, branch string) { t.Helper() - ev, _ := json.Marshal(git.BranchMovedEvent{Repository: repository, Branch: "main", Head: strings.Repeat("f", 40)}) + ev, _ := json.Marshal(git.BranchMovedEvent{Repository: catalog, Branch: branch, Head: strings.Repeat("f", 40)}) if _, err := b.js.Publish(b.ctx, git.SubjectBranchMoved, ev); err != nil { t.Fatal(err) } } -// TestBridgeWritesPullMessages starts the program the way the node does (its entry, run, with MESH_BROKER_FILE). -func TestBridgeWritesPullMessages(t *testing.T) { // 1235/AC2 - ctl, js, ctx, _ := startBridge(t, `{"pulls":[]}`) - defer branchDeletedCase(t, ctl.ConnectedUrl(), js, ctx) - - // pull.updated as the seat git says it (its contract's PullUpdatedEvent). - ev, _ := json.Marshal(git.PullUpdatedEvent{Repository: "novox/mesh-delivery", Number: 12, Title: "t", Base: "main", Branch: "feat/x", Head: head, - Change: &git.Change{Paths: []string{"modules/a/x.go"}, ModuleDirs: []string{"modules/a"}}}) - if _, err := js.Publish(ctx, git.SubjectPullUpdated, ev); err != nil { - t.Fatal(err) - } - - forge, err := js.Stream(ctx, "FORGE") - if err != nil { - t.Fatal(err) - } - var info *jetstream.StreamInfo - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if info, err = forge.Info(ctx); err == nil && info.State.Msgs >= 2 { - break - } - } - // The open message the bridge writes at its start (ADR 0443 §5), and the event's message. - if info.State.Msgs != 2 { - t.Fatalf("FORGE holds %d messages within 20 s, want 2", info.State.Msgs) - } - raw, err := forge.GetLastMsgForSubject(ctx, "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.pull") - if err != nil { - t.Fatal(err) - } - f, err := forgemsg.DecodeForge(raw.Data) - if err != nil { - t.Fatal(err) - } - want := forgemsg.Forge{V: keys.Version, Kind: "pull", Repository: "novox/mesh-delivery", Branch: "feat/x", Number: 12, Head: head, - Action: "updated", Dirs: []string{"modules/a"}, DirsKnown: true, Manifests: map[string]string{"modules/a": "{}"}} - if !forgemsg.SameForge(f, want) { - t.Errorf("message = %+v, want %+v", f, want) - } - - // The event is acknowledged: the consumer owes nothing and has nothing pending. - cons, err := js.Consumer(ctx, "EVENTS", "n1_mesh-delivery-forge-bridge") - if err != nil { - t.Fatal(err) - } - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - ci, err := cons.Info(ctx) - if err == nil && ci.NumAckPending == 0 && ci.NumPending == 0 && ci.Delivered.Consumer >= 1 { - return - } - } - ci, _ := cons.Info(ctx) - t.Errorf("the event is not acknowledged: %+v", ci) -} - -// branchDeletedCase is DLV-FB1's case of the bridge's whole-module test (design 51): the seat git's forge.delete of a -// branch is a branch-deleted message on FORGE, and a forge.delete from another account than the seat's holder is refused -// by the bus. -func branchDeletedCase(t *testing.T, srv string, js jetstream.JetStream, ctx context.Context) { +// held waits, on a watch of the state heads, until it holds head for main of the catalog. +func held(t *testing.T, b *bed, head string) { t.Helper() - ev, _ := json.Marshal(git.ForgeDeleteEvent{Repository: "novox/mesh-sdk", Ref: "feat/x", RefType: "branch"}) - if _, err := js.Publish(ctx, git.SubjectForgeDelete, ev); err != nil { - t.Fatal(err) - } - forge, err := js.Stream(ctx, "FORGE") + kv, err := b.js.KeyValue(b.ctx, headsBucket(forgeBridgeModule())) if err != nil { t.Fatal(err) } - subject := "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-sdk.branch-deleted" - var raw *jetstream.RawStreamMsg - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if raw, err = forge.GetLastMsgForSubject(ctx, subject); err == nil { - break - } - } - if err != nil || !strings.Contains(string(raw.Data), `"branch":"feat/x"`) { - t.Fatalf("no branch-deleted message on FORGE within 20 s: %v", err) - } - other, err := nats.Connect(srv, nats.UserInfo("n1.mesh-delivery-forge-bridge", "pw")) + w, err := kv.Watch(b.ctx, "branch.novox.mesh-catalog.main") if err != nil { t.Fatal(err) } - defer other.Close() - ojs, _ := jetstream.New(other) - octx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - if _, err := ojs.Publish(octx, git.SubjectForgeDelete, ev); err == nil { - t.Error("a forge.delete from the bridge's account was taken by the bus: only the seat git's holder may say it") - } -} - -const merge = "89abcdef0123456789abcdef0123456789abcdef" - -// openPull is one entry of the seat git's open-pulls answer. -func openPull(repo string, number int, branch, head string) string { - b, _ := json.Marshal(git.OpenPull{Pull: git.Pull{Repository: "novox/" + repo, Number: int64(number), Base: "main", Branch: branch, Head: head, State: "open"}, - Checks: map[string]git.Status{}, Required: []string{}}) - return string(b) -} - -// TestBridgeWritesMergedMessage: the stand-in seat git answers trees and file on the caller-named subjects. -func TestBridgeWritesMergedMessage(t *testing.T) { // 1236/AC4, 1448/AC5 - bed := startBed(t, `{"pulls":[]}`, nil) - js, ctx := bed.js, bed.ctx - // The stand-in forge's files are two real files of this repository (this module's module.json and go.sum, read from the - // working tree), in the seat git's file answer: the root has a manifest only, modules/a a manifest and go.sum. - manifest, err := os.ReadFile("../../module.json") - if err != nil { - t.Fatal(err) - } - sum, err := os.ReadFile("../../go.sum") - if err != nil { - t.Fatal(err) - } - bed.files(func(_, path, ref string) (string, bool) { - if ref != merge { - t.Errorf("the forge was asked for %s at %s, want the merge commit %s", path, ref, merge) - } - switch path { - case "module.json", "modules/a/module.json": - return string(manifest), true - case "modules/a/go.sum": - return string(sum), true - } - return "", false - }) - // design 47 G §11, §509, §714: main moved, read by the seat's branch, and the forge names #12 merged at its head. - landedOn(bed, "novox/mesh-delivery", 12, "feat/x", head, merge) - moveMain(t, bed, "novox/mesh-delivery") - - forge, err := js.Stream(ctx, "FORGE") - if err != nil { - t.Fatal(err) - } - var info *jetstream.StreamInfo - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if info, err = forge.Info(ctx); err == nil && info.State.Msgs >= 2 { - break - } - } - // The open message the bridge writes at its start (ADR 0443 §5), and the event's message. - if info.State.Msgs != 2 { - t.Fatalf("FORGE holds %d messages within 20 s, want 2", info.State.Msgs) - } - raw, err := forge.GetLastMsgForSubject(ctx, "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.merged") - if err != nil { - t.Fatal(err) - } - f, err := forgemsg.DecodeForge(raw.Data) - if err != nil { - t.Fatal(err) - } - want := forgemsg.Forge{V: keys.Version, Kind: "merged", Repository: "novox/mesh-delivery", Branch: "feat/x", Number: 12, Head: head, - Merge: merge, Base: "main", Root: "r0", Trees: map[string]string{"": "t0", "modules/a": "t1"}, - Manifests: map[string]string{"": string(manifest), "modules/a": string(manifest)}, - // No mesh package: only the indexer computes what a fingerprint takes (ADR 0593 §2). - Locks: map[string]map[string]string{"modules/a": {"go.sum": hex.EncodeToString(sha256Sum(sum))}}} - if !forgemsg.SameForge(f, want) { - t.Errorf("message = %+v, want %+v", f, want) - } - var trees []string - for _, c := range bed.calls() { - if strings.HasPrefix(c, "git.trees ") { - trees = append(trees, c) - } - } - in, _ := json.Marshal(git.TreesInput{Repository: "novox/mesh-delivery", Commit: merge}) - if len(trees) != 1 || trees[0] != "git.trees "+string(in) { - t.Errorf("the seat git was asked for trees %v, want once at the merge commit", trees) - } - cons, err := js.Consumer(ctx, git.StreamBranchMoved, "n1_mesh-delivery-forge-bridge") - if err != nil { - t.Fatal(err) - } - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - ci, err := cons.Info(ctx) - if err == nil && ci.NumAckPending == 0 && ci.NumPending == 0 && ci.Delivered.Consumer >= 1 { - return - } - } - ci, _ := cons.Info(ctx) - t.Errorf("the event is not acknowledged: %+v", ci) -} - -// TestBridgeSaysTheOpenPullsAtStart: the forge holds two open pull requests when the bridge starts; one message each is on -// FORGE, and the open message naming both after them (ADR 0443 §5). -func TestBridgeSaysTheOpenPullsAtStart(t *testing.T) { // 1237/AC1 - // The entries are the seat git's open-pulls answer (its contract's OpenPull). - _, js, ctx, _ := startBridge(t, `{"pulls":[ - `+openPull("mesh-delivery", 12, "feat/x", head)+`, - `+openPull("mesh-catalog", 300, "feat/x", strings.Repeat("a", 40))+`]}`) - forge, err := js.Stream(ctx, "FORGE") - if err != nil { - t.Fatal(err) - } - var info *jetstream.StreamInfo - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if info, err = forge.Info(ctx); err == nil && info.State.Msgs >= 3 { - break - } - } - if info.State.Msgs != 3 { - t.Fatalf("FORGE holds %d messages within 20 s, want 3", info.State.Msgs) - } - for _, repo := range []string{"mesh-delivery", "mesh-catalog"} { - raw, err := forge.GetLastMsgForSubject(ctx, "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox."+repo+".pull") - if err != nil { - t.Fatal(err) - } - if f, err := forgemsg.DecodeForge(raw.Data); err != nil || f.Action != "updated" || f.DirsKnown || f.Branch != "feat/x" { - t.Errorf("%s: %+v err %v", repo, f, err) - } - } -} - -// TestBridgeExitsWhenTheOpenPullsCannotBeRead: the process manager starts it again. -func TestBridgeExitsWhenTheOpenPullsCannotBeRead(t *testing.T) { // 1237/AC3 - _, _, _, done := startBridge(t, `{"error":"the forge said 502","error-kind":"failed","pulls":[]}`) - select { - case err := <-done: - if err == nil || !strings.Contains(err.Error(), "open-pulls") || !strings.Contains(err.Error(), "the forge said 502") { - t.Errorf("run returned %v", err) - } - case <-time.After(10 * time.Second): - t.Fatal("the bridge did not exit") - } -} - -// TestBridgeReadsTheForgeAtStartAndAfterAReconnectAndHearsNoOlderEvent starts the bridge whole against a fake forge with two -// open pull requests, one of them with its head already kept in the bucket heads, and a bus whose EVENTS holds older pull events from -// before its consumer was made, under the permissions the controller composes for the bridge. At start it writes the one pull message that differs and the open message naming both; -// the bus connection closed, it reads the forge again and writes the open message alone, since every head is held now; -// for the older events it writes nothing (ADR 0443 §1, §5). -func TestBridgeReadsTheForgeAtStartAndAfterAReconnectAndHearsNoOlderEvent(t *testing.T) { // 1279/AC8 - h2 := strings.Repeat("a", 40) - pullSubject := func(repo string) string { - return "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox." + repo + ".pull" - } - openSubject := "mesh.stream.mesh-delivery-forge-bridge.event.forge.open" - b := startBed(t, `{"pulls":[`+openPull("mesh-delivery", 12, "feat/x", head)+`,`+openPull("mesh-catalog", 300, "feat/x", h2)+`]}`, - func(ctx context.Context, js jetstream.JetStream) { - // Older events: a pull request long closed and one long updated, from before the bridge's consumer. - for subject, ev := range map[string]any{ - git.SubjectPullUpdated: git.PullUpdatedEvent{Repository: "novox/mesh-old", Number: 5, Base: "main", Branch: "feat/old", Head: h2}, - git.SubjectPullClosed: git.PullClosedEvent{Repository: "novox/mesh-older", Number: 6, Base: "main", Branch: "feat/older", Head: h2}, - } { - raw, _ := json.Marshal(ev) - if _, err := js.Publish(ctx, subject, raw); err != nil { - t.Fatal(err) - } + defer w.Stop() + bound := time.After(20 * time.Second) + for { + select { + case e := <-w.Updates(): + if e != nil && string(e.Value()) == head { + return } - // What the bridge kept of an earlier write: the head of mesh-delivery#12. - kv, err := js.KeyValue(ctx, headsBucket(forgeBridgeModule())) - if err != nil { - t.Fatal(err) - } - if _, err := kv.PutString(ctx, "novox.mesh-delivery.12", head); err != nil { - t.Fatal(err) - } - }) - forge, err := b.js.Stream(b.ctx, "FORGE") - if err != nil { - t.Fatal(err) + case <-bound: + t.Fatalf("the state heads does not hold %s within 20 s", head) + } } - waitMsgs := func(want uint64) { +} + +// Design 47 H §739 (B4 AC1, the bridge's whole test): a start, a merge, an admitted push to an unprotected branch and a +// restart each give one head-moved on the stream forge, naming the head read through the seat git's verb branch and the +// head held before, start true at a start; a head heard twice, a restart at the head held and a branch not watched give +// none; the bridge asks no pull, tree or file. +func TestBridgeSaysOneHeadMovedPerMove(t *testing.T) { + const h1, h2, h3, h4, h5 = "1111111111111111111111111111111111111111", "2222222222222222222222222222222222222222", + "3333333333333333333333333333333333333333", "4444444444444444444444444444444444444444", "5555555555555555555555555555555555555555" + b := startBed(t, h1) + ch := heard(t, b) + subject := forgeSubject("forge.novox.mesh-catalog.main.head-moved") + said := func(what string, want forgemsg.HeadMoved) { t.Helper() - var info *jetstream.StreamInfo - for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if info, err = forge.Info(b.ctx); err == nil && info.State.Msgs >= want { - break - } - } - time.Sleep(300 * time.Millisecond) // and nothing more arrives - if info, err = forge.Info(b.ctx); err != nil || info.State.Msgs != want { - t.Fatalf("FORGE holds %d messages (%v), want %d", info.State.Msgs, err, want) + h, err := forgemsg.DecodeHeadMoved(next(t, ch, subject)) + want.V, want.Repository, want.Branch = forgemsg.Version, catalog, "main" + if err != nil || h != want { + t.Errorf("%s: %+v %v, want %+v", what, h, err, want) } } - named := func(seq uint64) []forgemsg.OpenPull { - t.Helper() - raw, err := forge.GetMsg(b.ctx, seq) - if err != nil || raw.Subject != openSubject { - t.Fatalf("message %d: %v %v, want the open message", seq, raw, err) + said("the start", forgemsg.HeadMoved{Head: h1, Start: true}) + headAt(b, h2, true) + move(t, b, "main") + said("a merge", forgemsg.HeadMoved{Head: h2, Before: h1}) + move(t, b, "main") // the same head heard twice + move(t, b, "feat/47-H") // a branch not watched + headAt(b, h3, false) // an admitted push, the branch unprotected (ADR 0682 §13) + move(t, b, "main") + said("an admitted push to an unprotected branch", forgemsg.HeadMoved{Head: h3, Before: h2}) + held(t, b, h3) // the bridge keeps the head after it writes the message: a stop between says the older head before + b.restart(func() { headAt(b, h4, true) }) + said("a restart after a move", forgemsg.HeadMoved{Head: h4, Before: h3, Start: true}) + held(t, b, h4) + b.restart(func() {}) // at the head held: nothing + headAt(b, h5, true) + move(t, b, "main") + said("the next move, the first message after the restart at the head held", forgemsg.HeadMoved{Head: h5, Before: h4}) + for _, c := range b.calls() { + if strings.HasPrefix(c, "git.") && !strings.HasPrefix(c, "git.branch ") { + t.Errorf("the bridge asked %s; it asks the seat git nothing but branch", c) } - f, err := forgemsg.DecodeForge(raw.Data) - if err != nil { - t.Fatal(err) - } - return f.Open } - bothOpen := []forgemsg.OpenPull{{Repository: "novox/mesh-catalog", Number: 300}, {Repository: "novox/mesh-delivery", Number: 12}} - same := func(got []forgemsg.OpenPull) bool { - return len(got) == 2 && got[0] == bothOpen[0] && got[1] == bothOpen[1] - } - - // At start: the one pull message that differs (1), the open message naming both (2). - waitMsgs(2) - if raw, err := forge.GetMsg(b.ctx, 1); err != nil || raw.Subject != pullSubject("mesh-catalog") { - t.Fatalf("message 1 = %v %v, want mesh-catalog's pull message", raw, err) - } - if got := named(2); !same(got) { - t.Fatalf("the open message names %v, want %v", got, bothOpen) - } - - // The connection closes and reopens: the forge is read again, every head is held, the open message alone follows. - conns, err := b.srv.Connz(&server.ConnzOptions{}) + heads, err := b.js.KeyValue(b.ctx, headsBucket(forgeBridgeModule())) if err != nil { t.Fatal(err) } - closed := 0 - for _, c := range conns.Conns { - if c.Name == "n1.mesh-delivery-forge-bridge" { - if err := b.srv.DisconnectClientByID(c.Cid); err != nil { - t.Fatal(err) - } - closed++ - } - } - if closed != 1 { - t.Fatalf("%d connections of the bridge found", closed) - } - waitMsgs(3) - if got := named(3); !same(got) { - t.Fatalf("after the reconnect the open message names %v, want %v", got, bothOpen) - } - - // For the older events nothing was written. - for _, repo := range []string{"mesh-old", "mesh-older"} { - if raw, err := forge.GetLastMsgForSubject(b.ctx, pullSubject(repo)); err == nil { - t.Errorf("a message for %s's older event: %+v", repo, raw) - } + if e, err := heads.Get(b.ctx, "branch.novox.mesh-catalog.main"); err != nil || string(e.Value()) != h5 { + t.Errorf("the state heads holds %v (%v), want %s", e, err, h5) } } -// heard is every message published under the bridge's stream subjects from now, by subject. func heard(t *testing.T, b *bed) <-chan *nats.Msg { t.Helper() ch := make(chan *nats.Msg, 64) @@ -787,37 +435,8 @@ func refusedRead(t *testing.T, b *bed, bucket string) { // Acceptance 49: the forge bridge sets the group on each member's merged message and says the group's end once, after the // last member's, from the seat mesh-delivery's verb groups; its account reads no state of the gate's. -func TestBridgeSaysAGroupFromTheSeatsGroups(t *testing.T) { // 1585, ADR 0633 §4 - b := startBed(t, `{"pulls":[]}`, nil) - headB := strings.Repeat("b", 40) - mergeB := strings.Repeat("e", 40) - groups, _ := json.Marshal(seat.GroupsAnswer{Groups: []seat.Group{{ID: "feat/x", State: "merging", Members: []seat.Member{ - {Repository: "novox/mesh-delivery", Number: 12, Head: head, State: "merged", Base: "main"}, {Repository: "novox/mesh-sdk", Number: 4, Head: headB, State: "merging", Base: "main"}}}}}) - b.answer("mesh-delivery.groups", string(groups)) - ch := heard(t, b) - landedOn(b, "novox/mesh-delivery", 12, "feat/x", head, merge) - landedOn(b, "novox/mesh-sdk", 4, "feat/x", headB, mergeB) - for _, m := range []git.PullMergedEvent{{Repository: "novox/mesh-delivery"}, {Repository: "novox/mesh-sdk"}} { - moveMain(t, b, m.Repository) - repo := strings.TrimPrefix(m.Repository, "novox/") - f, err := forgemsg.DecodeForge(next(t, ch, "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox."+repo+".merged")) - if err != nil || f.Group != "feat/x" || len(f.Members) != 2 || f.Members[1].Number != 4 { - t.Fatalf("%s's merged message: %+v %v, want the group feat/x with both members", repo, f, err) - } - } - end, err := forgemsg.DecodeForgeGroupEnd(next(t, ch, forgeSubject(forgemsg.ForgeGroupEndEvent))) - if err != nil || end.Group != "feat/x" || end.Base != "main" || len(end.Members) != 2 || end.Members[0].Merge != merge || end.Members[1].Merge != mergeB { - t.Errorf("the group's end: %+v %v", end, err) - } - refusedRead(t, b, "mesh-delivery-gate_merges") -} - -// Acceptance 53 (design 47 *What the gate owes the forge*): an owed act said on a seat's own stream owed is performed through -// the seat git and its outcome said as owed.ended; said twice it is performed once; one it cannot read is said undecodable; -// one said while the bridge is stopped is performed once after its restart; bridge_owed_again's ask is answered by the -// process; and its account reads neither the gate's nor the checker's state. func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { - b := startBed(t, `{"pulls":[]}`, nil) + b := startBed(t, strings.Repeat("1", 40)) ch := heard(t, b) ended := func() forgemsg.OwedEnded { t.Helper() @@ -836,7 +455,7 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { } return n } - gateOwed := gitfixture.Seat(t, seat.Seat, "events", "owed is said, a merge", "event:owed")[0] + gateOwed := gitfixture.Seat(t, seat.Seat, "events", "owed is said, a status", "event:owed")[0] subject := seat.SubjectOwed("novox~mesh-sdk", "178") for range 2 { if _, err := b.js.Publish(b.ctx, subject, gateOwed); err != nil { @@ -844,7 +463,7 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { } } if e := ended(); e.Outcome != forgemsg.OwedPerformed || e.Of != seat.Seat { - t.Errorf("the gate's merge: %+v, want performed", e) + t.Errorf("the gate's status: %+v, want performed", e) } if _, err := b.js.Publish(b.ctx, subject, []byte("{")); err != nil { t.Fatal(err) @@ -852,21 +471,24 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { if e := ended(); e.Outcome != forgemsg.OwedUndecodable { t.Errorf("an act it cannot read: %+v, want undecodable", e) } - if n := count("git.merge-pull"); n != 1 { + if n := count("git.status"); n != 1 { t.Errorf("an act said twice was performed %d times", n) } // Said while the bridge is stopped: performed once after its restart. - checkerOwed := gitfixture.Seat(t, checker.Seat, "events", "owed is said", "event:owed")[0] + other := map[string]any{} + _ = json.Unmarshal(gateOwed, &other) + other["id"] = "status.novox/mesh-sdk#178.aaaaaaaaaaaa.mesh/other" + otherOwed, _ := json.Marshal(other) b.restart(func() { - if _, err := b.js.Publish(b.ctx, checker.SubjectOwed("novox~mesh-sdk", "178"), checkerOwed); err != nil { + if _, err := b.js.Publish(b.ctx, subject, otherOwed); err != nil { t.Fatal(err) } }) - if e := ended(); e.Of != checker.Seat || e.Outcome != forgemsg.OwedPerformed { - t.Errorf("the checker's status after the restart: %+v, want performed", e) + if e := ended(); e.Of != seat.Seat || e.Outcome != forgemsg.OwedPerformed { + t.Errorf("the gate's status after the restart: %+v, want performed", e) } - if n := count("git.status"); n != 1 { - t.Errorf("the checker's status was performed %d times, want once", n) + if n := count("git.status"); n != 2 { + t.Errorf("the statuses were performed %d times, want twice", n) } // bridge_owed_again asks through the state owed-asks; the process performs the act again and answers there. var g struct { @@ -898,8 +520,8 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { } if a, err := groupkeys.DecodeOwedAsk(e.Value()); err == nil && a.Done() { answered = true - if a.Outcome != forgemsg.OwedPerformed || count("git.merge-pull") != 2 { - t.Errorf("bridge_owed_again: %+v, merge-pull asked %d times; want performed again", a, count("git.merge-pull")) + if a.Outcome != forgemsg.OwedPerformed || count("git.status") != 3 { + t.Errorf("bridge_owed_again: %+v, status asked %d times; want performed again", a, count("git.status")) } } case <-bound: @@ -907,52 +529,4 @@ func TestBridgePerformsWhatIsOwedOnce(t *testing.T) { } } refusedRead(t, b, "mesh-delivery-gate_owed") - refusedRead(t, b, "mesh-delivery-checker_owed") -} - -func sha256Sum(b []byte) []byte { s := sha256.Sum256(b); return s[:] } - -// Design 47 G §17, §383, §529, A-251 (FB2): the bridge started whole against the real bus says a move of a branch whose protection -// was removed as the finding branch-unprotected, into its bound state findings and its finding stream, and writes no message. -func TestBridgeSaysAnUnprotectedBranchAsAFinding(t *testing.T) { - b := startBed(t, `{"pulls":[]}`, nil) - b.answer("git.branch novox/mesh-delivery", `{"repository":"novox/mesh-delivery","branch":"main","head":"`+merge+`","protected":false}`) - moveMain(t, b, "novox/mesh-delivery") - kv, err := b.js.KeyValue(b.ctx, boundFindings) - if err != nil { - t.Fatal(err) - } - var e jetstream.KeyValueEntry - for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { - if e, err = kv.Get(b.ctx, "merge.novox/mesh-delivery/main.branch-unprotected"); err == nil { - break - } - } - if err != nil { - t.Fatalf("the finding is not in the bound state findings: %v", err) - } - var f struct{ Kind, Scope, ID, Observer string } - if err := json.Unmarshal(e.Value(), &f); err != nil || f.Kind != "branch-unprotected" || f.Observer != "mesh-delivery-forge-bridge" { - t.Errorf("the finding = %s %v", e.Value(), err) - } - // A-274: the finding is said under the bridge's binding finding-events, never on the old stream. - events, err := b.js.Stream(b.ctx, boundFindingEvents) - if err != nil { - t.Fatal(err) - } - for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(50 * time.Millisecond) { - if _, err = events.GetLastMsgForSubject(b.ctx, boundFindingEventsSubject+".finding-written.n1"); err == nil || time.Now().After(deadline) { - break - } - } - if err != nil { - t.Errorf("no finding-written under the binding finding-events: %v", err) - } - forge, err := b.js.Stream(b.ctx, "FORGE") - if err != nil { - t.Fatal(err) - } - if info, err := forge.Info(b.ctx); err != nil || info.State.Msgs != 1 { // the open message of its start only - t.Errorf("FORGE holds %+v %v: an unprotected branch's move writes no message", info, err) - } } diff --git a/modules/mesh-delivery-forge-bridge/manifest_test.go b/modules/mesh-delivery-forge-bridge/manifest_test.go index 9760f1bf..6420c530 100644 --- a/modules/mesh-delivery-forge-bridge/manifest_test.go +++ b/modules/mesh-delivery-forge-bridge/manifest_test.go @@ -131,8 +131,9 @@ func TestManifestDeclarations(t *testing.T) { // 1235/AC1 if want := []kept{{Name: "performed", Storage: "key-value", Template: "state", Options: map[string]any{"history": float64(1), "ttl-seconds": float64(604800)}}}; !reflect.DeepEqual(m.Requires, want) { t.Errorf("requires = %+v, want performed alone as %+v", m.Requires, want) } - // bridge_tags reads a package's tags for the builder's floor (design 51); the owed tools ask the bridge through owed-asks. - if want := []string{"bridge_owed", "bridge_owed_again", "bridge_owed_drop", "bridge_tags"}; !reflect.DeepEqual(sorted(m.Tools), want) { + // bridge_tags reads a package's tags for the builder's floor (design 51); bridge_heads reads the state heads (design 47 + // H-A-85); the owed tools ask the bridge through owed-asks. + if want := []string{"bridge_heads", "bridge_owed", "bridge_owed_again", "bridge_owed_drop", "bridge_tags"}; !reflect.DeepEqual(sorted(m.Tools), want) { t.Errorf("tools = %v, want %v", m.Tools, want) } // Design 47 H §764 (B3 AC1): the earlier model's names are in no file of the bridge but tests asserting their absence. diff --git a/modules/mesh-delivery-forge-bridge/module.json b/modules/mesh-delivery-forge-bridge/module.json index d4243381..c29a645c 100644 --- a/modules/mesh-delivery-forge-bridge/module.json +++ b/modules/mesh-delivery-forge-bridge/module.json @@ -19,6 +19,7 @@ ], "tools": [ "bridge_tags", + "bridge_heads", "bridge_owed", "bridge_owed_again", "bridge_owed_drop"