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
3// Team mode's scheduled work. The drain acts as the system: it is not a
4// person's request and holds nobody's lease, as Memoria's connector runs
5// do (oficina/memoria #32, deviation 3). Its bookkeeping writes — claims,
6// deferrals, fires, hold expiry — are the instance's own and unguarded.
7//
8// What it DELIVERS to a person is decided on that person's standing,
9// asked when it is about to go, so a job acting on a removed member's
10// events leaks nothing to them:
11//
12// - a reminder is delivered only to a recipient the roster says is a
13// Member now, who still reaches the event on that standing, and, for a
14// rule that is mailed, who has an address. No reach, or an email-only
15// rule of a Home-only recipient, settles that occurrence unsent and
16// queues the next, decided the same way on its day. An in-app rule
17// needs no address: its delivery is a notice in this database.
18// NotMember settles it unsent and queues NOTHING: the rule goes
19// dormant, so a removed member's daily standup does not wake the
20// instance every day for nobody (Fable #35 N2). Re-added, their next
21// request wakes every dormant rule of theirs (wakeDormantReminders).
22// Unknown defers it, unsent and unattempted, by standingRetry.
23// - a booking's HOST mail goes only to a host who is a Member with an
24// address; NotMember or addressless retires it unsent, Unknown defers
25// it. The booker's own mail is theirs (they typed the address to be
26// mailed, B5) and is unchanged.
27//
28// Outside team mode every decision here is deliverNow and the drain is
29// what it always was.
30
31import (
32 "context"
33 "fmt"
34 "time"
35
36 "amadan.net/oficina/home/roster"
37 "amadan.net/oficina/home/teammode"
38
39 "amadan.net/oficina/calendar/internal/calendar/teamstate"
40)
41
42// delivery is what the drain may do with one item owed to a person.
43type delivery int
44
45const (
46 deliverNow delivery = iota
47 // deliverLater: standing cannot be read now. Nothing is sent and
48 // nothing is decided against the person.
49 deliverLater
50 // deliverNever: definitely not this occurrence — out of reach, or no
51 // address. The next is queued and decided on its own day.
52 deliverNever
53 // deliverDormant: off the team. Not this occurrence, and none after it
54 // until they are back.
55 deliverDormant
56)
57
58// dormantClaim marks a reminder queue row settled because its person left
59// the team: fired (so nothing claims it and NextDue ignores it) and held
60// under this claim instead of a random one, so their return can find it.
61const dormantClaim = "team:dormant"
62
63// standingRetry is how long a reminder waits when its recipient's
64// standing cannot be read. Longer than the sender's own deferral: every
65// wake costs a quarter hour of residency (AGENTS.md §Ticks), and a Home
66// outage should not keep the instance awake polling it every thirty
67// seconds. A reminder that arrives late says so.
68const standingRetry = 5 * time.Minute
69
70// reminderDelivery decides one claimed reminder on its recipient's
71// standing. Standing is read before reach and again after it (the
72// stream-order lesson): a lease that lapsed in between is a deferral.
73func (h *handlers) reminderDelivery(ctx context.Context, due DueReminder) delivery {
74 if h.team == nil {
75 return deliverNow
76 }
77 if !channelInApp(due.Channel) && teamstate.Addressless(due.Address) {
78 return deliverNever
79 }
80 acc := h.standingFor(ctx, due.PersonID)
81 switch acc.State() {
82 case roster.NotMember:
83 return deliverDormant
84 case roster.Unknown:
85 return deliverLater
86 }
87 _, err := h.store.Event(teammode.WithAccess(ctx, acc), due.PersonID, due.EventID)
88 if acc.State() != roster.Member {
89 return deliverLater
90 }
91 switch {
92 case NotFound(err):
93 return deliverNever
94 case err != nil:
95 return deliverLater
96 }
97 return deliverNow
98}
99
100// settleWithoutSending applies reminderDelivery: true when the reminder
101// was settled (deferred or retired) without a send, false when it should
102// be sent. A bookkeeping failure is the drain's error, as any other is.
103func (h *handlers) settleWithoutSending(ctx context.Context, due DueReminder, now time.Time) (bool, error) {
104 switch h.reminderDelivery(ctx, due) {
105 case deliverLater:
106 _, err := h.store.deferReminderFor(keep(ctx), due.Queue.ID, due.ClaimID, now.Unix(), standingRetry)
107 return true, err
108 case deliverNever:
109 // This occurrence is settled, unsent; the next is queued and
110 // decided on its own day.
111 return true, h.store.CompleteReminder(keep(ctx), due, now.Unix())
112 case deliverDormant:
113 return true, h.store.settleDormant(keep(ctx), due, now.Unix())
114 }
115 return false, nil
116}
117
118// deliverInApp delivers the in-app half of a reminder the drain may
119// deliver: it marks the person's notice, under the claim. done is true
120// when that was everything — an in-app-only rule, or a rule whose email
121// half has no address to go to in team mode — and the reminder has been
122// completed, which queues its next occurrence. An email-only rule is
123// untouched (done false, nothing written), so its path is what it always
124// was.
125func (h *handlers) deliverInApp(ctx context.Context, due DueReminder, now time.Time) (done bool, err error) {
126 if !channelInApp(due.Channel) {
127 return false, nil
128 }
129 if err := h.store.MarkReminderNotice(keep(ctx), due, now.Unix()); err != nil {
130 return false, err
131 }
132 if channelEmail(due.Channel) && (h.team == nil || !teamstate.Addressless(due.Address)) {
133 return false, nil
134 }
135 return true, h.store.CompleteReminder(keep(ctx), due, now.Unix())
136}
137
138// settleDormant settles a claimed reminder unsent and queues nothing,
139// conditional on the claim as every completion is: the row is fired and
140// held under dormantClaim until its person returns.
141func (s *Store) settleDormant(ctx context.Context, due DueReminder, now int64) error {
142 return s.g.WithContext(ctx).Model(&ReminderQueue{}).
143 Where("id = ? AND claim_id = ?", due.Queue.ID, due.ClaimID).
144 Updates(map[string]any{"fired_at": now, "claimed_at": nil, "claim_id": dormantClaim}).Error
145}
146
147// wakeDormantReminders reschedules every rule of personID's that went
148// dormant when they left the team, from now: run on a request whose
149// standing is Member, which is how a re-added member is noticed. One
150// indexed read when there is nothing to wake. A failure costs only the
151// wake, which the next request tries again.
152func (s *Store) wakeDormantReminders(ctx context.Context, personID int64) error {
153 var ids []int64
154 if err := s.g.WithContext(ctx).Model(&ReminderQueue{}).
155 Joins("JOIN reminders ON reminders.id = reminder_queues.reminder_id").
156 Where("reminders.person_id = ? AND reminder_queues.claim_id = ?", personID, dormantClaim).
157 Pluck("reminder_queues.reminder_id", &ids).Error; err != nil {
158 return fmt.Errorf("calendar: find dormant reminders: %w", err)
159 }
160 for _, id := range ids {
161 if err := s.rescheduleAfterTx(s.g.WithContext(ctx), id, 0); err != nil {
162 return err
163 }
164 }
165 return nil
166}
167
168// hostMail decides a booking's host mail on the host's standing.
169func (h *handlers) hostMail(ctx context.Context, host Person) delivery {
170 if h.team == nil {
171 return deliverNow
172 }
173 if teamstate.Addressless(host.Address) {
174 return deliverNever
175 }
176 switch h.standingFor(ctx, host.ID).State() {
177 case roster.Member:
178 return deliverNow
179 case roster.NotMember:
180 return deliverNever
181 }
182 return deliverLater
183}
184
185// deferReminderFor is DeferReminder by wait, for a deferral that is not
186// the sender's (team mode's unknown standing: team_jobs.go).
187func (s *Store) deferReminderFor(ctx context.Context, queueID int64, claimID string, now int64, wait time.Duration) (ok bool, err error) {
188 res := s.g.WithContext(ctx).Model(&ReminderQueue{}).
189 Where("id = ? AND claim_id = ?", queueID, claimID).
190 Updates(map[string]any{"retry_at": now + int64(wait.Seconds()), "claimed_at": nil, "claim_id": nil})
191 if res.Error != nil {
192 return false, fmt.Errorf("calendar: defer reminder: %w", res.Error)
193 }
194 return res.RowsAffected == 1, nil
195}
196