| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 14 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // API-key connections (connectors spec 2026-11-12, §2.2, slice S1). The |
| 20 | // person pastes a provider key (TensorX); the page seals it to this |
| 21 | // runner as a Claude token is sealed, and it is delivered the same way |
| 22 | // (Secret, keep) into the connection's own home, 0600. The runner, never |
| 23 | // a namespace, reads the provider's model list with it; the person picks |
| 24 | // the one model from those Equipo can price; a one-token completion on |
| 25 | // that model, admitted through the metered guard and charged like any |
| 26 | // other attempt (a usage row with role probe), makes the connection |
| 27 | // healthy. The connection lives in thin.db (metered.Conn), not in the |
| 28 | // bindings file: no Claude or Codex launch can ever be given it. |
| 29 | |
| 30 | // errHeld: the metered guard held the probe. |
| 31 | var errHeld = errors.New("the connection's guard held the probe") |
| 32 | |
| 33 | // apiClient is the provider's API at its origin from the table (a test |
| 34 | // points origin at a fake server on 127.0.0.1). |
| 35 | func (c *Connector) apiClient(prov string) (connect.APIClient, bool) { |
| 36 | kp, ok := wire.APIKeyProviders[prov] |
| 37 | if !ok { |
| 38 | return connect.APIClient{}, false |
| 39 | } |
| 40 | origin := kp.Upstream |
| 41 | if c.origin != nil { |
| 42 | origin = c.origin(prov) |
| 43 | } |
| 44 | return connect.APIClient{HTTP: c.http, Origin: origin, Path: kp.APIPath, ModelsPath: kp.ModelsPath}, true |
| 45 | } |
| 46 | |
| 47 | // meter is the runner's metered guard (nil: no metered connection can be |
| 48 | // added). |
| 49 | func (c *Connector) meter() *metered.Meter { |
| 50 | if c.Conns == nil { |
| 51 | return nil |
| 52 | } |
| 53 | return c.Conns.Meter |
| 54 | } |
| 55 | |
| 56 | // meteredHome reports whether a validated metered connection keeps its |
| 57 | // key in home: such a home is deleted only by its sign-out. |
| 58 | func (c *Connector) meteredHome(home string) bool { |
| 59 | var n int |
| 60 | _ = c.State.db.QueryRow("SELECT count(*) FROM metered_connections WHERE home=? AND validated=1", home).Scan(&n) |
| 61 | return n > 0 |
| 62 | } |
| 63 | |
| 64 | // attemptExtra is what an API-key attempt recorded beside its row: its |
| 65 | // billing and budget from the connect frame and the model picked. |
| 66 | func (c *Connector) attemptExtra(ctx context.Context, id string) (billing string, budget wire.Budget, model string, err error) { |
| 67 | var raw string |
| 68 | err = c.State.db.QueryRowContext(ctx, "SELECT billing, budget, model FROM connect_attempts WHERE id=?", id).Scan(&billing, &raw, &model) |
| 69 | if err == nil && raw != "" { |
| 70 | err = json.Unmarshal([]byte(raw), &budget) |
| 71 | } |
| 72 | return billing, budget, model, err |
| 73 | } |
| 74 | |
| 75 | // attemptAllowed is the allowed set the person sent for a connecting |
| 76 | // attempt and its revision: the models frame's (ProtocolModels), else |
| 77 | // S1's one model from an older instance's model frame, as a set of one |
| 78 | // at revision 1. |
| 79 | func (c *Connector) attemptAllowed(ctx context.Context, id string) ([]string, int64, error) { |
| 80 | var raw, model string |
| 81 | if err := c.State.db.QueryRowContext(ctx, "SELECT allowed, model FROM connect_attempts WHERE id=?", id).Scan(&raw, &model); err != nil { |
| 82 | return nil, 0, err |
| 83 | } |
| 84 | if raw != "" { |
| 85 | var set wire.ModelsCommand |
| 86 | if err := json.Unmarshal([]byte(raw), &set); err != nil { |
| 87 | return nil, 0, err |
| 88 | } |
| 89 | return set.Allowed, set.Revision, nil |
| 90 | } |
| 91 | if model != "" { |
| 92 | return []string{model}, 1, nil |
| 93 | } |
| 94 | return nil, 0, nil |
| 95 | } |
| 96 | |
| 97 | // runAPIKey is an API-key attempt: the card asking for the key, the wait |
| 98 | // for its sealed box, the model list, the card asking for the model, the |
| 99 | // probe, then the healthy report. A restart picks it up where it was. |
| 100 | func (c *Connector) runAPIKey(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { |
| 101 | failed := func(home, reason string) { c.failAPIKey(cmd, home, reason) } |
| 102 | kp, known := wire.APIKeyProviders[cmd.Provider] |
| 103 | m := c.meter() |
| 104 | billing, budget, _, err := c.attemptExtra(ctx, cmd.Connection) |
| 105 | if !known || m == nil || err != nil || billing != wire.BillingMetered && billing != wire.BillingSubscription || !wire.ValidBudget(budget) { |
| 106 | failed("", "provider_refused") |
| 107 | return |
| 108 | } |
| 109 | table, priced := metered.TableFor(metered.Current[cmd.Provider]) |
| 110 | wake := c.waitFor(cmd.Connection) |
| 111 | defer c.stopWaiting(cmd.Connection) |
| 112 | home, err := c.tokenHome(ctx, cmd.Connection) |
| 113 | if err != nil { |
| 114 | c.log("connect home", err) |
| 115 | failed(home, "provider_refused") |
| 116 | return |
| 117 | } |
| 118 | local := filepath.Base(home) |
| 119 | a, _, err := c.attempt(ctx, cmd.Connection) |
| 120 | if err == nil && a.secret == "" { |
| 121 | r := base |
| 122 | r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptAPIKey} |
| 123 | c.report(r) |
| 124 | } |
| 125 | for err == nil && a.secret == "" && a.state == "running" { |
| 126 | select { |
| 127 | case <-ctx.Done(): |
| 128 | failed(home, reasonOf(ctx.Err())) |
| 129 | return |
| 130 | case <-wake: |
| 131 | } |
| 132 | a, _, err = c.attempt(ctx, cmd.Connection) |
| 133 | } |
| 134 | if err != nil || a.state != "running" { |
| 135 | if err != nil { |
| 136 | failed(home, "provider_refused") |
| 137 | } |
| 138 | return |
| 139 | } |
| 140 | if conn, ok, _ := metered.Get(ctx, c.State.db, local); ok && conn.Validated { |
| 141 | // Made before a stop: it stands. |
| 142 | c.finishAPIKey(cmd, local, conn) |
| 143 | return |
| 144 | } |
| 145 | key, err := provider.ReadToken(home) |
| 146 | if err != nil { |
| 147 | failed(home, "provider_refused") |
| 148 | return |
| 149 | } |
| 150 | defer clear(key) |
| 151 | api, _ := c.apiClient(cmd.Provider) |
| 152 | listed, err := api.Models(ctx, key) |
| 153 | if err != nil { |
| 154 | c.log("connect api key", err) |
| 155 | failed(home, refusal(ctx, err)) |
| 156 | return |
| 157 | } |
| 158 | // Every model the key lists, each saying whether it can be allowed |
| 159 | // (priced and tiered); the card ticks those by default (§16.1). |
| 160 | var models []string |
| 161 | choices := []wire.ModelChoice{} |
| 162 | for _, m := range listed { |
| 163 | t, _, ok := metered.Eligible(cmd.Provider, table.Version, m) |
| 164 | if !priced { |
| 165 | ok = false |
| 166 | } |
| 167 | choices = append(choices, wire.ModelChoice{ID: m, Eligible: ok, Family: t.Family, Tier: t.Tier}) |
| 168 | if ok { |
| 169 | models = append(models, m) |
| 170 | } |
| 171 | } |
| 172 | if len(models) == 0 { |
| 173 | failed(home, "no_priced_model") |
| 174 | return |
| 175 | } |
| 176 | // A card carries at most wire.MaxModels: the ones that can be allowed |
| 177 | // first. |
| 178 | choices = metered.CapChoices(choices) |
| 179 | models = models[:0] |
| 180 | for _, c := range choices { |
| 181 | if c.Eligible { |
| 182 | models = append(models, c.ID) |
| 183 | } |
| 184 | } |
| 185 | shown := false |
| 186 | var allowed []string |
| 187 | var revision int64 |
| 188 | for { |
| 189 | if allowed, revision, err = c.attemptAllowed(ctx, cmd.Connection); err != nil { |
| 190 | failed(home, "provider_refused") |
| 191 | return |
| 192 | } |
| 193 | if len(allowed) > 0 && !slices.ContainsFunc(allowed, func(m string) bool { return !slices.Contains(models, m) }) { |
| 194 | break |
| 195 | } |
| 196 | if !shown { |
| 197 | // An older instance is said the one-model pick (Encode). |
| 198 | r := base |
| 199 | r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptModels, Choices: choices} |
| 200 | c.report(r) |
| 201 | shown = true |
| 202 | } |
| 203 | select { |
| 204 | case <-ctx.Done(): |
| 205 | failed(home, reasonOf(ctx.Err())) |
| 206 | return |
| 207 | case <-wake: |
| 208 | } |
| 209 | } |
| 210 | if a, _, err = c.attempt(ctx, cmd.Connection); err != nil || a.cancelled || a.state != "running" { |
| 211 | failed(home, reasonOf(firstErr(ctx.Err(), context.Canceled))) |
| 212 | return |
| 213 | } |
| 214 | // The key is proven once, on the cheapest allowed model; every other |
| 215 | // allowed model starts unprobed (§16.1). |
| 216 | model := metered.Cheapest(cmd.Provider, table.Version, allowed) |
| 217 | conn := metered.Conn{Connection: cmd.Connection, LocalID: local, Person: cmd.Person, Provider: cmd.Provider, Harness: kp.Harness, Upstream: kp.Upstream, Billing: billing, Model: model, Home: home, Currency: table.Currency, PriceVersion: table.Version, Budget: wire.Budget{Day: budget.Day, Month: budget.Month, Currency: table.Currency, Revision: budget.Revision}, ModelsRevision: revision} |
| 218 | err = c.State.tx(ctx, func(t *sql.Tx) error { |
| 219 | if _, ok, err := metered.Get(ctx, t, local); err != nil { |
| 220 | return err |
| 221 | } else if !ok { |
| 222 | if err := metered.Add(ctx, t, conn, time.Now()); err != nil { |
| 223 | return err |
| 224 | } |
| 225 | } else if err := metered.SetModel(ctx, t, local, model); err != nil { |
| 226 | return err |
| 227 | } |
| 228 | if err := metered.SetListed(ctx, t, local, listed); err != nil { |
| 229 | return err |
| 230 | } |
| 231 | return metered.InitModels(ctx, t, local, allowed, revision) |
| 232 | }) |
| 233 | if err != nil { |
| 234 | failed(home, "provider_refused") |
| 235 | return |
| 236 | } |
| 237 | if _, err = c.probe(ctx, conn, model, "pr_"+cmd.Connection, nil); err != nil { |
| 238 | c.log("connect probe", err) |
| 239 | failed(home, refusal(ctx, err)) |
| 240 | return |
| 241 | } |
| 242 | conn, _, _ = metered.Get(ctx, c.State.db, local) |
| 243 | c.finishAPIKey(cmd, local, conn) |
| 244 | } |
| 245 | |
| 246 | // refusal is the reason an attempt ends with after err. |
| 247 | func refusal(ctx context.Context, err error) string { |
| 248 | switch { |
| 249 | case ctx.Err() != nil: |
| 250 | return reasonOf(ctx.Err()) |
| 251 | case errors.Is(err, connect.ErrKeyRefused): |
| 252 | return "key_refused" |
| 253 | } |
| 254 | return "provider_refused" |
| 255 | } |
| 256 | |
| 257 | // finishAPIKey reports the attempt healthy; one cancelled meanwhile is |
| 258 | // signed out instead. |
| 259 | func (c *Connector) finishAPIKey(cmd wire.ConnectCommand, local string, conn metered.Conn) { |
| 260 | r := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: cmd.Provider, State: wire.ConnHealthy, LocalID: local} |
| 261 | c.finish(cmd.Connection, r) |
| 262 | c.Conns.changed() |
| 263 | var cancelled int |
| 264 | _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) |
| 265 | if cancelled == 1 { |
| 266 | k := cleanup{connection: cmd.Connection, person: cmd.Person, local: local, home: conn.Home, provider: conn.Provider} |
| 267 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { return owe(t, k) }) |
| 268 | c.log("disconnect record", err) |
| 269 | c.settle(k) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // failAPIKey ends an attempt not yet healthy: its unvalidated metered |
| 274 | // record and its home (the key with it) go, then the error report. |
| 275 | func (c *Connector) failAPIKey(cmd wire.ConnectCommand, home, reason string) { |
| 276 | c.delivery.Lock() |
| 277 | defer c.delivery.Unlock() |
| 278 | c.endAPIKey(cmd.Connection, cmd.Person, cmd.Provider, home, reason) |
| 279 | } |
| 280 | |
| 281 | // endAPIKey removes an API-key attempt's unvalidated record and home and |
| 282 | // reports its end. |
| 283 | func (c *Connector) endAPIKey(id, person, prov, home, reason string) { |
| 284 | if home != "" { |
| 285 | local := filepath.Base(home) |
| 286 | err := c.State.tx(context.Background(), func(t *sql.Tx) error { |
| 287 | _, err := t.Exec("DELETE FROM metered_connections WHERE local_id=? AND home=? AND validated=0", local, home) |
| 288 | return err |
| 289 | }) |
| 290 | c.log("connect api key", err) |
| 291 | c.removeHome(home) |
| 292 | } |
| 293 | c.finish(id, wire.ConnectionReport{Connection: id, Person: person, Provider: prov, State: wire.ConnError, Reason: reason}) |
| 294 | } |
| 295 | |
| 296 | // probe proves a model with one billable token (§2.2, §16.4), admitted |
| 297 | // through the metered guard with the slot claimed (and admit, a step's |
| 298 | // scheduler admission, in that same transaction), its usage charged and |
| 299 | // reported as a probe's (role probe) under id, the slot released with |
| 300 | // the charge or spend_unknown. Its verdict commits with the charge: |
| 301 | // answered by that model, the model is healthy and the key proven; a |
| 302 | // refused key refuses the connection (no model is marked); the model |
| 303 | // not found, or another model answering, makes the model unhealthy; no |
| 304 | // usable usage leaves the spend unknown. It runs at connect, on Check |
| 305 | // again, and on a model's first use in a step. |
| 306 | func (c *Connector) probe(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) { |
| 307 | m := c.meter() |
| 308 | api, ok := c.apiClient(conn.Provider) |
| 309 | if m == nil || !ok { |
| 310 | return metered.Admission{}, connect.ErrProviderAnswer |
| 311 | } |
| 312 | // Each execution of a probe id is its own attempt (a durable |
| 313 | // sequence): charged and settled as itself, while a resent usage frame |
| 314 | // of it stays one charge (security round #2). |
| 315 | attempt, err := c.State.nextProbe(ctx, id) |
| 316 | if err != nil { |
| 317 | return metered.Admission{}, err |
| 318 | } |
| 319 | var perr error |
| 320 | h := metered.Holder{Step: id, Attempt: attempt, Role: metered.RoleProbe, Model: model} |
| 321 | adm, _, err := m.RunAdmitted(ctx, conn.LocalID, h, admit, func(ctx context.Context, l metered.Launch) metered.Result { |
| 322 | key, err := provider.ReadToken(conn.Home) |
| 323 | if err != nil { |
| 324 | perr = err |
| 325 | return metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}} |
| 326 | } |
| 327 | defer clear(key) |
| 328 | u, err := api.Probe(ctx, key, model) |
| 329 | perr = err |
| 330 | // Another model answering proves nothing about the selected one; |
| 331 | // its usage is that model's, priced as it (security round, |
| 332 | // finding 6). |
| 333 | if errors.Is(err, connect.ErrKeyRefused) || errors.Is(err, connect.ErrModelNotFound) { |
| 334 | // Refused before any work: nothing was billed. |
| 335 | return metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}} |
| 336 | } |
| 337 | // The request ran in this process, which is its whole boundary. |
| 338 | return metered.Result{Usage: []wire.Usage{u.Row(conn.Provider, conn.LocalID, model, attempt, err == nil)}, Ending: metered.Ending{Proven: true}} |
| 339 | }, func(t *sql.Tx, priced []wire.Usage) error { |
| 340 | // The verdict commits with the probe's charge. |
| 341 | now := time.Now() |
| 342 | switch { |
| 343 | case perr == nil: |
| 344 | if err := metered.Checked(ctx, t, conn.LocalID, true); err != nil { |
| 345 | return err |
| 346 | } |
| 347 | if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelHealthy, "", now); err != nil { |
| 348 | return err |
| 349 | } |
| 350 | case errors.Is(perr, connect.ErrKeyRefused): |
| 351 | if err := metered.Checked(ctx, t, conn.LocalID, false); err != nil { |
| 352 | return err |
| 353 | } |
| 354 | case errors.Is(perr, connect.ErrModelNotFound): |
| 355 | if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelUnhealthy, wire.ModelNotFound, now); err != nil { |
| 356 | return err |
| 357 | } |
| 358 | case errors.Is(perr, connect.ErrModelMismatch): |
| 359 | if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelUnhealthy, wire.ModelOtherAnswered, now); err != nil { |
| 360 | return err |
| 361 | } |
| 362 | } |
| 363 | if len(priced) == 0 { |
| 364 | return nil |
| 365 | } |
| 366 | return c.State.enqueue(t, wire.FrameUsage, "", wire.UsageReport{ProbeID: id, Rows: priced}) |
| 367 | }) |
| 368 | if err != nil { |
| 369 | return adm, err |
| 370 | } |
| 371 | if !adm.Admitted { |
| 372 | return adm, errHeld |
| 373 | } |
| 374 | return adm, perr |
| 375 | } |
| 376 | |
| 377 | // probeModel is a step's first-use probe (Conns.Prober, §16.4). |
| 378 | func (c *Connector) probeModel(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) { |
| 379 | adm, err := c.probe(ctx, conn, model, id, admit) |
| 380 | if errors.Is(err, errHeld) { |
| 381 | err = nil |
| 382 | } |
| 383 | if c.Notify != nil { |
| 384 | c.Notify() |
| 385 | } |
| 386 | return adm, err |
| 387 | } |
| 388 | |
| 389 | // Model takes the person's pick of a connecting attempt's model, once |
| 390 | // per frame, and wakes the attempt. |
| 391 | func (c *Connector) Model(ctx context.Context, frameID string, cmd wire.ModelCommand) error { |
| 392 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 393 | fresh, err := seen(t, frameID) |
| 394 | if err != nil || !fresh || len(cmd.Model) > wire.MaxModelName { |
| 395 | return err |
| 396 | } |
| 397 | _, err = t.Exec("UPDATE connect_attempts SET model=? WHERE id=? AND person=? AND kind=? AND state='running'", cmd.Model, cmd.Connection, cmd.Person, wire.KindAPIKey) |
| 398 | return err |
| 399 | }) |
| 400 | if err == nil { |
| 401 | c.wake(cmd.Connection) |
| 402 | } |
| 403 | return err |
| 404 | } |
| 405 | |
| 406 | // Models applies the person's allowed set (§16.1), once per frame. A |
| 407 | // connecting attempt (no runner name yet) takes it as its card's answer |
| 408 | // and wakes. A metered connection applies it in one transaction, only |
| 409 | // for the connection, person and runner name the frame names and only |
| 410 | // above the revision held; the link acks it after, which is when the |
| 411 | // instance shows it applied. A frame that does not bind is acked |
| 412 | // unapplied: hello carries the revision held, so the instance sees it. |
| 413 | func (c *Connector) Models(ctx context.Context, frameID string, cmd wire.ModelsCommand) error { |
| 414 | m := c.meter() |
| 415 | applied, woke := false, false |
| 416 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 417 | fresh, err := seen(t, frameID) |
| 418 | if err != nil || !fresh || !wire.ValidAllowed(cmd.Allowed) { |
| 419 | return err |
| 420 | } |
| 421 | if cmd.LocalID == "" { |
| 422 | raw, err := json.Marshal(wire.ModelsCommand{Allowed: cmd.Allowed, Revision: cmd.Revision}) |
| 423 | if err != nil { |
| 424 | return err |
| 425 | } |
| 426 | res, err := t.Exec("UPDATE connect_attempts SET allowed=? WHERE id=? AND person=? AND kind=? AND state='running'", string(raw), cmd.Connection, cmd.Person, wire.KindAPIKey) |
| 427 | if err != nil { |
| 428 | return err |
| 429 | } |
| 430 | n, _ := res.RowsAffected() |
| 431 | woke = n == 1 |
| 432 | return nil |
| 433 | } |
| 434 | if m == nil { |
| 435 | return nil |
| 436 | } |
| 437 | if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { |
| 438 | return err |
| 439 | } |
| 440 | applied, err = metered.SetModels(ctx, t, cmd.LocalID, cmd.Connection, cmd.Allowed, cmd.Revision) |
| 441 | if errors.Is(err, metered.ErrNotAllowable) { |
| 442 | // A model it cannot price or tier: acked, not applied. |
| 443 | return nil |
| 444 | } |
| 445 | return err |
| 446 | }) |
| 447 | if err == nil && woke { |
| 448 | c.wake(cmd.Connection) |
| 449 | } |
| 450 | if err == nil && applied { |
| 451 | m.Notify() |
| 452 | if c.Notify != nil { |
| 453 | c.Notify() |
| 454 | } |
| 455 | } |
| 456 | return err |
| 457 | } |
| 458 | |
| 459 | // Budget applies a budget frame for one of the person's metered |
| 460 | // connections. In one transaction: a frame already consumed changes |
| 461 | // nothing; the command must name the connection's own instance id, |
| 462 | // person and runner name, and a budget in bounds; then it is applied |
| 463 | // (security round, finding 4). The link acks it after, which is when the |
| 464 | // instance shows it applied. A frame that does not bind is acked |
| 465 | // unapplied. |
| 466 | func (c *Connector) Budget(ctx context.Context, frameID string, cmd wire.BudgetCommand) error { |
| 467 | m := c.meter() |
| 468 | if m == nil { |
| 469 | return nil |
| 470 | } |
| 471 | applied := false |
| 472 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 473 | fresh, err := seen(t, frameID) |
| 474 | if err != nil || !fresh || !wire.ValidBudget(cmd.Budget) { |
| 475 | return err |
| 476 | } |
| 477 | if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { |
| 478 | return err |
| 479 | } |
| 480 | applied, err = metered.ApplyBudget(ctx, t, cmd.LocalID, cmd.Connection, cmd.Budget) |
| 481 | return err |
| 482 | }) |
| 483 | if err == nil && applied { |
| 484 | m.Notify() |
| 485 | } |
| 486 | return err |
| 487 | } |
| 488 | |
| 489 | // bound reports whether a frame's binding is the metered connection's |
| 490 | // own: its runner name, the instance's id for it and its person. |
| 491 | func bound(ctx context.Context, t *sql.Tx, local, connection, person string) (bool, error) { |
| 492 | conn, ok, err := metered.Get(ctx, t, local) |
| 493 | if err != nil || !ok { |
| 494 | return false, err |
| 495 | } |
| 496 | return conn.Connection != "" && conn.Connection == connection && conn.Person == person, nil |
| 497 | } |
| 498 | |
| 499 | // ResumeSpend consumes the person's Resume for the pause it names, under |
| 500 | // the same binding and freshness rules as Budget. |
| 501 | func (c *Connector) ResumeSpend(ctx context.Context, frameID string, cmd wire.ResumeSpendCommand) error { |
| 502 | m := c.meter() |
| 503 | if m == nil { |
| 504 | return nil |
| 505 | } |
| 506 | cleared := false |
| 507 | err := c.State.tx(ctx, func(t *sql.Tx) error { |
| 508 | fresh, err := seen(t, frameID) |
| 509 | if err != nil || !fresh { |
| 510 | return err |
| 511 | } |
| 512 | if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { |
| 513 | return err |
| 514 | } |
| 515 | cleared, err = metered.Resume(ctx, t, cmd.LocalID, cmd.Connection, cmd.PauseRevision) |
| 516 | return err |
| 517 | }) |
| 518 | if err == nil && cleared { |
| 519 | m.Notify() |
| 520 | } |
| 521 | return err |
| 522 | } |
| 523 | |
| 524 | // checkMetered is Check again on a metered connection (§16.4): the key |
| 525 | // proven again on the cheapest allowed model, then every unhealthy |
| 526 | // allowed model probed, each billable and through the guard under the |
| 527 | // normal budget bar. A refused key makes it sign_in_again and stops. |
| 528 | func (c *Connector) checkMetered(conn metered.Conn) { |
| 529 | c.background(func() { |
| 530 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| 531 | defer cancel() |
| 532 | // The key's list read again: the page's choices (a connection |
| 533 | // from before S5b gets its list here). |
| 534 | if api, ok := c.apiClient(conn.Provider); ok { |
| 535 | if key, err := provider.ReadToken(conn.Home); err == nil { |
| 536 | listed, err := api.Models(ctx, key) |
| 537 | clear(key) |
| 538 | if err == nil { |
| 539 | c.log("connection models", c.State.tx(ctx, func(t *sql.Tx) error { return metered.SetListed(ctx, t, conn.LocalID, listed) })) |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | models, err := metered.Models(ctx, c.State.db, conn.LocalID) |
| 544 | c.log("connection probe", err) |
| 545 | ids := make([]string, 0, len(models)) |
| 546 | for _, m := range models { |
| 547 | ids = append(ids, m.ID) |
| 548 | } |
| 549 | first := metered.Cheapest(conn.Provider, conn.PriceVersion, ids) |
| 550 | if first == "" { |
| 551 | first = conn.Model |
| 552 | } |
| 553 | _, err = c.probe(ctx, conn, first, "pr_"+conn.LocalID+"_"+rand.Text()[:10], nil) |
| 554 | c.log("connection probe", err) |
| 555 | for _, m := range models { |
| 556 | if err != nil && !errors.Is(err, connect.ErrModelNotFound) && !errors.Is(err, connect.ErrModelMismatch) || ctx.Err() != nil { |
| 557 | break |
| 558 | } |
| 559 | if m.ID == first || m.State != wire.ModelUnhealthy { |
| 560 | continue |
| 561 | } |
| 562 | _, err = c.probe(ctx, conn, m.ID, "pr_"+conn.LocalID+"_"+rand.Text()[:10], nil) |
| 563 | c.log("connection probe", err) |
| 564 | } |
| 565 | c.Conns.changed() |
| 566 | if c.Notify != nil { |
| 567 | c.Notify() |
| 568 | } |
| 569 | }) |
| 570 | } |
| 571 | |
| 572 | // removeMetered is a metered connection's part of its sign-out |
| 573 | // (security round, finding 3): it retires first, so nothing more is |
| 574 | // admitted; an attempt still holding its slot (a Check again's probe) is |
| 575 | // awaited, and its charge or spend_unknown commits before the record |
| 576 | // goes; then the record goes before its home (a stop between them leaves |
| 577 | // the home in the cleanup record, deleted on the next start). An attempt |
| 578 | // that does not end in time leaves the sign-out owed, retired. |
| 579 | func (c *Connector) removeMetered(k cleanup) bool { |
| 580 | ctx := context.Background() |
| 581 | if err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Retire(ctx, t, k.local) }); err != nil { |
| 582 | c.log("disconnect metered", err) |
| 583 | return false |
| 584 | } |
| 585 | deadline := time.Now().Add(removeWait) |
| 586 | for { |
| 587 | err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Remove(ctx, t, k.local) }) |
| 588 | if err == nil { |
| 589 | break |
| 590 | } |
| 591 | if !errors.Is(err, metered.ErrSlotHeld) || time.Now().After(deadline) { |
| 592 | c.log("disconnect metered", err) |
| 593 | return false |
| 594 | } |
| 595 | // An attempt that ended unproven is proven here, if it can be. |
| 596 | if m := c.meter(); m != nil { |
| 597 | _ = m.Recover(ctx) |
| 598 | } |
| 599 | time.Sleep(100 * time.Millisecond) |
| 600 | } |
| 601 | c.Conns.changed() |
| 602 | return true |
| 603 | } |
| 604 | |
| 605 | // removeWait bounds how long a sign-out waits for a running attempt: a |
| 606 | // probe's own limit and a little more. |
| 607 | const removeWait = 3 * time.Minute |
| 608 | |