oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package metered
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/wire"
11)
12
13// Schema is the metered tables in thin.db (§2.3). metered_connections
14// holds each metered connection (its home, model, price version, budget
15// and pause); metered_slot its one slot, which every attempt on it
16// claims in the transaction that admits it; budget_charge the ledger,
17// keyed by the usage row's key so a resent row charges once.
18const Schema = `
19CREATE TABLE IF NOT EXISTS metered_connections (local_id TEXT PRIMARY KEY, connection TEXT NOT NULL DEFAULT '', retiring INTEGER NOT NULL DEFAULT 0, person TEXT NOT NULL, provider TEXT NOT NULL, harness TEXT NOT NULL, upstream TEXT NOT NULL, billing TEXT NOT NULL, model TEXT NOT NULL DEFAULT '', home TEXT NOT NULL, currency TEXT NOT NULL, price_version TEXT NOT NULL, budget_day INTEGER NOT NULL, budget_month INTEGER NOT NULL, budget_revision INTEGER NOT NULL DEFAULT 0, spend_unknown INTEGER NOT NULL DEFAULT 0, pause_revision INTEGER NOT NULL DEFAULT 0, validated INTEGER NOT NULL DEFAULT 0, refused INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, models_revision INTEGER NOT NULL DEFAULT 0, listed TEXT NOT NULL DEFAULT '');
20CREATE TABLE IF NOT EXISTS metered_slot (local_id TEXT PRIMARY KEY, holder TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '', namespace TEXT NOT NULL DEFAULT '', claimed_at TEXT NOT NULL DEFAULT '');
21CREATE TABLE IF NOT EXISTS budget_charge (turn TEXT NOT NULL, step TEXT NOT NULL, attempt INTEGER NOT NULL, connection TEXT NOT NULL, model TEXT NOT NULL, holder TEXT NOT NULL, cost_micros INTEGER, reported_micros INTEGER, currency TEXT NOT NULL, price_version TEXT NOT NULL, day TEXT NOT NULL, month TEXT NOT NULL, recorded_at TEXT NOT NULL, PRIMARY KEY (turn, step, attempt, connection, model));
22CREATE INDEX IF NOT EXISTS budget_charge_period ON budget_charge(connection, day, month);
23` + modelsSchema
24
25// Holds: why an attempt on a metered connection is not admitted.
26const (
27 HoldBusy = wire.HoldBusy
28 HoldBudget = wire.HoldBudget
29 HoldSpendUnknown = wire.HoldSpendUnknown
30)
31
32// Roles an attempt holds the slot for.
33const (
34 RoleEngineering = "engineering"
35 RoleReview = "review"
36 RoleAsk = "ask"
37 RoleProbe = wire.UsageProbe
38)
39
40// ErrNotMetered: the connection is not a metered one this runner holds.
41var ErrNotMetered = errors.New("metered: not a metered connection")
42
43// ErrNotProven: a slot is released only after its attempt's termination
44// proof.
45var ErrNotProven = errors.New("metered: the attempt's exit is not proven")
46
47// Conn is one metered connection as the runner holds it. Connection is
48// the instance's id for it: every budget and Resume frame must name it.
49// Retiring: its sign-out has begun; nothing more is admitted.
50type Conn struct {
51 Connection string
52 Retiring bool
53 LocalID, Person, Provider, Harness, Upstream, Billing, Model, Home string
54 Currency, PriceVersion string
55 Budget wire.Budget
56 SpendUnknown bool
57 PauseRevision int64
58 // Validated: its one-token probe on the model succeeded once.
59 // Refused: the provider refused the key at the last probe.
60 Validated, Refused bool
61 // ModelsRevision is the allowed set's revision (§16.1); Model is the
62 // cheapest allowed model, the one S1's frames and an older instance
63 // name.
64 ModelsRevision int64
65}
66
67// Holder is one attempt holding a slot: the usage row key's turn, step
68// and attempt (a question's id is its step; a probe's id too) and the
69// role it runs.
70type Holder struct {
71 Turn, Step string
72 Attempt int64
73 Role string
74 // Model is the model the attempt runs on (§16): the guard admits it
75 // only on a model it may run now, and a usage row naming another is a
76 // model_mismatch. Not part of the slot's key.
77 Model string
78}
79
80// Key is the holder's slot record.
81func (h Holder) Key() string { return fmt.Sprintf("%s|%s|%s|%d", h.Role, h.Turn, h.Step, h.Attempt) }
82
83// Admission is Admit's answer: admitted, or held with why and, for the
84// budget, when a new day or month starts. Claimed: the holder already
85// claims the slot (an attempt of it is running, or awaits its proof);
86// that never gives leave to launch again.
87type Admission struct {
88 Admitted bool
89 Claimed bool
90 Hold string
91 WakeAt time.Time
92}
93
94type querier interface {
95 QueryRowContext(context.Context, string, ...any) *sql.Row
96 QueryContext(context.Context, string, ...any) (*sql.Rows, error)
97}
98
99const connColumns = "connection, retiring, local_id, person, provider, harness, upstream, billing, model, home, currency, price_version, budget_day, budget_month, budget_revision, spend_unknown, pause_revision, validated, refused, models_revision"
100
101func scanConn(scan func(...any) error) (Conn, error) {
102 var c Conn
103 var unknown, validated, refused, retiring int
104 err := scan(&c.Connection, &retiring, &c.LocalID, &c.Person, &c.Provider, &c.Harness, &c.Upstream, &c.Billing, &c.Model, &c.Home, &c.Currency, &c.PriceVersion, &c.Budget.Day, &c.Budget.Month, &c.Budget.Revision, &unknown, &c.PauseRevision, &validated, &refused, &c.ModelsRevision)
105 c.Budget.Currency = c.Currency
106 c.SpendUnknown, c.Validated, c.Refused, c.Retiring = unknown == 1, validated == 1, refused == 1, retiring == 1
107 return c, err
108}
109
110// Add records a new metered connection and its free slot.
111func Add(ctx context.Context, tx *sql.Tx, c Conn, now time.Time) error {
112 if _, err := tx.ExecContext(ctx, "INSERT INTO metered_connections("+connColumns+", created_at) VALUES(?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,0,?,?)", c.Connection, c.LocalID, c.Person, c.Provider, c.Harness, c.Upstream, c.Billing, c.Model, c.Home, c.Currency, c.PriceVersion, c.Budget.Day, c.Budget.Month, c.Budget.Revision, c.ModelsRevision, stamp(now)); err != nil {
113 return err
114 }
115 _, err := tx.ExecContext(ctx, "INSERT INTO metered_slot(local_id) VALUES(?) ON CONFLICT DO NOTHING", c.LocalID)
116 return err
117}
118
119// Get reads one metered connection.
120func Get(ctx context.Context, q querier, local string) (Conn, bool, error) {
121 c, err := scanConn(q.QueryRowContext(ctx, "SELECT "+connColumns+" FROM metered_connections WHERE local_id=?", local).Scan)
122 if errors.Is(err, sql.ErrNoRows) {
123 return Conn{}, false, nil
124 }
125 return c, err == nil, err
126}
127
128// List reads every metered connection, oldest first.
129func List(ctx context.Context, q querier) ([]Conn, error) {
130 rows, err := q.QueryContext(ctx, "SELECT "+connColumns+" FROM metered_connections ORDER BY created_at, local_id")
131 if err != nil {
132 return nil, err
133 }
134 defer rows.Close()
135 var out []Conn
136 for rows.Next() {
137 c, err := scanConn(rows.Scan)
138 if err != nil {
139 return nil, err
140 }
141 out = append(out, c)
142 }
143 return out, rows.Err()
144}
145
146// ErrSlotHeld: the connection cannot go while an attempt holds its slot.
147var ErrSlotHeld = errors.New("metered: an attempt holds the slot")
148
149// Retire starts a connection's sign-out: from this transaction on,
150// nothing more is admitted to it.
151func Retire(ctx context.Context, tx *sql.Tx, local string) error {
152 _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET retiring=1 WHERE local_id=?", local)
153 return err
154}
155
156// Remove forgets a signed-out connection, its record and slot, only once
157// its slot is free: an attempt still running is charged (or its spend
158// made unknown) first (ErrSlotHeld until then). Its charges stay until
159// they age out with the day's and month's sums.
160func Remove(ctx context.Context, tx *sql.Tx, local string) error {
161 var holder string
162 if err := tx.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder); err != nil && !errors.Is(err, sql.ErrNoRows) {
163 return err
164 }
165 if holder != "" {
166 return ErrSlotHeld
167 }
168 if _, err := tx.ExecContext(ctx, "DELETE FROM metered_connections WHERE local_id=?", local); err != nil {
169 return err
170 }
171 _, err := tx.ExecContext(ctx, "DELETE FROM metered_slot WHERE local_id=?", local)
172 return err
173}
174
175// SetModel records the connection's one model.
176func SetModel(ctx context.Context, tx *sql.Tx, local, model string) error {
177 _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET model=? WHERE local_id=?", model, local)
178 return err
179}
180
181// Checked records a probe's verdict: validated after a success, refused
182// after the provider refused the key.
183func Checked(ctx context.Context, tx *sql.Tx, local string, ok bool) error {
184 q := "UPDATE metered_connections SET validated=1, refused=0 WHERE local_id=?"
185 if !ok {
186 q = "UPDATE metered_connections SET refused=1 WHERE local_id=?"
187 }
188 _, err := tx.ExecContext(ctx, q, local)
189 return err
190}
191
192func stamp(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) }
193
194// period is the budget day and month a time falls in: UTC until the
195// person's zone is known (§2.3).
196func period(t time.Time) (day, month string) {
197 t = t.UTC()
198 return t.Format("2006-01-02"), t.Format("2006-01")
199}
200
201// spent sums the connection's known charges in now's day and month.
202func spent(ctx context.Context, q querier, local string, now time.Time) (day, month int64, err error) {
203 d, m := period(now)
204 err = q.QueryRowContext(ctx, "SELECT coalesce(sum(CASE WHEN day=? THEN cost_micros END),0), coalesce(sum(cost_micros),0) FROM budget_charge WHERE connection=? AND month=?", d, local, m).Scan(&day, &month)
205 return day, month, err
206}
207
208// Admit is the metered guard (§2.3, §7): in the caller's transaction,
209// the attempt claims the connection's one slot only when the slot is
210// free, the spend is known, and the reported spend is under both the
211// day's and the month's budget. The same holder asking again is
212// admitted (its claim stands). Every attempt on a metered connection
213// passes here: an Engineering or Review step, a question, a probe. A
214// holder that already claims the slot is not admitted again, and a
215// retiring connection admits nothing.
216func Admit(ctx context.Context, tx *sql.Tx, local string, h Holder, now time.Time) (Admission, error) {
217 c, ok, err := Get(ctx, tx, local)
218 if err != nil || !ok {
219 return Admission{}, firstErr(err, ErrNotMetered)
220 }
221 var holder string
222 if err := tx.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder); err != nil {
223 return Admission{}, err
224 }
225 if holder == h.Key() {
226 return Admission{Claimed: true, Hold: HoldBusy}, nil
227 }
228 if holder != "" || c.Retiring {
229 return Admission{Hold: HoldBusy}, nil
230 }
231 if c.SpendUnknown {
232 return Admission{Hold: HoldSpendUnknown}, nil
233 }
234 if ok, err := admitModel(ctx, tx, c, h); err != nil || !ok {
235 return Admission{Hold: HoldModel}, err
236 }
237 day, month, err := spent(ctx, tx, local, now)
238 if err != nil {
239 return Admission{}, err
240 }
241 if day >= c.Budget.Day || month >= c.Budget.Month {
242 return Admission{Hold: HoldBudget, WakeAt: nextPeriod(now, month >= c.Budget.Month)}, nil
243 }
244 res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET holder=?, role=?, namespace='', claimed_at=? WHERE local_id=? AND holder=''", h.Key(), h.Role, stamp(now), local)
245 if err != nil {
246 return Admission{}, err
247 }
248 if n, err := res.RowsAffected(); err != nil || n != 1 {
249 return Admission{Hold: HoldBusy}, err
250 }
251 return Admission{Admitted: true}, nil
252}
253
254// nextPeriod is when the next budget day (or month) starts, UTC.
255func nextPeriod(now time.Time, month bool) time.Time {
256 now = now.UTC()
257 if month {
258 return time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC)
259 }
260 return time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC)
261}
262
263// SetNamespace records the namespace of the slot's attempt before its
264// harness starts, so a restart can prove it gone.
265func SetNamespace(ctx context.Context, tx *sql.Tx, local string, h Holder, ns string) error {
266 res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET namespace=? WHERE local_id=? AND holder=?", ns, local, h.Key())
267 if err != nil {
268 return err
269 }
270 if n, err := res.RowsAffected(); err != nil || n != 1 {
271 return firstErr(err, errors.New("metered: the slot is not this attempt's"))
272 }
273 return nil
274}
275
276// Charge prices the attempt's usage rows with the connection's table and
277// records each in the ledger once, keyed by the row's key (a resent row
278// charges once), in the period the charge is recorded in. It returns the
279// rows with their cost, to report in the same transaction.
280func Charge(ctx context.Context, tx *sql.Tx, local string, h Holder, rows []wire.Usage, now time.Time) ([]wire.Usage, error) {
281 c, ok, err := Get(ctx, tx, local)
282 if err != nil || !ok {
283 return nil, firstErr(err, ErrNotMetered)
284 }
285 table, known := TableFor(c.PriceVersion)
286 day, month := period(now)
287 out := make([]wire.Usage, 0, len(rows))
288 mismatch := false
289 for _, u := range rows {
290 if u.Connection != local {
291 out = append(out, u)
292 continue
293 }
294 priced := u
295 priced.Currency, priced.PriceVersion, priced.CostMicros = c.Currency, c.PriceVersion, nil
296 if known {
297 priced, _ = table.Price(u)
298 }
299 // The row is the model the provider reported (§16.5): its tier
300 // and family are that model's, and naming another model than the
301 // one chosen is a model_mismatch, charged at the reported model's
302 // price (or unknown, when it has none).
303 if t, ok := TierOf(c.Provider, u.Model); ok {
304 priced.Family, priced.Tier = t.Family, t.Tier
305 }
306 priced.TierVersion = CurrentTiers
307 if h.Model != "" && u.Model != h.Model {
308 priced.ModelMismatch, mismatch = true, true
309 }
310 var cost, reported any
311 if priced.CostMicros != nil {
312 cost = *priced.CostMicros
313 }
314 if priced.CostReportedMicros != nil {
315 reported = *priced.CostReportedMicros
316 }
317 if _, err := tx.ExecContext(ctx, "INSERT INTO budget_charge(turn, step, attempt, connection, model, holder, cost_micros, reported_micros, currency, price_version, day, month, recorded_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", h.Turn, h.Step, u.Attempt, local, u.Model, h.Key(), cost, reported, c.Currency, c.PriceVersion, day, month, stamp(now)); err != nil {
318 return nil, err
319 }
320 out = append(out, priced)
321 }
322 if mismatch {
323 // The chosen model is not trusted again until Check again.
324 if err := MarkModel(ctx, tx, local, h.Model, wire.ModelUnhealthy, wire.ModelMismatch, now); err != nil {
325 return nil, err
326 }
327 }
328 return out, nil
329}
330
331// Ending is how an attempt ended, for Settle: Proven says its
332// namespace's exit is proven; NotStarted that no harness was started
333// for it at all, so nothing can have been spent.
334type Ending struct {
335 Proven, NotStarted bool
336}
337
338// Settle releases the slot of an attempt whose exit is proven, in the
339// caller's transaction: with a committed, known charge for the attempt
340// the spend stands; otherwise (no usage figure, an incomplete or
341// unpriced one) the connection's spend becomes unknown, under a new
342// pause revision, in the same transaction. A slot another attempt holds
343// is left alone.
344func Settle(ctx context.Context, tx *sql.Tx, local string, h Holder, e Ending) error {
345 return settle(ctx, tx, local, h.Key(), e)
346}
347
348func settle(ctx context.Context, tx *sql.Tx, local, key string, e Ending) error {
349 if !e.Proven {
350 return ErrNotProven
351 }
352 res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET holder='', role='', namespace='', claimed_at='' WHERE local_id=? AND holder=?", local, key)
353 if err != nil {
354 return err
355 }
356 if n, err := res.RowsAffected(); err != nil || n != 1 {
357 return err
358 }
359 if e.NotStarted {
360 return nil
361 }
362 var rows, unknown int
363 if err := tx.QueryRowContext(ctx, "SELECT count(*), coalesce(sum(cost_micros IS NULL),0) FROM budget_charge WHERE connection=? AND holder=?", local, key).Scan(&rows, &unknown); err != nil {
364 return err
365 }
366 if rows > 0 && unknown == 0 {
367 return nil
368 }
369 return pause(ctx, tx, local)
370}
371
372// pause marks the connection's spend unknown under a new pause revision.
373func pause(ctx context.Context, tx *sql.Tx, local string) error {
374 _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=1, pause_revision=pause_revision+1 WHERE local_id=?", local)
375 return err
376}
377
378// Resume consumes the person's Resume for connection (the instance's
379// id), bound to the pause they saw: it
380// clears the unknown spend once, and only while pauseRevision is still
381// the connection's pause. A stale or repeated Resume changes nothing,
382// so a newer pause stays. It reports whether it cleared one.
383func Resume(ctx context.Context, tx *sql.Tx, local, connection string, pauseRevision int64) (bool, error) {
384 res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=0 WHERE local_id=? AND connection=? AND spend_unknown=1 AND pause_revision=?", local, connection, pauseRevision)
385 if err != nil {
386 return false, err
387 }
388 n, err := res.RowsAffected()
389 return n == 1, err
390}
391
392// ApplyBudget applies a budget change for connection (the instance's
393// id) above the revision the runner holds; an older or equal revision changes nothing. A running attempt
394// is not stopped: the budget is read at the next admission.
395func ApplyBudget(ctx context.Context, tx *sql.Tx, local, connection string, b wire.Budget) (bool, error) {
396 if !wire.ValidBudget(b) {
397 return false, errors.New("metered: budget out of bounds")
398 }
399 res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET budget_day=?, budget_month=?, budget_revision=? WHERE local_id=? AND connection=? AND budget_revision<?", b.Day, b.Month, b.Revision, local, connection, b.Revision)
400 if err != nil {
401 return false, err
402 }
403 n, err := res.RowsAffected()
404 return n == 1, err
405}
406
407// SpendOf is what the connection has spent today and this month, as
408// hello reports it, with its pause and whether its slot is held.
409func SpendOf(ctx context.Context, q querier, c Conn, now time.Time) (wire.Spend, error) {
410 day, month, err := spent(ctx, q, c.LocalID, now)
411 if err != nil {
412 return wire.Spend{}, err
413 }
414 var holder string
415 if err := q.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", c.LocalID).Scan(&holder); err != nil && !errors.Is(err, sql.ErrNoRows) {
416 return wire.Spend{}, err
417 }
418 return wire.Spend{Day: day, Month: month, Currency: c.Currency, Unknown: c.SpendUnknown, PauseRevision: c.PauseRevision, Running: holder != ""}, nil
419}
420
421// Claimed is a held slot: whose, and the namespace its attempt runs in.
422type Claimed struct {
423 Local, Namespace string
424 Holder string
425}
426
427// claimed lists every held slot.
428func claimed(ctx context.Context, q querier) ([]Claimed, error) {
429 rows, err := q.QueryContext(ctx, "SELECT local_id, holder, namespace FROM metered_slot WHERE holder<>''")
430 if err != nil {
431 return nil, err
432 }
433 defer rows.Close()
434 var out []Claimed
435 for rows.Next() {
436 var c Claimed
437 if err := rows.Scan(&c.Local, &c.Holder, &c.Namespace); err != nil {
438 return nil, err
439 }
440 out = append(out, c)
441 }
442 return out, rows.Err()
443}
444
445func firstErr(errs ...error) error {
446 for _, e := range errs {
447 if e != nil {
448 return e
449 }
450 }
451 return nil
452}
453