-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmanager.ts
More file actions
435 lines (355 loc) · 12.2 KB
/
manager.ts
File metadata and controls
435 lines (355 loc) · 12.2 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import { dequal } from "dequal/lite";
import { DeserializedJson } from "../../schemas/json.js";
import { ApiClient } from "../apiClient/index.js";
import { FlushedRunMetadata, RunMetadataChangeOperation } from "../schemas/common.js";
import { ApiRequestOptions } from "../zodfetch.js";
import { MetadataStream } from "./metadataStream.js";
import { applyMetadataOperations, collapseOperations } from "./operations.js";
import { RunMetadataManager, RunMetadataUpdater } from "./types.js";
import { AsyncIterableStream } from "../streams/asyncIterableStream.js";
const MAXIMUM_ACTIVE_STREAMS = 5;
const MAXIMUM_TOTAL_STREAMS = 10;
export class StandardMetadataManager implements RunMetadataManager {
private flushTimeoutId: NodeJS.Timeout | null = null;
private isFlushing: boolean = false;
private store: Record<string, DeserializedJson> | undefined;
// Add a Map to track active streams
private activeStreams = new Map<string, MetadataStream<any>>();
private queuedOperations: Set<RunMetadataChangeOperation> = new Set();
private queuedParentOperations: Set<RunMetadataChangeOperation> = new Set();
private queuedRootOperations: Set<RunMetadataChangeOperation> = new Set();
public runId: string | undefined;
constructor(
private apiClient: ApiClient,
private streamsBaseUrl: string,
private streamsVersion: "v1" | "v2" = "v1"
) {}
get parent(): RunMetadataUpdater {
// Store a reference to 'this' to ensure proper context
const self = this;
// Create the updater object and store it in a local variable
const parentUpdater: RunMetadataUpdater = {
set: (key, value) => {
self.queuedParentOperations.add({ type: "set", key, value });
return parentUpdater;
},
del: (key) => {
self.queuedParentOperations.add({ type: "delete", key });
return parentUpdater;
},
append: (key, value) => {
self.queuedParentOperations.add({ type: "append", key, value });
return parentUpdater;
},
remove: (key, value) => {
self.queuedParentOperations.add({ type: "remove", key, value });
return parentUpdater;
},
increment: (key, value) => {
self.queuedParentOperations.add({ type: "increment", key, value });
return parentUpdater;
},
decrement: (key, value) => {
self.queuedParentOperations.add({ type: "increment", key, value: -Math.abs(value) });
return parentUpdater;
},
update: (value) => {
self.queuedParentOperations.add({ type: "update", value });
return parentUpdater;
},
stream: (key, value, signal) => self.doStream(key, value, "parent", parentUpdater, signal),
};
return parentUpdater;
}
get root(): RunMetadataUpdater {
// Store a reference to 'this' to ensure proper context
const self = this;
// Create the updater object and store it in a local variable
const rootUpdater: RunMetadataUpdater = {
set: (key, value) => {
self.queuedRootOperations.add({ type: "set", key, value });
return rootUpdater;
},
del: (key) => {
self.queuedRootOperations.add({ type: "delete", key });
return rootUpdater;
},
append: (key, value) => {
self.queuedRootOperations.add({ type: "append", key, value });
return rootUpdater;
},
remove: (key, value) => {
self.queuedRootOperations.add({ type: "remove", key, value });
return rootUpdater;
},
increment: (key, value) => {
self.queuedRootOperations.add({ type: "increment", key, value });
return rootUpdater;
},
decrement: (key, value) => {
self.queuedRootOperations.add({ type: "increment", key, value: -Math.abs(value) });
return rootUpdater;
},
update: (value) => {
self.queuedRootOperations.add({ type: "update", value });
return rootUpdater;
},
stream: (key, value, signal) => self.doStream(key, value, "root", rootUpdater, signal),
};
return rootUpdater;
}
public enterWithMetadata(metadata: Record<string, DeserializedJson>): void {
this.store = metadata ?? {};
}
public current(): Record<string, DeserializedJson> | undefined {
return this.store;
}
public getKey(key: string): DeserializedJson | undefined {
return this.store?.[key];
}
private enqueueOperation(operation: RunMetadataChangeOperation) {
const applyResults = applyMetadataOperations(this.store ?? {}, operation);
if (applyResults.unappliedOperations.length > 0) {
return;
}
if (dequal(this.store, applyResults.newMetadata)) {
return;
}
this.queuedOperations.add(operation);
this.store = applyResults.newMetadata as Record<string, DeserializedJson>;
}
public set(key: string, value: DeserializedJson) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "set", key, value });
return this;
}
public del(key: string) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "delete", key });
return this;
}
public append(key: string, value: DeserializedJson) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "append", key, value });
return this;
}
public remove(key: string, value: DeserializedJson) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "remove", key, value });
return this;
}
public increment(key: string, increment: number = 1) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "increment", key, value: increment });
return this;
}
public decrement(key: string, decrement: number = 1) {
return this.increment(key, -decrement);
}
public update(metadata: Record<string, DeserializedJson>) {
if (!this.runId) {
return this;
}
this.enqueueOperation({ type: "update", value: metadata });
return this;
}
public async stream<T>(
key: string,
value: AsyncIterable<T> | ReadableStream<T>,
signal?: AbortSignal
): Promise<AsyncIterable<T>> {
return this.doStream(key, value, "self", this, signal);
}
public async fetchStream<T>(key: string, signal?: AbortSignal): Promise<AsyncIterableStream<T>> {
if (!this.runId) {
throw new Error("Run ID is required to fetch metadata streams.");
}
const baseUrl = this.getKey("$$streamsBaseUrl");
const $baseUrl = typeof baseUrl === "string" ? baseUrl : this.streamsBaseUrl;
return this.apiClient.fetchStream<T>(this.runId, key, { baseUrl: $baseUrl, signal });
}
private async doStream<T>(
key: string,
value: AsyncIterable<T> | ReadableStream<T>,
target: "self" | "parent" | "root",
updater: RunMetadataUpdater = this,
signal?: AbortSignal
): Promise<AsyncIterable<T>> {
const $value = value as AsyncIterable<T>;
if (!this.runId) {
return $value;
}
// Check to make sure we haven't exceeded the max number of active streams
if (this.activeStreams.size >= MAXIMUM_ACTIVE_STREAMS) {
console.warn(
`Exceeded the maximum number of active streams (${MAXIMUM_ACTIVE_STREAMS}). The "${key}" stream will be ignored.`
);
return $value;
}
// Check to make sure we haven't exceeded the max number of total streams
const streams = (this.store?.$$streams ?? []) as string[];
if (streams.length >= MAXIMUM_TOTAL_STREAMS) {
console.warn(
`Exceeded the maximum number of total streams (${MAXIMUM_TOTAL_STREAMS}). The "${key}" stream will be ignored.`
);
return $value;
}
try {
const streamInstance = new MetadataStream({
key,
runId: this.runId,
source: $value,
baseUrl: this.streamsBaseUrl,
headers: this.apiClient.getHeaders(),
signal,
version: this.streamsVersion,
target,
});
this.activeStreams.set(key, streamInstance);
// Clean up when stream completes
streamInstance.wait().finally(() => this.activeStreams.delete(key));
// Add the key to the special stream metadata object
updater
.append(`$$streams`, key)
.set("$$streamsVersion", this.streamsVersion)
.set("$$streamsBaseUrl", this.streamsBaseUrl);
await this.flush();
return streamInstance;
} catch (error) {
// Clean up metadata key if stream creation fails
updater.remove(`$$streams`, key);
throw error;
}
}
public hasActiveStreams(): boolean {
return this.activeStreams.size > 0;
}
// Waits for all the streams to finish
public async waitForAllStreams(timeout: number = 60_000): Promise<void> {
if (this.activeStreams.size === 0) {
return;
}
const promises = Array.from(this.activeStreams.values()).map((stream) => stream.wait());
try {
await Promise.race([
Promise.allSettled(promises),
new Promise<void>((resolve, _) => setTimeout(() => resolve(), timeout)),
]);
} catch (error) {
console.error("Error waiting for streams to finish:", error);
// If we time out, abort all remaining streams
for (const [key, promise] of this.activeStreams.entries()) {
// We can add abort logic here if needed
this.activeStreams.delete(key);
}
throw error;
}
}
public async refresh(requestOptions?: ApiRequestOptions): Promise<void> {
if (!this.runId) {
return;
}
try {
const metadata = await this.apiClient.getRunMetadata(this.runId, requestOptions);
this.store = metadata.metadata;
} catch (error) {
console.error("Failed to refresh metadata", error);
throw error;
}
}
public async flush(requestOptions?: ApiRequestOptions): Promise<void> {
if (!this.runId) {
return;
}
if (!this.#needsFlush()) {
return;
}
if (this.isFlushing) {
return;
}
this.isFlushing = true;
const operations = Array.from(this.queuedOperations);
this.queuedOperations.clear();
const parentOperations = Array.from(this.queuedParentOperations);
this.queuedParentOperations.clear();
const rootOperations = Array.from(this.queuedRootOperations);
this.queuedRootOperations.clear();
try {
const collapsedOperations = collapseOperations(operations);
const collapsedParentOperations = collapseOperations(parentOperations);
const collapsedRootOperations = collapseOperations(rootOperations);
const response = await this.apiClient.updateRunMetadata(
this.runId,
{
operations: collapsedOperations,
parentOperations: collapsedParentOperations,
rootOperations: collapsedRootOperations,
},
requestOptions
);
this.store = response.metadata;
} catch (error) {
console.error("Failed to flush metadata", error);
} finally {
this.isFlushing = false;
}
}
public startPeriodicFlush(intervalMs: number = 1000) {
const periodicFlush = async (intervalMs: number) => {
if (this.isFlushing) {
return;
}
try {
await this.flush();
} catch (error) {
console.error("Failed to flush metadata", error);
throw error;
} finally {
this.isFlushing = false;
scheduleNext();
}
};
const scheduleNext = () => {
this.flushTimeoutId = setTimeout(() => periodicFlush(intervalMs), intervalMs);
};
scheduleNext();
}
stopPeriodicFlush(): void {
if (this.flushTimeoutId) {
clearTimeout(this.flushTimeoutId);
this.flushTimeoutId = null;
}
}
stopAndReturnLastFlush(): FlushedRunMetadata | undefined {
this.stopPeriodicFlush();
this.isFlushing = true;
if (!this.#needsFlush()) {
return;
}
const operations = Array.from(this.queuedOperations);
const parentOperations = Array.from(this.queuedParentOperations);
const rootOperations = Array.from(this.queuedRootOperations);
return {
operations: collapseOperations(operations),
parentOperations: collapseOperations(parentOperations),
rootOperations: collapseOperations(rootOperations),
};
}
#needsFlush(): boolean {
return (
this.queuedOperations.size > 0 ||
this.queuedParentOperations.size > 0 ||
this.queuedRootOperations.size > 0
);
}
}