Files
mesh-delivery/modules/mesh-delivery-teller/cmd/mesh-delivery-teller/teller_test.go
T
jschoubben 3d058af14c D1 (teller): the teller names its own module from its credential's
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
2026-11-12 22:47:50 +01:00

533 lines
20 KiB
Go

package main
import (
"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"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-teller/tellerevents"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-assigner/asks"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
stdio "git.novox.be/novox/mesh-sdk/go"
)
var now = time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC)
// nowIs sets the tests' clock now to at and returns what puts it back; a test sets it only as t.Cleanup(nowIs(at)), so no
// test leaves its clock to the next one (-shuffle runs them in any order).
func nowIs(at time.Time) (restore func()) {
was := now
now = at
return func() { now = was }
}
// memStore is a state bucket in memory with the revisions and the compare-and-set of the runtime's state.
type memStore struct {
entries map[string]*stdio.StateEntry
seq uint64
}
func (m *memStore) Get(key string) (*stdio.StateEntry, error) {
if e, ok := m.entries[key]; ok {
c := *e
return &c, nil
}
return nil, nil
}
func (m *memStore) put(key string, value any) (uint64, error) {
b, err := json.Marshal(value)
if err != nil {
return 0, err
}
m.seq++
m.entries[key] = &stdio.StateEntry{Key: key, Value: b, Revision: m.seq}
return m.seq, nil
}
func (m *memStore) Create(key string, value any) (uint64, error) {
if _, ok := m.entries[key]; ok {
return 0, stdio.ErrChanged
}
return m.put(key, value)
}
func (m *memStore) Update(key string, value any, revision uint64) (uint64, error) {
if e, ok := m.entries[key]; !ok || e.Revision != revision {
return 0, stdio.ErrChanged
}
return m.put(key, value)
}
func (m *memStore) Delete(key string) error { delete(m.entries, key); return nil }
type memAnswers struct {
written map[string][]byte
revs map[string]uint64
seq uint64
writes int
}
func (a *memAnswers) Get(key string) ([]byte, uint64, bool, error) {
v, ok := a.written[key]
return v, a.revs[key], ok, nil
}
// Write is the bucket's compare-and-set: a create of a key that has an answer, or an update at another revision, loses.
func (a *memAnswers) Write(key string, value []byte, rev uint64, found bool) (bool, error) {
_, has := a.written[key]
if found != has || (found && rev != a.revs[key]) {
return false, nil
}
a.seq++
a.writes++
if a.revs == nil {
a.revs = map[string]uint64{}
}
a.written[key], a.revs[key] = value, a.seq
return true, nil
}
type memGate map[string][]byte
func (g memGate) Get(key string) ([]byte, bool, error) { v, ok := g[key]; return v, ok, nil }
type published struct {
subject string
body json.RawMessage
id string
}
// bed is a teller with the occ.Client of the SDK on in-memory ends: what is published, the router's records, the
// warrants it would hear, and the conditions it says.
type bed struct {
t *Teller
client *occ.Client
store *memStore
answers *memAnswers
// assigner and view are the pictures of the assigner's asks and the view's answers the teller follows.
assigner, view memGate
pubs []published
conds []oc.Condition
records map[string]string
// seenIDs are the ids the fake router has taken an ask under, and dropped the asks it took a second time under: the
// messenger keeps an ask after it ends and returns for an ask whose id it holds (mesh-catalog modules/messenger
// cmd/messenger/asks.go:487-489, keepAsk), so a reused id reaches no phone.
seenIDs map[string]bool
dropped []string
// msgIDs are the bus message ids published, and busDropped the messages the bus dropped as a second under one.
msgIDs map[string]bool
busDropped []string
hear func(stdio.Envelope) error
logs strings.Builder
// emitted are the teller's own events said, as `<event> <key> <ask> <outcome>`.
emitted []string
}
func newBed(t *testing.T) *bed {
t.Helper()
b := &bed{store: &memStore{entries: map[string]*stdio.StateEntry{}}, answers: &memAnswers{written: map[string][]byte{}, revs: map[string]uint64{}},
assigner: memGate{}, view: memGate{}, records: map[string]string{}, seenIDs: map[string]bool{}, msgIDs: map[string]bool{}}
b.client = &occ.Client{Module: tellerModule, State: b.store, Now: func() time.Time { return now },
Publish: func(subject string, body any, id string) error {
raw, err := json.Marshal(body)
if b.msgIDs[id] {
// The bus drops a second message under an id it holds (JetStream's duplicate window): it reaches nobody.
b.busDropped = append(b.busDropped, id)
return err
}
b.msgIDs[id] = true
if subject == oc.AcceptSubjectAsk(tellerModule) {
var a struct {
ID string `json:"id"`
}
_ = json.Unmarshal(raw, &a)
if b.seenIDs[a.ID] {
b.dropped = append(b.dropped, a.ID)
} else if _, kept := b.records[a.ID]; !kept {
b.records[a.ID] = `{"state":"open"}` // the router keeps the ask it took (asks.go CreateAsk)
}
b.seenIDs[a.ID] = true
}
b.pubs = append(b.pubs, published{subject, raw, id})
return err
},
Record: func(id string) (*stdio.StateEntry, error) {
if v, ok := b.records[id]; ok {
return &stdio.StateEntry{Key: id, Value: json.RawMessage(v)}, nil
}
return nil, nil
},
Subscribe: func(_ string, handle func(stdio.Envelope) error) error { b.hear = handle; return nil },
}
b.t = &Teller{Module: tellerModule, Asker: b.client, Store: b.store, Answers: b.answers, Assigner: b.assigner, View: b.view, Publish: b.client.Publish, Now: func() time.Time { return now },
Say: func(c oc.Condition) error {
if _, err := occ.EncodeCondition(c); err != nil {
t.Errorf("a condition the router would refuse: %v", err)
}
b.conds = append(b.conds, c)
return nil
},
Logf: func(f string, a ...any) { fmt.Fprintf(&b.logs, f+"\n", a...) },
Emit: func(event string, body []byte, id string) error {
e, err := tellerevents.DecodeEnded(body)
if err != nil || id != event+"."+e.Ask {
t.Errorf("the event %s said under %s holds %s: %v", event, id, body, err)
}
if b.msgIDs[id] {
b.busDropped = append(b.busDropped, id) // the bus drops a second message under an id it holds
return nil
}
b.msgIDs[id] = true
b.emitted = append(b.emitted, strings.Join([]string{event, e.Key, e.Ask, e.Outcome}, " "))
return nil
}}
if err := b.client.Listen(b.t.Answer, b.t.Said); err != nil {
t.Fatal(err)
}
return b
}
// holdOf is the assigner's hold ask of module plex at the n-th fingerprint, written at its asking-th writing (its router id is
// AskingID(key, asking)), put in the bed's picture of the assigner's asks and handed to the teller as the watch would.
func (b *bed) holdOf(t *testing.T, n, asking int) (string, oc.Ask) {
t.Helper()
key, value, ask := holdAskAt(t, n, asking)
b.assigner[key] = value
b.t.OnAssignerAsk(key)
return key, ask
}
// holdAskAt is the assigner's hold ask at the n-th fingerprint and the asking-th writing, shaped as the assigner composes it
// (two options of level acknowledge that bind no act, so the router takes it).
func holdAskAt(t *testing.T, n, asking int) (string, []byte, oc.Ask) {
t.Helper()
key, err := asks.HoldAskKey("plex", "src2:"+strings.Repeat(string(rune('0'+n)), 64))
if err != nil {
t.Fatal(err)
}
_, _, ask := holdAsk(t)
ask.ID = meshdeliveryclient.AskingID(key, asking)
value, err := asks.EncodeAsk(key, asks.Ask{Ask: rawAsk(t, ask), Asking: asking})
if err != nil {
t.Fatal(err)
}
return key, value, ask
}
// rawAsk is the router's ask as the JSON a gate or assigner value carries (the seat's ask value).
func rawAsk(t *testing.T, a oc.Ask) json.RawMessage {
t.Helper()
b, err := json.Marshal(a)
if err != nil {
t.Fatal(err)
}
return b
}
// warrantFor is the router's warrant for a chosen option of an ask, as the router verified the operator.
func warrantFor(a oc.Ask, option string) oc.Warrant {
return oc.Warrant{Ask: a.ID, Asker: tellerModule, Outcome: occ.OutcomeChosen, Option: option, Label: option, Level: occ.Acknowledge,
By: &oc.Person{Who: occ.Operator, Kind: "telegram", Identity: "42", Verified: "user id"}, Channel: "telegram",
At: occ.FormatTime(now.Add(time.Hour)), AskDigest: occ.Digest(a)}
}
func (b *bed) deliver(t *testing.T, w oc.Warrant) {
t.Helper()
raw, _ := json.Marshal(w)
if err := b.hear(stdio.Envelope{Key: oc.Seat + ".decided." + tellerModule, Body: raw}); err != nil {
t.Fatal(err)
}
}
func (b *bed) askedOf(subject string) []published {
var out []published
for _, p := range b.pubs {
if p.subject == subject {
out = append(out, p)
}
}
return out
}
func TestAnAssignersKeyBecomesOneRouterAskAndDeletingItCancelsIt(t *testing.T) { // 1343/AC1
b := newBed(t)
key, value, ask := holdAskAt(t, 1, 1)
b.assigner[key] = value
b.t.OnAssignerAsk(key)
asked := b.askedOf(oc.AcceptSubjectAsk(tellerModule))
if len(asked) != 1 || asked[0].id != ask.ID {
t.Fatalf("published %+v, want one ask under %s with id %s", b.pubs, tellerModule, ask.ID)
}
b.t.OnAssignerAsk(key) // the key written again with the same ask, or heard again at a restart
if n := len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))); n != 1 {
t.Errorf("the ask was published %d times", n)
}
delete(b.assigner, key)
b.t.OnAssignerAskGone(key)
cancels := b.askedOf(oc.AcceptSubjectCancel(tellerModule))
if len(cancels) != 1 || string(cancels[0].body) != `{"id":"`+ask.ID+`"}` {
t.Fatalf("cancels = %+v", cancels)
}
b.t.OnAssignerAskGone(key)
if n := len(b.askedOf(oc.AcceptSubjectCancel(tellerModule))); n != 1 {
t.Errorf("the ask was cancelled %d times", n)
}
// Issue 774: teller_end_ask ends one by hand, named by its key or its router id; the router's word that it ended asks the
// one waiting for room again (the assigner's asks hold at most mostAssignerOpen places, the third waits).
for _, c := range []struct {
name string
by func(key string, ask oc.Ask) string
}{
{"774: ended by hand, named by its key", func(key string, _ oc.Ask) string { return key }},
{"774: ended by hand, named by its router id", func(_ string, ask oc.Ask) string { return ask.ID }},
} {
t.Run(c.name, func(t *testing.T) {
b := newBed(t)
k1, first := b.holdOf(t, 1, 1)
b.holdOf(t, 2, 1)
_, third := b.holdOf(t, 3, 1)
r := b.t.EndAsk(c.by(k1, first), "the hold no longer holds", "lead@shanks")
cancels := b.askedOf(oc.AcceptSubjectCancel(tellerModule))
if !r.Ended || r.ID != first.ID || r.Key != k1 || len(cancels) != 1 || string(cancels[0].body) != `{"id":"`+first.ID+`"}` {
t.Fatalf("end = %+v, cancels %+v", r, cancels)
}
b.deliver(t, oc.Warrant{Ask: first.ID, Asker: tellerModule, Outcome: occ.OutcomeCancelled, At: occ.FormatTime(now), AskDigest: occ.Digest(first)})
if got := b.askedIDs(); len(got) != 3 || got[2] != third.ID {
t.Errorf("asks = %v, want the waiting %s asked once the ask ended by hand left", got, third.ID)
}
if again := b.t.EndAsk(k1, "again", "lead@shanks"); again.Ended || len(b.askedOf(oc.AcceptSubjectCancel(tellerModule))) != 1 {
t.Errorf("a second end = %+v: an ended ask is left", again)
}
})
}
t.Run("774: an ask waiting for room is dropped from the wait; a name the teller holds no ask under is said", func(t *testing.T) {
b := newBed(t)
_, first := b.holdOf(t, 1, 1)
b.holdOf(t, 2, 1)
_, third := b.holdOf(t, 3, 1)
if r := b.t.EndAsk(third.ID, "asked about what no longer holds", "lead@shanks"); !r.Ended || len(b.askedOf(oc.AcceptSubjectCancel(tellerModule))) != 0 {
t.Fatalf("end of a waiting ask = %+v", r)
}
b.deliver(t, warrantFor(first, "keep"))
if got := b.askedIDs(); len(got) != 2 {
t.Errorf("asks = %v: the ask ended while it waited was asked again", got)
}
if r := b.t.EndAsk("hold.nothing.here", "a typo", "lead@shanks"); r.Ended || !strings.Contains(r.Says, "holds no ask") {
t.Errorf("end of an unknown ask = %+v", r)
}
})
}
// ADR 0596 §2: the teller says answered after each answer it writes, under one message id per ask, and says it again for an
// answer written whose event was not said.
func TestEveryAnswerWrittenIsSaidAsTheEventAnswered(t *testing.T) {
b := newBed(t)
var said []string
fail := true
b.t.Answered = func(key, askID string, answer []byte) error {
if fail {
return fmt.Errorf("the bus did not answer")
}
said = append(said, answeredID(key, askID)+" "+string(answer))
return nil
}
key, ask := b.holdOf(t, 1, 1)
b.deliver(t, warrantFor(ask, "keep"))
if len(said) != 0 || b.answers.writes != 1 {
t.Fatalf("said %v with the bus down, written %d times", said, b.answers.writes)
}
fail = false
if err := b.t.writeAnswer(key, ask.ID, b.answers.written[answerKey(key)], "again"); err != nil { // the answer is there; its event was not said
t.Fatal(err)
}
if len(said) != 1 || b.answers.writes != 1 {
t.Fatalf("said %v, written %d times; want the event said once and the answer written once", said, b.answers.writes)
}
raw := b.answers.written[answerKey(key)]
if want := answeredID(key, ask.ID) + " " + string(raw); said[0] != want {
t.Errorf("said %q, want %q", said[0], want)
}
}
func TestAWarrantThatDoesNotHoldWritesNoAnswerAndRaisesTheCondition(t *testing.T) { // 1343/AC3
cases := map[string]func(w *oc.Warrant){
"an asker that differs": func(w *oc.Warrant) { w.Asker = "mesh-delivery" },
"a digest that differs": func(w *oc.Warrant) { w.AskDigest = "sha256:0000" },
"an option the ask lacks": func(w *oc.Warrant) { w.Option = "delete" },
}
for name, change := range cases {
t.Run(name, func(t *testing.T) {
b := newBed(t)
key, ask := b.holdOf(t, 1, 1)
w := warrantFor(ask, "keep")
change(&w)
b.deliver(t, w)
if len(b.answers.written) != 0 {
t.Errorf("an answer was written: %v", b.answers.written)
}
if len(b.conds) != 1 || b.conds[0].State != occ.StateRaised || b.conds[0].Subject.ID != key || b.conds[0].Subject.Scope != "delivery" ||
!strings.HasPrefix(b.conds[0].Explanation, occ.NeedsYou) || strings.Contains(b.conds[0].Explanation, "merge") {
t.Fatalf("conditions = %+v", b.conds)
}
})
}
}
// design 47 G §653, A-172: the teller carries no merge ask. A router ask it holds under a key that is no assigner key (a merge
// ask kept before the Approve per merge went) answers nothing, and a merge ask waiting for room is dropped from the wait.
func TestAMergeAskOfBeforeTheApprovePerMergeWentAnswersNothingAndWaitsNoMore(t *testing.T) {
b := newBed(t)
_, _, ask := holdAskAt(t, 1, 1)
mergeKey := "merge.g.0123456789ab"
ask.ID = meshdeliveryclient.AskID(mergeKey)
if err := b.t.note(ask.ID, mergeKey, 3, nil); err != nil {
t.Fatal(err)
}
if err := b.client.Ask(ask); err != nil {
t.Fatal(err)
}
if ws, rec, _ := b.t.waiting(); rec != nil || len(ws) != 0 {
t.Fatalf("the wait holds %v", ws)
}
b.refuse(t, ask.ID, roomRefusal) // it waits for room, as a merge ask did
b.deliver(t, warrantFor(ask, "keep"))
if len(b.answers.written) != 0 {
t.Errorf("a merge ask was answered: %v", b.answers.written)
}
b.t.OnCurrent() // the start: the wait is read, and the merge ask is dropped, not asked again
if got := b.askedIDs(); len(got) != 1 {
t.Errorf("asks = %v: a merge ask was asked again", got)
}
if ws, _, _ := b.t.waiting(); len(ws) != 0 {
t.Errorf("the wait still holds %+v", ws)
}
}
func TestAGoodAnswerClearsTheConditionOfAnAskAskedAgain(t *testing.T) { // 1343/AC3 (cleared when a good answer is written)
b := newBed(t)
key, bad := b.holdOf(t, 1, 1)
w := warrantFor(bad, "keep")
w.AskDigest = "sha256:0000"
b.deliver(t, w)
if len(b.conds) != 1 || b.conds[0].State != occ.StateRaised {
t.Fatalf("conditions = %+v", b.conds)
}
// The assigner writes the ask again at a new asking, under a new id.
_, value, good := holdAskAt(t, 1, 2)
b.assigner[key] = value
b.t.OnAssignerAsk(key)
if n := len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))); n != 2 {
t.Fatalf("the ask was published %d times, want again at the new asking", n)
}
b.deliver(t, warrantFor(good, "keep"))
if _, ok := b.answers.written[answerKey(key)]; !ok {
t.Fatalf("no answer: %v\n%s", b.answers.written, b.logs.String())
}
if len(b.conds) != 2 || b.conds[1].State != occ.StateCleared || b.conds[1].Key != b.conds[0].Key {
t.Errorf("conditions = %+v", b.conds)
}
}
func TestAWarrantComingWhileTheTellerWasAwayIsReadFromTheRouter(t *testing.T) {
b := newBed(t)
key, ask := b.holdOf(t, 1, 1)
w, _ := json.Marshal(warrantFor(ask, "keep"))
b.records[ask.ID] = `{"state":"chosen","warrant":` + string(w) + `}`
b.t.OnAssignerAsk(key) // the teller starts again and reads the key
if _, ok := b.answers.written[answerKey(key)]; !ok {
t.Errorf("no answer: %s", b.logs.String())
}
}
func TestARewriteWithAskingTwoCancelsAskingOneAndAsksUnderTheNewID(t *testing.T) { // G2 of review round 1
b := newBed(t)
key, g1 := b.holdOf(t, 1, 1)
_, two, g2 := holdAskAt(t, 1, 2)
if g1.ID == g2.ID {
t.Fatal("the two askings share an id")
}
b.assigner[key] = two
b.t.OnAssignerAsk(key)
cancels := b.askedOf(oc.AcceptSubjectCancel(tellerModule))
if len(cancels) != 1 || string(cancels[0].body) != `{"id":"`+g1.ID+`"}` {
t.Fatalf("cancels = %+v, want asking 1's router ask", cancels)
}
asked := b.askedOf(oc.AcceptSubjectAsk(tellerModule))
if len(asked) != 2 || asked[1].id != g2.ID {
t.Fatalf("asks = %+v, want the second under %s", asked, g2.ID)
}
if len(b.dropped) != 0 {
t.Errorf("the router dropped asks under a reused id: %v", b.dropped)
}
// The same key again, and a warrant for the first asking (the assigner has moved on), change nothing.
b.t.OnAssignerAsk(key)
b.deliver(t, warrantFor(g1, "keep"))
if len(b.answers.written) != 0 || len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))) != 2 {
t.Errorf("answers %v asks %d", b.answers.written, len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))))
}
// The warrant of the second names it: its answer's warrant is the router id and the time.
w := warrantFor(g2, "keep")
b.deliver(t, w)
raw, ok := b.answers.written[answerKey(key)]
a, err := meshdeliveryclient.DecodeAnswer(raw)
if !ok || err != nil || a.Warrant != warrantID(w) {
t.Errorf("answer %+v (%v) err %v", a, ok, err)
}
}
func TestAKeyWhoseValueIsNotItsOwnAskIsLeft(t *testing.T) {
b := newBed(t)
key, _, _ := holdAskAt(t, 1, 1)
b.assigner[key] = []byte(`{"v":1`)
b.t.OnAssignerAsk(key)
if len(b.pubs) != 0 || !strings.Contains(b.logs.String(), "the ask is not raised") {
t.Errorf("published %+v; log:\n%s", b.pubs, b.logs.String())
}
}
func TestARefusedAskIsSaidAsACondition(t *testing.T) { // ADR 0437 §9
b := newBed(t)
_, ask := b.holdOf(t, 1, 1)
b.deliver(t, oc.Warrant{Ask: ask.ID, Asker: tellerModule, Outcome: occ.OutcomeRefused, Words: "no channel can send", At: occ.FormatTime(now)})
if len(b.conds) != 1 || b.conds[0].State != occ.StateRaised || !strings.Contains(b.conds[0].Summary, "no channel can send") {
t.Errorf("conditions = %+v", b.conds)
}
}
func TestAnAnswerToAnEarlierAskingDoesNotBlockTheNextAsking(t *testing.T) { // R2-1 of review round 2
b := newBed(t)
key, g1 := b.holdOf(t, 1, 1)
b.deliver(t, warrantFor(g1, "keep"))
first, ok := b.answers.written[answerKey(key)]
if a, err := meshdeliveryclient.DecodeAnswer(first); !ok || err != nil || !strings.HasPrefix(a.Warrant, g1.ID+"@") {
t.Fatalf("asking 1's answer: %+v %v %v", a, ok, err)
}
// The assigner writes the key again at asking 2. Asking 1's answer stays in the bucket.
_, two, g2 := holdAskAt(t, 1, 2)
b.assigner[key] = two
b.t.OnAssignerAsk(key)
asked := b.askedOf(oc.AcceptSubjectAsk(tellerModule))
if len(asked) != 2 || asked[1].id != g2.ID {
t.Fatalf("asks = %+v, want asking 2 asked under %s", asked, g2.ID)
}
w := warrantFor(g2, "release")
b.deliver(t, w)
a, err := meshdeliveryclient.DecodeAnswer(b.answers.written[answerKey(key)])
if err != nil || a.Warrant != warrantID(w) {
t.Fatalf("the key holds %+v (%v), want asking 2's answer", a, err)
}
// A second warrant for the same asking writes nothing, and a replay of asking 2 asks nothing.
w2 := w
w2.At = occ.FormatTime(now.Add(time.Hour + time.Minute))
b.deliver(t, w2)
b.t.OnAssignerAsk(key)
if b.answers.writes != 2 || len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))) != 2 || len(b.dropped) != 0 {
t.Errorf("writes %d asks %d dropped %v", b.answers.writes, len(b.askedOf(oc.AcceptSubjectAsk(tellerModule))), b.dropped)
}
}