@tracelumo/node 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 CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # TRACELUMO for Node.js
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
+ `@tracelumo/node` adds automatic tracing to Node.js applications. It instruments Node HTTP and HTTPS, Express, and built-in `fetch`. It sends traces to your TRACELUMO project over OTLP/HTTP protobuf with request batching and W3C trace propagation. Requires Node.js 22.15 or later.
4
+
5
+ ## Set up
6
+
7
+ Install the SDK in your application.
8
+
9
+ ```sh
10
+ npm install @tracelumo/node
11
+ ```
12
+
13
+ Create a project token in **Agent tokens**. Set two environment variables in your app's environment or in its `.env.local`.
14
+
15
+ ```dotenv
16
+ TRACELUMO_OTLP_ENDPOINT=http://127.0.0.1:8080
17
+ TRACELUMO_AGENT_TOKEN=tl_agent_your_project_token
18
+ ```
19
+
20
+ With the package installed, preload it before your application starts.
21
+
22
+ ```sh
23
+ node --require @tracelumo/node/register server.js
24
+ ```
25
+
26
+ For an existing npm script, pass the preload through `NODE_OPTIONS`.
27
+
28
+ ```sh
29
+ NODE_OPTIONS="--require @tracelumo/node/register" npm run dev
30
+ ```
31
+
32
+ Make a request and open your project's **Traces Explorer**. The service defaults to the `name` in your app's `package.json`. Set `TRACELUMO_SERVICE_NAME` to label it explicitly. Endpoint URLs accept an origin or the full trace endpoint. Remote endpoints use HTTPS.
33
+
34
+ Use a single OpenTelemetry preload. If you already initialize a tracer, replace that startup hook when moving to this package. Your settings and tracing SDK can remain server-side. `TRACELUMO_ENABLED=false` disables the preload.
35
+
36
+ ## Lifecycle hooks
37
+
38
+ Long-running apps export completed spans automatically. Short jobs and custom shutdown handlers can call `await flush()` to export buffered spans or `await shutdown()` to stop tracing and close the exporter. These functions are available from the package's CommonJS and ESM entry points. The package leaves process signal handling to the application.
39
+
40
+ ```js
41
+ import { shutdown } from "@tracelumo/node";
42
+
43
+ await shutdown();
44
+ ```
45
+
46
+ ## Local package
47
+
48
+ From the TRACELUMO repository, run
49
+
50
+ ```sh
51
+ (cd packages/node && npm pack --pack-destination /tmp)
52
+ ```
53
+
54
+ Then run `npm install /tmp/tracelumo-node-0.1.0.tgz` in the application directory.
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@tracelumo/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Automatic Node.js tracing for TRACELUMO",
5
+ "type": "commonjs",
6
+ "main": "./src/index.cjs",
7
+ "exports": {
8
+ ".": {
9
+ "import": {
10
+ "types": "./src/index.d.mts",
11
+ "default": "./src/index.mjs"
12
+ },
13
+ "require": {
14
+ "types": "./src/index.d.cts",
15
+ "default": "./src/index.cjs"
16
+ }
17
+ },
18
+ "./register": {
19
+ "types": "./src/register.d.cts",
20
+ "default": "./src/register.cjs"
21
+ }
22
+ },
23
+ "files": [
24
+ "src/"
25
+ ],
26
+ "engines": {
27
+ "node": ">=22.15.0"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test test/*.test.cjs"
31
+ },
32
+ "dependencies": {
33
+ "@opentelemetry/api": "^1.10.0",
34
+ "@opentelemetry/context-async-hooks": "^3.1.1",
35
+ "@opentelemetry/core": "^3.1.1",
36
+ "@opentelemetry/instrumentation": "^0.301.2",
37
+ "@opentelemetry/instrumentation-express": "^0.73.0",
38
+ "@opentelemetry/instrumentation-http": "^0.301.2",
39
+ "@opentelemetry/instrumentation-undici": "^0.35.1",
40
+ "@opentelemetry/otlp-exporter-base": "0.301.2",
41
+ "@opentelemetry/otlp-transformer": "0.301.2",
42
+ "@opentelemetry/resources": "^3.1.1",
43
+ "@opentelemetry/sdk-trace": "^3.1.1"
44
+ },
45
+ "devDependencies": {
46
+ "express": "^5.3.0"
47
+ }
48
+ }
package/src/config.cjs ADDED
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ const { readFileSync } = require('node:fs');
4
+ const { resolve } = require('node:path');
5
+ const { parseEnv } = require('node:util');
6
+
7
+ function readIfPresent(path) {
8
+ try {
9
+ return readFileSync(path, 'utf8');
10
+ } catch (error) {
11
+ if (error.code === 'ENOENT') return '';
12
+ throw error;
13
+ }
14
+ }
15
+
16
+ function appName(cwd) {
17
+ const manifest = readIfPresent(resolve(cwd, 'package.json'));
18
+ if (!manifest) return 'node-app';
19
+ const name = JSON.parse(manifest)?.name;
20
+ return typeof name === 'string' && name.trim() ? name : 'node-app';
21
+ }
22
+
23
+ function traceURL(endpoint) {
24
+ let url;
25
+ try {
26
+ url = new URL(endpoint);
27
+ } catch {
28
+ throw new Error('Set TRACELUMO_OTLP_ENDPOINT to an absolute HTTP or HTTPS URL.');
29
+ }
30
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
31
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
32
+ url.username || url.password || url.search || url.hash) {
33
+ throw new Error('Use an HTTPS endpoint without credentials, query parameters, or a fragment. HTTP is available on loopback.');
34
+ }
35
+ const path = url.pathname.replace(/\/+$/, '');
36
+ url.pathname = path.endsWith('/v1/traces') ? path : `${path}/v1/traces`;
37
+ return url.href;
38
+ }
39
+
40
+ function configuration(options = {}, cwd = process.cwd(), environment = process.env) {
41
+ if (options.enabled === false || (options.enabled === undefined && environment.TRACELUMO_ENABLED === 'false')) return null;
42
+
43
+ const dotEnv = {
44
+ ...parseEnv(readIfPresent(resolve(cwd, '.env'))),
45
+ ...parseEnv(readIfPresent(resolve(cwd, '.env.local'))),
46
+ };
47
+ const setting = (key) => environment[key] ?? dotEnv[key];
48
+ if (options.enabled === undefined && setting('TRACELUMO_ENABLED') === 'false') return null;
49
+
50
+ const endpoint = options.endpoint ?? setting('TRACELUMO_OTLP_ENDPOINT');
51
+ const token = (options.token ?? setting('TRACELUMO_AGENT_TOKEN') ?? '').trim();
52
+ const service = (options.serviceName ?? setting('TRACELUMO_SERVICE_NAME') ?? appName(cwd)).trim();
53
+ if (!endpoint || !token) throw new Error('Set TRACELUMO_OTLP_ENDPOINT and TRACELUMO_AGENT_TOKEN.');
54
+ if (!/^tl_agent_[A-Za-z0-9_-]{23,119}$/.test(token)) {
55
+ throw new Error('TRACELUMO_AGENT_TOKEN must be an active project agent token.');
56
+ }
57
+ if (!service || Buffer.byteLength(service) > 128 || /[\0\r\n]/.test(service)) {
58
+ throw new Error('TRACELUMO_SERVICE_NAME must contain 1 to 128 bytes on a single line.');
59
+ }
60
+ return { url: traceURL(endpoint), token, service };
61
+ }
62
+
63
+ module.exports = { configuration };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const { OTLPExporterBase } = require('@opentelemetry/otlp-exporter-base');
4
+ const { createOtlpHttpExportDelegate, httpAgentFactoryFromOptions } = require('@opentelemetry/otlp-exporter-base/node-http');
5
+ const { ProtobufTraceSerializer, TraceExporterMetricsHelper } = require('@opentelemetry/otlp-transformer');
6
+
7
+ function createExporter({ url, token }) {
8
+ // Use an explicit transport configuration so unrelated OTEL_* headers and credentials stay isolated.
9
+ const transport = createOtlpHttpExportDelegate({
10
+ url,
11
+ timeoutMillis: 5000,
12
+ concurrencyLimit: 2,
13
+ compression: 'gzip',
14
+ agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),
15
+ headers: async () => ({
16
+ 'Content-Type': 'application/x-protobuf',
17
+ Authorization: `Bearer ${token}`,
18
+ }),
19
+ }, ProtobufTraceSerializer, 'otlp_http_span_exporter', TraceExporterMetricsHelper);
20
+ return new OTLPExporterBase(transport);
21
+ }
22
+
23
+ module.exports = { createExporter };
package/src/index.cjs ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const { configuration } = require('./config.cjs');
4
+ const { syncBuiltinESMExports } = require('node:module');
5
+
6
+ const instance = Symbol.for('@tracelumo/node.sdk');
7
+
8
+ function start(options) {
9
+ if (globalThis[instance]) return;
10
+ const config = configuration(options);
11
+ if (!config) return;
12
+
13
+ const { context, propagation, trace } = require('@opentelemetry/api');
14
+ const { AsyncLocalStorageContextManager } = require('@opentelemetry/context-async-hooks');
15
+ const { W3CTraceContextPropagator } = require('@opentelemetry/core');
16
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
17
+ const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
18
+ const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
19
+ const { UndiciInstrumentation } = require('@opentelemetry/instrumentation-undici');
20
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
21
+ const { TracerProvider, BatchSpanProcessor } = require('@opentelemetry/sdk-trace');
22
+
23
+ const { createExporter } = require('./exporter.cjs');
24
+
25
+ const provider = new TracerProvider({
26
+ resource: resourceFromAttributes({ 'service.name': config.service }),
27
+ spanLimits: {
28
+ attributeCountLimit: 32,
29
+ attributeValueLengthLimit: 128,
30
+ eventCountLimit: 0,
31
+ linkCountLimit: 0,
32
+ },
33
+ spanProcessors: [new BatchSpanProcessor({
34
+ exporter: createExporter(config),
35
+ maxQueueSize: 1024,
36
+ maxExportBatchSize: 64,
37
+ scheduledDelayMillis: 1000,
38
+ exportTimeoutMillis: 6000,
39
+ })],
40
+ });
41
+
42
+ if (!trace.setGlobalTracerProvider(provider)) {
43
+ void provider.shutdown().catch(() => {});
44
+ throw new Error('An OpenTelemetry tracer is already registered. Use a single tracing preload.');
45
+ }
46
+ const manager = new AsyncLocalStorageContextManager().enable();
47
+ if (!context.setGlobalContextManager(manager)) manager.disable();
48
+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());
49
+
50
+ const stopInstrumentation = registerInstrumentations({
51
+ tracerProvider: provider,
52
+ instrumentations: [
53
+ new HttpInstrumentation(),
54
+ new ExpressInstrumentation(),
55
+ new UndiciInstrumentation(),
56
+ ],
57
+ });
58
+ // Apply the HTTP hooks before an ESM application reads named built-in exports.
59
+ require('node:http');
60
+ require('node:https');
61
+ syncBuiltinESMExports();
62
+ globalThis[instance] = { provider, stopInstrumentation };
63
+ }
64
+
65
+ async function flush() {
66
+ const sdk = globalThis[instance];
67
+ if (sdk) await (sdk.stopping ?? sdk.provider.forceFlush());
68
+ }
69
+
70
+ async function shutdown() {
71
+ const sdk = globalThis[instance];
72
+ if (!sdk) return;
73
+ if (!sdk.stopping) {
74
+ sdk.stopInstrumentation();
75
+ syncBuiltinESMExports();
76
+ sdk.stopping = sdk.provider.shutdown();
77
+ }
78
+ await sdk.stopping;
79
+ }
80
+
81
+ module.exports = { start, flush, shutdown };
@@ -0,0 +1,10 @@
1
+ export interface TracingOptions {
2
+ endpoint?: string;
3
+ token?: string;
4
+ serviceName?: string;
5
+ enabled?: boolean;
6
+ }
7
+
8
+ export function start(options?: TracingOptions): void;
9
+ export function flush(): Promise<void>;
10
+ export function shutdown(): Promise<void>;
@@ -0,0 +1 @@
1
+ export { start, flush, shutdown, type TracingOptions } from './index.cjs';
package/src/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { start, flush, shutdown } from './index.cjs';
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ try {
4
+ require('./index.cjs').start();
5
+ } catch (error) {
6
+ process.emitWarning(error.message, { code: 'TRACELUMO_SETUP' });
7
+ }
@@ -0,0 +1 @@
1
+ export {};