Files
mesh-delivery/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/integration_test.go
T
jschoubben 77b683c1c1 mesh-delivery-forge-bridge: performed keeps the outcome and the pull request, not the act
The state performed filled to 77% of its template's 64 MiB (19,530 keys, 2.6 KB each): the bridge kept every owed
event whole beside its outcome. performed's value is now the outcome said as owed.ended, with when, and the
repository and number the act names (groups.Performed); bridge_owed_again reads the act from the gate's stream owed
on its pull request's subject through an ordered consumer, the stream being the act's one copy; bridge_owed reads
one act or one pull request's acts, never the whole state, whose answer had grown past what the bus carries.

Builds: design 47 G §163, §162, §168; H-A-181, H-A-182
2026-11-20 19:38:34 +01:00

628 lines
25 KiB
Go

//go:build integration
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
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"
"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"
groupkeys "mesh-delivery-forge-bridge/internal/groups"
)
// busConf is the shape of the composed accounts file (the grants part's buscompose): one account with JetStream, the
// controller's user, and the bridge's own principal <node>.<module> 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 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_<seat>_<event>), and each seat's kept
// event also read through an ordered consumer of its own (mesh-grants heardGrants, A-233; bridge_owed_again, H-A-181); 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.<seat>.call.<verb>.<token> (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 }
accounts {
MESH {
jetstream: enabled
users = [
{ user: "ctl", password: "pw" }
{ user: "n1.mesh-delivery-forge-bridge", password: "pw"
permissions {
publish { allow: [
"$JS.API.CONSUMER.CREATE.KV_mesh-delivery-forge-bridge_heads.>"
"$JS.API.CONSUMER.DELETE.KV_mesh-delivery-forge-bridge_heads.>"
"$JS.API.DIRECT.GET.KV_mesh-delivery-forge-bridge_heads.>"
"$JS.API.STREAM.INFO.KV_mesh-delivery-forge-bridge_heads"
"$JS.FC.KV_mesh-delivery-forge-bridge_heads.>"
"$KV.mesh-delivery-forge-bridge_heads.>"
"$JS.API.CONSUMER.CREATE.KV_mod_mesh-delivery-forge-bridge_performed_b1.>"
"$JS.API.CONSUMER.DELETE.KV_mod_mesh-delivery-forge-bridge_performed_b1.>"
"$JS.API.DIRECT.GET.KV_mod_mesh-delivery-forge-bridge_performed_b1.>"
"$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.>"
"$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.>"
"$KV.mesh-delivery-forge-bridge_inputs.>"
"$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.>"
"$JS.API.DIRECT.GET.KV_mesh-delivery-forge-bridge_owed-asks.>"
"$JS.API.STREAM.INFO.KV_mesh-delivery-forge-bridge_owed-asks"
"$JS.FC.KV_mesh-delivery-forge-bridge_owed-asks.>"
"$KV.mesh-delivery-forge-bridge_owed-asks.>"
"$JS.ACK.EVENTS.n1_mesh-delivery-forge-bridge.>"
"$JS.API.CONSUMER.INFO.EVENTS.n1_mesh-delivery-forge-bridge"
"$JS.API.CONSUMER.MSG.NEXT.EVENTS.n1_mesh-delivery-forge-bridge"
"$JS.API.STREAM.INFO.SEAT_mesh-delivery_owed"
"$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.CONSUMER.CREATE.SEAT_mesh-delivery_owed"
"$JS.API.CONSUMER.CREATE.SEAT_mesh-delivery_owed.>"
"$JS.API.CONSUMER.MSG.NEXT.SEAT_mesh-delivery_owed.*"
"$JS.API.CONSUMER.INFO.SEAT_mesh-delivery_owed.*"
"$JS.API.CONSUMER.DELETE.SEAT_mesh-delivery_owed.*"
"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"
"mesh.seat.mesh-catalog.tool.registrations"
"mesh.seat.mesh-delivery.call.source.n1~mesh-delivery-forge-bridge"
"mesh.seat.mesh-delivery.tool.source"
"mesh.seat.git.call.branch.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.branch"
"$JS.API.STREAM.INFO.SEAT_git_branch-moved"
"$JS.ACK.SEAT_git_branch-moved.n1_mesh-delivery-forge-bridge.>"
"$JS.API.CONSUMER.INFO.SEAT_git_branch-moved.n1_mesh-delivery-forge-bridge"
"$JS.API.CONSUMER.MSG.NEXT.SEAT_git_branch-moved.n1_mesh-delivery-forge-bridge"
"mesh.seat.git.call.status.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.status"
"mesh.seat.git.call.comment.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.comment"
"mesh.seat.git.call.view.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.view"
"mesh.seat.git.call.note.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.note"
"mesh.seat.git.call.tags.n1~mesh-delivery-forge-bridge"
"mesh.seat.git.tool.tags"
"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.>"
"mesh.stream.mesh-delivery-forge-bridge.event.owed.ended"
] }
subscribe { allow: [
"_INBOX.n1.mesh-delivery-forge-bridge.>"
"mesh.assignment.n1.mesh-delivery-forge-bridge"
"mesh.mod.mesh-delivery-forge-bridge.call.>"
"mesh.mod.mesh-delivery-forge-bridge.tool.>"
] }
allow_responses: true
}
}
]
}
}
`
func startBus(t *testing.T) *server.Server {
t.Helper()
dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "b")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
conf := filepath.Join(dir, "bus.conf")
if err := os.WriteFile(conf, []byte(fmt.Sprintf(busConf, filepath.Join(dir, "js"))), 0o600); err != nil {
t.Fatal(err)
}
opts, err := server.ProcessConfigFile(conf)
if err != nil {
t.Fatal(err)
}
opts.NoLog, opts.NoSigs = true, true
srv, err := server.NewServer(opts)
if err != nil {
t.Fatal(err)
}
go srv.Start()
if !srv.ReadyForConnections(10 * time.Second) {
t.Fatal("the bus did not come up")
}
t.Cleanup(srv.Shutdown)
return srv
}
// 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
// answer sets the stand-in's answer to one verb of a seat (`<seat>.<verb>`, or `<seat>.<verb> <repository>`) from then on.
answer func(verb string, answer string)
// calls are the verbs the stand-in was called with, in order, as `<seat>.<verb> <input>`.
calls func() []string
// called is signalled after each call the stand-in answered, its answer chosen.
called <-chan struct{}
// restart stops the bridge, runs between, and starts it again on the same bus.
restart func(between func())
}
// 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"}`) }
// 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"
// catalog is the repository the stand-in registrations name, its branch main watched (the seat mesh-catalog's fixture).
const catalog = "novox/mesh-catalog"
// 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 {
t.Fatal(err)
}
t.Cleanup(ctl.Close)
js, err := jetstream.New(ctl)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
t.Cleanup(cancel)
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS", Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.*.event.>"}}); err != nil {
t.Fatal(err)
}
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)
}
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)
}
}
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)
}
}
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{"mesh.seat.mesh-catalog.event.registration-changed", "mesh.seat.mesh-delivery.event.source-moved"},
}); err != nil {
t.Fatal(err)
}
for name, subjects := range seats {
if _, err := js.CreateOrUpdateConsumer(ctx, name, acct.SeatEventConsumerConfig([]string{subjects}, false)); err != nil {
t.Fatal(err)
}
}
// The stand-in seats, answering on the caller-named subject and its plain fallback.
var mu sync.Mutex
answers := map[string]string{
"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"} {
answers["git."+verb] = string(gitfixture.Given(t, verb+" answers", "verb:"+verb+".answer"))
}
var called []string
signal := make(chan struct{}, 1)
for _, subject := range []string{"mesh.seat.*.call.*.*", "mesh.seat.*.tool.*"} {
sub, err := ctl.Subscribe(subject, func(m *nats.Msg) {
parts := strings.Split(m.Subject, ".")
verb := parts[2] + "." + parts[4]
mu.Lock()
called = append(called, verb+" "+string(m.Data))
answer := answers[verb]
var in struct{ Repository string }
if json.Unmarshal(m.Data, &in) == nil && answers[verb+" "+in.Repository] != "" {
answer = answers[verb+" "+in.Repository]
}
mu.Unlock()
select {
case signal <- struct{}{}:
default:
}
if answer == "" {
answer = `{"error":"the stand-in holds no answer"}`
}
_ = m.Respond(answerOf(answer))
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = sub.Unsubscribe() })
}
if err := ctl.Flush(); err != nil {
t.Fatal(err)
}
broker := filepath.Join(t.TempDir(), "broker")
cred, _ := json.Marshal(process.Account{URL: srv.ClientURL(), Node: "n1", Module: "mesh-delivery-forge-bridge", User: "n1.mesh-delivery-forge-bridge", Password: "pw"})
if err := os.WriteFile(broker, cred, 0o600); err != nil {
t.Fatal(err)
}
env := map[string]string{"MESH_BROKER_FILE": broker}
done := make(chan error, 1)
var stop context.CancelFunc
start := func() {
var runCtx context.Context
runCtx, stop = context.WithCancel(ctx)
go func() { done <- run(runCtx, func(k string) string { return env[k] }, io.Discard) }()
}
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, answer: set, called: signal,
calls: func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), called...) },
restart: func(between func()) {
stop()
<-done
between()
start()
}}
}
// callsOf is how many calls of the stand-in start with prefix.
func callsOf(b *bed, prefix string) int {
n := 0
for _, c := range b.calls() {
if strings.HasPrefix(c, prefix) {
n++
}
}
return n
}
// calledTimes waits until the stand-in answered n calls starting with prefix: a call's answer is chosen when it is counted.
func calledTimes(t *testing.T, b *bed, prefix string, n int) {
t.Helper()
bound := time.After(20 * time.Second)
for callsOf(b, prefix) < n {
select {
case <-b.called:
case <-bound:
t.Fatalf("%d calls %s within 20 s, want %d", callsOf(b, prefix), prefix, n)
}
}
}
// 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+`}`)
}
// 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: catalog, Branch: branch, Head: strings.Repeat("f", 40)})
if _, err := b.js.Publish(b.ctx, git.SubjectBranchMoved, ev); err != nil {
t.Fatal(err)
}
}
// 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()
kv, err := b.js.KeyValue(b.ctx, headsBucket(forgeBridgeModule()))
if err != nil {
t.Fatal(err)
}
w, err := kv.Watch(b.ctx, "branch.novox.mesh-catalog.main")
if 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
}
case <-bound:
t.Fatalf("the state heads does not hold %s within 20 s", head)
}
}
}
// 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()
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)
}
}
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)
branchReads := callsOf(b, "git.branch ")
b.restart(func() {}) // at the head held: nothing
// The head moves only once the start has read the head held, so that read is not the move's (§739: start true).
calledTimes(t, b, "git.branch ", branchReads+1)
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)
}
}
// One read per start and per move of main: the first view's registrations, said after a start, adopt no branch (§532).
if n := callsOf(b, "git.branch "); n != 3+4 {
t.Errorf("the bridge read the head %d times, want 7: once at each of 3 starts and once per move of main (4)", n)
}
held(t, b, h5) // kept after the message is written, so watched for, not read at once
}
func heard(t *testing.T, b *bed) <-chan *nats.Msg {
t.Helper()
ch := make(chan *nats.Msg, 64)
sub, err := b.ctl.ChanSubscribe("mesh.stream.mesh-delivery-forge-bridge.event.>", ch)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = sub.Unsubscribe() })
if err := b.ctl.Flush(); err != nil {
t.Fatal(err)
}
return ch
}
// next is the next message heard on subject within 20 s; the others are passed by.
func next(t *testing.T, ch <-chan *nats.Msg, subject string) []byte {
t.Helper()
return nextWithin(t, ch, subject, 20*time.Second)
}
// nextWithin is next within bound.
func nextWithin(t *testing.T, ch <-chan *nats.Msg, subject string, within time.Duration) []byte {
t.Helper()
bound := time.After(within)
for {
select {
case m := <-ch:
if m.Subject == subject {
return m.Data
}
case <-bound:
t.Fatalf("nothing on %s within %s", subject, within)
return nil
}
}
}
// refusedRead says the bridge's account cannot read the bucket: a key-value read of another module's state is refused.
func refusedRead(t *testing.T, b *bed, bucket string) {
t.Helper()
if _, err := b.js.CreateKeyValue(b.ctx, jetstream.KeyValueConfig{Bucket: bucket}); err != nil {
t.Fatal(err)
}
nc, err := nats.Connect(b.srv.ClientURL(), nats.UserInfo("n1.mesh-delivery-forge-bridge", "pw"))
if err != nil {
t.Fatal(err)
}
defer nc.Close()
js, _ := jetstream.New(nc)
ctx, cancel := context.WithTimeout(b.ctx, 2*time.Second)
defer cancel()
if kv, err := js.KeyValue(ctx, bucket); err == nil {
if _, err := kv.Get(ctx, "any"); err == nil || errors.Is(err, jetstream.ErrKeyNotFound) {
t.Errorf("the bridge's account reads %s", bucket)
}
}
}
// 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 TestBridgePerformsWhatIsOwedOnce(t *testing.T) {
b := startBed(t, strings.Repeat("1", 40))
ch := heard(t, b)
ended := func() forgemsg.OwedEnded {
t.Helper()
e, err := forgemsg.DecodeOwedEnded(next(t, ch, forgeSubject(forgemsg.OwedEndedEvent)))
if err != nil {
t.Fatal(err)
}
return e
}
count := func(verb string) int {
n := 0
for _, c := range b.calls() {
if strings.HasPrefix(c, verb+" ") {
n++
}
}
return n
}
// The bridge's acknowledgements on its durable of the stream owed, heard as the bus hears them.
acks := make(chan *nats.Msg, 16)
ackSub, err := b.ctl.ChanSubscribe("$JS.ACK."+seat.StreamOwed+".n1_mesh-delivery-forge-bridge.>", acks)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ackSub.Unsubscribe() })
if err := b.ctl.Flush(); err != nil {
t.Fatal(err)
}
acked := func(n int) {
t.Helper()
bound := time.After(20 * time.Second)
for n > 0 {
select {
case m := <-acks:
if string(m.Data) == "+ACK" {
n--
}
case <-bound:
t.Fatalf("the bridge did not acknowledge what it heard on %s within 20 s", seat.StreamOwed)
}
}
}
gateOwed := gitfixture.Seat(t, seat.Seat, "events", "owed is said, a status", "event:owed")[0]
// On the pull request's subject as the gate says it (its repository escaped as a key part), where bridge_owed_again
// reads the act again (H-A-181).
subject := seat.SubjectOwed(keys.EscapeName("novox/mesh-sdk"), "178")
for range 2 {
if _, err := b.js.Publish(b.ctx, subject, gateOwed); err != nil {
t.Fatal(err)
}
}
if e := ended(); e.Outcome != forgemsg.OwedPerformed || e.Of != seat.Seat {
t.Errorf("the gate's status: %+v, want performed", e)
}
if _, err := b.js.Publish(b.ctx, subject, []byte("{")); err != nil {
t.Fatal(err)
}
if e := ended(); e.Outcome != forgemsg.OwedUndecodable {
t.Errorf("an act it cannot read: %+v, want undecodable", e)
}
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.
other := map[string]any{}
_ = json.Unmarshal(gateOwed, &other)
other["id"] = "status.novox/mesh-sdk#178.aaaaaaaaaaaa.mesh/other"
otherOwed, _ := json.Marshal(other)
// The three acts heard are acknowledged before the stop: one stopped while its outcome is on its way is heard again
// after the start, by design, which is not what this part of the test is about.
acked(3)
// An act said while the bridge stops may be handed to the stopped bridge's pull before the bus has seen it go: the bus
// hands it again after its consumer's acknowledgement wait, its redelivery the only clock (H-A-48).
owedConsumer, err := b.js.Consumer(b.ctx, seat.StreamOwed, "n1_mesh-delivery-forge-bridge")
if err != nil {
t.Fatal(err)
}
ackWait := owedConsumer.CachedInfo().Config.AckWait
b.restart(func() {
if _, err := b.js.Publish(b.ctx, subject, otherOwed); err != nil {
t.Fatal(err)
}
})
afterRestart, err := forgemsg.DecodeOwedEnded(nextWithin(t, ch, forgeSubject(forgemsg.OwedEndedEvent), ackWait+20*time.Second))
if err != nil {
t.Fatal(err)
}
if e := afterRestart; 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 != 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 {
ID string `json:"id"`
}
_ = json.Unmarshal(gateOwed, &g)
key, value, err := groupkeys.NewOwedAsk(groupkeys.OwedAgain, seat.Seat, g.ID, "a test", "lead@n1", time.Now())
if err != nil {
t.Fatal(err)
}
asks, err := b.js.KeyValue(b.ctx, groupkeys.OwedAsksBucket(forgeBridgeModule()))
if err != nil {
t.Fatal(err)
}
w, err := asks.Watch(b.ctx, key)
if err != nil {
t.Fatal(err)
}
defer w.Stop()
if _, err := asks.Put(b.ctx, key, value); err != nil {
t.Fatal(err)
}
bound := time.After(20 * time.Second)
for answered := false; !answered; {
select {
case e := <-w.Updates():
if e == nil {
continue
}
if a, err := groupkeys.DecodeOwedAsk(e.Value()); err == nil && a.Done() {
answered = true
if a.Outcome != forgemsg.OwedPerformed || count("git.status") != 3 {
t.Errorf("bridge_owed_again: %+v, status asked %d times; want performed again, read from the gate's stream owed", a, count("git.status"))
}
}
case <-bound:
t.Fatal("bridge_owed_again was not answered within 20 s")
}
}
// performed keeps the outcome, when and the pull request, never the act (§163, H-A-181, H-A-182).
kept, err := b.js.KeyValue(b.ctx, boundPerformed)
if err != nil {
t.Fatal(err)
}
if e, err := kept.Get(b.ctx, performedKey(seat.Seat, g.ID)); err != nil {
t.Errorf("performed of %s: %v", g.ID, err)
} else if fields := (map[string]json.RawMessage{}); json.Unmarshal(e.Value(), &fields) != nil || len(fields) != 3 || fields["owed"] != nil {
t.Errorf("performed of %s keeps %s, want the outcome, when and the pull request alone", g.ID, e.Value())
}
refusedRead(t, b, "mesh-delivery-gate_owed")
}