@rocketflare/houston-otel 0.0.0-stage → 0.1.1

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 CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @rocketflare/houston-otel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Logs, request spans, SQL spans and `gen_ai` spans from Cloudflare Workers to
4
+ [houston](https://github.com/rocketflare-dev/houston), all in one trace per request. It speaks OTLP/HTTP JSON over
5
+ `fetch`, has no runtime dependencies (about 5 KB gzipped for the core), and sends everything in `waitUntil` after the
6
+ response.
7
+
8
+ ```sh
9
+ npm i @rocketflare/houston-otel
10
+ ```
11
+
12
+ Needs the `nodejs_compat` compatibility flag: the active span rides `AsyncLocalStorage` from `node:async_hooks`.
13
+
14
+ ## Quick start (Hono on Workers)
15
+
16
+ ```jsonc
17
+ // wrangler.jsonc
18
+ "compatibility_flags": ["nodejs_compat"],
19
+ "vars": { "HOUSTON_OTLP_ENDPOINT": "https://houston.example.com", "HOUSTON_SERVICE_NAME": "shop-api" }
20
+ // then: wrangler secret put HOUSTON_API_KEY (an ingest key from houston's /projects)
21
+ ```
22
+
23
+ ```ts
24
+ import { createHouston, houstonOptionsFromEnv, tracedStep, withStep } from '@rocketflare/houston-otel'
25
+ import { houstonMiddleware } from '@rocketflare/houston-otel/hono'
26
+ import { pinoTransmit } from '@rocketflare/houston-otel/pino'
27
+ import { instrumentNeonHttp } from '@rocketflare/houston-otel/sql'
28
+ import { traceGenAi } from '@rocketflare/houston-otel/genai'
29
+ import { neon } from '@neondatabase/serverless'
30
+ import { drizzle } from 'drizzle-orm/neon-http'
31
+ import { Hono } from 'hono'
32
+ import pino from 'pino'
33
+
34
+ let houston: ReturnType<typeof createHouston> | undefined
35
+ const houstonFor = (env: Env) => (houston ??= createHouston(houstonOptionsFromEnv(env, { environment: env.APP_ENV })))
36
+
37
+ const app = new Hono<{ Bindings: Env }>()
38
+ app.use('*', houstonMiddleware((c) => houstonFor(c.env))) // one SERVER span per request, flushed in waitUntil
39
+
40
+ app.get('/api/orders/:id', async (c) => {
41
+ const h = houstonFor(c.env)
42
+ const log = pino({ browser: { asObject: true, transmit: pinoTransmit(h) } })
43
+ const db = drizzle(instrumentNeonHttp(h, neon(c.env.DATABASE_URL))) // a CLIENT span per statement
44
+ const order = await db.query.orders.findFirst()
45
+ const reply = await traceGenAi(h, { provider: 'anthropic', model: 'model-a' }, () => callModel(order),
46
+ (r) => ({ inputTokens: r.usage.input, outputTokens: r.usage.output, finishReasons: [r.stop] }))
47
+ log.info({ order: order?.id }, 'summarised')
48
+ await c.env.SUMMARY.create({ params: { id: order?.id, traceparent: h.traceparent() } }) // a Workflow
49
+ return c.json(reply)
50
+ })
51
+ export default app
52
+ ```
53
+
54
+ In the Workflow, each step is its own invocation in the request's trace:
55
+
56
+ ```ts
57
+ async run(event, step) {
58
+ const s = tracedStep(houstonFor(this.env), step, { traceparent: event.payload.traceparent })
59
+ await s.do('notify', async () => { /* logs and SQL here land under `step notify` */ })
60
+ }
61
+ ```
62
+
63
+ Leave `HOUSTON_API_KEY` unset (or set `HOUSTON_ENABLED=false`) and every call is a no-op that never fetches.
64
+
65
+ ## What it does
66
+
67
+ - **One invocation at a time.** `houston.run(fn, { waitUntil })` covers a request, a cron tick, a queue batch or a
68
+ workflow step. What `fn` records stays in memory and goes out when `fn` settles: one POST per signal (chunked at 500
69
+ records), handed to `waitUntil`, or awaited when there's none. Records made outside any invocation wait in a capped
70
+ backlog for the next flush.
71
+ - **Never in your way.** Export never throws or rejects. Network errors, timeouts (10 s) and non-2xx answers go to
72
+ `onExportError`, and the records are dropped. Memory is capped at `maxQueueSize` (5000) records per invocation.
73
+ - **Correlated.** `houston.log.*`, pino lines and child spans anywhere below a span carry its trace and span id. An
74
+ incoming `traceparent` is continued, and `houston.traceparent()` gives you one to pass on.
75
+ - **The names houston promotes.** The resource has `service.name`, `service.version` and
76
+ `deployment.environment.name`. Request spans have `http.request.method`, `http.route` and `http.response.status_code`,
77
+ so houston filters, groups and alerts on them cheaply.
78
+
79
+ ### Entry points
80
+
81
+ | Import | What |
82
+ | --- | --- |
83
+ | `@rocketflare/houston-otel` | `createHouston`, `houstonOptionsFromEnv`, `disabledHouston`; `withRequest`, `withScheduled`, `withQueue`, `withStep`, `tracedStep`; `traceparent` helpers; the OTLP encoders |
84
+ | `/hono` | `houstonMiddleware(houston \| (c) => houston, { logErrors, ignore, attributes })`, `routeOf(c)` |
85
+ | `/pino` | `pinoTransmit(houston, { level, omit })` for pino's `browser.transmit` (the browser build a Worker bundle gets); `fromPinoEvent` |
86
+ | `/sql` | `traceQuery`, `traceTransaction`; `instrumentNeonHttp`, `instrumentPgPool`, `instrumentPgClient`, `instrumentPostgresJs`, `instrumentTransactions`; `redactSql`, `summarizeSql`, `redactErrorMessage`, `serverAddressOf`, `dbErrorAttributes` |
87
+ | `/genai` | `traceGenAi`, `recordGenAi`, `genAiSpanSink` (for an existing AI tracer), `genAiAttributes`, `isContentAttribute`, `toHoustonSpan` |
88
+
89
+ `hono` and `pino` are optional peer dependencies. Each is imported only by its own entry point.
90
+
91
+ ### Other handlers
92
+
93
+ ```ts
94
+ export default {
95
+ fetch: withRequest(houstonFor, handler), // without Hono: a SERVER span per request
96
+ scheduled: withScheduled(houstonFor, onCron), // a `cron <expression>` span per tick
97
+ queue: withQueue(houstonFor, onBatch), // a CONSUMER `process <queue>` span per batch
98
+ }
99
+ ```
100
+
101
+ Inside a workflow step, without `tracedStep`, use `step.do('x', () => withStep(h, 'x', fn, { traceparent }))`.
102
+
103
+ ### SQL
104
+
105
+ Each adapter wraps the driver's own query function, so the span times the real round trip. Drizzle's logger sees the
106
+ SQL but not how long it took. Wrap the client before you hand it to Drizzle.
107
+
108
+ | Driver | Adapter | Transactions |
109
+ | --- | --- | --- |
110
+ | `neon()` HTTP (`drizzle-orm/neon-http`) | `instrumentNeonHttp(h, sql)` | `sql.transaction([...])` (Drizzle's `db.batch`) is one span |
111
+ | Neon `Pool` (`drizzle-orm/neon-serverless`), node-postgres | `instrumentPgPool(h, pool)` | `BEGIN` … `COMMIT` on a pooled client is one span |
112
+ | Neon `Client`, a pg `Client` | `instrumentPgClient(h, client)` | the same |
113
+ | postgres.js (`drizzle-orm/postgres-js`) | `instrumentPostgresJs(h, sql)` | `sql.begin(...)` is one span |
114
+ | anything else | `traceQuery(h, { text, system }, run)`, `instrumentTransactions(h, db)` | `db.transaction` is one span |
115
+
116
+ Spans are named `<operation> <table>` (`SELECT orders`). They have `db.system.name`, `db.operation.name`,
117
+ `db.collection.name`, `db.query.summary`, `db.query.text`, `db.response.returned_rows` and `server.address`. A failure
118
+ sets status ERROR, adds `error.type` and `db.response.status_code` (the SQLSTATE), and records an `exception` event
119
+ with a redacted message and no stack.
120
+
121
+ `BEGIN`, `COMMIT`, `ROLLBACK` and savepoints get no span. Settings (`SET`, `RESET`, `set_config(…)`, role switches)
122
+ don't either. Their names, never their values, go in `db.transaction.settings` on the enclosing transaction, or in
123
+ `db.settings` on the next statement (`noise: 'fold'`, the default). `noise: 'skip'` drops them and `noise: 'span'`
124
+ traces them.
125
+
126
+ ### AI
127
+
128
+ `traceGenAi` and `recordGenAi` make CLIENT spans named `<operation> <model>` under the active span. Their attributes
129
+ are `gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`,
130
+ `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` and `gen_ai.response.finish_reasons`, plus `error.type` on
131
+ failure.
132
+
133
+ If your app already has an AI tracer, `genAiSpanSink(h)` takes its finished spans and sends them with content stripped.
134
+ Each foreign root span becomes a child of the request span, so the calls sit inside the request's trace. Make the sink
135
+ once per invocation, or pass `parent`.
136
+
137
+ ## What's sent, and what never is
138
+
139
+ | Sent | Never sent |
140
+ | --- | --- |
141
+ | Log records: body, severity, attributes, trace and span ids | SQL parameter values: they're never read |
142
+ | Spans: names, timings, status, the attributes above | Literals inlined in SQL: strings, numbers and dollar-quoted bodies become `?`; comments are dropped |
143
+ | `db.query.text` with placeholders, capped at 2048 chars (`queryText: false` or `HOUSTON_DB_QUERY_TEXT=false` turns it off) | An ORM's `params:` line in an error message or stack, wherever the error is recorded |
144
+ | Exception type, message and (outside `/sql`) stack | Prompts, completions, tool arguments and results: content-looking keys are dropped and foreign events are never forwarded |
145
+ | `server.address` as a host name | Connection-string credentials, paths or query strings |
146
+
147
+ ## Configuration
148
+
149
+ `houstonOptionsFromEnv(env, defaults)` reads:
150
+
151
+ | Variable | |
152
+ | --- | --- |
153
+ | `HOUSTON_OTLP_ENDPOINT` | houston's origin. `/v1/logs` and `/v1/traces` are appended |
154
+ | `HOUSTON_API_KEY` | an ingest key (secret). Unset means off |
155
+ | `HOUSTON_ENABLED` | `false`, `0` or `off` turns it off with both set |
156
+ | `HOUSTON_SERVICE_NAME` | `service.name` (default `defaults.serviceName`, else `unknown_service`) |
157
+ | `HOUSTON_SERVICE_VERSION` | `service.version` (falls back to a `CF_VERSION_METADATA` binding's id) |
158
+ | `HOUSTON_ENVIRONMENT` | `deployment.environment.name` |
159
+ | `HOUSTON_DB_QUERY_TEXT` | `false` keeps `db.query.text` out of SQL spans |
160
+
161
+ `createHouston(options)` also takes `resource` (extra resource attributes), `minSeverity`, `maxBatchSize` (500),
162
+ `maxQueueSize` (5000), `timeoutMs` (10 000), `fetch` and `onExportError`. Don't log through houston from
163
+ `onExportError`: the line would come back to it.
164
+
165
+ ## Notes
166
+
167
+ - Worker time only advances on I/O, so a CPU-only span can show zero duration.
168
+ - A streaming body that outlives the handler isn't inside the request span. Its records go out with the next flush.
169
+ - Tagged-template calls (`` sql`…` ``) on neon and postgres.js aren't traced. Drizzle doesn't use them.
170
+
171
+ ## Licence
172
+
173
+ MIT
@@ -0,0 +1,16 @@
1
+ import type { Attributes } from './otlp.js';
2
+ /** `value` cut to `max` characters, an ellipsis marking the cut. */
3
+ export declare function truncate(value: string, max?: number): string;
4
+ /** `text` without an ORM's `params:` line, so no bound value leaves through an exception message or stack. */
5
+ export declare function withoutBoundValues(text: string): string;
6
+ /** An `Error` (or a serialised `{ type, message, stack }`) as `exception.type`, `.message` and `.stacktrace`. */
7
+ export declare function exceptionAttributes(error: unknown): Attributes;
8
+ /** The one-line message an error gives a span status (500 characters at most). */
9
+ export declare function errorMessage(error: unknown): string;
10
+ /**
11
+ * Flatten `value` under `prefix` into `out`: `{ req: { method: 'GET' } }` → `req.method`. Top-level keys named
12
+ * `err` or `error` holding an error become `exception.*` instead.
13
+ */
14
+ export declare function flattenInto(out: Attributes, prefix: string, value: unknown, depth?: number): void;
15
+ /** A plain object of fields as flat attributes (see `flattenInto`). */
16
+ export declare function flatten(fields: Record<string, unknown> | undefined): Attributes;
@@ -0,0 +1,133 @@
1
+ const MAX_STRING = 8_192;
2
+ const MAX_DEPTH = 4;
3
+ /** `value` cut to `max` characters, an ellipsis marking the cut. */
4
+ export function truncate(value, max = MAX_STRING) {
5
+ return value.length > max ? `${value.slice(0, max)}…` : value;
6
+ }
7
+ // An ORM's query error (`Failed query: <sql>\nparams: <values>`) carries the bound values on a `params:` line.
8
+ const BOUND_VALUES = /\r?\nparams:[\s\S]*?(?=\n\s+at |$)/;
9
+ /** `text` without an ORM's `params:` line, so no bound value leaves through an exception message or stack. */
10
+ export function withoutBoundValues(text) {
11
+ return text.replace(BOUND_VALUES, '');
12
+ }
13
+ function isPlainObject(value) {
14
+ if (value === null || typeof value !== 'object')
15
+ return false;
16
+ const proto = Object.getPrototypeOf(value);
17
+ return proto === Object.prototype || proto === null;
18
+ }
19
+ function primitiveArray(value) {
20
+ if (value.length === 0)
21
+ return undefined;
22
+ if (value.every((v) => typeof v === 'string'))
23
+ return value.map((v) => truncate(v));
24
+ if (value.every((v) => typeof v === 'number' && Number.isFinite(v)))
25
+ return value;
26
+ if (value.every((v) => typeof v === 'boolean'))
27
+ return value;
28
+ return undefined;
29
+ }
30
+ function json(value) {
31
+ try {
32
+ return truncate(JSON.stringify(value) ?? String(value));
33
+ }
34
+ catch {
35
+ return '[unserialisable]';
36
+ }
37
+ }
38
+ /** An `Error` (or a serialised `{ type, message, stack }`) as `exception.type`, `.message` and `.stacktrace`. */
39
+ export function exceptionAttributes(error) {
40
+ if (error instanceof Error) {
41
+ const code = error.code;
42
+ return {
43
+ 'exception.type': typeof code === 'string' ? code : error.name,
44
+ 'exception.message': truncate(withoutBoundValues(error.message)),
45
+ 'exception.stacktrace': error.stack ? truncate(withoutBoundValues(error.stack)) : undefined,
46
+ };
47
+ }
48
+ if (isPlainObject(error) && (typeof error.message === 'string' || typeof error.type === 'string')) {
49
+ // pino's browser serialiser says `msg`, its Node one `message`
50
+ const message = typeof error.message === 'string' ? error.message : error.msg;
51
+ return {
52
+ 'exception.type': typeof error.type === 'string' ? error.type : 'Error',
53
+ 'exception.message': typeof message === 'string' ? truncate(withoutBoundValues(message)) : undefined,
54
+ 'exception.stacktrace': typeof error.stack === 'string' ? truncate(withoutBoundValues(error.stack)) : undefined,
55
+ };
56
+ }
57
+ return { 'exception.type': 'Error', 'exception.message': truncate(withoutBoundValues(String(error))) };
58
+ }
59
+ /** The one-line message an error gives a span status (500 characters at most). */
60
+ export function errorMessage(error) {
61
+ if (error instanceof Error)
62
+ return truncate(withoutBoundValues(error.message), 500);
63
+ if (isPlainObject(error)) {
64
+ const message = error.message ?? error.msg;
65
+ if (typeof message === 'string')
66
+ return truncate(withoutBoundValues(message), 500);
67
+ }
68
+ return truncate(withoutBoundValues(String(error)), 500);
69
+ }
70
+ /**
71
+ * Flatten `value` under `prefix` into `out`: `{ req: { method: 'GET' } }` → `req.method`. Top-level keys named
72
+ * `err` or `error` holding an error become `exception.*` instead.
73
+ */
74
+ export function flattenInto(out, prefix, value, depth = 0) {
75
+ if (value === undefined || value === null)
76
+ return;
77
+ if (typeof value === 'string') {
78
+ out[prefix] = truncate(value);
79
+ return;
80
+ }
81
+ if (typeof value === 'number') {
82
+ if (Number.isFinite(value))
83
+ out[prefix] = value;
84
+ return;
85
+ }
86
+ if (typeof value === 'boolean') {
87
+ out[prefix] = value;
88
+ return;
89
+ }
90
+ if (typeof value === 'bigint') {
91
+ out[prefix] = value.toString();
92
+ return;
93
+ }
94
+ if (value instanceof Date) {
95
+ out[prefix] = value.toISOString();
96
+ return;
97
+ }
98
+ if (value instanceof Error) {
99
+ Object.assign(out, exceptionAttributes(value));
100
+ return;
101
+ }
102
+ if (Array.isArray(value)) {
103
+ const arr = primitiveArray(value);
104
+ if (arr !== undefined)
105
+ out[prefix] = arr;
106
+ else if (value.length > 0)
107
+ out[prefix] = json(value);
108
+ return;
109
+ }
110
+ if (isPlainObject(value)) {
111
+ if (depth >= MAX_DEPTH) {
112
+ out[prefix] = json(value);
113
+ return;
114
+ }
115
+ for (const [key, inner] of Object.entries(value)) {
116
+ if ((key === 'err' || key === 'error') && !prefix && (inner instanceof Error || isPlainObject(inner))) {
117
+ Object.assign(out, exceptionAttributes(inner));
118
+ continue;
119
+ }
120
+ flattenInto(out, prefix ? `${prefix}.${key}` : key, inner, depth + 1);
121
+ }
122
+ return;
123
+ }
124
+ if (typeof value !== 'function' && typeof value !== 'symbol')
125
+ out[prefix] = json(value);
126
+ }
127
+ /** A plain object of fields as flat attributes (see `flattenInto`). */
128
+ export function flatten(fields) {
129
+ const out = {};
130
+ if (fields)
131
+ flattenInto(out, '', fields);
132
+ return out;
133
+ }
@@ -0,0 +1,97 @@
1
+ import type { Houston, Span } from './houston.js';
2
+ import { type SpanContext } from './ids.js';
3
+ import type { Attributes, SpanData, SpanKindName } from './otlp.js';
4
+ /** What a model call asks for. */
5
+ export interface GenAiRequest {
6
+ /** `gen_ai.operation.name`: `chat` (default), `embeddings`, `text_completion`, `generate_content`, `execute_tool`, … */
7
+ operation?: string;
8
+ /** `gen_ai.provider.name`: `anthropic`, `openai`, `gcp.gemini`, `cloudflare.workers_ai`, … */
9
+ provider: string;
10
+ /** `gen_ai.request.model`. */
11
+ model: string;
12
+ /** `gen_ai.request.max_tokens`. */
13
+ maxTokens?: number;
14
+ /** `gen_ai.request.temperature`. */
15
+ temperature?: number;
16
+ /** Extra attributes (content-looking keys are dropped). */
17
+ attributes?: Attributes;
18
+ }
19
+ /** What a model call answered (counts and ids only). */
20
+ export interface GenAiResponse {
21
+ /** `gen_ai.response.model`, when the provider reports a specific one. */
22
+ responseModel?: string;
23
+ /** `gen_ai.response.id`. */
24
+ responseId?: string;
25
+ /** `gen_ai.usage.input_tokens`. */
26
+ inputTokens?: number;
27
+ /** `gen_ai.usage.output_tokens`. */
28
+ outputTokens?: number;
29
+ /** `gen_ai.response.finish_reasons`. */
30
+ finishReasons?: string[];
31
+ /** Extra attributes (content-looking keys are dropped). */
32
+ attributes?: Attributes;
33
+ }
34
+ /** True for attribute keys that can carry content (`gen_ai.input.messages`, `input.value`, `llm.prompts.0`, …). */
35
+ export declare function isContentAttribute(key: string): boolean;
36
+ /** The `gen_ai.*` attributes of a call, request and response together. Pure; never includes content. */
37
+ export declare function genAiAttributes(request: GenAiRequest, response?: GenAiResponse): Attributes;
38
+ /** The span of a call in progress: set what the response says as soon as you know it (a stream's last chunk). */
39
+ export interface GenAiCall {
40
+ readonly span: Span;
41
+ setResponse(response: GenAiResponse): void;
42
+ }
43
+ /**
44
+ * Run one model call under a CLIENT `<operation> <model>` span, a child of the active span. `describe` reads
45
+ * the response's counts off the result (or call `call.setResponse` inside `run`). A throw marks the span ERROR
46
+ * and is rethrown; the call's own result always reaches the caller.
47
+ */
48
+ export declare function traceGenAi<T>(houston: Houston, request: GenAiRequest, run: (call: GenAiCall) => Promise<T> | T, describe?: (result: T) => GenAiResponse): Promise<T>;
49
+ /** A finished call for `recordGenAi`. */
50
+ export interface GenAiRecord extends GenAiRequest, GenAiResponse {
51
+ /** Epoch ms or a Date. */
52
+ startTime: number | Date;
53
+ /** Epoch ms or a Date; defaults to now. */
54
+ endTime?: number | Date;
55
+ /** The call failed with this. */
56
+ error?: unknown;
57
+ }
58
+ /** Record a call that already happened as a CLIENT span under the active span. */
59
+ export declare function recordGenAi(houston: Houston, record: GenAiRecord): void;
60
+ /** A finished span from another tracer. Anything else on it (content, events) is never read. */
61
+ export interface ForeignSpan {
62
+ traceId: string;
63
+ spanId: string;
64
+ parentSpanId?: string;
65
+ name: string;
66
+ /** An OTLP kind name, or the tracer's own (`llm`, `embedding` → client; others → internal). */
67
+ kind?: string;
68
+ startTime: number | Date;
69
+ endTime: number | Date;
70
+ /** `error` → ERROR; anything else is UNSET. */
71
+ status?: string;
72
+ statusMessage?: string;
73
+ attributes?: Record<string, unknown>;
74
+ }
75
+ export interface GenAiSinkOptions {
76
+ /**
77
+ * Where the foreign trace hangs: its root spans become children of this span (and the whole trace takes its
78
+ * trace id). Default: the span active when the sink was made, else when it's called. `null` keeps the
79
+ * foreign trace as it is. A function is read on every call.
80
+ */
81
+ parent?: SpanContext | string | null | (() => SpanContext | string | null | undefined);
82
+ /** Map a foreign span's kind. */
83
+ kind?: (span: ForeignSpan) => SpanKindName;
84
+ /** Keep only attributes this says yes to (content-looking keys are dropped whatever it says). */
85
+ keep?: (key: string) => boolean;
86
+ }
87
+ /** A foreign span as houston span data: ids lowercased, content-looking attributes and all events dropped. Null if its ids are bad. */
88
+ export declare function toHoustonSpan(span: ForeignSpan, options?: Pick<GenAiSinkOptions, 'kind' | 'keep'>): SpanData | null;
89
+ /** Hang each foreign trace's roots under `parent` and move the trace to its trace id. Pure. */
90
+ export declare function reparent(spans: SpanData[], parent: SpanContext): SpanData[];
91
+ /**
92
+ * A sink for an existing AI tracer: `(spans) => Promise<void>` that sends its finished spans to houston without
93
+ * content, as children of the request (or step) span. Make it per invocation, or pass `parent`. To have the
94
+ * tracer start its traces in houston's trace instead, give it `houston.activeSpan()`'s ids as its parent.
95
+ * Never rejects.
96
+ */
97
+ export declare function genAiSpanSink(houston: Houston, options?: GenAiSinkOptions): (spans: ForeignSpan[]) => Promise<void>;
package/dist/genai.js ADDED
@@ -0,0 +1,200 @@
1
+ // `./genai`: model and tool calls as `gen_ai.*` spans in the request's trace, attributes only. Prompts,
2
+ // completions, tool arguments and results are never sent: content-looking keys are dropped from every
3
+ // attribute set this module writes, and a foreign tracer's events (where content lives) are not forwarded.
4
+ import { errorMessage, truncate, withoutBoundValues } from './attributes.js';
5
+ import { isSpanId, isTraceId, parseTraceparent } from './ids.js';
6
+ // a key with one of these dot-separated segments can carry a prompt, completion or tool I/O
7
+ const CONTENT_SEGMENT = /(?:^|\.)(?:input|output|inputs|outputs|prompt|prompts|completion|completions|messages|input_messages|output_messages|system_instructions|instructions|content|contents|arguments|result|results|text|query|documents|definitions|choice|choices)(?:\.|$)/i;
8
+ /** True for attribute keys that can carry content (`gen_ai.input.messages`, `input.value`, `llm.prompts.0`, …). */
9
+ export function isContentAttribute(key) {
10
+ if (/(?:^|\.)token_count(?:\.|$)|_tokens(?:\.|$)/.test(key))
11
+ return false; // counts (`llm.token_count.prompt`)
12
+ return CONTENT_SEGMENT.test(key);
13
+ }
14
+ function withoutContent(attributes, keep = () => true) {
15
+ const out = {};
16
+ for (const [key, value] of Object.entries(attributes ?? {})) {
17
+ if (isContentAttribute(key) || !keep(key))
18
+ continue;
19
+ const v = attributeValue(value);
20
+ if (v !== undefined)
21
+ out[key] = v;
22
+ }
23
+ return out;
24
+ }
25
+ function attributeValue(value) {
26
+ if (typeof value === 'string')
27
+ return truncate(value, 1_024);
28
+ if (typeof value === 'number')
29
+ return Number.isFinite(value) ? value : undefined;
30
+ if (typeof value === 'boolean')
31
+ return value;
32
+ if (Array.isArray(value) && value.length > 0) {
33
+ if (value.every((v) => typeof v === 'string'))
34
+ return value.map((v) => truncate(v, 1_024));
35
+ if (value.every((v) => typeof v === 'number' && Number.isFinite(v)))
36
+ return value;
37
+ if (value.every((v) => typeof v === 'boolean'))
38
+ return value;
39
+ }
40
+ return undefined;
41
+ }
42
+ /** The `gen_ai.*` attributes of a call, request and response together. Pure; never includes content. */
43
+ export function genAiAttributes(request, response = {}) {
44
+ return {
45
+ ...withoutContent(request.attributes),
46
+ ...withoutContent(response.attributes),
47
+ 'gen_ai.operation.name': request.operation ?? 'chat',
48
+ 'gen_ai.provider.name': request.provider,
49
+ 'gen_ai.request.model': request.model,
50
+ 'gen_ai.request.max_tokens': request.maxTokens,
51
+ 'gen_ai.request.temperature': request.temperature,
52
+ 'gen_ai.response.model': response.responseModel,
53
+ 'gen_ai.response.id': response.responseId,
54
+ 'gen_ai.usage.input_tokens': response.inputTokens,
55
+ 'gen_ai.usage.output_tokens': response.outputTokens,
56
+ 'gen_ai.response.finish_reasons': response.finishReasons?.length ? response.finishReasons : undefined,
57
+ };
58
+ }
59
+ const spanName = (request) => `${request.operation ?? 'chat'} ${request.model}`;
60
+ function failed(span, error) {
61
+ const code = error?.code;
62
+ const type = typeof code === 'string' ? code : error instanceof Error ? error.name : 'Error';
63
+ const message = errorMessage(error);
64
+ span.setAttribute('error.type', type);
65
+ span.addEvent('exception', { 'exception.type': type, 'exception.message': message });
66
+ span.setStatus('error', message);
67
+ }
68
+ /**
69
+ * Run one model call under a CLIENT `<operation> <model>` span, a child of the active span. `describe` reads
70
+ * the response's counts off the result (or call `call.setResponse` inside `run`). A throw marks the span ERROR
71
+ * and is rethrown; the call's own result always reaches the caller.
72
+ */
73
+ export async function traceGenAi(houston, request, run, describe) {
74
+ if (!houston.enabled)
75
+ return run({ span: houston.startSpan(''), setResponse() { } });
76
+ const span = houston.startSpan(spanName(request), { kind: 'client', attributes: genAiAttributes(request) });
77
+ const call = {
78
+ span,
79
+ setResponse(response) {
80
+ try {
81
+ span.setAttributes(genAiAttributes(request, response));
82
+ }
83
+ catch {
84
+ // best effort
85
+ }
86
+ },
87
+ };
88
+ try {
89
+ const result = await houston.withSpan(span, () => run(call));
90
+ if (describe) {
91
+ try {
92
+ call.setResponse(describe(result));
93
+ }
94
+ catch {
95
+ // best effort
96
+ }
97
+ }
98
+ return result;
99
+ }
100
+ catch (error) {
101
+ failed(span, error);
102
+ throw error;
103
+ }
104
+ finally {
105
+ span.end();
106
+ }
107
+ }
108
+ const ms = (t) => (t instanceof Date ? t.getTime() : t);
109
+ /** Record a call that already happened as a CLIENT span under the active span. */
110
+ export function recordGenAi(houston, record) {
111
+ if (!houston.enabled)
112
+ return;
113
+ try {
114
+ const span = houston.startSpan(spanName(record), { kind: 'client', startTime: ms(record.startTime), attributes: genAiAttributes(record, record) });
115
+ if (record.error !== undefined)
116
+ failed(span, record.error);
117
+ span.end(record.endTime === undefined ? undefined : ms(record.endTime));
118
+ }
119
+ catch {
120
+ // best effort
121
+ }
122
+ }
123
+ const KINDS = new Set(['internal', 'server', 'client', 'producer', 'consumer']);
124
+ const CLIENT_OPERATIONS = new Set(['chat', 'text_completion', 'generate_content', 'embeddings']);
125
+ function defaultKind(span) {
126
+ const kind = span.kind?.toLowerCase();
127
+ if (kind && KINDS.has(kind))
128
+ return kind;
129
+ if (kind === 'llm' || kind === 'embedding' || kind === 'generation')
130
+ return 'client';
131
+ return CLIENT_OPERATIONS.has(String(span.attributes?.['gen_ai.operation.name'])) ? 'client' : 'internal';
132
+ }
133
+ /** A foreign span as houston span data: ids lowercased, content-looking attributes and all events dropped. Null if its ids are bad. */
134
+ export function toHoustonSpan(span, options = {}) {
135
+ const traceId = span.traceId.toLowerCase();
136
+ const spanId = span.spanId.toLowerCase();
137
+ if (!isTraceId(traceId) || !isSpanId(spanId))
138
+ return null;
139
+ const parentSpanId = span.parentSpanId?.toLowerCase();
140
+ const error = span.status === 'error';
141
+ return {
142
+ traceId,
143
+ spanId,
144
+ ...(parentSpanId && isSpanId(parentSpanId) && { parentSpanId }),
145
+ name: span.name,
146
+ kind: (options.kind ?? defaultKind)(span),
147
+ startTime: ms(span.startTime),
148
+ endTime: ms(span.endTime),
149
+ status: error ? 'error' : 'unset',
150
+ ...(error && span.statusMessage && { statusMessage: truncate(withoutBoundValues(span.statusMessage), 500) }),
151
+ attributes: withoutContent(span.attributes, options.keep),
152
+ events: [],
153
+ };
154
+ }
155
+ function contextOf(parent) {
156
+ if (parent === null || parent === undefined)
157
+ return parent;
158
+ if (typeof parent === 'string')
159
+ return parseTraceparent(parent);
160
+ return isTraceId(parent.traceId) && isSpanId(parent.spanId) ? { traceId: parent.traceId, spanId: parent.spanId } : undefined;
161
+ }
162
+ /** Hang each foreign trace's roots under `parent` and move the trace to its trace id. Pure. */
163
+ export function reparent(spans, parent) {
164
+ const moved = new Map();
165
+ for (const s of spans)
166
+ if (!s.parentSpanId)
167
+ moved.set(s.traceId, parent.traceId);
168
+ return spans.map((s) => {
169
+ if (!moved.has(s.traceId))
170
+ return s;
171
+ return { ...s, traceId: parent.traceId, ...(!s.parentSpanId && s.spanId !== parent.spanId && { parentSpanId: parent.spanId }) };
172
+ });
173
+ }
174
+ /**
175
+ * A sink for an existing AI tracer: `(spans) => Promise<void>` that sends its finished spans to houston without
176
+ * content, as children of the request (or step) span. Make it per invocation, or pass `parent`. To have the
177
+ * tracer start its traces in houston's trace instead, give it `houston.activeSpan()`'s ids as its parent.
178
+ * Never rejects.
179
+ */
180
+ export function genAiSpanSink(houston, options = {}) {
181
+ if (!houston.enabled)
182
+ return async () => { };
183
+ const active = houston.activeSpan();
184
+ const made = options.parent !== undefined ? options.parent : active?.isRecording ? { traceId: active.traceId, spanId: active.spanId } : undefined;
185
+ return async (spans) => {
186
+ try {
187
+ const given = typeof made === 'function' ? made() : made;
188
+ let parent = contextOf(given);
189
+ if (parent === undefined && given === undefined) {
190
+ const now = houston.activeSpan();
191
+ parent = now?.isRecording ? { traceId: now.traceId, spanId: now.spanId } : undefined;
192
+ }
193
+ const data = spans.map((s) => toHoustonSpan(s, options)).filter((s) => s !== null);
194
+ await houston.exportSpans(parent ? reparent(data, parent) : data);
195
+ }
196
+ catch {
197
+ // never into the tracer
198
+ }
199
+ };
200
+ }
package/dist/hono.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+ import type { Houston } from './houston.js';
3
+ import type { Attributes } from './otlp.js';
4
+ export interface HoustonMiddlewareOptions {
5
+ /** Log a 5xx's error at ERROR here too (default true). Turn it off when your `onError` already logs it. */
6
+ logErrors?: boolean;
7
+ /** Skip a request entirely (no span, no flush), e.g. a health probe. */
8
+ ignore?: (c: Context) => boolean;
9
+ /** Extra span attributes, read once the response exists (request id, tenant, …). */
10
+ attributes?: (c: Context) => Attributes;
11
+ }
12
+ /**
13
+ * The route pattern the request matched, e.g. `/api/posts/:id`: the first handler (one parameter; a middleware
14
+ * takes two) at or after the deepest dispatched index, so a request a middleware refused (a 400, a 401, a thrown
15
+ * 500) still names its route. Undefined when no handler matched (a 404).
16
+ */
17
+ export declare function routeOf(c: Context): string | undefined;
18
+ /**
19
+ * The request-span middleware. Mount it first (before a request logger) so every log line, including what
20
+ * `onError` logs, falls inside the span. `houston` may be a function of the context, to build it from `c.env`.
21
+ * A 5xx (returned or thrown) sets ERROR, a thrown error is also an `exception` event. A streaming body that
22
+ * outlives `next()` isn't covered by the span; its records go out with the next flush.
23
+ */
24
+ export declare function houstonMiddleware(houston: Houston | ((c: Context) => Houston), options?: HoustonMiddlewareOptions): MiddlewareHandler;