-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathflattenAttributes.ts
More file actions
385 lines (324 loc) · 10.6 KB
/
flattenAttributes.ts
File metadata and controls
385 lines (324 loc) · 10.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
import { Attributes } from "@opentelemetry/api";
export const NULL_SENTINEL = "$@null((";
export const CIRCULAR_REFERENCE_SENTINEL = "$@circular((";
const DEFAULT_MAX_DEPTH = 128;
export function flattenAttributes(
obj: unknown,
prefix?: string,
maxAttributeCount?: number,
maxDepth: number = DEFAULT_MAX_DEPTH
): Attributes {
const flattener = new AttributeFlattener(maxAttributeCount, maxDepth);
flattener.doFlatten(obj, prefix, 0);
return flattener.attributes;
}
class AttributeFlattener {
private seen: WeakSet<object> = new WeakSet();
private attributeCounter: number = 0;
private result: Attributes = {};
constructor(
private maxAttributeCount?: number,
private maxDepth: number = DEFAULT_MAX_DEPTH
) {}
get attributes(): Attributes {
return this.result;
}
private canAddMoreAttributes(): boolean {
return this.maxAttributeCount === undefined || this.attributeCounter < this.maxAttributeCount;
}
private addAttribute(key: string, value: any): boolean {
if (!this.canAddMoreAttributes()) {
return false;
}
this.result[key] = value;
this.attributeCounter++;
return true;
}
doFlatten(obj: unknown, prefix?: string, depth: number = 0) {
if (!this.canAddMoreAttributes()) {
return;
}
// Check depth limit to prevent stack overflow
if (depth > this.maxDepth) {
return;
}
// Check if obj is null or undefined
if (obj === undefined) {
return;
}
if (obj === null) {
this.addAttribute(prefix || "", NULL_SENTINEL);
return;
}
if (typeof obj === "string") {
this.addAttribute(prefix || "", obj);
return;
}
if (typeof obj === "number") {
this.addAttribute(prefix || "", obj);
return;
}
if (typeof obj === "boolean") {
this.addAttribute(prefix || "", obj);
return;
}
if (obj instanceof Date) {
this.addAttribute(prefix || "", obj.toISOString());
return;
}
// Handle Error objects
if (obj instanceof Error) {
this.addAttribute(`${prefix || "error"}.name`, obj.name);
this.addAttribute(`${prefix || "error"}.message`, obj.message);
if (obj.stack) {
this.addAttribute(`${prefix || "error"}.stack`, obj.stack);
}
return;
}
// Handle functions
if (typeof obj === "function") {
const funcName = obj.name || "anonymous";
this.addAttribute(prefix || "", `[Function: ${funcName}]`);
return;
}
// Handle Set objects
if (obj instanceof Set) {
let index = 0;
for (const item of obj) {
if (!this.canAddMoreAttributes()) break;
this.#processValue(item, `${prefix || "set"}.[${index}]`, depth);
index++;
}
return;
}
// Handle Map objects
if (obj instanceof Map) {
for (const [key, value] of obj) {
if (!this.canAddMoreAttributes()) break;
// Use the key directly if it's a string, otherwise convert it
const keyStr = typeof key === "string" ? key : String(key);
this.#processValue(value, `${prefix || "map"}.${keyStr}`, depth);
}
return;
}
// Handle File objects
if (typeof File !== "undefined" && obj instanceof File) {
this.addAttribute(`${prefix || "file"}.name`, obj.name);
this.addAttribute(`${prefix || "file"}.size`, obj.size);
this.addAttribute(`${prefix || "file"}.type`, obj.type);
this.addAttribute(`${prefix || "file"}.lastModified`, obj.lastModified);
return;
}
// Handle ReadableStream objects
if (typeof ReadableStream !== "undefined" && obj instanceof ReadableStream) {
this.addAttribute(`${prefix || "stream"}.type`, "ReadableStream");
this.addAttribute(`${prefix || "stream"}.locked`, obj.locked);
return;
}
// Handle WritableStream objects
if (typeof WritableStream !== "undefined" && obj instanceof WritableStream) {
this.addAttribute(`${prefix || "stream"}.type`, "WritableStream");
this.addAttribute(`${prefix || "stream"}.locked`, obj.locked);
return;
}
// Handle Promise objects
if (obj instanceof Promise) {
this.addAttribute(prefix || "promise", "[Promise object]");
// We can't inspect promise state synchronously, so just indicate it's a promise
return;
}
// Handle RegExp objects
if (obj instanceof RegExp) {
this.addAttribute(`${prefix || "regexp"}.source`, obj.source);
this.addAttribute(`${prefix || "regexp"}.flags`, obj.flags);
return;
}
// Handle URL objects
if (typeof URL !== "undefined" && obj instanceof URL) {
this.addAttribute(`${prefix || "url"}.href`, obj.href);
this.addAttribute(`${prefix || "url"}.protocol`, obj.protocol);
this.addAttribute(`${prefix || "url"}.host`, obj.host);
this.addAttribute(`${prefix || "url"}.pathname`, obj.pathname);
return;
}
// Handle ArrayBuffer and TypedArrays
if (obj instanceof ArrayBuffer) {
this.addAttribute(`${prefix || "arraybuffer"}.byteLength`, obj.byteLength);
return;
}
// Handle TypedArrays (Uint8Array, Int32Array, etc.)
if (ArrayBuffer.isView(obj)) {
const typedArray = obj as any;
this.addAttribute(`${prefix || "typedarray"}.constructor`, typedArray.constructor.name);
this.addAttribute(`${prefix || "typedarray"}.length`, typedArray.length);
this.addAttribute(`${prefix || "typedarray"}.byteLength`, typedArray.byteLength);
this.addAttribute(`${prefix || "typedarray"}.byteOffset`, typedArray.byteOffset);
return;
}
// Check for circular reference
if (obj !== null && typeof obj === "object" && this.seen.has(obj)) {
this.addAttribute(prefix || "", CIRCULAR_REFERENCE_SENTINEL);
return;
}
// Add object to seen set
if (obj !== null && typeof obj === "object") {
this.seen.add(obj);
}
for (const [key, value] of Object.entries(obj)) {
if (!this.canAddMoreAttributes()) {
break;
}
const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
if (!this.canAddMoreAttributes()) {
break;
}
this.#processValue(value[i], `${newPrefix}.[${i}]`, depth);
}
} else {
this.#processValue(value, newPrefix, depth);
}
}
}
#processValue(value: unknown, prefix: string, depth: number) {
if (!this.canAddMoreAttributes()) {
return;
}
if (value === undefined) {
return;
}
// Handle primitive values directly
if (value === null) {
this.addAttribute(prefix, NULL_SENTINEL);
return;
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
this.addAttribute(prefix, value);
return;
}
// Handle non-primitive values by recursing (increment depth)
if (typeof value === "object" || typeof value === "function") {
this.doFlatten(value as any, prefix, depth + 1);
} else {
// Convert other types to strings (bigint, symbol, etc.)
this.addAttribute(prefix, String(value));
}
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
export function unflattenAttributes(
obj: Attributes,
filteredKeys?: string[],
maxDepth: number = DEFAULT_MAX_DEPTH
): Record<string, unknown> | string | number | boolean | null | undefined {
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
return obj;
}
if (
typeof obj === "object" &&
obj !== null &&
Object.keys(obj).length === 1 &&
Object.keys(obj)[0] === ""
) {
return rehydrateNull(obj[""]) as any;
}
if (Object.keys(obj).length === 0) {
return;
}
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
if (filteredKeys?.includes(key)) {
continue;
}
const parts = key.split(".").reduce(
(acc, part) => {
if (part.startsWith("[") && part.endsWith("]")) {
// Handle array indices more precisely
const match = part.match(/^\[(\d+)\]$/);
if (match && match[1]) {
acc.push(parseInt(match[1]));
} else {
// Remove brackets for non-numeric array keys
acc.push(part.slice(1, -1));
}
} else {
acc.push(part);
}
return acc;
},
[] as (string | number)[]
);
// Skip keys that exceed max depth to prevent memory exhaustion
if (parts.length > maxDepth) {
continue;
}
let current: any = result;
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
const nextPart = parts[i + 1];
if (!part && part !== 0) {
continue;
}
if (typeof nextPart === "number") {
// Ensure we create an array for numeric indices
current[part] = Array.isArray(current[part]) ? current[part] : [];
} else if (current[part] === undefined) {
// Create an object for non-numeric paths
current[part] = {};
}
current = current[part];
}
const lastPart = parts[parts.length - 1];
if (lastPart !== undefined) {
current[lastPart] = rehydrateNull(rehydrateCircular(value));
}
}
// Convert the result to an array if all top-level keys are numeric indices
if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
const arrayResult = Array(maxIndex + 1);
for (const key in result) {
arrayResult[parseInt(key)] = result[key];
}
return arrayResult as any;
}
return result;
}
function rehydrateCircular(value: any): any {
if (value === CIRCULAR_REFERENCE_SENTINEL) {
return "[Circular Reference]";
}
return value;
}
export function primitiveValueOrflattenedAttributes(
obj: Record<string, unknown> | Array<unknown> | string | boolean | number | undefined,
prefix: string | undefined
): Attributes | string | number | boolean | undefined {
if (
typeof obj === "string" ||
typeof obj === "number" ||
typeof obj === "boolean" ||
obj === null ||
obj === undefined
) {
return obj;
}
const attributes = flattenAttributes(obj, prefix);
if (
prefix !== undefined &&
typeof attributes[prefix] !== "undefined" &&
attributes[prefix] !== null
) {
return attributes[prefix] as unknown as Attributes;
}
return attributes;
}
function rehydrateNull(value: any): any {
if (value === NULL_SENTINEL) {
return null;
}
return value;
}