-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcomputeSnapshotService.ts
More file actions
323 lines (289 loc) · 10.8 KB
/
Copy pathcomputeSnapshotService.ts
File metadata and controls
323 lines (289 loc) · 10.8 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import pLimit from "p-limit";
import { SimpleStructuredLogger } from "@trigger.dev/core/v3/utils/structuredLogger";
import { parseTraceparent } from "@trigger.dev/core/v3/isomorphic";
import type { SupervisorHttpClient } from "@trigger.dev/core/v3/workers";
import { type SnapshotCallbackPayload } from "@internal/compute";
import type { ComputeWorkloadManager } from "../workloadManager/compute.js";
import { TimerWheel } from "./timerWheel.js";
import type { OtlpTraceService } from "./otlpTraceService.js";
import {
emitOneShot,
fromContext,
recordPhaseSince,
runWideEvent,
setExtra,
setMeta,
type WideEventOptions,
} from "../wideEvents/index.js";
type DelayedSnapshot = {
runnerId: string;
runFriendlyId: string;
snapshotFriendlyId: string;
};
export type RunTraceContext = {
traceparent: string;
envId: string;
orgId: string;
projectId: string;
};
export type ComputeSnapshotServiceOptions = {
computeManager: ComputeWorkloadManager;
workerClient: SupervisorHttpClient;
tracing?: OtlpTraceService;
wideEventOpts: WideEventOptions;
};
export class ComputeSnapshotService {
private readonly logger = new SimpleStructuredLogger("compute-snapshot-service");
private static readonly MAX_TRACE_CONTEXTS = 10_000;
private readonly runTraceContexts = new Map<string, RunTraceContext>();
private readonly timerWheel: TimerWheel<DelayedSnapshot>;
private readonly dispatchLimit: ReturnType<typeof pLimit>;
private readonly computeManager: ComputeWorkloadManager;
private readonly workerClient: SupervisorHttpClient;
private readonly tracing?: OtlpTraceService;
private readonly wideEventOpts: WideEventOptions;
constructor(opts: ComputeSnapshotServiceOptions) {
this.computeManager = opts.computeManager;
this.workerClient = opts.workerClient;
this.tracing = opts.tracing;
this.wideEventOpts = opts.wideEventOpts;
this.dispatchLimit = pLimit(this.computeManager.snapshotDispatchLimit);
this.timerWheel = new TimerWheel<DelayedSnapshot>({
delayMs: this.computeManager.snapshotDelayMs,
onExpire: (item) => {
this.dispatchLimit(() => this.dispatch(item.data)).catch((error) => {
this.logger.error("Snapshot dispatch failed", {
runId: item.data.runFriendlyId,
runnerId: item.data.runnerId,
error,
});
});
},
});
this.timerWheel.start();
}
/** Schedule a delayed snapshot for a run. Replaces any pending snapshot for the same run. */
schedule(runFriendlyId: string, data: DelayedSnapshot) {
this.timerWheel.submit(runFriendlyId, data);
emitOneShot({
...this.wideEventOpts,
op: "snapshot.schedule",
kind: "event",
populate: (state) => {
state.meta.run_id = runFriendlyId;
state.meta.snapshot_id = data.snapshotFriendlyId;
state.extras.runner_id = data.runnerId;
state.extras.delay_ms = this.computeManager.snapshotDelayMs;
},
});
this.logger.debug("Snapshot scheduled", {
runFriendlyId,
snapshotFriendlyId: data.snapshotFriendlyId,
delayMs: this.computeManager.snapshotDelayMs,
});
}
/**
* Cancel a pending delayed snapshot. Returns true if one was cancelled.
* When `runnerId` is given, only a snapshot scheduled for that same runner
* is cancelled - a stale runner for a run that has since been reassigned
* must not cancel the new runner's pending snapshot.
*/
cancel(runFriendlyId: string, runnerId?: string): boolean {
if (runnerId) {
const pending = this.timerWheel.peek(runFriendlyId);
if (pending && pending.data.runnerId !== runnerId) {
return false;
}
}
const cancelled = this.timerWheel.cancel(runFriendlyId);
if (cancelled) {
emitOneShot({
...this.wideEventOpts,
op: "snapshot.canceled",
kind: "event",
populate: (state) => {
state.meta.run_id = runFriendlyId;
},
});
this.logger.debug("Snapshot cancelled", { runFriendlyId });
}
return cancelled;
}
/** Handle the callback from the gateway after a snapshot completes or fails. */
async handleCallback(body: SnapshotCallbackPayload) {
const snapshotId = body.status === "completed" ? body.snapshot_id : undefined;
const runId = body.metadata?.runId;
const snapshotFriendlyId = body.metadata?.snapshotFriendlyId;
// Enrich the wrapping route's wide event with snapshot metadata. The
// `/api/v1/compute/snapshot-complete` route is registered with `wideRoute`,
// so `fromContext()` returns the State of that route and these calls
// become extras/meta on the same wide event - no nested emission.
const state = fromContext();
if (state) {
state.extras["snapshot.status"] = body.status;
if (body.instance_id) state.extras["snapshot.instance_id"] = body.instance_id;
if (body.duration_ms !== undefined) state.extras["snapshot.duration_ms"] = body.duration_ms;
if (snapshotId) state.extras["snapshot.id"] = snapshotId;
if (body.status === "failed" && body.error) state.extras["snapshot.error"] = body.error;
}
if (runId) setMeta(state, "run_id", runId);
if (snapshotFriendlyId) setMeta(state, "snapshot_id", snapshotFriendlyId);
this.logger.debug("Snapshot callback", {
snapshotId,
instanceId: body.instance_id,
status: body.status,
error: body.status === "failed" ? body.error : undefined,
metadata: body.metadata,
durationMs: body.duration_ms,
});
if (!runId || !snapshotFriendlyId) {
this.logger.error("Snapshot callback missing metadata", { body });
return { ok: false as const, status: 400 };
}
this.#emitSnapshotSpan(runId, body.duration_ms, snapshotId);
if (body.status === "completed") {
const submitStart = performance.now();
const result = await this.workerClient.submitSuspendCompletion({
runId,
snapshotId: snapshotFriendlyId,
body: {
success: true,
checkpoint: {
type: "COMPUTE",
location: body.snapshot_id,
},
},
});
recordPhaseSince(
"submit_completion",
submitStart,
result.success ? undefined : new Error(String(result.error))
);
if (result.success) {
this.logger.debug("Suspend completion submitted", {
runId,
instanceId: body.instance_id,
snapshotId: body.snapshot_id,
});
} else {
setExtra(state, "submit_completion.error", String(result.error));
this.logger.error("Failed to submit suspend completion", {
runId,
snapshotFriendlyId,
error: result.error,
});
}
} else {
const submitStart = performance.now();
const result = await this.workerClient.submitSuspendCompletion({
runId,
snapshotId: snapshotFriendlyId,
body: {
success: false,
error: body.error ?? "Snapshot failed",
},
});
recordPhaseSince(
"submit_completion",
submitStart,
result.success ? undefined : new Error(String(result.error))
);
if (!result.success) {
setExtra(state, "submit_completion.error", String(result.error));
this.logger.error("Failed to submit suspend failure", {
runId,
snapshotFriendlyId,
error: result.error,
});
}
}
return { ok: true as const, status: 200 };
}
registerTraceContext(runFriendlyId: string, ctx: RunTraceContext) {
// Evict oldest entries if we've hit the cap. This is best-effort: on a busy
// supervisor, entries for long-lived runs may be evicted before their snapshot
// callback arrives, causing those snapshot spans to be silently dropped.
// That's acceptable - trace spans are observability sugar, not correctness.
if (this.runTraceContexts.size >= ComputeSnapshotService.MAX_TRACE_CONTEXTS) {
const firstKey = this.runTraceContexts.keys().next().value;
if (firstKey) {
this.runTraceContexts.delete(firstKey);
}
}
this.runTraceContexts.set(runFriendlyId, ctx);
}
/** Stop the timer wheel, dropping pending snapshots. */
stop(): string[] {
// Intentionally drop pending snapshots rather than dispatching them. The supervisor
// is shutting down, so our callback URL will be dead by the time the gateway responds.
// Runners detect the supervisor is gone and reconnect to a new instance, which
// re-triggers the snapshot workflow. Snapshots are an optimization, not a correctness
// requirement - runs continue fine without them.
const remaining = this.timerWheel.stop();
const droppedRuns = remaining.map((item) => item.key);
if (droppedRuns.length > 0) {
this.logger.info("Stopped, dropped pending snapshots", { count: droppedRuns.length });
this.logger.debug("Dropped snapshot details", { runs: droppedRuns });
}
return droppedRuns;
}
/** Dispatch a snapshot request to the gateway. */
private async dispatch(snapshot: DelayedSnapshot): Promise<void> {
await runWideEvent(
{
...this.wideEventOpts,
op: "snapshot.dispatch",
kind: "scheduled",
setup: (state) => {
state.meta.run_id = snapshot.runFriendlyId;
state.meta.snapshot_id = snapshot.snapshotFriendlyId;
state.extras.runner_id = snapshot.runnerId;
},
},
async () => {
const result = await this.computeManager.snapshot({
runnerId: snapshot.runnerId,
metadata: {
runId: snapshot.runFriendlyId,
snapshotFriendlyId: snapshot.snapshotFriendlyId,
},
});
if (!result) {
throw new Error("Snapshot dispatch returned no result");
}
}
);
}
#emitSnapshotSpan(runFriendlyId: string, durationMs?: number, snapshotId?: string) {
if (!this.tracing) return;
const ctx = this.runTraceContexts.get(runFriendlyId);
if (!ctx) return;
const parsed = parseTraceparent(ctx.traceparent);
if (!parsed) return;
const endEpochMs = Date.now();
const startEpochMs = durationMs ? endEpochMs - durationMs : endEpochMs;
const spanAttributes: Record<string, string | number | boolean> = {
"compute.type": "snapshot",
};
if (durationMs !== undefined) {
spanAttributes["compute.total_ms"] = durationMs;
}
if (snapshotId) {
spanAttributes["compute.snapshot_id"] = snapshotId;
}
this.tracing.emit({
traceId: parsed.traceId,
parentSpanId: parsed.spanId,
spanName: "compute.snapshot",
startTimeMs: startEpochMs,
endTimeMs: endEpochMs,
resourceAttributes: {
"ctx.environment.id": ctx.envId,
"ctx.organization.id": ctx.orgId,
"ctx.project.id": ctx.projectId,
"ctx.run.id": runFriendlyId,
},
spanAttributes,
});
}
}