package metered import ( "context" "database/sql" "errors" "sync" "time" "amadan.net/oficina/equipo/internal/wire" ) // Meter runs attempts on metered connections through the guard (§2.3): // admitted with the slot claimed in one transaction; the usage charged // and reported in one transaction; the slot released only after the // attempt's termination proof, with its charge or with the spend // unknown, in that same transaction. A harness (S2's Pi, a test's fake) // runs the attempt; the Meter never starts one itself. type Meter struct { DB *sql.DB // Gone proves an attempt's namespace gone (killed and its exit // verified, as the step recovery does). An attempt that recorded no // namespace started no harness. Gone func(ctx context.Context, namespace string) error Now func() time.Time // Changed is called when a slot was released or a pause, a budget or // a charge changed what hello reports. Changed func() // Fault, in tests, stops the process at a boundary ("exited": after // the harness ended, before its charge), as if it stopped there. Fault func(stage string) error // running are the slots this process admitted whose attempt has not // ended: Recover never touches them. mu sync.Mutex running map[string]bool } func (m *Meter) setRunning(local string, h Holder, on bool) { m.mu.Lock() defer m.mu.Unlock() if m.running == nil { m.running = map[string]bool{} } if on { m.running[local+"\x00"+h.Key()] = true } else { delete(m.running, local+"\x00"+h.Key()) } } func (m *Meter) isRunning(local, holder string) bool { m.mu.Lock() defer m.mu.Unlock() return m.running[local+"\x00"+holder] } // ErrStopped is a test fault's stop. var ErrStopped = errors.New("metered: stopped") // Launch is what a harness gets for one admitted attempt: the connection // and the holder, and Namespace, which records the attempt's namespace // in its slot before the harness starts it. type Launch struct { Conn Conn Holder Holder Namespace func(ns string) error } // Result is how an attempt ended: the usage rows the harness reported, // and its Ending. type Result struct { Usage []wire.Usage Ending } func (m *Meter) now() time.Time { if m.Now != nil { return m.Now() } return time.Now() } func (m *Meter) tx(ctx context.Context, fn func(*sql.Tx) error) error { t, err := m.DB.BeginTx(ctx, nil) if err != nil { return err } defer t.Rollback() if err = fn(t); err != nil { return err } return t.Commit() } func (m *Meter) changed() { if m.Changed != nil { m.Changed() } } // Admit claims the slot for h when the guard allows it, in its own // transaction plus whatever admit adds to it (the caller's admission // record), so the claim and the admission commit together. // // The attempt is registered as running here before its admission // commits, so a Recover never sees its claim without it and never // releases it unproven; a holder running here already is held, never // launched twice. func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error) (Admission, error) { if !m.reserve(local, h) { return Admission{Claimed: true, Hold: HoldBusy}, nil } var a Admission err := m.tx(ctx, func(t *sql.Tx) error { var err error if a, err = Admit(ctx, t, local, h, m.now()); err != nil || !a.Admitted || admit == nil { return err } return admit(t) }) if err != nil || !a.Admitted { // A failed admission (the caller's part refused it) admits nothing. m.setRunning(local, h, false) if err != nil { a.Admitted = false } return a, err } if m.Fault != nil { if err := m.Fault("admitted"); err != nil { return a, err } } m.changed() return a, nil } // reserve registers h as running on local unless it is already. func (m *Meter) reserve(local string, h Holder) bool { m.mu.Lock() defer m.mu.Unlock() if m.running == nil { m.running = map[string]bool{} } key := local + "\x00" + h.Key() if m.running[key] { return false } m.running[key] = true return true } // Notify tells the runner a metered connection's standing changed (a // budget applied, a pause resumed) outside the Meter's own calls. func (m *Meter) Notify() { m.changed() } // Run admits h on the connection, runs the attempt and settles it. // Held, it returns the hold and runs nothing. report, in the charge's // transaction, records the priced rows (the attempt's report or usage // frame). An attempt whose exit is not proven keeps its slot until // Recover proves it. func (m *Meter) Run(ctx context.Context, local string, h Holder, run func(context.Context, Launch) Result, report func(*sql.Tx, []wire.Usage) error) (Admission, Result, error) { return m.RunAdmitted(ctx, local, h, nil, run, report) } // RunAdmitted is Run with the caller's admission (the scheduler's: the // facts rechecked, a Run now consumed, the admission row) written in the // guard's transaction, so the slot's claim and the admission commit // together or not at all. func (m *Meter) RunAdmitted(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error, run func(context.Context, Launch) Result, report func(*sql.Tx, []wire.Usage) error) (Admission, Result, error) { a, err := m.Admit(ctx, local, h, admit) if err != nil || !a.Admitted { return a, Result{}, err } c, _, err := Get(ctx, m.DB, local) if err != nil { return a, Result{}, err } res := run(ctx, Launch{Conn: c, Holder: h, Namespace: func(ns string) error { return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) }) }}) if m.Fault != nil { if err := m.Fault("exited"); err != nil { return a, res, err } } err = m.Finish(context.WithoutCancel(ctx), local, h, res, report) return a, res, err } // Namespace records the namespace of h's attempt in its slot (before the // harness starts it). func (m *Meter) Namespace(ctx context.Context, local string, h Holder, ns string) error { return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) }) } // Finish charges an attempt's usage and, once its exit is proven, // releases its slot, in one transaction. The attempt has ended either // way: an unproven one is Recover's to prove. func (m *Meter) Finish(ctx context.Context, local string, h Holder, res Result, report func(*sql.Tx, []wire.Usage) error) error { defer m.setRunning(local, h, false) err := m.tx(ctx, func(t *sql.Tx) error { priced, err := Charge(ctx, t, local, h, res.Usage, m.now()) if err != nil { return err } if report != nil { if err := report(t, priced); err != nil { return err } } if !res.Proven { return nil } return Settle(ctx, t, local, h, res.Ending) }) if err == nil { m.changed() } return err } // Recover reconciles every claimed slot whose attempt is not running in // this process, at start-up before anything is admitted and again // whenever an exit could not be proven (§2.3): the // attempt's namespace is proven gone; a usage row it committed is // already charged (Charge commits with the report); otherwise the // connection's spend becomes unknown; then the slot is released, in one // transaction. A slot whose namespace cannot be proven gone stays held, // so nothing else is admitted to that connection. func (m *Meter) Recover(ctx context.Context) error { held, err := claimed(ctx, m.DB) if err != nil { return err } var first error for _, c := range held { if m.isRunning(c.Local, c.Holder) { continue } if c.Namespace != "" { if m.Gone == nil { first = firstErr(first, ErrNotProven) continue } if err := m.Gone(ctx, c.Namespace); err != nil { first = firstErr(first, err) continue } } if err := m.tx(ctx, func(t *sql.Tx) error { return settle(ctx, t, c.Local, c.Holder, Ending{Proven: true}) }); err != nil { return err } m.changed() } return first } // Resume consumes a Resume for the pause it names (Resume). func (m *Meter) Resume(ctx context.Context, local, connection string, pauseRevision int64, record func(*sql.Tx) error) (bool, error) { var cleared bool err := m.tx(ctx, func(t *sql.Tx) error { var err error if cleared, err = Resume(ctx, t, local, connection, pauseRevision); err != nil { return err } if record != nil { return record(t) } return nil }) if err == nil && cleared { m.changed() } return cleared, err } // ApplyBudget applies a budget frame (ApplyBudget) with record, the // frame's own bookkeeping, in one transaction. func (m *Meter) ApplyBudget(ctx context.Context, local, connection string, b wire.Budget, record func(*sql.Tx) error) (bool, error) { var applied bool err := m.tx(ctx, func(t *sql.Tx) error { var err error if applied, err = ApplyBudget(ctx, t, local, connection, b); err != nil { return err } if record != nil { return record(t) } return nil }) if err == nil && applied { m.changed() } return applied, err }