@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
package/dist/hono.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { matchedRoutes } from 'hono/route';
|
|
2
|
+
import { errorMessage } from './attributes.js';
|
|
3
|
+
import { failServerSpan, finishServerSpan, startServerSpan } from './http.js';
|
|
4
|
+
/**
|
|
5
|
+
* The route pattern the request matched, e.g. `/api/posts/:id`: the first handler (one parameter; a middleware
|
|
6
|
+
* takes two) at or after the deepest dispatched index, so a request a middleware refused (a 400, a 401, a thrown
|
|
7
|
+
* 500) still names its route. Undefined when no handler matched (a 404).
|
|
8
|
+
*/
|
|
9
|
+
export function routeOf(c) {
|
|
10
|
+
const routes = matchedRoutes(c);
|
|
11
|
+
for (let i = Math.max(0, c.req.routeIndex); i < routes.length; i++) {
|
|
12
|
+
if (routes[i].handler.length < 2)
|
|
13
|
+
return routes[i].path;
|
|
14
|
+
}
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
function waitUntilOf(c) {
|
|
18
|
+
try {
|
|
19
|
+
const ctx = c.executionCtx;
|
|
20
|
+
return (p) => ctx.waitUntil(p);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined; // no execution context (a test's app.request)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function finish(c, houston, span, options) {
|
|
27
|
+
const status = c.res.status;
|
|
28
|
+
const route = routeOf(c);
|
|
29
|
+
finishServerSpan(span, c.req.method, route, status, c.error);
|
|
30
|
+
if (options.attributes) {
|
|
31
|
+
try {
|
|
32
|
+
span.setAttributes(options.attributes(c));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// best effort
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (status >= 500 && c.error && options.logErrors !== false) {
|
|
39
|
+
houston.log.error(errorMessage(c.error), { 'http.request.method': c.req.method, 'http.route': route, 'http.response.status_code': status }, c.error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The request-span middleware. Mount it first (before a request logger) so every log line, including what
|
|
44
|
+
* `onError` logs, falls inside the span. `houston` may be a function of the context, to build it from `c.env`.
|
|
45
|
+
* A 5xx (returned or thrown) sets ERROR, a thrown error is also an `exception` event. A streaming body that
|
|
46
|
+
* outlives `next()` isn't covered by the span; its records go out with the next flush.
|
|
47
|
+
*/
|
|
48
|
+
export function houstonMiddleware(houston, options = {}) {
|
|
49
|
+
return async (c, next) => {
|
|
50
|
+
const h = typeof houston === 'function' ? houston(c) : houston;
|
|
51
|
+
if (!h.enabled || options.ignore?.(c))
|
|
52
|
+
return next();
|
|
53
|
+
await h.run(async () => {
|
|
54
|
+
const span = startServerSpan(h, c.req.raw);
|
|
55
|
+
let thrown = false;
|
|
56
|
+
try {
|
|
57
|
+
await h.withSpan(span, next);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// only when the app's own error handling rethrows; the runtime answers 500
|
|
61
|
+
thrown = true;
|
|
62
|
+
failServerSpan(span, error);
|
|
63
|
+
if (options.logErrors !== false)
|
|
64
|
+
h.withSpan(span, () => h.log.error(errorMessage(error), {}, error));
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
if (!thrown) {
|
|
69
|
+
try {
|
|
70
|
+
h.withSpan(span, () => finish(c, h, span, options));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// telemetry never changes the response
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
span.end();
|
|
77
|
+
}
|
|
78
|
+
}, { waitUntil: waitUntilOf(c) });
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { type SpanContext } from './ids.js';
|
|
2
|
+
import { type Attributes, type AttributeValue, type SeverityName, type SpanData, type SpanKindName, type SpanStatusCode } from './otlp.js';
|
|
3
|
+
/** `telemetry.sdk.name` and the instrumentation scope name. */
|
|
4
|
+
export declare const SDK_NAME = "@rocketflare/houston-otel";
|
|
5
|
+
/** `telemetry.sdk.version`; kept equal to package.json's version by a test. */
|
|
6
|
+
export declare const SDK_VERSION = "0.1.0";
|
|
7
|
+
/** What `createHouston` needs. `houstonOptionsFromEnv` builds it from a Worker's env. */
|
|
8
|
+
export interface HoustonOptions {
|
|
9
|
+
/** houston's origin, e.g. `https://houston.example.com`; `/v1/logs` and `/v1/traces` are appended. */
|
|
10
|
+
endpoint: string;
|
|
11
|
+
/** A houston ingest key, sent as `Authorization: Bearer …`. */
|
|
12
|
+
apiKey: string;
|
|
13
|
+
/** `service.name`: what houston groups, colours and filters by. */
|
|
14
|
+
serviceName: string;
|
|
15
|
+
/** `service.version`, e.g. the deployed commit or Worker version id. */
|
|
16
|
+
serviceVersion?: string;
|
|
17
|
+
/** `deployment.environment.name`, e.g. `production`. */
|
|
18
|
+
environment?: string;
|
|
19
|
+
/** Extra resource attributes on every record. */
|
|
20
|
+
resource?: Attributes;
|
|
21
|
+
/** `false` gives the disabled instance even with an endpoint and key. Default true. */
|
|
22
|
+
enabled?: boolean;
|
|
23
|
+
/** Whether `./sql` sends `db.query.text` (redacted) when an adapter isn't told. Default true. */
|
|
24
|
+
dbQueryText?: boolean;
|
|
25
|
+
/** Log records below this are dropped. Default `trace` (everything). */
|
|
26
|
+
minSeverity?: SeverityName;
|
|
27
|
+
/** Records per POST. Default 500. */
|
|
28
|
+
maxBatchSize?: number;
|
|
29
|
+
/** Records one invocation (and the backlog) may hold; more are dropped. Default 5000. */
|
|
30
|
+
maxQueueSize?: number;
|
|
31
|
+
/** Timeout per POST in ms. Default 10 000. */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** For tests and proxies; defaults to the global `fetch`. */
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
/** Told about every failed export (the records are dropped). Must not log through houston itself. */
|
|
36
|
+
onExportError?: (error: unknown, signal: 'logs' | 'traces') => void;
|
|
37
|
+
}
|
|
38
|
+
/** How `startSpan` places and describes a new span. */
|
|
39
|
+
export interface StartSpanOptions {
|
|
40
|
+
/** Default `internal`. */
|
|
41
|
+
kind?: SpanKindName;
|
|
42
|
+
attributes?: Attributes;
|
|
43
|
+
/** Epoch ms; defaults to now. */
|
|
44
|
+
startTime?: number;
|
|
45
|
+
/** The parent: a span or span context, a `traceparent` value, or `null` for a new trace. Defaults to the active span. */
|
|
46
|
+
parent?: SpanContext | string | null;
|
|
47
|
+
}
|
|
48
|
+
/** A span being recorded. Every method is safe after `end()` (it does nothing). */
|
|
49
|
+
export interface Span {
|
|
50
|
+
readonly traceId: string;
|
|
51
|
+
readonly spanId: string;
|
|
52
|
+
/** False for the disabled instance's spans and once ended. */
|
|
53
|
+
readonly isRecording: boolean;
|
|
54
|
+
setAttribute(key: string, value: AttributeValue | null | undefined): Span;
|
|
55
|
+
setAttributes(attributes: Attributes): Span;
|
|
56
|
+
addEvent(name: string, attributes?: Attributes, time?: number): Span;
|
|
57
|
+
/** An `exception` event with `exception.type`, `.message` and `.stacktrace`. Does not set the status. */
|
|
58
|
+
recordException(error: unknown): Span;
|
|
59
|
+
setStatus(status: SpanStatusCode, message?: string): Span;
|
|
60
|
+
updateName(name: string): Span;
|
|
61
|
+
/** Records the span. Idempotent: only the first call counts. */
|
|
62
|
+
end(endTime?: number): void;
|
|
63
|
+
}
|
|
64
|
+
/** Structured log records, correlated with the active span. */
|
|
65
|
+
export interface Logger {
|
|
66
|
+
trace(message: string, attributes?: Attributes): void;
|
|
67
|
+
debug(message: string, attributes?: Attributes): void;
|
|
68
|
+
info(message: string, attributes?: Attributes): void;
|
|
69
|
+
warn(message: string, attributes?: Attributes, error?: unknown): void;
|
|
70
|
+
error(message: string, attributes?: Attributes, error?: unknown): void;
|
|
71
|
+
fatal(message: string, attributes?: Attributes, error?: unknown): void;
|
|
72
|
+
/** The general form: `time` (epoch ms) defaults to now, `error` adds `exception.*`. */
|
|
73
|
+
emit(severity: SeverityName, message: string, attributes?: Attributes, options?: {
|
|
74
|
+
time?: number;
|
|
75
|
+
error?: unknown;
|
|
76
|
+
eventName?: string;
|
|
77
|
+
}): void;
|
|
78
|
+
/** A logger whose records all carry `attributes`. */
|
|
79
|
+
child(attributes: Attributes): Logger;
|
|
80
|
+
}
|
|
81
|
+
/** How `run` hands off its flush. */
|
|
82
|
+
export interface RunOptions {
|
|
83
|
+
/** `ctx.waitUntil` (bound): the flush is handed to it. Omitted, the flush is awaited before `run` settles. */
|
|
84
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
85
|
+
}
|
|
86
|
+
/** One Worker's telemetry. Every method is safe to call anywhere and never throws because of export. */
|
|
87
|
+
export interface Houston {
|
|
88
|
+
/** False when there is no endpoint or key (or `enabled: false`): everything is a no-op and nothing is fetched. */
|
|
89
|
+
readonly enabled: boolean;
|
|
90
|
+
/** `HoustonOptions.dbQueryText`: the default for `./sql`'s `queryText`. */
|
|
91
|
+
readonly dbQueryText: boolean;
|
|
92
|
+
readonly log: Logger;
|
|
93
|
+
/** A span, child of the active one unless `parent` says otherwise. It becomes active only inside `withSpan`. */
|
|
94
|
+
startSpan(name: string, options?: StartSpanOptions): Span;
|
|
95
|
+
/** Run `fn` with `span` active, so logs and child spans inside it attach to it. */
|
|
96
|
+
withSpan<T>(span: Span, fn: () => T): T;
|
|
97
|
+
/** Start a span, make it active for `fn` and end it; a throw is recorded, sets ERROR and is rethrown. */
|
|
98
|
+
span<T>(name: string, fn: (span: Span) => Promise<T> | T, options?: StartSpanOptions): Promise<T>;
|
|
99
|
+
activeSpan(): Span | undefined;
|
|
100
|
+
/** The active span as a `traceparent` value, for an outbound call or a workflow payload. */
|
|
101
|
+
traceparent(): string | undefined;
|
|
102
|
+
/** One invocation (a request, cron tick, queue batch or workflow step): what `fn` records is sent when it settles. */
|
|
103
|
+
run<T>(fn: () => Promise<T> | T, options?: RunOptions): Promise<T>;
|
|
104
|
+
/** Send what the active invocation (or, outside one, the backlog) holds now. Never rejects. */
|
|
105
|
+
flush(): Promise<void>;
|
|
106
|
+
/** Send finished spans recorded elsewhere (another tracer), now. Never rejects. */
|
|
107
|
+
exportSpans(spans: SpanData[]): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
/** The disabled instance: the same API, records nothing, sends nothing. */
|
|
110
|
+
export declare const disabledHouston: Houston;
|
|
111
|
+
/** The resource every record carries: the `service.*` and `deployment.environment.name` keys houston promotes. */
|
|
112
|
+
export declare function resourceAttributes(options: HoustonOptions): Attributes;
|
|
113
|
+
/**
|
|
114
|
+
* One Worker's telemetry. With no options, no endpoint or key, or `enabled: false`, this is `disabledHouston`.
|
|
115
|
+
* Create it once per isolate (module scope or memoised per env) and wrap each invocation in `run`.
|
|
116
|
+
*/
|
|
117
|
+
export declare function createHouston(options: HoustonOptions | null | undefined): Houston;
|
|
118
|
+
/**
|
|
119
|
+
* `HoustonOptions` from a Worker's env, or null (off) unless both `HOUSTON_OTLP_ENDPOINT` and `HOUSTON_API_KEY`
|
|
120
|
+
* are set. `HOUSTON_ENABLED=false` (or `0`, `off`) turns it off with both set. `HOUSTON_SERVICE_NAME`,
|
|
121
|
+
* `HOUSTON_SERVICE_VERSION` and `HOUSTON_ENVIRONMENT` override `defaults`; the version falls back to a
|
|
122
|
+
* `CF_VERSION_METADATA` binding's id when there is one. `HOUSTON_DB_QUERY_TEXT=false` keeps SQL text out.
|
|
123
|
+
*/
|
|
124
|
+
export declare function houstonOptionsFromEnv(env: object, defaults?: Partial<Omit<HoustonOptions, 'endpoint' | 'apiKey'>>): HoustonOptions | null;
|
package/dist/houston.js
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
// `createHouston(options)`: logs and spans for one Worker, posted to houston as OTLP/HTTP JSON at the end of each
|
|
2
|
+
// invocation (`run`), in `waitUntil`. The active span and invocation ride AsyncLocalStorage (`nodejs_compat`).
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
import { errorMessage, exceptionAttributes, flattenInto, truncate } from './attributes.js';
|
|
5
|
+
import { formatTraceparent, isSpanId, isTraceId, newSpanId, newTraceId, parseTraceparent } from './ids.js';
|
|
6
|
+
import { logsRequest, SEVERITY_NUMBER, tracesRequest, } from './otlp.js';
|
|
7
|
+
/** `telemetry.sdk.name` and the instrumentation scope name. */
|
|
8
|
+
export const SDK_NAME = '@rocketflare/houston-otel';
|
|
9
|
+
/** `telemetry.sdk.version`; kept equal to package.json's version by a test. */
|
|
10
|
+
export const SDK_VERSION = '0.1.0';
|
|
11
|
+
const DEFAULTS = { maxBatchSize: 500, maxQueueSize: 5_000, timeoutMs: 10_000 };
|
|
12
|
+
const ZERO_TRACE = '0'.repeat(32);
|
|
13
|
+
const ZERO_SPAN = '0'.repeat(16);
|
|
14
|
+
const noopSpan = {
|
|
15
|
+
traceId: ZERO_TRACE,
|
|
16
|
+
spanId: ZERO_SPAN,
|
|
17
|
+
isRecording: false,
|
|
18
|
+
setAttribute: () => noopSpan,
|
|
19
|
+
setAttributes: () => noopSpan,
|
|
20
|
+
addEvent: () => noopSpan,
|
|
21
|
+
recordException: () => noopSpan,
|
|
22
|
+
setStatus: () => noopSpan,
|
|
23
|
+
updateName: () => noopSpan,
|
|
24
|
+
end() { },
|
|
25
|
+
};
|
|
26
|
+
const noopLogger = {
|
|
27
|
+
trace() { },
|
|
28
|
+
debug() { },
|
|
29
|
+
info() { },
|
|
30
|
+
warn() { },
|
|
31
|
+
error() { },
|
|
32
|
+
fatal() { },
|
|
33
|
+
emit() { },
|
|
34
|
+
child: () => noopLogger,
|
|
35
|
+
};
|
|
36
|
+
/** The disabled instance: the same API, records nothing, sends nothing. */
|
|
37
|
+
export const disabledHouston = {
|
|
38
|
+
enabled: false,
|
|
39
|
+
dbQueryText: false,
|
|
40
|
+
log: noopLogger,
|
|
41
|
+
startSpan: () => noopSpan,
|
|
42
|
+
withSpan: (_span, fn) => fn(),
|
|
43
|
+
span: async (_name, fn) => fn(noopSpan),
|
|
44
|
+
activeSpan: () => undefined,
|
|
45
|
+
traceparent: () => undefined,
|
|
46
|
+
run: async (fn) => fn(),
|
|
47
|
+
flush: async () => { },
|
|
48
|
+
exportSpans: async () => { },
|
|
49
|
+
};
|
|
50
|
+
/** The resource every record carries: the `service.*` and `deployment.environment.name` keys houston promotes. */
|
|
51
|
+
export function resourceAttributes(options) {
|
|
52
|
+
return {
|
|
53
|
+
'service.name': options.serviceName,
|
|
54
|
+
'service.version': options.serviceVersion,
|
|
55
|
+
'deployment.environment.name': options.environment,
|
|
56
|
+
'telemetry.sdk.name': SDK_NAME,
|
|
57
|
+
'telemetry.sdk.version': SDK_VERSION,
|
|
58
|
+
'telemetry.sdk.language': 'webjs',
|
|
59
|
+
'cloud.provider': 'cloudflare',
|
|
60
|
+
'cloud.platform': 'cloudflare.workers',
|
|
61
|
+
...options.resource,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function resolveParent(parent, active) {
|
|
65
|
+
if (parent === null)
|
|
66
|
+
return null;
|
|
67
|
+
if (typeof parent === 'string')
|
|
68
|
+
return parseTraceparent(parent);
|
|
69
|
+
if (parent)
|
|
70
|
+
return isTraceId(parent.traceId) && isSpanId(parent.spanId) ? { traceId: parent.traceId, spanId: parent.spanId } : null;
|
|
71
|
+
return active && active.traceId !== ZERO_TRACE ? active : null;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* One Worker's telemetry. With no options, no endpoint or key, or `enabled: false`, this is `disabledHouston`.
|
|
75
|
+
* Create it once per isolate (module scope or memoised per env) and wrap each invocation in `run`.
|
|
76
|
+
*/
|
|
77
|
+
export function createHouston(options) {
|
|
78
|
+
if (!options?.endpoint || !options.apiKey || options.enabled === false)
|
|
79
|
+
return disabledHouston;
|
|
80
|
+
const base = options.endpoint.replace(/\/+$/, '');
|
|
81
|
+
const resource = resourceAttributes(options);
|
|
82
|
+
const scope = { name: SDK_NAME, version: SDK_VERSION };
|
|
83
|
+
const maxBatchSize = Math.max(1, options.maxBatchSize ?? DEFAULTS.maxBatchSize);
|
|
84
|
+
const maxQueueSize = Math.max(1, options.maxQueueSize ?? DEFAULTS.maxQueueSize);
|
|
85
|
+
const timeoutMs = options.timeoutMs ?? DEFAULTS.timeoutMs;
|
|
86
|
+
const minSeverity = SEVERITY_NUMBER[options.minSeverity ?? 'trace'];
|
|
87
|
+
const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
88
|
+
const store = new AsyncLocalStorage();
|
|
89
|
+
const backlog = { logs: [], spans: [], closed: false };
|
|
90
|
+
const reportError = (error, signal) => {
|
|
91
|
+
try {
|
|
92
|
+
options.onExportError?.(error, signal);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// a reporter that throws is not an export failure
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
// A record goes to the invocation it was made in, or to the backlog once that has flushed.
|
|
99
|
+
const target = (batch) => (batch && !batch.closed ? batch : backlog);
|
|
100
|
+
const room = (b) => b.logs.length + b.spans.length < maxQueueSize;
|
|
101
|
+
const pushLog = (batch, log) => {
|
|
102
|
+
const into = target(batch);
|
|
103
|
+
if (room(into))
|
|
104
|
+
into.logs.push(log);
|
|
105
|
+
};
|
|
106
|
+
const pushSpan = (batch, span) => {
|
|
107
|
+
const into = target(batch);
|
|
108
|
+
if (room(into))
|
|
109
|
+
into.spans.push(span);
|
|
110
|
+
};
|
|
111
|
+
const post = async (signal, body) => {
|
|
112
|
+
try {
|
|
113
|
+
const res = await fetchImpl(`${base}/v1/${signal}`, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${options.apiKey}` },
|
|
116
|
+
body: JSON.stringify(body),
|
|
117
|
+
signal: typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined,
|
|
118
|
+
});
|
|
119
|
+
if (!res.ok) {
|
|
120
|
+
const text = await res.text().catch(() => '');
|
|
121
|
+
reportError(new Error(`houston ${signal}: HTTP ${res.status} ${truncate(text, 200)}`), signal);
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
await res.body?.cancel().catch(() => { }); // release the connection
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
reportError(error, signal);
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
const chunks = (items) => {
|
|
132
|
+
const out = [];
|
|
133
|
+
for (let i = 0; i < items.length; i += maxBatchSize)
|
|
134
|
+
out.push(items.slice(i, i + maxBatchSize));
|
|
135
|
+
return out;
|
|
136
|
+
};
|
|
137
|
+
const send = async (logs, spans) => {
|
|
138
|
+
const posts = [];
|
|
139
|
+
for (const chunk of chunks(logs))
|
|
140
|
+
posts.push(post('logs', logsRequest(chunk, resource, scope)));
|
|
141
|
+
for (const chunk of chunks(spans))
|
|
142
|
+
posts.push(post('traces', tracesRequest(chunk, resource, scope)));
|
|
143
|
+
await Promise.all(posts);
|
|
144
|
+
};
|
|
145
|
+
const drain = (batch) => {
|
|
146
|
+
const logs = batch.logs.splice(0);
|
|
147
|
+
const spans = batch.spans.splice(0);
|
|
148
|
+
if (batch !== backlog) {
|
|
149
|
+
logs.push(...backlog.logs.splice(0));
|
|
150
|
+
spans.push(...backlog.spans.splice(0));
|
|
151
|
+
}
|
|
152
|
+
if (logs.length === 0 && spans.length === 0)
|
|
153
|
+
return Promise.resolve();
|
|
154
|
+
return send(logs, spans).catch(() => { });
|
|
155
|
+
};
|
|
156
|
+
const makeSpan = (name, startOptions = {}) => {
|
|
157
|
+
const current = store.getStore();
|
|
158
|
+
const batch = current?.batch;
|
|
159
|
+
const parent = resolveParent(startOptions.parent, current?.span);
|
|
160
|
+
const data = {
|
|
161
|
+
traceId: parent?.traceId ?? newTraceId(),
|
|
162
|
+
spanId: newSpanId(),
|
|
163
|
+
...(parent && { parentSpanId: parent.spanId }),
|
|
164
|
+
name,
|
|
165
|
+
kind: startOptions.kind ?? 'internal',
|
|
166
|
+
startTime: startOptions.startTime ?? Date.now(),
|
|
167
|
+
endTime: 0,
|
|
168
|
+
status: 'unset',
|
|
169
|
+
attributes: { ...startOptions.attributes },
|
|
170
|
+
events: [],
|
|
171
|
+
};
|
|
172
|
+
let ended = false;
|
|
173
|
+
const span = {
|
|
174
|
+
traceId: data.traceId,
|
|
175
|
+
spanId: data.spanId,
|
|
176
|
+
get isRecording() {
|
|
177
|
+
return !ended;
|
|
178
|
+
},
|
|
179
|
+
setAttribute(key, value) {
|
|
180
|
+
if (!ended)
|
|
181
|
+
data.attributes[key] = value;
|
|
182
|
+
return span;
|
|
183
|
+
},
|
|
184
|
+
setAttributes(attributes) {
|
|
185
|
+
if (!ended)
|
|
186
|
+
Object.assign(data.attributes, attributes);
|
|
187
|
+
return span;
|
|
188
|
+
},
|
|
189
|
+
addEvent(eventName, attributes = {}, time = Date.now()) {
|
|
190
|
+
if (!ended)
|
|
191
|
+
data.events.push({ name: eventName, time, attributes });
|
|
192
|
+
return span;
|
|
193
|
+
},
|
|
194
|
+
recordException(error) {
|
|
195
|
+
return span.addEvent('exception', exceptionAttributes(error));
|
|
196
|
+
},
|
|
197
|
+
setStatus(status, message) {
|
|
198
|
+
if (ended)
|
|
199
|
+
return span;
|
|
200
|
+
data.status = status;
|
|
201
|
+
data.statusMessage = status === 'error' ? message : undefined;
|
|
202
|
+
return span;
|
|
203
|
+
},
|
|
204
|
+
updateName(next) {
|
|
205
|
+
if (!ended)
|
|
206
|
+
data.name = next;
|
|
207
|
+
return span;
|
|
208
|
+
},
|
|
209
|
+
end(endTime) {
|
|
210
|
+
if (ended)
|
|
211
|
+
return;
|
|
212
|
+
ended = true;
|
|
213
|
+
data.endTime = endTime ?? Date.now();
|
|
214
|
+
pushSpan(batch, data);
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
return span;
|
|
218
|
+
};
|
|
219
|
+
const emit = (severity, message, attributes, emitOptions = {}) => {
|
|
220
|
+
if (SEVERITY_NUMBER[severity] < minSeverity)
|
|
221
|
+
return;
|
|
222
|
+
const current = store.getStore();
|
|
223
|
+
const span = current?.span;
|
|
224
|
+
pushLog(current?.batch, {
|
|
225
|
+
time: emitOptions.time ?? Date.now(),
|
|
226
|
+
severity,
|
|
227
|
+
body: truncate(message, 32_000),
|
|
228
|
+
attributes: { ...plain(attributes), ...(emitOptions.error !== undefined && exceptionAttributes(emitOptions.error)) },
|
|
229
|
+
...(span && span.traceId !== ZERO_TRACE && { traceId: span.traceId, spanId: span.spanId }),
|
|
230
|
+
...(emitOptions.eventName && { eventName: emitOptions.eventName }),
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
const loggerWith = (bound) => {
|
|
234
|
+
const at = (severity) => (message, attributes, error) => emit(severity, message, { ...bound, ...attributes }, { error });
|
|
235
|
+
return {
|
|
236
|
+
trace: at('trace'),
|
|
237
|
+
debug: at('debug'),
|
|
238
|
+
info: at('info'),
|
|
239
|
+
warn: at('warn'),
|
|
240
|
+
error: at('error'),
|
|
241
|
+
fatal: at('fatal'),
|
|
242
|
+
emit: (severity, message, attributes, emitOptions) => emit(severity, message, { ...bound, ...attributes }, emitOptions),
|
|
243
|
+
child: (attributes) => loggerWith({ ...bound, ...attributes }),
|
|
244
|
+
};
|
|
245
|
+
};
|
|
246
|
+
const withSpan = (span, fn) => store.run({ batch: store.getStore()?.batch, span }, fn);
|
|
247
|
+
return {
|
|
248
|
+
enabled: true,
|
|
249
|
+
dbQueryText: options.dbQueryText !== false,
|
|
250
|
+
log: loggerWith({}),
|
|
251
|
+
startSpan: makeSpan,
|
|
252
|
+
withSpan,
|
|
253
|
+
async span(name, fn, startOptions) {
|
|
254
|
+
const span = makeSpan(name, startOptions);
|
|
255
|
+
try {
|
|
256
|
+
return await withSpan(span, () => fn(span));
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
span.recordException(error);
|
|
260
|
+
span.setStatus('error', errorMessage(error));
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
span.end();
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
activeSpan: () => store.getStore()?.span,
|
|
268
|
+
traceparent() {
|
|
269
|
+
const span = store.getStore()?.span;
|
|
270
|
+
return span && span.traceId !== ZERO_TRACE ? formatTraceparent(span) : undefined;
|
|
271
|
+
},
|
|
272
|
+
async run(fn, runOptions = {}) {
|
|
273
|
+
const batch = { logs: [], spans: [], closed: false };
|
|
274
|
+
const finish = () => {
|
|
275
|
+
batch.closed = true;
|
|
276
|
+
const flushing = drain(batch);
|
|
277
|
+
if (runOptions.waitUntil) {
|
|
278
|
+
try {
|
|
279
|
+
runOptions.waitUntil(flushing);
|
|
280
|
+
return Promise.resolve();
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
// no usable waitUntil: await it instead
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return flushing;
|
|
287
|
+
};
|
|
288
|
+
try {
|
|
289
|
+
return await store.run({ batch, span: store.getStore()?.span }, fn);
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
await finish();
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
flush() {
|
|
296
|
+
const batch = store.getStore()?.batch;
|
|
297
|
+
return drain(batch && !batch.closed ? batch : backlog);
|
|
298
|
+
},
|
|
299
|
+
exportSpans(spans) {
|
|
300
|
+
if (spans.length === 0)
|
|
301
|
+
return Promise.resolve();
|
|
302
|
+
return send([], spans).catch(() => { });
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/** Attributes as given, with any object an untyped caller put in flattened (`err` → `exception.*`). */
|
|
307
|
+
function plain(attributes) {
|
|
308
|
+
if (!attributes)
|
|
309
|
+
return attributes;
|
|
310
|
+
const values = Object.values(attributes);
|
|
311
|
+
if (!values.some((v) => v !== null && typeof v === 'object' && !Array.isArray(v)))
|
|
312
|
+
return attributes;
|
|
313
|
+
const out = {};
|
|
314
|
+
flattenInto(out, '', attributes);
|
|
315
|
+
return out;
|
|
316
|
+
}
|
|
317
|
+
const OFF = /^(?:0|false|off|no|disabled?)$/i;
|
|
318
|
+
/**
|
|
319
|
+
* `HoustonOptions` from a Worker's env, or null (off) unless both `HOUSTON_OTLP_ENDPOINT` and `HOUSTON_API_KEY`
|
|
320
|
+
* are set. `HOUSTON_ENABLED=false` (or `0`, `off`) turns it off with both set. `HOUSTON_SERVICE_NAME`,
|
|
321
|
+
* `HOUSTON_SERVICE_VERSION` and `HOUSTON_ENVIRONMENT` override `defaults`; the version falls back to a
|
|
322
|
+
* `CF_VERSION_METADATA` binding's id when there is one. `HOUSTON_DB_QUERY_TEXT=false` keeps SQL text out.
|
|
323
|
+
*/
|
|
324
|
+
export function houstonOptionsFromEnv(env, defaults = {}) {
|
|
325
|
+
const vars = env;
|
|
326
|
+
const str = (key) => {
|
|
327
|
+
const value = vars[key];
|
|
328
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
|
329
|
+
};
|
|
330
|
+
const endpoint = str('HOUSTON_OTLP_ENDPOINT');
|
|
331
|
+
const apiKey = str('HOUSTON_API_KEY');
|
|
332
|
+
const enabled = str('HOUSTON_ENABLED');
|
|
333
|
+
if (!endpoint || !apiKey || (enabled && OFF.test(enabled)))
|
|
334
|
+
return null;
|
|
335
|
+
const metadata = vars.CF_VERSION_METADATA;
|
|
336
|
+
const versionId = typeof metadata?.id === 'string' && metadata.id ? metadata.id : undefined;
|
|
337
|
+
const options = {
|
|
338
|
+
...defaults,
|
|
339
|
+
endpoint,
|
|
340
|
+
apiKey,
|
|
341
|
+
serviceName: str('HOUSTON_SERVICE_NAME') ?? defaults.serviceName ?? 'unknown_service',
|
|
342
|
+
};
|
|
343
|
+
const serviceVersion = str('HOUSTON_SERVICE_VERSION') ?? defaults.serviceVersion ?? versionId;
|
|
344
|
+
const environment = str('HOUSTON_ENVIRONMENT') ?? defaults.environment;
|
|
345
|
+
const queryText = str('HOUSTON_DB_QUERY_TEXT');
|
|
346
|
+
if (queryText)
|
|
347
|
+
options.dbQueryText = !OFF.test(queryText);
|
|
348
|
+
if (serviceVersion)
|
|
349
|
+
options.serviceVersion = serviceVersion;
|
|
350
|
+
if (environment)
|
|
351
|
+
options.environment = environment;
|
|
352
|
+
return options;
|
|
353
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Houston, Span } from './houston.js';
|
|
2
|
+
import type { Attributes } from './otlp.js';
|
|
3
|
+
export declare function requestAttributes(request: Request): Attributes;
|
|
4
|
+
export declare function startServerSpan(houston: Houston, request: Request): Span;
|
|
5
|
+
/** Name, route and status once the response exists; a 5xx is ERROR, `error` (if any) an `exception` event. */
|
|
6
|
+
export declare function finishServerSpan(span: Span, method: string, route: string | undefined, status: number, error?: unknown): void;
|
|
7
|
+
/** A handler threw: the runtime answers 500. */
|
|
8
|
+
export declare function failServerSpan(span: Span, error: unknown): void;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The SERVER span of an HTTP request, shared by the Hono middleware and `withRequest`: the request attributes
|
|
2
|
+
// houston promotes (`http.request.method`, later `http.route` and `http.response.status_code`) plus `url.*`.
|
|
3
|
+
import { errorMessage } from './attributes.js';
|
|
4
|
+
export function requestAttributes(request) {
|
|
5
|
+
const url = new URL(request.url);
|
|
6
|
+
return {
|
|
7
|
+
'http.request.method': request.method,
|
|
8
|
+
'url.path': url.pathname,
|
|
9
|
+
'url.scheme': url.protocol.replace(/:$/, ''),
|
|
10
|
+
'server.address': url.hostname,
|
|
11
|
+
'user_agent.original': request.headers.get('user-agent') ?? undefined,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function startServerSpan(houston, request) {
|
|
15
|
+
return houston.startSpan(request.method, {
|
|
16
|
+
kind: 'server',
|
|
17
|
+
parent: request.headers.get('traceparent') ?? undefined,
|
|
18
|
+
attributes: requestAttributes(request),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Name, route and status once the response exists; a 5xx is ERROR, `error` (if any) an `exception` event. */
|
|
22
|
+
export function finishServerSpan(span, method, route, status, error) {
|
|
23
|
+
span.updateName(route ? `${method} ${route}` : method);
|
|
24
|
+
span.setAttributes({ 'http.route': route, 'http.response.status_code': status });
|
|
25
|
+
if (error !== undefined)
|
|
26
|
+
span.recordException(error);
|
|
27
|
+
if (status >= 500)
|
|
28
|
+
span.setStatus('error', error !== undefined ? errorMessage(error) : `HTTP ${status}`);
|
|
29
|
+
}
|
|
30
|
+
/** A handler threw: the runtime answers 500. */
|
|
31
|
+
export function failServerSpan(span, error) {
|
|
32
|
+
span.recordException(error);
|
|
33
|
+
span.setStatus('error', errorMessage(error));
|
|
34
|
+
span.setAttribute('http.response.status_code', 500);
|
|
35
|
+
}
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** A random 16-byte trace id as 32 lowercase hex characters. */
|
|
2
|
+
export declare const newTraceId: () => string;
|
|
3
|
+
/** A random 8-byte span id as 16 lowercase hex characters. */
|
|
4
|
+
export declare const newSpanId: () => string;
|
|
5
|
+
/** True for 32 lowercase hex characters, not all zero. */
|
|
6
|
+
export declare const isTraceId: (id: string) => boolean;
|
|
7
|
+
/** True for 16 lowercase hex characters, not all zero. */
|
|
8
|
+
export declare const isSpanId: (id: string) => boolean;
|
|
9
|
+
/** The two ids that place a span in a trace: what a child needs from its parent. */
|
|
10
|
+
export interface SpanContext {
|
|
11
|
+
traceId: string;
|
|
12
|
+
spanId: string;
|
|
13
|
+
}
|
|
14
|
+
/** `00-<trace>-<span>-<flags>` → its ids; null for anything malformed or all-zero. */
|
|
15
|
+
export declare function parseTraceparent(header: string | null | undefined): SpanContext | null;
|
|
16
|
+
/** The `traceparent` header for an outbound call (or a workflow payload) so the callee joins this trace. */
|
|
17
|
+
export declare function formatTraceparent(span: SpanContext): string;
|
package/dist/ids.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Trace and span ids (lowercase hex, never all zero) and the W3C `traceparent` header.
|
|
2
|
+
function randomHex(bytes) {
|
|
3
|
+
const buf = new Uint8Array(bytes);
|
|
4
|
+
do
|
|
5
|
+
crypto.getRandomValues(buf);
|
|
6
|
+
while (buf.every((b) => b === 0));
|
|
7
|
+
let out = '';
|
|
8
|
+
for (const b of buf)
|
|
9
|
+
out += b.toString(16).padStart(2, '0');
|
|
10
|
+
return out;
|
|
11
|
+
}
|
|
12
|
+
/** A random 16-byte trace id as 32 lowercase hex characters. */
|
|
13
|
+
export const newTraceId = () => randomHex(16);
|
|
14
|
+
/** A random 8-byte span id as 16 lowercase hex characters. */
|
|
15
|
+
export const newSpanId = () => randomHex(8);
|
|
16
|
+
const TRACE_ID = /^[0-9a-f]{32}$/;
|
|
17
|
+
const SPAN_ID = /^[0-9a-f]{16}$/;
|
|
18
|
+
/** True for 32 lowercase hex characters, not all zero. */
|
|
19
|
+
export const isTraceId = (id) => TRACE_ID.test(id) && !/^0+$/.test(id);
|
|
20
|
+
/** True for 16 lowercase hex characters, not all zero. */
|
|
21
|
+
export const isSpanId = (id) => SPAN_ID.test(id) && !/^0+$/.test(id);
|
|
22
|
+
/** `00-<trace>-<span>-<flags>` → its ids; null for anything malformed or all-zero. */
|
|
23
|
+
export function parseTraceparent(header) {
|
|
24
|
+
if (!header)
|
|
25
|
+
return null;
|
|
26
|
+
const parts = header.trim().toLowerCase().split('-');
|
|
27
|
+
if (parts.length < 4 || parts[0] === 'ff' || !/^[0-9a-f]{2}$/.test(parts[0]))
|
|
28
|
+
return null;
|
|
29
|
+
const [, traceId, spanId] = parts;
|
|
30
|
+
return isTraceId(traceId) && isSpanId(spanId) ? { traceId, spanId } : null;
|
|
31
|
+
}
|
|
32
|
+
/** The `traceparent` header for an outbound call (or a workflow payload) so the callee joins this trace. */
|
|
33
|
+
export function formatTraceparent(span) {
|
|
34
|
+
return `00-${span.traceId}-${span.spanId}-01`;
|
|
35
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { errorMessage, exceptionAttributes, flatten } from './attributes.js';
|
|
2
|
+
export { createHouston, disabledHouston, type Houston, type HoustonOptions, houstonOptionsFromEnv, type Logger, type RunOptions, resourceAttributes, SDK_NAME, SDK_VERSION, type Span, type StartSpanOptions, } from './houston.js';
|
|
3
|
+
export { formatTraceparent, isSpanId, isTraceId, newSpanId, newTraceId, parseTraceparent, type SpanContext } from './ids.js';
|
|
4
|
+
export { type HoustonSource, type MessageBatchLike, type ScheduledLike, tracedStep, type WaitUntilContext, withQueue, withRequest, type WithRequestOptions, withScheduled, withStep, type WithStepOptions, type WorkflowStepLike, } from './invocations.js';
|
|
5
|
+
export { type Attributes, type AttributeValue, type LogData, logsRequest, type OtlpLogsRequest, type OtlpTracesRequest, SEVERITY_NUMBER, type SeverityName, type SpanData, type SpanEventData, type SpanKindName, type SpanStatusCode, tracesRequest, } from './otlp.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @rocketflare/houston-otel: logs and spans from a Cloudflare Worker to houston over OTLP/HTTP JSON. This entry has
|
|
2
|
+
// no dependencies; `./hono`, `./pino`, `./sql` and `./genai` are the integrations.
|
|
3
|
+
export { errorMessage, exceptionAttributes, flatten } from './attributes.js';
|
|
4
|
+
export { createHouston, disabledHouston, houstonOptionsFromEnv, resourceAttributes, SDK_NAME, SDK_VERSION, } from './houston.js';
|
|
5
|
+
export { formatTraceparent, isSpanId, isTraceId, newSpanId, newTraceId, parseTraceparent } from './ids.js';
|
|
6
|
+
export { tracedStep, withQueue, withRequest, withScheduled, withStep, } from './invocations.js';
|
|
7
|
+
export { logsRequest, SEVERITY_NUMBER, tracesRequest, } from './otlp.js';
|