-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathwarmStartClient.ts
More file actions
215 lines (186 loc) · 5.45 KB
/
warmStartClient.ts
File metadata and controls
215 lines (186 loc) · 5.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
import { DequeuedMessage } from "../schemas/runEngine.js";
import { SimpleStructuredLogger } from "../utils/structuredLogger.js";
import { WarmStartConnectResponse } from "../schemas/warmStart.js";
import { ApiResult, wrapZodFetch } from "../zodfetch.js";
import { ExponentialBackoff } from "../apps/backoff.js";
export type WarmStartClientOptions = {
apiUrl: URL;
controllerId: string;
deploymentId: string;
deploymentVersion: string;
machineCpu: string;
machineMemory: string;
};
export class WarmStartClient {
private readonly logger = new SimpleStructuredLogger("warm-start-client");
private readonly apiUrl: URL;
private backoff = new ExponentialBackoff("FullJitter");
private abortController: AbortController | null = null;
private get connectUrl() {
return new URL("/connect", this.apiUrl);
}
private get warmStartUrl() {
return new URL("/warm-start", this.apiUrl);
}
constructor(private opts: WarmStartClientOptions) {
this.apiUrl = opts.apiUrl;
}
abort() {
if (!this.abortController) {
this.logger.warn("Abort called but no abort controller exists");
return;
}
this.abortController.abort();
this.abortController = null;
}
private async withAbort<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (this.abortController) {
throw new Error("A warm start is already in progress");
}
this.abortController = new AbortController();
try {
return await fn(this.abortController.signal);
} finally {
this.abortController = null;
}
}
async connect(): Promise<ApiResult<WarmStartConnectResponse>> {
return wrapZodFetch(
WarmStartConnectResponse,
this.connectUrl.href,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
},
{
retry: {
minTimeoutInMs: 200,
maxTimeoutInMs: 2000,
maxAttempts: 3,
factor: 2,
randomize: false,
},
}
);
}
async warmStart({
workerInstanceName,
connectionTimeoutMs,
keepaliveMs,
}: {
workerInstanceName: string;
connectionTimeoutMs: number;
keepaliveMs: number;
}): Promise<DequeuedMessage | null> {
return this.withAbort(async (abortSignal) => {
const res = await this.longPoll<unknown>(
this.warmStartUrl.href,
{
method: "GET",
headers: {
"x-trigger-workload-controller-id": this.opts.controllerId,
"x-trigger-deployment-id": this.opts.deploymentId,
"x-trigger-deployment-version": this.opts.deploymentVersion,
"x-trigger-machine-cpu": this.opts.machineCpu,
"x-trigger-machine-memory": this.opts.machineMemory,
"x-trigger-worker-instance-name": workerInstanceName,
},
},
{
timeoutMs: connectionTimeoutMs,
totalDurationMs: keepaliveMs,
abortSignal,
}
);
if (!res.ok) {
this.logger.error("warmStart: failed", {
error: res.error,
connectionTimeoutMs,
keepaliveMs,
});
return null;
}
const nextRun = DequeuedMessage.parse(res.data);
this.logger.debug("warmStart: got next run", { nextRun });
return nextRun;
});
}
private async longPoll<T = any>(
url: string,
requestInit: Omit<RequestInit, "signal">,
{
timeoutMs,
totalDurationMs,
abortSignal,
}: {
timeoutMs: number;
totalDurationMs: number;
abortSignal: AbortSignal;
}
): Promise<
| {
ok: true;
data: T;
}
| {
ok: false;
error: string;
}
> {
this.logger.debug("Long polling", { url, requestInit, timeoutMs, totalDurationMs });
const endTime = Date.now() + totalDurationMs;
let retries = 0;
while (Date.now() < endTime) {
if (abortSignal.aborted) {
return {
ok: false,
error: "Aborted - abort signal triggered before fetch",
};
}
try {
const timeoutController = new AbortController();
const timeoutId = setTimeout(() => timeoutController.abort(), timeoutMs);
// Create compound signal that aborts on either timeout or parent abort
const signals = [timeoutController.signal, abortSignal];
const signal = AbortSignal.any(signals);
const response = await fetch(url, { ...requestInit, signal });
clearTimeout(timeoutId);
if (response.ok) {
const data = await response.json();
return {
ok: true,
data,
};
} else {
return {
ok: false,
error: `Server error: ${response.status}`,
};
}
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// Check if this was a parent abort or just a timeout
if (abortSignal.aborted) {
return {
ok: false,
error: "Aborted - abort signal triggered during fetch",
};
}
this.logger.log("Long poll request timed out, retrying...");
continue;
} else {
this.logger.error("Error during fetch, retrying...", { error });
// Wait with exponential backoff
await this.backoff.wait(retries++);
continue;
}
}
}
return {
ok: false,
error: "TotalDurationExceeded",
};
}
}