@parsrun/service 0.1.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.
@@ -0,0 +1,106 @@
1
+ import { Logger } from '@parsrun/core';
2
+ import { b as ServiceDefinition, m as TraceContext, f as RpcRequest, g as RpcResponse } from './types-n4LLSPQU.js';
3
+
4
+ /**
5
+ * @parsrun/service - RPC Server
6
+ * Server for handling RPC requests
7
+ */
8
+
9
+ /**
10
+ * RPC handler context
11
+ */
12
+ interface RpcHandlerContext {
13
+ /** Request ID */
14
+ requestId: string;
15
+ /** Service name */
16
+ service: string;
17
+ /** Method name */
18
+ method: string;
19
+ /** Method type */
20
+ type: "query" | "mutation";
21
+ /** Request metadata */
22
+ metadata: Record<string, unknown>;
23
+ /** Trace context */
24
+ traceContext?: TraceContext;
25
+ /** Logger */
26
+ logger: Logger;
27
+ }
28
+ /**
29
+ * RPC handler function
30
+ */
31
+ type RpcHandler<TInput = unknown, TOutput = unknown> = (input: TInput, context: RpcHandlerContext) => Promise<TOutput>;
32
+ /**
33
+ * RPC handlers record
34
+ */
35
+ type RpcHandlers = {
36
+ queries?: Record<string, RpcHandler>;
37
+ mutations?: Record<string, RpcHandler>;
38
+ };
39
+ interface RpcServerOptions {
40
+ /** Service definition */
41
+ definition: ServiceDefinition;
42
+ /** RPC handlers */
43
+ handlers: RpcHandlers;
44
+ /** Logger */
45
+ logger?: Logger;
46
+ /** Default timeout in ms */
47
+ defaultTimeout?: number;
48
+ /** Middleware */
49
+ middleware?: RpcMiddleware[];
50
+ }
51
+ /**
52
+ * RPC middleware function
53
+ */
54
+ type RpcMiddleware = (request: RpcRequest, context: RpcHandlerContext, next: () => Promise<unknown>) => Promise<unknown>;
55
+ /**
56
+ * RPC Server for handling incoming requests
57
+ */
58
+ declare class RpcServer {
59
+ private readonly definition;
60
+ private readonly handlers;
61
+ private readonly logger;
62
+ private readonly defaultTimeout;
63
+ private readonly middleware;
64
+ constructor(options: RpcServerOptions);
65
+ /**
66
+ * Handle an RPC request
67
+ */
68
+ handle<TInput, TOutput>(request: RpcRequest<TInput>): Promise<RpcResponse<TOutput>>;
69
+ /**
70
+ * Get handler for a method
71
+ */
72
+ private getHandler;
73
+ /**
74
+ * Build middleware chain
75
+ */
76
+ private buildMiddlewareChain;
77
+ /**
78
+ * Get service definition
79
+ */
80
+ getDefinition(): ServiceDefinition;
81
+ /**
82
+ * Get registered methods
83
+ */
84
+ getMethods(): {
85
+ queries: string[];
86
+ mutations: string[];
87
+ };
88
+ }
89
+ /**
90
+ * Create an RPC server
91
+ */
92
+ declare function createRpcServer(options: RpcServerOptions): RpcServer;
93
+ /**
94
+ * Logging middleware
95
+ */
96
+ declare function loggingMiddleware(): RpcMiddleware;
97
+ /**
98
+ * Validation middleware (placeholder - integrate with ArkType)
99
+ */
100
+ declare function validationMiddleware(validators: Record<string, (input: unknown) => unknown>): RpcMiddleware;
101
+ /**
102
+ * Tenant context middleware
103
+ */
104
+ declare function tenantMiddleware(): RpcMiddleware;
105
+
106
+ export { RpcServer as R, type RpcHandler as a, type RpcHandlers as b, createRpcServer as c, type RpcMiddleware as d, type RpcHandlerContext as e, loggingMiddleware as l, tenantMiddleware as t, validationMiddleware as v };
@@ -0,0 +1,406 @@
1
+ import { m as TraceContext, o as SpanKind, q as SpanAttributeValue, n as Span, p as SpanStatus, T as TracingConfig } from '../types-n4LLSPQU.js';
2
+ import { Logger } from '@parsrun/core';
3
+
4
+ /**
5
+ * @parsrun/service - Trace Context
6
+ * W3C Trace Context implementation
7
+ */
8
+
9
+ /**
10
+ * Generate a trace ID (32 hex characters)
11
+ */
12
+ declare function generateTraceId(): string;
13
+ /**
14
+ * Generate a span ID (16 hex characters)
15
+ */
16
+ declare function generateSpanId(): string;
17
+ /**
18
+ * Create a new trace context
19
+ */
20
+ declare function createTraceContext(options?: {
21
+ traceId?: string;
22
+ spanId?: string;
23
+ traceFlags?: number;
24
+ traceState?: string;
25
+ }): TraceContext;
26
+ /**
27
+ * Create child trace context (new span in same trace)
28
+ */
29
+ declare function createChildContext(parent: TraceContext): TraceContext;
30
+ /**
31
+ * Format trace context as W3C traceparent header
32
+ *
33
+ * Format: {version}-{trace-id}-{span-id}-{trace-flags}
34
+ * Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
35
+ */
36
+ declare function formatTraceparent(ctx: TraceContext): string;
37
+ /**
38
+ * Parse W3C traceparent header
39
+ */
40
+ declare function parseTraceparent(header: string): TraceContext | null;
41
+ /**
42
+ * Format trace state as W3C tracestate header
43
+ *
44
+ * Format: key1=value1,key2=value2
45
+ */
46
+ declare function formatTracestate(state: Record<string, string>): string;
47
+ /**
48
+ * Parse W3C tracestate header
49
+ */
50
+ declare function parseTracestate(header: string): Record<string, string>;
51
+ /**
52
+ * Async-local-storage-like context manager for tracing
53
+ * Uses a simple stack for edge compatibility
54
+ */
55
+ declare class TraceContextManager {
56
+ private readonly stack;
57
+ /**
58
+ * Get current trace context
59
+ */
60
+ current(): TraceContext | undefined;
61
+ /**
62
+ * Run a function with a trace context
63
+ */
64
+ run<T>(ctx: TraceContext, fn: () => Promise<T>): Promise<T>;
65
+ /**
66
+ * Run a function with a new child context
67
+ */
68
+ runChild<T>(fn: () => Promise<T>): Promise<T>;
69
+ /**
70
+ * Create context from incoming request headers
71
+ */
72
+ fromHeaders(headers: Headers | Record<string, string>): TraceContext | undefined;
73
+ /**
74
+ * Add trace context to outgoing request headers
75
+ */
76
+ toHeaders(ctx: TraceContext): Record<string, string>;
77
+ /**
78
+ * Check if current context is sampled
79
+ */
80
+ isSampled(): boolean;
81
+ /**
82
+ * Clear all contexts (for testing)
83
+ */
84
+ clear(): void;
85
+ }
86
+ type Sampler = "always" | "never" | {
87
+ ratio: number;
88
+ };
89
+ /**
90
+ * Determine if a trace should be sampled
91
+ */
92
+ declare function shouldSample(sampler: Sampler, traceId?: string): boolean;
93
+
94
+ /**
95
+ * @parsrun/service - Spans
96
+ * Span creation and management
97
+ */
98
+
99
+ interface SpanOptions {
100
+ /** Span name */
101
+ name: string;
102
+ /** Span kind */
103
+ kind?: SpanKind;
104
+ /** Parent trace context */
105
+ parent?: TraceContext;
106
+ /** Initial attributes */
107
+ attributes?: Record<string, SpanAttributeValue>;
108
+ /** Start time (default: now) */
109
+ startTime?: number;
110
+ }
111
+ /**
112
+ * Create a new span
113
+ */
114
+ declare function createSpan(options: SpanOptions): Span;
115
+ /**
116
+ * Span manager for creating and managing spans
117
+ */
118
+ declare class SpanManager {
119
+ private readonly spans;
120
+ /**
121
+ * Start a new span
122
+ */
123
+ startSpan(options: SpanOptions): Span;
124
+ /**
125
+ * End a span
126
+ */
127
+ endSpan(span: Span, status?: SpanStatus): Span;
128
+ /**
129
+ * Set span attribute
130
+ */
131
+ setAttribute(span: Span, key: string, value: SpanAttributeValue): void;
132
+ /**
133
+ * Set multiple span attributes
134
+ */
135
+ setAttributes(span: Span, attributes: Record<string, SpanAttributeValue>): void;
136
+ /**
137
+ * Add span event
138
+ */
139
+ addEvent(span: Span, name: string, attributes?: Record<string, SpanAttributeValue>): void;
140
+ /**
141
+ * Set span status
142
+ */
143
+ setStatus(span: Span, status: SpanStatus): void;
144
+ /**
145
+ * Record exception on span
146
+ */
147
+ recordException(span: Span, error: Error): void;
148
+ /**
149
+ * Get span by ID
150
+ */
151
+ getSpan(spanId: string): Span | undefined;
152
+ /**
153
+ * Get all completed spans and clear
154
+ */
155
+ flush(): Span[];
156
+ /**
157
+ * Clear all spans
158
+ */
159
+ clear(): void;
160
+ }
161
+ /**
162
+ * Calculate span duration in milliseconds
163
+ */
164
+ declare function getSpanDuration(span: Span): number | undefined;
165
+ /**
166
+ * Check if span is completed
167
+ */
168
+ declare function isSpanCompleted(span: Span): boolean;
169
+ /**
170
+ * Get span as simplified object (for logging)
171
+ */
172
+ declare function spanToLogObject(span: Span): Record<string, unknown>;
173
+ /**
174
+ * Common span attribute keys (OpenTelemetry semantic conventions)
175
+ */
176
+ declare const SpanAttributes: {
177
+ readonly HTTP_METHOD: "http.method";
178
+ readonly HTTP_URL: "http.url";
179
+ readonly HTTP_STATUS_CODE: "http.status_code";
180
+ readonly HTTP_REQUEST_CONTENT_LENGTH: "http.request_content_length";
181
+ readonly HTTP_RESPONSE_CONTENT_LENGTH: "http.response_content_length";
182
+ readonly RPC_SYSTEM: "rpc.system";
183
+ readonly RPC_SERVICE: "rpc.service";
184
+ readonly RPC_METHOD: "rpc.method";
185
+ readonly DB_SYSTEM: "db.system";
186
+ readonly DB_NAME: "db.name";
187
+ readonly DB_OPERATION: "db.operation";
188
+ readonly DB_STATEMENT: "db.statement";
189
+ readonly MESSAGING_SYSTEM: "messaging.system";
190
+ readonly MESSAGING_DESTINATION: "messaging.destination";
191
+ readonly MESSAGING_MESSAGE_ID: "messaging.message_id";
192
+ readonly SERVICE_NAME: "service.name";
193
+ readonly SERVICE_VERSION: "service.version";
194
+ readonly EXCEPTION_TYPE: "exception.type";
195
+ readonly EXCEPTION_MESSAGE: "exception.message";
196
+ readonly EXCEPTION_STACKTRACE: "exception.stacktrace";
197
+ readonly PARS_TENANT_ID: "pars.tenant_id";
198
+ readonly PARS_USER_ID: "pars.user_id";
199
+ readonly PARS_REQUEST_ID: "pars.request_id";
200
+ };
201
+
202
+ /**
203
+ * @parsrun/service - Trace Exporters
204
+ * Console and OTLP exporters for spans
205
+ */
206
+
207
+ interface SpanExporter {
208
+ /** Exporter name */
209
+ readonly name: string;
210
+ /** Export spans */
211
+ export(spans: Span[]): Promise<void>;
212
+ /** Shutdown exporter */
213
+ shutdown(): Promise<void>;
214
+ }
215
+ interface ExporterOptions {
216
+ /** Logger */
217
+ logger?: Logger;
218
+ }
219
+ interface ConsoleExporterOptions extends ExporterOptions {
220
+ /** Pretty print (default: true in dev) */
221
+ pretty?: boolean;
222
+ /** Include attributes (default: true) */
223
+ includeAttributes?: boolean;
224
+ /** Include events (default: true) */
225
+ includeEvents?: boolean;
226
+ }
227
+ /**
228
+ * Console exporter for development/debugging
229
+ */
230
+ declare class ConsoleExporter implements SpanExporter {
231
+ readonly name = "console";
232
+ private readonly logger;
233
+ private readonly pretty;
234
+ private readonly includeAttributes;
235
+ private readonly includeEvents;
236
+ constructor(options?: ConsoleExporterOptions);
237
+ export(spans: Span[]): Promise<void>;
238
+ shutdown(): Promise<void>;
239
+ }
240
+ /**
241
+ * Create a console exporter
242
+ */
243
+ declare function createConsoleExporter(options?: ConsoleExporterOptions): ConsoleExporter;
244
+ interface OtlpExporterOptions extends ExporterOptions {
245
+ /** OTLP endpoint URL */
246
+ endpoint: string;
247
+ /** Service name */
248
+ serviceName: string;
249
+ /** Service version */
250
+ serviceVersion?: string;
251
+ /** Custom headers */
252
+ headers?: Record<string, string>;
253
+ /** Timeout in ms */
254
+ timeout?: number;
255
+ /** Batch size */
256
+ batchSize?: number;
257
+ /** Flush interval in ms */
258
+ flushInterval?: number;
259
+ }
260
+ /**
261
+ * OTLP exporter for production tracing
262
+ */
263
+ declare class OtlpExporter implements SpanExporter {
264
+ readonly name = "otlp";
265
+ private readonly endpoint;
266
+ private readonly serviceName;
267
+ private readonly serviceVersion;
268
+ private readonly headers;
269
+ private readonly timeout;
270
+ private readonly batchSize;
271
+ private readonly flushInterval;
272
+ private readonly logger;
273
+ private readonly buffer;
274
+ private flushTimer;
275
+ constructor(options: OtlpExporterOptions);
276
+ export(spans: Span[]): Promise<void>;
277
+ private flush;
278
+ private buildOtlpPayload;
279
+ private convertSpan;
280
+ private convertSpanKind;
281
+ private convertAttributeValue;
282
+ shutdown(): Promise<void>;
283
+ }
284
+ /**
285
+ * Create an OTLP exporter
286
+ */
287
+ declare function createOtlpExporter(options: OtlpExporterOptions): OtlpExporter;
288
+
289
+ /**
290
+ * @parsrun/service - Tracer
291
+ * High-level tracing API
292
+ */
293
+
294
+ interface TracerOptions {
295
+ /** Service name */
296
+ serviceName: string;
297
+ /** Service version */
298
+ serviceVersion?: string;
299
+ /** Tracing config */
300
+ config?: TracingConfig;
301
+ /** Span exporter */
302
+ exporter?: SpanExporter;
303
+ /** Logger */
304
+ logger?: Logger;
305
+ }
306
+ /**
307
+ * Main tracer class for distributed tracing
308
+ */
309
+ declare class Tracer {
310
+ private readonly serviceName;
311
+ private readonly serviceVersion;
312
+ private readonly sampler;
313
+ private readonly exporter;
314
+ private readonly logger;
315
+ private readonly contextManager;
316
+ private readonly spanManager;
317
+ private readonly enabled;
318
+ private flushTimer;
319
+ constructor(options: TracerOptions);
320
+ /**
321
+ * Start a new span
322
+ */
323
+ startSpan(name: string, options?: {
324
+ kind?: SpanKind;
325
+ parent?: TraceContext;
326
+ attributes?: Record<string, SpanAttributeValue>;
327
+ }): Span | null;
328
+ /**
329
+ * End a span
330
+ */
331
+ endSpan(span: Span | null, error?: Error): void;
332
+ /**
333
+ * Run a function with automatic span creation
334
+ */
335
+ trace<T>(name: string, fn: (span: Span | null) => Promise<T>, options?: {
336
+ kind?: SpanKind;
337
+ attributes?: Record<string, SpanAttributeValue>;
338
+ }): Promise<T>;
339
+ /**
340
+ * Add attribute to current span
341
+ */
342
+ setAttribute(key: string, value: SpanAttributeValue): void;
343
+ /**
344
+ * Add event to current span
345
+ */
346
+ addEvent(name: string, attributes?: Record<string, SpanAttributeValue>): void;
347
+ /**
348
+ * Get current trace context
349
+ */
350
+ currentContext(): TraceContext | undefined;
351
+ /**
352
+ * Get context manager for advanced use
353
+ */
354
+ getContextManager(): TraceContextManager;
355
+ /**
356
+ * Extract trace context from incoming request
357
+ */
358
+ extract(headers: Headers | Record<string, string>): TraceContext | undefined;
359
+ /**
360
+ * Inject trace context into outgoing request headers
361
+ */
362
+ inject(ctx?: TraceContext): Record<string, string>;
363
+ /**
364
+ * Flush completed spans to exporter
365
+ */
366
+ flush(): Promise<void>;
367
+ /**
368
+ * Shutdown tracer
369
+ */
370
+ shutdown(): Promise<void>;
371
+ }
372
+ /**
373
+ * Create a tracer
374
+ */
375
+ declare function createTracer(options: TracerOptions): Tracer;
376
+ /**
377
+ * Get the global tracer instance
378
+ */
379
+ declare function getGlobalTracer(): Tracer | null;
380
+ /**
381
+ * Set the global tracer instance
382
+ */
383
+ declare function setGlobalTracer(tracer: Tracer): void;
384
+ /**
385
+ * Reset the global tracer (for testing)
386
+ */
387
+ declare function resetGlobalTracer(): void;
388
+ /**
389
+ * Create HTTP server tracing middleware
390
+ */
391
+ declare function createTracingMiddleware(tracer: Tracer): (request: Request, next: () => Promise<Response>) => Promise<Response>;
392
+ /**
393
+ * Create RPC tracing helpers
394
+ */
395
+ declare function createRpcTracing(tracer: Tracer): {
396
+ /**
397
+ * Trace an outgoing RPC call
398
+ */
399
+ traceCall<T>(service: string, method: string, fn: () => Promise<T>): Promise<T>;
400
+ /**
401
+ * Trace an incoming RPC request
402
+ */
403
+ traceHandler<T>(service: string, method: string, fn: () => Promise<T>, parentCtx?: TraceContext): Promise<T>;
404
+ };
405
+
406
+ export { ConsoleExporter, type ConsoleExporterOptions, type ExporterOptions, OtlpExporter, type OtlpExporterOptions, type Sampler, SpanAttributes, type SpanExporter, SpanManager, type SpanOptions, TraceContextManager, Tracer, type TracerOptions, createChildContext, createConsoleExporter, createOtlpExporter, createRpcTracing, createSpan, createTraceContext, createTracer, createTracingMiddleware, formatTraceparent, formatTracestate, generateSpanId, generateTraceId, getGlobalTracer, getSpanDuration, isSpanCompleted, parseTraceparent, parseTracestate, resetGlobalTracer, setGlobalTracer, shouldSample, spanToLogObject };