oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "sync"
9 "sync/atomic"
10 "testing"
11 "time"
12
13 access "amadan.net/oficina/agent-access.git"
14 "github.com/google/uuid"
15)
16
17func agentUpdateInput(id int64, seq int, changes map[string]any) map[string]any {
18 return map[string]any{"team": "acme", "id": id, "expected_revision": seq, "client_id": uuid.NewString(), "changes": changes}
19}
20func createdAgentEvent(t *testing.T, a *App, person Person, cal int64) EventView {
21 t.Helper()
22 w := calendarAgentCall(a, "calendar_create_event", eventAgentInput(cal))
23 if w.Code != 200 {
24 t.Fatal(w.Code, w.Body.String())
25 }
26 var out struct{ ID int64 }
27 if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
28 t.Fatal(err)
29 }
30 e, err := a.store.Event(t.Context(), person.ID, out.ID)
31 if err != nil {
32 t.Fatal(err)
33 }
34 return e
35}
36
37func TestAgentEventUpdateLifecycleAndReminders(t *testing.T) {
38 f, _, person, cal := linkedCalendarAgent(t)
39 e := createdAgentEvent(t, f.app, person, cal)
40 if err := f.app.store.AddReminderOn(t.Context(), person.ID, e.ID, 30, "inapp"); err != nil {
41 t.Fatal(err)
42 }
43 if err := f.app.store.AddReminderOn(t.Context(), person.ID, e.ID, 45, "both"); err != nil {
44 t.Fatal(err)
45 }
46 var oldRules []Reminder
47 f.app.db.G.Where("event_id=?", e.ID).Order("id").Find(&oldRules)
48 next := time.Unix(e.StartUTC, 0).Add(24 * time.Hour)
49 input := agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "Updated event", "start_local": next.Format(LayoutLocal), "end_local": next.Add(time.Hour).Format(LayoutLocal)})
50 first := calendarAgentCall(f.app, "calendar_update_event", input)
51 if first.Code != 200 || !strings.Contains(first.Body.String(), `"invitations_sent":false`) {
52 t.Fatal(first.Code, first.Body.String())
53 }
54 got, err := f.app.store.Event(t.Context(), person.ID, e.ID)
55 if err != nil || got.Title != "Updated event" || got.StartUTC != next.Unix() || got.Sequence != e.Sequence+1 || got.Notes != e.Notes || got.Location != e.Location || got.UIDHash != e.UIDHash || got.CreatedBy != e.CreatedBy {
56 t.Fatal("wrong domain effect", got, err)
57 }
58 if w := f.do("GET", fmt.Sprintf("/events/%d", e.ID), ""); w.Code != 200 || !strings.Contains(w.Body.String(), "Updated event") {
59 t.Fatal("event page", w.Code)
60 }
61 var rules []Reminder
62 f.app.db.G.Where("event_id=?", e.ID).Order("id").Find(&rules)
63 if len(rules) != len(oldRules) {
64 t.Fatal("rules changed")
65 }
66 for i, r := range rules {
67 if r.ID != oldRules[i].ID || r.OffsetMin != oldRules[i].OffsetMin || r.Channel != oldRules[i].Channel {
68 t.Fatal("rule changed", r)
69 }
70 var q ReminderQueue
71 if err := f.app.db.G.Where("reminder_id=?", r.ID).First(&q).Error; err != nil || q.DueAt != next.Unix()-int64(r.OffsetMin)*60 || q.ClaimID != nil {
72 t.Fatal("queue not rescheduled", q, err)
73 }
74 }
75 if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "stale"})); w.Code != 409 {
76 t.Fatal("stale", w.Code)
77 }
78 later := agentUpdateInput(e.ID, got.Sequence, map[string]any{"notes": "later edit"})
79 if w := calendarAgentCall(f.app, "calendar_update_event", later); w.Code != 200 {
80 t.Fatal(w.Code, w.Body.String())
81 }
82 if w := calendarAgentCall(f.app, "calendar_update_event", input); w.Code != 200 || w.Body.String() != first.Body.String() {
83 t.Fatal("retry receipt", w.Code, w.Body.String())
84 }
85 got, _ = f.app.store.Event(t.Context(), person.ID, e.ID)
86 if got.Notes != "later edit" || got.Sequence != e.Sequence+2 {
87 t.Fatal("retry rewrote event")
88 }
89 input["changes"] = map[string]any{"title": "different"}
90 if w := calendarAgentCall(f.app, "calendar_update_event", input); w.Code != 409 {
91 t.Fatal("changed retry", w.Code)
92 }
93 if err := f.app.store.DeleteEvent(t.Context(), person.ID, e.ID); err != nil {
94 t.Fatal(err)
95 }
96 if w := calendarAgentCall(f.app, "calendar_update_event", later); w.Code != 404 {
97 t.Fatal("deleted replay", w.Code)
98 }
99}
100
101func TestAgentEventUpdateConcurrentPrecondition(t *testing.T) {
102 f, _, person, cal := linkedCalendarAgent(t)
103 e := createdAgentEvent(t, f.app, person, cal)
104 var success, conflict atomic.Int32
105 var wg sync.WaitGroup
106 for range 8 {
107 wg.Go(func() {
108 w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "winner"}))
109 switch w.Code {
110 case 200:
111 success.Add(1)
112 case 409:
113 conflict.Add(1)
114 default:
115 t.Errorf("status %d: %s", w.Code, w.Body.String())
116 }
117 })
118 }
119 wg.Wait()
120 if success.Load() != 1 || conflict.Load() != 7 {
121 t.Fatal(success.Load(), conflict.Load())
122 }
123 var n int64
124 f.app.db.G.Table("calendar_agent_updates").Count(&n)
125 if n != 1 {
126 t.Fatal("partial receipts", n)
127 }
128}
129
130func TestAgentEventUpdateAtomicRollback(t *testing.T) {
131 for _, mode := range []string{"receipt", "queue", "unlink", "grant", "reserved", "final"} {
132 t.Run(mode, func(t *testing.T) {
133 f, p, person, cal := linkedCalendarAgent(t)
134 e := createdAgentEvent(t, f.app, person, cal)
135 var old []ReminderQueue
136 f.app.db.G.Find(&old)
137 var checks atomic.Int32
138 if err := f.app.mountAgent(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
139 n := checks.Add(1)
140 if mode == "reserved" && n >= 2 || mode == "final" && n >= 3 {
141 return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
142 }
143 return *p, nil
144 }), f.app.agentIssuer, "acme"); err != nil {
145 t.Fatal(err)
146 }
147 sql := ""
148 switch mode {
149 case "receipt":
150 sql = "CREATE TRIGGER fail_update BEFORE INSERT ON calendar_agent_updates BEGIN SELECT RAISE(ABORT,'injected'); END"
151 case "queue":
152 sql = "CREATE TRIGGER fail_update BEFORE UPDATE ON reminder_queues BEGIN SELECT RAISE(ABORT,'injected'); END"
153 case "unlink":
154 sql = "CREATE TRIGGER fail_update AFTER INSERT ON calendar_agent_updates BEGIN DELETE FROM home_identity_links; END"
155 case "grant":
156 sql = "CREATE TRIGGER fail_update AFTER INSERT ON calendar_agent_updates BEGIN UPDATE grants SET role='viewer'; END"
157 }
158 if sql != "" {
159 if err := f.app.db.G.Exec(sql).Error; err != nil {
160 t.Fatal(err)
161 }
162 }
163 next := time.Unix(e.StartUTC, 0).Add(time.Hour)
164 w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, map[string]any{"title": "after", "start_local": next.Format(LayoutLocal), "end_local": next.Add(time.Hour).Format(LayoutLocal)}))
165 if w.Code != 401 && w.Code != 403 && w.Code != 503 {
166 t.Fatal(w.Code, w.Body.String())
167 }
168 got, err := f.app.store.Event(t.Context(), person.ID, e.ID)
169 if err != nil || got.Title != e.Title || got.Sequence != e.Sequence || got.StartUTC != e.StartUTC {
170 t.Fatal("partial event", err)
171 }
172 var now []ReminderQueue
173 f.app.db.G.Find(&now)
174 a, _ := json.Marshal(old)
175 b, _ := json.Marshal(now)
176 if string(a) != string(b) {
177 t.Fatal("partial queue")
178 }
179 var n int64
180 f.app.db.G.Table("calendar_agent_updates").Count(&n)
181 if n != 0 {
182 t.Fatal("partial receipt")
183 }
184 })
185 }
186}
187
188func TestAgentEventUpdateUnsupportedShapes(t *testing.T) {
189 for _, mode := range []string{"recurring", "override", "exdates", "foreign", "cancelled", "status", "calendar", "null", "empty", "dst", "booking"} {
190 t.Run(mode, func(t *testing.T) {
191 f, _, person, cal := linkedCalendarAgent(t)
192 e := createdAgentEvent(t, f.app, person, cal)
193 changes := map[string]any{"title": "after"}
194 var update map[string]any
195 switch mode {
196 case "recurring":
197 update = map[string]any{"rrule": "FREQ=DAILY"}
198 case "override":
199 update = map[string]any{"series_id": e.ID}
200 case "exdates":
201 update = map[string]any{"exdates": e.StartLocal}
202 case "foreign":
203 update = map[string]any{"rrule_foreign": true}
204 case "cancelled":
205 update = map[string]any{"status": StatusCancelled}
206 case "status":
207 changes["status"] = StatusCancelled
208 case "calendar":
209 changes["calendar_id"] = cal
210 case "null":
211 changes["title"] = nil
212 case "empty":
213 changes = map[string]any{}
214 case "dst":
215 changes = map[string]any{"start_local": "2027-03-28T01:30", "end_local": "2027-03-28T03:30", "tz": "Europe/Dublin"}
216 case "booking":
217 if err := f.app.db.G.Create(&Booking{EventID: e.ID, State: BookingConfirmed, TokenHash: uuid.NewString()}).Error; err != nil {
218 t.Fatal(err)
219 }
220 changes["start_local"] = time.Unix(e.StartUTC, 0).Add(time.Minute).Format(LayoutLocal)
221 }
222 if update != nil {
223 if err := f.app.db.G.Model(&Event{}).Where("id=?", e.ID).Updates(update).Error; err != nil {
224 t.Fatal(err)
225 }
226 }
227 if w := calendarAgentCall(f.app, "calendar_update_event", agentUpdateInput(e.ID, e.Sequence, changes)); w.Code != 422 {
228 t.Fatal("unsupported mutation", w.Code, w.Body.String())
229 }
230 })
231 }
232}
233