| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | // The metered guard for questions (connectors spec §7, "Ask"). A |
| 14 | // question stays on its step's own session and connection; when that |
| 15 | // connection is metered it passes the same guard as a step, in the same |
| 16 | // admission transaction as its start: the slot free, the spend known, |
| 17 | // the day's and the month's budget not reached. Consent is the question |
| 18 | // itself. A question the guard refuses is held, never moved: it reports |
| 19 | // queued with the hold as its reason and goes on its own when the facts |
| 20 | // change (MeteredChanged) or, for the budget, at the next day. |
| 21 | |
| 22 | // heldUntilChange is a held question's not_before while it waits for a |
| 23 | // fact to change (the slot, a Resume), not for a time. |
| 24 | const heldUntilChange = "999999999999999" |
| 25 | |
| 26 | // MeteredAskFunc answers a question on a metered connection (S2's Pi |
| 27 | // adapter): the report, with the harness's usage rows, and how the |
| 28 | // attempt ended. l.Namespace records its namespace before it starts. |
| 29 | type MeteredAskFunc func(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) |
| 30 | |
| 31 | // meteredAsk is the metered connection a question's kept session is on, |
| 32 | // and the model the session was created on (§16.3: a question runs on |
| 33 | // that model or fails, never moving). |
| 34 | func (e *StepEngine) meteredAsk(ctx context.Context, a askRow) (string, string, bool) { |
| 35 | if e.Meter == nil { |
| 36 | return "", "", false |
| 37 | } |
| 38 | kept, found, _, err := e.State.keptForAsk(ctx, a.AskCommand) |
| 39 | if err != nil || !found { |
| 40 | return "", "", false |
| 41 | } |
| 42 | c, ok, err := metered.Get(ctx, e.State.db, kept.Account) |
| 43 | if err != nil || !ok { |
| 44 | return "", "", false |
| 45 | } |
| 46 | return c.LocalID, kept.Model, true |
| 47 | } |
| 48 | |
| 49 | // askMetered runs a question on metered connection local through the |
| 50 | // guard. With no harness for it here, it fails without claiming the |
| 51 | // slot. |
| 52 | func (e *StepEngine) askMetered(ctx, actx context.Context, a askRow, local, model string, report func(wire.AnswerReport)) { |
| 53 | finish := func(rep wire.AnswerReport) { |
| 54 | if err := e.State.startAsk(ctx, a); err != nil { |
| 55 | e.log("ask start", err) |
| 56 | return |
| 57 | } |
| 58 | e.log("answer report", e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, true)) |
| 59 | e.Notify() |
| 60 | } |
| 61 | base := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} |
| 62 | if e.MeteredAsk == nil { |
| 63 | rep := base |
| 64 | rep.State, rep.Reason = wire.QuestionFailed, "account_unavailable" |
| 65 | finish(rep) |
| 66 | return |
| 67 | } |
| 68 | h := metered.Holder{Step: a.QuestionID, Attempt: a.Attempt, Role: metered.RoleAsk, Model: model} |
| 69 | adm, err := e.Meter.Admit(ctx, local, h, func(t *sql.Tx) error { return startAskTx(t, a) }) |
| 70 | if err != nil { |
| 71 | e.log("ask admission", err) |
| 72 | _, herr := e.State.holdAsk(ctx, a, "", time.Now().Add(heldRetry)) |
| 73 | e.log("ask hold", herr) |
| 74 | time.AfterFunc(heldRetry, e.Wake) |
| 75 | return |
| 76 | } |
| 77 | if !adm.Admitted && adm.Hold == metered.HoldModel { |
| 78 | // The session's model was removed from the set or is unhealthy: |
| 79 | // the question fails, never moving to another model (§16.3). |
| 80 | rep := base |
| 81 | rep.State, rep.Reason = wire.QuestionFailed, wire.ReasonModelUnavailable |
| 82 | finish(rep) |
| 83 | return |
| 84 | } |
| 85 | if !adm.Admitted { |
| 86 | changed, err := e.State.holdAsk(ctx, a, adm.Hold, adm.WakeAt) |
| 87 | if err != nil { |
| 88 | e.log("ask hold", err) |
| 89 | return |
| 90 | } |
| 91 | if changed { |
| 92 | // Said once per hold, not at every look. |
| 93 | held := base |
| 94 | held.State, held.Reason = wire.QuestionQueued, adm.Hold |
| 95 | report(held) |
| 96 | } |
| 97 | return |
| 98 | } |
| 99 | l := metered.Launch{Holder: h, Namespace: func(ns string) error { |
| 100 | if err := e.State.setAskNamespace(ctx, a, ns); err != nil { |
| 101 | return err |
| 102 | } |
| 103 | return e.Meter.Namespace(ctx, local, h, ns) |
| 104 | }} |
| 105 | if c, ok, err := metered.Get(ctx, e.State.db, local); err == nil && ok { |
| 106 | l.Conn = c |
| 107 | } |
| 108 | rep, ending := e.MeteredAsk(actx, a, l, func(p wire.AnswerReport) { |
| 109 | p.State = wire.QuestionRunning |
| 110 | report(p) |
| 111 | }) |
| 112 | if actx.Err() != nil && rep.State != wire.QuestionAnswered { |
| 113 | rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| 114 | } |
| 115 | if !wire.QuestionTerminal(rep.State) { |
| 116 | rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" |
| 117 | } |
| 118 | rep.TaskID, rep.QuestionID, rep.Attempt = a.TaskID, a.QuestionID, a.Attempt |
| 119 | // The charge, the answer and (once proven) the slot's release commit |
| 120 | // together; a failed write is tried again, never the harness. |
| 121 | for i := 0; ; i++ { |
| 122 | err := e.Meter.Finish(context.WithoutCancel(ctx), local, h, metered.Result{Usage: rep.Usage, Ending: ending}, func(t *sql.Tx, priced []wire.Usage) error { |
| 123 | out := rep |
| 124 | out.Usage = priced |
| 125 | return e.State.finishAskTx(t, a, out, ending.Proven) |
| 126 | }) |
| 127 | if err == nil { |
| 128 | break |
| 129 | } |
| 130 | e.log("answer report", err) |
| 131 | select { |
| 132 | case <-ctx.Done(): |
| 133 | return |
| 134 | case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)): |
| 135 | } |
| 136 | } |
| 137 | e.Notify() |
| 138 | } |
| 139 | |
| 140 | // startAskTx marks a question started in the guard's transaction. |
| 141 | func startAskTx(t *sql.Tx, a askRow) error { |
| 142 | res, err := t.Exec("UPDATE asks SET started=1, hold='', not_before='' WHERE question_id=? AND attempt=? AND state=? AND started=0", a.QuestionID, a.Attempt, runRunning) |
| 143 | if err != nil { |
| 144 | return err |
| 145 | } |
| 146 | if n, _ := res.RowsAffected(); n != 1 { |
| 147 | return errors.New("question attempt not runnable") |
| 148 | } |
| 149 | return nil |
| 150 | } |
| 151 | |
| 152 | // holdAsk holds a question for its guard: until a fact changes, or (for |
| 153 | // the budget) until the next day or month. It reports whether the hold |
| 154 | // is not the one the question already had. |
| 155 | func (s *State) holdAsk(ctx context.Context, a askRow, hold string, until time.Time) (bool, error) { |
| 156 | at := heldUntilChange |
| 157 | if !until.IsZero() { |
| 158 | at = stamp(until) |
| 159 | } |
| 160 | changed := false |
| 161 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 162 | var was string |
| 163 | if err := t.QueryRow("SELECT hold FROM asks WHERE question_id=? AND attempt=?", a.QuestionID, a.Attempt).Scan(&was); err != nil { |
| 164 | return err |
| 165 | } |
| 166 | changed = was != hold |
| 167 | _, err := t.Exec("UPDATE asks SET hold=?, not_before=? WHERE question_id=? AND attempt=? AND state=? AND started=0", hold, at, a.QuestionID, a.Attempt, runRunning) |
| 168 | return err |
| 169 | }) |
| 170 | return changed, err |
| 171 | } |
| 172 | |
| 173 | // MeteredChanged looks at held questions again: a slot was released, a |
| 174 | // budget applied, a pause resumed, or a connection's standing changed. |
| 175 | func (e *StepEngine) MeteredChanged() { |
| 176 | if _, err := e.State.db.Exec("UPDATE asks SET not_before='' WHERE hold<>'' AND state=? AND started=0", runRunning); err != nil { |
| 177 | e.log("ask holds", err) |
| 178 | } |
| 179 | // Steps the scheduler holds look again too (connectors spec §7: on |
| 180 | // any reading, step end, budget change or preference change). |
| 181 | e.log("step holds", e.State.wakeHeld(context.Background())) |
| 182 | e.Wake() |
| 183 | } |
| 184 | |