-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathformatters.ts
More file actions
429 lines (346 loc) · 11.5 KB
/
formatters.ts
File metadata and controls
429 lines (346 loc) · 11.5 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
import { AnyRunShape } from "@trigger.dev/core/v3";
import {
ListRunResponseItem,
RetrieveRunResponse,
RetrieveRunTraceResponseBody,
} from "@trigger.dev/core/v3/schemas";
import type { CursorPageResponse } from "@trigger.dev/core/v3/zodfetch";
const DEFAULT_MAX_TRACE_LINES = 500;
export function formatRun(run: RetrieveRunResponse): string {
const lines: string[] = [];
// Header with basic info
lines.push(`Run ${run.id}`);
lines.push(`Task: ${run.taskIdentifier}`);
lines.push(`Status: ${formatStatus(run.status)}`);
// Timing information
const timing = formatTiming(run);
if (timing) {
lines.push(`Timing: ${timing}`);
}
// Duration and cost
if (run.durationMs > 0) {
lines.push(`Duration: ${formatDuration(run.durationMs)}`);
}
if (run.costInCents > 0) {
lines.push(`Cost: $${(run.costInCents / 100).toFixed(4)}`);
}
// Attempt count
if (run.attemptCount > 1) {
lines.push(`Attempts: ${run.attemptCount}`);
}
// Version and trigger info
if (run.version) {
lines.push(`Version: ${run.version}`);
}
// Tags
if (run.tags && run.tags.length > 0) {
lines.push(`Tags: ${run.tags.join(", ")}`);
}
// Error information
if (run.error) {
lines.push(`Error: ${run.error.name || "Error"}: ${run.error.message}`);
if (run.error.stackTrace) {
lines.push(`Stack: ${run.error.stackTrace.split("\n")[0]}`); // First line only
}
}
// Related runs
const relatedInfo = formatRelatedRuns(run.relatedRuns);
if (relatedInfo) {
lines.push(relatedInfo);
}
// Schedule info
if (run.schedule) {
lines.push(`Schedule: ${run.schedule.generator.expression} (${run.schedule.id})`);
}
// Batch info
if (run.batchId) {
lines.push(`Batch: ${run.batchId}`);
}
// Test flag
if (run.isTest) {
lines.push(`Test run`);
}
// TTL info
if (run.ttl) {
lines.push(`TTL: ${run.ttl}`);
}
// Payload and Output data
if (run.payload) {
lines.push(`Payload: ${JSON.stringify(run.payload, null, 2)}`);
} else if (run.payloadPresignedUrl) {
lines.push(`Payload: (large payload available via presigned URL: ${run.payloadPresignedUrl})`);
}
if (run.output) {
lines.push(`Output: ${JSON.stringify(run.output, null, 2)}`);
} else if (run.outputPresignedUrl) {
lines.push(`Output: (large output available via presigned URL: ${run.outputPresignedUrl})`);
}
// Metadata
if (run.metadata && Object.keys(run.metadata).length > 0) {
lines.push(`Metadata: ${Object.keys(run.metadata).length} fields`);
}
return lines.join("\n");
}
export function formatRunShape(run: AnyRunShape): string {
const lines: string[] = [];
lines.push(`Run ${run.id}`);
lines.push(`Task: ${run.taskIdentifier}`);
lines.push(`Status: ${formatStatus(run.status)}`);
if (run.output) {
lines.push(`Output: ${JSON.stringify(run.output, null, 2)}`);
}
if (run.error) {
lines.push(`Error: ${run.error.name || "Error"}: ${run.error.message}`);
}
if (run.metadata) {
lines.push(`Metadata: ${JSON.stringify(run.metadata, null, 2)}`);
}
lines.push(`Created at: ${formatDateTime(run.createdAt)}`);
if (run.finishedAt) {
lines.push(`Finished at: ${formatDateTime(run.finishedAt)}`);
}
return lines.join("\n");
}
function formatStatus(status: string): string {
return status.toLowerCase().replace(/_/g, " ");
}
function formatTiming(run: RetrieveRunResponse): string | null {
const parts: string[] = [];
parts.push(`created ${formatDateTime(run.createdAt)}`);
if (run.startedAt) {
parts.push(`started ${formatDateTime(run.startedAt)}`);
}
if (run.finishedAt) {
parts.push(`finished ${formatDateTime(run.finishedAt)}`);
} else if (run.delayedUntil) {
parts.push(`delayed until ${formatDateTime(run.delayedUntil)}`);
}
return parts.length > 0 ? parts.join(", ") : null;
}
function formatDateTime(date: Date | undefined): string {
if (!date) return "unknown";
try {
return date
.toISOString()
.replace("T", " ")
.replace(/\.\d{3}Z$/, " UTC");
} catch {
return "unknown";
}
}
function formatDuration(durationMs: number): string {
if (durationMs < 1000) return `${durationMs}ms`;
if (durationMs < 60000) return `${(durationMs / 1000).toFixed(1)}s`;
if (durationMs < 3600000) return `${(durationMs / 60000).toFixed(1)}m`;
return `${(durationMs / 3600000).toFixed(1)}h`;
}
function formatRelatedRuns(relatedRuns: RetrieveRunResponse["relatedRuns"]): string | null {
const parts: string[] = [];
if (relatedRuns.parent) {
parts.push(`parent: ${relatedRuns.parent.id} (${relatedRuns.parent.status.toLowerCase()})`);
}
if (relatedRuns.root && relatedRuns.root.id !== relatedRuns.parent?.id) {
parts.push(`root: ${relatedRuns.root.id} (${relatedRuns.root.status.toLowerCase()})`);
}
if (relatedRuns.children && relatedRuns.children.length > 0) {
const childStatuses = relatedRuns.children.reduce(
(acc, child) => {
acc[child.status.toLowerCase()] = (acc[child.status.toLowerCase()] || 0) + 1;
return acc;
},
{} as Record<string, number>
);
const statusSummary = Object.entries(childStatuses)
.map(([status, count]) => `${count} ${status}`)
.join(", ");
parts.push(`children: ${relatedRuns.children.length} runs (${statusSummary})`);
}
return parts.length > 0 ? `Related: ${parts.join("; ")}` : null;
}
export function formatRunTrace(
trace: RetrieveRunTraceResponseBody["trace"],
maxTraceLines: number = DEFAULT_MAX_TRACE_LINES
): string {
const lines: string[] = [];
lines.push(`Trace ID: ${trace.traceId}`);
lines.push("");
// Format the root span and its children recursively
const reachedMaxLines = formatSpan(trace.rootSpan, lines, 0, maxTraceLines);
if (reachedMaxLines) {
lines.push(`(truncated logs to ${maxTraceLines} lines)`);
}
return lines.join("\n");
}
function formatSpan(
span: RetrieveRunTraceResponseBody["trace"]["rootSpan"],
lines: string[],
depth: number,
maxLines: number
): boolean {
if (lines.length >= maxLines) {
return true;
}
const indent = " ".repeat(depth);
const prefix = depth === 0 ? "└─" : "├─";
// Format span header
const statusIndicator = getStatusIndicator(span.data);
const duration = formatDuration(span.data.duration);
const startTime = formatDateTime(span.data.startTime);
lines.push(`${indent}${prefix} ${span.data.message} ${statusIndicator}`);
lines.push(`${indent} Duration: ${duration}`);
lines.push(`${indent} Started: ${startTime}`);
if (span.data.taskSlug) {
lines.push(`${indent} Task: ${span.data.taskSlug}`);
}
if (span.data.taskPath) {
lines.push(`${indent} Path: ${span.data.taskPath}`);
}
if (span.data.queueName) {
lines.push(`${indent} Queue: ${span.data.queueName}`);
}
if (span.data.machinePreset) {
lines.push(`${indent} Machine: ${span.data.machinePreset}`);
}
if (span.data.workerVersion) {
lines.push(`${indent} Worker: ${span.data.workerVersion}`);
}
// Show properties if they exist
if (span.data.properties && Object.keys(span.data.properties).length > 0) {
lines.push(
`${indent} Properties: ${JSON.stringify(span.data.properties, null, 2).replace(
/\n/g,
"\n" + indent + " "
)}`
);
}
// Show output if it exists
if (span.data.output) {
lines.push(
`${indent} Output: ${JSON.stringify(span.data.output, null, 2).replace(
/\n/g,
"\n" + indent + " "
)}`
);
}
// Show events if they exist and are meaningful
if (span.data.events && span.data.events.length > 0) {
lines.push(`${indent} Events: ${span.data.events.length} events`);
// Optionally show first few events for context
const maxEvents = 3;
for (let i = 0; i < Math.min(span.data.events.length, maxEvents); i++) {
const event = span.data.events[i];
if (typeof event === "object" && event !== null) {
const eventStr = JSON.stringify(event, null, 2).replace(/\n/g, "\n" + indent + " ");
lines.push(`${indent} [${i + 1}] ${eventStr}`);
}
}
if (span.data.events.length > maxEvents) {
lines.push(`${indent} ... and ${span.data.events.length - maxEvents} more events`);
}
}
// Add spacing between spans
if (span.children && span.children.length > 0) {
lines.push("");
}
// Recursively format children
if (span.children) {
const reachedMaxLines = span.children.some((child, index) => {
const reachedMaxLines = formatSpan(child, lines, depth + 1, maxLines);
// Add spacing between sibling spans (except for the last one)
if (index < span.children.length - 1 && !reachedMaxLines) {
lines.push("");
}
return reachedMaxLines;
});
return reachedMaxLines;
}
return false;
}
function getStatusIndicator(
spanData: RetrieveRunTraceResponseBody["trace"]["rootSpan"]["data"]
): string {
if (spanData.isCancelled) return "[CANCELLED]";
if (spanData.isError) return "[ERROR]";
if (spanData.isPartial) return "[PARTIAL]";
return "[COMPLETED]";
}
export function formatRunList(runsPage: CursorPageResponse<ListRunResponseItem>): string {
const lines: string[] = [];
// Header with count info
const totalRuns = runsPage.data.length;
lines.push(`Found ${totalRuns} run${totalRuns === 1 ? "" : "s"}`);
lines.push("");
if (totalRuns === 0) {
lines.push("No runs found.");
return lines.join("\n");
}
// Format each run in a compact table-like format
runsPage.data.forEach((run, index) => {
lines.push(`${index + 1}. ${formatRunSummary(run)}`);
});
// Pagination info
lines.push("");
const paginationInfo = [];
if (runsPage.pagination.previous) {
paginationInfo.push("← Previous page available");
}
if (runsPage.pagination.next) {
paginationInfo.push("Next page available →");
}
if (paginationInfo.length > 0) {
lines.push(`Pagination: ${paginationInfo.join(" | ")}`);
if (runsPage.pagination.next) {
lines.push(`Next cursor: ${runsPage.pagination.next}`);
}
if (runsPage.pagination.previous) {
lines.push(`Previous cursor: ${runsPage.pagination.previous}`);
}
}
return lines.join("\n");
}
function formatRunSummary(run: ListRunResponseItem): string {
const parts: string[] = [];
// Basic info: ID, task, status
parts.push(`${run.id}`);
parts.push(`${run.taskIdentifier}`);
parts.push(`${formatStatus(run.status)}`);
// Environment
parts.push(`env:${run.env.name}`);
// Timing - show the most relevant time
let timeInfo = "";
if (run.finishedAt) {
timeInfo = `finished ${formatDateTime(run.finishedAt)}`;
} else if (run.startedAt) {
timeInfo = `started ${formatDateTime(run.startedAt)}`;
} else if (run.delayedUntil) {
timeInfo = `delayed until ${formatDateTime(run.delayedUntil)}`;
} else {
timeInfo = `created ${formatDateTime(run.createdAt)}`;
}
parts.push(timeInfo);
// Duration if available
if (run.durationMs > 0) {
parts.push(`took ${formatDuration(run.durationMs)}`);
}
// Cost if significant
if (run.costInCents > 0) {
parts.push(`$${(run.costInCents / 100).toFixed(4)}`);
}
// Tags if present
if (run.tags && run.tags.length > 0) {
const tagStr =
run.tags.length > 2
? `${run.tags.slice(0, 2).join(", ")}+${run.tags.length - 2}`
: run.tags.join(", ");
parts.push(`tags:[${tagStr}]`);
}
// Test flag
if (run.isTest) {
parts.push("[TEST]");
}
// Version if available
if (run.version) {
parts.push(`v${run.version}`);
}
return parts.join(" | ");
}