oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "log/slog"
9 "strings"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16const accessSchema = `CREATE TABLE IF NOT EXISTS access_requests (card_id TEXT PRIMARY KEY, command TEXT NOT NULL, report TEXT NOT NULL DEFAULT '', state TEXT NOT NULL, confirmed_at INTEGER NOT NULL DEFAULT 0, poll_failures INTEGER NOT NULL DEFAULT 0);`
17
18func (s *State) AcceptAccess(ctx context.Context, frame string, c wire.AccessCommand) error {
19 if !validAccessCommand(c) {
20 return errAccess
21 }
22 raw, _ := json.Marshal(c)
23 return s.tx(ctx, func(tx *sql.Tx) error {
24 fresh, err := seen(tx, frame)
25 if err != nil || !fresh {
26 return err
27 }
28 var old string
29 err = tx.QueryRow("SELECT command FROM access_requests WHERE card_id=?", c.CardID).Scan(&old)
30 if err == nil {
31 if old != string(raw) {
32 return errAccess
33 }
34 return nil
35 }
36 if !errors.Is(err, sql.ErrNoRows) {
37 return err
38 }
39 _, err = tx.Exec("INSERT INTO access_requests(card_id,command,state,confirmed_at) VALUES(?,?,'queued',?)", c.CardID, string(raw), time.Now().UnixNano())
40 return err
41 })
42}
43
44type AccessEngine struct {
45 Authorize func(context.Context, string) error
46 State *State
47 Forge AccessForge
48 Refresh func()
49 Notify func()
50 Logger *slog.Logger
51}
52
53// Step files at most once. An interrupted POST has an uncertain outcome and
54// needs a fresh person confirmation; a saved id always resumes by GET.
55func (e *AccessEngine) Step(ctx context.Context, id string) error {
56 var command, report, state string
57 if err := e.State.db.QueryRowContext(ctx, "SELECT command,report,state FROM access_requests WHERE card_id=?", id).Scan(&command, &report, &state); err != nil {
58 return err
59 }
60 if wire.AccessFinal(state) {
61 return nil
62 }
63 var cmd wire.AccessCommand
64 var old wire.AccessReport
65 if json.Unmarshal([]byte(command), &cmd) != nil {
66 return errAccess
67 }
68 if report != "" && json.Unmarshal([]byte(report), &old) != nil {
69 return errAccess
70 }
71 var out wire.AccessReport
72 settled := false
73 localExpiry := false
74 var err error
75 switch state {
76 case "queued":
77 if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET state='filing' WHERE card_id=?", id); err != nil {
78 return err
79 }
80 if e.Authorize != nil {
81 err = e.Authorize(ctx, cmd.CardID)
82 settled = errors.Is(err, ErrWithdrawn)
83 }
84 if errors.Is(err, ErrNoAuthority) || ctx.Err() != nil {
85 _, _ = e.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE access_requests SET state='queued' WHERE card_id=?", id)
86 return err
87 }
88 if err != nil {
89 out.State = "authority"
90 } else {
91 if e.Forge == nil {
92 err = errAccess
93 } else {
94 out, err = e.Forge.RequestAccess(ctx, cmd)
95 }
96 if err != nil {
97 out.State = "failed"
98 if errors.Is(err, errAccessNotOwned) {
99 out.State = "not_owned"
100 }
101 if errors.Is(err, errAccessAlready) {
102 out.State = "already"
103 }
104 if errors.Is(err, errAccessLimit) {
105 out.State = "limited"
106 }
107 if errors.Is(err, errAccessContract) || errors.Is(err, errAccessState) {
108 out.State = "unconfirmed"
109 }
110 }
111 }
112 case "filing":
113 out.State = "unconfirmed"
114 case "pending", "checking_expiry":
115 out, err = e.Forge.PollAccess(ctx, old.RequestID, cmd)
116 if err == nil && out.RequestID != old.RequestID {
117 err = errAccessContract
118 }
119 // A server answer wins over the runner clock. An offline estimate is
120 // provisional and keeps reconciling the saved id, never another POST.
121 if err != nil && ctx.Err() == nil && (errors.Is(err, errAccess) || errors.Is(err, context.DeadlineExceeded)) && old.Expires > 0 && time.Now().After(time.Unix(old.Expires, 0).Add(10*time.Minute)) {
122 out, err, localExpiry = old, nil, true
123 out.State = "expired"
124 }
125 if err != nil {
126 final := ""
127 switch {
128 case errors.Is(err, errAccessMissing):
129 final = "missing"
130 case errors.Is(err, errAccessDenied), errors.Is(err, errAccessState):
131 final = "uncheckable"
132 case errors.Is(err, errAccessContract):
133 final = "unconfirmed"
134 }
135 if final == "" {
136 return err
137 }
138 var failures int
139 if xerr := e.State.db.QueryRowContext(ctx, "UPDATE access_requests SET poll_failures=poll_failures+1 WHERE card_id=? RETURNING poll_failures", id).Scan(&failures); xerr != nil {
140 return xerr
141 }
142 if failures < 3 {
143 return err
144 }
145 out = old
146 out.State = final
147 } else if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET poll_failures=0 WHERE card_id=?", id); err != nil {
148 return err
149 }
150
151 default:
152 return errAccess
153 }
154 out.CardID, out.Person = cmd.CardID, cmd.Person
155 if out.ApproveURL == "" {
156 out.ApproveURL = old.ApproveURL
157 }
158 if out.Expires == 0 {
159 out.Expires = old.Expires
160 }
161 raw, _ := json.Marshal(out)
162 savedState := out.State
163 if localExpiry {
164 savedState = "checking_expiry"
165 }
166 if err := e.State.tx(ctx, func(tx *sql.Tx) error {
167 if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", savedState, string(raw), id); err != nil {
168 return err
169 }
170 if string(raw) == report || settled {
171 return nil
172 }
173 return e.State.enqueue(tx, wire.FrameAccess, "", out)
174 }); err != nil {
175 return err
176 }
177 if out.State == "approved" || out.State == "already" {
178 e.Forge.Recheck()
179 e.Forge.Reachable(ctx)
180 if e.Refresh != nil {
181 e.Refresh()
182 }
183 }
184 if e.Notify != nil {
185 e.Notify()
186 }
187 return nil
188}
189
190// Run reserves a filing worker independently of the five long polls.
191// SQLite insertion order breaks confirmation-time ties, including legacy rows.
192func (e *AccessEngine) Run(ctx context.Context) {
193 var wg sync.WaitGroup
194 defer wg.Wait()
195 type finished struct {
196 id string
197 filing bool
198 err error
199 }
200 active := map[string]bool{}
201 next := map[string]time.Time{}
202 delays := map[string]time.Duration{}
203 done := make(chan finished, 6)
204 filing, polls := false, 0
205 tick := time.NewTicker(time.Second)
206 defer tick.Stop()
207 for {
208 select {
209 case <-ctx.Done():
210 return
211 case result := <-done:
212 delete(active, result.id)
213 if result.filing {
214 filing = false
215 } else {
216 polls--
217 }
218 delay := time.Second
219 var state string
220 if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", result.id).Scan(&state) == nil && state == "checking_expiry" {
221 delay = time.Minute
222 }
223 if result.err != nil {
224 delay = min(max(delays[result.id]*2, 2*time.Second), time.Minute)
225 }
226 delays[result.id] = delay
227 next[result.id] = time.Now().Add(delay)
228 case <-tick.C:
229 rows, err := e.State.db.QueryContext(ctx, "SELECT card_id,state FROM access_requests WHERE state IN ('queued','filing','pending','checking_expiry') ORDER BY CASE WHEN state IN ('pending','checking_expiry') THEN 1 ELSE 0 END, confirmed_at, rowid LIMIT 128")
230 if err != nil {
231 continue
232 }
233 var jobs []struct{ id, state string }
234 for rows.Next() {
235 var j struct{ id, state string }
236 if rows.Scan(&j.id, &j.state) == nil {
237 jobs = append(jobs, j)
238 }
239 }
240 rows.Close()
241 for _, j := range jobs {
242 fresh := j.state == "queued" || j.state == "filing"
243 if active[j.id] || time.Now().Before(next[j.id]) || fresh && filing || !fresh && polls >= 5 {
244 continue
245 }
246 active[j.id] = true
247 if fresh {
248 filing = true
249 } else {
250 polls++
251 }
252 wg.Add(1)
253 go func(id string, fresh bool) { defer wg.Done(); err := e.Step(ctx, id); done <- finished{id, fresh, err} }(j.id, fresh)
254 }
255 }
256 }
257}
258
259func migrateAccess(ctx context.Context, db *sql.DB) error {
260 for _, column := range []string{"confirmed_at INTEGER NOT NULL DEFAULT 0", "poll_failures INTEGER NOT NULL DEFAULT 0"} {
261 if _, err := db.ExecContext(ctx, "ALTER TABLE access_requests ADD COLUMN "+column); err != nil && !strings.Contains(err.Error(), "duplicate column") {
262 return err
263 }
264 }
265 return nil
266}
267