package operatorchannelclient import ( "encoding/json" "errors" "strings" "testing" "time" seat "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/approval" "git.novox.be/novox/mesh-sdk/go/process" ) type mem struct { vals map[string]json.RawMessage revs map[string]uint64 n uint64 } func (m *mem) Get(k string) (*stdio.StateEntry, error) { v, ok := m.vals[k] if !ok { return nil, nil } return &stdio.StateEntry{Key: k, Value: v, Revision: m.revs[k]}, nil } func (m *mem) Create(k string, v any) (uint64, error) { if _, ok := m.vals[k]; ok { return 0, stdio.ErrChanged } return m.put(k, v) } func (m *mem) Update(k string, v any, rev uint64) (uint64, error) { if rev == 0 || m.revs[k] != rev { return 0, stdio.ErrChanged } return m.put(k, v) } func (m *mem) put(k string, v any) (uint64, error) { raw, _ := json.Marshal(v) m.n++ m.vals[k], m.revs[k] = raw, m.n return m.n, nil } func client() (*Client, map[string][]string) { sent := map[string][]string{} c := &Client{Module: "an-asker", State: &mem{vals: map[string]json.RawMessage{}, revs: map[string]uint64{}}, Now: func() time.Time { return now }, Publish: func(subject string, body any, id string) error { sent[subject] = append(sent[subject], id) return nil }} return c, sent } // releaseHQ is the act the ask's one option binds. var releaseHQ = map[string]string{"verb": "release", "delivery": "hq"} func askedHeld() seat.Ask { binds, _ := ActDigest(releaseHQ) return seat.Ask{ID: "d-1", Headline: "Delivery of hq held", Explanation: "Needs you: release it, or stop it.", Who: Operator, Expires: FormatTime(now.Add(time.Hour)), OnExpiry: "the delivery stays held", Options: []seat.Option{{ID: "release", Label: "Release", Does: "it goes on", Level: Approve, Binds: binds}}} } func askedWarrant() seat.Warrant { return seat.Warrant{Ask: "d-1", Asker: "an-asker", Outcome: OutcomeChosen, Option: "release", Label: "Release", Level: Approve, At: FormatTime(now.Add(time.Minute)), AskDigest: Digest(askedHeld()), By: &seat.Person{Who: Operator, Kind: "telegram", Identity: "42", Verified: "user id verified"}} } func TestAnAskIsKeptThenPublishedUnderTheModulesOwnName(t *testing.T) { var _ Store = process.State{} // a process connection's state keeps the asks (issue 1188 AC2) c, sent := client() if err := c.Ask(askedHeld()); err != nil { t.Fatal(err) } if got := sent[seat.AcceptSubjectAsk("an-asker")]; len(got) != 1 || got[0] != "d-1" { t.Fatalf("%v", sent) } if err := c.Ask(askedHeld()); err == nil || !strings.Contains(err.Error(), "already made") { t.Errorf("the same id was asked twice: %v", err) } bad := askedHeld() bad.Who = "agent" if err := c.Ask(bad); err == nil { t.Error("an ask the contract refuses was published") } t.Run("AKeyPrefixIsPutBeforeEveryKeyOfTheClientsOwnStateAndNotBeforeWhere", func(t *testing.T) { for _, tc := range []struct{ prefix, key string }{{"n1.", "n1.ask.d-1"}, {"", "ask.d-1"}} { c, _ := client() store := c.State.(*mem) c.KeyPrefix = tc.prefix var asked string c.Record = func(k string) (*stdio.StateEntry, error) { asked = k; return nil, nil } if err := c.Ask(askedHeld()); err != nil { t.Fatal(err) } if _, ok := store.vals[tc.key]; len(store.vals) != 1 || !ok { t.Fatalf("prefix %q: keys written %v, want %s", tc.prefix, store.vals, tc.key) } // Design 46 7-approval-mark §13: the act and the call's arguments kept beside the ask stay as Take marks it. e, _ := store.Get(tc.key) var k Kept _ = json.Unmarshal(e.Value, &k) k.Act, k.Arguments = releaseHQ, json.RawMessage(`{"delivery":"hq"}`) if _, err := store.Update(tc.key, k, e.Revision); err != nil { t.Fatal(err) } if h, err := c.Take(askedWarrant(), func(seat.Option, seat.Warrant) error { return nil }); h != Acted || err != nil { t.Fatalf("prefix %q: the warrant was not read from %s: %s %v", tc.prefix, tc.key, h, err) } raw := string(store.vals[tc.key]) if !strings.Contains(raw, `"act":{"delivery":"hq","verb":"release"}`) || !strings.Contains(raw, `"arguments":{"delivery":"hq"}`) || strings.Contains(raw, `"recorded"`) { t.Errorf("prefix %q: the kept ask after Take is %s", tc.prefix, raw) } if _, _, err := c.Where("an-asker.d-1"); err != nil || asked != "an-asker.d-1" { t.Errorf("prefix %q: Where read %q", tc.prefix, asked) } } }) // Design 47 G §700, A-91: Where reads the router's record as the contract's typed value, its warrant included. t.Run("WhereReadsTheRecordsWarrantTyped", func(t *testing.T) { c, _ := client() rec := seat.AsksByAskerIDValue{Key: "an-asker.d-1", Asker: "an-asker", State: "chosen", Warrant: &seat.Warrant{Ask: "d-1", Asker: "an-asker", Outcome: seat.WarrantOutcomeChosen, Option: "ok"}} raw, _ := json.Marshal(rec) c.Record = func(string) (*stdio.StateEntry, error) { return &stdio.StateEntry{Value: raw}, nil } state, w, err := c.Where("d-1") if err != nil || state != "chosen" || w == nil || w.Option != "ok" { t.Fatalf("Where = %q, %+v, %v; want chosen and the record's warrant", state, w, err) } }) } func TestAWarrantIsActedOnOnceAndOnlyForItsOwnAsk(t *testing.T) { c, _ := client() _ = c.Ask(askedHeld()) acted := 0 act := func(o seat.Option, _ seat.Warrant) error { if err := Performs(o, releaseHQ); err != nil { t.Errorf("the bound act: %v", err) } acted++ return nil } if h, err := c.Take(askedWarrant(), act); h != Acted || err != nil || acted != 1 { t.Fatalf("%s %v %d", h, err, acted) } if h, _ := c.Take(askedWarrant(), act); h != Done || acted != 1 { t.Errorf("a redelivery was acted on: %s", h) } for why, change := range map[string]func(*seat.Warrant){ "another asker": func(w *seat.Warrant) { w.Asker = "mesh-controller" }, "an ask not made": func(w *seat.Warrant) { w.Ask = "d-9" }, "another level": func(w *seat.Warrant) { w.Level = Acknowledge }, "an option not offered": func(w *seat.Warrant) { w.Option = "delete" }, "after its expiry": func(w *seat.Warrant) { w.At = FormatTime(now.Add(2 * time.Hour)) }, "another ask's digest": func(w *seat.Warrant) { w.AskDigest = "sha256:00" }, } { c2, _ := client() _ = c2.Ask(askedHeld()) w := askedWarrant() change(&w) if h, _ := c2.Take(w, act); h == Acted { t.Errorf("a warrant from %s was acted on", why) } } if acted != 1 { t.Errorf("acted %d times", acted) } // The gate's channel (design 47 G lead answers A-219, A-228): the gate's ask raised to the operator at the level approve, // the router's record read in the gate's form with its warrant whole, and a warrant claimed once, only for the act its // option binds. t.Run("TheGateChannelTranslatesTheGatesForms", func(t *testing.T) { st := &mem{vals: map[string]json.RawMessage{}, revs: map[string]uint64{}} records := map[string]seat.AsksByAskerIDValue{} g := &GateChannel{State: st, KeyPrefix: "n1.", Now: func() time.Time { return now }, Publish: func(module, subject string, body any, id string) error { if subject != seat.AcceptSubjectAsk(module) { t.Fatalf("published on %s", subject) } return nil }, ReadRecord: func(module, id string) (*stdio.StateEntry, error) { rec, ok := records[module+"."+id] if !ok { return nil, nil } raw, _ := json.Marshal(rec) return &stdio.StateEntry{Value: raw}, nil }} digest, _ := ActDigest(releaseHQ) a := approval.Ask{ID: "a1", About: digest, Headline: "Run wipe?", Explanation: "Wipes.", Expires: FormatTime(now.Add(time.Hour)), OnExpiry: "nothing runs", Options: []approval.Option{{ID: "approve", Label: "Approve", Does: "runs", Binds: digest}}} if err := g.Ask("shell", a); err != nil { t.Fatal(err) } var k Kept if e, _ := st.Get("n1.ask.a1"); e == nil || json.Unmarshal(e.Value, &k) != nil || k.Ask.Who != Operator || k.Ask.Options[0].Level != Approve { t.Fatalf("kept %+v", k) } if rec, err := g.Record("shell", "a1"); rec != nil || err != nil { t.Fatalf("a record not yet there: %+v %v", rec, err) } w := seat.Warrant{Ask: "a1", Asker: "shell", Outcome: OutcomeChosen, Option: "approve", Level: Approve, At: FormatTime(now), AskDigest: Digest(k.Ask), Channel: "telegram", By: &seat.Person{Who: Operator, Kind: "telegram"}} records["shell.a1"] = seat.AsksByAskerIDValue{Asker: "shell", State: "chosen", Opened: FormatTime(now), Warrant: &w} rec, err := g.Record("shell", "a1") if err != nil || rec == nil || rec.State != "chosen" || rec.Warrant == nil || rec.Warrant.Channel != "telegram" || rec.Warrant.Option != "approve" { t.Fatalf("record %+v %v", rec, err) } if h, err := g.Claim("shell", *rec.Warrant, map[string]string{"verb": "other"}, func() { t.Fatal("ran another act") }); h != approval.Claimed || err == nil { t.Fatalf("another act: %s %v", h, err) } delete(st.vals, "n1.ask.a1") _ = g.Ask("shell", a) runs := 0 for i := 0; i < 2; i++ { h, err := g.Claim("shell", *rec.Warrant, releaseHQ, func() { runs++ }) if want := []approval.Claim{approval.Claimed, approval.ClaimDone}[i]; h != want || err != nil { t.Fatalf("claim %d: %s %v", i, h, err) } } if runs != 1 || g.Decided("shell") != seat.SubjectDecided("shell") { t.Fatalf("runs %d", runs) } }) // The gate's channel over a process connection (design 47 G lead answers A-272, A-273): an ask and its cancel go out as // accepted kinds of the seat operator-channel with the ask's id as the message id, the router's record is the get of // `.` in the state asks of the seat's holder, and nothing else is reached: another subject, or a seat with no // holder, is refused. t.Run("TheGateChannelOverAConnectionAsksAndReadsOnlyThroughTheSeat", func(t *testing.T) { type sent struct{ seat, kind, id string } var out []sent accept := func(s, kind string, _ any, opts ...stdio.EmitOptions) error { out = append(out, sent{s, kind, opts[0].MessageID}) return nil } raw, _ := json.Marshal(seat.AsksByAskerIDValue{Asker: "shell", State: "open", Opened: FormatTime(now)}) vals := map[string]json.RawMessage{"messenger_holder.asks|shell.a1": raw, "other.asks|shell.a1": json.RawMessage(`{"state":"wrong"}`)} read := func(r string) asksRead { return readOf{state: r, vals: vals} } holder := func() (string, error) { return "messenger_holder", nil } st := &mem{vals: map[string]json.RawMessage{}, revs: map[string]uint64{}} g := gateChannelOver(accept, read, st, "n1.", holder) g.Now = func() time.Time { return now } digest, _ := ActDigest(releaseHQ) a := approval.Ask{ID: "a1", About: digest, Headline: "Run wipe?", Explanation: "Wipes.", Expires: FormatTime(now.Add(time.Hour)), OnExpiry: "nothing runs", Options: []approval.Option{{ID: "approve", Label: "Approve", Does: "runs", Binds: digest}}} if err := g.Ask("shell", a); err != nil { t.Fatal(err) } if err := g.Cancel("shell", "a1"); err != nil { t.Fatal(err) } if len(out) != 2 || out[0] != (sent{seat.Seat, seat.AcceptAsk, "a1"}) || out[1] != (sent{seat.Seat, seat.AcceptCancel, "cancel.a1"}) { t.Fatalf("sent %+v, want the ask and its cancel on the seat's accepts", out) } if rec, err := g.Record("shell", "a1"); err != nil || rec == nil || rec.State != "open" { t.Fatalf("record %+v %v, want the one in the holder's state asks", rec, err) } if rec, err := g.Record("shell", "zz"); err != nil || rec != nil { t.Fatalf("a record not there: %+v %v", rec, err) } if err := g.Publish("shell", "mesh.seat.operator-channel.accept.ask.other", nil, "x"); err == nil { t.Fatal("an accept subject naming another caller was sent") } for _, c := range []func() (string, error){func() (string, error) { return "", nil }, func() (string, error) { return "", errors.New("unread") }} { if _, err := gateChannelOver(accept, read, st, "n1.", c).Record("shell", "a1"); err == nil { t.Fatal("a record was read with no holder of the seat") } } }) } func TestAnAskEndedWithoutAChoiceIsRecordedAndNothingDone(t *testing.T) { c, _ := client() _ = c.Ask(askedHeld()) w := askedWarrant() w.Outcome, w.Option, w.By = OutcomeExpired, "", nil if h, err := c.Take(w, func(seat.Option, seat.Warrant) error { t.Fatal("acted"); return nil }); h != Recorded || err != nil { t.Fatalf("%s %v", h, err) } if h, _ := c.Take(askedWarrant(), func(seat.Option, seat.Warrant) error { t.Fatal("acted after it ended"); return nil }); h != Done { t.Errorf("%s", h) } t.Run("AnAskTheRouterRefusedEndsTheRequestWithItsWords", func(t *testing.T) { c, _ := client() _ = c.Ask(askedHeld()) w := askedWarrant() w.Outcome, w.Option, w.By, w.Words = OutcomeRefused, "", nil, "its expiry passes the bound of its level" h, err := c.Take(w, func(seat.Option, seat.Warrant) error { t.Fatal("acted"); return nil }) if h != Refused || err == nil || !strings.Contains(err.Error(), w.Words) { t.Fatalf("%s %v, want refused with the router's words", h, err) } if h, _ := c.Take(askedWarrant(), func(seat.Option, seat.Warrant) error { t.Fatal("acted after it ended"); return nil }); h != Done { t.Errorf("the refused ask was not closed: %s", h) } }) }