-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathupdateMetadata.server.ts
More file actions
469 lines (405 loc) · 13.6 KB
/
updateMetadata.server.ts
File metadata and controls
469 lines (405 loc) · 13.6 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import {
applyMetadataOperations,
IOPacket,
parsePacket,
RunMetadataChangeOperation,
UpdateMetadataRequestBody,
} from "@trigger.dev/core/v3";
import { prisma, PrismaClientOrTransaction } from "~/db.server";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { handleMetadataPacket } from "~/utils/packets";
import { BaseService, ServiceValidationError } from "~/v3/services/baseService.server";
import { isFinalRunStatus } from "~/v3/taskStatus";
import { Effect, Schedule, Duration } from "effect";
import { type RuntimeFiber } from "effect/Fiber";
import { logger } from "../logger.server";
import { singleton } from "~/utils/singleton";
import { env } from "~/env.server";
import { setTimeout } from "timers/promises";
type BufferedRunMetadataChangeOperation = {
runId: string;
timestamp: number;
operation: RunMetadataChangeOperation;
};
export class UpdateMetadataService extends BaseService {
private _bufferedOperations: Map<string, BufferedRunMetadataChangeOperation[]> = new Map();
private _flushFiber: RuntimeFiber<void> | null = null;
constructor(
protected readonly _prisma: PrismaClientOrTransaction = prisma,
private readonly flushIntervalMs: number = 5000,
private readonly flushEnabled: boolean = true,
private readonly flushLoggingEnabled: boolean = true
) {
super();
this._startFlushing();
}
// Start a loop that periodically flushes buffered operations
private _startFlushing() {
if (!this.flushEnabled) {
logger.info("[UpdateMetadataService] 🚽 Flushing disabled");
return;
}
logger.info("[UpdateMetadataService] 🚽 Flushing started");
// Create a program that sleeps, then processes buffered ops
const program = Effect.gen(this, function* (_) {
while (true) {
// Wait for flushIntervalMs before flushing again
yield* _(Effect.sleep(Duration.millis(this.flushIntervalMs)));
// Atomically get and clear current operations
const currentOperations = new Map(this._bufferedOperations);
this._bufferedOperations.clear();
yield* Effect.sync(() => {
if (this.flushLoggingEnabled) {
logger.debug(`[UpdateMetadataService] Flushing operations`, {
operations: Object.fromEntries(currentOperations),
});
}
});
// If we have operations, process them
if (currentOperations.size > 0) {
yield* _(this._processBufferedOperations(currentOperations));
}
}
}).pipe(
// Handle any unexpected errors, ensuring program does not fail
Effect.catchAll((error) =>
Effect.sync(() => {
logger.error("Error in flushing program:", { error });
})
)
);
// Fork the program so it runs in the background
this._flushFiber = Effect.runFork(program as Effect.Effect<void, never, never>);
}
private _processBufferedOperations = (
operations: Map<string, BufferedRunMetadataChangeOperation[]>
) => {
return Effect.gen(this, function* (_) {
for (const [runId, ops] of operations) {
// Process and cull operations
const processedOps = this._cullOperations(ops);
// If there are no operations to process, skip
if (processedOps.length === 0) {
continue;
}
yield* Effect.sync(() => {
if (this.flushLoggingEnabled) {
logger.debug(`[UpdateMetadataService] Processing operations for run`, {
runId,
operationsCount: processedOps.length,
});
}
});
// Update run with retry
yield* _(
this._updateRunWithOperations(runId, processedOps).pipe(
Effect.retry(Schedule.exponential(Duration.millis(100), 1.4)),
Effect.catchAll((error) =>
Effect.sync(() => {
// On complete failure, return ops to buffer
const existingOps = this._bufferedOperations.get(runId) ?? [];
this._bufferedOperations.set(runId, [...existingOps, ...ops]);
console.error(`Failed to process run ${runId}:`, error);
})
)
)
);
}
});
};
private _updateRunWithOperations = (
runId: string,
operations: BufferedRunMetadataChangeOperation[]
) => {
return Effect.gen(this, function* (_) {
// Fetch current run
const run = yield* _(
Effect.tryPromise(() =>
this._prisma.taskRun.findFirst({
where: { id: runId },
select: { id: true, metadata: true, metadataType: true, metadataVersion: true },
})
)
);
if (!run) {
return yield* _(Effect.fail(new Error(`Run ${runId} not found`)));
}
const metadata = yield* _(
Effect.tryPromise(() =>
run.metadata
? parsePacket({ data: run.metadata, dataType: run.metadataType })
: Promise.resolve({})
)
);
// Apply operations and update
const applyResult = applyMetadataOperations(
metadata,
operations.map((op) => op.operation)
);
if (applyResult.unappliedOperations.length === operations.length) {
logger.warn(`No operations applied for run ${runId}`);
// If no operations were applied, return
return;
}
// Stringify the metadata
const newMetadataPacket = yield* _(
Effect.try(() => handleMetadataPacket(applyResult.newMetadata, run.metadataType))
);
if (!newMetadataPacket) {
// Log and skip if metadata is invalid
logger.warn(`Invalid metadata after operations, skipping update`);
return;
}
const result = yield* _(
Effect.tryPromise(() =>
this._prisma.taskRun.updateMany({
where: {
id: runId,
metadataVersion: run.metadataVersion,
},
data: {
metadata: newMetadataPacket.data,
metadataVersion: { increment: 1 },
},
})
)
);
if (result.count === 0) {
yield* Effect.sync(() => {
logger.warn(`Optimistic lock failed for run ${runId}`, {
metadataVersion: run.metadataVersion,
});
});
return yield* _(Effect.fail(new Error("Optimistic lock failed")));
}
return result;
});
};
private _cullOperations(
operations: BufferedRunMetadataChangeOperation[]
): BufferedRunMetadataChangeOperation[] {
// Sort by timestamp
const sortedOps = [...operations].sort((a, b) => a.timestamp - b.timestamp);
// Track latest set operations by key
const latestSetOps = new Map<string, BufferedRunMetadataChangeOperation>();
const resultOps: BufferedRunMetadataChangeOperation[] = [];
for (const op of sortedOps) {
if (op.operation.type === "set") {
latestSetOps.set(op.operation.key, op);
} else {
resultOps.push(op);
}
}
// Add winning set operations
resultOps.push(...latestSetOps.values());
return resultOps;
}
public async call(
runId: string,
body: UpdateMetadataRequestBody,
environment?: AuthenticatedEnvironment
) {
const runIdType = runId.startsWith("run_") ? "friendly" : "internal";
const taskRun = await this._prisma.taskRun.findFirst({
where: environment
? {
runtimeEnvironmentId: environment.id,
...(runIdType === "internal" ? { id: runId } : { friendlyId: runId }),
}
: {
...(runIdType === "internal" ? { id: runId } : { friendlyId: runId }),
},
select: {
id: true,
status: true,
metadata: true,
metadataType: true,
metadataVersion: true,
parentTaskRun: {
select: {
id: true,
status: true,
},
},
rootTaskRun: {
select: {
id: true,
status: true,
},
},
},
});
if (!taskRun) {
return;
}
if (isFinalRunStatus(taskRun.status)) {
throw new ServiceValidationError("Cannot update metadata for a completed run");
}
if (body.parentOperations && body.parentOperations.length > 0 && taskRun.parentTaskRun) {
this.#ingestRunOperations(taskRun.parentTaskRun.id, body.parentOperations);
}
if (body.rootOperations && body.rootOperations.length > 0 && taskRun.rootTaskRun) {
this.#ingestRunOperations(taskRun.rootTaskRun.id, body.rootOperations);
}
const newMetadata = await this.#updateRunMetadata({
runId: taskRun.id,
body,
existingMetadata: {
data: taskRun.metadata ?? undefined,
dataType: taskRun.metadataType,
},
});
return {
metadata: newMetadata,
};
}
async #updateRunMetadata({
runId,
body,
existingMetadata,
}: {
runId: string;
body: UpdateMetadataRequestBody;
existingMetadata: IOPacket;
}) {
if (Array.isArray(body.operations)) {
return this.#updateRunMetadataWithOperations(runId, body.operations);
} else {
return this.#updateRunMetadataDirectly(runId, body, existingMetadata);
}
}
async #updateRunMetadataWithOperations(runId: string, operations: RunMetadataChangeOperation[]) {
const MAX_RETRIES = 3;
let attempts = 0;
while (attempts <= MAX_RETRIES) {
// Fetch the latest run data
const run = await this._prisma.taskRun.findFirst({
where: { id: runId },
select: { metadata: true, metadataType: true, metadataVersion: true },
});
if (!run) {
throw new Error(`Run ${runId} not found`);
}
// Parse the current metadata
const currentMetadata = await (run.metadata
? parsePacket({ data: run.metadata, dataType: run.metadataType })
: Promise.resolve({}));
// Apply operations to the current metadata
const applyResults = applyMetadataOperations(currentMetadata, operations);
// If no operations were applied, return the current metadata
if (applyResults.unappliedOperations.length === operations.length) {
return currentMetadata;
}
// Update with optimistic locking
const result = await this._prisma.taskRun.updateMany({
where: {
id: runId,
metadataVersion: run.metadataVersion,
},
data: {
metadata: JSON.stringify(applyResults.newMetadata),
metadataType: run.metadataType,
metadataVersion: {
increment: 1,
},
},
});
if (result.count === 0) {
if (this.flushLoggingEnabled) {
logger.debug(
`[UpdateMetadataService][updateRunMetadataWithOperations] Optimistic lock failed for run ${runId}`,
{
metadataVersion: run.metadataVersion,
}
);
}
// If this was our last attempt, buffer the operations and return optimistically
if (attempts === MAX_RETRIES) {
this.#ingestRunOperations(runId, operations);
return applyResults.newMetadata;
}
// Otherwise sleep and try again
await setTimeout(100 * Math.pow(1.4, attempts));
attempts++;
continue;
}
if (this.flushLoggingEnabled) {
logger.debug(
`[UpdateMetadataService][updateRunMetadataWithOperations] Updated metadata for run ${runId}`,
{
metadata: applyResults.newMetadata,
operations: operations,
}
);
}
// Success! Return the new metadata
return applyResults.newMetadata;
}
}
async #updateRunMetadataDirectly(
runId: string,
body: UpdateMetadataRequestBody,
existingMetadata: IOPacket
) {
const metadataPacket = handleMetadataPacket(body.metadata, "application/json");
if (!metadataPacket) {
throw new ServiceValidationError("Invalid metadata");
}
if (
metadataPacket.data !== "{}" ||
(existingMetadata.data && metadataPacket.data !== existingMetadata.data)
) {
if (this.flushLoggingEnabled) {
logger.debug(
`[UpdateMetadataService][updateRunMetadataDirectly] Updating metadata directly for run`,
{
metadata: metadataPacket.data,
runId,
}
);
}
// Update the metadata without version check
await this._prisma.taskRun.update({
where: {
id: runId,
},
data: {
metadata: metadataPacket?.data,
metadataType: metadataPacket?.dataType,
metadataVersion: {
increment: 1,
},
},
});
}
const newMetadata = await parsePacket(metadataPacket);
return newMetadata;
}
#ingestRunOperations(runId: string, operations: RunMetadataChangeOperation[]) {
const bufferedOperations: BufferedRunMetadataChangeOperation[] = operations.map((operation) => {
return {
runId,
timestamp: Date.now(),
operation,
};
});
if (this.flushLoggingEnabled) {
logger.debug(`[UpdateMetadataService] Ingesting operations for run`, {
runId,
bufferedOperations,
});
}
const existingBufferedOperations = this._bufferedOperations.get(runId) ?? [];
this._bufferedOperations.set(runId, [...existingBufferedOperations, ...bufferedOperations]);
}
}
export const updateMetadataService = singleton(
"update-metadata-service",
() =>
new UpdateMetadataService(
prisma,
env.BATCH_METADATA_OPERATIONS_FLUSH_INTERVAL_MS,
env.BATCH_METADATA_OPERATIONS_FLUSH_ENABLED === "1",
env.BATCH_METADATA_OPERATIONS_FLUSH_LOGGING_ENABLED === "1"
)
);