package thin import ( "context" "database/sql" "errors" "time" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/wire" ) // The metered guard for questions (connectors spec §7, "Ask"). A // question stays on its step's own session and connection; when that // connection is metered it passes the same guard as a step, in the same // admission transaction as its start: the slot free, the spend known, // the day's and the month's budget not reached. Consent is the question // itself. A question the guard refuses is held, never moved: it reports // queued with the hold as its reason and goes on its own when the facts // change (MeteredChanged) or, for the budget, at the next day. // heldUntilChange is a held question's not_before while it waits for a // fact to change (the slot, a Resume), not for a time. const heldUntilChange = "999999999999999" // MeteredAskFunc answers a question on a metered connection (S2's Pi // adapter): the report, with the harness's usage rows, and how the // attempt ended. l.Namespace records its namespace before it starts. type MeteredAskFunc func(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) // meteredAsk is the metered connection a question's kept session is on, // and the model the session was created on (§16.3: a question runs on // that model or fails, never moving). func (e *StepEngine) meteredAsk(ctx context.Context, a askRow) (string, string, bool) { if e.Meter == nil { return "", "", false } kept, found, _, err := e.State.keptForAsk(ctx, a.AskCommand) if err != nil || !found { return "", "", false } c, ok, err := metered.Get(ctx, e.State.db, kept.Account) if err != nil || !ok { return "", "", false } return c.LocalID, kept.Model, true } // askMetered runs a question on metered connection local through the // guard. With no harness for it here, it fails without claiming the // slot. func (e *StepEngine) askMetered(ctx, actx context.Context, a askRow, local, model string, report func(wire.AnswerReport)) { finish := func(rep wire.AnswerReport) { if err := e.State.startAsk(ctx, a); err != nil { e.log("ask start", err) return } e.log("answer report", e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, true)) e.Notify() } base := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} if e.MeteredAsk == nil { rep := base rep.State, rep.Reason = wire.QuestionFailed, "account_unavailable" finish(rep) return } h := metered.Holder{Step: a.QuestionID, Attempt: a.Attempt, Role: metered.RoleAsk, Model: model} adm, err := e.Meter.Admit(ctx, local, h, func(t *sql.Tx) error { return startAskTx(t, a) }) if err != nil { e.log("ask admission", err) _, herr := e.State.holdAsk(ctx, a, "", time.Now().Add(heldRetry)) e.log("ask hold", herr) time.AfterFunc(heldRetry, e.Wake) return } if !adm.Admitted && adm.Hold == metered.HoldModel { // The session's model was removed from the set or is unhealthy: // the question fails, never moving to another model (§16.3). rep := base rep.State, rep.Reason = wire.QuestionFailed, wire.ReasonModelUnavailable finish(rep) return } if !adm.Admitted { changed, err := e.State.holdAsk(ctx, a, adm.Hold, adm.WakeAt) if err != nil { e.log("ask hold", err) return } if changed { // Said once per hold, not at every look. held := base held.State, held.Reason = wire.QuestionQueued, adm.Hold report(held) } return } l := metered.Launch{Holder: h, Namespace: func(ns string) error { if err := e.State.setAskNamespace(ctx, a, ns); err != nil { return err } return e.Meter.Namespace(ctx, local, h, ns) }} if c, ok, err := metered.Get(ctx, e.State.db, local); err == nil && ok { l.Conn = c } rep, ending := e.MeteredAsk(actx, a, l, func(p wire.AnswerReport) { p.State = wire.QuestionRunning report(p) }) if actx.Err() != nil && rep.State != wire.QuestionAnswered { rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" } if !wire.QuestionTerminal(rep.State) { rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" } rep.TaskID, rep.QuestionID, rep.Attempt = a.TaskID, a.QuestionID, a.Attempt // The charge, the answer and (once proven) the slot's release commit // together; a failed write is tried again, never the harness. for i := 0; ; i++ { err := e.Meter.Finish(context.WithoutCancel(ctx), local, h, metered.Result{Usage: rep.Usage, Ending: ending}, func(t *sql.Tx, priced []wire.Usage) error { out := rep out.Usage = priced return e.State.finishAskTx(t, a, out, ending.Proven) }) if err == nil { break } e.log("answer report", err) select { case <-ctx.Done(): return case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)): } } e.Notify() } // startAskTx marks a question started in the guard's transaction. func startAskTx(t *sql.Tx, a askRow) error { 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) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return errors.New("question attempt not runnable") } return nil } // holdAsk holds a question for its guard: until a fact changes, or (for // the budget) until the next day or month. It reports whether the hold // is not the one the question already had. func (s *State) holdAsk(ctx context.Context, a askRow, hold string, until time.Time) (bool, error) { at := heldUntilChange if !until.IsZero() { at = stamp(until) } changed := false err := s.tx(ctx, func(t *sql.Tx) error { var was string if err := t.QueryRow("SELECT hold FROM asks WHERE question_id=? AND attempt=?", a.QuestionID, a.Attempt).Scan(&was); err != nil { return err } changed = was != hold _, 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) return err }) return changed, err } // MeteredChanged looks at held questions again: a slot was released, a // budget applied, a pause resumed, or a connection's standing changed. func (e *StepEngine) MeteredChanged() { if _, err := e.State.db.Exec("UPDATE asks SET not_before='' WHERE hold<>'' AND state=? AND started=0", runRunning); err != nil { e.log("ask holds", err) } // Steps the scheduler holds look again too (connectors spec §7: on // any reading, step end, budget change or preference change). e.log("step holds", e.State.wakeHeld(context.Background())) e.Wake() }