package thin import ( "context" "database/sql" "encoding/json" "errors" "log/slog" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/wire" ) const 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);` func (s *State) AcceptAccess(ctx context.Context, frame string, c wire.AccessCommand) error { if !validAccessCommand(c) { return errAccess } raw, _ := json.Marshal(c) return s.tx(ctx, func(tx *sql.Tx) error { fresh, err := seen(tx, frame) if err != nil || !fresh { return err } var old string err = tx.QueryRow("SELECT command FROM access_requests WHERE card_id=?", c.CardID).Scan(&old) if err == nil { if old != string(raw) { return errAccess } return nil } if !errors.Is(err, sql.ErrNoRows) { return err } _, err = tx.Exec("INSERT INTO access_requests(card_id,command,state,confirmed_at) VALUES(?,?,'queued',?)", c.CardID, string(raw), time.Now().UnixNano()) return err }) } type AccessEngine struct { Authorize func(context.Context, string) error State *State Forge AccessForge Refresh func() Notify func() Logger *slog.Logger } // Step files at most once. An interrupted POST has an uncertain outcome and // needs a fresh person confirmation; a saved id always resumes by GET. func (e *AccessEngine) Step(ctx context.Context, id string) error { var command, report, state string if err := e.State.db.QueryRowContext(ctx, "SELECT command,report,state FROM access_requests WHERE card_id=?", id).Scan(&command, &report, &state); err != nil { return err } if wire.AccessFinal(state) { return nil } var cmd wire.AccessCommand var old wire.AccessReport if json.Unmarshal([]byte(command), &cmd) != nil { return errAccess } if report != "" && json.Unmarshal([]byte(report), &old) != nil { return errAccess } var out wire.AccessReport settled := false localExpiry := false var err error switch state { case "queued": if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET state='filing' WHERE card_id=?", id); err != nil { return err } if e.Authorize != nil { err = e.Authorize(ctx, cmd.CardID) settled = errors.Is(err, ErrWithdrawn) } if errors.Is(err, ErrNoAuthority) || ctx.Err() != nil { _, _ = e.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE access_requests SET state='queued' WHERE card_id=?", id) return err } if err != nil { out.State = "authority" } else { if e.Forge == nil { err = errAccess } else { out, err = e.Forge.RequestAccess(ctx, cmd) } if err != nil { out.State = "failed" if errors.Is(err, errAccessNotOwned) { out.State = "not_owned" } if errors.Is(err, errAccessAlready) { out.State = "already" } if errors.Is(err, errAccessLimit) { out.State = "limited" } if errors.Is(err, errAccessContract) || errors.Is(err, errAccessState) { out.State = "unconfirmed" } } } case "filing": out.State = "unconfirmed" case "pending", "checking_expiry": out, err = e.Forge.PollAccess(ctx, old.RequestID, cmd) if err == nil && out.RequestID != old.RequestID { err = errAccessContract } // A server answer wins over the runner clock. An offline estimate is // provisional and keeps reconciling the saved id, never another POST. 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)) { out, err, localExpiry = old, nil, true out.State = "expired" } if err != nil { final := "" switch { case errors.Is(err, errAccessMissing): final = "missing" case errors.Is(err, errAccessDenied), errors.Is(err, errAccessState): final = "uncheckable" case errors.Is(err, errAccessContract): final = "unconfirmed" } if final == "" { return err } var failures int 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 { return xerr } if failures < 3 { return err } out = old out.State = final } else if _, err = e.State.db.ExecContext(ctx, "UPDATE access_requests SET poll_failures=0 WHERE card_id=?", id); err != nil { return err } default: return errAccess } out.CardID, out.Person = cmd.CardID, cmd.Person if out.ApproveURL == "" { out.ApproveURL = old.ApproveURL } if out.Expires == 0 { out.Expires = old.Expires } raw, _ := json.Marshal(out) savedState := out.State if localExpiry { savedState = "checking_expiry" } if err := e.State.tx(ctx, func(tx *sql.Tx) error { if _, err := tx.Exec("UPDATE access_requests SET state=?,report=? WHERE card_id=?", savedState, string(raw), id); err != nil { return err } if string(raw) == report || settled { return nil } return e.State.enqueue(tx, wire.FrameAccess, "", out) }); err != nil { return err } if out.State == "approved" || out.State == "already" { e.Forge.Recheck() e.Forge.Reachable(ctx) if e.Refresh != nil { e.Refresh() } } if e.Notify != nil { e.Notify() } return nil } // Run reserves a filing worker independently of the five long polls. // SQLite insertion order breaks confirmation-time ties, including legacy rows. func (e *AccessEngine) Run(ctx context.Context) { var wg sync.WaitGroup defer wg.Wait() type finished struct { id string filing bool err error } active := map[string]bool{} next := map[string]time.Time{} delays := map[string]time.Duration{} done := make(chan finished, 6) filing, polls := false, 0 tick := time.NewTicker(time.Second) defer tick.Stop() for { select { case <-ctx.Done(): return case result := <-done: delete(active, result.id) if result.filing { filing = false } else { polls-- } delay := time.Second var state string if e.State.db.QueryRowContext(ctx, "SELECT state FROM access_requests WHERE card_id=?", result.id).Scan(&state) == nil && state == "checking_expiry" { delay = time.Minute } if result.err != nil { delay = min(max(delays[result.id]*2, 2*time.Second), time.Minute) } delays[result.id] = delay next[result.id] = time.Now().Add(delay) case <-tick.C: 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") if err != nil { continue } var jobs []struct{ id, state string } for rows.Next() { var j struct{ id, state string } if rows.Scan(&j.id, &j.state) == nil { jobs = append(jobs, j) } } rows.Close() for _, j := range jobs { fresh := j.state == "queued" || j.state == "filing" if active[j.id] || time.Now().Before(next[j.id]) || fresh && filing || !fresh && polls >= 5 { continue } active[j.id] = true if fresh { filing = true } else { polls++ } wg.Add(1) go func(id string, fresh bool) { defer wg.Done(); err := e.Step(ctx, id); done <- finished{id, fresh, err} }(j.id, fresh) } } } } func migrateAccess(ctx context.Context, db *sql.DB) error { for _, column := range []string{"confirmed_at INTEGER NOT NULL DEFAULT 0", "poll_failures INTEGER NOT NULL DEFAULT 0"} { if _, err := db.ExecContext(ctx, "ALTER TABLE access_requests ADD COLUMN "+column); err != nil && !strings.Contains(err.Error(), "duplicate column") { return err } } return nil }