Its conditions' keys, its asks' subjects, its reader and emitter, its ends bucket and its tools' first views take the module its credential names (the tools: the module the runtime serves them as) instead of constants of its name; a guard test finds none in its code. Builds: design 47 G A-296, §428 Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
674 lines
30 KiB
Go
674 lines
30 KiB
Go
//go:build integration
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
|
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
|
"git.novox.be/novox/mesh-sdk/go/views/viewstest"
|
|
"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.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
|
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
|
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
|
"git.novox.be/novox/mesh-sdk/go/process"
|
|
|
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view/viewstate"
|
|
|
|
"mesh-delivery-teller/internal/ends"
|
|
)
|
|
|
|
type syncBuffer struct {
|
|
mu sync.Mutex
|
|
b strings.Builder
|
|
}
|
|
|
|
func (s *syncBuffer) Write(p []byte) (int, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.b.Write(p)
|
|
}
|
|
func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
|
|
|
|
// The principals of the composed accounts file for the teller's tests, with the permissions mesh-controller composes for
|
|
// them (internal/broker): a module's own state is the read grants of its bucket and `$KV.<bucket>.>` to write it
|
|
// (state.go stateGrants, readGrants), a read of another module's bucket is the read grants alone, and a module that uses
|
|
// the seat operator-channel submits its own `accept.ask.<module>`, `accept.cancel.<module>` and `accept.condition.<module>`,
|
|
// hears its own `event.decided.<module>` and reads `$KV.messenger_asks.<module>.>` of the router's record (seattraffic.go
|
|
// SeatTrafficOf, with the messenger's seat declaring accepts ask, cancel, condition, emits decided, by-caller and records
|
|
// messenger_asks). The gate is a bundle on the tool runner's account (ADR 0437 §3), so the gate's writes are the account node-tools'.
|
|
// The permissions are these lists written out, not the controller's function: the broker tests of issue 1243 prove that.
|
|
func readOf(bucket string) []string {
|
|
stream := "KV_" + bucket
|
|
return []string{"$JS.API.STREAM.INFO." + stream, "$JS.API.DIRECT.GET." + stream + ".>", "$JS.API.CONSUMER.CREATE." + stream + ".>",
|
|
"$JS.API.CONSUMER.DELETE." + stream + ".>", "$JS.FC." + stream + ".>"}
|
|
}
|
|
|
|
func keepsOf(bucket string) []string { return append(readOf(bucket), "$KV."+bucket+".>") }
|
|
|
|
func user(name string, pub, sub []string) string {
|
|
q := func(l []string) string {
|
|
var b strings.Builder
|
|
for _, s := range l {
|
|
b.WriteString(fmt.Sprintf(" %q\n", s))
|
|
}
|
|
return b.String()
|
|
}
|
|
return fmt.Sprintf(` { user: %q, password: "pw"
|
|
permissions {
|
|
publish { allow: [
|
|
%s ] }
|
|
subscribe { allow: [
|
|
%s ] }
|
|
allow_responses: true
|
|
}
|
|
}
|
|
`, name, q(pub), q(append([]string{"_INBOX." + name + ".>"}, sub...)))
|
|
}
|
|
|
|
const (
|
|
tellerAnswers = "mesh-delivery-teller_answers"
|
|
tellerAsked = "mesh-delivery-teller_asked"
|
|
assignerAsks = "mesh-delivery-assigner_asks"
|
|
viewAnswers = "mesh-delivery-view_" + viewstate.ViewAnswersState
|
|
tellerConsumer = "n1_mesh-delivery-teller"
|
|
// The stand-ins of the seats' holders: the teller's code names neither (design 47 G §717).
|
|
assignerModule = "mesh-delivery-assigner"
|
|
viewModule = "mesh-delivery-view"
|
|
seatAsk = "mesh.seat.operator-channel.accept.ask.mesh-delivery-teller"
|
|
seatCancel = "mesh.seat.operator-channel.accept.cancel.mesh-delivery-teller"
|
|
seatCondition = "mesh.seat.operator-channel.accept.condition.mesh-delivery-teller"
|
|
seatDecided = "mesh.seat.operator-channel.event.decided.mesh-delivery-teller"
|
|
// routerAsksBucket is the router's state asks in the bucket of the seat operator-channel's holder on the seat list (here ops-router):
|
|
// the holder's module name and the seat's state, never a name in the program (design 47 G A-101, A-74).
|
|
routerAsksBucket = "ops-router_asks"
|
|
)
|
|
|
|
func fullConf(dir string) string {
|
|
// ends is the teller's own state (manifest state entry ends), which the controller makes before it starts: a bed
|
|
// without it held the start ten seconds on a read the bus never answered, and the tests raced that stall.
|
|
teller := append(append(append(keepsOf(tellerAnswers), keepsOf(tellerAsked)...), keepsOf(ends.Bucket(tellerModule))...),
|
|
seatAsk, seatCancel, seatCondition, "$JS.API.DIRECT.GET.KV_"+routerAsksBucket+".$KV."+routerAsksBucket+".mesh-delivery-teller.>")
|
|
teller = append(teller, keepsOf(bucketsOf(tellerModule).widensSaid)...) // design 47 G §335: the state widens-said
|
|
// The durable consumer on EVENTS the controller makes for the seat it uses, pulled and acknowledged (issue 1126).
|
|
teller = append(teller, "$JS.API.CONSUMER.INFO.EVENTS."+tellerConsumer, "$JS.API.CONSUMER.MSG.NEXT.EVENTS."+tellerConsumer, "$JS.ACK.EVENTS."+tellerConsumer+".>")
|
|
// The finding writer finds the stream of the keeper's findings-asked (design 47 G §384): the bed has none, so it is
|
|
// said and the findings stay in the state.
|
|
teller = append(teller, "$JS.API.STREAM.NAMES")
|
|
// The manifest's emits (ADR 0596 §2; design 47 G A-175: its answers as its views family) and its marks state (A-178).
|
|
teller = append(teller, "mesh.mod.mesh-delivery-teller.event.answered", "mesh.mod.mesh-delivery-teller.event.ask-ended", "mesh.mod.mesh-delivery-teller.event.views.answers")
|
|
teller = append(teller, keepsOf(bucketsOf(tellerModule).marks)...)
|
|
// The assigner's asks and the view's answers, each by its read tool and its views family (ADR 0615, DLV-M3; A-175), and the
|
|
// teller's own first-views and findings; the buckets themselves are no longer the teller's to read.
|
|
teller = append(append(append(teller, viewstest.Grants(assignerModule, assignerModule+"."+meshwants.StateAsks, tellerConsumer)...), viewstest.Grants(viewModule, viewModule+"."+viewstate.ViewAnswersTool, tellerConsumer)...), keepsOf(bucketsOf(tellerModule).firstViews)...)
|
|
// Design 47 G §717, §614: the catalog half's first views and the seat-holders view of the claimant it names.
|
|
teller = append(append(teller, viewstest.Grants(assignerModule, assignerModule+".seat-holders", tellerConsumer)...),
|
|
"mesh.seat.mesh-catalog.call.revision", "mesh.seat.mesh-catalog.call.revision.>", "mesh.seat.mesh-catalog.call.registrations",
|
|
"mesh.seat.mesh-catalog.call.registrations.>", "mesh.seat.mesh-delivery.call.source", "mesh.seat.mesh-delivery.call.source.>")
|
|
teller = append(teller, keepsOf(bucketsOf(tellerModule).findings)...)
|
|
view := append(append(readOf(tellerAnswers), readOf(assignerAsks)...), keepsOf(viewAnswers)...)
|
|
assigner := keepsOf(assignerAsks)
|
|
return fmt.Sprintf(`
|
|
listen: 127.0.0.1:-1
|
|
jetstream { store_dir: %q }
|
|
accounts {
|
|
MESH {
|
|
jetstream: enabled
|
|
users = [
|
|
{ user: "ctl", password: "pw" }
|
|
%s%s%s ]
|
|
}
|
|
}
|
|
`, filepath.Join(dir, "js"),
|
|
user("n1.mesh-delivery-teller", teller, nil),
|
|
user("n1.mesh-delivery-view", view, nil),
|
|
user("n1.mesh-delivery-assigner", assigner, nil))
|
|
}
|
|
|
|
type fullBed struct {
|
|
holders jetstream.KeyValue // the assigner's seat-holders (place)
|
|
srv *server.Server
|
|
ctl *nats.Conn
|
|
js jetstream.JetStream
|
|
ctx context.Context
|
|
}
|
|
|
|
// startFull starts the bus with the principals above and what the controller makes before any module starts: the buckets
|
|
// of the assigner's asks, the view's answers, the teller's answers, asked and marks, the router's work queue SEAT_OPERATOR_CHANNEL.
|
|
func startFull(t *testing.T) *fullBed {
|
|
t.Helper()
|
|
dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "t")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
|
conf := filepath.Join(dir, "bus.conf")
|
|
if err := os.WriteFile(conf, []byte(fullConf(dir)), 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)
|
|
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)
|
|
for name, history := range map[string]uint8{tellerAnswers: answersHistory, tellerAsked: 1, ends.Bucket(tellerModule): 1, routerAsksBucket: 1, assignerAsks: 5, viewAnswers: 5, bucketsOf(tellerModule).marks: 1, bucketsOf(tellerModule).firstViews: 1, bucketsOf(tellerModule).findings: 1, bucketsOf(tellerModule).widensSaid: 1} {
|
|
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: history}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "SEAT_OPERATOR_CHANNEL", Subjects: []string{"mesh.seat.operator-channel.accept.>"},
|
|
Retention: jetstream.WorkQueuePolicy}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS", Subjects: []string{"mesh.seat.operator-channel.event.>", "mesh.mod.*.event.>"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := js.CreateOrUpdateConsumer(ctx, "EVENTS", jetstream.ConsumerConfig{Durable: tellerConsumer,
|
|
AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// The assigner as the owner of its asks: its read tool and its views family (ADR 0615).
|
|
viewstest.Serve(t, ctx, js, ctl, assignerModule, "asks", assignerModule+"."+meshwants.StateAsks, tellerConsumer)
|
|
// The view as the owner of its answers, as the teller follows them (A-175, A-178).
|
|
viewstest.Serve(t, ctx, js, ctl, viewModule, viewstate.ViewAnswersState, viewModule+"."+viewstate.ViewAnswersTool, tellerConsumer)
|
|
// Design 47 G §717: the catalog half names the assigner the claimant of mesh-module-assigner, and its seat-holders view
|
|
// names no holder of mesh-wants or mesh-delivery-view until a test places them (place).
|
|
serveCatalogHalf(t, ctl)
|
|
holders := viewstest.Serve(t, ctx, js, ctl, assignerModule, "seat-holders", assignerModule+".seat-holders", tellerConsumer)
|
|
return &fullBed{srv: srv, ctl: ctl, js: js, ctx: ctx, holders: holders}
|
|
}
|
|
|
|
// place says the assigner and the view hold mesh-wants and mesh-delivery-view, on the seat-holders view.
|
|
func (b *fullBed) place(t *testing.T) {
|
|
t.Helper()
|
|
for seat, module := range map[string]string{"mesh-wants": assignerModule, "mesh-delivery-view": viewModule} {
|
|
if _, err := b.holders.Put(b.ctx, seat, []byte(`{"seat":"`+seat+`","holders":[{"module":"`+module+`","node":"n1"}]}`)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// serveCatalogHalf answers the catalog half's three first views (design 47 G §614): the gate's one source branch, the
|
|
// assigner registered on it, and its trunk revision whose entry of the assigner claims mesh-module-assigner.
|
|
func serveCatalogHalf(t *testing.T, nc *nats.Conn) {
|
|
t.Helper()
|
|
respond := func(a any) nats.MsgHandler {
|
|
raw, _ := json.Marshal(map[string]any{"result": a, "node": "n0"})
|
|
return func(m *nats.Msg) { _ = m.Respond(raw) }
|
|
}
|
|
revision := meshcatalog.RevisionAnswer{Revision: &meshcatalog.CatalogRevision{Revision: 1, Kind: meshcatalogclient.KindTrunk},
|
|
Entries: []meshcatalog.CatalogEntry{{Module: assignerModule, ManifestDigest: "d1", Manifest: map[string]any{"module": assignerModule,
|
|
"claims": []any{map[string]any{"name": "mesh-module-assigner", "scope": "mesh"}}}}}}
|
|
registrations := meshcatalog.RegistrationsAnswer{Registrations: []meshcatalog.Registration{{Module: assignerModule, Version: 1, Branches: []string{"release"}}}}
|
|
for subject, handle := range map[string]nats.MsgHandler{"mesh.seat.mesh-catalog.call.revision": respond(revision),
|
|
"mesh.seat.mesh-catalog.call.registrations": respond(registrations), "mesh.seat.mesh-delivery.call.source": respond(map[string]any{"branches": []string{"release"}})} {
|
|
for _, s := range []string{subject, subject + ".>"} {
|
|
sub, err := nc.Subscribe(s, handle)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
|
}
|
|
}
|
|
}
|
|
|
|
// listening waits until the program hears the router's warrants (its pull of the durable consumer is waiting on the bus),
|
|
// which it does before it watches any bucket: an event, not a pause a loaded machine can outlast.
|
|
func (b *fullBed) listening(t *testing.T) {
|
|
t.Helper()
|
|
cons, err := b.js.Consumer(b.ctx, "EVENTS", tellerConsumer)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(10 * time.Millisecond) {
|
|
if info, err := cons.Info(b.ctx); err == nil && info.NumWaiting > 0 {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the program did not pull the router's warrants within 20 s")
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *fullBed) as(t *testing.T, name string) jetstream.JetStream {
|
|
t.Helper()
|
|
c, err := nats.Connect(b.srv.ClientURL(), nats.UserInfo(name, "pw"), nats.CustomInboxPrefix("_INBOX."+name))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(c.Close)
|
|
js, err := jetstream.New(c)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return js
|
|
}
|
|
|
|
// put writes a key as a principal, within a bounded time: a write the permissions refuse reaches the writer as a timeout.
|
|
func (b *fullBed) put(t *testing.T, js jetstream.JetStream, bucket, key string) error {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(b.ctx, 3*time.Second)
|
|
defer cancel()
|
|
kv, err := js.KeyValue(ctx, bucket)
|
|
if err != nil {
|
|
t.Fatalf("%s cannot be bound: %v", bucket, err)
|
|
}
|
|
_, err = kv.Put(ctx, key, []byte(`{}`))
|
|
return err
|
|
}
|
|
|
|
// TestCredentialsWriteOnlyTheirOwnBuckets: the view's credential, which reads the teller's answers, is refused writing them; each
|
|
// credential writes its own buckets, so a refusal is the permissions' and not a bus that does not take writes (1343/AC4, ADR
|
|
// 0437 §6's check). The teller reads neither the assigner's asks nor the view's answers: it follows them.
|
|
func TestCredentialsWriteOnlyTheirOwnBuckets(t *testing.T) { // 1343/AC4
|
|
b := startFull(t)
|
|
teller, view, assigner := b.as(t, "n1.mesh-delivery-teller"), b.as(t, "n1.mesh-delivery-view"), b.as(t, "n1.mesh-delivery-assigner")
|
|
for _, c := range []struct {
|
|
who jetstream.JetStream
|
|
bucket string
|
|
key string
|
|
}{{teller, tellerAnswers, "hold.a"}, {teller, bucketsOf(tellerModule).marks, "answers"}, {assigner, assignerAsks, "hold.a"}, {view, viewAnswers, "hold.a.view"}} {
|
|
if err := b.put(t, c.who, c.bucket, c.key); err != nil {
|
|
t.Errorf("a credential cannot write its own %s: %v", c.bucket, err)
|
|
}
|
|
}
|
|
for _, c := range []struct {
|
|
who jetstream.JetStream
|
|
bucket string
|
|
key string
|
|
}{{view, tellerAnswers, "hold.f"}} {
|
|
if err := b.put(t, c.who, c.bucket, c.key); err == nil {
|
|
t.Errorf("a credential wrote %s, which is not its own", c.bucket)
|
|
}
|
|
kv, _ := b.js.KeyValue(b.ctx, c.bucket)
|
|
if _, err := kv.Get(b.ctx, c.key); err == nil {
|
|
t.Errorf("%s holds %s though its write was refused", c.bucket, c.key)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestTellerCarriesAnAskAndWritesTheAnswer starts the program on the composed principal against the bus: the assigner writes
|
|
// a hold ask, the teller publishes it to the seat's work queue under its own name, the router (the test) says the warrant on
|
|
// the teller's decided subject, and the answer is under the ask's key in the teller's bucket and said as the event answered
|
|
// and on the views family views.answers (A-175); taking a second ask away cancels it (1343/AC1, AC2, 1906/H1, H2).
|
|
func TestTellerCarriesAnAskAndWritesTheAnswer(t *testing.T) { // 1343/AC1, AC2
|
|
t.Cleanup(nowIs(time.Now().UTC()))
|
|
b := startFull(t)
|
|
assigner := b.as(t, "n1.mesh-delivery-assigner")
|
|
broker := filepath.Join(t.TempDir(), "broker")
|
|
cred, _ := json.Marshal(process.Account{URL: b.srv.ClientURL(), Node: "n1", Module: "mesh-delivery-teller", User: "n1.mesh-delivery-teller", Password: "pw"})
|
|
if err := os.WriteFile(broker, cred, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
env := map[string]string{"MESH_BROKER_FILE": broker}
|
|
logs := &syncBuffer{}
|
|
rn := startRunner(b.ctx, func(c context.Context) error { return run(c, func(k string) string { return env[k] }, logs) })
|
|
t.Cleanup(func() { rn.finish(t, 10*time.Second) })
|
|
|
|
// Issue 774: the router's record is read on the teller's own credential from the bucket the controller grants it.
|
|
if mkv, err := b.js.KeyValue(b.ctx, routerAsksBucket); err != nil {
|
|
t.Fatal(err)
|
|
} else if _, err := mkv.Put(b.ctx, "mesh-delivery-teller.r1", []byte(`{"state":"open"}`)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
tc, err := nats.Connect(b.srv.ClientURL(), nats.UserInfo("n1.mesh-delivery-teller", "pw"), nats.CustomInboxPrefix("_INBOX.n1.mesh-delivery-teller"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(tc.Close)
|
|
seatList := func(key string, _ any) (json.RawMessage, error) {
|
|
if key != "seat:mesh-module-assigner.assignments" {
|
|
t.Errorf("the router's holder was asked of %s, want the seat mesh-module-assigner's assignments", key)
|
|
}
|
|
return json.RawMessage(`{"seats":[{"seat":"operator-channel","scope":"mesh","holders":[{"module":"ops-router","node":"n2"}]}]}`), nil
|
|
}
|
|
getRecord := func(bucket, id string) (*stdio.StateEntry, error) {
|
|
msg, err := tc.RequestWithContext(b.ctx, "$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+".mesh-delivery-teller."+id, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &stdio.StateEntry{Key: id, Value: msg.Data}, nil
|
|
}
|
|
if rec, err := recordVia(seatList, getRecord)("r1"); err != nil || rec == nil {
|
|
t.Fatalf("the router's record read as the teller: %v, %v; want it", rec, err)
|
|
}
|
|
|
|
key, value, ask := holdAsk(t)
|
|
kv, err := assigner.KeyValue(b.ctx, assignerAsks)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// The program hears warrants before it reads the asks; it has its subscription before the ask is written.
|
|
b.listening(t)
|
|
// Design 47 G §717: the teller started before any module held mesh-wants; once the holder is placed it follows it, and
|
|
// raises the ask the holder then writes.
|
|
b.place(t)
|
|
for deadline := time.Now().Add(10 * time.Second); !strings.Contains(logs.String(), "holds "+assignerModule+"'s asks, the holder of the seat mesh-wants"); time.Sleep(10 * time.Millisecond) {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("the teller did not follow the placed holder of mesh-wants:\n%s", logs.String())
|
|
}
|
|
}
|
|
if _, err := kv.Put(b.ctx, key, value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
seat, err := b.js.Stream(b.ctx, "SEAT_OPERATOR_CHANNEL")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var raw *jetstream.RawStreamMsg
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if raw, err = seat.GetLastMsgForSubject(b.ctx, seatAsk); err == nil {
|
|
break
|
|
}
|
|
}
|
|
if raw == nil {
|
|
t.Fatalf("no ask on the seat's queue: %v\n%s", err, logs.String())
|
|
}
|
|
var asked oc.Ask
|
|
if err := json.Unmarshal(raw.Data, &asked); err != nil || occ.Digest(asked) != occ.Digest(ask) {
|
|
t.Fatalf("the ask on the queue is %+v (%v), want the assigner's", asked, err)
|
|
}
|
|
// The router says the warrant.
|
|
w, _ := json.Marshal(ackFor(ask, "release"))
|
|
if err := b.ctl.Publish(seatDecided, w); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
answers, err := b.js.KeyValue(b.ctx, tellerAnswers)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var e jetstream.KeyValueEntry
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if e, err = answers.Get(b.ctx, answerKey(key)); err == nil {
|
|
break
|
|
}
|
|
}
|
|
if e == nil {
|
|
t.Fatalf("no answer under %s: %v\n%s", key, err, logs.String())
|
|
}
|
|
if a, err := meshdeliveryclient.DecodeAnswer(e.Value()); err != nil || a.Option != "release" {
|
|
t.Errorf("answer %+v err %v", a, err)
|
|
}
|
|
// The answer is said as the event answered (ADR 0596 §2) and on the views family views.answers (A-175).
|
|
events, err := b.js.Stream(b.ctx, process.EventsStream)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var said *jetstream.RawStreamMsg
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if said, err = events.GetLastMsgForSubject(b.ctx, "mesh.mod.mesh-delivery-teller.event.answered"); err == nil {
|
|
break
|
|
}
|
|
}
|
|
if said == nil {
|
|
t.Fatalf("the answer was not said as the event answered: %v\n%s", err, logs.String())
|
|
}
|
|
if got := string(said.Data); !strings.Contains(got, `"key":"`+key+`"`) || !strings.Contains(got, `"option":"release"`) {
|
|
t.Errorf("the event answered is %s", got)
|
|
}
|
|
if vs, err := events.GetLastMsgForSubject(b.ctx, "mesh.mod.mesh-delivery-teller.event.views.answers"); err != nil || !strings.Contains(string(vs.Data), key) {
|
|
t.Errorf("the answer was not said on the views family views.answers: %v\n%s", err, logs.String())
|
|
}
|
|
// A second ask, taken away by the assigner, is cancelled at the router.
|
|
key2, err := asks.HoldAskKey("plex", "src2:"+strings.Repeat("3", 64))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ask2 := ask
|
|
ask2.ID = meshdeliveryclient.AskID(key2)
|
|
value2, err := asks.EncodeAsk(key2, asks.Ask{Ask: rawAsk(t, ask2)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := kv.Put(b.ctx, key2, value2); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if strings.Contains(logs.String(), ask2.ID+" is asked") {
|
|
break
|
|
}
|
|
}
|
|
if err := kv.Delete(b.ctx, key2); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if raw, err = seat.GetLastMsgForSubject(b.ctx, seatCancel); err == nil {
|
|
break
|
|
}
|
|
}
|
|
if err != nil || string(raw.Data) != `{"id":"`+ask2.ID+`"}` {
|
|
t.Errorf("the ask taken away was not cancelled: %v %v\n%s", raw, err, logs.String())
|
|
}
|
|
}
|
|
|
|
// TestTellerAsksAgainAnAskRefusedForWantOfRoom starts the program against the bus: the router (the test) refuses the assigner's
|
|
// ask for want of room, as the live router did on 2026-10-21 (issue 1610), and then says another of the teller's asks
|
|
// lapsed; the refused ask is on the seat's work queue again, which the bus's duplicate window would have dropped under its
|
|
// first message id (1610/AC1 on the real bus).
|
|
func TestTellerAsksAgainAnAskRefusedForWantOfRoom(t *testing.T) { // 1610/AC1
|
|
t.Cleanup(nowIs(time.Now().UTC()))
|
|
b := startFull(t)
|
|
b.place(t)
|
|
assigner := b.as(t, "n1.mesh-delivery-assigner")
|
|
broker := filepath.Join(t.TempDir(), "broker")
|
|
cred, _ := json.Marshal(process.Account{URL: b.srv.ClientURL(), Node: "n1", Module: "mesh-delivery-teller", User: "n1.mesh-delivery-teller", Password: "pw"})
|
|
if err := os.WriteFile(broker, cred, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
env := map[string]string{"MESH_BROKER_FILE": broker}
|
|
logs := &syncBuffer{}
|
|
rn := startRunner(b.ctx, func(c context.Context) error { return run(c, func(k string) string { return env[k] }, logs) })
|
|
t.Cleanup(func() { rn.finish(t, 10*time.Second) })
|
|
kv, err := assigner.KeyValue(b.ctx, assignerAsks)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
seat, err := b.js.Stream(b.ctx, "SEAT_OPERATOR_CHANNEL")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b.listening(t)
|
|
// lastAsk waits for the seat's queue to hold an ask newer than seq under id, and gives its sequence.
|
|
lastAsk := func(id string, after uint64) uint64 {
|
|
t.Helper()
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
raw, err := seat.GetLastMsgForSubject(b.ctx, seatAsk)
|
|
if err != nil || raw.Sequence <= after {
|
|
continue
|
|
}
|
|
var a oc.Ask
|
|
if json.Unmarshal(raw.Data, &a) == nil && a.ID == id {
|
|
return raw.Sequence
|
|
}
|
|
}
|
|
t.Fatalf("the ask %s is not on the seat's queue after sequence %d\n%s", id, after, logs.String())
|
|
return 0
|
|
}
|
|
say := func(w oc.Warrant) {
|
|
t.Helper()
|
|
raw, _ := json.Marshal(w)
|
|
if err := b.ctl.Publish(seatDecided, raw); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
key, value, held := holdAskAt(t, 1, 1)
|
|
if _, err := kv.Put(b.ctx, key, value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
first := lastAsk(held.ID, 0)
|
|
say(oc.Warrant{Ask: held.ID, Asker: tellerModule, Outcome: occ.OutcomeRefused, Words: roomRefusal, At: occ.FormatTime(now)})
|
|
for deadline := time.Now().Add(10 * time.Second); !strings.Contains(logs.String(), "for want of room"); time.Sleep(50 * time.Millisecond) {
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("the refusal was not heard\n%s", logs.String())
|
|
}
|
|
}
|
|
key2, value2, ga2 := holdAskAt(t, 2, 1)
|
|
if _, err := kv.Put(b.ctx, key2, value2); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
second := lastAsk(ga2.ID, first)
|
|
// The other ask lapses at the router: there is room, and the refused ask is asked again.
|
|
say(oc.Warrant{Ask: ga2.ID, Asker: tellerModule, Outcome: occ.OutcomeExpired, At: occ.FormatTime(now), AskDigest: occ.Digest(ga2)})
|
|
lastAsk(held.ID, second)
|
|
}
|
|
|
|
// TestTellerFillsAnAskFromTheViewsAnswerOnce starts the program against the bus with the permissions above: the assigner's
|
|
// fixture hold ask is written, then the view's answer under `<ask key>.view`; the answer is under the ask's own key, once
|
|
// (rewriting the view's answer does not write a second), and a view answer under a key that is no assigner's (a merge's) fills nothing
|
|
// (1297/B10 AC: a view answer fills the ask once; an ask needing proof is not answered from a view key).
|
|
func TestTellerFillsAnAskFromTheViewsAnswerOnce(t *testing.T) { // 1297/B10 AC
|
|
t.Cleanup(nowIs(time.Now().UTC()))
|
|
b := startFull(t)
|
|
b.place(t)
|
|
assigner, view := b.as(t, "n1.mesh-delivery-assigner"), b.as(t, "n1.mesh-delivery-view")
|
|
broker := filepath.Join(t.TempDir(), "broker")
|
|
cred, _ := json.Marshal(process.Account{URL: b.srv.ClientURL(), Node: "n1", Module: "mesh-delivery-teller", User: "n1.mesh-delivery-teller", Password: "pw"})
|
|
if err := os.WriteFile(broker, cred, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
env := map[string]string{"MESH_BROKER_FILE": broker}
|
|
logs := &syncBuffer{}
|
|
rn := startRunner(b.ctx, func(c context.Context) error { return run(c, func(k string) string { return env[k] }, logs) })
|
|
t.Cleanup(func() { rn.finish(t, 10*time.Second) })
|
|
|
|
key, value, ask := holdAsk(t)
|
|
askKV, err := assigner.KeyValue(b.ctx, assignerAsks)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
viewKV, err := view.KeyValue(b.ctx, viewAnswers)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
answers, err := b.js.KeyValue(b.ctx, tellerAnswers)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b.listening(t) // the program hears warrants and watches
|
|
if _, err := askKV.Put(b.ctx, key, value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := viewKV.Put(b.ctx, key+".view", viewAnswer(t, "release", "the check was a flake")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var e jetstream.KeyValueEntry
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if e, err = answers.Get(b.ctx, answerKey(key)); err == nil {
|
|
break
|
|
}
|
|
}
|
|
if e == nil {
|
|
t.Fatalf("no answer under %s: %v\n%s", key, err, logs.String())
|
|
}
|
|
if a, err := meshdeliveryclient.DecodeAnswer(e.Value()); err != nil || a.Option != "release" || answeredAsking(e.Value()) != ask.ID {
|
|
t.Fatalf("answer %+v err %v", a, err)
|
|
}
|
|
// The view's answer written again with the same option changes nothing under the ask (another option, later, is the
|
|
// operator changing their mind: TestTellerTakesAChangedHoldAnswerFromTheView, issue 1906 note 23).
|
|
if _, err := viewKV.Put(b.ctx, key+".view", viewAnswer(t, "release", "")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
time.Sleep(time.Second)
|
|
if again, err := answers.Get(b.ctx, answerKey(key)); err != nil || again.Revision() != e.Revision() {
|
|
t.Errorf("the answer was written a second time: %v", err)
|
|
}
|
|
// An answer under the merge's key fills nothing.
|
|
mkey, mvalue := "merge.g.0123456789ab", value
|
|
if _, err := askKV.Put(b.ctx, mkey, mvalue); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := viewKV.Put(b.ctx, mkey+".view", viewAnswer(t, "approve", "")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
time.Sleep(time.Second)
|
|
if _, err := answers.Get(b.ctx, answerKey(mkey)); err == nil {
|
|
t.Error("the merge's ask was answered from a view key")
|
|
}
|
|
}
|
|
|
|
// TestTellerTakesAChangedHoldAnswerFromTheView starts the program against the bus: a hold ask answered "keep" earlier, and the
|
|
// view's answer "release" written now, replace the answer of that asking with "release" (1906/N23 on the real bus).
|
|
func TestTellerTakesAChangedHoldAnswerFromTheView(t *testing.T) {
|
|
t.Cleanup(nowIs(time.Now().UTC()))
|
|
b := startFull(t)
|
|
b.place(t)
|
|
assigner, view := b.as(t, "n1.mesh-delivery-assigner"), b.as(t, "n1.mesh-delivery-view")
|
|
broker := filepath.Join(t.TempDir(), "broker")
|
|
cred, _ := json.Marshal(process.Account{URL: b.srv.ClientURL(), Node: "n1", Module: "mesh-delivery-teller", User: "n1.mesh-delivery-teller", Password: "pw"})
|
|
if err := os.WriteFile(broker, cred, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
key, value, ask := holdAsk(t)
|
|
answers, err := b.js.KeyValue(b.ctx, tellerAnswers)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
kept, _ := meshdeliveryclient.EncodeAnswer(meshdeliveryclient.Answer{Option: "keep", Warrant: ask.ID + "@" + time.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano), Words: "the operator chose keep"})
|
|
if _, err := answers.Put(b.ctx, answerKey(key), kept); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
askKV, err := assigner.KeyValue(b.ctx, assignerAsks)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := askKV.Put(b.ctx, key, value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
env := map[string]string{"MESH_BROKER_FILE": broker}
|
|
logs := &syncBuffer{}
|
|
rn := startRunner(b.ctx, func(c context.Context) error { return run(c, func(k string) string { return env[k] }, logs) })
|
|
t.Cleanup(func() { rn.finish(t, 10*time.Second) })
|
|
viewKV, err := view.KeyValue(b.ctx, viewAnswers)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b.listening(t) // the program hears warrants and watches
|
|
if _, err := viewKV.Put(b.ctx, key+".view", viewAnswer(t, "release", "it was a flake")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
|
if e, err := answers.Get(b.ctx, answerKey(key)); err == nil {
|
|
if a, err := meshdeliveryclient.DecodeAnswer(e.Value()); err == nil && a.Option == "release" && answeredAsking(e.Value()) == ask.ID {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
t.Fatalf("the kept hold's answer was not changed to release\n%s", logs.String())
|
|
}
|