@softistx/telemetry-hono 0.0.0-stage → 0.3.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
1
+ # @softistx/telemetry-hono
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
+ One server span per Hono request, around the whole handler — with the inbound
4
+ `traceparent` continued, the route as the span name, and everything the handler
5
+ logs carrying the request's trace id.
6
+
7
+ ```sh
8
+ bun add @softistx/telemetry @softistx/telemetry-hono hono
9
+ ```
10
+
11
+ ```ts
12
+ import { Hono } from 'hono';
13
+ import { telemetry } from '@softistx/telemetry-hono';
14
+ import { otlpExporter } from '@softistx/telemetry-otlp';
15
+
16
+ const tracing = telemetry({
17
+ service: 'checkout',
18
+ version: '1.4.0',
19
+ exporters: [otlpExporter({ endpoint: 'http://localhost:4318' })],
20
+ });
21
+
22
+ const app = new Hono();
23
+ app.use('*', tracing);
24
+
25
+ app.get('/orders/:id', async (c) => {
26
+ log.info('order read', { id: c.req.param('id') }); // carries this request's traceId
27
+ return c.json(await orders.find(c.req.param('id')));
28
+ });
29
+
30
+ process.on('SIGTERM', async () => {
31
+ await tracing.telemetry.close(); // awaited, or the last batch is lost
32
+ process.exit(0);
33
+ });
34
+ ```
35
+
36
+ ## The span wraps the handler
37
+
38
+ It is one middleware around `next()`, not a pair of before/after hooks. That is
39
+ what puts the whole handler — everything it awaits, and everything it throws —
40
+ inside the span's context, so a `log.info()` three calls down carries this
41
+ request's `traceId` without anything having been passed to it.
42
+
43
+ A `traceparent` on the way in continues that trace, as a child of the caller's
44
+ span. An unusable header is **not** an error: it starts a fresh trace, because
45
+ the header came from a stranger.
46
+
47
+ ## The name is the route, and routing knows it last
48
+
49
+ The span starts as `"<METHOD> <path>"` and is renamed to `"<METHOD> <route>"`
50
+ once the router has matched — `GET /orders/:id`, not `GET /orders/o-1`. A span
51
+ named for the path it arrived at gives a dashboard one row per order id. The
52
+ path is still there, as `url.path`.
53
+
54
+ A request that matched nothing keeps the path in its name and gets no
55
+ `http.route`: there is no route to report.
56
+
57
+ ## What it records
58
+
59
+ | attribute | |
60
+ | --- | --- |
61
+ | `http.request.method` | before the handler runs |
62
+ | `url.path`, `url.scheme`, `server.address` | the request as it arrived |
63
+ | `http.route` | after routing, when something matched |
64
+ | `http.response.status_code` | after the handler |
65
+
66
+ **A 4xx is `ok`.** The client sent something the server refused, which is the
67
+ server working; counting it as an error is what makes an error rate nobody can
68
+ act on. Only `5xx` marks the span.
69
+
70
+ **Hono catches.** A handler that throws does not reject `next()` — the router
71
+ turns the exception into a reply and leaves the failure on `c.error`. This
72
+ middleware reads it, so the span carries `exception.type` and not just a status.
73
+
74
+ **The reply decides the status, not the exception.** `HTTPException` is how a
75
+ Hono application says `401`: it is what `basicAuth`, `bearerAuth`, `jwt` and the
76
+ validators all throw. Letting a thrown failure mark the span would put every
77
+ rejected login in the error rate, so a thrown `4xx` is still `ok` — with its
78
+ `exception.type` recorded. An abort answered with a `500` stays `cancelled`.
79
+
80
+ ## Options
81
+
82
+ ```ts
83
+ telemetry({ service: 'checkout', exporters: [...] }) // builds one, and installs it
84
+ telemetry({ instance }) // adopts one; never closes it
85
+ ```
86
+
87
+ The two shapes are exclusive, and the compiler says so: `service` beside an
88
+ `instance` would be silently ignored.
89
+
90
+ | | default | |
91
+ | --- | --- | --- |
92
+ | `service` | — | the service name, plus every `createTelemetry` option |
93
+ | `instance` | — | an existing telemetry. **Adopted, not closed** |
94
+ | `traced` | everything | whether a request gets a span at all |
95
+ | `spanName` | `"<METHOD> <path>"` | the name before routing |
96
+ | `route` | the last matched handler | the route template, after the handler |
97
+
98
+ `traced` is the health-check hook:
99
+
100
+ ```ts
101
+ telemetry({ service: 'checkout', traced: (c) => c.req.path !== '/health' })
102
+ ```
103
+
104
+ Nothing is skipped by default. A library that decides for you which requests do
105
+ not matter is a library that hides the one that did.
106
+
107
+ ## Closing it
108
+
109
+ A middleware has no shutdown to hook, so it does not close anything. The
110
+ telemetry it is using comes back on the middleware itself:
111
+
112
+ ```ts
113
+ const tracing = telemetry({ service: 'checkout', exporters: [...] });
114
+ process.on('SIGTERM', async () => {
115
+ await tracing.telemetry.close(); // has to be awaited: the last batch is the one that explains the shutdown
116
+ process.exit(0);
117
+ });
118
+ ```
119
+
120
+ ## From the handler
121
+
122
+ ```ts
123
+ app.get('/orders/:id', (c) => {
124
+ c.get('span')?.attribute('tenant', tenant);
125
+ c.get('span')?.event('cache.missed');
126
+ c.get('telemetry'); // the one this request is written to
127
+ return c.json(order);
128
+ });
129
+ ```
130
+
131
+ Importing anything from this package augments Hono's `ContextVariableMap`, so
132
+ both are typed in a handler that imports nothing from here. `c.get('span')` is
133
+ `undefined` when `traced` said no.
134
+
135
+ ## API
136
+
137
+ | | |
138
+ | --- | --- |
139
+ | `telemetry(options)` | the middleware, with `.telemetry` on it |
140
+ | `TelemetryMiddlewareOptions` | the two shapes above |
141
+ | `TelemetryMiddleware` | a `MiddlewareHandler` carrying its `Telemetry` |
142
+ | `requestAttributes(request)` | what is known before the handler runs |
143
+ | `serverFailed(status)` | whether a status marks the span |
144
+ | `HTTP_METHOD`, `URL_PATH`, `URL_SCHEME`, `HTTP_ROUTE`, `HTTP_STATUS`, `SERVER_ADDRESS` | the attribute names |
145
+ | `SERVER_ERROR_FROM` | `500` |
146
+ | `TELEMETRY_VARIABLE`, `SPAN_VARIABLE` | the context keys, as values |
147
+
148
+ ## Traps
149
+
150
+ - **`hono` is an optional peer, from `^4.8.0`** — where `hono/route` arrived.
151
+ The route comes from `matchedRoutes(c)`, which has been the same one-argument
152
+ function ever since. `routePath(c, -1)` would have been the obvious call and
153
+ is the wrong one twice over: it only takes a second argument from hono 4.10,
154
+ so on 4.8 and 4.9 the `-1` is silently ignored, and even where it works it
155
+ answers the last matched *entry* — which is a middleware registered after the
156
+ routes.
157
+ - **The route is the last matched handler, not the last matched route.** A
158
+ middleware takes `(c, next)` and a handler takes `(c)`, which is how hono's
159
+ own `matchedRoutes` example tells them apart and how this does. Taking the
160
+ last match instead would name the span after a middleware registered *after*
161
+ the routes, and would report `/v1/*` as the route of a 404 under a mount.
162
+ - **A catch-all a handler owns is a route.** `app.get('/files/*')` reports
163
+ `http.route: '/files/*'`, because the application registered it. Only
164
+ `app.use`'s patterns are filtered out, and they are filtered out by being
165
+ middleware, not by their shape.
166
+ - **The telemetry built from `service` is installed**, so a log written outside
167
+ any request finds it. An adopted `instance` is left exactly as it was.
168
+ - **`close()` is not called for you**, and it has to be awaited. A
169
+ `process.exit()` before it resolves loses the last batch.
170
+ - **A 4xx is `ok`, a 5xx is not.** If your API answers `200` with an error body,
171
+ set `c.get('span')!.status = 'error'` yourself — nothing here can know.
172
+ - **`traced: false` means no context either.** `c.get('span')` is `undefined`,
173
+ and a log written in that handler carries no trace id. Both context variables
174
+ are declared optional, so the compiler makes you say so.
175
+ - **The span ends when the handler returns, not when the body finishes.** A
176
+ streamed reply is recorded as the milliseconds it took to *start*. What
177
+ happens after the `Response` is outside every middleware.
178
+ - **A thrown non-`Error` is rethrown by hono rather than parked on `c.error`.**
179
+ The span still records it — the core does that — but there is no reply to read,
180
+ so it carries no `http.response.status_code`.
181
+ - **A hook that throws costs its own answer and nothing else.** `traced` falls
182
+ back to tracing, `spanName` and `route` to the defaults. A predicate that
183
+ raises must not turn observability into an outage.
184
+
185
+ ## License
186
+
187
+ MIT
@@ -0,0 +1,37 @@
1
+ import type { Attributes } from '@softistx/telemetry';
2
+ /**
3
+ * The semantic conventions this middleware sets, by name. They are the ones a
4
+ * backend's HTTP dashboards look for, and getting a name wrong means the
5
+ * attribute is still there and the dashboard is still empty.
6
+ *
7
+ * `-httpyz` sets four of the same names on the client side. That duplication is
8
+ * deliberate and recorded in `AGENTS.md`: a shared helper would make each
9
+ * package depend on the other's host.
10
+ */
11
+ export declare const HTTP_METHOD = "http.request.method";
12
+ export declare const URL_PATH = "url.path";
13
+ export declare const URL_SCHEME = "url.scheme";
14
+ export declare const HTTP_ROUTE = "http.route";
15
+ export declare const HTTP_STATUS = "http.response.status_code";
16
+ export declare const SERVER_ADDRESS = "server.address";
17
+ export declare const SERVER_PORT = "server.port";
18
+ /** The status at which a server span is the server's fault, and not before. */
19
+ export declare const SERVER_ERROR_FROM = 500;
20
+ /**
21
+ * What is known about a request **before** it is handled: the method, the path
22
+ * as it arrived, and where it was addressed.
23
+ *
24
+ * The route is not here. It is not known until the router has matched, which is
25
+ * after `next()`, and a span named for the path it arrived at would give a
26
+ * dashboard one row per order id.
27
+ */
28
+ export declare function requestAttributes(request: Request): Attributes;
29
+ /**
30
+ * Whether a reply says the server failed.
31
+ *
32
+ * **A 4xx is `ok`.** The client sent something the server refused, which is the
33
+ * server working; counting it as an error is what makes an error rate that
34
+ * nobody can act on. Only `5xx` marks the span.
35
+ */
36
+ export declare function serverFailed(status: number): boolean;
37
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/attributes/http.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,wBAAwB,CAAC;AACjD,eAAO,MAAM,QAAQ,aAAa,CAAC;AACnC,eAAO,MAAM,UAAU,eAAe,CAAC;AACvC,eAAO,MAAM,UAAU,eAAe,CAAC;AACvC,eAAO,MAAM,WAAW,8BAA8B,CAAC;AACvD,eAAO,MAAM,cAAc,mBAAmB,CAAC;AAC/C,eAAO,MAAM,WAAW,gBAAgB,CAAC;AAEzC,+EAA+E;AAC/E,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,UAAU,CAkB9D;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAEpD"}
@@ -0,0 +1,4 @@
1
+ export * from './attributes/http';
2
+ export * from './middleware/telemetry';
3
+ export * from './middleware/variables';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ // src/attributes/http.ts
2
+ var HTTP_METHOD = "http.request.method";
3
+ var URL_PATH = "url.path";
4
+ var URL_SCHEME = "url.scheme";
5
+ var HTTP_ROUTE = "http.route";
6
+ var HTTP_STATUS = "http.response.status_code";
7
+ var SERVER_ADDRESS = "server.address";
8
+ var SERVER_PORT = "server.port";
9
+ var SERVER_ERROR_FROM = 500;
10
+ function requestAttributes(request) {
11
+ const url = safeUrl(request.url);
12
+ return {
13
+ [HTTP_METHOD]: request.method,
14
+ ...url === undefined ? {} : {
15
+ [URL_PATH]: url.pathname,
16
+ [URL_SCHEME]: url.protocol.replace(":", ""),
17
+ [SERVER_ADDRESS]: url.hostname,
18
+ ...url.port === "" ? {} : { [SERVER_PORT]: Number(url.port) }
19
+ }
20
+ };
21
+ }
22
+ function serverFailed(status) {
23
+ return status >= SERVER_ERROR_FROM;
24
+ }
25
+ function safeUrl(url) {
26
+ try {
27
+ return new URL(url);
28
+ } catch {
29
+ return;
30
+ }
31
+ }
32
+ // src/middleware/telemetry.ts
33
+ import {
34
+ continuing,
35
+ createTelemetry,
36
+ withTelemetry
37
+ } from "@softistx/telemetry";
38
+ import { matchedRoutes } from "hono/route";
39
+
40
+ // src/middleware/variables.ts
41
+ var TELEMETRY_VARIABLE = "telemetry";
42
+ var SPAN_VARIABLE = "span";
43
+
44
+ // src/middleware/telemetry.ts
45
+ function telemetry(options) {
46
+ const instance = options.instance ?? createTelemetry(options.service, options).install();
47
+ const traced = guarded(options.traced ?? always, always);
48
+ const spanName = guarded(options.spanName ?? defaultName, defaultName);
49
+ const route = guarded(options.route ?? defaultRoute, nothing);
50
+ const handler = async (c, next) => {
51
+ if (!traced(c))
52
+ return next();
53
+ return withTelemetry(instance, () => continuing(c.req.header("traceparent"), spanName(c), { kind: "server", attributes: requestAttributes(c.req.raw) }, async (scope) => {
54
+ c.set(TELEMETRY_VARIABLE, instance);
55
+ c.set(SPAN_VARIABLE, scope);
56
+ try {
57
+ await next();
58
+ } finally {
59
+ rename(c, scope, route);
60
+ }
61
+ record(c, scope);
62
+ }));
63
+ };
64
+ return Object.assign(handler, { telemetry: instance });
65
+ }
66
+ function defaultRoute(c) {
67
+ const handled = matchedRoutes(c).filter((matched) => matched.handler.length < 2);
68
+ return handled.at(-1)?.path;
69
+ }
70
+ function defaultName(c) {
71
+ return `${c.req.method} ${c.req.path}`;
72
+ }
73
+ function guarded(hook, fallback) {
74
+ return (c) => {
75
+ try {
76
+ return hook(c);
77
+ } catch {
78
+ return fallback(c);
79
+ }
80
+ };
81
+ }
82
+ function always() {
83
+ return true;
84
+ }
85
+ function nothing() {
86
+ return;
87
+ }
88
+ function rename(c, scope, route) {
89
+ const template = route(c);
90
+ if (template === undefined || template === "")
91
+ return;
92
+ scope.name = `${c.req.method} ${template}`;
93
+ scope.attribute(HTTP_ROUTE, template);
94
+ }
95
+ function record(c, scope) {
96
+ const status = statusOf(c);
97
+ if (c.error !== undefined) {
98
+ const before = scope.status;
99
+ scope.fail(c.error);
100
+ if (status !== undefined && !serverFailed(status))
101
+ scope.status = before;
102
+ }
103
+ if (status === undefined)
104
+ return;
105
+ scope.attribute(HTTP_STATUS, status);
106
+ if (serverFailed(status) && scope.status === "ok")
107
+ scope.status = "error";
108
+ }
109
+ function statusOf(c) {
110
+ try {
111
+ return c.res.status;
112
+ } catch {
113
+ return;
114
+ }
115
+ }
116
+ export {
117
+ HTTP_METHOD,
118
+ HTTP_ROUTE,
119
+ HTTP_STATUS,
120
+ SERVER_ADDRESS,
121
+ SERVER_ERROR_FROM,
122
+ SERVER_PORT,
123
+ SPAN_VARIABLE,
124
+ TELEMETRY_VARIABLE,
125
+ URL_PATH,
126
+ URL_SCHEME,
127
+ requestAttributes,
128
+ serverFailed,
129
+ telemetry
130
+ };
131
+
132
+ //# debugId=17434F8203A338E464756E2164756E21
133
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/attributes/http.ts", "../src/middleware/telemetry.ts", "../src/middleware/variables.ts"],
4
+ "sourcesContent": [
5
+ "import type { Attributes } from '@softistx/telemetry';\n\n/**\n * The semantic conventions this middleware sets, by name. They are the ones a\n * backend's HTTP dashboards look for, and getting a name wrong means the\n * attribute is still there and the dashboard is still empty.\n *\n * `-httpyz` sets four of the same names on the client side. That duplication is\n * deliberate and recorded in `AGENTS.md`: a shared helper would make each\n * package depend on the other's host.\n */\nexport const HTTP_METHOD = 'http.request.method';\nexport const URL_PATH = 'url.path';\nexport const URL_SCHEME = 'url.scheme';\nexport const HTTP_ROUTE = 'http.route';\nexport const HTTP_STATUS = 'http.response.status_code';\nexport const SERVER_ADDRESS = 'server.address';\nexport const SERVER_PORT = 'server.port';\n\n/** The status at which a server span is the server's fault, and not before. */\nexport const SERVER_ERROR_FROM = 500;\n\n/**\n * What is known about a request **before** it is handled: the method, the path\n * as it arrived, and where it was addressed.\n *\n * The route is not here. It is not known until the router has matched, which is\n * after `next()`, and a span named for the path it arrived at would give a\n * dashboard one row per order id.\n */\nexport function requestAttributes(request: Request): Attributes {\n\tconst url = safeUrl(request.url);\n\n\treturn {\n\t\t[HTTP_METHOD]: request.method,\n\t\t...(url === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\t[URL_PATH]: url.pathname,\n\t\t\t\t\t[URL_SCHEME]: url.protocol.replace(':', ''),\n\t\t\t\t\t// The host **without** the port, which goes in its own\n\t\t\t\t\t// attribute. `-httpyz` splits them the same way, and a\n\t\t\t\t\t// server span and the client span that called it have to\n\t\t\t\t\t// agree on a name every HTTP dashboard groups by.\n\t\t\t\t\t[SERVER_ADDRESS]: url.hostname,\n\t\t\t\t\t...(url.port === '' ? {} : { [SERVER_PORT]: Number(url.port) }),\n\t\t\t\t}),\n\t};\n}\n\n/**\n * Whether a reply says the server failed.\n *\n * **A 4xx is `ok`.** The client sent something the server refused, which is the\n * server working; counting it as an error is what makes an error rate that\n * nobody can act on. Only `5xx` marks the span.\n */\nexport function serverFailed(status: number): boolean {\n\treturn status >= SERVER_ERROR_FROM;\n}\n\nfunction safeUrl(url: string): URL | undefined {\n\ttry {\n\t\treturn new URL(url);\n\t} catch {\n\t\t// A request whose URL this runtime will not parse still gets a span.\n\t\treturn undefined;\n\t}\n}\n",
6
+ "import {\n\tcontinuing,\n\tcreateTelemetry,\n\ttype SpanScope,\n\ttype Telemetry,\n\ttype TelemetryOptions,\n\twithTelemetry,\n} from '@softistx/telemetry';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { matchedRoutes } from 'hono/route';\nimport {\n\tHTTP_ROUTE,\n\tHTTP_STATUS,\n\trequestAttributes,\n\tserverFailed,\n} from '../attributes/http';\nimport { SPAN_VARIABLE, TELEMETRY_VARIABLE } from './variables';\n\n/** The hooks both shapes of the middleware share. */\ninterface Hooks {\n\t/**\n\t * Whether this request gets a span at all. Default: every request does.\n\t *\n\t * This is the health-check hook. Nothing is skipped by default, because a\n\t * library that decides for you which requests do not matter is a library\n\t * that hides the one that did.\n\t */\n\treadonly traced?: (c: Context) => boolean;\n\t/**\n\t * The span's name **before** routing. Default `\"<METHOD> <path>\"`, which is\n\t * replaced by `\"<METHOD> <route>\"` once the router has matched.\n\t */\n\treadonly spanName?: (c: Context) => string;\n\t/**\n\t * The route template, once the handler has run. Default `routePath(c, -1)`.\n\t * Return `undefined` to leave the span named as it was.\n\t */\n\treadonly route?: (c: Context) => string | undefined;\n}\n\n/**\n * Either build a telemetry from `service` and the usual options, or hand one\n * over as `instance`. The compiler refuses both at once: `service` would be\n * silently ignored beside an instance that already has one.\n */\nexport type TelemetryMiddlewareOptions =\n\t| (Hooks &\n\t\t\tTelemetryOptions & {\n\t\t\t\t/** The service name. Everything groups by it. */\n\t\t\t\treadonly service: string;\n\t\t\t\treadonly instance?: undefined;\n\t\t\t})\n\t| (Hooks & {\n\t\t\t/** An existing telemetry. It is **adopted, not closed**. */\n\t\t\treadonly instance: Telemetry;\n\t\t\treadonly service?: undefined;\n\t });\n\n/** The middleware, with the telemetry it is writing to. */\nexport interface TelemetryMiddleware extends MiddlewareHandler {\n\t/**\n\t * The telemetry this middleware uses — the one it built, or the one it was\n\t * handed. `close()` it on shutdown; nothing here does that for you, because\n\t * a middleware has no shutdown to hook.\n\t */\n\treadonly telemetry: Telemetry;\n}\n\n/**\n * One server span per request, around the whole handler.\n *\n * ```ts\n * const tracing = telemetry({\n * service: 'checkout',\n * exporters: [otlpExporter({ endpoint: 'http://localhost:4318' })],\n * traced: (c) => c.req.path !== '/health',\n * });\n *\n * app.use('*', tracing);\n * process.on('SIGTERM', () => void tracing.telemetry.close());\n * ```\n *\n * The span **wraps `next()`** rather than being two hooks. That is what puts\n * the whole handler — and everything it awaits, and everything it throws —\n * inside the span's context, so `log.info()` in a service three calls down\n * carries this request's `traceId` without anything being passed to it.\n *\n * An inbound `traceparent` continues its trace. An unusable one is not an\n * error: it starts a fresh trace, because the header came from a stranger.\n */\nexport function telemetry(\n\toptions: TelemetryMiddlewareOptions,\n): TelemetryMiddleware {\n\tconst instance =\n\t\toptions.instance ?? createTelemetry(options.service, options).install();\n\n\t// Every hook is application code, and every hook is on the path that decides\n\t// whether a request is observed. One that throws must cost its answer, not\n\t// the request: a predicate that raises would otherwise turn observability\n\t// into an outage.\n\tconst traced = guarded(options.traced ?? always, always);\n\tconst spanName = guarded(options.spanName ?? defaultName, defaultName);\n\tconst route = guarded(options.route ?? defaultRoute, nothing);\n\n\tconst handler: MiddlewareHandler = async (c, next) => {\n\t\tif (!traced(c)) return next();\n\n\t\treturn withTelemetry(instance, () =>\n\t\t\tcontinuing(\n\t\t\t\tc.req.header('traceparent'),\n\t\t\t\tspanName(c),\n\t\t\t\t{ kind: 'server', attributes: requestAttributes(c.req.raw) },\n\t\t\t\tasync (scope) => {\n\t\t\t\t\tc.set(TELEMETRY_VARIABLE, instance);\n\t\t\t\t\tc.set(SPAN_VARIABLE, scope);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait next();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\t// Even a handler that threw was routed, and the route is\n\t\t\t\t\t\t// what the span should be called either way.\n\t\t\t\t\t\trename(c, scope, route);\n\t\t\t\t\t}\n\n\t\t\t\t\trecord(c, scope);\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\n\treturn Object.assign(handler, { telemetry: instance });\n}\n\n/**\n * The route template, which is only known **after** the router has matched.\n *\n * It is the last *handler* among the matched routes, not simply the last match:\n * `routePath(c)` answers whichever route ran last, which is a middleware\n * registered after the routes, and `routePath(c, -1)` — besides taking a second\n * argument only since hono 4.10 — answers the last entry whatever it is. Hono's\n * own `matchedRoutes` example tells a handler from a middleware by its arity,\n * because a middleware takes `(c, next)` and a handler takes `(c)`.\n *\n * Nothing matched means there is no route to report: a 404, or a request that\n * only ever reached `app.use('*', …)`.\n */\nfunction defaultRoute(c: Context): string | undefined {\n\tconst handled = matchedRoutes(c).filter(\n\t\t(matched) =>\n\t\t\t(matched.handler as (...args: unknown[]) => unknown).length < 2,\n\t);\n\n\treturn handled.at(-1)?.path;\n}\n\nfunction defaultName(c: Context): string {\n\treturn `${c.req.method} ${c.req.path}`;\n}\n\n/** A hook, and what to ask instead when it throws. */\nfunction guarded<T>(\n\thook: (c: Context) => T,\n\tfallback: (c: Context) => T,\n): (c: Context) => T {\n\treturn (c) => {\n\t\ttry {\n\t\t\treturn hook(c);\n\t\t} catch {\n\t\t\treturn fallback(c);\n\t\t}\n\t};\n}\n\nfunction always(): true {\n\treturn true;\n}\n\nfunction nothing(): undefined {\n\treturn undefined;\n}\n\n/**\n * A span named for the path it arrived at gives a dashboard one row per order\n * id. The template is the name; the path stays as `url.path`.\n */\nfunction rename(\n\tc: Context,\n\tscope: SpanScope,\n\troute: (c: Context) => string | undefined,\n): void {\n\tconst template = route(c);\n\n\t// There is no wildcard to filter out here: the template comes from a\n\t// handler, and a handler's registered path is a route the application\n\t// chose — `app.get('/files/*')` included. The patterns worth dropping are\n\t// `app.use`'s, and those never reach this.\n\tif (template === undefined || template === '') return;\n\n\tscope.name = `${c.req.method} ${template}`;\n\tscope.attribute(HTTP_ROUTE, template);\n}\n\n/**\n * The status, the failure, and which of them decides how the span reads.\n *\n * **Hono catches.** A handler that throws does not reject `next()`: the router\n * turns the exception into a reply and leaves it on `c.error`, so the only\n * thing that knows what went wrong is that field. Reading it is what puts\n * `exception.type` on the span; without it the span says \"error\" and nothing\n * about why.\n *\n * **The reply decides the status, not the exception.** `HTTPException` is how\n * a Hono application says `401` — it is what `basicAuth`, `bearerAuth`, `jwt`\n * and the validators all throw — so letting a thrown failure mark the span\n * would put every rejected login in the error rate. A `4xx` is the server\n * working. Only a `5xx` is the server's fault, and only then does an `ok` span\n * become an `error` one.\n *\n * A status the scope already decided is left alone: an abort answered with a\n * `500` stays `cancelled`, which is the whole reason that status exists.\n */\nfunction record(c: Context, scope: SpanScope): void {\n\tconst status = statusOf(c);\n\n\tif (c.error !== undefined) {\n\t\tconst before = scope.status;\n\t\t// Records `exception.*`. It also sets a status, which is right when the\n\t\t// exception is the reply and wrong when the reply is a 4xx.\n\t\tscope.fail(c.error);\n\t\tif (status !== undefined && !serverFailed(status)) scope.status = before;\n\t}\n\n\tif (status === undefined) return;\n\n\tscope.attribute(HTTP_STATUS, status);\n\tif (serverFailed(status) && scope.status === 'ok') scope.status = 'error';\n}\n\nfunction statusOf(c: Context): number | undefined {\n\ttry {\n\t\treturn c.res.status;\n\t} catch {\n\t\t// A response this runtime will not build is not worth losing the span\n\t\t// over.\n\t\treturn undefined;\n\t}\n}\n",
7
+ "import type { SpanScope, Telemetry } from '@softistx/telemetry';\n\n/**\n * What the middleware puts on the request context.\n *\n * Augmenting `ContextVariableMap` rather than asking for a typed `Env` is what\n * makes `c.get('span')` typed in a handler that knows nothing about this\n * package — which is the whole point of putting it there.\n *\n * It is declared here and re-exported from the entry point, so importing\n * anything from `@softistx/telemetry-hono` is what turns it on.\n */\ndeclare module 'hono' {\n\tinterface ContextVariableMap {\n\t\t/**\n\t\t * The telemetry this request is being written to.\n\t\t *\n\t\t * **Optional**, and the compiler enforces it: a request `traced` refused\n\t\t * never had a middleware set it, so `c.get('telemetry')` is `undefined`\n\t\t * there. Type safety is what the compiler rejects, not what a README\n\t\t * claims.\n\t\t */\n\t\ttelemetry?: Telemetry;\n\t\t/** The server span around this request. `undefined` when `traced` said no. */\n\t\tspan?: SpanScope;\n\t}\n}\n\n/** The keys, as values, for code that sets them by name. */\nexport const TELEMETRY_VARIABLE = 'telemetry';\nexport const SPAN_VARIABLE = 'span';\n"
8
+ ],
9
+ "mappings": "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",
10
+ "debugId": "17434F8203A338E464756E2164756E21",
11
+ "names": []
12
+ }
@@ -0,0 +1,71 @@
1
+ import { type Telemetry, type TelemetryOptions } from '@softistx/telemetry';
2
+ import type { Context, MiddlewareHandler } from 'hono';
3
+ /** The hooks both shapes of the middleware share. */
4
+ interface Hooks {
5
+ /**
6
+ * Whether this request gets a span at all. Default: every request does.
7
+ *
8
+ * This is the health-check hook. Nothing is skipped by default, because a
9
+ * library that decides for you which requests do not matter is a library
10
+ * that hides the one that did.
11
+ */
12
+ readonly traced?: (c: Context) => boolean;
13
+ /**
14
+ * The span's name **before** routing. Default `"<METHOD> <path>"`, which is
15
+ * replaced by `"<METHOD> <route>"` once the router has matched.
16
+ */
17
+ readonly spanName?: (c: Context) => string;
18
+ /**
19
+ * The route template, once the handler has run. Default `routePath(c, -1)`.
20
+ * Return `undefined` to leave the span named as it was.
21
+ */
22
+ readonly route?: (c: Context) => string | undefined;
23
+ }
24
+ /**
25
+ * Either build a telemetry from `service` and the usual options, or hand one
26
+ * over as `instance`. The compiler refuses both at once: `service` would be
27
+ * silently ignored beside an instance that already has one.
28
+ */
29
+ export type TelemetryMiddlewareOptions = (Hooks & TelemetryOptions & {
30
+ /** The service name. Everything groups by it. */
31
+ readonly service: string;
32
+ readonly instance?: undefined;
33
+ }) | (Hooks & {
34
+ /** An existing telemetry. It is **adopted, not closed**. */
35
+ readonly instance: Telemetry;
36
+ readonly service?: undefined;
37
+ });
38
+ /** The middleware, with the telemetry it is writing to. */
39
+ export interface TelemetryMiddleware extends MiddlewareHandler {
40
+ /**
41
+ * The telemetry this middleware uses — the one it built, or the one it was
42
+ * handed. `close()` it on shutdown; nothing here does that for you, because
43
+ * a middleware has no shutdown to hook.
44
+ */
45
+ readonly telemetry: Telemetry;
46
+ }
47
+ /**
48
+ * One server span per request, around the whole handler.
49
+ *
50
+ * ```ts
51
+ * const tracing = telemetry({
52
+ * service: 'checkout',
53
+ * exporters: [otlpExporter({ endpoint: 'http://localhost:4318' })],
54
+ * traced: (c) => c.req.path !== '/health',
55
+ * });
56
+ *
57
+ * app.use('*', tracing);
58
+ * process.on('SIGTERM', () => void tracing.telemetry.close());
59
+ * ```
60
+ *
61
+ * The span **wraps `next()`** rather than being two hooks. That is what puts
62
+ * the whole handler — and everything it awaits, and everything it throws —
63
+ * inside the span's context, so `log.info()` in a service three calls down
64
+ * carries this request's `traceId` without anything being passed to it.
65
+ *
66
+ * An inbound `traceparent` continues its trace. An unusable one is not an
67
+ * error: it starts a fresh trace, because the header came from a stranger.
68
+ */
69
+ export declare function telemetry(options: TelemetryMiddlewareOptions): TelemetryMiddleware;
70
+ export {};
71
+ //# sourceMappingURL=telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/middleware/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,SAAS,EACd,KAAK,gBAAgB,EAErB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAUvD,qDAAqD;AACrD,UAAU,KAAK;IACd;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,MAAM,CAAC;IAC3C;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,MAAM,GAAG,SAAS,CAAC;CACpD;AAED;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GACnC,CAAC,KAAK,GACN,gBAAgB,GAAG;IAClB,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;CAC9B,CAAC,GACF,CAAC,KAAK,GAAG;IACT,4DAA4D;IAC5D,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;IAC7B,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC;CAC5B,CAAC,CAAC;AAEN,2DAA2D;AAC3D,MAAM,WAAW,mBAAoB,SAAQ,iBAAiB;IAC7D;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,0BAA0B,GACjC,mBAAmB,CAuCrB"}
@@ -0,0 +1,30 @@
1
+ import type { SpanScope, Telemetry } from '@softistx/telemetry';
2
+ /**
3
+ * What the middleware puts on the request context.
4
+ *
5
+ * Augmenting `ContextVariableMap` rather than asking for a typed `Env` is what
6
+ * makes `c.get('span')` typed in a handler that knows nothing about this
7
+ * package — which is the whole point of putting it there.
8
+ *
9
+ * It is declared here and re-exported from the entry point, so importing
10
+ * anything from `@softistx/telemetry-hono` is what turns it on.
11
+ */
12
+ declare module 'hono' {
13
+ interface ContextVariableMap {
14
+ /**
15
+ * The telemetry this request is being written to.
16
+ *
17
+ * **Optional**, and the compiler enforces it: a request `traced` refused
18
+ * never had a middleware set it, so `c.get('telemetry')` is `undefined`
19
+ * there. Type safety is what the compiler rejects, not what a README
20
+ * claims.
21
+ */
22
+ telemetry?: Telemetry;
23
+ /** The server span around this request. `undefined` when `traced` said no. */
24
+ span?: SpanScope;
25
+ }
26
+ }
27
+ /** The keys, as values, for code that sets them by name. */
28
+ export declare const TELEMETRY_VARIABLE = "telemetry";
29
+ export declare const SPAN_VARIABLE = "span";
30
+ //# sourceMappingURL=variables.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"variables.d.ts","sourceRoot":"","sources":["../../src/middleware/variables.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhE;;;;;;;;;GASG;AACH,OAAO,QAAQ,MAAM,CAAC;IACrB,UAAU,kBAAkB;QAC3B;;;;;;;WAOG;QACH,SAAS,CAAC,EAAE,SAAS,CAAC;QACtB,8EAA8E;QAC9E,IAAI,CAAC,EAAE,SAAS,CAAC;KACjB;CACD;AAED,4DAA4D;AAC5D,eAAO,MAAM,kBAAkB,cAAc,CAAC;AAC9C,eAAO,MAAM,aAAa,SAAS,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
- "name": "@softistx/telemetry-hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@softistx/telemetry-hono",
3
+ "version": "0.3.3",
4
+ "description": "A Hono middleware for @softistx/telemetry: one server span per request, W3C traceparent continuation, and the route as the span name",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "package.json",
13
+ "LICENSE"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "keywords": [
24
+ "hono",
25
+ "telemetry",
26
+ "observability",
27
+ "tracing",
28
+ "middleware",
29
+ "traceparent",
30
+ "opentelemetry",
31
+ "typescript"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/softistx/nxgt-telemetry.git",
36
+ "directory": "packages/telemetry-hono"
37
+ },
38
+ "publishConfig": {
39
+ "registry": "https://registry.npmjs.org",
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "bun run ../../build.ts",
44
+ "test": "bun test src",
45
+ "typecheck": "tsc --noEmit"
46
+ },
47
+ "nxgt": {
48
+ "entrypoints": [
49
+ "src/index.ts"
50
+ ]
51
+ },
52
+ "dependencies": {
53
+ "@softistx/telemetry": "^0.4.2"
54
+ },
55
+ "devDependencies": {
56
+ "@types/bun": "^1.4.2",
57
+ "hono": "4.13.8"
58
+ },
59
+ "peerDependencies": {
60
+ "hono": "^4.8.0",
61
+ "typescript": "^6.0.3 || ^7.0.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "hono": {
65
+ "optional": true
66
+ },
67
+ "typescript": {
68
+ "optional": true
69
+ }
70
+ }
71
+ }