Repository navigation
Expand file tree
/
Copy pathobserve-until.ts
More file actions
277 lines (252 loc) · 9.45 KB
/
Copy pathobserve-until.ts
File metadata and controls
277 lines (252 loc) · 9.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { createRequestCanceledError } from '@agent-device/kernel/errors';
import type { ObservationEnd } from '@agent-device/contracts/observation';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
/**
* The one observation loop: capture until a verdict accepts, on a schedule, under a budget that is
* enforced by cancellation. Owns cadence, the deadline, abort-and-join of an in-flight capture,
* which capture errors are ridden out, and the per-poll timeline. Owns nothing about WHAT is
* observed: the verdict is the caller's, and so is the equality rule behind it (digest, signature,
* pixel).
*/
export type ObservationSchedule = Readonly<{
/** Delay between polls, clamped to the remaining budget. */
intervalMs: number;
/**
* Wall-clock budget from the first capture. It bounds when a poll may start, and a capture that
* starts inside it may overrun it by at most one interval: the sample after the last sleep is
* always taken, so a verdict that reads elapsed time against a cap sees a poll at or past it.
*/
budgetMs: number;
/** Observations (an `initial` counts) the loop always completes before the budget may end it. */
minPolls?: number;
/**
* `'start'` (default) bounds every capture, the first included. `'first-capture'` leaves the first
* capture unbounded and spends the budget only on retries, so a caller whose first attempt is a
* one-shot pays nothing on its success path.
*/
budgetFrom?: 'start' | 'first-capture';
}>;
export type ObservationClock = Readonly<{
now(): number;
sleep(ms: number): Promise<void>;
}>;
export type ObservationVerdict<R> =
| Readonly<{ kind: 'done'; result: R }>
/** Keep polling; `budgetMs` raises the budget measured from the first capture (never lowers it). */
| Readonly<{ kind: 'continue'; budgetMs?: number }>;
export type ObservationPollOutcome = 'observed' | 'rode-out' | 'stalled';
export type ObservationPoll = Readonly<{
startedMs: number;
durationMs: number;
outcome: ObservationPollOutcome;
}>;
export type ObservationEvidence = Readonly<{
polls: readonly ObservationPoll[];
waitedMs: number;
}>;
type ObservedEnd<T, R> =
| Readonly<{ kind: 'done'; result: R; value: T }>
| Readonly<{ kind: 'expired'; last: T | undefined; lastError: unknown }>
| Readonly<{ kind: 'stalled'; last: T | undefined; error: unknown }>
| Readonly<{ kind: 'failed'; last: T | undefined; error: unknown }>;
export type Observed<T, R> = ObservationEvidence & ObservedEnd<T, R>;
export type ObserveUntilParams<T, R> = Readonly<{
capture: (signal: AbortSignal) => Promise<T>;
/** Judges the latest capture; `previous` is the last observed value, for quiet-pair predicates. */
verdict: (latest: T, previous: T | undefined, polls: number) => ObservationVerdict<R>;
schedule: ObservationSchedule;
/** True keeps polling past this capture error. Default: no error is ridden out. */
rideOut?: (error: unknown) => boolean;
signal?: AbortSignal;
clock?: ObservationClock;
/** A capture the caller already holds; judged first, without a poll. */
initial?: T;
/** Diagnostic phase for the end-of-loop line; nothing is logged without it. */
phase?: string;
}>;
const REAL_CLOCK: ObservationClock = {
now: () => Date.now(),
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
};
type LoopState<T> = {
readonly startedMs: number;
budgetStartedMs: number;
budgetMs: number;
observations: number;
readonly polls: ObservationPoll[];
previous: T | undefined;
last: T | undefined;
lastError: unknown;
};
type Loop<T, R> = Readonly<{
params: ObserveUntilParams<T, R>;
clock: ObservationClock;
state: LoopState<T>;
}>;
export async function observeUntil<T, R>(
params: ObserveUntilParams<T, R>,
): Promise<Observed<T, R>> {
const clock = params.clock ?? REAL_CLOCK;
const startedMs = clock.now();
const loop: Loop<T, R> = {
params,
clock,
state: {
startedMs,
budgetStartedMs: startedMs,
budgetMs: params.schedule.budgetMs,
observations: 0,
polls: [],
previous: undefined,
last: undefined,
lastError: undefined,
},
};
if (params.initial !== undefined) {
loop.state.observations += 1;
const done = judge(loop, params.initial);
if (done) return done;
}
while (true) {
if (params.signal?.aborted) throw createRequestCanceledError();
const expired = await waitBeforePoll(loop);
if (expired) return expired;
const ended = await pollOnce(loop);
if (ended) return ended;
}
}
function remainingMs<T, R>({ state, clock }: Loop<T, R>): number {
return state.budgetStartedMs + state.budgetMs - clock.now();
}
function mustPoll<T, R>({ params, state }: Loop<T, R>): boolean {
return state.observations < (params.schedule.minPolls ?? 1);
}
/** Sleeps one interval between observations; ends the loop when the budget is spent first. */
async function waitBeforePoll<T, R>(loop: Loop<T, R>): Promise<Observed<T, R> | undefined> {
const { state, clock, params } = loop;
if (state.observations === 0) return undefined;
const forced = mustPoll(loop);
if (!forced && remainingMs(loop) <= 0)
return finish(loop, { kind: 'expired', last: state.last, lastError: state.lastError });
const { intervalMs } = params.schedule;
await clock.sleep(forced ? intervalMs : Math.max(0, Math.min(intervalMs, remainingMs(loop))));
return undefined;
}
async function pollOnce<T, R>(loop: Loop<T, R>): Promise<Observed<T, R> | undefined> {
const { params, clock, state } = loop;
const unbounded = params.schedule.budgetFrom === 'first-capture' && state.polls.length === 0;
const pollStartedMs = clock.now();
const poll = await captureWithin(
unbounded ? undefined : Math.max(remainingMs(loop), params.schedule.intervalMs),
params.signal,
params.capture,
);
state.observations += 1;
if (unbounded) state.budgetStartedMs = clock.now();
const outcome = pollOutcome(loop, poll);
state.polls.push({
startedMs: pollStartedMs - state.startedMs,
durationMs: clock.now() - pollStartedMs,
outcome,
});
if (poll.kind === 'observed') return judge(loop, poll.value);
if (outcome === 'rode-out') return undefined;
return finish(loop, { kind: poll.kind, last: state.last, error: poll.error });
}
function pollOutcome<T, R>(
loop: Loop<T, R>,
poll: CaptureWithinOutcome<T>,
): ObservationPollOutcome {
if (poll.kind === 'stalled') return 'stalled';
if (poll.kind === 'failed') return loop.params.rideOut?.(poll.error) ? 'rode-out' : 'observed';
return 'observed';
}
function judge<T, R>(loop: Loop<T, R>, value: T): Observed<T, R> | undefined {
const { params, state } = loop;
const verdict = params.verdict(value, state.previous, state.polls.length);
state.previous = value;
state.last = value;
if (verdict.kind === 'done') return finish(loop, { kind: 'done', result: verdict.result, value });
if (verdict.budgetMs !== undefined) state.budgetMs = Math.max(state.budgetMs, verdict.budgetMs);
return undefined;
}
function finish<T, R>(loop: Loop<T, R>, end: ObservedEnd<T, R>): Observed<T, R> {
const { params, state, clock } = loop;
const observed: Observed<T, R> = {
...end,
polls: state.polls,
waitedMs: clock.now() - state.startedMs,
};
if (params.phase) {
emitDiagnostic({
level: 'debug',
phase: params.phase,
data: {
end: observed.kind satisfies ObservationEnd,
polls: state.polls.length,
waitedMs: observed.waitedMs,
},
});
}
return observed;
}
type CaptureWithinOutcome<T> =
| Readonly<{ kind: 'observed'; value: T }>
| Readonly<{ kind: 'failed'; error: unknown }>
| Readonly<{ kind: 'stalled'; error: unknown }>;
/**
* Runs one capture under the remaining budget by cancellation, then waits for it to quiesce.
* Deliberately not race-and-abandon: a late capture could otherwise mutate session state or keep a
* platform helper after the loop has returned.
*/
async function captureWithin<T>(
remainingMs: number | undefined,
parent: AbortSignal | undefined,
capture: (signal: AbortSignal) => Promise<T>,
): Promise<CaptureWithinOutcome<T>> {
const deadline = armDeadline(remainingMs);
const signal = parent ? AbortSignal.any([parent, deadline.signal]) : deadline.signal;
try {
const value = await capture(signal);
return endOfCapture(parent, deadline.expired(), undefined) ?? { kind: 'observed', value };
} catch (error) {
return endOfCapture(parent, deadline.expired(), error) ?? { kind: 'failed', error };
} finally {
deadline.dispose();
}
}
/** A capture that ended after the deadline stalled; one ended by the caller's signal was canceled. */
function endOfCapture<T>(
parent: AbortSignal | undefined,
deadlineExpired: boolean,
error: unknown,
): CaptureWithinOutcome<T> | undefined {
if (parent?.aborted) throw createRequestCanceledError();
return deadlineExpired ? { kind: 'stalled', error } : undefined;
}
function armDeadline(remainingMs: number | undefined): {
signal: AbortSignal;
expired: () => boolean;
dispose: () => void;
} {
const controller = new AbortController();
let expired = false;
const timer =
remainingMs === undefined
? undefined
: setTimeout(
() => {
expired = true;
controller.abort(new DOMException('Observation deadline exceeded', 'TimeoutError'));
},
Math.max(0, remainingMs),
);
timer?.unref();
return {
signal: controller.signal,
expired: () => expired,
dispose: () => {
if (timer !== undefined) clearTimeout(timer);
},
};
}