-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathioSerialization.ts
More file actions
507 lines (425 loc) · 11.7 KB
/
ioSerialization.ts
File metadata and controls
507 lines (425 loc) · 11.7 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import { Attributes, Span } from "@opentelemetry/api";
import { OFFLOAD_IO_PACKET_LENGTH_LIMIT, imposeAttributeLimits } from "../limits.js";
import { SemanticInternalAttributes } from "../semanticInternalAttributes.js";
import { TriggerTracer } from "../tracer.js";
import { flattenAttributes } from "./flattenAttributes.js";
import { apiClientManager } from "../apiClientManager-api.js";
import { zodfetch } from "../zodfetch.js";
import { z } from "zod";
import type { RetryOptions } from "../schemas/index.js";
import { ApiClient } from "../apiClient/index.js";
export type IOPacket = {
data?: string | undefined;
dataType: string;
};
export type ParsePacketOptions = {
filteredKeys?: string[];
};
export async function parsePacket(value: IOPacket, options?: ParsePacketOptions): Promise<any> {
if (!value.data) {
return undefined;
}
switch (value.dataType) {
case "application/json":
return JSON.parse(value.data, makeSafeReviver(options));
case "application/super+json":
const { parse } = await loadSuperJSON();
return parse(value.data);
case "text/plain":
return value.data;
case "application/store":
throw new Error(
`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`
);
default:
return value.data;
}
}
export async function parsePacketAsJson(
value: IOPacket,
options?: ParsePacketOptions
): Promise<any> {
if (!value.data) {
return undefined;
}
switch (value.dataType) {
case "application/json":
return JSON.parse(value.data, makeSafeReviver(options));
case "application/super+json":
const { parse, serialize } = await loadSuperJSON();
const superJsonResult = parse(value.data);
const { json } = serialize(superJsonResult);
return json;
case "text/plain":
return value.data;
case "application/store":
throw new Error(
`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`
);
default:
return value.data;
}
}
export async function conditionallyImportAndParsePacket(
value: IOPacket,
client?: ApiClient
): Promise<any> {
const importedPacket = await conditionallyImportPacket(value, undefined, client);
return await parsePacket(importedPacket);
}
export async function stringifyIO(value: any): Promise<IOPacket> {
if (value === undefined) {
return { dataType: "application/json" };
}
if (typeof value === "string") {
return { data: value, dataType: "text/plain" };
}
try {
const { stringify } = await loadSuperJSON();
const data = stringify(value);
return { data, dataType: "application/super+json" };
} catch {
return { data: value, dataType: "application/json" };
}
}
export async function conditionallyExportPacket(
packet: IOPacket,
pathPrefix: string,
tracer?: TriggerTracer
): Promise<IOPacket> {
if (apiClientManager.client) {
const { needsOffloading, size } = packetRequiresOffloading(packet);
if (needsOffloading) {
if (!tracer) {
return await exportPacket(packet, pathPrefix);
} else {
const result = await tracer.startActiveSpan(
"store.uploadOutput",
async (span) => {
return await exportPacket(packet, pathPrefix);
},
{
attributes: {
byteLength: size,
[SemanticInternalAttributes.STYLE_ICON]: "cloud-upload",
},
}
);
return result ?? packet;
}
}
}
return packet;
}
export function packetRequiresOffloading(
packet: IOPacket,
lengthLimit?: number
): {
needsOffloading: boolean;
size: number;
} {
if (!packet.data) {
return {
needsOffloading: false,
size: 0,
};
}
const byteSize = Buffer.byteLength(packet.data, "utf8");
return {
needsOffloading: byteSize >= (lengthLimit ?? OFFLOAD_IO_PACKET_LENGTH_LIMIT),
size: byteSize,
};
}
const ioRetryOptions = {
minTimeoutInMs: 500,
maxTimeoutInMs: 5000,
maxAttempts: 5,
factor: 2,
randomize: true,
} satisfies RetryOptions;
async function exportPacket(packet: IOPacket, pathPrefix: string): Promise<IOPacket> {
// Offload the output
const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
const presignedResponse = await apiClientManager.client!.createUploadPayloadUrl(filename);
const uploadResponse = await zodfetch(
z.any(),
presignedResponse.presignedUrl,
{
method: "PUT",
headers: {
"Content-Type": packet.dataType,
},
body: packet.data,
},
{
retry: ioRetryOptions,
}
).asResponse();
if (!uploadResponse.ok) {
throw new Error(
`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`
);
}
return {
data: filename,
dataType: "application/store",
};
}
export async function conditionallyImportPacket(
packet: IOPacket,
tracer?: TriggerTracer,
client?: ApiClient
): Promise<IOPacket> {
if (packet.dataType !== "application/store") {
return packet;
}
if (!tracer) {
return await importPacket(packet, undefined, client);
} else {
const result = await tracer.startActiveSpan(
"store.downloadPayload",
async (span) => {
return await importPacket(packet, span, client);
},
{
attributes: {
[SemanticInternalAttributes.STYLE_ICON]: "cloud-download",
},
}
);
return result ?? packet;
}
}
export async function resolvePresignedPacketUrl(
url: string,
tracer?: TriggerTracer
): Promise<any | undefined> {
try {
const response = await fetch(url);
if (!response.ok) {
return;
}
const data = await response.text();
const dataType = response.headers.get("content-type") ?? "application/json";
const packet = {
data,
dataType,
};
return await parsePacket(packet);
} catch (error) {
return;
}
}
async function importPacket(packet: IOPacket, span?: Span, client?: ApiClient): Promise<IOPacket> {
if (!packet.data) {
return packet;
}
const $client = client ?? apiClientManager.client;
if (!$client) {
return packet;
}
const presignedResponse = await $client.getPayloadUrl(packet.data);
const response = await zodfetch(z.any(), presignedResponse.presignedUrl, undefined, {
retry: ioRetryOptions,
}).asResponse();
if (!response.ok) {
throw new Error(
`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`
);
}
const data = await response.text();
span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
return {
data,
dataType: response.headers.get("content-type") ?? "application/json",
};
}
export async function createPacketAttributes(
packet: IOPacket,
dataKey: string,
dataTypeKey: string
): Promise<Attributes | undefined> {
if (!packet.data) {
return;
}
switch (packet.dataType) {
case "application/json":
return {
...flattenAttributes(packet, dataKey),
[dataTypeKey]: packet.dataType,
};
case "application/super+json":
const { parse } = await loadSuperJSON();
if (typeof packet.data === "undefined" || packet.data === null) {
return;
}
try {
const parsed = parse(packet.data) as any;
const jsonified = JSON.parse(JSON.stringify(parsed, makeSafeReplacer()));
const result = {
...flattenAttributes(jsonified, dataKey),
[dataTypeKey]: "application/json",
};
return result;
} catch (e) {
return;
}
case "application/store":
return {
[dataKey]: packet.data,
[dataTypeKey]: packet.dataType,
};
case "text/plain":
return {
[dataKey]: packet.data,
[dataTypeKey]: packet.dataType,
};
default:
return;
}
}
export async function createPacketAttributesAsJson(
data: any,
dataType: string
): Promise<Attributes> {
if (
typeof data === "string" ||
typeof data === "number" ||
typeof data === "boolean" ||
data === null ||
data === undefined
) {
return data;
}
switch (dataType) {
case "application/json":
return imposeAttributeLimits(flattenAttributes(data, undefined));
case "application/super+json":
const { deserialize } = await loadSuperJSON();
const deserialized = deserialize(data) as any;
const jsonify = safeJsonParse(JSON.stringify(deserialized, makeSafeReplacer()));
return imposeAttributeLimits(flattenAttributes(jsonify, undefined));
case "application/store":
return data;
default:
return {};
}
}
export async function prettyPrintPacket(
rawData: any,
dataType?: string,
options?: ReplacerOptions
): Promise<string> {
if (rawData === undefined) {
return "";
}
if (dataType === "application/super+json") {
if (typeof rawData === "string") {
rawData = safeJsonParse(rawData);
}
const { deserialize } = await loadSuperJSON();
return await prettyPrintPacket(deserialize(rawData), "application/json");
}
if (dataType === "application/json") {
if (typeof rawData === "string") {
rawData = safeJsonParse(rawData);
}
return JSON.stringify(rawData, makeSafeReplacer(options), 2);
}
if (typeof rawData === "string") {
return rawData;
}
return JSON.stringify(rawData, makeSafeReplacer(options), 2);
}
interface ReplacerOptions {
filteredKeys?: string[];
}
function makeSafeReplacer(options?: ReplacerOptions) {
const seen = new WeakSet<any>();
return function replacer(key: string, value: any) {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
// Check if the key should be filtered out
if (options?.filteredKeys?.includes(key)) {
return undefined;
}
// If it is a BigInt
if (typeof value === "bigint") {
return value.toString();
}
// if it is a Regex
if (value instanceof RegExp) {
return value.toString();
}
// if it is a Set
if (value instanceof Set) {
return Array.from(value);
}
// if it is a Map, convert it to an object
if (value instanceof Map) {
const obj: Record<string, any> = {};
value.forEach((v, k) => {
obj[k] = v;
});
return obj;
}
return value;
};
}
function makeSafeReviver(options?: ReplacerOptions) {
if (!options) {
return undefined;
}
return function reviver(key: string, value: any) {
// Check if the key should be filtered out
if (options?.filteredKeys?.includes(key)) {
return undefined;
}
return value;
};
}
function getPacketExtension(outputType: string): string {
switch (outputType) {
case "application/json":
return "json";
case "application/super+json":
return "json";
case "text/plain":
return "txt";
default:
return "txt";
}
}
async function loadSuperJSON() {
const superjson = await import("superjson");
superjson.registerCustom<Buffer, number[]>(
{
isApplicable: (v): v is Buffer => typeof Buffer === "function" && Buffer.isBuffer(v),
serialize: (v) => [...v],
deserialize: (v) => Buffer.from(v),
},
"buffer"
);
return superjson;
}
function safeJsonParse(value: string): any {
try {
return JSON.parse(value);
} catch {
return;
}
}
export async function replaceSuperJsonPayload(original: string, newPayload: string) {
const superjson = await loadSuperJSON();
const originalObject = superjson.parse(original);
const { meta } = superjson.serialize(originalObject);
const newSuperJson = {
json: JSON.parse(newPayload) as any,
meta,
};
return superjson.deserialize(newSuperJson);
}