FB1, FB9, FB10: the forge bridge writes one message per move of every watched branch

The bridge watches the registrations' branches by origin (a first view of registrations, then registration-changed),
before the first registration the gate's source's (source-moved); no branch is named in its code, Trunk goes. Every
move is heard on the seat git's branch-moved through the bridge's durable on SEAT_git_branch-moved, its head read by
the seat's verb branch, never the event's: merged with its pull request and `base` (the watched branch) when the
seat's pull names the head a pull request's merge, else `pushed` with branch, head and `before`, both with the
take-in inputs at the head. The last head written per watched branch is kept in the state heads under
branch.<owner>.<name>.<escaped branch>, so a move heard twice writes once, and each watched branch's head is read at
the start and when a branch is registered. A move of an unprotected branch writes nothing. pull.merged into a watched
branch writes nothing (its message is the move's); the forge-made merge's trunk filter goes.

Builds: design 47 G §4, §7, §11, §20, §41, §507, §509, §532, §714, A-227, A-236

Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
This commit is contained in:
2026-11-12 09:15:04 +01:00
parent dcb7ba016c
commit dce4d01a58
22 changed files with 819 additions and 241 deletions
@@ -131,7 +131,7 @@ func MergedOf(of []seat.Group, repository, merge string, number int, trees bridg
if err != nil {
return nil, fmt.Errorf("the forge gives no merged pull request of %s with the commit %s: %w", repository, merge, err)
}
msg, err := bridge.MergedMessage(owner, repo, fp.Number, fp.Branch, fp.Head, merge, trees, files)
msg, err := bridge.MergedMessage(owner, repo, fp.Number, fp.Branch, fp.Head, merge, fp.Base, trees, files)
if err != nil {
return nil, fmt.Errorf("the merged message of %s at %s cannot be built: %w", repository, merge, err)
}
@@ -135,8 +135,7 @@ func TestTheBridgeToolsReadTheGroupsAndAskTheEndAgain(t *testing.T) {
return nil, bridge.ErrNotFound
}
published := func(repo string, number int, head, branch, merge string) forgemsg.Forge {
body, _ := json.Marshal(git.PullMergedEvent{Repository: "novox/" + repo, Number: int64(number), Branch: branch, Head: head, Base: "main", MergeCommit: merge})
msg, err := bridge.Convert(bridge.MergedSubject, body, trees, files)
msg, err := bridge.MergedMessage("novox", repo, number, branch, head, merge, "main", trees, files)
if err != nil {
t.Fatal(err)
}
@@ -172,8 +171,13 @@ func TestTheBridgeToolsReadTheGroupsAndAskTheEndAgain(t *testing.T) {
api: forgeAnswers(t, 9, "", "merged", "fix/x", h2, c1, "main"), fail: "not at " + c2},
{name: "a forge pull request not merged", repository: "novox/a", merge: c2, number: 9,
api: forgeAnswers(t, 9, "", "open", "fix/x", h2, "", "main"), fail: "not merged"},
// design 47 G §714: no filter to the trunk alone; the merged message names the branch it was merged into.
{name: "a forge pull request merged into another branch", repository: "novox/a", merge: c2, number: 9,
api: forgeAnswers(t, 9, "", "merged", "fix/x", h2, c2, "dev"), fail: "not the trunk"},
api: forgeAnswers(t, 9, "", "merged", "fix/x", h2, c2, "dev"), want: func() forgemsg.Forge {
f := published("a", 9, h2, "fix/x", c2)
f.Base = "dev"
return f
}()},
{name: "a forge pull request with no head branch", repository: "novox/a", merge: c2, number: 9,
api: forgeAnswers(t, 9, "", "merged", "", h2, c2, "main"), fail: "no head branch"},
{name: "a seat answer that says an error", repository: "novox/a", merge: c2, number: 9,
@@ -97,6 +97,16 @@ accounts {
"$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"
"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"
@@ -232,7 +242,7 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context,
}
// Each seat's own stream owed, as its contract keeps it (Stream<E>, SEAT_<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} {
for name, subjects := range map[string]string{seat.StreamOwed: seat.SubjectOwedAll, checker.StreamOwed: checker.SubjectOwedAll, git.StreamBranchMoved: git.SubjectBranchMoved} {
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)
@@ -251,11 +261,12 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context,
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},
FilterSubjects: []string{git.SubjectPullUpdated, git.SubjectPullMerged, git.SubjectPullClosed, git.SubjectForgeDelete,
"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} {
for name, subjects := range map[string]string{seat.StreamOwed: seat.SubjectOwedAll, checker.StreamOwed: checker.SubjectOwedAll, git.StreamBranchMoved: git.SubjectBranchMoved} {
if _, err := js.CreateOrUpdateConsumer(ctx, name, acct.SeatEventConsumerConfig([]string{subjects}, false)); err != nil {
t.Fatal(err)
}
@@ -266,6 +277,9 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context,
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 + `"}}`,
}
for _, verb := range []string{"status", "comment", "view", "note", "merge-pull"} {
@@ -280,6 +294,10 @@ func startBed(t *testing.T, openReply string, prepare func(ctx context.Context,
mu.Lock()
called = append(called, verb+" "+string(m.Data))
answer, files := answers[verb], filesOf
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)
}
mu.Unlock()
if verb == "git.file" {
var in git.FileInput
@@ -326,6 +344,23 @@ 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))
}
// 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) {
t.Helper()
ev, _ := json.Marshal(git.BranchMovedEvent{Repository: repository, Branch: "main", 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":[]}`)
@@ -452,12 +487,9 @@ func TestBridgeWritesMergedMessage(t *testing.T) { // 1236/AC4, 1448/AC5
}
return "", false
})
// pull.merged as the seat git says it (its contract's PullMergedEvent).
ev, _ := json.Marshal(git.PullMergedEvent{Repository: "novox/mesh-delivery", Number: 12, Title: "t", Head: head, Branch: "feat/x", Base: "main",
MergeCommit: merge, Change: &git.Change{Paths: []string{"modules/a/x.go"}, ModuleDirs: []string{"modules/a"}}})
if _, err := js.Publish(ctx, git.SubjectPullMerged, ev); err != nil {
t.Fatal(err)
}
// 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 {
@@ -482,7 +514,7 @@ func TestBridgeWritesMergedMessage(t *testing.T) { // 1236/AC4, 1448/AC5
t.Fatal(err)
}
want := forgemsg.Forge{V: keys.Version, Kind: "merged", Repository: "novox/mesh-delivery", Branch: "feat/x", Number: 12, Head: head,
Merge: merge, Root: "r0", Trees: map[string]string{"": "t0", "modules/a": "t1"},
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))}}}
@@ -499,7 +531,7 @@ func TestBridgeWritesMergedMessage(t *testing.T) { // 1236/AC4, 1448/AC5
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, "EVENTS", "n1_mesh-delivery-forge-bridge")
cons, err := js.Consumer(ctx, git.StreamBranchMoved, "n1_mesh-delivery-forge-bridge")
if err != nil {
t.Fatal(err)
}
@@ -725,14 +757,10 @@ func TestBridgeSaysAGroupFromTheSeatsGroups(t *testing.T) { // 1585, ADR 0633 §
{Repository: "novox/mesh-delivery", Number: 12, Head: head, State: "merged"}, {Repository: "novox/mesh-sdk", Number: 4, Head: headB, State: "merging"}}}}})
b.answer("mesh-delivery.groups", string(groups))
ch := heard(t, b)
for _, m := range []git.PullMergedEvent{
{Repository: "novox/mesh-delivery", Number: 12, Head: head, Branch: "feat/x", Base: "main", MergeCommit: merge, Change: &git.Change{Paths: []string{"modules/a/x.go"}, ModuleDirs: []string{"modules/a"}}},
{Repository: "novox/mesh-sdk", Number: 4, Head: headB, Branch: "feat/x", Base: "main", MergeCommit: mergeB, Change: &git.Change{Paths: []string{"go/x.go"}}},
} {
ev, _ := json.Marshal(m)
if _, err := b.js.Publish(b.ctx, git.SubjectPullMerged, ev); err != nil {
t.Fatal(err)
}
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 {
@@ -6,6 +6,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -17,14 +18,17 @@ import (
"time"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/views"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
git "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
mcseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
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-delivery/modules/mesh-delivery-sdk/sourcebranches"
"mesh-delivery-forge-bridge/internal/bridge"
groupkeys "mesh-delivery-forge-bridge/internal/groups"
@@ -68,17 +72,11 @@ type publisher interface {
Publish(ctx context.Context, subject string, payload []byte, opts ...jetstream.PublishOpt) (*jetstream.PubAck, error)
}
// handle turns one event into its message on FORGE and acknowledges it. An event it cannot read is terminated, never
// redelivered, and the log names its subject and why. A message it could not write stays unacknowledged: the server
// delivers it again (the server's ack wait is the only clock).
func handle(ctx context.Context, m delivered, pub publisher, trees bridge.Trees, files bridge.Files, kept bridge.Kept, logger *log.Logger) {
handleGrouped(ctx, m, pub, trees, files, kept, nil, logger)
}
// handleGrouped is handle; a merged message of a delivery group's member names its group (g, ADR 0633 §4; nil names
// none), and the member's merged message written may end the group.
func handleGrouped(ctx context.Context, m delivered, pub publisher, trees bridge.Trees, files bridge.Files, kept bridge.Kept, g *grouper, logger *log.Logger) {
msg, err := bridge.ConvertKept(m.Subject(), m.Data(), trees, files, kept)
// handle turns one pull request event into its message on FORGE and acknowledges it (bridge.Convert). An event it cannot
// read is terminated, never redelivered, and the log names its subject and why. A message it could not write stays
// unacknowledged: the server delivers it again (the server's ack wait is the only clock).
func handle(ctx context.Context, m delivered, pub publisher, files bridge.Files, watched bridge.Watching, logger *log.Logger) {
msg, err := bridge.Convert(m.Subject(), m.Data(), files, watched)
switch {
case errors.Is(err, bridge.ErrRetry):
logger.Printf("%v; heard again in %s", err, retryDelay)
@@ -98,18 +96,10 @@ func handleGrouped(ctx context.Context, m delivered, pub publisher, trees bridge
if id := m.Headers().Get("x-event-id"); id != "" {
opts = append(opts, jetstream.WithMsgID(id))
}
var member forgemsg.Forge
grouped := false
if g != nil {
msg.Data, member, grouped = g.member(ctx, msg.Data)
}
if _, err := pub.Publish(ctx, forgeSubject(msg.Event), msg.Data, opts...); err != nil {
logger.Printf("%s: %s could not be written on FORGE, left for redelivery: %v", m.Subject(), msg.Event, err)
return
}
if grouped {
g.published(ctx, member)
}
if msg.Said != "" {
logger.Printf("%s: %s", m.Subject(), msg.Said)
}
@@ -147,7 +137,11 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
heads := kvHeads{kv}
// Everything written on FORGE, an event's and a sync's, keeps the head in the bucket.
rec := &recorder{pub: js, heads: heads, logger: logger}
said := func(ctx context.Context) error { return syncOpen(ctx, call, rec, heads, &turn, logger) }
// The branches the bridge watches (design 47 G §4, §507, §532): the registrations' first view and then
// registration-changed; before the first registration, the gate's source's branches and its source-moved. Nothing is
// written before both first views are held (ready).
watched := &bridge.Watched{}
said := func(ctx context.Context) error { return syncOpen(ctx, call, rec, heads, watched, &turn, logger) }
// The module's one pull of its durable consumer on the shared events stream is its event hub (below).
hub := process.NewEventHub(logger.Printf)
// The state performed is a `requires` entry: opened by its binding, asked of the seat mesh-broker's show at this start
@@ -176,9 +170,91 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
}
}()
}
keptCall := keptCallOf(ctx, call)
reader := &views.ProcessReader{Module: forgeBridgeModule, Call: keptCall, Logf: logger.Printf, Hub: hub}
src := sourcebranches.New(sourcebranches.Call(keptCall))
var regs *meshcatalogclient.Registrations
var mv *mover
recompute := func() {
if regs != nil {
watched.Set(registeredOf(regs.All()), unescaped(src.Branches()))
}
}
started := make(chan struct{}) // closed once the watched branches are read and the open pull requests said
regs, _, err = meshcatalogclient.WireRegistrationsProcess(reader, keptCall, func(mcseat.Registration, bool) {
recompute()
select {
case <-started: // a branch registered while the bridge runs is adopted: its head read (§532)
go mv.readHeads(ctx)
default:
}
})
if err != nil {
return err
}
src.Follower.Changed = func(string, json.RawMessage, bool, time.Time) { recompute() }
if _, err := reader.Adopt(src.Follower, sourcebranches.Seat, sourcebranches.EventSourceMoved, src.Hear); err != nil {
return err
}
reader.Start(ctx, js, cred, nil)
// What a merge read of each module directory, by its tree (issue 1126): a merge reads only the directories it changed.
inputs := newKept(process.OptionalBucket(ctx, js, inputsBucket, "a merge's module directories are kept in memory only, so the first merge after a start reads every one", logger.Printf), logger)
mv = &mover{call: call, pub: rec, heads: heads, watched: watched, inputs: inputs, groups: groups, turn: &turn, logger: logger}
// The hub's handler of the forge's events, for every event its consumes filter lets through. Essential: the forge's
// events are what the bridge carries. The forge's events are the seat git's (novox/hq design 47 *The seat `git`*),
// whichever module holds it.
if err := hub.Handle("mesh.seat."+git.Seat+".event.>", func(m jetstream.Msg) {
select {
case <-started:
case <-ctx.Done():
return
}
hear(&turn, func() {
// Bounded: the turn is held, and no sync or other event goes on without it.
hctx, cancel := context.WithTimeout(ctx, syncDeadline)
defer cancel()
handle(hctx, m, rec, filesVia(hctx, call), watched, logger)
})
}); err != nil {
return err
}
if err := hub.Start(ctx, js, cred); err != nil {
return fmt.Errorf("%w: the bridge hears no forge event without it, so it stops; where the bus refused it or did not answer, this module's consumes (made by the controller with its grant) have not reached the bus yet", err)
}
defer hub.Stop()
// Every move of a branch, heard on the seat git's stream branch-moved through this module's durable there (§11), so a
// move said while the bridge was stopped is heard at its start. Essential: every merge and push reaches the stream so.
moves, err := cred.HearSeatEvents(ctx, js, git.StreamBranchMoved, func(m jetstream.Msg) {
select {
case <-started:
case <-ctx.Done():
return
}
hctx, cancel := context.WithTimeout(ctx, syncDeadline)
defer cancel()
mv.hear(hctx, m)
}, logger.Printf)
if err != nil {
return fmt.Errorf("the seat git's branch-moved cannot be heard, so no merge or push reaches the forge stream: %w", err)
}
defer moves.Stop()
select {
case <-regs.Ready():
case <-ctx.Done():
return nil
}
if len(regs.All()) == 0 {
select {
case <-src.Follower.Ready():
case <-ctx.Done():
return nil
}
}
recompute()
if err := said(ctx); err != nil {
return err
}
close(started)
// What the gate and the checker say they owe, each on its seat's own stream owed through this module's durable there
// (made from its consumes). A stream not there yet is said, and the bridge goes on: its other work does not wait on the
// gate, and what was said meanwhile is caught up from the groups at the next start.
@@ -217,25 +293,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
logger.Printf("%d acts owed to the forge, said while the bridge was away, performed from the groups", n)
}
go onReconnect(ctx, again, said, logger)
// What a merge read of each module directory, by its tree (issue 1126): a merge reads only the directories it changed.
inputs := newKept(process.OptionalBucket(ctx, js, inputsBucket, "a merge's module directories are kept in memory only, so the first merge after a start reads every one", logger.Printf), logger)
// The hub's handler of the forge's events, for every event its consumes filter lets through. Essential: the forge's
// events are what the bridge carries.
// The forge's events are the seat git's (novox/hq design 47 *The seat `git`*), whichever module holds it.
if err := hub.Handle("mesh.seat."+git.Seat+".event.>", func(m jetstream.Msg) {
hear(&turn, func() {
// Bounded: the turn is held, and no sync or other event goes on without it.
hctx, cancel := context.WithTimeout(ctx, syncDeadline)
defer cancel()
handleGrouped(hctx, m, rec, treesVia(hctx, call), filesVia(hctx, call), inputs, groups, logger)
})
}); err != nil {
return err
}
if err := hub.Start(ctx, js, cred); err != nil {
return fmt.Errorf("%w: the bridge hears no forge event without it, so it stops; where the bus refused it or did not answer, this module's consumes (made by the controller with its grant) have not reached the bus yet", err)
}
defer hub.Stop()
// Each watched branch's head, read at the start (§11): a head missed while the bridge was stopped is written now.
mv.readHeads(ctx)
<-ctx.Done()
return nil
}
@@ -79,7 +79,7 @@ func TestReadableEventIsWrittenOnForgeAndAcked(t *testing.T) { // 1235/AC2 (unit
})
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullUpdated, data: body(nil)}, &fakePub{}
handle(context.Background(), m, pub, nil, someFiles, nil, log.New(&logs, "", 0))
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if len(pub.subjects) != 1 || pub.subjects[0] != "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.pull" {
t.Fatalf("published on %v", pub.subjects)
}
@@ -95,7 +95,7 @@ func TestReadableEventIsWrittenOnForgeAndAcked(t *testing.T) { // 1235/AC2 (unit
func TestUnreadableEventIsTerminatedAndLogged(t *testing.T) { // 1235/AC5
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullUpdated, data: body(map[string]any{"head_sha": "short"})}, &fakePub{}
handle(context.Background(), m, pub, nil, someFiles, nil, log.New(&logs, "", 0))
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if len(pub.subjects) != 0 {
t.Errorf("a message was written: %v", pub.subjects)
}
@@ -109,7 +109,7 @@ func TestUnreadableEventIsTerminatedAndLogged(t *testing.T) { // 1235/AC5
// from a test of its own, for the test budget.
logs.Reset()
m, pub = &fakeMsg{subject: git.SubjectPullUpdated, data: body(nil)}, &fakePub{err: errors.New("no stream")}
handle(context.Background(), m, pub, nil, someFiles, nil, log.New(&logs, "", 0))
handle(context.Background(), m, pub, someFiles, watchesMain(), log.New(&logs, "", 0))
if m.acked != 0 || m.termd != 0 {
t.Errorf("acked %d terminated %d, want neither", m.acked, m.termd)
}
@@ -118,55 +118,93 @@ func TestUnreadableEventIsTerminatedAndLogged(t *testing.T) { // 1235/AC5
}
}
// mergedEvent is the seat git's pull.merged.
func mergedEvent() []byte {
b, _ := json.Marshal(map[string]any{"repository": "novox/mesh-delivery", "number": 12, "branch": "feat/x", "head": head,
"base": "main", "merge-commit": "89abcdef0123456789abcdef0123456789abcdef"})
// watchesMain watches main of every repository, as the gate's source names it before the first registration.
func watchesMain() *bridge.Watched {
w := &bridge.Watched{}
w.Set(nil, []string{"main"})
return w
}
// movedEvent is the seat git's branch-moved of main of novox/mesh-delivery, naming a head the bridge never takes.
func movedEvent(branch string) []byte {
b, _ := json.Marshal(map[string]any{"repository": "novox/mesh-delivery", "branch": branch, "head": strings.Repeat("f", 40)})
return b
}
const landed = "89abcdef0123456789abcdef0123456789abcdef"
// moveCall answers the seat git as a forge whose main of novox/mesh-delivery is protected at landed, merged there by #12;
// trees answers trees, every other verb answers err.
func moveCall(trees json.RawMessage, err error, keys *[]string, args *[]any, mu *sync.Mutex) caller {
return func(_ context.Context, key string, body any) (json.RawMessage, error) {
mu.Lock()
*keys, *args = append(*keys, key), append(*args, body)
mu.Unlock()
switch key {
case "seat:git.branch":
return json.RawMessage(`{"repository":"novox/mesh-delivery","branch":"main","head":"` + landed + `","protected":true}`), nil
case "seat:git.pull":
return json.RawMessage(`{"pull":{"repository":"novox/mesh-delivery","number":12,"branch":"feat/x","head":"` + head + `","base":"main","state":"merged","merge-commit":"` + landed + `"}}`), nil
case "seat:git.trees":
if trees != nil {
return trees, nil
}
}
return nil, err
}
}
func newMover(call caller, pub publisher, heads headStore, logs *bytes.Buffer) *mover {
return &mover{call: call, pub: pub, heads: heads, watched: watchesMain(), turn: &sync.Mutex{}, logger: log.New(logs, "", 0)}
}
func TestTreesRefusedLeavesTheEventForTenSecondsAndLogs(t *testing.T) { // 1236/AC3
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullMerged, data: mergedEvent()}, &fakePub{}
call := func(context.Context, string, any) (json.RawMessage, error) {
return nil, errors.New("the tree listing of novox/mesh-delivery was cut")
}
handle(context.Background(), m, pub, treesVia(context.Background(), call), filesVia(context.Background(), call), nil, log.New(&logs, "", 0))
if len(pub.subjects) != 0 {
var keys []string
var args []any
var mu sync.Mutex
m, pub, heads := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakePub{}, newHeads()
newMover(moveCall(nil, errors.New("the tree listing of novox/mesh-delivery was cut"), &keys, &args, &mu), pub, heads, &logs).hear(context.Background(), m)
if len(pub.subjects) != 0 || heads.get("branch.novox.mesh-delivery.main") != "" {
t.Errorf("a message was written: %v", pub.subjects)
}
if m.acked != 0 || m.termd != 0 || len(m.nak) != 1 || m.nak[0] < 10*time.Second {
t.Errorf("acked %d terminated %d naks %v, want one nak of at least 10 s", m.acked, m.termd, m.nak)
}
for _, w := range []string{"novox/mesh-delivery", "89abcdef0123456789abcdef0123456789abcdef", "the tree listing of novox/mesh-delivery was cut"} {
for _, w := range []string{"novox/mesh-delivery", landed, "the tree listing of novox/mesh-delivery was cut"} {
if !strings.Contains(logs.String(), w) {
t.Errorf("log %q does not name %q", logs.String(), w)
}
}
}
func TestMergeCallsTheToolOnceAndWritesTheMergedMessage(t *testing.T) { // 1236/AC1; design 47 *The seat git* (verbs trees, file)
// 1236/AC1; design 47 *The seat git* (verbs trees, file); design 47 G §11, §20, §509 (FB1, FB10): a move of a watched branch
// is taken by the seat's verb branch, never the event's head, written once as merged with its pull request and base, and
// its head kept, so the same move heard again writes nothing; a move of a branch not watched writes nothing.
func TestMergeCallsTheToolOnceAndWritesTheMergedMessage(t *testing.T) {
var logs bytes.Buffer
m, pub := &fakeMsg{subject: git.SubjectPullMerged, data: mergedEvent()}, &fakePub{}
var keys []string
var args []any
var mu sync.Mutex // the files are asked for concurrently (issue 1458)
trees := gitfixture.Given(t, "trees answers", "verb:trees.answer") // root ddd…, "" ddd…, contracts eee…
call := moveCall(trees, nil, &keys, &args, &mu)
file := gitfixture.Given(t, "file answers", "verb:file.answer")
call := func(_ context.Context, key string, body any) (json.RawMessage, error) {
mu.Lock()
keys, args = append(keys, key), append(args, body)
mu.Unlock()
files := func(ctx context.Context, key string, body any) (json.RawMessage, error) {
if key == "seat:git.file" { // the manifests, 1448; the trees are what this test is about
mu.Lock()
keys = append(keys, key)
mu.Unlock()
return file, nil
}
return trees, nil
return call(ctx, key, body)
}
handle(context.Background(), m, pub, treesVia(context.Background(), call), filesVia(context.Background(), call), nil, log.New(&logs, "", 0))
if len(keys) == 0 || keys[0] != "seat:git.trees" || slices.Index(keys[1:], "seat:git.trees") >= 0 {
t.Fatalf("calls %v, want the trees once and first", keys)
m, pub, heads := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakePub{}, newHeads()
mv := newMover(files, pub, heads, &logs)
mv.hear(context.Background(), m)
if len(keys) < 3 || keys[0] != "seat:git.branch" || keys[1] != "seat:git.pull" || keys[2] != "seat:git.trees" || slices.Index(keys[3:], "seat:git.trees") >= 0 {
t.Fatalf("calls %v, want the branch, its pull, then the trees once", keys)
}
if got, _ := json.Marshal(args[0]); !sameJSON(got, []byte(`{"repository":"novox/mesh-delivery","commit":"89abcdef0123456789abcdef0123456789abcdef"}`)) {
if got, _ := json.Marshal(args[2]); !sameJSON(got, []byte(`{"repository":"novox/mesh-delivery","commit":"`+landed+`"}`)) {
t.Errorf("arguments %s", got)
}
if len(pub.subjects) != 1 || pub.subjects[0] != "mesh.stream.mesh-delivery-forge-bridge.event.forge.novox.mesh-delivery.merged" {
@@ -174,11 +212,17 @@ func TestMergeCallsTheToolOnceAndWritesTheMergedMessage(t *testing.T) { // 1236/
}
f, err := forgemsg.DecodeForge(pub.data[0])
d, e := strings.Repeat("d", 40), strings.Repeat("e", 40)
if err != nil || f.Root != d || f.Trees[""] != d || f.Trees["contracts"] != e || f.Merge == "" {
if err != nil || f.Root != d || f.Trees[""] != d || f.Trees["contracts"] != e || f.Merge != landed || f.Base != "main" || f.Number != 12 || f.Branch != "feat/x" {
t.Errorf("message %+v err %v", f, err)
}
if m.acked != 1 {
t.Errorf("acked %d", m.acked)
if m.acked != 1 || heads.get("branch.novox.mesh-delivery.main") != landed {
t.Errorf("acked %d, head kept %q", m.acked, heads.get("branch.novox.mesh-delivery.main"))
}
again, other := &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("main")}, &fakeMsg{subject: bridge.BranchMovedSubject, data: movedEvent("feat/x")}
mv.hear(context.Background(), again)
mv.hear(context.Background(), other)
if len(pub.subjects) != 1 || again.acked != 1 || other.acked != 1 {
t.Errorf("the same move again and a move of a branch not watched wrote %d messages (acked %d, %d), want none", len(pub.subjects)-1, again.acked, other.acked)
}
}
@@ -0,0 +1,143 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"strings"
"sync"
"github.com/nats-io/nats.go/jetstream"
mcseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg"
"git.novox.be/novox/mesh-sdk/go/keys"
"mesh-delivery-forge-bridge/internal/bridge"
)
// mover writes the one message of each move of a watched branch (design 47 G §11, §509, §714): heard on the seat git's
// branch-moved through the bridge's durable on SEAT_git_branch-moved, the head read by the seat's verb branch, never the
// event's; merged with its pull request, or pushed; the head written kept in the state heads under the branch's key
// (A-236), so a move heard twice writes once and the next pushed says its head before.
type mover struct {
call caller
pub publisher
heads headStore
watched *bridge.Watched
inputs bridge.Kept
groups *grouper
turn *sync.Mutex
logger *log.Logger
}
// hear takes one branch-moved: one it cannot read is terminated, one of a branch not watched is acknowledged with nothing
// written, one the forge could not say about is heard again.
func (mv *mover) hear(ctx context.Context, m delivered) {
moved, err := bridge.MovedOf(m.Data())
if err != nil {
mv.logger.Printf("%v; the event is dropped", err)
_ = m.Term()
return
}
if !mv.watched.Watches(moved.Repository(), moved.Branch) {
_ = m.Ack()
return
}
mv.turn.Lock()
err = mv.move(ctx, moved)
mv.turn.Unlock()
switch {
case errors.Is(err, bridge.ErrUnreadable):
mv.logger.Printf("%v; the event is dropped", err)
_ = m.Term()
case err != nil:
mv.logger.Printf("%v; heard again in %s", err, retryDelay)
_ = m.NakWithDelay(retryDelay)
default:
_ = m.Ack()
}
}
// move reads the branch's head and writes its message, unless that head is the one last written for it.
func (mv *mover) move(ctx context.Context, moved bridge.Moved) error {
b, err := bridge.ReadBranch(ctx, bridge.Caller(mv.call), moved)
if err != nil {
return fmt.Errorf("%s of %s: %w", moved.Branch, moved.Repository(), err)
}
before, _, err := mv.heads.Get(ctx, moved.HeadKey())
if err != nil {
return fmt.Errorf("%s of %s: the head last written cannot be read: %w", moved.Branch, moved.Repository(), err)
}
if before == b.Head {
return nil
}
if !b.Protected {
// A branch whose protection was removed starts nothing: nothing is written (§17, §509).
mv.logger.Printf("%s of %s moved to %s while it is not protected: nothing is written", moved.Branch, moved.Repository(), b.Head)
return nil
}
msg, err := bridge.MoveMessage(ctx, bridge.Caller(mv.call), moved, b.Head, before, treesVia(ctx, mv.call), filesVia(ctx, mv.call), mv.inputs)
if err != nil {
return err
}
data, grouped := msg.Data, false
var member forgemsg.Forge
if mv.groups != nil {
data, member, grouped = mv.groups.member(ctx, msg.Data)
}
// The branch's new head makes a write after a lost acknowledgement the same message to the stream.
id := "moved." + keys.EscapeName(moved.Repository()) + "." + keys.EscapeName(moved.Branch) + "." + b.Head
if _, err := mv.pub.Publish(ctx, forgeSubject(msg.Event), data, jetstream.WithMsgID(id)); err != nil {
return fmt.Errorf("%s could not be written on FORGE: %w", msg.Event, err)
}
if grouped {
mv.groups.published(ctx, member)
}
if err := mv.heads.Put(ctx, moved.HeadKey(), b.Head); err != nil {
mv.logger.Printf("%s of %s: the head %s written is not kept, so the next move says the older head before: %v", moved.Branch, moved.Repository(), b.Head, err)
}
if msg.Said != "" {
mv.logger.Printf("%s", msg.Said)
}
return nil
}
// readHeads reads each watched branch's head (§11): a head missed while the bridge was stopped is written now.
func (mv *mover) readHeads(ctx context.Context) {
for _, repo := range mv.watched.Repositories() {
owner, name, ok := strings.Cut(repo, "/")
if !ok {
continue
}
for _, branch := range mv.watched.Branches(repo) {
mv.turn.Lock()
err := mv.move(ctx, bridge.Moved{Owner: owner, Repo: name, Branch: branch})
mv.turn.Unlock()
if err != nil {
mv.logger.Printf("the head of %s of %s is not read at this start, so a move missed meanwhile waits for its next move: %v", branch, repo, err)
}
}
}
}
// registeredOf is the registrations as the watched branches read them.
func registeredOf(regs []mcseat.Registration) []bridge.Registered {
out := make([]bridge.Registered, 0, len(regs))
for _, r := range regs {
out = append(out, bridge.Registered{Origin: r.Origin, Branches: r.Branches})
}
return out
}
// unescaped is the gate's source's branches by name (they are kept by their escaped name).
func unescaped(branches []string) []string {
out := make([]string, 0, len(branches))
for _, b := range branches {
if name, err := keys.UnescapeName(b); err == nil {
out = append(out, name)
}
}
return out
}
@@ -80,7 +80,7 @@ func hear(mu *sync.Mutex, react func()) {
// ADR 0443 §5). pub keeps the bucket as it writes (recorder). It holds mu from before it reads the forge until the open
// message is written, so no event is heard between, and never past syncDeadline. A bucket that cannot be read is logged
// and every open pull request is written. An error names the call and the forge's words.
func syncOpen(ctx context.Context, call caller, pub publisher, heads headStore, mu *sync.Mutex, logger *log.Logger) error {
func syncOpen(ctx context.Context, call caller, pub publisher, heads headStore, watched bridge.Watching, mu *sync.Mutex, logger *log.Logger) error {
mu.Lock()
defer mu.Unlock()
ctx, cancel := context.WithTimeout(ctx, syncDeadline)
@@ -89,11 +89,11 @@ func syncOpen(ctx context.Context, call caller, pub publisher, heads headStore,
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
msgs, skipped, err := bridge.OpenPulls(raw)
msgs, skipped, err := bridge.OpenPulls(raw, watched)
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
open, err := bridge.OpenMessage(raw)
open, err := bridge.OpenMessage(raw, watched)
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
@@ -90,7 +90,7 @@ func (m *memHeads) get(key string) string { m.mu.Lock(); defer m.mu.Unlock(); re
// runSync runs syncOpen with the recorder the program writes through.
func runSync(call caller, pub publisher, heads headStore, mu *sync.Mutex, logger *log.Logger) error {
return syncOpen(context.Background(), call, &recorder{pub: pub, heads: heads, logger: logger}, heads, mu, logger)
return syncOpen(context.Background(), call, &recorder{pub: pub, heads: heads, logger: logger}, heads, watchesMain(), mu, logger)
}
// 1279/AC6: the sync writes a pull message only for a head that differs from what FORGE holds, then one open message