@appweaver/skill 0.0.0-stage → 3.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.
@@ -0,0 +1,207 @@
1
+ # Telemetry (OpenTelemetry)
2
+
3
+ Appweaver is instrumented with [OpenTelemetry](https://opentelemetry.io): the framework records traces and metrics
4
+ through the OpenTelemetry API, and the `@appweaver/opentelemetry` module starts the SDK exporting them, with the logs,
5
+ over OTLP. The config keys are listed in [configuration.md](./configuration.md#telemetry-telemetry_).
6
+
7
+ Two parts, on purpose:
8
+
9
+ - **Instrumentation** — in `@appweaver/common`, `core`, `data`, `web` and the drivers, through `@opentelemetry/api`
10
+ only. It records nothing, at no cost, until an SDK is registered, and reaches _any_ registered SDK.
11
+ - **SDK** — `@appweaver/opentelemetry`, enabled by installing it (`weaver module add telemetry`, or
12
+ `npm install @appweaver/opentelemetry`). It reads the `telemetry` config, exports over OTLP (HTTP), and is flushed
13
+ and stopped with the application.
14
+
15
+ There is no telemetry contract and no provider per vendor: OTLP is the standard every backend ingests, see
16
+ [Backends](#backends).
17
+
18
+ ## What is recorded
19
+
20
+ | Part (`telemetry.instrumentations.<key>`) | Spans | Metrics |
21
+ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `http` (`@appweaver/web`) | A server span per request, `GET /api/posts/:id`, continuing the `traceparent` header, with the status and the `user.id` | `http.server.request.duration`, `http.server.active_requests` |
23
+ | `database` (`@appweaver/data`) | A client span per Prisma operation, `findMany Post` or `$queryRaw`, without the query and its arguments | `db.client.operation.duration` |
24
+ | `queue` (`memory`, `bullmq`) | A producer span `send <queue>` and a consumer span `process <queue>` per attempt, in the trace of the sender | `messaging.client.sent.messages`, `messaging.process.duration` |
25
+ | `scheduler` (`@appweaver/cron`) | The root span of a new trace per run, `scheduler <name>` | `appweaver.scheduler.job.duration` |
26
+ | `mailer`, `sms` | A client span per sent email (`mailer send`) and text message (`sms send`), inside the span of their queue job | — |
27
+ | `cache` | — | `appweaver.cache.requests` (`appweaver.cache.result`: `hit`, `miss`) |
28
+ | `task` (`weaver run`) | The root span of the task, `task <name>`, exported when the task ends | — |
29
+ | `realtime` (`@appweaver/realtime`) | A server span per action call, `realtime action <name>`, over the WebSocket or HTTP, until the end of a streaming action; a producer span per stream opened, `realtime stream <name>` | `appweaver.realtime.connections`, `appweaver.realtime.events` (`appweaver.realtime.outcome`: `delivered`, `denied`, `dropped`), `appweaver.realtime.messages`, `appweaver.realtime.streams`, `appweaver.realtime.stream.chunks`, `appweaver.realtime.stream.bytes`, `appweaver.realtime.input.bytes` |
30
+ | `ai` (`@appweaver/ai`) | A client span per model call, `chat <model>` or `embeddings <model>`, with the `gen_ai.*` attributes, and an `execute_tool <name>` span per tool call | `gen_ai.client.token.usage` (`gen_ai.token.type`: `input`, `output`), `gen_ai.client.operation.duration` |
31
+ | `mcp` (`@appweaver/mcp`) | A server span per tool call, `tools/call <tool>`, with `mcp.method.name` and `gen_ai.tool.name` | `mcp.server.operation.duration` |
32
+ | `audit` (`@appweaver/data`) | — | `appweaver.audit.written`, `appweaver.audit.dropped` |
33
+ | `payments` (`@appweaver/payments`) | A client span per call of a payment gateway, `payments createPayment`, with `appweaver.payments.gateway`, `appweaver.payments.driver` and `appweaver.payments.operation` | `appweaver.payments.gateway.duration`, `appweaver.payments.webhook.events` (`appweaver.payments.outcome`: `received`, `duplicate`, `ignored`, `invalid`, `processed`, `failed`), `appweaver.payments.events` (`appweaver.payments.event`, `appweaver.payments.outcome`: `delivered`, `retried`, `failed`) |
34
+ | `fetch` (`@appweaver/opentelemetry`) | A client span per outbound `fetch` request, which also sends the `traceparent` header. Node.js only | `http.client.request.duration` |
35
+
36
+ The names and the attributes follow the OpenTelemetry semantic conventions (`http.*`, `db.*`, `messaging.*`, `gen_ai.*`), the ones
37
+ of the framework are prefixed with `appweaver.`.
38
+
39
+ - **HTTP**: only a `5xx` response fails the span (`error.type`, the exception). A `4xx` keeps it unset and adds the
40
+ error code as `appweaver.error.code`. The health check routes are left out (`telemetry.http.healthCheck`), and so
41
+ are the paths of `telemetry.http.ignorePaths` (`['/public/*', '/favicon.ico']`). An unknown route is named after its
42
+ method alone.
43
+ - **Queue**: the trace context travels with the job, so the request that sent a job, the job and everything the worker
44
+ does are one trace, whichever process runs the worker. BullMQ stores it in the `telemetry.metadata` option of the
45
+ job, which `bullmq-otel` of another service reads too.
46
+ - **Payments**: the span of a gateway call is the parent of the `fetch` span of the request the Stripe SDK sends, and
47
+ the processing of a webhook event runs in the trace of its `payments` queue job. A failed call records its
48
+ `error.type` on the span and on the `appweaver.payments.gateway.duration` series. No amount, card detail or customer
49
+ is ever an attribute.
50
+ - **Scheduler**: name a job to name its spans and its metric series, `addJob({ name: 'reports:daily', ... })`.
51
+ - **Problem details**: an error response of a traced request carries the `traceId` next to the `requestId`, to find
52
+ its trace from a bug report.
53
+
54
+ ## Configuration
55
+
56
+ ```jsonc
57
+ // appweaver.json
58
+ "telemetry": {
59
+ "endpoint": "http://${OTEL_HOST:-localhost}:4318",
60
+ "headers": ["x-api-key=${OTEL_API_KEY}"],
61
+ "traces": { "sampleRatio": 0.2 },
62
+ "logs": { "enabled": true, "level": "warn" },
63
+ "http": { "ignorePaths": ["/public/*"] },
64
+ "instrumentations": { "cache": false }
65
+ }
66
+ ```
67
+
68
+ - `telemetry.enabled: false` turns everything off: the instrumentation, the log correlation and the SDK. A project
69
+ scaffolded with the `telemetry` module sets it in the `test` environment.
70
+ - `telemetry.exporter`: `otlp` (default), `console` (prints the telemetry, for development) or `none` (the default of
71
+ the `test` environment, exporting only through the processors of `configureTelemetry`).
72
+ - The traces and the metrics are exported by default, the logs with `telemetry.logs.enabled`.
73
+ - The standard `OTEL_*` environment variables are read where the config sets nothing: `OTEL_EXPORTER_OTLP_ENDPOINT`,
74
+ `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_SERVICE_NAME`, `OTEL_RESOURCE_ATTRIBUTES`. The `telemetry` keys win.
75
+ - The service is described by `service.name` (`telemetry.serviceName`, else `app.name`), `service.version`
76
+ (`app.version`) and `deployment.environment.name` (`app.env`), plus `telemetry.resourceAttributes`
77
+ (`['service.namespace=shop']`).
78
+
79
+ ## Logs
80
+
81
+ The `log` config is untouched, telemetry adds two things to the logs:
82
+
83
+ - **Correlation** (`telemetry.logCorrelation`, on by default): every record written inside a span carries its
84
+ `trace_id`, `span_id` and `trace_flags`, on the console and in the log file, with or without the SDK module.
85
+ - **Export** (`telemetry.logs.enabled`, off by default): the records of every logger are also sent over OTLP, from
86
+ `telemetry.logs.level` up, with the logger name as `appweaver.logger`, the error as `exception.*` and the trace of
87
+ their span. The level never lowers what a logger writes (`log.level`, `log.levels`).
88
+
89
+ ## Custom spans and metrics
90
+
91
+ `@appweaver/common` exports the helpers the framework itself uses, so application code needs no OpenTelemetry import:
92
+
93
+ ```ts
94
+ import { currentSpan, telemetryCounter, withSpan } from '@appweaver/common';
95
+
96
+ const invoices = telemetryCounter('billing.invoices', {
97
+ description: 'Invoices issued.'
98
+ });
99
+
100
+ export async function issueInvoice(orderId: number) {
101
+ // The span of the request or the job this runs in
102
+ currentSpan()?.setAttribute('order.id', orderId);
103
+
104
+ // Ends when the promise settles, an error is recorded on it and thrown again
105
+ return withSpan(
106
+ 'invoice render',
107
+ { attributes: { 'order.id': orderId } },
108
+ async (span) => {
109
+ const pdf = await render(orderId);
110
+ span.setAttribute('invoice.size', pdf.length);
111
+ invoices().add(1, { currency: 'EUR' });
112
+ return pdf;
113
+ }
114
+ );
115
+ }
116
+ ```
117
+
118
+ | Helper | Purpose |
119
+ | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
120
+ | `withSpan(name, options, fn)` | Runs `fn` in a span, the parent of what it calls. `options`: `kind`, `attributes`, `root`, `parent` |
121
+ | `startSpan(name, options)` / `runInTraceContext(context, fn)` | A span ended by the caller, and running code as its child |
122
+ | `currentSpan()` / `currentTraceId()` | The active span and the id of its trace |
123
+ | `telemetryCounter` / `telemetryUpDownCounter` / `telemetryHistogram` | Declare a metric once at module level, call the result to record: `counter().add(1)` |
124
+ | `injectTraceContext()` / `extractTraceContext(carrier)` | Carry a trace through a transport of your own (a message, a file, a webhook) |
125
+ | `traceQueueSend` / `traceQueueProcess` | The producer and consumer spans of a custom `Queue` driver |
126
+ | `telemetryEnabled(part?)` | Whether telemetry, or one part of it, is on |
127
+ | `telemetryTracer()` / `telemetryMeter()` | The tracer and the meter, for anything else |
128
+
129
+ Keep span names free of ids and other high-cardinality values, put them into attributes. For the full API install
130
+ `@opentelemetry/api` (the version of `@appweaver/common`), it shares the same global SDK.
131
+
132
+ ## Backends
133
+
134
+ | Route | How | Use for |
135
+ | -------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
136
+ | OTLP config | `telemetry.endpoint` and `telemetry.headers`, or the `OTEL_EXPORTER_OTLP_*` variables | Honeycomb, Datadog, Sentry, Grafana, New Relic, an OpenTelemetry Collector |
137
+ | `configureTelemetry` | Add or replace exporters, processors, the sampler, the id generator, instrumentations | A vendor exporter, AWS X-Ray ids and propagator, Prisma engine spans |
138
+ | Own SDK | Do not install `@appweaver/opentelemetry`, start the SDK of the vendor before the application | `dd-trace`, the Sentry SDK, the Azure Monitor distro, ADOT |
139
+
140
+ ```jsonc
141
+ // Honeycomb
142
+ "telemetry": { "endpoint": "https://api.honeycomb.io", "headers": ["x-honeycomb-team=${HONEYCOMB_API_KEY}"] }
143
+ // A collector or an agent on the host (Datadog Agent, Grafana Alloy, ADOT for X-Ray, ...)
144
+ "telemetry": { "endpoint": "http://localhost:4318" }
145
+ ```
146
+
147
+ A backend that takes no OTLP directly (AWS X-Ray, Azure Application Insights) is reached through a collector, or its
148
+ exporter with `configureTelemetry`. Call it before the application starts, in an application file or the `main` part
149
+ of a module:
150
+
151
+ ```ts
152
+ // src/features/telemetry/index.ts
153
+ import { configureTelemetry } from '@appweaver/opentelemetry';
154
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace';
155
+ import { PrismaInstrumentation } from '@prisma/instrumentation';
156
+
157
+ configureTelemetry((options) => {
158
+ // The parts created from the config, changed in place
159
+ options.spanProcessors.push(
160
+ new BatchSpanProcessor({ exporter: new MyVendorExporter() })
161
+ );
162
+ options.instrumentations.push(new PrismaInstrumentation());
163
+ options.resourceAttributes['service.namespace'] = 'shop';
164
+ });
165
+ ```
166
+
167
+ `options` holds `resourceAttributes`, `spanProcessors`, `sampler`, `propagator`, `metricReaders`, `views`,
168
+ `logRecordProcessors`, `instrumentations`, `idGenerator` and `contextManager`. With `telemetry.exporter: 'none'` only
169
+ what the function adds is exported.
170
+
171
+ When another OpenTelemetry SDK is already registered, `@appweaver/opentelemetry` leaves it in place with a warning,
172
+ and the framework spans go to it. The instrumentations patching a library when it is imported (`pg`, `ioredis`) are not
173
+ included: the Prisma operations and the queue jobs are traced by the framework, and such an instrumentation must be
174
+ loaded with `node --import` before the application.
175
+
176
+ To look at traces locally without a vendor, run Jaeger and keep the default endpoint:
177
+
178
+ ```sh
179
+ docker run --rm -p 16686:16686 -p 4318:4318 jaegertracing/jaeger
180
+ ```
181
+
182
+ ## Testing
183
+
184
+ `recordTelemetry` of `@appweaver/testing` registers an in-memory SDK, so a test reads the spans and the metrics of the
185
+ framework and of the application:
186
+
187
+ ```ts
188
+ import { recordTelemetry, TelemetryRecorder } from '@appweaver/testing';
189
+
190
+ let telemetry: TelemetryRecorder;
191
+ beforeEach(() => (telemetry = recordTelemetry()));
192
+ afterEach(() => telemetry.stop());
193
+
194
+ test('traces the invoice', async () => {
195
+ await issueInvoice(7);
196
+
197
+ expect(telemetry.span('invoice render').attributes).toMatchObject({
198
+ 'order.id': 7
199
+ });
200
+ expect(
201
+ (await telemetry.metric('billing.invoices'))?.dataPoints[0].value
202
+ ).toBe(1);
203
+ });
204
+ ```
205
+
206
+ `TelemetryService` of `@appweaver/opentelemetry` (`inject(TelemetryService)`) exposes the started `sdk` and
207
+ `forceFlush()`, for a process exiting without stopping the application.