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 "errors"
6 "fmt"
7 "sort"
8
9 "gorm.io/gorm"
10)
11
12// eventRow is the join every range query reads: the event plus the two
13// things a chip needs from its calendar and the viewer's grant.
14type eventRow struct {
15 Event
16 Role string
17 CalendarName []byte
18 CalendarHue int
19}
20
21// EventsInRange returns everything a person may see that overlaps the
22// half-open UTC window [from, to), with series expanded and overrides
23// substituted.
24//
25// The two-pass shape is what makes moved occurrences behave. Overrides
26// are stored against the occurrence's ORIGINAL time and may be moved to
27// any other, so:
28//
29// 1. Expand each master over the window and substitute any override
30// matching the occurrence's original key. An override that moved
31// OUT of the window is dropped here, which is correct — it is no
32// longer in these days.
33// 2. Separately collect overrides whose own times land IN the window,
34// and add the ones pass 1 did not already place. That is the
35// occurrence dragged in from last week, which pass 1 cannot see
36// because the master never generates it here.
37//
38// Skipping pass 2 is the classic vanishing-event bug; skipping the
39// dedupe is the classic duplicated one.
40func (s *Store) EventsInRange(ctx context.Context, personID, from, to int64) ([]EventView, error) {
41 return s.eventsInRange(s.g.WithContext(ctx), personID, from, to, false)
42}
43
44// ErrIncompleteExpansion says a busy series in the window could not be
45// expanded to completion — its rule is outside the subset, or it ran
46// out of steps before reaching the window — so the answer is not a
47// full account of the person's time.
48var ErrIncompleteExpansion = errors.New("calendar: a busy series could not be fully expanded")
49
50// EventsInRangeStrict is EventsInRange for anyone deciding FREE time.
51//
52// The tolerant reader renders a foreign rule as its first occurrence
53// and a truncated expansion as whatever it reached, because a view
54// that shows less is better than a view that shows nothing. A booking
55// page cannot afford either: an occurrence it does not see is a slot it
56// offers. So this returns ErrIncompleteExpansion for any master that
57// occupies time, is not cancelled, and either has a rule ParseRule
58// rejects or ran out of steps (booking spec §4.1, B23). The rule is
59// still stored verbatim, per ruling 4.
60func (s *Store) EventsInRangeStrict(ctx context.Context, personID, from, to int64) ([]EventView, error) {
61 return s.eventsInRange(s.g.WithContext(ctx), personID, from, to, true)
62}
63
64// eventsInRange runs on any *gorm.DB — the store's own, or a caller's
65// transaction — so a hold can re-read busy time behind the write lock.
66func (s *Store) eventsInRange(db *gorm.DB, personID, from, to int64, strict bool) ([]EventView, error) {
67 // Standing is read once, before either pass, so both passes join
68 // through the same reach (team_reach.go).
69 rung := s.reaches(db.Statement.Context)
70 rows, err := s.rangeRows(db, personID, from, to, rung)
71 if err != nil {
72 return nil, err
73 }
74
75 // Overrides for every series touched, keyed by series and original
76 // occurrence. Fetched in one query rather than per occurrence: a
77 // query inside an expansion loop is a query per day per series.
78 //
79 // An override row in the window volunteers its own series too. Its
80 // master may have FINISHED before the window — excluded by
81 // until_utc — in which case nothing else names that series, and
82 // without this the occurrence dragged past the series' end would be
83 // skipped in pass 1 and never loaded for pass 2: a moved meeting
84 // that vanishes.
85 var masterIDs []int64
86 seen := map[int64]bool{}
87 for _, r := range rows {
88 switch {
89 case r.RRule != "" && r.SeriesID == nil:
90 if !seen[r.ID] {
91 seen[r.ID] = true
92 masterIDs = append(masterIDs, r.ID)
93 }
94 case r.SeriesID != nil:
95 if !seen[*r.SeriesID] {
96 seen[*r.SeriesID] = true
97 masterIDs = append(masterIDs, *r.SeriesID)
98 }
99 }
100 }
101 overrides, err := s.overridesFor(db, personID, masterIDs, rung)
102 if err != nil {
103 return nil, err
104 }
105
106 placed := map[string]bool{}
107 var out []EventView
108
109 for _, r := range rows {
110 switch {
111 case r.SeriesID != nil:
112 // Handled below, in pass 2 — an override is never rendered
113 // as if it were an independent event.
114 continue
115
116 case r.RRule == "":
117 v, err := s.openEvent(r.Event, r.Role, r.CalendarName, r.CalendarHue)
118 if err != nil {
119 return nil, err
120 }
121 out = append(out, v)
122
123 default:
124 // A rule this app cannot expand still has its own first
125 // occurrence, which is a real event on a real day.
126 rule, perr := ParseRule(r.RRule)
127 if perr != nil {
128 if strict && OccupiesTime(r.Kind) && r.Status != StatusCancelled {
129 return nil, ErrIncompleteExpansion
130 }
131 v, err := s.openEvent(r.Event, r.Role, r.CalendarName, r.CalendarHue)
132 if err != nil {
133 return nil, err
134 }
135 if v.EndUTC > from && v.StartUTC < to {
136 out = append(out, v)
137 }
138 continue
139 }
140 occs, complete := ExpandComplete(r.StartLocal, r.EndLocal, r.TZ, r.AllDay, rule, r.Exdates, from, to)
141 if !complete && strict && OccupiesTime(r.Kind) && r.Status != StatusCancelled {
142 return nil, ErrIncompleteExpansion
143 }
144 for _, occ := range occs {
145 key := overrideKey(r.ID, occ.Local)
146 if ov, ok := overrides[key]; ok {
147 placed[key] = true
148 if ov.DeletedAt != nil {
149 continue
150 }
151 v, err := s.openEvent(ov.Event, ov.Role, ov.CalendarName, ov.CalendarHue)
152 if err != nil {
153 return nil, err
154 }
155 // An override moved outside the window is not in
156 // these days any more.
157 if v.OccEndUTC <= from || v.OccStartUTC >= to {
158 continue
159 }
160 v.OccurrenceLocal = occ.Local
161 out = append(out, v)
162 continue
163 }
164 v, err := s.openEvent(r.Event, r.Role, r.CalendarName, r.CalendarHue)
165 if err != nil {
166 return nil, err
167 }
168 v.OccStartUTC, v.OccEndUTC = occ.StartUTC, occ.EndUTC
169 v.OccurrenceLocal = occ.Local
170 out = append(out, v)
171 }
172 }
173 }
174
175 // Pass 2: overrides dragged into the window from an original the
176 // expansion never reached.
177 for key, ov := range overrides {
178 if placed[key] || ov.DeletedAt != nil {
179 continue
180 }
181 if ov.EndUTC <= from || ov.StartUTC >= to {
182 continue
183 }
184 v, err := s.openEvent(ov.Event, ov.Role, ov.CalendarName, ov.CalendarHue)
185 if err != nil {
186 return nil, err
187 }
188 v.OccurrenceLocal = ov.RecurrenceIDLocal
189 out = append(out, v)
190 }
191
192 sortOccurrences(out)
193 return out, nil
194}
195
196// rangeRows reads the candidate events: anything overlapping the window,
197// plus every series master that could still be producing in it.
198func (s *Store) rangeRows(db *gorm.DB, personID, from, to int64, rung bool) ([]eventRow, error) {
199 var rows []eventRow
200 err := db.
201 Model(&Event{}).
202 Select("events.*, grants.role as role, calendars.name_sealed as calendar_name, calendars.hue as calendar_hue").
203 Joins("JOIN calendars ON calendars.id = events.calendar_id AND calendars.archived_at IS NULL").
204 Joins(grantJoin("events.calendar_id", rung), personID).
205 Where("events.deleted_at IS NULL").
206 Where(`
207 -- a single, or an override, overlapping the window
208 (events.rrule = '' AND events.end_utc > ? AND events.start_utc < ?)
209 -- or a master that starts before the window ends and has
210 -- not already finished. until_utc is NULL for a forever
211 -- series and for one bounded by COUNT, whose end cannot be
212 -- known without expanding it — so those are always
213 -- candidates, and the expander bounds them.
214 --
215 -- UNTIL bounds the last occurrence's START, not its end, so
216 -- "finished" is until_utc plus one occurrence's length: a
217 -- final occurrence that runs for four days is still in
218 -- progress two days after the last start the rule allows.
219 -- Plus a 25-hour day of slack, because an occurrence's
220 -- elapsed length is not the master's across a DST day: the
221 -- fold makes a four-hour night shift five hours long, and
222 -- a bound measured from the master would have excluded it
223 -- from a query that opened in its fifth hour. A day's extra
224 -- expansion is cheap; a lost occurrence is a double-booking.
225 OR (events.rrule <> '' AND events.start_utc < ?
226 AND (events.until_utc IS NULL OR events.until_utc + (events.end_utc - events.start_utc) + 90000 >= ?))
227 `, from, to, to, from).
228 Scan(&rows).Error
229 if err != nil {
230 return nil, fmt.Errorf("calendar: range query: %w", err)
231 }
232 return rows, nil
233}
234
235// overridesFor reads every override of the given series, keyed by
236// series and ORIGINAL occurrence.
237func (s *Store) overridesFor(db *gorm.DB, personID int64, seriesIDs []int64, rung bool) (map[string]eventRow, error) {
238 out := map[string]eventRow{}
239 if len(seriesIDs) == 0 {
240 return out, nil
241 }
242 var rows []eventRow
243 err := db.
244 Model(&Event{}).
245 Select("events.*, grants.role as role, calendars.name_sealed as calendar_name, calendars.hue as calendar_hue").
246 Joins("JOIN calendars ON calendars.id = events.calendar_id").
247 Joins(grantJoin("events.calendar_id", rung), personID).
248 Where("events.series_id IN ?", seriesIDs).
249 Scan(&rows).Error
250 if err != nil {
251 return nil, fmt.Errorf("calendar: overrides query: %w", err)
252 }
253 for _, r := range rows {
254 out[overrideKey(*r.SeriesID, r.RecurrenceIDLocal)] = r
255 }
256 return out, nil
257}
258
259func overrideKey(seriesID int64, local string) string {
260 return fmt.Sprintf("%d/%s", seriesID, local)
261}
262
263// sortOccurrences puts a day in reading order: earliest first, all-day
264// events ahead of timed ones that start at the same moment, then by
265// title so the order is stable across requests.
266//
267// Stability matters more than it looks: an unstable sort makes a page
268// reorder itself between two identical requests, which reads as data
269// changing when nothing has.
270func sortOccurrences(v []EventView) {
271 sort.SliceStable(v, func(i, j int) bool {
272 if v[i].OccStartUTC != v[j].OccStartUTC {
273 return v[i].OccStartUTC < v[j].OccStartUTC
274 }
275 if v[i].AllDay != v[j].AllDay {
276 return v[i].AllDay
277 }
278 if v[i].Title != v[j].Title {
279 return v[i].Title < v[j].Title
280 }
281 return v[i].ID < v[j].ID
282 })
283}
284