@decocms/blocks 8.1.0-next.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 (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
@@ -1,800 +0,0 @@
1
- /**
2
- * Observability utilities for deco middleware.
3
- *
4
- * Pluggable adapters for tracing (spans) and metrics (counters, gauges,
5
- * histograms). Works with any backend: OpenTelemetry, Sentry, Datadog, etc.
6
- *
7
- * Per-request active spans are propagated via an injectable `RequestStore`
8
- * — by default an AsyncLocalStorage-backed implementation. Tests can swap
9
- * it via `setObservabilitySpanStore()` to assert span lifecycle without
10
- * relying on `node:async_hooks` semantics in the test runner.
11
- *
12
- * @example
13
- * ```ts
14
- * import { configureTracer, configureMeter } from "@decocms/start/middleware";
15
- * import { trace, metrics } from "@opentelemetry/api";
16
- *
17
- * configureTracer({
18
- * startSpan: (name, attrs) => {
19
- * const span = trace.getTracer("deco").startSpan(name, { attributes: attrs });
20
- * return {
21
- * end: () => span.end(),
22
- * setError: (e) => span.recordException(e),
23
- * setAttribute: (k, v) => span.setAttribute(k, v),
24
- * };
25
- * },
26
- * });
27
- *
28
- * configureMeter({
29
- * counterInc: (name, value, labels) => metrics.getMeter("deco").createCounter(name).add(value, labels),
30
- * histogramRecord: (name, value, labels) => {
31
- * // METRIC_METADATA carries the unit AND the bucket boundaries. Forwarding
32
- * // `boundaries` to `advice` is required, not optional: durations are
33
- * // recorded in seconds and the SDK's default buckets are milliseconds, so
34
- * // an adapter that omits it files everything into the first bucket and
35
- * // every quantile reads back as ~0.
36
- * const meta = METRIC_METADATA[name];
37
- * metrics.getMeter("deco")
38
- * .createHistogram(name, {
39
- * unit: meta?.unit,
40
- * description: meta?.description,
41
- * advice: meta?.boundaries
42
- * ? { explicitBucketBoundaries: [...meta.boundaries] }
43
- * : undefined,
44
- * })
45
- * .record(value, labels);
46
- * },
47
- * });
48
- * ```
49
- */
50
-
51
- import * as asyncHooks from "node:async_hooks";
52
- import {
53
- ATTR_HTTP_REQUEST_METHOD,
54
- ATTR_HTTP_RESPONSE_STATUS_CODE,
55
- ATTR_HTTP_ROUTE,
56
- METRIC_HTTP_CLIENT_REQUEST_DURATION,
57
- METRIC_HTTP_SERVER_REQUEST_DURATION,
58
- } from "@opentelemetry/semantic-conventions";
59
- import { logger } from "../sdk/logger";
60
-
61
- // ---------------------------------------------------------------------------
62
- // RequestStore — minimal per-request context abstraction. Inlined here so
63
- // the observability module has zero cross-package dependencies and tests
64
- // can inject a custom implementation via `setObservabilitySpanStore`.
65
- // ---------------------------------------------------------------------------
66
-
67
- export interface RequestStore<T> {
68
- get(): T | undefined;
69
- run<R>(value: T, fn: () => R): R;
70
- }
71
-
72
- class NoopRequestStore implements RequestStore<unknown> {
73
- get(): undefined {
74
- return undefined;
75
- }
76
- run<R>(_value: unknown, fn: () => R): R {
77
- return fn();
78
- }
79
- }
80
-
81
- const noopRequestStore: RequestStore<unknown> = new NoopRequestStore();
82
-
83
- class AlsRequestStore<T> implements RequestStore<T> {
84
- private readonly als:
85
- | { getStore(): T | undefined; run<R>(store: T, fn: () => R): R }
86
- | null;
87
- constructor() {
88
- const ALS = (asyncHooks as { AsyncLocalStorage?: new <U>() => {
89
- getStore(): U | undefined;
90
- run<R>(store: U, fn: () => R): R;
91
- } }).AsyncLocalStorage;
92
- this.als = ALS ? new ALS<T>() : null;
93
- }
94
- get(): T | undefined {
95
- return this.als?.getStore();
96
- }
97
- run<R>(value: T, fn: () => R): R {
98
- return this.als ? this.als.run(value, fn) : fn();
99
- }
100
- }
101
-
102
- // ---------------------------------------------------------------------------
103
- // Tracer
104
- // ---------------------------------------------------------------------------
105
-
106
- export interface Span {
107
- end(): void;
108
- setError?(error: unknown): void;
109
- setAttribute?(key: string, value: string | number | boolean): void;
110
- /**
111
- * Return W3C trace context for the current span. Used by helpers that
112
- * need to correlate logs to traces (`logger`) or propagate context to
113
- * downstream services (`injectTraceContext`). Optional — adapters that
114
- * can't expose it simply leave it off and callers no-op gracefully.
115
- */
116
- spanContext?(): { traceId: string; spanId: string; traceFlags: number };
117
- }
118
-
119
- export interface TracerAdapter {
120
- startSpan(name: string, attributes?: Record<string, string | number | boolean>): Span;
121
- }
122
-
123
- // ---------------------------------------------------------------------------
124
- // Shared module state — pinned to globalThis via Symbol.for so multiple
125
- // inlined copies of this module (one per bundled entry file if/when
126
- // bundling is ever reintroduced) converge on the SAME state. Without this
127
- // indirection, `configureMeter()` from one entry's copy writes to a meter
128
- // that `getMeter()` in another entry's copy never sees, and direct-POST
129
- // telemetry silently no-ops.
130
- //
131
- // Pattern borrowed from @opentelemetry/api / Sentry — both solve the same
132
- // "library with multiple entry exports re-bundles internal state modules"
133
- // problem. Cloudflare Workers guarantee one `globalThis` per isolate, so
134
- // there's no risk of cross-isolate bleed. Defensive against future
135
- // bundling changes; harmless when consumers import from src/ as today.
136
- // ---------------------------------------------------------------------------
137
-
138
- interface ObservabilityState {
139
- tracer: TracerAdapter | null;
140
- meter: MeterAdapter | null;
141
- spanStore: RequestStore<Span | null>;
142
- }
143
-
144
- const STATE_KEY = Symbol.for("@decocms/start/observability/state.v1");
145
-
146
- function getState(): ObservabilityState {
147
- const g = globalThis as Record<symbol, unknown>;
148
- if (!g[STATE_KEY]) {
149
- g[STATE_KEY] = {
150
- tracer: null,
151
- meter: null,
152
- spanStore: new AlsRequestStore<Span | null>(),
153
- } satisfies ObservabilityState;
154
- }
155
- return g[STATE_KEY] as ObservabilityState;
156
- }
157
-
158
- /**
159
- * Swap the RequestStore used for active-span propagation.
160
- *
161
- * Pass `undefined` to reset to the default AsyncLocalStorage-backed store.
162
- * Primarily intended for tests that need deterministic span access without
163
- * setting up an actual ALS context.
164
- */
165
- export function setObservabilitySpanStore(s: RequestStore<Span | null> | undefined): void {
166
- getState().spanStore = s ?? new AlsRequestStore<Span | null>();
167
- }
168
-
169
- export function configureTracer(t: TracerAdapter) {
170
- getState().tracer = t;
171
- }
172
-
173
- export function getTracer(): TracerAdapter | null {
174
- return getState().tracer;
175
- }
176
-
177
- /** Get the currently active span for the current async context, if any. */
178
- export function getActiveSpan(): Span | null {
179
- return getState().spanStore.get() ?? null;
180
- }
181
-
182
- /** Set an attribute on the active span, if one exists. */
183
- export function setSpanAttribute(key: string, value: string | number | boolean) {
184
- getActiveSpan()?.setAttribute?.(key, value);
185
- }
186
-
187
- /**
188
- * Inject the active span's W3C trace context into outbound request headers
189
- * as a `traceparent` header (RFC W3C-tracecontext format
190
- * `version-traceId-parentId-flags`). Call this from outbound `fetch`
191
- * wrappers (e.g. `createInstrumentedFetch` in `@decocms/apps`) so upstream
192
- * services that participate in OTel can correlate their spans with ours.
193
- *
194
- * No-op when no active span exists, when the active span has no
195
- * `spanContext()` adapter method, or when the trace/span IDs aren't
196
- * populated. Never throws.
197
- *
198
- * @example
199
- * ```ts
200
- * import { injectTraceContext } from "@decocms/start/sdk/observability";
201
- *
202
- * async function tracedFetch(url: string, init?: RequestInit) {
203
- * const headers = new Headers(init?.headers);
204
- * injectTraceContext(headers);
205
- * return fetch(url, { ...init, headers });
206
- * }
207
- * ```
208
- */
209
- export function injectTraceContext(headers: Headers): void {
210
- const ctx = getActiveSpan()?.spanContext?.();
211
- if (!ctx || !ctx.traceId || !ctx.spanId) return;
212
- const flags = (ctx.traceFlags & 0xff).toString(16).padStart(2, "0");
213
- headers.set("traceparent", `00-${ctx.traceId}-${ctx.spanId}-${flags}`);
214
- }
215
-
216
- export async function withTracing<T>(
217
- name: string,
218
- fn: () => Promise<T>,
219
- attributes?: Record<string, string | number | boolean>,
220
- ): Promise<T> {
221
- const s = getState();
222
- if (!s.tracer) return fn();
223
-
224
- const span = s.tracer.startSpan(name, attributes);
225
-
226
- try {
227
- const result = await s.spanStore.run(span, fn);
228
- span.end();
229
- return result;
230
- } catch (error) {
231
- span.setError?.(error);
232
- span.end();
233
- throw error;
234
- }
235
- }
236
-
237
- // ---------------------------------------------------------------------------
238
- // Meter
239
- // ---------------------------------------------------------------------------
240
-
241
- type Labels = Record<string, string | number | boolean>;
242
-
243
- export interface MeterAdapter {
244
- counterInc(name: string, value?: number, labels?: Labels): void;
245
- gaugeSet?(name: string, value: number, labels?: Labels): void;
246
- histogramRecord?(name: string, value: number, labels?: Labels): void;
247
- }
248
-
249
- export function configureMeter(m: MeterAdapter) {
250
- getState().meter = m;
251
- }
252
-
253
- export function getMeter(): MeterAdapter | null {
254
- return getState().meter;
255
- }
256
-
257
- /**
258
- * Pre-defined metric names. Where the OTel community SemConv defines a
259
- * canonical metric we use the constant imported from
260
- * `@opentelemetry/semantic-conventions` (e.g.
261
- * `METRIC_HTTP_SERVER_REQUEST_DURATION`) — never write the string ourselves.
262
- * Browse: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
263
- *
264
- * Concepts the OTel community does NOT define (cache hits, CMS resolve,
265
- * per-loader latency) use the Deco extension namespace `deco.*` in dotted
266
- * notation, matching the OTel attribute-naming convention.
267
- *
268
- * Unit / value handling: emitters declare the unit honestly via the
269
- * METRIC_METADATA map below; the framework never converts numeric values.
270
- * Consumers (otel-ingest collector, future Go Collector swap, query
271
- * layers) apply UCUM conversions if their target backend requires a
272
- * specific unit (e.g. canonical OTel `s` for HTTP durations).
273
- */
274
- export const MetricNames = {
275
- // OTel SemConv (stable).
276
- HTTP_SERVER_REQUEST_DURATION: METRIC_HTTP_SERVER_REQUEST_DURATION,
277
- HTTP_CLIENT_REQUEST_DURATION: METRIC_HTTP_CLIENT_REQUEST_DURATION,
278
- // Deco extensions — no canonical OTel metric exists for these concepts.
279
- // Single cache counter dimensioned by `deco.cache.status` — follows the OTel
280
- // semconv pattern (cf. nfs.server.repcache.requests + .status). deco-cx/deco
281
- // uses the same name so both frameworks aggregate together.
282
- // Labels on this counter use short keys (status/profile/layer/provider) —
283
- // the metric name already provides the deco.cache.* namespace.
284
- CACHE_REQUESTS: "deco.cache.requests",
285
- // Size in bytes of the values moving through a cache, dimensioned by `op`.
286
- // Bucketed in decades of bytes — see CACHE_SIZE_BUCKET_BOUNDARIES_BYTES.
287
- CACHE_SIZE: "deco.cache.size",
288
- RESOLVE_DURATION: "deco.cms.resolve.duration",
289
- LOADER_DURATION: "deco.loader.duration",
290
- LOADER_ERRORS: "deco.loader.errors",
291
- } as const;
292
-
293
- /**
294
- * Explicit bucket boundaries, in SECONDS, for every duration histogram declared
295
- * in {@link METRIC_METADATA}.
296
- *
297
- * These exist because the unit and the buckets are configured in two different
298
- * places and had drifted apart. The record helpers divide by 1000, so values
299
- * arrive in seconds — correct per SemConv. But the OTel SDK's *default*
300
- * boundaries are `[0, 5, 10, 25, 50, 75, 100, 250, 500, 1000]`, which are
301
- * milliseconds. An adapter that calls `createHistogram(name)` without an
302
- * `advice` therefore files every sub-5-second observation into the first bucket.
303
- *
304
- * Measured on the production ClickHouse before this change: 99.8%–99.95% of all
305
- * observations on `http.server.request.duration` (78.7M/hour),
306
- * `http.client.request.duration`, `deco.loader.duration` and
307
- * `deco.cms.resolve.duration` sat in bucket 1, so every quantile read back as
308
- * ~0 and the latency dashboards had to fall back to tail-sampled traces.
309
- *
310
- * Values are the SemConv-recommended defaults for HTTP duration histograms.
311
- */
312
- export const DURATION_BUCKET_BOUNDARIES_SECONDS: readonly number[] = [
313
- 0.005,
314
- 0.01,
315
- 0.025,
316
- 0.05,
317
- 0.075,
318
- 0.1,
319
- 0.25,
320
- 0.5,
321
- 0.75,
322
- 1,
323
- 2.5,
324
- 5,
325
- 7.5,
326
- 10,
327
- ];
328
-
329
- /**
330
- * Bucket boundaries, in BYTES, for {@link MetricNames.CACHE_SIZE}.
331
- *
332
- * Decades, matching the `http.server.response.body.size` histogram already
333
- * flowing through the same ingestor — a size distribution is read in orders of
334
- * magnitude, not in linear steps, and reusing the house convention means the
335
- * two byte histograms are directly comparable.
336
- *
337
- * The range is bounded on both ends by the loader cache itself: entries are
338
- * floored at `MIN_ENTRY_BYTES` (512 B) and the store is capped at 32 MB, which
339
- * is why the last bound is the cap rather than another decade — the top bucket
340
- * then reads as "single entry at/near the whole cache budget", which is the
341
- * thing worth alerting on.
342
- */
343
- export const CACHE_SIZE_BUCKET_BOUNDARIES_BYTES: readonly number[] = [
344
- 1_000,
345
- 10_000,
346
- 100_000,
347
- 1_000_000,
348
- 10_000_000,
349
- 33_554_432,
350
- ];
351
-
352
- /**
353
- * Per-metric metadata emitted in the OTLP payload's `description` and
354
- * `unit` fields. Durations are normalized to **seconds at the source** (OTel
355
- * semconv), matching the deco-cx/deco framework — NOT converted downstream in
356
- * the collector. Callers still pass milliseconds; the record helpers divide.
357
- *
358
- * `boundaries`, when present, MUST be forwarded to the histogram's `advice` at
359
- * creation time — the unit alone does not tell the SDK how to bucket, and its
360
- * defaults assume milliseconds. See
361
- * {@link DURATION_BUCKET_BOUNDARIES_SECONDS}.
362
- *
363
- * Keep keys aligned with `MetricNames` values so a missing entry is a
364
- * type error at compile time when a new metric ships without metadata.
365
- */
366
- export const METRIC_METADATA: Record<
367
- string,
368
- {
369
- description: string;
370
- unit: string;
371
- boundaries?: readonly number[];
372
- }
373
- > = {
374
- [MetricNames.HTTP_SERVER_REQUEST_DURATION]: {
375
- description: "Duration of HTTP server requests handled at the Worker entry point.",
376
- unit: "s",
377
- boundaries: DURATION_BUCKET_BOUNDARIES_SECONDS,
378
- },
379
- [MetricNames.HTTP_CLIENT_REQUEST_DURATION]: {
380
- description: "Duration of outbound HTTP client requests (commerce, generic fetch).",
381
- unit: "s",
382
- boundaries: DURATION_BUCKET_BOUNDARIES_SECONDS,
383
- },
384
- [MetricNames.CACHE_REQUESTS]: {
385
- description: "Cache lookups, dimensioned by status (hit/stale/miss/bypass).",
386
- unit: "{request}",
387
- },
388
- [MetricNames.CACHE_SIZE]: {
389
- description: "Size in bytes of values written to / read from a cache, dimensioned by op.",
390
- unit: "By",
391
- boundaries: CACHE_SIZE_BUCKET_BOUNDARIES_BYTES,
392
- },
393
- [MetricNames.RESOLVE_DURATION]: {
394
- description: "Duration of `deco.cms.resolvePage` — CMS route to block tree resolution.",
395
- unit: "s",
396
- boundaries: DURATION_BUCKET_BOUNDARIES_SECONDS,
397
- },
398
- [MetricNames.LOADER_DURATION]: {
399
- description: "Per-loader execution duration, emitted by cachedLoader.",
400
- unit: "s",
401
- boundaries: DURATION_BUCKET_BOUNDARIES_SECONDS,
402
- },
403
- [MetricNames.LOADER_ERRORS]: {
404
- description: "Per-loader error count.",
405
- unit: "{error}",
406
- },
407
- };
408
-
409
- /**
410
- * Map an HTTP status code to its canonical class label (`2xx` / ... /
411
- * `5xx`). Out-of-range numbers (e.g. -1 from a thrown fetch) fall back
412
- * to `"unknown"` so dashboards don't break on edge cases.
413
- *
414
- * Exported because callers occasionally need the same mapping for
415
- * non-metric purposes (logging, tail enrichment).
416
- */
417
- export function statusClassFor(status: number): string {
418
- if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
419
- if (status < 100 || status >= 600) return "unknown";
420
- return `${Math.floor(status / 100)}xx`;
421
- }
422
-
423
- /**
424
- * Optional dimensions stamped on `http.server.request.duration` (semconv).
425
- * Request count and error rate are derived from the histogram's `count` and
426
- * a `http.response.status_code` filter — the old separate `_total` /
427
- * `_errors_total` counters were removed. All fields are optional — callers
428
- * pass what they have, the framework fills in the rest from defaults.
429
- *
430
- * Cardinality discipline: every field here is bounded. `route_pattern`
431
- * comes from the TanStack router (a closed set), `outcome` is the CF
432
- * Workers Observability enum, `cache_decision` / `cache_layer` are
433
- * union types declared in this module, `region` is a small set of CF
434
- * colo codes. Status is unbounded by spec but bounded in practice; the
435
- * `status_class` label bounds the cardinality further for dashboards
436
- * that don't need the raw value.
437
- */
438
- /**
439
- * Per-request identifiers that MUST NOT be stamped on metric labels.
440
- * They belong on spans (where they are 1:1 with the entity being
441
- * observed) and on logs (where they enable cross-channel correlation).
442
- * Putting them on metric labels collapses aggregation — every request
443
- * becomes its own histogram data point.
444
- */
445
- const HIGH_CARDINALITY_BLOCKLIST = new Set<string>([
446
- "request.id",
447
- "trace.id",
448
- "span.id",
449
- "session.id",
450
- "user.id",
451
- ]);
452
-
453
- export interface RequestMetricLabels {
454
- /** TanStack route pattern (`/_products/$slug/p`) — closed set. */
455
- route_pattern?: string;
456
- /** Cloudflare Workers Observability `outcome` (`ok`, `exception`, ...). */
457
- outcome?: string;
458
- /** Cache layer + decision when known. */
459
- cache_decision?: CacheDecision;
460
- cache_layer?: CacheLayer;
461
- /** Cloudflare colo (`GRU`, `IAD`, ...). */
462
- region?: string;
463
- /**
464
- * Arbitrary extra labels — callers should avoid this and add fields
465
- * to the typed surface above instead. Kept as an escape hatch so
466
- * non-canonical experiments don't require a framework release.
467
- */
468
- extra?: Record<string, string | number | boolean>;
469
- }
470
-
471
- /**
472
- * Record an HTTP request metric.
473
- *
474
- * Call in middleware after the response is produced. Two-call surface
475
- * for backward compat:
476
- *
477
- * recordRequestMetric(method, path, status, durationMs)
478
- * recordRequestMetric(method, path, status, durationMs, labels)
479
- *
480
- * The labels argument is optional — sites that haven't bumped to the
481
- * Phase 2 metric shape still emit the original three labels
482
- * (`method`, `route_pattern`, `status`). Adding labels never changes
483
- * existing labels' values; only adds new ones.
484
- */
485
- export function recordRequestMetric(
486
- method: string,
487
- path: string,
488
- status: number,
489
- durationMs: number,
490
- labels?: RequestMetricLabels,
491
- ) {
492
- const m = getState().meter;
493
- if (!m) return;
494
- // Cardinality discipline:
495
- // - `method`: small (GET, POST, ...).
496
- // - `route_pattern`: closed set (caller-supplied) OR normalized path
497
- // (fallback). Either way bounded.
498
- // - `status`: full HTTP code (bounded ~50 values in practice).
499
- // - `status_class`: 5-element enum (2xx / 3xx / 4xx / 5xx / unknown).
500
- // - `outcome`: CF outcome enum (~7 values).
501
- // - `cache_decision`: 5-element enum.
502
- // - `cache_layer`: 3-element enum (edge / cachedLoader / swr).
503
- // - `region`: ~250 CF colo codes worldwide.
504
- // Total combinations are bounded — safe for unbounded series on
505
- // ClickHouse but operators should still avoid grouping by `region`
506
- // unless explicitly needed.
507
- // semconv attribute keys for the core HTTP dimensions; deco.* for the
508
- // proprietary extras. Unified with deco-cx/deco so both frameworks land on
509
- // the same series/labels in ClickHouse.
510
- const merged: Labels = {
511
- [ATTR_HTTP_REQUEST_METHOD]: method,
512
- [ATTR_HTTP_ROUTE]: labels?.route_pattern ?? normalizePath(path),
513
- [ATTR_HTTP_RESPONSE_STATUS_CODE]: status,
514
- "deco.http.status_class": statusClassFor(status),
515
- };
516
- if (labels?.outcome) merged["deco.http.outcome"] = labels.outcome;
517
- if (labels?.cache_decision) merged["deco.cache.decision"] = labels.cache_decision;
518
- if (labels?.cache_layer) merged["deco.cache.layer"] = labels.cache_layer;
519
- if (labels?.region) merged["deco.http.region"] = labels.region;
520
- if (labels?.extra) {
521
- for (const [k, v] of Object.entries(labels.extra)) {
522
- // Defense-in-depth — refuse to stamp known per-request identifiers
523
- // on metric labels. These belong on spans and logs only; putting
524
- // them here makes every request its own histogram data point and
525
- // destroys aggregation. Caller-supplied `extra` should remain a
526
- // low-cardinality escape hatch (A/B variant, feature flag, ...).
527
- if (HIGH_CARDINALITY_BLOCKLIST.has(k)) continue;
528
- merged[k] = v;
529
- }
530
- }
531
- // OTel canonical HTTP metrics define a single histogram per direction
532
- // (`http.server.request.duration` for incoming). The request count is
533
- // derived from the histogram's `count` field; error rate is derived by
534
- // filtering on `http.response.status_code`. Separate `_total` /
535
- // `_errors_total` counters were removed because they duplicate
536
- // histogram-derived signals and aren't part of the canonical spec.
537
- // Record in seconds (semconv) — caller passes ms.
538
- m.histogramRecord?.(
539
- MetricNames.HTTP_SERVER_REQUEST_DURATION,
540
- durationMs / 1000,
541
- merged,
542
- );
543
- }
544
-
545
- /**
546
- * Cache decision label. Mirrors the `X-Cache` response header we set in
547
- * `workerEntry.ts` so dashboards can join on it.
548
- * - `HIT` — fresh entry returned from cache
549
- * - `STALE-HIT` — stale entry served, async revalidation kicked off (SWR)
550
- * - `STALE-ERROR` — stale entry served because origin errored (SIE)
551
- * - `MISS` — cache lookup returned nothing, origin fetched
552
- * - `BYPASS` — request not eligible for caching (private, cookies, etc.)
553
- */
554
- export type CacheDecision = "HIT" | "STALE-HIT" | "STALE-ERROR" | "MISS" | "BYPASS";
555
-
556
- /**
557
- * Where the cache lives. Phase 2 label expansion (D-11).
558
- * - `edge` — Cloudflare Cache API (HTML pages, server-fn responses)
559
- * - `cachedLoader` — In-memory per-isolate via `sdk/cachedLoader.ts`
560
- * (loader-level SWR, dedup, in-flight)
561
- * - `swr` — Apps-side in-memory SWR fetch cache shared by commerce
562
- * clients (VTEX intelligent-search, Magento GraphQL,
563
- * Shopify, etc.) via `sdk/fetchCache.ts`. Provider-agnostic;
564
- * the specific backend rides on `deco.cache.provider`
565
- * (e.g. `vtex` / `magento` / `shopify`), a separate label
566
- * from `deco.cache.profile` (page-type, set by `edge`).
567
- * Renamed from the old `vtex-swr` once the util was shared.
568
- */
569
- export type CacheLayer = "edge" | "cachedLoader" | "swr";
570
-
571
- /**
572
- * Record a cache hit/miss metric. Also stamps the decision on the active
573
- * trace span (when one exists) as `deco.cache.decision` / `deco.cache.profile`
574
- * so operators can filter ClickStack traces by cache decision directly,
575
- * without joining to metrics.
576
- *
577
- * Backward-compatible signature:
578
- * recordCacheMetric(hit, profile?, decision?)
579
- * recordCacheMetric(hit, profile?, decision?, layer?)
580
- * recordCacheMetric(hit, profile?, decision?, layer?, provider?)
581
- *
582
- * `decision` is optional — when omitted, the metric still records HIT
583
- * vs MISS but dashboards can't distinguish SWR/SIE paths. Pass it
584
- * whenever known. `layer` defaults to `edge` when called from
585
- * workerEntry; cachedLoader / swr call sites should pass their
586
- * value explicitly.
587
- *
588
- * `profile` and `provider` are DISTINCT dimensions and must not be
589
- * conflated: `profile` is the page/route type (`product` / `listing` /
590
- * `search`, set by the `edge` layer) or loader name (`cachedLoader`);
591
- * `provider` is the commerce backend (`vtex` / `magento` / `shopify`, set
592
- * by the `swr` layer). Keeping them on separate labels means a
593
- * `sum by (profile)` panel never blends page-types with backend
594
- * names. The `swr` layer passes `provider` and leaves `profile` unset.
595
- */
596
- export function recordCacheMetric(
597
- hit: boolean,
598
- profile?: string,
599
- decision?: CacheDecision,
600
- layer?: CacheLayer,
601
- provider?: string,
602
- ) {
603
- // Stamp on the active span FIRST so the attribute survives even if the
604
- // meter is a no-op (e.g. on tests, or in dev without DECO_METRICS).
605
- const active = getActiveSpan();
606
- if (active) {
607
- if (decision) active.setAttribute?.("deco.cache.status", decision);
608
- if (profile) active.setAttribute?.("deco.cache.profile", profile);
609
- if (layer) active.setAttribute?.("deco.cache.layer", layer);
610
- if (provider) active.setAttribute?.("deco.cache.provider", provider);
611
- }
612
-
613
- const m = getState().meter;
614
- if (!m) return;
615
- // Single counter dimensioned by status — the metric name deco.cache.requests
616
- // already scopes the label, so the deco.cache. prefix is redundant on labels.
617
- // Span attribute keeps the full deco.cache.status key (spans mix attrs from
618
- // many sources, so the namespace is needed there).
619
- const labels: Labels = {
620
- status: decision ?? (hit ? "HIT" : "MISS"),
621
- };
622
- if (profile) labels["profile"] = profile;
623
- if (layer) labels["layer"] = layer;
624
- if (provider) labels["provider"] = provider;
625
- m.counterInc(MetricNames.CACHE_REQUESTS, 1, labels);
626
- }
627
-
628
- /**
629
- * Record the size of a value moving through a cache, in BYTES — not seconds,
630
- * so unlike the duration helpers this one does not divide.
631
- *
632
- * `profile` deliberately reuses the label key {@link recordCacheMetric} already
633
- * uses for the `cachedLoader` layer (there it carries the loader name), so
634
- * `deco.cache.size` joins `deco.cache.requests{layer="cachedLoader"}` on
635
- * `profile` with no renaming in the query.
636
- *
637
- * Only `op: "set"` is emitted today; the label exists so a future read-side
638
- * measurement lands on the same series without a breaking dashboard change.
639
- */
640
- export function recordCacheSizeMetric(bytes: number, profile: string, op: "set" | "get" = "set") {
641
- getState().meter?.histogramRecord?.(MetricNames.CACHE_SIZE, bytes, { op, profile });
642
- }
643
-
644
- /**
645
- * Labels for the outbound commerce sample recorded on
646
- * `http.client.request.duration`. Owned by the framework so apps-start (and
647
- * any future provider package) can register operation strings without owning
648
- * the histogram declaration. Phase 2 (D-11).
649
- */
650
- export interface CommerceMetricLabels {
651
- /** `vtex`, `shopify`, `wake`, ... — small closed set. */
652
- provider: string;
653
- /** Per-provider operation, e.g. `intelligent-search.product_search`. */
654
- operation: string;
655
- /** Set when known (e.g. from the HTTP response). Bounded enum. */
656
- status_class?: string;
657
- /** Whether the underlying fetch was served from a cache. */
658
- cached?: boolean;
659
- }
660
-
661
- /**
662
- * Record a commerce / outbound-fetch duration sample. No-op when no meter is
663
- * configured. Emitted on the canonical `http.client.request.duration` metric
664
- * (semconv) — providers vary by the `provider`/`operation` labels, not by
665
- * name, so dashboards aggregate cleanly across the fleet.
666
- */
667
- export function recordCommerceMetric(
668
- durationMs: number,
669
- labels: CommerceMetricLabels,
670
- ) {
671
- const m = getState().meter;
672
- if (!m) return;
673
- const merged: Labels = {
674
- provider: labels.provider,
675
- operation: labels.operation,
676
- };
677
- if (labels.status_class) merged.status_class = labels.status_class;
678
- if (typeof labels.cached === "boolean") merged.cached = labels.cached;
679
- // Canonical OTel HTTP client metric — outbound commerce calls share the
680
- // same metric as any other outbound HTTP request; `peer.service` /
681
- // `commerce.operation` attributes disambiguate consumer queries.
682
- // Record in seconds (semconv) — caller passes ms.
683
- m.histogramRecord?.(
684
- MetricNames.HTTP_CLIENT_REQUEST_DURATION,
685
- durationMs / 1000,
686
- merged,
687
- );
688
- }
689
-
690
- /**
691
- * Record a loader execution sample. Call from `cachedLoader` after the
692
- * loader resolves or rejects. `cache_status` mirrors `CacheDecision` so
693
- * dashboards can distinguish HIT (fresh) from STALE-HIT (SWR), STALE-ERROR
694
- * (SIE fallback), MISS (origin fetch), and BYPASS (dev / no-store).
695
- */
696
- export function recordLoaderMetric(
697
- name: string,
698
- durationMs: number,
699
- cacheStatus: CacheDecision | "BYPASS",
700
- ) {
701
- const m = getState().meter;
702
- if (!m) return;
703
- // Record in seconds (semconv) — caller passes ms.
704
- m.histogramRecord?.(MetricNames.LOADER_DURATION, durationMs / 1000, {
705
- "deco.loader.name": name,
706
- "deco.cache.result": cacheStatus,
707
- });
708
- }
709
-
710
- /**
711
- * Increment the loader error counter. Call when a loader throws and the
712
- * error is not swallowed by a SIE fallback.
713
- */
714
- export function recordLoaderError(name: string) {
715
- const m = getState().meter;
716
- if (!m) return;
717
- m.counterInc(MetricNames.LOADER_ERRORS, 1, { "deco.loader.name": name });
718
- }
719
-
720
- /**
721
- * Collapse dynamic path segments (ids, product slugs) into placeholders so a
722
- * path can be used as a bounded metric label. Exported so every metric that
723
- * labels by route (`http.server.request.duration`, `deco.cms.resolve.duration`)
724
- * shares the exact same normalization — a raw path is unbounded cardinality
725
- * (one histogram series per URL) and must never reach a metric attribute.
726
- */
727
- export function normalizePath(path: string): string {
728
- // Collapse dynamic segments to reduce cardinality
729
- const collapsed = path
730
- .replace(/\/[0-9a-f]{8,}/gi, "/:id")
731
- .replace(/\/\d+/g, "/:id")
732
- .replace(/\/[^/]+\/p$/, "/:slug/p");
733
-
734
- // Content slugs are the case none of the rules above catch: they carry no
735
- // digits, no hex id and no `/p` suffix, so a CMS page passes through as its
736
- // own literal path and becomes its own series.
737
- //
738
- // /mochila-de-couro
739
- // /moveis/quarto-infantil
740
- // /acme/eau-de-toilette-spritz-100ml
741
- //
742
- // Measured on the production ClickHouse, `http.route` reached 20,714
743
- // distinct values across only 6 tenants — on `http.server.request.duration`,
744
- // the highest-volume metric in the pipeline (19M rows / 3h).
745
- //
746
- // A hyphen is the discriminator. CMS slugs are hyphenated by construction,
747
- // while framework and API segments are single words (`api`, `sessions`,
748
- // `deco`, `invoke`, `loaders`, `render`). Dotfile segments such as
749
- // `.well-known` are excluded so they keep their meaning.
750
- return collapsed
751
- .split("/")
752
- .map((segment) =>
753
- segment.includes("-") && !segment.startsWith(".") ? ":slug" : segment,
754
- )
755
- .join("/");
756
- }
757
-
758
- // ---------------------------------------------------------------------------
759
- // Request logging
760
- // ---------------------------------------------------------------------------
761
-
762
- const isDev =
763
- typeof globalThis.process !== "undefined" && globalThis.process.env?.NODE_ENV === "development";
764
-
765
- /**
766
- * Structured request log entry.
767
- * JSON in production, colorized in development.
768
- * Includes traceId when available.
769
- */
770
- export function logRequest(
771
- request: Request,
772
- status: number,
773
- durationMs: number,
774
- extra?: Record<string, unknown>,
775
- ) {
776
- const url = new URL(request.url);
777
- // Truncate long paths (e.g. /_serverFn/ base64 payloads) so log messages
778
- // remain readable. Full path is preserved in the `path` attribute.
779
- const rawPath = url.pathname;
780
- const displayPath = rawPath.length > 80 ? `${rawPath.slice(0, 80)}…` : rawPath;
781
- // Route through the framework logger so the access log fans out to every
782
- // configured adapter — local stdout via `defaultLoggerAdapter`, OTLP direct-
783
- // POST via `otlpLog.adapter` when configured (subject to its
784
- // `DECO_OTEL_LOGS_MIN_LEVEL` threshold). Always debug: filtered in prod
785
- // (default `warn` minLevel), visible in dev with DECO_OTEL_LOGS_MIN_LEVEL=debug.
786
- // 5xx errors are already logged at the throw site with full context; the
787
- // access log is just a dev convenience, not a production alert source.
788
- logger.debug(`${request.method} ${displayPath} ${status}`, {
789
- method: request.method,
790
- path: rawPath,
791
- status,
792
- duration_ms: Math.round(durationMs),
793
- ...extra,
794
- });
795
- }
796
-
797
- // noopRequestStore is kept as a no-op fallback for advanced tests; not
798
- // re-exported because consumers should reach for `setObservabilitySpanStore`
799
- // instead.
800
- void noopRequestStore;