oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "net/http"
8 "sync"
9 "testing"
10
11 "amadan.net/oficina/home/connect"
12 "amadan.net/oficina/memoria/internal/memoria/seal"
13 "amadan.net/rastrillo/rastrillo/db"
14)
15
16func reopenAgentNoteFixture(t *testing.T, f *homeRouterFixture, closeOld bool) *homeRouterFixture {
17 t.Helper()
18 var path string
19 if e := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
20 t.Fatal(e)
21 }
22 if closeOld {
23 f.app.store.ix.Close()
24 f.app.db.Close()
25 }
26 d, e := db.Open(path, f.app.logger)
27 if e != nil {
28 t.Fatal(e)
29 }
30 t.Cleanup(func() { d.Close() })
31 cipher, e := seal.New(bytes.Repeat([]byte{6}, 32))
32 if e != nil {
33 t.Fatal(e)
34 }
35 mux, a, e := App(d, homeTestOrigin, cipher, f.app.logger)
36 if e != nil {
37 t.Fatal(e)
38 }
39 t.Cleanup(func() { a.store.ix.Close() })
40 a.SetOwners([]string{"alice@example.test"})
41 auth, e := NewAuth(d.Writer(), AuthEnv{Origin: homeTestOrigin, InstanceKey: "isolated-test-instance-key", Mailer: f.mail, HomeEnabled: true}, f.app.logger, a)
42 if e != nil {
43 t.Fatal(e)
44 }
45 a.UseAuth(auth)
46 cfg := Config{Origin: homeTestOrigin, Home: &connect.DecodedCredentials{Issuer: homeTestIssuer, ConsumerID: "memoria-test", Keys: map[string][]byte{"key": f.key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}}
47 if e = a.WireHome(mux, cfg); e != nil {
48 t.Fatal(e)
49 }
50 a.MountAuth(mux, homeTestOrigin)
51 return &homeRouterFixture{a, mux, f.key, f.mail, map[string]*http.Cookie{}}
52}
53func agentNoteResultFrom(t *testing.T, code int, raw []byte) agentNoteResult {
54 t.Helper()
55 var out agentNoteResult
56 if code != 200 || json.Unmarshal(raw, &out) != nil || out.ID <= 0 {
57 t.Fatalf("note create: %d %s", code, raw)
58 }
59 return out
60}
61func TestAgentNotePostcommitRecoveryPreservesEditsAndDeletion(t *testing.T) {
62 for _, stage := range []string{"index", "index-receipt"} {
63 t.Run(stage, func(t *testing.T) {
64 f, p := linkedAgentFixture(t)
65 active := true
66 h := mountAgentFixture(t, f, &p, &active)
67 if stage == "index" {
68 f.app.store.ix.Close()
69 } else {
70 if _, e := f.app.db.Writer().Exec("CREATE TRIGGER fail_index_receipt BEFORE UPDATE OF indexed ON memoria_agent_notes WHEN OLD.document_id IS NOT NULL BEGIN SELECT RAISE(ABORT,'injected'); END"); e != nil {
71 t.Fatal(e)
72 }
73 }
74 rec := agentCall(h, "notes_create", agentNoteInput)
75 made := agentNoteResultFrom(t, rec.Code, rec.Body.Bytes())
76 if made.Indexed {
77 t.Fatal("uncertain index reported complete")
78 }
79 var receiptID int64
80 if e := f.app.db.Writer().QueryRow("SELECT document_id FROM memoria_agent_notes").Scan(&receiptID); e != nil || receiptID != made.ID {
81 t.Fatal("body committed without receipt", e)
82 }
83 key := agentNoteCoordinate(t, f.app, p)
84 id, e := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "agent-" + key, Title: "Edited note", Body: "Later edits survive all initial retries"})
85 if id != made.ID || e != nil && !errors.Is(e, ErrIndexLag) {
86 t.Fatal("browser edit", id, e)
87 }
88 restarted := reopenAgentNoteFixture(t, f, true)
89 h = mountAgentFixture(t, restarted, &p, &active)
90 rec = agentCall(h, "notes_create", agentNoteInput)
91 got := agentNoteResultFrom(t, rec.Code, rec.Body.Bytes())
92 if got.ID != made.ID || got.Indexed {
93 t.Fatal("retry changed historical index result", got)
94 }
95 var d Document
96 if e = restarted.app.db.G.First(&d, made.ID).Error; e != nil {
97 t.Fatal(e)
98 }
99 body, e := restarted.app.store.sealer.Open(seal.PurposeBody, d.SealedBody)
100 if e != nil || string(body) != "Later edits survive all initial retries" || d.Revision != 2 {
101 t.Fatal("retry overwrote later edit", d.Revision, e)
102 }
103 if e = restarted.app.store.Delete(t.Context(), made.ID); e != nil {
104 t.Fatal(e)
105 }
106 if rec = agentCall(h, "notes_create", agentNoteInput); rec.Code != 404 {
107 t.Fatal("deleted note retry", rec.Code)
108 }
109 var n int
110 if e = restarted.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&n); e != nil || n != 0 {
111 t.Fatal("deleted note recreated", n, e)
112 }
113 })
114 }
115}
116func TestAgentNoteIndependentInstancesFirstCreate(t *testing.T) {
117 first, p := linkedAgentFixture(t)
118 active := true
119 h1 := mountAgentFixture(t, first, &p, &active)
120 second := reopenAgentNoteFixture(t, first, false)
121 h2 := mountAgentFixture(t, second, &p, &active)
122 start := make(chan struct{})
123 results := make(chan agentNoteResult, 2)
124 var wg sync.WaitGroup
125 for _, h := range []http.Handler{h1, h2} {
126 wg.Add(1)
127 go func(h http.Handler) {
128 defer wg.Done()
129 <-start
130 rec := agentCall(h, "notes_create", agentNoteInput)
131 results <- agentNoteResultFrom(t, rec.Code, rec.Body.Bytes())
132 }(h)
133 }
134 close(start)
135 wg.Wait()
136 close(results)
137 var id int64
138 count := 0
139 for result := range results {
140 count++
141 if id == 0 {
142 id = result.ID
143 }
144 if id != result.ID {
145 t.Fatal("independent writers duplicated", id, result.ID)
146 }
147 }
148 if count != 2 {
149 t.Fatal("missing concurrent result")
150 }
151 for _, table := range []string{"documents", "memoria_agent_notes"} {
152 var n int
153 if e := first.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 1 {
154 t.Fatal("duplicate durable effect", table, n, e)
155 }
156 }
157}
158