| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/runner" |
| 10 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // heldRecheck bounds how long a turn held for a connection waits before |
| 15 | // it looks again on its own (a connection added by the terminal login, |
| 16 | // or one whose cool-off ended, wakes it sooner). |
| 17 | const heldRecheck = time.Minute |
| 18 | |
| 19 | // converse runs one turn on the person's chosen connection (spec §3). A |
| 20 | // turn the provider refuses on quota marks that connection limited and |
| 21 | // starts again, as a new attempt, on the next connection the choice |
| 22 | // gives: a new session there, seeded from the notebook and the tail like |
| 23 | // any fresh session, with the draft of the refused attempt discarded and |
| 24 | // one quiet switched line on the reply. When no connection can answer, |
| 25 | // the turn is held (state running, reason no_connection): the message |
| 26 | // waits and the turn goes on its own when a connection returns. |
| 27 | func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, act func(kind, tool string)) TurnResult { |
| 28 | var switched *wire.Switched |
| 29 | held := false |
| 30 | // The connection that answered the person last: a reply from another |
| 31 | // one says so, whether this turn moved or waited for it. |
| 32 | conn := connKey(person, r.Lane) |
| 33 | last, _ := e.State.meta(ctx, conn) |
| 34 | // An Assistant person turn's glance: asked once, beside the first |
| 35 | // attempt, and closed when the reply's first words go or the turn |
| 36 | // ends, so it is sent before them or never. |
| 37 | var gl *glanceRun |
| 38 | defer func() { |
| 39 | if gl != nil { |
| 40 | gl.close() |
| 41 | } |
| 42 | }() |
| 43 | for { |
| 44 | b, choice, err := e.choose(ctx, person, conn, w.connID) |
| 45 | if errors.Is(err, ErrNoConnection) { |
| 46 | if !held { |
| 47 | held = true |
| 48 | e.log("runner hold", e.State.Hold(e.ctx, *r, wire.ReasonNoConnection)) |
| 49 | e.Notify() |
| 50 | } |
| 51 | if !e.waitConnection(ctx, person, w) { |
| 52 | return TurnResult{Reason: "cancelled"} |
| 53 | } |
| 54 | continue |
| 55 | } |
| 56 | if err != nil { |
| 57 | e.log("runner choose", err) |
| 58 | return TurnResult{Reason: "account_unavailable"} |
| 59 | } |
| 60 | if held { |
| 61 | held = false |
| 62 | e.log("runner hold", e.State.Hold(e.ctx, *r, "")) |
| 63 | e.Notify() |
| 64 | } |
| 65 | if err := e.seat(ctx, person, r.Lane, conn, w, b); err != nil { |
| 66 | e.log("coordinator open", err) |
| 67 | return TurnResult{Reason: "account_unavailable"} |
| 68 | } |
| 69 | _ = choice |
| 70 | var offset int64 |
| 71 | var done []string |
| 72 | if r.Attempt > 1 { |
| 73 | done = e.State.doneEarlier(ctx, r.TurnID, r.Attempt) |
| 74 | } |
| 75 | if gl == nil && e.Glance != nil && r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson { |
| 76 | gl = e.startGlance(ctx, person, w, r, b) |
| 77 | } |
| 78 | res := w.coord.Turn(ctx, TurnInput{PlacementNotes: r.PlacementNotes, Person: person, Lane: r.Lane, TurnID: r.TurnID, Kind: r.Kind, Attempt: r.Attempt, Text: r.Text, PersonText: r.PersonText, Tail: r.Tail, Attachments: r.Attachments, Earlier: r.Earlier, EarlierMore: r.EarlierMore, Received: r.Received, Activity: act, Done: done}, func(text string) { |
| 79 | if gl != nil { |
| 80 | gl.close() |
| 81 | } |
| 82 | e.Emit(wire.DeltaReport{TurnID: r.TurnID, Attempt: r.Attempt, Offset: offset, Text: text}) |
| 83 | offset += int64(len(text)) |
| 84 | }) |
| 85 | if e.Conns != nil && res.Seen != nil { |
| 86 | e.Conns.Observe(b.ID, *res.Seen, res.Plan) |
| 87 | } |
| 88 | if res.Limit != nil && e.Conns != nil { |
| 89 | e.Conns.Limit(b.ID, *res.Limit) |
| 90 | } |
| 91 | if res.SignIn && e.Conns != nil { |
| 92 | e.Conns.SignInAgain(b.ID) |
| 93 | } |
| 94 | res.rows = usageRows(res.Usage, b, r.Attempt, wire.OutcomeReplied) |
| 95 | if res.Limit == nil && !res.SignIn || !res.Proven || ctx.Err() != nil || e.Conns == nil { |
| 96 | if res.Reason == "" && e.Conns != nil { |
| 97 | // An answer proves the credential, whatever a check said. |
| 98 | e.Conns.Answered(b.ID) |
| 99 | e.log("runner session", e.State.setMeta(context.WithoutCancel(ctx), conn, b.ID)) |
| 100 | } |
| 101 | |
| 102 | if switched == nil && res.Reason == "" && last != "" && last != b.ID && e.Conns != nil { |
| 103 | switched = e.Conns.LimitedFrom(last) |
| 104 | } |
| 105 | if switched != nil && res.Reason == "" { |
| 106 | switched.To = b.Provider |
| 107 | res.Switched = switched |
| 108 | } |
| 109 | res.glance = gl |
| 110 | // The glance harness stays warm beside the Assistant's. |
| 111 | if r.Lane == wire.LaneAssistant && res.Reason == "" { |
| 112 | e.warmGlance(person, w, b) |
| 113 | } |
| 114 | return res |
| 115 | } |
| 116 | // Refused on quota, and the attempt's exit proven: a new attempt, |
| 117 | // advanced durably before anything runs, on the next connection. |
| 118 | if switched == nil { |
| 119 | switched = e.Conns.LimitedFrom(b.ID) |
| 120 | if res.SignIn { |
| 121 | switched = &wire.Switched{From: b.Provider} |
| 122 | } |
| 123 | } |
| 124 | w.coord.Close() |
| 125 | w.coord = nil |
| 126 | if err := e.State.Retry(e.ctx, r, waitReason(res), usageRows(res.Usage, b, r.Attempt, wire.OutcomeFailed)); err != nil { |
| 127 | e.log("runner retry", err) |
| 128 | return TurnResult{Reason: "limited"} |
| 129 | } |
| 130 | e.mu.Lock() |
| 131 | w.attempt = r.Attempt |
| 132 | e.mu.Unlock() |
| 133 | e.Notify() |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // seat makes the worker's harness the one on connection b, closing one |
| 138 | // on another connection; conn is the lane's connKey. |
| 139 | func (e *Engine) seat(ctx context.Context, person, lane, conn string, w *worker, b runner.AccountBinding) error { |
| 140 | if w.coord != nil && w.connID == b.ID { |
| 141 | return nil |
| 142 | } |
| 143 | if w.coord != nil { |
| 144 | w.coord.Close() |
| 145 | w.coord = nil |
| 146 | } |
| 147 | // A session the conversation went on without is stale: coming back |
| 148 | // to a connection starts afresh from the notebook and the tail, never |
| 149 | // resumes a session that missed turns. |
| 150 | if last, _ := e.State.meta(ctx, conn); last != "" && last != b.ID { |
| 151 | e.log("runner session", e.State.deleteSession(ctx, person, lane)) |
| 152 | } |
| 153 | c, err := e.Open(person, lane, b) |
| 154 | if err != nil { |
| 155 | return err |
| 156 | } |
| 157 | w.coord, w.connID = c, b.ID |
| 158 | return nil |
| 159 | } |
| 160 | |
| 161 | // usageRows fills an attempt's rows with what ran it: one row with no |
| 162 | // figures (complete false) when the harness reported nothing, so the |
| 163 | // attempt is recorded all the same. |
| 164 | func usageRows(rows []wire.Usage, b runner.AccountBinding, attempt int64, outcome string) []wire.Usage { |
| 165 | if b.ID == "" { |
| 166 | // No connection (an engine test without one): nothing to key a row by. |
| 167 | return []wire.Usage{} |
| 168 | } |
| 169 | if len(rows) == 0 { |
| 170 | rows = []wire.Usage{{}} |
| 171 | } |
| 172 | out := make([]wire.Usage, len(rows)) |
| 173 | for i, u := range rows { |
| 174 | u.Provider, u.Connection, u.Attempt, u.Outcome = b.Provider, b.ID, attempt, outcome |
| 175 | if u.Model == "" { |
| 176 | u.Model = b.Model |
| 177 | } |
| 178 | out[i] = u |
| 179 | } |
| 180 | return out |
| 181 | } |
| 182 | |
| 183 | // waitReason is why a turn waits between attempts: its connection was |
| 184 | // limited, or refused the credential. |
| 185 | func waitReason(res TurnResult) string { |
| 186 | if res.SignIn { |
| 187 | return "sign_in_again" |
| 188 | } |
| 189 | return "limited" |
| 190 | } |
| 191 | |
| 192 | // connKey is where the connection that answered a lane last is kept. |
| 193 | // The coordinator's key is the one it had before the Assistant. |
| 194 | func connKey(person, lane string) string { |
| 195 | if lane == wire.LaneCoordinator { |
| 196 | return "conn:" + person |
| 197 | } |
| 198 | return "conn:" + person + "#" + lane |
| 199 | } |
| 200 | |
| 201 | // choose asks Conns for the connection of the person's lane (conn is its |
| 202 | // connKey); without Conns (engine tests) every turn runs on a zero |
| 203 | // binding. |
| 204 | func (e *Engine) choose(ctx context.Context, person, conn, current string) (runner.AccountBinding, connect.Choice, error) { |
| 205 | if e.Conns == nil { |
| 206 | return runner.AccountBinding{}, connect.Choice{Reason: connect.ReasonOnlyOption}, nil |
| 207 | } |
| 208 | if current == "" { |
| 209 | // After a restart the session's connection is the one that |
| 210 | // answered last: stickiness holds across processes. |
| 211 | current, _ = e.State.meta(ctx, conn) |
| 212 | } |
| 213 | return e.Conns.Choose(ctx, person, connect.RoleCoordinator, current, nil) |
| 214 | } |
| 215 | |
| 216 | // waitConnection waits for a connection to come back: a change in the |
| 217 | // connections, the earliest provider reset, or a minute. False means the |
| 218 | // turn was cancelled or the runner is stopping. |
| 219 | func (e *Engine) waitConnection(ctx context.Context, person string, w *worker) bool { |
| 220 | wait := heldRecheck |
| 221 | if at := e.Conns.NextCheck(person); !at.IsZero() { |
| 222 | wait = min(wait, max(time.Until(at), 0)+time.Second) |
| 223 | } |
| 224 | select { |
| 225 | case <-ctx.Done(): |
| 226 | return false |
| 227 | case <-w.conn: |
| 228 | case <-time.After(wait): |
| 229 | } |
| 230 | return true |
| 231 | } |
| 232 | |
| 233 | // Hold reports a held turn as waiting for a connection (reason |
| 234 | // no_connection) or, with an empty reason, as running again. The run |
| 235 | // stays held here; only the instance's view changes. |
| 236 | func (s *State) Hold(ctx context.Context, r run, reason string) error { |
| 237 | state := wire.TurnRunning |
| 238 | if reason != "" { |
| 239 | state = wire.TurnWaiting |
| 240 | } |
| 241 | return s.tx(ctx, func(t *sql.Tx) error { |
| 242 | return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: reason}) |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | // Retry starts a new attempt of a held run after its connection was |
| 247 | // refused: the instance learns of it (state running, the new attempt) |
| 248 | // in the same transaction, so a draft of the old attempt is dropped and |
| 249 | // a cancel names the new one. |
| 250 | func (s *State) Retry(ctx context.Context, r *run, reason string, used []wire.Usage) error { |
| 251 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 252 | res, err := t.Exec("UPDATE runs SET attempt=attempt+1 WHERE turn_id=? AND attempt=? AND state=?", r.TurnID, r.Attempt, runRunning) |
| 253 | if err != nil { |
| 254 | return err |
| 255 | } |
| 256 | if n, _ := res.RowsAffected(); n != 1 { |
| 257 | return errors.New("run not held") |
| 258 | } |
| 259 | if len(used) > 0 { |
| 260 | // What the refused attempt used, recorded against it. |
| 261 | if err = s.enqueue(t, wire.FrameUsage, r.TurnID, wire.UsageReport{TurnID: r.TurnID, Rows: used}); err != nil { |
| 262 | return err |
| 263 | } |
| 264 | } |
| 265 | // The turn waits between attempts (spec §3 step 2): the draft goes, |
| 266 | // and the instance takes the new attempt only after it. |
| 267 | if err = s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnWaiting, Reason: reason}); err != nil { |
| 268 | return err |
| 269 | } |
| 270 | return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt + 1, State: wire.TurnRunning}) |
| 271 | }) |
| 272 | if err == nil { |
| 273 | r.Attempt++ |
| 274 | } |
| 275 | return err |
| 276 | } |
| 277 | |