package metered import ( "bytes" "context" "database/sql" "encoding/json" "errors" "slices" "strings" "time" "amadan.net/oficina/equipo/internal/wire" ) // A metered connection's allowed set (connectors spec rev 3.3, §16.1, // §16.4): metered_models holds one row per allowed model with its state // (unprobed, healthy, unhealthy), when and why it failed. The set is // the rows; metered_connections.models_revision is the set's revision, // which only rises. A removed model's row goes: it is never admitted // again, and a model allowed again starts unprobed. const modelsSchema = ` CREATE TABLE IF NOT EXISTS metered_models (local_id TEXT NOT NULL, model TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'unprobed', failed_at TEXT NOT NULL DEFAULT '', reason TEXT NOT NULL DEFAULT '', PRIMARY KEY (local_id, model)); ` // RetryAfter is how long an unhealthy model waits before a step that // would pick it may probe it again (§16.4): on demand only, never by a // timer. const RetryAfter = 24 * time.Hour // HoldModel is the guard's answer when the attempt's model is not one it // may run on now: removed from the set, no longer eligible, or (for a // step) not proven healthy. A question fails with it // (model_unavailable); a step decides again. const HoldModel = wire.ReasonModelUnavailable // Model is one allowed model on a connection. type Model struct { ID, State, Reason string FailedAt time.Time } // Retryable reports whether an unhealthy model may be probed again on // demand at now: a day after it failed. A model_mismatch never is: it // stays unhealthy until Check again (§16.5). func (m Model) Retryable(now time.Time) bool { return m.State == wire.ModelUnhealthy && m.Reason != wire.ModelMismatch && !m.FailedAt.IsZero() && !now.Before(m.FailedAt.Add(RetryAfter)) } // Migrate brings an older thin.db to the allowed sets (§16.5): the // column, then every connection that has none yet. With a model picked // (S1's one model) the set is that model, healthy when the connection // was proven on it and unprobed otherwise, no time invented; with none // picked, every model that can be allowed, unprobed. Its revision is 1. func Migrate(ctx context.Context, db *sql.DB) error { if _, err := db.ExecContext(ctx, modelsSchema); err != nil { return err } for _, col := range []string{"models_revision INTEGER NOT NULL DEFAULT 0", "listed TEXT NOT NULL DEFAULT ''"} { if _, err := db.ExecContext(ctx, "ALTER TABLE metered_connections ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") { return err } } tx, err := db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() conns, err := List(ctx, tx) if err != nil { return err } for _, c := range conns { if c.ModelsRevision != 0 { continue } var allowed []Model if c.Model != "" { state := wire.ModelUnprobed if c.Validated { state = wire.ModelHealthy } allowed = []Model{{ID: c.Model, State: state}} } else if table, ok := TableFor(c.PriceVersion); ok { for id := range table.Models { if _, _, ok := Eligible(c.Provider, c.PriceVersion, id); ok { allowed = append(allowed, Model{ID: id, State: wire.ModelUnprobed}) } } } for _, m := range allowed { if _, err := tx.ExecContext(ctx, "INSERT INTO metered_models(local_id, model, state) VALUES(?,?,?) ON CONFLICT DO NOTHING", c.LocalID, m.ID, m.State); err != nil { return err } } if _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET models_revision=1 WHERE local_id=? AND models_revision=0", c.LocalID); err != nil { return err } } return tx.Commit() } // SetListed records the models the key listed when it was last read // (at connect, and on Check again): the page's choices. func SetListed(ctx context.Context, tx *sql.Tx, local string, listed []string) error { raw, err := json.Marshal(listed) if err != nil { return err } _, err = tx.ExecContext(ctx, "UPDATE metered_connections SET listed=? WHERE local_id=?", string(raw), local) return err } // listedOf is the key's list as this runner last read it (nil: never // read, a connection from before S5b). func listedOf(ctx context.Context, q querier, local string) ([]string, error) { var raw string if err := q.QueryRowContext(ctx, "SELECT listed FROM metered_connections WHERE local_id=?", local).Scan(&raw); err != nil { return nil, err } if raw == "" { return nil, nil } var listed []string if err := json.Unmarshal([]byte(raw), &listed); err != nil { return nil, err } if listed == nil { listed = []string{} } return listed, nil } // Choices are the models a connection's key listed, each with whether it // can be allowed now (priced in the connection's table, tiered now), // sorted; none when the list was never read (a connection from before // S5b, until Check again). func Choices(ctx context.Context, q querier, c Conn) ([]wire.ModelChoice, error) { listed, err := listedOf(ctx, q, c.LocalID) if err != nil { return nil, err } slices.Sort(listed) out := []wire.ModelChoice{} for _, m := range slices.Compact(listed) { t, _, ok := Eligible(c.Provider, c.PriceVersion, m) out = append(out, wire.ModelChoice{ID: m, Eligible: ok, Family: t.Family, Tier: t.Tier}) } return CapChoices(out), nil } // CapChoices bounds a key's list to what a card or hello may carry // (wire.MaxModels): the models that can be allowed first, then the rest, // each in its order. func CapChoices(cs []wire.ModelChoice) []wire.ModelChoice { if len(cs) <= wire.MaxModels { return cs } out := make([]wire.ModelChoice, 0, wire.MaxModels) for _, eligible := range []bool{true, false} { for _, c := range cs { if c.Eligible == eligible && len(out) < wire.MaxModels { out = append(out, c) } } } return out } // Models is a connection's allowed set, by model id. func Models(ctx context.Context, q querier, local string) ([]Model, error) { rows, err := q.QueryContext(ctx, "SELECT model, state, failed_at, reason FROM metered_models WHERE local_id=? ORDER BY model", local) if err != nil { return nil, err } defer rows.Close() var out []Model for rows.Next() { var m Model var at string if err := rows.Scan(&m.ID, &m.State, &at, &m.Reason); err != nil { return nil, err } if at != "" { m.FailedAt, _ = time.Parse(time.RFC3339Nano, at) } out = append(out, m) } return out, rows.Err() } // modelOf is one allowed model (false: not in the set). func modelOf(ctx context.Context, q querier, local, model string) (Model, bool, error) { var m Model var at string err := q.QueryRowContext(ctx, "SELECT model, state, failed_at, reason FROM metered_models WHERE local_id=? AND model=?", local, model).Scan(&m.ID, &m.State, &at, &m.Reason) if errors.Is(err, sql.ErrNoRows) { return m, false, nil } if at != "" { m.FailedAt, _ = time.Parse(time.RFC3339Nano, at) } return m, err == nil, err } // ErrNotAllowable: a set holds a model that cannot be allowed (not // eligible on this connection), or none. var ErrNotAllowable = errors.New("metered: a model in the set cannot be allowed") // SetModels applies a connection's allowed set at revision, in the // caller's transaction (§16.1): only above the revision held, only for // the connection the frame names, only a set of models that can be // allowed. Models kept keep their state, new ones start unprobed, and a // removed one goes (a step already running on it finishes). The // connection's one model (S1's, which an older instance shows) becomes // the cheapest allowed. It reports whether it applied. func SetModels(ctx context.Context, tx *sql.Tx, local, connection string, allowed []string, revision int64) (bool, error) { c, ok, err := Get(ctx, tx, local) if err != nil || !ok { return false, firstErr(err, ErrNotMetered) } if c.Connection == "" || c.Connection != connection || revision <= c.ModelsRevision { return false, nil } if !wire.ValidAllowed(allowed) { return false, ErrNotAllowable } for _, m := range allowed { if _, _, ok := Eligible(c.Provider, c.PriceVersion, m); !ok { return false, ErrNotAllowable } } // Only models the key lists (§16.1), from the list this runner read, // in this transaction. A connection from before S5b has no list until // Check again reads one: its set may shrink or stay, never grow. listed, err := listedOf(ctx, tx, local) if err != nil { return false, err } held, err := Models(ctx, tx, local) if err != nil { return false, err } for _, m := range allowed { if listed != nil && !slices.Contains(listed, m) || listed == nil && !slices.ContainsFunc(held, func(h Model) bool { return h.ID == m }) { return false, ErrNotAllowable } } // The revision moves first, bound to the connection and above the // one held, so a frame that does not bind changes no row. res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET models_revision=?, model=? WHERE local_id=? AND connection=? AND models_revision