@decocms/blocks 8.0.0 → 8.1.0-next.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.
Files changed (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
package/src/sdk/otel.ts DELETED
@@ -1,1012 +0,0 @@
1
- /**
2
- * Single observability entry point for `@decocms/start` on Cloudflare Workers.
3
- *
4
- * `instrumentWorker(handler, options)` wraps a Worker handler with:
5
- * - structured JSON logger (stdout → Cloudflare Workers Logs) — always
6
- * - Workers Analytics Engine metrics — when `env.DECO_METRICS` binding exists
7
- * - OTLP/HTTP metrics exporter, direct POST to `deco-otel-ingest`
8
- * `/v1/metrics` — when `env.DECO_OTEL_METRICS_ENDPOINT` is set. Buffered
9
- * per-isolate, flushed via `ctx.waitUntil` at the end of every request.
10
- * See `otelHttpMeter.ts` for the aggregation + flush model.
11
- * - OTLP/HTTP error-log channel, direct POST to `deco-otel-ingest`
12
- * `/v1/logs` — when `env.DECO_OTEL_LOGS_ENDPOINT` is set. Carries
13
- * `logger.error(...)` calls at 100% capture (rate-limited per
14
- * isolate) so head-sampled CF Destinations don't drop them.
15
- * See `otelHttpLog.ts` for the rate limiter + flush model.
16
- * - Bridges framework-internal `withTracing()` calls onto the global
17
- * `@opentelemetry/api` tracer, stamping `deco.*` attributes on every span
18
- * so they survive Cloudflare's platform-managed trace export
19
- *
20
- * **Transport split.** Logs (info/warn) and traces flow through Cloudflare
21
- * Destinations (configured in `wrangler.jsonc`
22
- * `observability.{logs,traces}.destinations`). Metrics are NOT supported
23
- * by Destinations today (CF only exports OTLP for logs and traces), so the
24
- * framework POSTs them directly. Errors travel BOTH paths — via
25
- * `console.error` (sampled by CF Destinations) and direct POST (100%
26
- * capture). Same OTLP/HTTP JSON wire format, same ingest Worker.
27
- *
28
- * Required `wrangler.jsonc` block (run `scripts/migrate-to-cf-observability.ts`
29
- * to inject this automatically). Sampling defaults follow the fleet-scale cost
30
- * model documented in `docs/observability.md`:
31
- * ```jsonc
32
- * "observability": {
33
- * "enabled": true,
34
- * "logs": { "enabled": true, "invocation_logs": true,
35
- * "head_sampling_rate": 1, "persist": true },
36
- * "traces": { "enabled": true,
37
- * "head_sampling_rate": 0.01, "persist": true }
38
- * },
39
- * "version_metadata": { "binding": "CF_VERSION_METADATA" },
40
- * "analytics_engine_datasets": [{ "binding": "DECO_METRICS",
41
- * "dataset": "deco_metrics_my_site" }]
42
- * ```
43
- *
44
- * @example
45
- * ```ts
46
- * // worker-entry.ts
47
- * import { createDecoWorkerEntry } from "@decocms/start/sdk/workerEntry";
48
- * import { instrumentWorker } from "@decocms/start/sdk/otel";
49
- *
50
- * const handler = createDecoWorkerEntry(serverEntry, options);
51
- * export default instrumentWorker(handler, { serviceName: "my-store" });
52
- * ```
53
- *
54
- * **Future ClickHouse path.** When a co-deployed OTel collector lands, an
55
- * exporter that pushes spans + logs + metrics to that collector will live in
56
- * `./otelAdapters/clickhouseCollector.ts` (today: documented stub that throws).
57
- * The `withTracing` / `recordRequestMetric` / `logger` instrumentation surface
58
- * does not change — only the transport layer wires up.
59
- */
60
-
61
- import { SpanStatusCode, trace } from "@opentelemetry/api";
62
- // OTel community SemConv constants — official attribute names from the OTel
63
- // specification. Importing from the package (rather than typing strings)
64
- // guards against typos, surfaces deprecations via TypeScript, and tracks
65
- // upstream spec changes via the dep version.
66
- // https://opentelemetry.io/docs/specs/semconv/resource/
67
- // https://www.npmjs.com/package/@opentelemetry/semantic-conventions
68
- //
69
- // Stable attributes (graduated in upstream SemConv) come from the default
70
- // entry point. Incubating attributes (still experimental upstream) come from
71
- // the `/incubating` subpath — using them is a deliberate trade-off: stable
72
- // attribute names + a stability disclaimer documented in the conventions
73
- // guide (see context/04_engineering/o11y/02-conventions.md §4.2).
74
- import {
75
- ATTR_DEPLOYMENT_ENVIRONMENT_NAME,
76
- ATTR_SERVICE_INSTANCE_ID,
77
- ATTR_SERVICE_NAME,
78
- ATTR_SERVICE_VERSION,
79
- } from "@opentelemetry/semantic-conventions";
80
- import {
81
- ATTR_CLOUD_PLATFORM,
82
- ATTR_CLOUD_PROVIDER,
83
- } from "@opentelemetry/semantic-conventions/incubating";
84
- import { createCompositeLogger, createCompositeMeter } from "./composite";
85
- import { isDevMode } from "./env";
86
- import { configureLogger, defaultLoggerAdapter, logger, setLogLevel, setLoggerAttributeFloor, type LogLevel } from "./logger";
87
- import { configureMeter, configureTracer, getActiveSpan, METRIC_METADATA } from "../middleware/observability";
88
- import { createAnalyticsEngineMeterAdapter } from "./otelAdapters";
89
- import { createOtlpHttpLogAdapter, type OtlpHttpLog } from "./otelHttpLog";
90
- import { createOtlpHttpMeterAdapter, type OtlpHttpMeter } from "./otelHttpMeter";
91
- import {
92
- createOtlpHttpTracerAdapter,
93
- type OtlpHttpTracer,
94
- type TraceContext,
95
- } from "./otelHttpTracer";
96
- import { RequestContext } from "./requestContext";
97
-
98
- // ---------------------------------------------------------------------------
99
- // Types
100
- // ---------------------------------------------------------------------------
101
-
102
- export interface OtelOptions {
103
- /**
104
- * When `true`, skips all observability exporters (AE, OTLP metrics,
105
- * logs, traces). Overridden by the env var.
106
- */
107
- disabled?: boolean;
108
- /**
109
- * Env var name holding the tri-state observability switch. Values:
110
- * - `"on"` → force enable (even in local dev)
111
- * - `"off"` → force disable
112
- * - unset → auto: enabled in real deploys, disabled in local
113
- *
114
- * Local is detected via `isDevMode()` (reads
115
- * `process.env.NODE_ENV === "development"`, which Vite and
116
- * `@cloudflare/vite-plugin` set during `vite dev`).
117
- *
118
- * Defaults to `"DECO_OTEL"`.
119
- */
120
- envVar?: string;
121
- /** Logical service name. Falls back to `env.DECO_SITE_NAME`, then "deco-site". */
122
- serviceName?: string;
123
- /** Env var name holding the AE binding. Defaults to `"DECO_METRICS"`. */
124
- analyticsEngineBindingName?: string;
125
- /** Set to `false` to disable AE even when the binding is present. */
126
- analyticsEngineEnabled?: boolean;
127
- /**
128
- * Env var name holding the OTLP/HTTP metrics endpoint. Defaults to
129
- * `"DECO_OTEL_METRICS_ENDPOINT"`. When the env var is set (and
130
- * `otlpMetricsEnabled !== false`), `instrumentWorker` wires a direct-POST
131
- * metrics exporter and flushes the buffer via `ctx.waitUntil` at the
132
- * end of every request. Cooldown + buffer cap are controlled by
133
- * `OtlpHttpMeterOptions`.
134
- */
135
- otlpMetricsEndpointEnvVar?: string;
136
- /** Set to `false` to disable the OTLP/HTTP metrics exporter explicitly. */
137
- otlpMetricsEnabled?: boolean;
138
- /**
139
- * Env var name holding the OTLP/HTTP logs endpoint — the primary log
140
- * transport. Defaults to `"DECO_OTEL_LOGS_ENDPOINT"`. When set (and
141
- * `otlpLogsEnabled !== false`), `instrumentWorker` patches `console.*`
142
- * at boot so all application and third-party log calls route through
143
- * the framework logger → direct-POST to this endpoint.
144
- */
145
- otlpLogsEndpointEnvVar?: string;
146
- /** Set to `false` to disable the OTLP/HTTP logs exporter explicitly. */
147
- otlpLogsEnabled?: boolean;
148
- /**
149
- * Minimum log level forwarded via direct-POST. Defaults to `"info"` per
150
- * the OpenTelemetry specification. Set to `"warn"` to forward only errors
151
- * and warnings, or `"debug"` to capture everything (can be high volume).
152
- *
153
- * Precedence: env var (`otlpLogsMinLevelEnvVar`, default
154
- * `DECO_OTEL_LOGS_MIN_LEVEL`) > this option > `"info"`. Invalid env
155
- * values fall through silently.
156
- */
157
- otlpLogsMinLevel?: LogLevel;
158
- /**
159
- * Env var name to read the minimum log level from. Defaults to
160
- * `"DECO_OTEL_LOGS_MIN_LEVEL"`. Value MUST be one of
161
- * `"debug"`, `"info"`, `"warn"`, `"error"`.
162
- */
163
- otlpLogsMinLevelEnvVar?: string;
164
- /**
165
- * Extra HTTP headers sent on every OTLP POST (logs, traces, metrics).
166
- * Merged with the adapter default (`Content-Type: application/json`).
167
- *
168
- * Resolved from `DECO_OTEL_HEADERS` env var (format: `key=value,key2=value2`)
169
- * when not set programmatically. Useful for collector auth:
170
- *
171
- * ```
172
- * DECO_OTEL_HEADERS=Authorization=Bearer <token>
173
- * ```
174
- */
175
- otlpHeaders?: Record<string, string>;
176
- /**
177
- * Env var name to read extra OTLP headers from. Defaults to `"DECO_OTEL_HEADERS"`.
178
- * Format: `key=value,key2=value2`.
179
- */
180
- otlpHeadersEnvVar?: string;
181
- /**
182
- * Authorization header value sent on every OTLP POST.
183
- * Equivalent to `otlpHeaders: { authorization: "<value>" }` but intended
184
- * for secrets: store via `wrangler secret put DECO_OTEL_AUTH_TOKEN` so the
185
- * token is never committed to the repo. Non-secret headers go in
186
- * `DECO_OTEL_HEADERS` (plaintext in `wrangler.jsonc`).
187
- *
188
- * Example: `DECO_OTEL_AUTH_TOKEN=Bearer eyJhbGci...`
189
- *
190
- * Precedence (lowest → highest): auth token env var → `DECO_OTEL_HEADERS`
191
- * env var → `otlpHeaders` option. An explicit `authorization` key in
192
- * `DECO_OTEL_HEADERS` or `otlpHeaders` overrides this value.
193
- */
194
- otlpAuthToken?: string;
195
- /**
196
- * Env var name to read the auth token from. Defaults to `"DECO_OTEL_AUTH_TOKEN"`.
197
- */
198
- otlpAuthTokenEnvVar?: string;
199
- /**
200
- * Env var name holding the OTLP/HTTP traces endpoint used by the
201
- * direct-POST span exporter. Defaults to `"DECO_OTEL_TRACES_ENDPOINT"`.
202
- * When set (and `otlpTracesEnabled !== false`), framework `deco.*`
203
- * spans created via `withTracing` are captured, sampled, and POSTed
204
- * directly to this endpoint. Flushed alongside metrics via
205
- * `ctx.waitUntil`.
206
- *
207
- * Without this endpoint configured, `withTracing` falls back to the
208
- * `@opentelemetry/api` global tracer (the legacy CF auto-instrumentation
209
- * path). The framework registers BOTH adapters when a traces endpoint
210
- * is set so CF auto-spans stay intact AND framework spans get
211
- * direct-POSTed to ClickHouse. See Phase 3 in
212
- * `MIGRATION_TOOLING_PLAN.md`.
213
- */
214
- otlpTracesEndpointEnvVar?: string;
215
- /** Set to `false` to disable the OTLP/HTTP traces exporter explicitly. */
216
- otlpTracesEnabled?: boolean;
217
- /**
218
- * Head sampling rate for framework spans direct-POSTed via the OTLP
219
- * traces endpoint. Default `0.01` matches the CF Destinations
220
- * `traces.head_sampling_rate` recommendation. Decisions are consistent
221
- * per trace (hash of `trace_id`), so child spans (`deco.cache.lookup`,
222
- * `deco.cms.resolvePage`, ...) are kept iff their root
223
- * `deco.http.request` span is kept. Set to `1` to capture every trace
224
- * (preview / debug only — production cost grows linearly).
225
- *
226
- * Precedence: env var (`otlpTracesSamplingRateEnvVar`, default
227
- * `DECO_OTEL_TRACES_SAMPLING_RATE`) > this option > `0.01`. Reading from
228
- * env lets local-dev opt into 100% sampling via `.dev.vars` without
229
- * changing the worker entry.
230
- */
231
- otlpTracesSamplingRate?: number;
232
- /**
233
- * Env var name to read the head sampling rate from when set on `env`.
234
- * Defaults to `DECO_OTEL_TRACES_SAMPLING_RATE`. Value MUST be a finite
235
- * number in `[0, 1]`. Invalid values are ignored (falls back to
236
- * `otlpTracesSamplingRate` then `0.01`).
237
- */
238
- otlpTracesSamplingRateEnvVar?: string;
239
- /**
240
- * When `true` (or when `DECO_OTEL_ERROR_PROMOTION=true` is set), any
241
- * `logger.error()` call with an active trace context marks that trace for
242
- * export even if head sampling did not select it. Useful for ensuring
243
- * errors always have a trace in ClickHouse without raising the global
244
- * sampling rate.
245
- *
246
- * Disabled by default — enable via env var or this option once validated
247
- * in production. Precedence: env var (`otlpTracesErrorPromotionEnvVar`,
248
- * default `DECO_OTEL_ERROR_PROMOTION`) > this option > `false`.
249
- */
250
- otlpTracesErrorPromotion?: boolean;
251
- /**
252
- * Env var name to read the error promotion flag from. Defaults to
253
- * `"DECO_OTEL_ERROR_PROMOTION"`. Value must be `"true"` to enable.
254
- */
255
- otlpTracesErrorPromotionEnvVar?: string;
256
- /**
257
- * Sampling rate applied to error-promoted traces, 0.0..1.0. Default `0.1`
258
- * (promote 10% of error traces). Lower values cap ClickHouse volume when
259
- * errors are frequent. Uses the same FNV-1a hash as head sampling.
260
- *
261
- * Precedence: env var (`otlpTracesErrorPromotionRateEnvVar`, default
262
- * `DECO_OTEL_ERROR_PROMOTION_RATE`) > this option > `0.1`.
263
- */
264
- otlpTracesErrorPromotionRate?: number;
265
- /**
266
- * Env var name to read the error promotion rate from. Defaults to
267
- * `"DECO_OTEL_ERROR_PROMOTION_RATE"`. Value must be a finite number in
268
- * `[0, 1]`. Invalid values are ignored.
269
- */
270
- otlpTracesErrorPromotionRateEnvVar?: string;
271
- /** Test seam — replace the global `fetch` used by the traces exporter. */
272
- otlpTracesFetchImpl?: typeof fetch;
273
- /**
274
- * Version of `@decocms/start` to advertise as `deco.runtime.version`
275
- * on every span and every log line. Falls back to a build-time constant;
276
- * override only for tests.
277
- */
278
- decoRuntimeVersion?: string;
279
- /** Optional `@decocms/apps` version, stamped as `deco.apps.version`. */
280
- decoAppsVersion?: string;
281
- /**
282
- * Test seam — replace the global `fetch` used by the OTLP metrics
283
- * exporter without touching the worker's outbound fetch.
284
- */
285
- otlpMetricsFetchImpl?: typeof fetch;
286
- /** Test seam — replace the global `fetch` used by the logs exporter. */
287
- otlpLogsFetchImpl?: typeof fetch;
288
- }
289
-
290
- interface WorkerExecutionContext {
291
- waitUntil(promise: Promise<unknown>): void;
292
- passThroughOnException(): void;
293
- }
294
-
295
- interface WorkerHandler {
296
- fetch(
297
- request: Request,
298
- env: Record<string, unknown>,
299
- ctx: WorkerExecutionContext,
300
- ): Promise<Response>;
301
- }
302
-
303
- // ---------------------------------------------------------------------------
304
- // Boot state — pinned to globalThis via Symbol.for so multiple bundled
305
- // copies of this module converge on the SAME state.
306
- //
307
- // Why: Vite (and any bundler chunking by entry) can produce more than one
308
- // inlined copy of this file when multiple package entries — e.g.
309
- // `@decocms/start/sdk/otel` and `@decocms/start/sdk/workerEntry` — both
310
- // pull it transitively. With plain module-scoped `let` variables, the
311
- // auto-wrap path inside `createDecoWorkerEntry` ends up writing the meter
312
- // into Copy A's `otlpMeter` while the per-request `recordRequestMetric`
313
- // closure reads from Copy B's empty `otlpMeter`. Net effect in prod:
314
- // `bootObservability` runs (we observed the very first `POST /v1/metrics`
315
- // from miess-tanstack), but every subsequent request's `flush()` finds an
316
- // empty buffer because the meter the framework writes into is a different
317
- // instance from the one the exporter drains.
318
- //
319
- // `observability.ts` already uses this pattern (see the `STATE_KEY` block
320
- // there); the comment there flags this exact failure mode. The reason it
321
- // took so long to surface here is that until PR #232 added the auto-wrap
322
- // inside `createDecoWorkerEntry`, sites always called `instrumentWorker`
323
- // once from their own `worker-entry.ts` — a single bundle entry — so
324
- // nobody hit the duplication path.
325
- //
326
- // CF Workers guarantee one `globalThis` per isolate, so there's no risk
327
- // of cross-isolate bleed. Symbol.for keeps the registry stable across
328
- // hot reloads in `wrangler dev` too.
329
- // ---------------------------------------------------------------------------
330
-
331
- type OrigConsole = Pick<typeof console, "log" | "info" | "warn" | "error" | "debug">;
332
-
333
- interface BootState {
334
- booted: boolean;
335
- otlpMeter: OtlpHttpMeter | null;
336
- otlpLog: OtlpHttpLog | null;
337
- otlpTracer: OtlpHttpTracer | null;
338
- spanAttributeFloor: Record<string, string>;
339
- origConsole: OrigConsole | null;
340
- }
341
-
342
- const BOOT_STATE_KEY = Symbol.for("@decocms/start/sdk/otel/boot.v1");
343
-
344
- function getBootState(): BootState {
345
- const g = globalThis as Record<symbol, unknown>;
346
- if (!g[BOOT_STATE_KEY]) {
347
- g[BOOT_STATE_KEY] = {
348
- booted: false,
349
- otlpMeter: null,
350
- otlpLog: null,
351
- otlpTracer: null,
352
- spanAttributeFloor: {},
353
- origConsole: null,
354
- } satisfies BootState;
355
- }
356
- return g[BOOT_STATE_KEY] as BootState;
357
- }
358
-
359
- /**
360
- * Per-request inbound W3C trace context, parsed from the `traceparent`
361
- * header at request entry. Read by the OTLP trace exporter when it
362
- * creates a root span so we honor remote parents and the `sampled`
363
- * flag. Stored on a request-scoped slot (via `RequestContext.bag`) so
364
- * concurrent requests in the same isolate don't trample each other.
365
- */
366
- const TRACE_CTX_BAG_KEY = "deco.observability.traceContext.v1";
367
- const DEBUG_SAMPLED_BAG_KEY = "deco.observability.debugSampled.v1";
368
-
369
- function getRequestTraceContext(): TraceContext | null {
370
- return RequestContext.getBag<TraceContext>(TRACE_CTX_BAG_KEY) ?? null;
371
- }
372
-
373
- function getDebugSampled(): boolean {
374
- return RequestContext.getBag<boolean>(DEBUG_SAMPLED_BAG_KEY) ?? false;
375
- }
376
-
377
- /**
378
- * Public entry point used by `workerEntry.ts` to stash the parsed
379
- * traceparent for the OTLP tracer to consume. Exported (not just
380
- * module-local) because the parser lives in `otelHttpTracer.ts` and
381
- * the call site is `workerEntry.ts`.
382
- */
383
- export function _setRequestTraceContext(ctx: TraceContext | null): void {
384
- if (ctx) RequestContext.setBag(TRACE_CTX_BAG_KEY, ctx);
385
- }
386
-
387
- /**
388
- * Called by `workerEntry.ts` when the inbound URL contains `?__d=<any>`.
389
- * Forces trace sampling for the current request regardless of `headSamplingRate`.
390
- * Useful for debugging individual requests in production without changing
391
- * the global sampling rate.
392
- */
393
- export function _setDebugSampled(): void {
394
- RequestContext.setBag(DEBUG_SAMPLED_BAG_KEY, true);
395
- }
396
-
397
- /**
398
- * Per-span attribute floor — stamped on every span we create via
399
- * `configureTracer().startSpan(...)`. Lives on the shared `BootState`
400
- * (see above) so framework code paths that read it through different
401
- * bundled copies of this module all see the floor `bootObservability`
402
- * just installed.
403
- */
404
-
405
- // ---------------------------------------------------------------------------
406
- // instrumentWorker
407
- // ---------------------------------------------------------------------------
408
-
409
- /**
410
- * Wraps a Cloudflare Worker handler with the @decocms/start observability
411
- * stack:
412
- * - structured JSON logger to console.* (CF captures via observability.logs)
413
- * - AE meter (when `DECO_METRICS` binding present)
414
- * - bridge from framework-internal `withTracing()` to `@opentelemetry/api`
415
- * global tracer (CF observability.traces ingests via auto-instrumentation
416
- * + the global-tracer hook)
417
- *
418
- * No external destinations, no OTLP transport. Forwarding to a future
419
- * OTel collector for ClickHouse will live behind a separate adapter
420
- * (see `./otelAdapters/clickhouseCollector.ts`).
421
- */
422
- export function instrumentWorker(
423
- handler: WorkerHandler,
424
- options: OtelOptions | ((env: Record<string, unknown>) => OtelOptions) = {},
425
- ): WorkerHandler {
426
- // Default tracer bridge — delegates to `@opentelemetry/api` global. When
427
- // `bootObservability` discovers `DECO_OTEL_TRACES_ENDPOINT`, it composes
428
- // this bridge with the direct-POST OTLP tracer so framework spans flow to
429
- // BOTH the CF dashboard AND ClickHouse (the bridge stays a no-op when CF
430
- // tracing isn't configured, which is the common case today). See
431
- // `configureTracerStack` below.
432
- configureTracer(buildOtelApiTracer());
433
-
434
- return {
435
- async fetch(request, env, ctx) {
436
- const opts =
437
- typeof options === "function" ? options(env as Record<string, unknown>) : options;
438
- bootObservability(opts, env as Record<string, unknown>);
439
- // RequestContext.run + setRuntimeEnv(env) is handled inside
440
- // workerEntry.ts on the inner handler — instrumentWorker does
441
- // NOT re-wrap so we don't double-enter AsyncLocalStorage.
442
- try {
443
- return await handler.fetch(request, env, ctx);
444
- } finally {
445
- // Drain the OTLP metrics + error-log + traces buffers via
446
- // ctx.waitUntil so no POST blocks the response. Each exporter
447
- // throttles itself per isolate — calling on every request is
448
- // cheap; the network only fires when the cooldown elapses or
449
- // the buffer fills.
450
- const state = getBootState();
451
- if (state.otlpMeter) {
452
- try {
453
- ctx.waitUntil(state.otlpMeter.flush());
454
- } catch {
455
- /* ctx.waitUntil throwing is benign — never block the response */
456
- }
457
- }
458
- if (state.otlpLog) {
459
- try {
460
- ctx.waitUntil(state.otlpLog.flush());
461
- } catch {
462
- /* swallow */
463
- }
464
- }
465
- if (state.otlpTracer) {
466
- try {
467
- ctx.waitUntil(state.otlpTracer.flush());
468
- } catch {
469
- /* swallow */
470
- }
471
- }
472
- }
473
- },
474
- };
475
- }
476
-
477
- /**
478
- * Build the legacy `@opentelemetry/api` global-tracer bridge. Stays a
479
- * no-op when no global TracerProvider is registered — same outcome as
480
- * the historical configuration.
481
- */
482
- function buildOtelApiTracer(): import("../middleware/observability").TracerAdapter {
483
- return {
484
- startSpan: (name, attrs) => {
485
- const merged = { ...getBootState().spanAttributeFloor, ...(attrs ?? {}) };
486
- const span = trace.getTracer("@decocms/start").startSpan(name, { attributes: merged });
487
- return {
488
- end: () => span.end(),
489
- setError: (error) => {
490
- const message = error instanceof Error ? error.message : String(error);
491
- if (error instanceof Error) span.recordException(error);
492
- span.setStatus({ code: SpanStatusCode.ERROR, message });
493
- },
494
- setAttribute: (k, v) => {
495
- span.setAttribute(k, v);
496
- if (k === "http.status_code" && typeof v === "number" && v >= 400) {
497
- span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${v}` });
498
- }
499
- },
500
- spanContext: () => {
501
- const ctx = span.spanContext();
502
- return {
503
- traceId: ctx.traceId,
504
- spanId: ctx.spanId,
505
- traceFlags: ctx.traceFlags,
506
- };
507
- },
508
- };
509
- },
510
- };
511
- }
512
-
513
- /**
514
- * Wire the framework tracer. When the OTLP traces endpoint is configured,
515
- * compose the direct-POST tracer ALONGSIDE the `@opentelemetry/api` bridge
516
- * via a fanout adapter so:
517
- * 1. `withTracing` calls feed BOTH adapters.
518
- * 2. A child span's `spanContext()` reports the direct-POST span's IDs
519
- * (the bridge is best-effort — if CF tracing isn't installed those
520
- * IDs are zeros anyway).
521
- *
522
- * When no traces endpoint is configured, fall back to the bridge alone —
523
- * preserves the legacy behavior for sites that haven't bumped wrangler.
524
- */
525
- function configureTracerStack(otlpAdapter: OtlpHttpTracer | null): void {
526
- const bridge = buildOtelApiTracer();
527
- if (!otlpAdapter) {
528
- configureTracer(bridge);
529
- return;
530
- }
531
- // Compose. The OTLP adapter is the "primary" (its IDs win for
532
- // `spanContext()` because callers downstream use them for trace
533
- // propagation). The bridge is best-effort — fed the same name/attrs
534
- // so CF Workers Observability still sees the spans if that channel
535
- // is enabled in wrangler.jsonc.
536
- configureTracer({
537
- startSpan(name, attrs) {
538
- const merged = { ...getBootState().spanAttributeFloor, ...(attrs ?? {}) };
539
- const primary = otlpAdapter.startSpan(name, merged);
540
- const secondary = bridge.startSpan(name, merged);
541
- return {
542
- end(): void {
543
- try {
544
- primary.end();
545
- } finally {
546
- try {
547
- secondary.end();
548
- } catch {
549
- /* swallow */
550
- }
551
- }
552
- },
553
- setError(error: unknown): void {
554
- try {
555
- primary.setError?.(error);
556
- } finally {
557
- try {
558
- secondary.setError?.(error);
559
- } catch {
560
- /* swallow */
561
- }
562
- }
563
- },
564
- setAttribute(key: string, value: string | number | boolean): void {
565
- primary.setAttribute?.(key, value);
566
- try {
567
- secondary.setAttribute?.(key, value);
568
- } catch {
569
- /* swallow */
570
- }
571
- },
572
- spanContext() {
573
- // The OTLP adapter owns the canonical IDs — those are the IDs
574
- // we propagate downstream via `traceparent` headers.
575
- return primary.spanContext?.() ?? secondary.spanContext?.() ?? {
576
- traceId: "",
577
- spanId: "",
578
- traceFlags: 0,
579
- };
580
- },
581
- };
582
- },
583
- });
584
- }
585
-
586
- // ---------------------------------------------------------------------------
587
- // Boot — wires the loggers/meters once (per worker isolate)
588
- // ---------------------------------------------------------------------------
589
-
590
- /**
591
- * Replaces `console.*` with thin shims that route every call through the
592
- * framework `logger`, which forwards to the configured adapter (direct-POST
593
- * OTLP when active). The original functions are saved on `BootState` so
594
- * `_resetBootStateForTests()` can restore them between test runs.
595
- *
596
- * A re-entrancy guard (`busy`) prevents the loop that would occur if the
597
- * active logger adapter ever calls back into `console.*` (e.g. the
598
- * `defaultLoggerAdapter` in dev mode). Without the guard:
599
- * console.error → logger.error → defaultLoggerAdapter → console.error → …
600
- *
601
- * Only called when the OTLP logs endpoint is configured. In dev (no OTLP),
602
- * `console.*` is left untouched so `wrangler dev` / `wrangler tail` keep
603
- * showing output normally.
604
- */
605
- function patchConsole(state: BootState): void {
606
- if (state.origConsole) return; // already patched this isolate
607
-
608
- const orig: OrigConsole = {
609
- log: console.log.bind(console),
610
- info: console.info.bind(console),
611
- warn: console.warn.bind(console),
612
- error: console.error.bind(console),
613
- debug: console.debug.bind(console),
614
- };
615
- state.origConsole = orig;
616
-
617
- let busy = false;
618
-
619
- const forward = (level: LogLevel, args: unknown[]): void => {
620
- if (busy) return;
621
- busy = true;
622
- try {
623
- const msg = args
624
- .map((a) => {
625
- if (typeof a === "string") return a;
626
- try { return JSON.stringify(a); } catch { return String(a); }
627
- })
628
- .join(" ");
629
- logger[level](msg);
630
- } finally {
631
- busy = false;
632
- }
633
- };
634
-
635
- console.log = (...args: unknown[]) => forward("info", args);
636
- console.info = (...args: unknown[]) => forward("info", args);
637
- console.warn = (...args: unknown[]) => forward("warn", args);
638
- console.error = (...args: unknown[]) => forward("error", args);
639
- console.debug = (...args: unknown[]) => forward("debug", args);
640
- }
641
-
642
- function bootObservability(opts: OtelOptions, env: Record<string, unknown>): void {
643
- const state = getBootState();
644
- if (state.booted) return;
645
-
646
- // `isDevMode()` reads `process.env.NODE_ENV === "development"`. Vite and
647
- // `@cloudflare/vite-plugin` set NODE_ENV during `vite dev`; `wrangler
648
- // deploy` does not. `CF_VERSION_METADATA` is NOT a reliable local signal —
649
- // wrangler dev populates it with a random per-session UUID.
650
- const mode = env[opts.envVar ?? "DECO_OTEL"];
651
- const isDisabled =
652
- mode === "off" ||
653
- (mode !== "on" && (opts.disabled || isDevMode()));
654
- if (isDisabled) {
655
- state.booted = true;
656
- return;
657
- }
658
-
659
- // Capture the original console.warn BEFORE patchConsole() runs. The onError
660
- // callbacks below need a direct channel to console that bypasses the logger
661
- // to avoid routing exporter-level warnings back through the OTLP adapter
662
- // that is currently failing.
663
- const warnDirect = console.warn.bind(console);
664
-
665
- const serviceName = opts.serviceName ?? (env.DECO_SITE_NAME as string | undefined) ?? "deco-site";
666
- const decoRuntimeVersion = opts.decoRuntimeVersion ?? DECO_RUNTIME_VERSION;
667
- const deploymentEnvironment = (env.DECO_ENV_NAME as string | undefined) ?? "production";
668
- const serviceVersion = (env.CF_VERSION_METADATA as { id?: string } | undefined)?.id;
669
-
670
- // service.name and service.version are OTel resource conventions. CF's
671
- // managed export already stamps service.name at the resource level (from
672
- // the Worker name in wrangler.jsonc) but framework-created spans don't
673
- // inherit resource attrs, so we stamp them per-span/per-log defensively.
674
- // service.version comes from the CF_VERSION_METADATA binding which is
675
- // unique per deployment — needed to correlate regressions with releases.
676
- //
677
- // service.instance.id (OTel SemConv required for distributed services) is a
678
- // per-isolate UUID generated at boot. Distinguishes parallel isolates on the
679
- // same deploy — required so the System Health Agent can attribute behavior
680
- // (memory creep, slow cold starts) to a specific instance.
681
- // https://opentelemetry.io/docs/specs/semconv/resource/#service
682
- //
683
- // cloud.provider / cloud.platform are stamped statically here because every
684
- // isolate runs on CF Workers. cloud.region (the CF colo) is per-request, not
685
- // per-isolate, so it's NOT in the resource floor — it MUST be attached at
686
- // the span level by the request handler.
687
- // https://opentelemetry.io/docs/specs/semconv/resource/cloud/
688
- //
689
- // Note: `deco.runtime.version` and `deco.apps.version` are Deco extensions
690
- // (not in OTel SemConv), so they remain as string literals.
691
- const floor: Record<string, string> = {
692
- [ATTR_SERVICE_NAME]: serviceName,
693
- [ATTR_SERVICE_INSTANCE_ID]: crypto.randomUUID(),
694
- [ATTR_DEPLOYMENT_ENVIRONMENT_NAME]: deploymentEnvironment,
695
- [ATTR_CLOUD_PROVIDER]: "cloudflare",
696
- [ATTR_CLOUD_PLATFORM]: "cloudflare_workers",
697
- "deco.runtime.version": decoRuntimeVersion,
698
- };
699
- if (serviceVersion) floor[ATTR_SERVICE_VERSION] = serviceVersion;
700
- if (opts.decoAppsVersion) floor["deco.apps.version"] = opts.decoAppsVersion;
701
-
702
- // Stamp on every span we create. CF-managed trace export emits its own
703
- // resource attribute set, so legacy resource attrs don't survive.
704
- // Stamping per-span preserves the dimensions dashboards / saved searches
705
- // filter on.
706
- state.spanAttributeFloor = floor;
707
-
708
- // Stamp on every log record. CF Workers Logs ships the JSON body
709
- // verbatim — without this floor, panels grouping logs by these
710
- // dimensions return empty. Caller-supplied `attrs` still win on
711
- // key collision (see logger.ts).
712
- setLoggerAttributeFloor(floor);
713
-
714
- // Logger — two paths composed:
715
- //
716
- // - `defaultLoggerAdapter`: structured JSON to `console.*`. CF
717
- // Workers Logs captures this and CF Destinations forwards a
718
- // `logs.head_sampling_rate` fraction to `deco-otel-ingest/v1/logs`.
719
- // Carries debug / info / warn / error.
720
- // - `otlpLog.adapter`: direct POST to `/v1/logs` for level=error
721
- // only, rate-limited (default 100/min, burst 20), buffered, flushed
722
- // via `ctx.waitUntil` at request end. Guarantees ≥99% error capture
723
- // regardless of the CF Destinations sampling rate. See
724
- // `otelHttpLog.ts` for the aggregation + rate-limit details.
725
- //
726
- // The two paths land in the SAME `default.otel_logs` table, so the
727
- // ingestor's existing PII redaction applies uniformly and dashboards
728
- // need no changes. Records from the direct-POST path are
729
- // distinguishable from CF-Destinations records by `ScopeName =
730
- // "@decocms/start"` if needed (CF stamps its own scope).
731
- const otlpLogsEnvVar = opts.otlpLogsEndpointEnvVar ?? "DECO_OTEL_LOGS_ENDPOINT";
732
- const otlpLogsEndpoint = (env[otlpLogsEnvVar] as string | undefined) ?? "";
733
- const otlpLogsEnabled =
734
- opts.otlpLogsEnabled !== false && otlpLogsEndpoint.length > 0;
735
- // Minimum log level precedence: env var > options > "info" default (OTel spec).
736
- // Invalid env values fall through silently.
737
- const otlpLogsMinLevelEnvVar =
738
- opts.otlpLogsMinLevelEnvVar ?? "DECO_OTEL_LOGS_MIN_LEVEL";
739
- const otlpLogsMinLevelFromEnv = (
740
- (env[otlpLogsMinLevelEnvVar] as string | undefined) ?? ""
741
- ).toLowerCase();
742
- const validLogLevels = ["debug", "info", "warn", "error"] as const;
743
- const otlpLogsMinLevel: LogLevel =
744
- (validLogLevels as readonly string[]).includes(otlpLogsMinLevelFromEnv)
745
- ? (otlpLogsMinLevelFromEnv as LogLevel)
746
- : opts.otlpLogsMinLevel ?? "info";
747
- // Sync the logger gate so logger.debug() calls are not silently dropped
748
- // before reaching the OTLP adapter when minLevel is "debug" or "info".
749
- setLogLevel(otlpLogsMinLevel);
750
- const otlpHeadersEnvVar = opts.otlpHeadersEnvVar ?? "DECO_OTEL_HEADERS";
751
- const otlpHeadersFromEnv = (env[otlpHeadersEnvVar] as string | undefined) ?? "";
752
- const parsedEnvHeaders: Record<string, string> = {};
753
- for (const pair of otlpHeadersFromEnv.split(",")) {
754
- const eqIdx = pair.indexOf("=");
755
- if (eqIdx > 0) {
756
- parsedEnvHeaders[pair.slice(0, eqIdx).trim()] = pair.slice(eqIdx + 1).trim();
757
- }
758
- }
759
- const otlpAuthTokenEnvVar = opts.otlpAuthTokenEnvVar ?? "DECO_OTEL_AUTH_TOKEN";
760
- const otlpAuthToken = (env[otlpAuthTokenEnvVar] as string | undefined) ?? opts.otlpAuthToken ?? "";
761
- const authHeader: Record<string, string> = otlpAuthToken ? { authorization: otlpAuthToken } : {};
762
- // Priority: auth token (lowest) → DECO_OTEL_HEADERS env → otlpHeaders option (highest).
763
- const otlpHeaders: Record<string, string> = { ...authHeader, ...parsedEnvHeaders, ...(opts.otlpHeaders ?? {}) };
764
-
765
- const errorPromotionEnvVar =
766
- opts.otlpTracesErrorPromotionEnvVar ?? "DECO_OTEL_ERROR_PROMOTION";
767
- const errorPromotionEnabled =
768
- (env[errorPromotionEnvVar] as string | undefined) === "true" ||
769
- (opts.otlpTracesErrorPromotion ?? false);
770
-
771
- if (otlpLogsEnabled) {
772
- state.otlpLog = createOtlpHttpLogAdapter({
773
- endpoint: otlpLogsEndpoint,
774
- resourceAttributes: floor,
775
- scopeVersion: decoRuntimeVersion,
776
- minLevel: otlpLogsMinLevel,
777
- headers: otlpHeaders,
778
- fetchImpl: opts.otlpLogsFetchImpl,
779
- promoteTrace: errorPromotionEnabled
780
- ? (traceId) => state.otlpTracer?.promoteTrace(traceId)
781
- : undefined,
782
- onError: (kind, err) => {
783
- // Use warnDirect (pre-patch console.warn) to avoid routing this
784
- // warning back through the OTLP adapter that is currently failing.
785
- try {
786
- warnDirect(
787
- JSON.stringify({
788
- level: "warn",
789
- msg: "otlp error-log exporter",
790
- kind,
791
- error: err instanceof Error ? err.message : String(err),
792
- timestamp: new Date().toISOString(),
793
- }),
794
- );
795
- } catch {
796
- /* swallow */
797
- }
798
- },
799
- });
800
- } else {
801
- state.otlpLog = null;
802
- }
803
-
804
- if (otlpLogsEnabled) {
805
- // OTLP active: direct-POST is the sole log transport.
806
- // console.* will be intercepted by patchConsole() below so all
807
- // application and third-party console calls route here too.
808
- // defaultLoggerAdapter is excluded to prevent workerd from capturing
809
- // framework logs (which would make them visible to the tail worker a
810
- // second time — the tail worker only needs to see what the worker
811
- // itself cannot capture: exceededCpu / exceededMemory / isolate crashes).
812
- configureLogger(createCompositeLogger([state.otlpLog!.adapter]));
813
- } else {
814
- // No OTLP endpoint — dev mode. Keep writing to console so wrangler dev /
815
- // wrangler tail show output normally. No monkey-patch applied.
816
- configureLogger(createCompositeLogger([defaultLoggerAdapter]));
817
- }
818
-
819
- // Meter — fan out to two backends when both are configured:
820
- //
821
- // - AE (binding `DECO_METRICS`): high-cardinality drill-down, queryable
822
- // via the per-site dataset.
823
- // - OTLP/HTTP (env `DECO_OTEL_METRICS_ENDPOINT`): SRE-grade rollups
824
- // landed in ClickHouse `otel_metrics_{sum,gauge,histogram}` via the
825
- // `deco-otel-ingest` Worker. Cumulative temporality, per-isolate
826
- // buffer flushed by `ctx.waitUntil` in `instrumentWorker`.
827
- //
828
- // The two emitters are NOT redundant — AE keeps per-request per-path
829
- // dimensions; OTLP carries the same metric names at coarser cardinality
830
- // and survives outside the CF dashboard. Cost model in
831
- // `docs/observability.md` accounts for both.
832
- const aeBindingName = opts.analyticsEngineBindingName ?? "DECO_METRICS";
833
- const aeEnabled = opts.analyticsEngineEnabled !== false && Boolean(env[aeBindingName]);
834
- const aeAdapter = aeEnabled
835
- ? createAnalyticsEngineMeterAdapter({ bindingName: aeBindingName })
836
- : null;
837
-
838
- const otlpEnvVar = opts.otlpMetricsEndpointEnvVar ?? "DECO_OTEL_METRICS_ENDPOINT";
839
- const otlpEndpoint = (env[otlpEnvVar] as string | undefined) ?? "";
840
- const otlpEnabled = opts.otlpMetricsEnabled !== false && otlpEndpoint.length > 0;
841
- if (otlpEnabled) {
842
- state.otlpMeter = createOtlpHttpMeterAdapter({
843
- endpoint: otlpEndpoint,
844
- resourceAttributes: floor,
845
- scopeVersion: decoRuntimeVersion,
846
- headers: otlpHeaders,
847
- fetchImpl: opts.otlpMetricsFetchImpl,
848
- metricMetadata: METRIC_METADATA,
849
- onError: (kind, err) => {
850
- try {
851
- warnDirect(
852
- JSON.stringify({
853
- level: "warn",
854
- msg: "otlp metrics exporter",
855
- kind,
856
- error: err instanceof Error ? err.message : String(err),
857
- timestamp: new Date().toISOString(),
858
- }),
859
- );
860
- } catch {
861
- /* swallow */
862
- }
863
- },
864
- });
865
- } else {
866
- state.otlpMeter = null;
867
- }
868
-
869
- const composedMeter = createCompositeMeter([aeAdapter, state.otlpMeter]);
870
- // Composite meter is always installed — when both backends are absent the
871
- // composite becomes a 0-element no-op via createCompositeMeter's filter.
872
- configureMeter(composedMeter);
873
-
874
- // Traces — direct-POST exporter for framework `deco.*` spans. Without
875
- // this, `withTracing` delegates to the no-op `@opentelemetry/api`
876
- // global tracer and every framework span silently disappears (the
877
- // Phase 3 gap documented in `MIGRATION_TOOLING_PLAN.md`). Same
878
- // transport pattern as metrics/error-logs — buffered, sampled by
879
- // trace-id hash, flushed via `ctx.waitUntil`.
880
- const otlpTracesEnvVar = opts.otlpTracesEndpointEnvVar ?? "DECO_OTEL_TRACES_ENDPOINT";
881
- const otlpTracesEndpoint = (env[otlpTracesEnvVar] as string | undefined) ?? "";
882
- const otlpTracesEnabled =
883
- opts.otlpTracesEnabled !== false && otlpTracesEndpoint.length > 0;
884
- if (otlpTracesEnabled) {
885
- // Sampling rate precedence: env var > options > 0.01 default.
886
- // Invalid env values (NaN, < 0, > 1) fall through silently.
887
- const otlpTracesSamplingRateEnvVar =
888
- opts.otlpTracesSamplingRateEnvVar ?? "DECO_OTEL_TRACES_SAMPLING_RATE";
889
- const samplingRateFromEnv = Number.parseFloat(
890
- (env[otlpTracesSamplingRateEnvVar] as string | undefined) ?? "",
891
- );
892
- const samplingRateOverride =
893
- Number.isFinite(samplingRateFromEnv) &&
894
- samplingRateFromEnv >= 0 &&
895
- samplingRateFromEnv <= 1
896
- ? samplingRateFromEnv
897
- : undefined;
898
- const errorPromotionRateEnvVar =
899
- opts.otlpTracesErrorPromotionRateEnvVar ?? "DECO_OTEL_ERROR_PROMOTION_RATE";
900
- const errorPromotionRateFromEnv = Number.parseFloat(
901
- (env[errorPromotionRateEnvVar] as string | undefined) ?? "",
902
- );
903
- const errorPromotionRate =
904
- Number.isFinite(errorPromotionRateFromEnv) &&
905
- errorPromotionRateFromEnv >= 0 &&
906
- errorPromotionRateFromEnv <= 1
907
- ? errorPromotionRateFromEnv
908
- : (opts.otlpTracesErrorPromotionRate ?? 0.1);
909
-
910
- state.otlpTracer = createOtlpHttpTracerAdapter({
911
- endpoint: otlpTracesEndpoint,
912
- resourceAttributes: floor,
913
- scopeVersion: decoRuntimeVersion,
914
- headSamplingRate: samplingRateOverride ?? opts.otlpTracesSamplingRate ?? 0.01,
915
- errorPromotionRate,
916
- headers: otlpHeaders,
917
- fetchImpl: opts.otlpTracesFetchImpl,
918
- getActiveSpanForParent: () => getActiveSpan(),
919
- getRequestTraceContext,
920
- getForceSampled: getDebugSampled,
921
- onError: (kind, err) => {
922
- try {
923
- warnDirect(
924
- JSON.stringify({
925
- level: "warn",
926
- msg: "otlp traces exporter",
927
- kind,
928
- error: err instanceof Error ? err.message : String(err),
929
- timestamp: new Date().toISOString(),
930
- }),
931
- );
932
- } catch {
933
- /* swallow */
934
- }
935
- },
936
- });
937
- } else {
938
- state.otlpTracer = null;
939
- }
940
-
941
- // Wire the tracer stack — composes the OTLP direct-POST adapter (when
942
- // configured) with the @opentelemetry/api bridge. See
943
- // `configureTracerStack` for the fanout semantics.
944
- configureTracerStack(state.otlpTracer);
945
-
946
- state.booted = true;
947
-
948
- // Intercept console.* only when OTLP is active (production). In dev mode
949
- // (no OTLP endpoint) console is left untouched so wrangler dev / wrangler
950
- // tail keep showing output normally.
951
- if (otlpLogsEnabled) {
952
- patchConsole(state);
953
- }
954
-
955
- // Boot breadcrumb — infra telemetry, not application telemetry. Goes to the
956
- // original console (pre-patch) so it shows in wrangler dev / wrangler tail
957
- // without polluting the OTLP buffer (where it would interfere with trace-
958
- // based sampling — there is no active span at boot time).
959
- try {
960
- warnDirect(
961
- JSON.stringify({
962
- level: "info",
963
- msg: "observability booted",
964
- service: serviceName,
965
- analyticsEngine: aeEnabled,
966
- otlpMetrics: otlpEnabled,
967
- otlpLogs: otlpLogsEnabled,
968
- otlpLogsMinLevel: otlpLogsMinLevel,
969
- otlpTraces: otlpTracesEnabled,
970
- consolePatch: otlpLogsEnabled,
971
- runtimeVersion: decoRuntimeVersion,
972
- deploymentEnvironment,
973
- ...(serviceVersion ? { serviceVersion } : {}),
974
- }),
975
- );
976
- } catch {
977
- /* swallow */
978
- }
979
- }
980
-
981
- /**
982
- * Test-only: clear boot state so successive tests can re-boot
983
- * `instrumentWorker` with different options. Do not call from app code.
984
- */
985
- export function _resetBootStateForTests(): void {
986
- const state = getBootState();
987
- state.booted = false;
988
- state.spanAttributeFloor = {};
989
- state.otlpMeter = null;
990
- state.otlpLog = null;
991
- state.otlpTracer = null;
992
- if (state.origConsole) {
993
- console.log = state.origConsole.log;
994
- console.info = state.origConsole.info;
995
- console.warn = state.origConsole.warn;
996
- console.error = state.origConsole.error;
997
- console.debug = state.origConsole.debug;
998
- state.origConsole = null;
999
- }
1000
- setLoggerAttributeFloor({});
1001
- }
1002
-
1003
- // ---------------------------------------------------------------------------
1004
- // Helpers
1005
- // ---------------------------------------------------------------------------
1006
-
1007
- /**
1008
- * @decocms/start version, read from package.json so it stays in sync
1009
- * automatically with every semantic-release cut.
1010
- */
1011
- import pkg from "../../package.json";
1012
- const DECO_RUNTIME_VERSION = pkg.version;