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 "sync"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/wire"
11)
12
13// Meter runs attempts on metered connections through the guard (§2.3):
14// admitted with the slot claimed in one transaction; the usage charged
15// and reported in one transaction; the slot released only after the
16// attempt's termination proof, with its charge or with the spend
17// unknown, in that same transaction. A harness (S2's Pi, a test's fake)
18// runs the attempt; the Meter never starts one itself.
19type Meter struct {
20 DB *sql.DB
21 // Gone proves an attempt's namespace gone (killed and its exit
22 // verified, as the step recovery does). An attempt that recorded no
23 // namespace started no harness.
24 Gone func(ctx context.Context, namespace string) error
25 Now func() time.Time
26 // Changed is called when a slot was released or a pause, a budget or
27 // a charge changed what hello reports.
28 Changed func()
29 // Fault, in tests, stops the process at a boundary ("exited": after
30 // the harness ended, before its charge), as if it stopped there.
31 Fault func(stage string) error
32
33 // running are the slots this process admitted whose attempt has not
34 // ended: Recover never touches them.
35 mu sync.Mutex
36 running map[string]bool
37}
38
39func (m *Meter) setRunning(local string, h Holder, on bool) {
40 m.mu.Lock()
41 defer m.mu.Unlock()
42 if m.running == nil {
43 m.running = map[string]bool{}
44 }
45 if on {
46 m.running[local+"\x00"+h.Key()] = true
47 } else {
48 delete(m.running, local+"\x00"+h.Key())
49 }
50}
51
52func (m *Meter) isRunning(local, holder string) bool {
53 m.mu.Lock()
54 defer m.mu.Unlock()
55 return m.running[local+"\x00"+holder]
56}
57
58// ErrStopped is a test fault's stop.
59var ErrStopped = errors.New("metered: stopped")
60
61// Launch is what a harness gets for one admitted attempt: the connection
62// and the holder, and Namespace, which records the attempt's namespace
63// in its slot before the harness starts it.
64type Launch struct {
65 Conn Conn
66 Holder Holder
67 Namespace func(ns string) error
68}
69
70// Result is how an attempt ended: the usage rows the harness reported,
71// and its Ending.
72type Result struct {
73 Usage []wire.Usage
74 Ending
75}
76
77func (m *Meter) now() time.Time {
78 if m.Now != nil {
79 return m.Now()
80 }
81 return time.Now()
82}
83
84func (m *Meter) tx(ctx context.Context, fn func(*sql.Tx) error) error {
85 t, err := m.DB.BeginTx(ctx, nil)
86 if err != nil {
87 return err
88 }
89 defer t.Rollback()
90 if err = fn(t); err != nil {
91 return err
92 }
93 return t.Commit()
94}
95
96func (m *Meter) changed() {
97 if m.Changed != nil {
98 m.Changed()
99 }
100}
101
102// Admit claims the slot for h when the guard allows it, in its own
103// transaction plus whatever admit adds to it (the caller's admission
104// record), so the claim and the admission commit together.
105//
106// The attempt is registered as running here before its admission
107// commits, so a Recover never sees its claim without it and never
108// releases it unproven; a holder running here already is held, never
109// launched twice.
110func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error) (Admission, error) {
111 if !m.reserve(local, h) {
112 return Admission{Claimed: true, Hold: HoldBusy}, nil
113 }
114 var a Admission
115 err := m.tx(ctx, func(t *sql.Tx) error {
116 var err error
117 if a, err = Admit(ctx, t, local, h, m.now()); err != nil || !a.Admitted || admit == nil {
118 return err
119 }
120 return admit(t)
121 })
122 if err != nil || !a.Admitted {
123 // A failed admission (the caller's part refused it) admits nothing.
124 m.setRunning(local, h, false)
125 if err != nil {
126 a.Admitted = false
127 }
128 return a, err
129 }
130 if m.Fault != nil {
131 if err := m.Fault("admitted"); err != nil {
132 return a, err
133 }
134 }
135 m.changed()
136 return a, nil
137}
138
139// reserve registers h as running on local unless it is already.
140func (m *Meter) reserve(local string, h Holder) bool {
141 m.mu.Lock()
142 defer m.mu.Unlock()
143 if m.running == nil {
144 m.running = map[string]bool{}
145 }
146 key := local + "\x00" + h.Key()
147 if m.running[key] {
148 return false
149 }
150 m.running[key] = true
151 return true
152}
153
154// Notify tells the runner a metered connection's standing changed (a
155// budget applied, a pause resumed) outside the Meter's own calls.
156func (m *Meter) Notify() { m.changed() }
157
158// Run admits h on the connection, runs the attempt and settles it.
159// Held, it returns the hold and runs nothing. report, in the charge's
160// transaction, records the priced rows (the attempt's report or usage
161// frame). An attempt whose exit is not proven keeps its slot until
162// Recover proves it.
163func (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) {
164 return m.RunAdmitted(ctx, local, h, nil, run, report)
165}
166
167// RunAdmitted is Run with the caller's admission (the scheduler's: the
168// facts rechecked, a Run now consumed, the admission row) written in the
169// guard's transaction, so the slot's claim and the admission commit
170// together or not at all.
171func (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) {
172 a, err := m.Admit(ctx, local, h, admit)
173 if err != nil || !a.Admitted {
174 return a, Result{}, err
175 }
176 c, _, err := Get(ctx, m.DB, local)
177 if err != nil {
178 return a, Result{}, err
179 }
180 res := run(ctx, Launch{Conn: c, Holder: h, Namespace: func(ns string) error {
181 return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) })
182 }})
183 if m.Fault != nil {
184 if err := m.Fault("exited"); err != nil {
185 return a, res, err
186 }
187 }
188 err = m.Finish(context.WithoutCancel(ctx), local, h, res, report)
189 return a, res, err
190}
191
192// Namespace records the namespace of h's attempt in its slot (before the
193// harness starts it).
194func (m *Meter) Namespace(ctx context.Context, local string, h Holder, ns string) error {
195 return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) })
196}
197
198// Finish charges an attempt's usage and, once its exit is proven,
199// releases its slot, in one transaction. The attempt has ended either
200// way: an unproven one is Recover's to prove.
201func (m *Meter) Finish(ctx context.Context, local string, h Holder, res Result, report func(*sql.Tx, []wire.Usage) error) error {
202 defer m.setRunning(local, h, false)
203 err := m.tx(ctx, func(t *sql.Tx) error {
204 priced, err := Charge(ctx, t, local, h, res.Usage, m.now())
205 if err != nil {
206 return err
207 }
208 if report != nil {
209 if err := report(t, priced); err != nil {
210 return err
211 }
212 }
213 if !res.Proven {
214 return nil
215 }
216 return Settle(ctx, t, local, h, res.Ending)
217 })
218 if err == nil {
219 m.changed()
220 }
221 return err
222}
223
224// Recover reconciles every claimed slot whose attempt is not running in
225// this process, at start-up before anything is admitted and again
226// whenever an exit could not be proven (§2.3): the
227// attempt's namespace is proven gone; a usage row it committed is
228// already charged (Charge commits with the report); otherwise the
229// connection's spend becomes unknown; then the slot is released, in one
230// transaction. A slot whose namespace cannot be proven gone stays held,
231// so nothing else is admitted to that connection.
232func (m *Meter) Recover(ctx context.Context) error {
233 held, err := claimed(ctx, m.DB)
234 if err != nil {
235 return err
236 }
237 var first error
238 for _, c := range held {
239 if m.isRunning(c.Local, c.Holder) {
240 continue
241 }
242 if c.Namespace != "" {
243 if m.Gone == nil {
244 first = firstErr(first, ErrNotProven)
245 continue
246 }
247 if err := m.Gone(ctx, c.Namespace); err != nil {
248 first = firstErr(first, err)
249 continue
250 }
251 }
252 if err := m.tx(ctx, func(t *sql.Tx) error { return settle(ctx, t, c.Local, c.Holder, Ending{Proven: true}) }); err != nil {
253 return err
254 }
255 m.changed()
256 }
257 return first
258}
259
260// Resume consumes a Resume for the pause it names (Resume).
261func (m *Meter) Resume(ctx context.Context, local, connection string, pauseRevision int64, record func(*sql.Tx) error) (bool, error) {
262 var cleared bool
263 err := m.tx(ctx, func(t *sql.Tx) error {
264 var err error
265 if cleared, err = Resume(ctx, t, local, connection, pauseRevision); err != nil {
266 return err
267 }
268 if record != nil {
269 return record(t)
270 }
271 return nil
272 })
273 if err == nil && cleared {
274 m.changed()
275 }
276 return cleared, err
277}
278
279// ApplyBudget applies a budget frame (ApplyBudget) with record, the
280// frame's own bookkeeping, in one transaction.
281func (m *Meter) ApplyBudget(ctx context.Context, local, connection string, b wire.Budget, record func(*sql.Tx) error) (bool, error) {
282 var applied bool
283 err := m.tx(ctx, func(t *sql.Tx) error {
284 var err error
285 if applied, err = ApplyBudget(ctx, t, local, connection, b); err != nil {
286 return err
287 }
288 if record != nil {
289 return record(t)
290 }
291 return nil
292 })
293 if err == nil && applied {
294 m.changed()
295 }
296 return applied, err
297}
298