oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "reflect"
9 "strconv"
10 "sync"
11 "testing"
12
13 access "amadan.net/oficina/agent-access.git"
14 "amadan.net/oficina/home/teammode"
15 "amadan.net/oficina/sheets/internal/sheets/store"
16 "github.com/google/uuid"
17)
18
19func rangeEdit(m sheetAgentCreated) sheetAgentSetRange {
20 return sheetAgentSetRange{Team: "blue", SheetID: m.SheetID, TabID: m.TabID, ExpectedRevision: m.Revision, ClientID: uuid.NewString(), Cells: []sheetAgentCell{{Row: 0, Column: 0, Raw: "32"}, {Row: 0, Column: 1, Raw: ""}}}
21}
22func editCounts(t *testing.T, f *sheetAgentFixture) []int64 {
23 t.Helper()
24 var out []int64
25 for _, name := range []string{"cells", "rows", "cols", "events", "sheets_agent_edits"} {
26 var n int64
27 if e := f.a.app.db.Table(name).Count(&n).Error; e != nil {
28 t.Fatal(e)
29 }
30 out = append(out, n)
31 }
32 return out
33}
34func TestAgentRangeEditParityAndLaterRetry(t *testing.T) {
35 f := newSheetAgentFixture(t)
36 made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
37 id, _ := sheetAgentID(made.TabID)
38 h, e := store.Open(f.a.app.db, f.a.app.sealer, id)
39 if e != nil {
40 t.Fatal(e)
41 }
42 defer h.Release()
43 in := rangeEdit(made)
44 sub := f.a.app.hub.Subscribe(id)
45 defer sub.Close()
46 ack := decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
47 select {
48 case msg := <-sub.C():
49 if !bytes.Contains(msg.Data, []byte("64")) {
50 t.Fatal("incomplete native publication", string(msg.Data))
51 }
52 default:
53 t.Fatal("missing native publication")
54 }
55 snap, e := h.ReadRange(0, 0, 2, 2)
56 if e != nil {
57 t.Fatal(e)
58 }
59 b, _ := json.Marshal(snap)
60 if !bytes.Contains(b, []byte("64")) || snap.Version != h.Version() || ack.Revision != strconv.FormatUint(snap.Version, 10) {
61 t.Fatal("native formula/revision mismatch", string(b), ack)
62 }
63 // A browser's native batch after our commit must never be overwritten by replay.
64 if _, e = h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "75"}}, 1); e != nil {
65 t.Fatal(e)
66 }
67 before := editCounts(t, f)
68 version := h.Version()
69 if replay := decodeSheetCreated(t, f.call(t, "sheets_set_range", in)); replay != ack {
70 t.Fatal("receipt changed", replay, ack)
71 }
72 select {
73 case <-sub.C():
74 t.Fatal("retry published a duplicate edit")
75 default:
76 }
77 if !reflect.DeepEqual(before, editCounts(t, f)) || h.Version() != version {
78 t.Fatal("retry applied another edit")
79 }
80 read := f.call(t, "sheets_get_range", f.rangeInput(made))
81 if read.Code != 200 || !bytes.Contains(read.Body.Bytes(), []byte("150")) {
82 t.Fatal("later browser value lost", read.Body.String())
83 }
84 stale := in
85 stale.ClientID = uuid.NewString()
86 if r := f.call(t, "sheets_set_range", stale); r.Code != 409 {
87 t.Fatal("stale overwrite", r.Code, r.Body.String())
88 }
89 changed := in
90 changed.Cells = append([]sheetAgentCell(nil), in.Cells...)
91 changed.Cells[0].Raw = "90"
92 if r := f.call(t, "sheets_set_range", changed); r.Code != 409 {
93 t.Fatal("payload reuse", r.Code)
94 }
95 var receipt sheetAgentEdit
96 if e = f.a.app.db.First(&receipt).Error; e != nil {
97 t.Fatal(e)
98 }
99 var attributed []store.Event
100 if e = f.a.app.db.Where("tab_id=? AND kind=? AND id>=? AND id<=?", id, store.KindInput, receipt.FirstEventID, receipt.LastEventID).Order("id").Find(&attributed).Error; e != nil {
101 t.Fatal(e)
102 }
103 if len(attributed) != len(in.Cells) || receipt.FirstEventID == 0 || attributed[0].ID != receipt.FirstEventID || attributed[len(attributed)-1].ID != receipt.LastEventID {
104 t.Fatal("receipt does not name the exact native input events", receipt, attributed)
105 }
106 for _, event := range attributed {
107 if event.ActorID != receipt.MemberID {
108 t.Fatal("connection and native actor disagree")
109 }
110 }
111 plain, e := f.a.app.sealer.Open("agent.edit.client/"+receipt.Coordinate, receipt.ClientSealed)
112 if e != nil || string(plain) != f.p.Client || bytes.Contains(receipt.ClientSealed, []byte(f.p.Client)) {
113 t.Fatal("attribution", e)
114 }
115}
116func TestAgentRangeEditAtomicFailures(t *testing.T) {
117 for _, sql := range []string{
118 `CREATE TRIGGER edit_fail BEFORE INSERT ON sheets_agent_edits BEGIN SELECT RAISE(ABORT,'receipt failure'); END`,
119 `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN DELETE FROM home_identity_links; END`,
120 `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN UPDATE home_identity_links SET person_binding=zeroblob(32); END`,
121 `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN UPDATE grants SET role='viewer'; END`,
122 } {
123 t.Run(sql, func(t *testing.T) {
124 f := newSheetAgentFixture(t)
125 made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
126 in := rangeEdit(made)
127 in.Cells = append(in.Cells, sheetAgentCell{Row: 30, Column: 40, Raw: "secret-new-axis"})
128 id, _ := sheetAgentID(made.TabID)
129 h, e := store.Open(f.a.app.db, f.a.app.sealer, id)
130 if e != nil {
131 t.Fatal(e)
132 }
133 defer h.Release()
134 before, e := h.ReadRange(0, 0, 2, 2)
135 if e != nil {
136 t.Fatal(e)
137 }
138 counts := editCounts(t, f)
139 if e = f.a.app.db.Exec(sql).Error; e != nil {
140 t.Fatal(e)
141 }
142 r := f.call(t, "sheets_set_range", in)
143 if r.Code == 200 {
144 t.Fatal("failed edit acknowledged")
145 }
146 after, e := h.ReadRange(0, 0, 2, 2)
147 if e != nil || !reflect.DeepEqual(before, after) || !reflect.DeepEqual(counts, editCounts(t, f)) {
148 t.Fatal("rollback leaked graph/storage", e, r.Code)
149 }
150 if e = f.a.app.db.Exec("DROP TRIGGER edit_fail").Error; e != nil {
151 t.Fatal(e)
152 }
153 decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
154 })
155 }
156}
157func TestAgentRangeEditConcurrency(t *testing.T) {
158 for _, same := range []bool{true, false} {
159 t.Run(strconv.FormatBool(same), func(t *testing.T) {
160 f := newSheetAgentFixture(t)
161 made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
162 in := rangeEdit(made)
163 var wg sync.WaitGroup
164 codes := make(chan int, 4)
165 for range 4 {
166 wg.Add(1)
167 go func() {
168 defer wg.Done()
169 v := in
170 if !same {
171 v.ClientID = uuid.NewString()
172 }
173 codes <- f.call(t, "sheets_set_range", v).Code
174 }()
175 }
176 wg.Wait()
177 close(codes)
178 ok, conflict := 0, 0
179 for n := range codes {
180 switch n {
181 case 200:
182 ok++
183 case 409:
184 conflict++
185 default:
186 t.Fatal(n)
187 }
188 }
189 if same && ok != 4 || !same && (ok != 1 || conflict != 3) {
190 t.Fatal(ok, conflict)
191 }
192 var n int64
193 f.a.app.db.Model(&sheetAgentEdit{}).Count(&n)
194 if n != 1 {
195 t.Fatal(n)
196 }
197 })
198 }
199}
200func TestAgentRangeEditWriterGuardsWithoutEmission(t *testing.T) {
201 for _, retry := range []bool{false, true} {
202 for _, phase := range []int{1, 2} {
203 t.Run(fmt.Sprintf("retry=%v/phase=%d", retry, phase), func(t *testing.T) {
204 f := newSheetAgentFixture(t)
205 made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
206 in := rangeEdit(made)
207 if retry {
208 decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
209 }
210 // If the early guard is removed, a fresh edit hits 503 before the final guard.
211 if !retry && phase == 1 {
212 if e := f.a.app.db.Exec(`CREATE TRIGGER trap BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT,'early guard omitted'); END`).Error; e != nil {
213 t.Fatal(e)
214 }
215 }
216 m, e := f.a.member(t.Context(), f.p, true)
217 if e != nil {
218 t.Fatal(e)
219 }
220 n := 0
221 state := &sheetAgentContext{member: m, sheets: map[uint64]bool{}, verify: func(context.Context) error {
222 n++
223 if n == phase {
224 return access.Fail("unauthenticated", "Revoked")
225 }
226 return nil
227 }}
228 counts := editCounts(t, f)
229 ctx := context.WithValue(t.Context(), sheetAgentKey{}, state)
230 _, e = f.a.setRange(ctx, f.p, m, in)
231 if access.SafeFailure(e).Code != "unauthenticated" || n != phase {
232 t.Fatal("writer boundary", e, n)
233 }
234 if !reflect.DeepEqual(counts, editCounts(t, f)) {
235 t.Fatal("revoked writer committed")
236 }
237 })
238 }
239 }
240}
241func TestAgentRangeEditTeamSharesAndLapse(t *testing.T) {
242 f, af, m := newTeamSheetAgent(t)
243 made := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
244 in := rangeEdit(made)
245 in.Team = teamTestTeam
246 // Independent editor grant, not the creator's self-grant.
247 if e := f.app.db.Model(&Grant{}).Where("sheet_id=?", made.SheetID).Update("granted_by", m.ID+1).Error; e != nil {
248 t.Fatal(e)
249 }
250 f.dir.Set(af.p.Subject, "")
251 f.refreshed(t)
252 ack := decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
253 in.ClientID = uuid.NewString()
254 in.ExpectedRevision = ack.Revision
255 f.expired(t)
256 decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
257 if e := f.app.db.Model(&Grant{}).Where("sheet_id=?", made.SheetID).Update("role", SheetViewer).Error; e != nil {
258 t.Fatal(e)
259 }
260 if r := af.call(t, "sheets_set_range", in); r.Code != 404 {
261 t.Fatal("viewer edit", r.Code)
262 }
263 for _, retry := range []bool{false, true} {
264 t.Run(strconv.FormatBool(retry), func(t *testing.T) {
265 f, af, _ := newTeamSheetAgent(t)
266 made := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
267 in := rangeEdit(made)
268 in.Team = teamTestTeam
269 if retry {
270 decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
271 }
272 m, e := af.a.member(t.Context(), af.p, true)
273 if e != nil {
274 t.Fatal(e)
275 }
276 n := 0
277 state := &sheetAgentContext{member: m, sheets: map[uint64]bool{}, verify: func(context.Context) error {
278 n++
279 if n == 2 {
280 f.expired(t)
281 }
282 return nil
283 }}
284 ctx := teammode.WithAccess(context.WithValue(t.Context(), sheetAgentKey{}, state), m.team.Access)
285 before := editCounts(t, af)
286 if _, e = af.a.setRange(ctx, af.p, m, in); e == nil {
287 t.Fatal("expired writer")
288 }
289 if !reflect.DeepEqual(before, editCounts(t, af)) {
290 t.Fatal("expired write effects")
291 }
292 })
293 }
294}
295