@rocketflare/houston-otel 0.0.0-stage → 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.
- package/README.md +172 -2
- package/dist/attributes.d.ts +16 -0
- package/dist/attributes.js +133 -0
- package/dist/genai.d.ts +97 -0
- package/dist/genai.js +200 -0
- package/dist/hono.d.ts +24 -0
- package/dist/hono.js +80 -0
- package/dist/houston.d.ts +124 -0
- package/dist/houston.js +353 -0
- package/dist/http.d.ts +8 -0
- package/dist/http.js +35 -0
- package/dist/ids.d.ts +17 -0
- package/dist/ids.js +35 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +7 -0
- package/dist/invocations.d.ts +56 -0
- package/dist/invocations.js +128 -0
- package/dist/otlp.d.ts +127 -0
- package/dist/otlp.js +83 -0
- package/dist/pino.d.ts +38 -0
- package/dist/pino.js +104 -0
- package/dist/sql-text.d.ts +25 -0
- package/dist/sql-text.js +297 -0
- package/dist/sql.d.ts +95 -0
- package/dist/sql.js +425 -0
- package/package.json +75 -4
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Houston, Span } from './houston.js';
|
|
2
|
+
import type { Attributes } from './otlp.js';
|
|
3
|
+
/** A Houston, or a function of the handler's env that returns one (memoise it per env). */
|
|
4
|
+
export type HoustonSource<E> = Houston | ((env: E) => Houston);
|
|
5
|
+
/** What the wrappers use of an `ExecutionContext`. */
|
|
6
|
+
export interface WaitUntilContext {
|
|
7
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
8
|
+
}
|
|
9
|
+
export interface WithRequestOptions {
|
|
10
|
+
/** The route pattern for `http.route` and the span name (e.g. from your router). Default none. */
|
|
11
|
+
route?: (request: Request) => string | undefined;
|
|
12
|
+
/** Skip a request entirely (no span, no flush), e.g. a health probe. */
|
|
13
|
+
ignore?: (request: Request) => boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A `fetch` handler as one invocation under a SERVER span (method, `url.*`, status; a 5xx or a throw is ERROR),
|
|
17
|
+
* continuing an incoming `traceparent`. For Hono apps use `houstonMiddleware` from `./hono` instead.
|
|
18
|
+
*/
|
|
19
|
+
export declare function withRequest<E, C extends WaitUntilContext, R extends Request>(houston: HoustonSource<E>, handler: (request: R, env: E, ctx: C) => Response | Promise<Response>, options?: WithRequestOptions): (request: R, env: E, ctx: C) => Promise<Response>;
|
|
20
|
+
/** What `withScheduled` reads of a `ScheduledController`. */
|
|
21
|
+
export interface ScheduledLike {
|
|
22
|
+
cron: string;
|
|
23
|
+
scheduledTime: number;
|
|
24
|
+
}
|
|
25
|
+
/** A `scheduled` handler as one invocation under a `cron <expression>` span (`faas.trigger` timer). */
|
|
26
|
+
export declare function withScheduled<E, C extends WaitUntilContext, S extends ScheduledLike>(houston: HoustonSource<E>, handler: (controller: S, env: E, ctx: C) => unknown): (controller: S, env: E, ctx: C) => Promise<void>;
|
|
27
|
+
/** What `withQueue` reads of a `MessageBatch`. */
|
|
28
|
+
export interface MessageBatchLike {
|
|
29
|
+
queue: string;
|
|
30
|
+
messages: readonly unknown[];
|
|
31
|
+
}
|
|
32
|
+
/** A `queue` handler as one invocation under a CONSUMER `process <queue>` span with the batch size. */
|
|
33
|
+
export declare function withQueue<E, C extends WaitUntilContext, B extends MessageBatchLike>(houston: HoustonSource<E>, handler: (batch: B, env: E, ctx: C) => unknown): (batch: B, env: E, ctx: C) => Promise<void>;
|
|
34
|
+
export interface WithStepOptions {
|
|
35
|
+
/** The parent's `traceparent` (from the workflow payload, set with `houston.traceparent()`), so the step joins its trace. */
|
|
36
|
+
traceparent?: string | null;
|
|
37
|
+
/** Extra span attributes. */
|
|
38
|
+
attributes?: Attributes;
|
|
39
|
+
/** Hand the flush to this instead of awaiting it at the step's end. */
|
|
40
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* One Workflow step as its own invocation: a `step <name>` span (a child of `traceparent` when given) whose
|
|
44
|
+
* records are flushed when the step ends. Use it inside `step.do(name, () => withStep(houston, name, fn, …))`,
|
|
45
|
+
* or wrap the whole `step` with `tracedStep`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function withStep<T>(houston: Houston, name: string, fn: (span: Span) => Promise<T> | T, options?: WithStepOptions): Promise<T>;
|
|
48
|
+
/** The part of a `WorkflowStep` that `tracedStep` wraps. */
|
|
49
|
+
export interface WorkflowStepLike {
|
|
50
|
+
do: (name: string, ...rest: never[]) => Promise<unknown>;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* `step` with every `step.do(name, [config], fn)` callback run through `withStep`, so each step is its own
|
|
54
|
+
* invocation in the workflow's trace. Everything else (`sleep`, `waitForEvent`, …) is the step's own.
|
|
55
|
+
*/
|
|
56
|
+
export declare function tracedStep<S extends WorkflowStepLike>(houston: Houston, step: S, options?: Omit<WithStepOptions, 'attributes'>): S;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// One invocation per Workers handler call: `withRequest` (fetch), `withScheduled` (cron), `withQueue` (a queue
|
|
2
|
+
// batch) and `withStep` / `tracedStep` (a Workflow step). Each wraps the call in `houston.run` under one span and
|
|
3
|
+
// flushes in the call's `waitUntil` (a step awaits its flush, so its records leave when the step ends).
|
|
4
|
+
import { errorMessage } from './attributes.js';
|
|
5
|
+
import { failServerSpan, finishServerSpan, startServerSpan } from './http.js';
|
|
6
|
+
const resolve = (source, env) => (typeof source === 'function' ? source(env) : source);
|
|
7
|
+
const waitUntilOf = (ctx) => ctx && typeof ctx.waitUntil === 'function' ? (p) => ctx.waitUntil(p) : undefined;
|
|
8
|
+
async function spanned(houston, span, fn) {
|
|
9
|
+
try {
|
|
10
|
+
return await houston.withSpan(span, fn);
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
span.recordException(error);
|
|
14
|
+
span.setStatus('error', errorMessage(error));
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
span.end();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A `fetch` handler as one invocation under a SERVER span (method, `url.*`, status; a 5xx or a throw is ERROR),
|
|
23
|
+
* continuing an incoming `traceparent`. For Hono apps use `houstonMiddleware` from `./hono` instead.
|
|
24
|
+
*/
|
|
25
|
+
export function withRequest(houston, handler, options = {}) {
|
|
26
|
+
return async (request, env, ctx) => {
|
|
27
|
+
const h = resolve(houston, env);
|
|
28
|
+
if (!h.enabled || options.ignore?.(request))
|
|
29
|
+
return handler(request, env, ctx);
|
|
30
|
+
return h.run(async () => {
|
|
31
|
+
const span = startServerSpan(h, request);
|
|
32
|
+
try {
|
|
33
|
+
const response = await h.withSpan(span, () => handler(request, env, ctx));
|
|
34
|
+
try {
|
|
35
|
+
finishServerSpan(span, request.method, options.route?.(request), response.status);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// telemetry never changes the response
|
|
39
|
+
}
|
|
40
|
+
return response;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
failServerSpan(span, error);
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
span.end();
|
|
48
|
+
}
|
|
49
|
+
}, { waitUntil: waitUntilOf(ctx) });
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** A `scheduled` handler as one invocation under a `cron <expression>` span (`faas.trigger` timer). */
|
|
53
|
+
export function withScheduled(houston, handler) {
|
|
54
|
+
return async (controller, env, ctx) => {
|
|
55
|
+
const h = resolve(houston, env);
|
|
56
|
+
if (!h.enabled)
|
|
57
|
+
return void (await handler(controller, env, ctx));
|
|
58
|
+
await h.run(() => {
|
|
59
|
+
const span = h.startSpan(`cron ${controller.cron}`, {
|
|
60
|
+
attributes: { 'faas.trigger': 'timer', 'faas.cron': controller.cron, 'faas.time': new Date(controller.scheduledTime).toISOString() },
|
|
61
|
+
});
|
|
62
|
+
return spanned(h, span, async () => void (await handler(controller, env, ctx)));
|
|
63
|
+
}, { waitUntil: waitUntilOf(ctx) });
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** A `queue` handler as one invocation under a CONSUMER `process <queue>` span with the batch size. */
|
|
67
|
+
export function withQueue(houston, handler) {
|
|
68
|
+
return async (batch, env, ctx) => {
|
|
69
|
+
const h = resolve(houston, env);
|
|
70
|
+
if (!h.enabled)
|
|
71
|
+
return void (await handler(batch, env, ctx));
|
|
72
|
+
await h.run(() => {
|
|
73
|
+
const span = h.startSpan(`process ${batch.queue}`, {
|
|
74
|
+
kind: 'consumer',
|
|
75
|
+
attributes: {
|
|
76
|
+
'messaging.system': 'cloudflare.queues',
|
|
77
|
+
'messaging.operation.type': 'process',
|
|
78
|
+
'messaging.destination.name': batch.queue,
|
|
79
|
+
'messaging.batch.message_count': batch.messages.length,
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
return spanned(h, span, async () => void (await handler(batch, env, ctx)));
|
|
83
|
+
}, { waitUntil: waitUntilOf(ctx) });
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* One Workflow step as its own invocation: a `step <name>` span (a child of `traceparent` when given) whose
|
|
88
|
+
* records are flushed when the step ends. Use it inside `step.do(name, () => withStep(houston, name, fn, …))`,
|
|
89
|
+
* or wrap the whole `step` with `tracedStep`.
|
|
90
|
+
*/
|
|
91
|
+
export function withStep(houston, name, fn, options = {}) {
|
|
92
|
+
if (!houston.enabled)
|
|
93
|
+
return Promise.resolve().then(() => fn(houston.startSpan(name)));
|
|
94
|
+
return houston.run(() => {
|
|
95
|
+
const span = houston.startSpan(`step ${name}`, {
|
|
96
|
+
parent: options.traceparent ?? undefined,
|
|
97
|
+
attributes: { 'workflow.step.name': name, ...options.attributes },
|
|
98
|
+
});
|
|
99
|
+
return spanned(houston, span, () => fn(span));
|
|
100
|
+
}, { waitUntil: options.waitUntil });
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* `step` with every `step.do(name, [config], fn)` callback run through `withStep`, so each step is its own
|
|
104
|
+
* invocation in the workflow's trace. Everything else (`sleep`, `waitForEvent`, …) is the step's own.
|
|
105
|
+
*/
|
|
106
|
+
export function tracedStep(houston, step, options = {}) {
|
|
107
|
+
if (!houston.enabled)
|
|
108
|
+
return step;
|
|
109
|
+
const original = step.do;
|
|
110
|
+
const traced = (name, ...rest) => {
|
|
111
|
+
const at = rest.length - 1;
|
|
112
|
+
const fn = rest[at];
|
|
113
|
+
if (typeof fn !== 'function')
|
|
114
|
+
return original.call(step, name, ...rest);
|
|
115
|
+
const args = [...rest];
|
|
116
|
+
args[at] = () => withStep(houston, name, () => fn(), options);
|
|
117
|
+
return original.call(step, name, ...args);
|
|
118
|
+
};
|
|
119
|
+
// methods bound to the real step: a runtime object may keep private state a proxy receiver can't reach
|
|
120
|
+
return new Proxy(step, {
|
|
121
|
+
get(target, key) {
|
|
122
|
+
if (key === 'do')
|
|
123
|
+
return traced;
|
|
124
|
+
const value = Reflect.get(target, key);
|
|
125
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
}
|
package/dist/otlp.d.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/** An attribute value: a primitive or a homogeneous array of primitives. */
|
|
2
|
+
export type AttributeValue = string | number | boolean | string[] | number[] | boolean[];
|
|
3
|
+
/** Attributes by key. `undefined` and `null` values (and non-finite numbers) are dropped when encoded. */
|
|
4
|
+
export type Attributes = Record<string, AttributeValue | null | undefined>;
|
|
5
|
+
/** Log levels, lowest first. */
|
|
6
|
+
export type SeverityName = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
7
|
+
/** The OTLP severity number at the bottom of each range (TRACE 1 … FATAL 21). */
|
|
8
|
+
export declare const SEVERITY_NUMBER: Record<SeverityName, number>;
|
|
9
|
+
/** OTLP span kinds by name. */
|
|
10
|
+
export type SpanKindName = 'internal' | 'server' | 'client' | 'producer' | 'consumer';
|
|
11
|
+
/** OTLP span status codes by name. */
|
|
12
|
+
export type SpanStatusCode = 'unset' | 'ok' | 'error';
|
|
13
|
+
/** One log record as kept before export. */
|
|
14
|
+
export interface LogData {
|
|
15
|
+
/** Epoch ms. */
|
|
16
|
+
time: number;
|
|
17
|
+
severity: SeverityName;
|
|
18
|
+
body: string;
|
|
19
|
+
attributes: Attributes;
|
|
20
|
+
traceId?: string;
|
|
21
|
+
spanId?: string;
|
|
22
|
+
eventName?: string;
|
|
23
|
+
}
|
|
24
|
+
/** One span event (an `exception`, say). */
|
|
25
|
+
export interface SpanEventData {
|
|
26
|
+
name: string;
|
|
27
|
+
/** Epoch ms. */
|
|
28
|
+
time: number;
|
|
29
|
+
attributes: Attributes;
|
|
30
|
+
}
|
|
31
|
+
/** One finished span as kept before export. */
|
|
32
|
+
export interface SpanData {
|
|
33
|
+
traceId: string;
|
|
34
|
+
spanId: string;
|
|
35
|
+
parentSpanId?: string;
|
|
36
|
+
name: string;
|
|
37
|
+
kind: SpanKindName;
|
|
38
|
+
/** Epoch ms. */
|
|
39
|
+
startTime: number;
|
|
40
|
+
/** Epoch ms. */
|
|
41
|
+
endTime: number;
|
|
42
|
+
status: SpanStatusCode;
|
|
43
|
+
statusMessage?: string;
|
|
44
|
+
attributes: Attributes;
|
|
45
|
+
events: SpanEventData[];
|
|
46
|
+
}
|
|
47
|
+
export type OtlpAnyValue = {
|
|
48
|
+
stringValue: string;
|
|
49
|
+
} | {
|
|
50
|
+
boolValue: boolean;
|
|
51
|
+
} | {
|
|
52
|
+
intValue: string;
|
|
53
|
+
} | {
|
|
54
|
+
doubleValue: number;
|
|
55
|
+
} | {
|
|
56
|
+
arrayValue: {
|
|
57
|
+
values: OtlpAnyValue[];
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export interface OtlpKeyValue {
|
|
61
|
+
key: string;
|
|
62
|
+
value: OtlpAnyValue;
|
|
63
|
+
}
|
|
64
|
+
export interface OtlpScope {
|
|
65
|
+
name: string;
|
|
66
|
+
version?: string;
|
|
67
|
+
}
|
|
68
|
+
export interface OtlpLogRecord {
|
|
69
|
+
timeUnixNano: string;
|
|
70
|
+
observedTimeUnixNano: string;
|
|
71
|
+
severityNumber: number;
|
|
72
|
+
severityText: string;
|
|
73
|
+
body: {
|
|
74
|
+
stringValue: string;
|
|
75
|
+
};
|
|
76
|
+
attributes: OtlpKeyValue[];
|
|
77
|
+
traceId?: string;
|
|
78
|
+
spanId?: string;
|
|
79
|
+
eventName?: string;
|
|
80
|
+
}
|
|
81
|
+
/** The body of a POST to `/v1/logs`. */
|
|
82
|
+
export interface OtlpLogsRequest {
|
|
83
|
+
resourceLogs: {
|
|
84
|
+
resource: {
|
|
85
|
+
attributes: OtlpKeyValue[];
|
|
86
|
+
};
|
|
87
|
+
scopeLogs: {
|
|
88
|
+
scope: OtlpScope;
|
|
89
|
+
logRecords: OtlpLogRecord[];
|
|
90
|
+
}[];
|
|
91
|
+
}[];
|
|
92
|
+
}
|
|
93
|
+
export interface OtlpSpan {
|
|
94
|
+
traceId: string;
|
|
95
|
+
spanId: string;
|
|
96
|
+
parentSpanId?: string;
|
|
97
|
+
name: string;
|
|
98
|
+
kind: number;
|
|
99
|
+
startTimeUnixNano: string;
|
|
100
|
+
endTimeUnixNano: string;
|
|
101
|
+
attributes: OtlpKeyValue[];
|
|
102
|
+
events: {
|
|
103
|
+
timeUnixNano: string;
|
|
104
|
+
name: string;
|
|
105
|
+
attributes: OtlpKeyValue[];
|
|
106
|
+
}[];
|
|
107
|
+
status: {
|
|
108
|
+
code: number;
|
|
109
|
+
message?: string;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** The body of a POST to `/v1/traces`. */
|
|
113
|
+
export interface OtlpTracesRequest {
|
|
114
|
+
resourceSpans: {
|
|
115
|
+
resource: {
|
|
116
|
+
attributes: OtlpKeyValue[];
|
|
117
|
+
};
|
|
118
|
+
scopeSpans: {
|
|
119
|
+
scope: OtlpScope;
|
|
120
|
+
spans: OtlpSpan[];
|
|
121
|
+
}[];
|
|
122
|
+
}[];
|
|
123
|
+
}
|
|
124
|
+
/** Log records as one OTLP/JSON logs request under `resource` and `scope`. */
|
|
125
|
+
export declare function logsRequest(logs: LogData[], resource: Attributes, scope: OtlpScope): OtlpLogsRequest;
|
|
126
|
+
/** Spans as one OTLP/JSON traces request under `resource` and `scope`. */
|
|
127
|
+
export declare function tracesRequest(spans: SpanData[], resource: Attributes, scope: OtlpScope): OtlpTracesRequest;
|
package/dist/otlp.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// OTLP/HTTP JSON by hand: the records this package keeps (`LogData`, `SpanData`) and their encoding as
|
|
2
|
+
// `ExportLogsServiceRequest` / `ExportTraceServiceRequest`. Ids are lowercase hex, times epoch ms turned into
|
|
3
|
+
// nanosecond strings, attribute values the OTLP `AnyValue` variants. Pure, no I/O.
|
|
4
|
+
/** The OTLP severity number at the bottom of each range (TRACE 1 … FATAL 21). */
|
|
5
|
+
export const SEVERITY_NUMBER = {
|
|
6
|
+
trace: 1,
|
|
7
|
+
debug: 5,
|
|
8
|
+
info: 9,
|
|
9
|
+
warn: 13,
|
|
10
|
+
error: 17,
|
|
11
|
+
fatal: 21,
|
|
12
|
+
};
|
|
13
|
+
const SPAN_KIND = { internal: 1, server: 2, client: 3, producer: 4, consumer: 5 };
|
|
14
|
+
const STATUS_CODE = { unset: 0, ok: 1, error: 2 };
|
|
15
|
+
function anyValue(value) {
|
|
16
|
+
if (Array.isArray(value))
|
|
17
|
+
return { arrayValue: { values: value.map(anyValue) } };
|
|
18
|
+
if (typeof value === 'string')
|
|
19
|
+
return { stringValue: value };
|
|
20
|
+
if (typeof value === 'boolean')
|
|
21
|
+
return { boolValue: value };
|
|
22
|
+
return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
|
|
23
|
+
}
|
|
24
|
+
const isPrimitive = (v) => typeof v === 'string' || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v));
|
|
25
|
+
const isAttributeValue = (v) => isPrimitive(v) || (Array.isArray(v) && v.every(isPrimitive));
|
|
26
|
+
function keyValues(attributes) {
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
29
|
+
if (value === undefined || value === null)
|
|
30
|
+
continue;
|
|
31
|
+
if (typeof value === 'number' && !Number.isFinite(value))
|
|
32
|
+
continue;
|
|
33
|
+
if (!isAttributeValue(value))
|
|
34
|
+
continue; // untyped callers: never encode an object as a value
|
|
35
|
+
out.push({ key, value: anyValue(value) });
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Epoch ms (fractions allowed) → nanoseconds as a decimal string. */
|
|
40
|
+
function unixNano(ms) {
|
|
41
|
+
const whole = Math.floor(ms);
|
|
42
|
+
const micros = Math.round((ms - whole) * 1000);
|
|
43
|
+
return (BigInt(whole) * 1000000n + BigInt(micros) * 1000n).toString();
|
|
44
|
+
}
|
|
45
|
+
function toOtlpLogRecord(log) {
|
|
46
|
+
const time = unixNano(log.time);
|
|
47
|
+
return {
|
|
48
|
+
timeUnixNano: time,
|
|
49
|
+
observedTimeUnixNano: time,
|
|
50
|
+
severityNumber: SEVERITY_NUMBER[log.severity],
|
|
51
|
+
severityText: log.severity.toUpperCase(),
|
|
52
|
+
body: { stringValue: log.body },
|
|
53
|
+
attributes: keyValues(log.attributes),
|
|
54
|
+
...(log.traceId && { traceId: log.traceId }),
|
|
55
|
+
...(log.spanId && { spanId: log.spanId }),
|
|
56
|
+
...(log.eventName && { eventName: log.eventName }),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function toOtlpSpan(span) {
|
|
60
|
+
return {
|
|
61
|
+
traceId: span.traceId,
|
|
62
|
+
spanId: span.spanId,
|
|
63
|
+
...(span.parentSpanId && { parentSpanId: span.parentSpanId }),
|
|
64
|
+
name: span.name,
|
|
65
|
+
kind: SPAN_KIND[span.kind],
|
|
66
|
+
startTimeUnixNano: unixNano(span.startTime),
|
|
67
|
+
endTimeUnixNano: unixNano(Math.max(span.endTime, span.startTime)),
|
|
68
|
+
attributes: keyValues(span.attributes),
|
|
69
|
+
events: span.events.map((e) => ({ timeUnixNano: unixNano(e.time), name: e.name, attributes: keyValues(e.attributes) })),
|
|
70
|
+
status: {
|
|
71
|
+
code: STATUS_CODE[span.status],
|
|
72
|
+
...(span.status === 'error' && span.statusMessage && { message: span.statusMessage }),
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Log records as one OTLP/JSON logs request under `resource` and `scope`. */
|
|
77
|
+
export function logsRequest(logs, resource, scope) {
|
|
78
|
+
return { resourceLogs: [{ resource: { attributes: keyValues(resource) }, scopeLogs: [{ scope, logRecords: logs.map(toOtlpLogRecord) }] }] };
|
|
79
|
+
}
|
|
80
|
+
/** Spans as one OTLP/JSON traces request under `resource` and `scope`. */
|
|
81
|
+
export function tracesRequest(spans, resource, scope) {
|
|
82
|
+
return { resourceSpans: [{ resource: { attributes: keyValues(resource) }, scopeSpans: [{ scope, spans: spans.map(toOtlpSpan) }] }] };
|
|
83
|
+
}
|
package/dist/pino.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Houston } from './houston.js';
|
|
2
|
+
import type { Attributes, SeverityName } from './otlp.js';
|
|
3
|
+
/** The shape pino's browser build hands `transmit.send`. */
|
|
4
|
+
export interface PinoLogEvent {
|
|
5
|
+
ts: number | string;
|
|
6
|
+
messages: unknown[];
|
|
7
|
+
bindings: Record<string, unknown>[];
|
|
8
|
+
level: {
|
|
9
|
+
label: string;
|
|
10
|
+
value: number;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export interface PinoTransmitOptions {
|
|
14
|
+
/** pino's `transmit.level`; defaults to the logger's own level. */
|
|
15
|
+
level?: string;
|
|
16
|
+
/** Field names to leave out (ones already on the resource, say). */
|
|
17
|
+
omit?: string[];
|
|
18
|
+
}
|
|
19
|
+
/** One pino call as a houston log record. */
|
|
20
|
+
export interface PinoRecord {
|
|
21
|
+
severity: SeverityName;
|
|
22
|
+
message: string;
|
|
23
|
+
attributes: Attributes;
|
|
24
|
+
time?: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* One pino call as a record: the message is the body, child bindings and the merge object become dotted
|
|
28
|
+
* attributes, `err` becomes `exception.*`. Pure.
|
|
29
|
+
*/
|
|
30
|
+
export declare function fromPinoEvent(event: PinoLogEvent, omit?: ReadonlySet<string>): PinoRecord;
|
|
31
|
+
/**
|
|
32
|
+
* The `browser.transmit` value for pino: each call becomes one houston log record, correlated with the active
|
|
33
|
+
* span. Pair it with `browser: { asObject: true }` and pino's `stdSerializers.err` for `err`. Never throws.
|
|
34
|
+
*/
|
|
35
|
+
export declare function pinoTransmit(houston: Houston | (() => Houston), options?: PinoTransmitOptions): {
|
|
36
|
+
level?: string;
|
|
37
|
+
send: (level: string, event: PinoLogEvent) => void;
|
|
38
|
+
};
|
package/dist/pino.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// pino → houston: `pinoTransmit(houston)` is a value for pino's `browser.transmit`, which pino's browser build (the
|
|
2
|
+
// one a Worker bundle gets) calls for every log call at or above its level. Node's pino ignores `browser.*`.
|
|
3
|
+
import { exceptionAttributes, flattenInto } from './attributes.js';
|
|
4
|
+
const SEVERITIES = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
|
|
5
|
+
const severityOf = (label) => (SEVERITIES.has(label) ? label : 'info');
|
|
6
|
+
function timeOf(ts) {
|
|
7
|
+
if (typeof ts === 'number' && Number.isFinite(ts))
|
|
8
|
+
return ts;
|
|
9
|
+
if (typeof ts === 'string') {
|
|
10
|
+
// pino's time functions return `,"time":…` fragments in Node and plain values in the browser
|
|
11
|
+
const raw = ts.replace(/^,"time":/, '').replace(/^"|"$/g, '');
|
|
12
|
+
const n = Number(raw);
|
|
13
|
+
if (Number.isFinite(n) && raw !== '')
|
|
14
|
+
return n;
|
|
15
|
+
const parsed = Date.parse(raw);
|
|
16
|
+
if (Number.isFinite(parsed))
|
|
17
|
+
return parsed;
|
|
18
|
+
}
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
/** pino's `printf`-ish substitution of `%s %d %i %f %o %O %j` from the args after the message. */
|
|
22
|
+
function format(message, args) {
|
|
23
|
+
let i = 0;
|
|
24
|
+
const out = message.replace(/%[sdifoOj%]/g, (token) => {
|
|
25
|
+
if (token === '%%')
|
|
26
|
+
return '%';
|
|
27
|
+
if (i >= args.length)
|
|
28
|
+
return token;
|
|
29
|
+
const arg = args[i++];
|
|
30
|
+
if (token === '%d' || token === '%i' || token === '%f')
|
|
31
|
+
return String(Number(arg));
|
|
32
|
+
if (typeof arg === 'string')
|
|
33
|
+
return arg;
|
|
34
|
+
try {
|
|
35
|
+
return JSON.stringify(arg);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return String(arg);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const rest = args.slice(i).map((a) => (typeof a === 'string' ? a : JSON.stringify(a)));
|
|
42
|
+
return rest.length > 0 ? `${out} ${rest.join(' ')}` : out;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* One pino call as a record: the message is the body, child bindings and the merge object become dotted
|
|
46
|
+
* attributes, `err` becomes `exception.*`. Pure.
|
|
47
|
+
*/
|
|
48
|
+
export function fromPinoEvent(event, omit = new Set()) {
|
|
49
|
+
const attributes = {};
|
|
50
|
+
const add = (fields) => {
|
|
51
|
+
const kept = {};
|
|
52
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
53
|
+
if (!omit.has(key) && key !== 'msg' && key !== 'level' && key !== 'time')
|
|
54
|
+
kept[key] = value;
|
|
55
|
+
}
|
|
56
|
+
flattenInto(attributes, '', kept);
|
|
57
|
+
};
|
|
58
|
+
for (const binding of event.bindings)
|
|
59
|
+
if (binding && typeof binding === 'object')
|
|
60
|
+
add(binding);
|
|
61
|
+
const args = [...event.messages];
|
|
62
|
+
let message = '';
|
|
63
|
+
let error;
|
|
64
|
+
const first = args[0];
|
|
65
|
+
if (first instanceof Error) {
|
|
66
|
+
error = args.shift();
|
|
67
|
+
}
|
|
68
|
+
else if (first && typeof first === 'object') {
|
|
69
|
+
const fields = args.shift();
|
|
70
|
+
if (typeof fields.msg === 'string')
|
|
71
|
+
message = fields.msg;
|
|
72
|
+
add(fields);
|
|
73
|
+
}
|
|
74
|
+
if (typeof args[0] === 'string')
|
|
75
|
+
message = format(args.shift(), args);
|
|
76
|
+
if (error !== undefined) {
|
|
77
|
+
Object.assign(attributes, exceptionAttributes(error));
|
|
78
|
+
if (!message)
|
|
79
|
+
message = error instanceof Error ? error.message : String(error);
|
|
80
|
+
}
|
|
81
|
+
return { severity: severityOf(event.level.label), message, attributes, time: timeOf(event.ts) };
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The `browser.transmit` value for pino: each call becomes one houston log record, correlated with the active
|
|
85
|
+
* span. Pair it with `browser: { asObject: true }` and pino's `stdSerializers.err` for `err`. Never throws.
|
|
86
|
+
*/
|
|
87
|
+
export function pinoTransmit(houston, options = {}) {
|
|
88
|
+
const omit = new Set(options.omit ?? []);
|
|
89
|
+
return {
|
|
90
|
+
...(options.level && { level: options.level }),
|
|
91
|
+
send(_level, event) {
|
|
92
|
+
try {
|
|
93
|
+
const h = typeof houston === 'function' ? houston() : houston;
|
|
94
|
+
if (!h.enabled)
|
|
95
|
+
return;
|
|
96
|
+
const record = fromPinoEvent(event, omit);
|
|
97
|
+
h.log.emit(record.severity, record.message, record.attributes, { time: record.time });
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// a log line never throws into the code that wrote it
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** What a statement is: an ordinary one, transaction control (`BEGIN`, `COMMIT`, …), or a setting (`SET`, `set_config`). */
|
|
2
|
+
export type SqlSummary = {
|
|
3
|
+
kind: 'statement';
|
|
4
|
+
operation?: string;
|
|
5
|
+
collection?: string;
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'transaction';
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'setting';
|
|
10
|
+
name?: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* `text` with every literal replaced by `?` and comments dropped, at most `max` characters
|
|
14
|
+
* (an ellipsis marks a cut). Placeholders (`$1`), identifiers, keywords and operators stay.
|
|
15
|
+
*/
|
|
16
|
+
export declare function redactSql(text: string, max?: number): string;
|
|
17
|
+
/** The operation, the first table it names, or what kind of non-statement it is. */
|
|
18
|
+
export declare function summarizeSql(text: string): SqlSummary;
|
|
19
|
+
/**
|
|
20
|
+
* A database error's message with the values it may quote removed: every single-quoted run, a
|
|
21
|
+
* double-quoted run after a colon (`invalid input syntax for type uuid: "…"`), and anything from
|
|
22
|
+
* a `params:` line on (an ORM's wrapper may append the bound values). Identifiers in double
|
|
23
|
+
* quotes elsewhere (`relation "orders" does not exist`) stay.
|
|
24
|
+
*/
|
|
25
|
+
export declare function redactErrorMessage(message: string, max?: number): string;
|