Files
MrAlders0n 03f66d1ae4 Database pools by workload, plan router, observe-only guards, metrics (rest of #237) (#238)
* feat(db): five pgx pools with fixed session settings and Prometheus tracing

* feat(guards): per-family observe/enforce guards with client slots, deadlines and a shadow budget

* fix(guards): attribute only guard deadlines and classify like the handlers

* feat(db): route API statements by sqlc name; class C always unnamed

* feat(admin): statement statistics by sqlc name; create pg_stat_statements where allowed

* fix(db): skip pg_stat_statements when no schema is creatable

* feat(background): index health against post-rebuild baselines, Postgres activity, job and ingest metrics

* feat: separate API, ingest and maintenance stores; guards on the public API; metrics listener

* fix(db): keep ingest writes waiting, size the ingest pool to the host, tidy

* test(db): give the statements probe a query id of its own
2026-10-19 07:52:51 -04:00

47 lines
1.1 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package guards
import "time"
// sweepEvery is how many debits pass between sweeps of idle budgets.
const sweepEvery = 1024
// bucket is a client's database-time budget in seconds, refilled lazily at one
// second per second up to BudgetBurst.
type bucket struct {
tokens float64
at time.Time
}
func (b *bucket) refill(now time.Time) {
b.tokens = min(BudgetBurst.Seconds(), b.tokens+now.Sub(b.at).Seconds())
b.at = now
}
// debit charges d to key's budget and reports whether the budget went below
// zero. The budget only observes: it never refuses.
func (g *Guard) debit(key string, d time.Duration, now time.Time) bool {
g.bmu.Lock()
defer g.bmu.Unlock()
b := g.budgets[key]
if b == nil {
b = &bucket{tokens: BudgetBurst.Seconds(), at: now}
g.budgets[key] = b
}
b.refill(now)
b.tokens -= d.Seconds()
over := b.tokens < 0
g.debits++
if g.debits%sweepEvery == 0 {
for k, other := range g.budgets {
other.refill(now)
if other.tokens >= BudgetBurst.Seconds() {
delete(g.budgets, k)
}
}
}
return over
}