pi-cloudflare-agent-tracing 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,225 +0,0 @@
1
- export type AttributeValue =
2
- | string
3
- | number
4
- | boolean
5
- | readonly string[]
6
- | readonly number[]
7
- | readonly boolean[];
8
-
9
- export interface SpanAttributes {
10
- [name: string]: AttributeValue | undefined;
11
- }
12
-
13
- export type TelemetryStatus =
14
- | { status: "ok" }
15
- | { status: "error"; error?: { name: string; message: string } };
16
-
17
- export interface TelemetryLink {
18
- context: TelemetryContext;
19
- attributes?: SpanAttributes;
20
- }
21
-
22
- export interface TelemetryContext {
23
- startSpan<T>(
24
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
25
- callback: (span: TelemetrySpan) => T | Promise<T>,
26
- ): Promise<T>;
27
- }
28
-
29
- export interface TelemetrySpan extends TelemetryContext {
30
- addLink(link: TelemetryLink): void;
31
- addEvent(name: string, attributes?: SpanAttributes): void;
32
- setAttributes(attributes: SpanAttributes): void;
33
- setStatus(status: TelemetryStatus): void;
34
- }
35
-
36
- export interface CloudflareSpan {
37
- setAttribute(key: string, value: string | number | boolean): this;
38
- setAttributes(
39
- attributes: Record<string, string | number | boolean | undefined>,
40
- ): this;
41
- setStatus(status: { code: "unset" | "ok" | "error"; message?: string }): this;
42
- spanContext(): { traceId: string; spanId: string; traceFlags: number };
43
- }
44
-
45
- export interface CloudflareTracing {
46
- enterSpan<T>(name: string, callback: (span: CloudflareSpan) => T): T;
47
- }
48
-
49
- export interface CloudflareTelemetryOptions {
50
- /** Error messages can contain user/provider content and are redacted by default. */
51
- includeErrorMessages?: boolean;
52
- /** Events are encoded as bounded attributes because Workers custom spans have no event API. */
53
- maxEventsPerSpan?: number;
54
- maxLinksPerSpan?: number;
55
- }
56
-
57
- const DEFAULT_MAX_EVENTS = 32;
58
- const DEFAULT_MAX_LINKS = 16;
59
- const MAX_ERROR_MESSAGE = 500;
60
-
61
- export function createCloudflareTelemetryContext(
62
- tracing: CloudflareTracing,
63
- options: CloudflareTelemetryOptions = {},
64
- ): TelemetryContext {
65
- return new CloudflareTelemetryContext(tracing, {
66
- includeErrorMessages: options.includeErrorMessages ?? false,
67
- maxEventsPerSpan: options.maxEventsPerSpan ?? DEFAULT_MAX_EVENTS,
68
- maxLinksPerSpan: options.maxLinksPerSpan ?? DEFAULT_MAX_LINKS,
69
- });
70
- }
71
-
72
- interface ResolvedOptions {
73
- includeErrorMessages: boolean;
74
- maxEventsPerSpan: number;
75
- maxLinksPerSpan: number;
76
- }
77
-
78
- class CloudflareTelemetryContext implements TelemetryContext {
79
- private readonly tracing: CloudflareTracing;
80
- private readonly options: ResolvedOptions;
81
-
82
- constructor(tracing: CloudflareTracing, options: ResolvedOptions) {
83
- this.tracing = tracing;
84
- this.options = options;
85
- }
86
-
87
- async startSpan<T>(
88
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
89
- callback: (span: TelemetrySpan) => T | Promise<T>,
90
- ): Promise<T> {
91
- return await this.tracing.enterSpan(options.name, (nativeSpan) => {
92
- const span = new CloudflareTelemetrySpan(this.tracing, nativeSpan, this.options);
93
- if (options.attributes) span.setAttributes(options.attributes);
94
- for (const link of options.links ?? []) span.addLink(link);
95
-
96
- let result: T | Promise<T>;
97
- try {
98
- result = callback(span);
99
- } catch (error) {
100
- span.finishError(error);
101
- return Promise.reject(error);
102
- }
103
-
104
- return Promise.resolve(result).then(
105
- (value) => {
106
- span.finishSuccess();
107
- return value;
108
- },
109
- (error: unknown) => {
110
- span.finishError(error);
111
- throw error;
112
- },
113
- );
114
- });
115
- }
116
- }
117
-
118
- class CloudflareTelemetrySpan implements TelemetrySpan {
119
- private settled = false;
120
- private explicitStatus = false;
121
- private eventCount = 0;
122
- private linkCount = 0;
123
- private readonly tracing: CloudflareTracing;
124
- private readonly nativeSpan: CloudflareSpan;
125
- private readonly options: ResolvedOptions;
126
-
127
- constructor(
128
- tracing: CloudflareTracing,
129
- nativeSpan: CloudflareSpan,
130
- options: ResolvedOptions,
131
- ) {
132
- this.tracing = tracing;
133
- this.nativeSpan = nativeSpan;
134
- this.options = options;
135
- }
136
-
137
- startSpan<T>(
138
- options: { name: string; attributes?: SpanAttributes; links?: readonly TelemetryLink[] },
139
- callback: (span: TelemetrySpan) => T | Promise<T>,
140
- ): Promise<T> {
141
- return new CloudflareTelemetryContext(this.tracing, this.options).startSpan(options, callback);
142
- }
143
-
144
- addLink(link: TelemetryLink): void {
145
- if (this.settled || this.linkCount >= this.options.maxLinksPerSpan) return;
146
- if (!(link.context instanceof CloudflareTelemetrySpan)) return;
147
-
148
- const index = this.linkCount++;
149
- const context = link.context.nativeSpan.spanContext();
150
- this.nativeSpan.setAttributes({
151
- [`link.${index}.trace_id`]: context.traceId,
152
- [`link.${index}.span_id`]: context.spanId,
153
- ...prefixAttributes(`link.${index}.attribute.`, link.attributes),
154
- });
155
- }
156
-
157
- addEvent(name: string, attributes?: SpanAttributes): void {
158
- if (this.settled || this.eventCount >= this.options.maxEventsPerSpan) return;
159
- const index = this.eventCount++;
160
- this.nativeSpan.setAttributes({
161
- [`event.${index}.name`]: name,
162
- ...prefixAttributes(`event.${index}.attribute.`, attributes),
163
- });
164
- }
165
-
166
- setAttributes(attributes: SpanAttributes): void {
167
- if (this.settled) return;
168
- this.nativeSpan.setAttributes(normalizeAttributes(attributes));
169
- }
170
-
171
- setStatus(status: TelemetryStatus): void {
172
- if (this.settled) return;
173
- this.explicitStatus = true;
174
- if (status.status === "ok") {
175
- this.nativeSpan.setStatus({ code: "ok" });
176
- return;
177
- }
178
-
179
- const message = this.options.includeErrorMessages
180
- ? status.error?.message.slice(0, MAX_ERROR_MESSAGE)
181
- : undefined;
182
- this.nativeSpan.setAttributes({ "error.name": status.error?.name });
183
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
184
- }
185
-
186
- finishSuccess(): void {
187
- if (this.settled) return;
188
- if (!this.explicitStatus) this.nativeSpan.setStatus({ code: "ok" });
189
- this.settled = true;
190
- }
191
-
192
- finishError(error: unknown): void {
193
- if (this.settled) return;
194
- const name = error instanceof Error ? error.name : "UnknownError";
195
- const message =
196
- this.options.includeErrorMessages && error instanceof Error
197
- ? error.message.slice(0, MAX_ERROR_MESSAGE)
198
- : undefined;
199
- this.nativeSpan.setAttributes({ "error.name": name });
200
- this.nativeSpan.setStatus({ code: "error", ...(message ? { message } : {}) });
201
- this.settled = true;
202
- }
203
- }
204
-
205
- function normalizeAttributes(
206
- attributes: SpanAttributes | undefined,
207
- ): Record<string, string | number | boolean | undefined> {
208
- const normalized: Record<string, string | number | boolean | undefined> = {};
209
- for (const [name, value] of Object.entries(attributes ?? {})) {
210
- normalized[name] =
211
- value !== undefined && typeof value === "object" ? JSON.stringify(value) : value;
212
- }
213
- return normalized;
214
- }
215
-
216
- function prefixAttributes(
217
- prefix: string,
218
- attributes: SpanAttributes | undefined,
219
- ): Record<string, string | number | boolean | undefined> {
220
- const prefixed: Record<string, string | number | boolean | undefined> = {};
221
- for (const [name, value] of Object.entries(normalizeAttributes(attributes))) {
222
- prefixed[`${prefix}${name}`] = value;
223
- }
224
- return prefixed;
225
- }