Files
mesh-delivery/modules/mesh-delivery-forge-bridge/cmd/mesh-delivery-forge-bridge/open.go
T
jschoubben 3a4768ab43 FB6a: the forge bridge reads trees, files, pulls and tags through the seat git and hears its pull and delete events
Taken over from the join's 473f9323, 5f40d230, 159a679b; the events are the seat's pull-updated, pull-merged, pull-closed and forge-delete.

Builds: design 47 G §252, §310, §312, §317

Claude-Session: https://claude.ai/code/session_01JG73KEq4zoDfM9WtYpcQgZ
2026-11-11 11:48:36 +01:00

144 lines
5.1 KiB
Go

package main
import (
"context"
"fmt"
"log"
"slices"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
git "git.novox.be/novox/mesh-delivery/contracts/go/seats/git"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg"
"mesh-delivery-forge-bridge/internal/bridge"
)
// openPullsTool is the seat git's verb for every open pull request (novox/hq design 47 *The seat `git`*): no arguments,
// answers {pulls: [...]} or an error.
var openPullsTool = bridge.GitKey(git.VerbOpenPulls)
// headStore is the bucket heads: the head last written on FORGE for each pull request, by bridge.Track's key
// (novox/hq ADR 0443 §5).
type headStore interface {
// Get is the head kept under the key; found is false when there is none.
Get(ctx context.Context, key string) (head string, found bool, err error)
Put(ctx context.Context, key, head string) error
Delete(ctx context.Context, key string) error
}
// recorder writes to FORGE and keeps in the bucket what it wrote: a pull message keeps its head, a closed or merged one
// takes its pull request's key away. Every write of the program goes through it, an event's and a sync's alike.
type recorder struct {
pub publisher
heads headStore
logger *log.Logger
}
func (r *recorder) Publish(ctx context.Context, subject string, payload []byte, opts ...jetstream.PublishOpt) (*jetstream.PubAck, error) {
ack, err := r.pub.Publish(ctx, subject, payload, opts...)
if err != nil {
return ack, err
}
f, derr := forgemsg.DecodeForge(payload)
if derr != nil {
return ack, nil
}
key, head, ok := bridge.Track(f)
if !ok {
return ack, nil
}
if head == "" {
err = r.heads.Delete(ctx, key)
} else {
err = r.heads.Put(ctx, key, head)
}
if err != nil {
return ack, fmt.Errorf("%s was written on FORGE but its head could not be kept in the bucket: %w", subject, err)
}
return ack, nil
}
// syncDeadline bounds one sync: the call to the forge and every read and write of the bucket and of FORGE, because
// the sync holds the turn that stops the bridge hearing any event.
const syncDeadline = 30 * time.Second
// hear runs one reaction to a forge event while no sync of the open pull requests is between reading the forge and
// writing the open message (novox/hq ADR 0443 §5): an event heard meanwhile waits, and is written after it, so a pull
// request opened after the read is added again by its own message and never dropped by the open message.
func hear(mu *sync.Mutex, react func()) {
mu.Lock()
defer mu.Unlock()
react()
}
// syncOpen reads the open pull requests from the forge and writes a pull message for each whose head differs from the
// one kept in the bucket, then one open message naming every one it read, those whose head did not differ among them:
// what makes the indexer's candidates match the forge after a restart or a gap in the forge's events (ADR 0429 §13,
// 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 {
mu.Lock()
defer mu.Unlock()
ctx, cancel := context.WithTimeout(ctx, syncDeadline)
defer cancel()
raw, err := call(ctx, openPullsTool, git.OpenPullsInput{})
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
msgs, skipped, err := bridge.OpenPulls(raw)
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
open, err := bridge.OpenMessage(raw)
if err != nil {
return fmt.Errorf("%s: %w", openPullsTool, err)
}
for _, s := range skipped {
logger.Printf("an open pull request is left out: %s", s)
}
var differing []bridge.Message
for _, m := range msgs {
f, err := forgemsg.DecodeForge(m.Data)
if err != nil {
differing = append(differing, m)
continue
}
key, head, _ := bridge.Track(f)
kept, found, err := heads.Get(ctx, key)
if err != nil {
logger.Printf("the heads kept could not be read, so every open pull request is written: %v", err)
differing = slices.Clone(msgs)
break
}
if !found || kept != head {
differing = append(differing, m)
}
}
for _, m := range append(differing, open) {
if _, err := pub.Publish(ctx, forgeSubject(m.Event), m.Data); err != nil {
return fmt.Errorf("the open pull request message %s could not be written on FORGE: %w", m.Event, err)
}
}
logger.Printf("%d pull messages and the open message written on FORGE", len(differing))
return nil
}
// onReconnect reads the open pull requests again each time the bus connection comes back, until ctx ends; a failure is
// logged and the bridge goes on (the next reconnect or event tries again).
func onReconnect(ctx context.Context, again <-chan struct{}, sync func(context.Context) error, logger *log.Logger) {
for {
select {
case <-ctx.Done():
return
case <-again:
if err := sync(ctx); err != nil {
logger.Printf("after a reconnect: %v", err)
}
}
}
}