@lunora/server 1.0.0-alpha.32 → 1.0.0-alpha.33

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.
@@ -0,0 +1,543 @@
1
+ import { SpanHandle, LunoraTracer } from "./types.mjs";
2
+ import '@lunora/values';
3
+ /**
4
+ * @since 1.0.0
5
+ */
6
+ interface Context {
7
+ /**
8
+ * Get a value from the context.
9
+ *
10
+ * @param key key which identifies a context value
11
+ */
12
+ getValue(key: symbol): unknown;
13
+ /**
14
+ * Create a new context which inherits from this context and has
15
+ * the given key set to the given value.
16
+ *
17
+ * @param key context key for which to set the value
18
+ * @param value value to set for the given key
19
+ */
20
+ setValue(key: symbol, value: unknown): Context;
21
+ /**
22
+ * Return a new context which inherits from this context but does
23
+ * not contain a value for the given key.
24
+ *
25
+ * @param key context key for which to clear a value
26
+ */
27
+ deleteValue(key: symbol): Context;
28
+ }
29
+ /**
30
+ * Attributes is a map from string to attribute values.
31
+ *
32
+ * Note: only the own enumerable keys are counted as valid attribute keys.
33
+ *
34
+ * @since 1.3.0
35
+ */
36
+ interface Attributes {
37
+ [attributeKey: string]: AttributeValue | undefined;
38
+ }
39
+ /**
40
+ * Attribute values may be any non-nullish primitive value except an object.
41
+ *
42
+ * null or undefined attribute values are invalid and will result in undefined behavior.
43
+ *
44
+ * @since 1.3.0
45
+ */
46
+ type AttributeValue = string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>;
47
+ interface ExceptionWithCode {
48
+ code: string | number;
49
+ name?: string;
50
+ message?: string;
51
+ stack?: string;
52
+ }
53
+ interface ExceptionWithMessage {
54
+ code?: string | number;
55
+ message: string;
56
+ name?: string;
57
+ stack?: string;
58
+ }
59
+ interface ExceptionWithName {
60
+ code?: string | number;
61
+ message?: string;
62
+ name: string;
63
+ stack?: string;
64
+ }
65
+ /**
66
+ * Defines Exception.
67
+ *
68
+ * string or an object with one of (message or name or code) and optional stack
69
+ *
70
+ * @since 1.0.0
71
+ */
72
+ type Exception = ExceptionWithCode | ExceptionWithMessage | ExceptionWithName | string;
73
+ /**
74
+ * Defines High-Resolution Time.
75
+ *
76
+ * The first number, HrTime[0], is UNIX Epoch time in seconds since 00:00:00 UTC on 1 January 1970.
77
+ * The second number, HrTime[1], represents the partial second elapsed since Unix Epoch time represented by first number in nanoseconds.
78
+ * For example, 2021-01-01T12:30:10.150Z in UNIX Epoch time in milliseconds is represented as 1609504210150.
79
+ * The first number is calculated by converting and truncating the Epoch time in milliseconds to seconds:
80
+ * HrTime[0] = Math.trunc(1609504210150 / 1000) = 1609504210.
81
+ * The second number is calculated by converting the digits after the decimal point of the subtraction, (1609504210150 / 1000) - HrTime[0], to nanoseconds:
82
+ * HrTime[1] = Number((1609504210.150 - HrTime[0]).toFixed(9)) * 1e9 = 150000000.
83
+ * This is represented in HrTime format as [1609504210, 150000000].
84
+ *
85
+ * @since 1.0.0
86
+ */
87
+ type HrTime = [number, number];
88
+ /**
89
+ * Defines TimeInput.
90
+ *
91
+ * hrtime, epoch milliseconds, performance.now() or Date
92
+ *
93
+ * @since 1.0.0
94
+ */
95
+ type TimeInput = HrTime | number | Date;
96
+ /**
97
+ * @deprecated please use {@link Attributes}
98
+ * @since 1.0.0
99
+ */
100
+ type SpanAttributes = Attributes;
101
+ /**
102
+ * @deprecated please use {@link AttributeValue}
103
+ * @since 1.0.0
104
+ */
105
+ type SpanAttributeValue = AttributeValue;
106
+ /**
107
+ * @since 1.0.0
108
+ */
109
+ interface TraceState {
110
+ /**
111
+ * Create a new TraceState which inherits from this TraceState and has the
112
+ * given key set.
113
+ * The new entry will always be added in the front of the list of states.
114
+ *
115
+ * @param key key of the TraceState entry.
116
+ * @param value value of the TraceState entry.
117
+ */
118
+ set(key: string, value: string): TraceState;
119
+ /**
120
+ * Return a new TraceState which inherits from this TraceState but does not
121
+ * contain the given key.
122
+ *
123
+ * @param key the key for the TraceState entry to be removed.
124
+ */
125
+ unset(key: string): TraceState;
126
+ /**
127
+ * Returns the value to which the specified key is mapped, or `undefined` if
128
+ * this map contains no mapping for the key.
129
+ *
130
+ * @param key with which the specified value is to be associated.
131
+ * @returns the value to which the specified key is mapped, or `undefined` if
132
+ * this map contains no mapping for the key.
133
+ */
134
+ get(key: string): string | undefined;
135
+ /**
136
+ * Serializes the TraceState to a `list` as defined below. The `list` is a
137
+ * series of `list-members` separated by commas `,`, and a list-member is a
138
+ * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs
139
+ * surrounding `list-members` are ignored. There can be a maximum of 32
140
+ * `list-members` in a `list`.
141
+ *
142
+ * @returns the serialized string.
143
+ */
144
+ serialize(): string;
145
+ }
146
+ /**
147
+ * A SpanContext represents the portion of a {@link Span} which must be
148
+ * serialized and propagated along side of a {@link Baggage}.
149
+ *
150
+ * @since 1.0.0
151
+ */
152
+ interface SpanContext {
153
+ /**
154
+ * The ID of the trace that this span belongs to. It is worldwide unique
155
+ * with practically sufficient probability by being made as 16 randomly
156
+ * generated bytes, encoded as a 32 lowercase hex characters corresponding to
157
+ * 128 bits.
158
+ */
159
+ traceId: string;
160
+ /**
161
+ * The ID of the Span. It is globally unique with practically sufficient
162
+ * probability by being made as 8 randomly generated bytes, encoded as a 16
163
+ * lowercase hex characters corresponding to 64 bits.
164
+ */
165
+ spanId: string;
166
+ /**
167
+ * Only true if the SpanContext was propagated from a remote parent.
168
+ */
169
+ isRemote?: boolean;
170
+ /**
171
+ * Trace flags to propagate.
172
+ *
173
+ * It is represented as 1 byte (bitmap). Bit to represent whether trace is
174
+ * sampled or not. When set, the least significant bit documents that the
175
+ * caller may have recorded trace data. A caller who does not record trace
176
+ * data out-of-band leaves this flag unset.
177
+ *
178
+ * see {@link TraceFlags} for valid flag values.
179
+ */
180
+ traceFlags: number;
181
+ /**
182
+ * Tracing-system-specific info to propagate.
183
+ *
184
+ * The tracestate field value is a `list` as defined below. The `list` is a
185
+ * series of `list-members` separated by commas `,`, and a list-member is a
186
+ * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs
187
+ * surrounding `list-members` are ignored. There can be a maximum of 32
188
+ * `list-members` in a `list`.
189
+ * More Info: https://www.w3.org/TR/trace-context/#tracestate-field
190
+ *
191
+ * Examples:
192
+ * Single tracing system (generic format):
193
+ * tracestate: rojo=00f067aa0ba902b7
194
+ * Multiple tracing systems (with different formatting):
195
+ * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE
196
+ */
197
+ traceState?: TraceState;
198
+ }
199
+ /**
200
+ * @since 1.0.0
201
+ */
202
+ interface SpanStatus {
203
+ /** The status code of this message. */
204
+ code: SpanStatusCode;
205
+ /** A developer-facing error message. */
206
+ message?: string;
207
+ }
208
+ /**
209
+ * An enumeration of status codes.
210
+ *
211
+ * @since 1.0.0
212
+ */
213
+ declare enum SpanStatusCode {
214
+ /**
215
+ * The default status.
216
+ */
217
+ UNSET = 0,
218
+ /**
219
+ * The operation has been validated by an Application developer or
220
+ * Operator to have completed successfully.
221
+ */
222
+ OK = 1,
223
+ /**
224
+ * The operation contains an error.
225
+ */
226
+ ERROR = 2
227
+ }
228
+ /**
229
+ * A pointer from the current {@link Span} to another span in the same trace or
230
+ * in a different trace.
231
+ * Few examples of Link usage.
232
+ * 1. Batch Processing: A batch of elements may contain elements associated
233
+ * with one or more traces/spans. Since there can only be one parent
234
+ * SpanContext, Link is used to keep reference to SpanContext of all
235
+ * elements in the batch.
236
+ * 2. Public Endpoint: A SpanContext in incoming client request on a public
237
+ * endpoint is untrusted from service provider perspective. In such case it
238
+ * is advisable to start a new trace with appropriate sampling decision.
239
+ * However, it is desirable to associate incoming SpanContext to new trace
240
+ * initiated on service provider side so two traces (from Client and from
241
+ * Service Provider) can be correlated.
242
+ *
243
+ * @since 1.0.0
244
+ */
245
+ interface Link {
246
+ /** The {@link SpanContext} of a linked span. */
247
+ context: SpanContext;
248
+ /** A set of {@link SpanAttributes} on the link. */
249
+ attributes?: SpanAttributes;
250
+ /** Count of attributes of the link that were dropped due to collection limits */
251
+ droppedAttributesCount?: number;
252
+ }
253
+ /**
254
+ * An interface that represents a span. A span represents a single operation
255
+ * within a trace. Examples of span might include remote procedure calls or a
256
+ * in-process function calls to sub-components. A Trace has a single, top-level
257
+ * "root" Span that in turn may have zero or more child Spans, which in turn
258
+ * may have children.
259
+ *
260
+ * Spans are created by the {@link Tracer.startSpan} method.
261
+ *
262
+ * @since 1.0.0
263
+ */
264
+ interface Span {
265
+ /**
266
+ * Returns the {@link SpanContext} object associated with this Span.
267
+ *
268
+ * Get an immutable, serializable identifier for this span that can be used
269
+ * to create new child spans. Returned SpanContext is usable even after the
270
+ * span ends.
271
+ *
272
+ * @returns the SpanContext object associated with this Span.
273
+ */
274
+ spanContext(): SpanContext;
275
+ /**
276
+ * Sets an attribute to the span.
277
+ *
278
+ * Sets a single Attribute with the key and value passed as arguments.
279
+ *
280
+ * @param key the key for this attribute.
281
+ * @param value the value for this attribute. Setting a value null or
282
+ * undefined is invalid and will result in undefined behavior.
283
+ */
284
+ setAttribute(key: string, value: SpanAttributeValue): this;
285
+ /**
286
+ * Sets attributes to the span.
287
+ *
288
+ * @param attributes the attributes that will be added.
289
+ * null or undefined attribute values
290
+ * are invalid and will result in undefined behavior.
291
+ */
292
+ setAttributes(attributes: SpanAttributes): this;
293
+ /**
294
+ * Adds an event to the Span.
295
+ *
296
+ * @param name the name of the event.
297
+ * @param [attributesOrStartTime] the attributes that will be added; these are
298
+ * associated with this event. Can be also a start time
299
+ * if type is {@type TimeInput} and 3rd param is undefined
300
+ * @param [startTime] start time of the event.
301
+ */
302
+ addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this;
303
+ /**
304
+ * Adds a single link to the span.
305
+ *
306
+ * Links added after the creation will not affect the sampling decision.
307
+ * It is preferred span links be added at span creation.
308
+ *
309
+ * @param link the link to add.
310
+ */
311
+ addLink(link: Link): this;
312
+ /**
313
+ * Adds multiple links to the span.
314
+ *
315
+ * Links added after the creation will not affect the sampling decision.
316
+ * It is preferred span links be added at span creation.
317
+ *
318
+ * @param links the links to add.
319
+ */
320
+ addLinks(links: Link[]): this;
321
+ /**
322
+ * Sets the status of the span.
323
+ *
324
+ * By default, a span has status {@link SpanStatusCode.UNSET}.
325
+ * Calling this method overrides that default.
326
+ *
327
+ * The status codes have a total order: `OK > ERROR > UNSET`.
328
+ *
329
+ * - Once {@link SpanStatusCode.OK} is set, any further attempts to change
330
+ * the status are ignored.
331
+ * - Any attempt to set {@link SpanStatusCode.UNSET} is always ignored.
332
+ *
333
+ * The `message` field is only used when {@link SpanStatusCode.ERROR} is set.
334
+ * For all other status codes, `message` is ignored.
335
+ *
336
+ * @param status The {@link SpanStatus} to set.
337
+ */
338
+ setStatus(status: SpanStatus): this;
339
+ /**
340
+ * Updates the Span name.
341
+ *
342
+ * This will override the name provided via {@link Tracer.startSpan}.
343
+ *
344
+ * Upon this update, any sampling behavior based on Span name will depend on
345
+ * the implementation.
346
+ *
347
+ * @param name the Span name.
348
+ */
349
+ updateName(name: string): this;
350
+ /**
351
+ * Marks the end of Span execution.
352
+ *
353
+ * Call to End of a Span MUST not have any effects on child spans. Those may
354
+ * still be running and can be ended later.
355
+ *
356
+ * Do not return `this`. The Span generally should not be used after it
357
+ * is ended so chaining is not desired in this context.
358
+ *
359
+ * @param [endTime] the time to set as Span's end time. If not provided,
360
+ * use the current time as the span's end time.
361
+ */
362
+ end(endTime?: TimeInput): void;
363
+ /**
364
+ * Returns the flag whether this span will be recorded.
365
+ *
366
+ * @returns true if this Span is active and recording information like events
367
+ * with the `AddEvent` operation and attributes using `setAttributes`.
368
+ */
369
+ isRecording(): boolean;
370
+ /**
371
+ * Sets exception as a span event
372
+ * @param exception the exception the only accepted values are string or Error
373
+ * @param [time] the time to set as Span's event time. If not provided,
374
+ * use the current time.
375
+ */
376
+ recordException(exception: Exception, time?: TimeInput): void;
377
+ }
378
+ /**
379
+ * @since 1.0.0
380
+ */
381
+ declare enum SpanKind {
382
+ /** Default value. Indicates that the span is used internally. */
383
+ INTERNAL = 0,
384
+ /**
385
+ * Indicates that the span covers server-side handling of an RPC or other
386
+ * remote request.
387
+ */
388
+ SERVER = 1,
389
+ /**
390
+ * Indicates that the span covers the client-side wrapper around an RPC or
391
+ * other remote request.
392
+ */
393
+ CLIENT = 2,
394
+ /**
395
+ * Indicates that the span describes producer sending a message to a
396
+ * broker. Unlike client and server, there is no direct critical path latency
397
+ * relationship between producer and consumer spans.
398
+ */
399
+ PRODUCER = 3,
400
+ /**
401
+ * Indicates that the span describes consumer receiving a message from a
402
+ * broker. Unlike client and server, there is no direct critical path latency
403
+ * relationship between producer and consumer spans.
404
+ */
405
+ CONSUMER = 4
406
+ }
407
+ /**
408
+ * Options needed for span creation
409
+ *
410
+ * @since 1.0.0
411
+ */
412
+ interface SpanOptions {
413
+ /**
414
+ * The SpanKind of a span
415
+ * @default {@link SpanKind.INTERNAL}
416
+ */
417
+ kind?: SpanKind;
418
+ /** A span's attributes */
419
+ attributes?: Attributes;
420
+ /** {@link Link}s span to other spans */
421
+ links?: Link[];
422
+ /** A manually specified start time for the created `Span` object. */
423
+ startTime?: TimeInput;
424
+ /** The new span should be a root span. (Ignore parent from context). */
425
+ root?: boolean;
426
+ }
427
+ /**
428
+ * Tracer provides an interface for creating {@link Span}s.
429
+ *
430
+ * @since 1.0.0
431
+ */
432
+ interface Tracer {
433
+ /**
434
+ * Starts a new {@link Span}. Start the span without setting it on context.
435
+ *
436
+ * This method do NOT modify the current Context.
437
+ *
438
+ * @param name The name of the span
439
+ * @param [options] SpanOptions used for span creation
440
+ * @param [context] Context to use to extract parent
441
+ * @returns Span The newly created span
442
+ * @example
443
+ * const span = tracer.startSpan('op');
444
+ * span.setAttribute('key', 'value');
445
+ * span.end();
446
+ */
447
+ startSpan(name: string, options?: SpanOptions, context?: Context): Span;
448
+ /**
449
+ * Starts a new {@link Span} and calls the given function passing it the
450
+ * created span as first argument.
451
+ * Additionally the new span gets set in context and this context is activated
452
+ * for the duration of the function call.
453
+ *
454
+ * @param name The name of the span
455
+ * @param [options] SpanOptions used for span creation
456
+ * @param [context] Context to use to extract parent
457
+ * @param fn function called in the context of the span and receives the newly created span as an argument
458
+ * @returns return value of fn
459
+ * @example
460
+ * const something = tracer.startActiveSpan('op', span => {
461
+ * try {
462
+ * do some work
463
+ * span.setStatus({code: SpanStatusCode.OK});
464
+ * return something;
465
+ * } catch (err) {
466
+ * span.setStatus({
467
+ * code: SpanStatusCode.ERROR,
468
+ * message: err.message,
469
+ * });
470
+ * throw err;
471
+ * } finally {
472
+ * span.end();
473
+ * }
474
+ * });
475
+ *
476
+ * @example
477
+ * const span = tracer.startActiveSpan('op', span => {
478
+ * try {
479
+ * do some work
480
+ * return span;
481
+ * } catch (err) {
482
+ * span.setStatus({
483
+ * code: SpanStatusCode.ERROR,
484
+ * message: err.message,
485
+ * });
486
+ * throw err;
487
+ * }
488
+ * });
489
+ * do some more work
490
+ * span.end();
491
+ */
492
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>;
493
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, fn: F): ReturnType<F>;
494
+ startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, context: Context, fn: F): ReturnType<F>;
495
+ }
496
+ /**
497
+ * The slice of a Lunora function `ctx` this bridge needs — the dispatch's span
498
+ * handle and the span factory.
499
+ *
500
+ * Structural rather than `QueryCtx`/`MutationCtx`/`ActionCtx` so one signature
501
+ * accepts all three (and a test double), while still being expressed in the real
502
+ * {@link SpanHandle} / {@link LunoraTracer} types now that this lives beside them.
503
+ */
504
+ interface LunoraTraceContext {
505
+ /** The dispatch's own span handle — supplies the trace this bridge joins. */
506
+ readonly span: SpanHandle;
507
+ /** The span factory: `ctx.trace(name, fn, options)`. */
508
+ readonly trace: LunoraTracer;
509
+ }
510
+ /** Options for {@link createOtelTracer}. */
511
+ interface OtelTracerOptions {
512
+ /**
513
+ * Prefix applied to every span name the bridge creates, e.g. `"ai."`.
514
+ *
515
+ * Useful when a third-party library emits generic names (`doGenerate`,
516
+ * `execute`) that would be ambiguous next to your own spans in a collector.
517
+ * Off by default — renaming someone else's spans breaks the dashboards their
518
+ * own documentation tells you to build.
519
+ */
520
+ namePrefix?: string;
521
+ }
522
+ /**
523
+ * Adapt a Lunora `ctx` into an `@opentelemetry/api` `Tracer`.
524
+ *
525
+ * Spans created through it are ordinary `ctx.trace` spans: they join the
526
+ * request's trace, appear in the studio waterfall, ride the same sampling
527
+ * decision, and export through the same OTLP sink. Nothing in the runtime has to
528
+ * know they came from a third-party library.
529
+ *
530
+ * **Parenting.** Every span is parented to the DISPATCH, not to a dynamically
531
+ * scoped "current" span, because tracking the latter across `await`s needs
532
+ * `AsyncLocalStorage` — unavailable in the Durable Object profile (see the
533
+ * module doc). `startActiveSpan` therefore runs its callback with the new span
534
+ * passed in, exactly as the interface requires, but does NOT make it ambient:
535
+ * `trace.getActiveSpan()` inside that callback still reports whatever the global
536
+ * provider says. A library that threads the span it is handed (the common case,
537
+ * and what the AI SDK does) nests correctly; one that relies on ambient context
538
+ * gets a flat trace instead of a nested one — flatter, never wrong, never lost.
539
+ * @param context Any Lunora function context (`QueryCtx` / `MutationCtx` / `ActionCtx`).
540
+ * @param options See {@link OtelTracerOptions}.
541
+ */
542
+ declare const createOtelTracer: (context: LunoraTraceContext, options?: OtelTracerOptions) => Tracer;
543
+ export { type LunoraTraceContext, type OtelTracerOptions, createOtelTracer };