@harlan-zw/nuxt-cloudflare 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/d1.d.mts CHANGED
@@ -1,3 +1,55 @@
1
+ /**
2
+ * Request-scoped D1 counters.
3
+ *
4
+ * D1 answers every remote query with a `meta` block naming the node that served
5
+ * it — `served_by_primary`, `served_by_region` — and the session layer here
6
+ * already knows when it had to recover from a reset. Neither fact survives the
7
+ * request unless something records it, and both are exactly what you want when
8
+ * a request is slow or an isolate dies: how many queries did this request make,
9
+ * how many of them crossed to the primary, and did the session have to restart.
10
+ *
11
+ * Kept separate from the session machinery so it stays optional. A caller that
12
+ * wants no telemetry passes no stats object and pays nothing.
13
+ */
14
+ declare const REQUEST_D1_STATS: unique symbol;
15
+ interface D1RequestStats {
16
+ /** Terminal statement executions and batches. */
17
+ queries: number;
18
+ /** Of those, served by the primary rather than a replica. */
19
+ primaryQueries: number;
20
+ /** Sessions restarted after a reset the layer could recover from. */
21
+ recoveries: number;
22
+ /** Recoveries that gave up, i.e. the caller saw the error. */
23
+ unrecovered: number;
24
+ /** Region of the last node that served a query, e.g. `OC`. */
25
+ region: string | null;
26
+ /** Total SQL execution time D1 reported, in milliseconds. */
27
+ durationMs: number;
28
+ }
29
+ declare function createD1Stats(): D1RequestStats;
30
+ /**
31
+ * The stats object for this request, created on first use.
32
+ *
33
+ * Takes the request context rather than an `H3Event` so the same helper works
34
+ * in a queue consumer or a scheduled task, which have no event but do have a
35
+ * per-invocation object to hang state on.
36
+ */
37
+ declare function useD1Stats(requestContext: Record<PropertyKey, unknown>): D1RequestStats;
38
+ /** The stats recorded so far, or `null` when this request never touched D1. */
39
+ declare function readD1Stats(requestContext: Record<PropertyKey, unknown> | undefined): D1RequestStats | null;
40
+ /**
41
+ * Fold one D1 result's `meta` into the request's counters.
42
+ *
43
+ * Every field is checked before use: `meta` is absent under `wrangler dev` and
44
+ * on a local D1, where these keys do not exist at all, and a telemetry helper
45
+ * that throws in development would be worse than one that records nothing.
46
+ */
47
+ declare function recordD1Meta(stats: D1RequestStats, result: unknown): void;
48
+ /** Fold a recovery event into the request's counters. */
49
+ declare function recordD1Recovery(stats: D1RequestStats, event: {
50
+ _tag: 'retrying' | 'stopped';
51
+ }): void;
52
+
1
53
  type D1WriteSafety = {
2
54
  _tag: 'lock-only';
3
55
  } | {
@@ -78,6 +130,11 @@ interface D1ResetRecoveryOptions {
78
130
  consistency?: D1Consistency;
79
131
  maxAttempts?: number;
80
132
  onRecovery?: (event: D1RecoveryEvent) => void;
133
+ /**
134
+ * Fold this session's query and recovery counts into a request-scoped stats
135
+ * object. Omit it and nothing is recorded. See `d1-stats.ts`.
136
+ */
137
+ stats?: D1RequestStats;
81
138
  random?: () => number;
82
139
  sleep?: (milliseconds: number) => Promise<void>;
83
140
  }
@@ -92,5 +149,5 @@ declare function getRequestD1Session<Session>(requestContext: Record<PropertyKey
92
149
  declare function getRecoveringRequestD1Session<Session extends D1SessionLike>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, options?: D1ResetRecoveryOptions): Session;
93
150
  declare function retryIdempotentD1Write<T>(options: RetryIdempotentD1WriteOptions<T>): Promise<T>;
94
151
 
95
- export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
96
- export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RecoveryEvent, D1ResetRecoveryOptions, D1RetryErrorKind, D1SessionLike, D1SessionSource, D1StatementLike, D1WriteSafety, RetryIdempotentD1WriteOptions };
152
+ export { D1_MAX_BOUND_PARAMETERS, REQUEST_D1_STATS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, createD1Stats, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, readD1Stats, recordD1Meta, recordD1Recovery, retryIdempotentD1Write, useD1Stats, withD1ResetRecovery };
153
+ export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RecoveryEvent, D1RequestStats, D1ResetRecoveryOptions, D1RetryErrorKind, D1SessionLike, D1SessionSource, D1StatementLike, D1WriteSafety, RetryIdempotentD1WriteOptions };
package/dist/d1.mjs CHANGED
@@ -1,3 +1,37 @@
1
+ const REQUEST_D1_STATS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-request-stats");
2
+ function createD1Stats() {
3
+ return { queries: 0, primaryQueries: 0, recoveries: 0, unrecovered: 0, region: null, durationMs: 0 };
4
+ }
5
+ function useD1Stats(requestContext) {
6
+ const existing = requestContext[REQUEST_D1_STATS];
7
+ if (existing && typeof existing === "object")
8
+ return existing;
9
+ const stats = createD1Stats();
10
+ requestContext[REQUEST_D1_STATS] = stats;
11
+ return stats;
12
+ }
13
+ function readD1Stats(requestContext) {
14
+ const stats = requestContext?.[REQUEST_D1_STATS];
15
+ return stats && typeof stats === "object" ? stats : null;
16
+ }
17
+ function recordD1Meta(stats, result) {
18
+ stats.queries++;
19
+ const meta = result?.meta;
20
+ if (!meta)
21
+ return;
22
+ if (meta.served_by_primary === true)
23
+ stats.primaryQueries++;
24
+ if (typeof meta.served_by_region === "string")
25
+ stats.region = meta.served_by_region;
26
+ if (typeof meta.duration === "number")
27
+ stats.durationMs += meta.duration;
28
+ }
29
+ function recordD1Recovery(stats, event) {
30
+ stats.recoveries++;
31
+ if (event._tag === "stopped")
32
+ stats.unrecovered++;
33
+ }
34
+
1
35
  const D1_MAX_BOUND_PARAMETERS = 100;
2
36
  const D1_PARAMETER_PLAN = Symbol("@harlan-zw/nuxt-cloudflare:d1-parameter-plan");
3
37
  const REQUEST_D1_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-sessions");
@@ -234,8 +268,11 @@ function withD1ResetRecovery(database, options = {}) {
234
268
  (value) => ({ _tag: "ok", value }),
235
269
  (error) => ({ _tag: "error", error })
236
270
  );
237
- if (outcome._tag === "ok")
271
+ if (outcome._tag === "ok") {
272
+ if (options.stats)
273
+ recordD1Meta(options.stats, outcome.value);
238
274
  return outcome.value;
275
+ }
239
276
  const failure = classifyD1RetryError(outcome.error);
240
277
  if (failure._tag !== "session-reset" && failure._tag !== "transient")
241
278
  throw outcome.error;
@@ -243,6 +280,8 @@ function withD1ResetRecovery(database, options = {}) {
243
280
  if (failure._tag === "session-reset")
244
281
  renewSession();
245
282
  if (!replayable || exhausted) {
283
+ if (options.stats)
284
+ recordD1Recovery(options.stats, { _tag: "stopped" });
246
285
  options.onRecovery?.({
247
286
  _tag: "stopped",
248
287
  attempt,
@@ -252,6 +291,8 @@ function withD1ResetRecovery(database, options = {}) {
252
291
  });
253
292
  throw outcome.error;
254
293
  }
294
+ if (options.stats)
295
+ recordD1Recovery(options.stats, { _tag: "retrying" });
255
296
  options.onRecovery?.({ _tag: "retrying", attempt, failure, sql });
256
297
  await sleep(retryDelay(attempt, random));
257
298
  }
@@ -343,6 +384,10 @@ function getRecoveringRequestD1Session(requestContext, binding, database, option
343
384
  const sessions = getD1SessionCache(requestContext, REQUEST_D1_RECOVERING_SESSIONS);
344
385
  if (!sessions.has(key)) {
345
386
  sessions.set(key, withD1ResetRecovery(database, {
387
+ // A request-scoped session gets request-scoped counters by default: the
388
+ // context to hang them on is the argument this function already takes,
389
+ // and a caller that wants none can pass its own `stats`.
390
+ stats: useD1Stats(requestContext),
346
391
  ...options,
347
392
  consistency
348
393
  }));
@@ -371,4 +416,4 @@ async function retryIdempotentD1Write(options) {
371
416
  throw lastError;
372
417
  }
373
418
 
374
- export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
419
+ export { D1_MAX_BOUND_PARAMETERS, REQUEST_D1_STATS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, createD1Stats, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, readD1Stats, recordD1Meta, recordD1Recovery, retryIdempotentD1Write, useD1Stats, withD1ResetRecovery };
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0 <5.0.0"
6
6
  },
7
- "version": "0.0.14",
7
+ "version": "0.0.16",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import process from 'node:process';
2
- import { useLogger, defineNuxtModule, addTypeTemplate } from '@nuxt/kit';
2
+ import { useLogger, defineNuxtModule, hasNuxtModule, addTypeTemplate } from '@nuxt/kit';
3
3
  import { resolve } from 'pathe';
4
4
  import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
5
5
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, applyCloudflareDefaults } from './wrangler.mjs';
@@ -101,6 +101,21 @@ const workersCachePluginPath = resolve(
101
101
  import.meta.dirname,
102
102
  import.meta.url.endsWith(".ts") ? "runtime/server/plugins/workers-cache.ts" : "runtime/server/plugins/workers-cache.js"
103
103
  );
104
+ const wideEventsPluginPath = resolve(
105
+ import.meta.dirname,
106
+ import.meta.url.endsWith(".ts") ? "runtime/server/plugins/wide-events.ts" : "runtime/server/plugins/wide-events.js"
107
+ );
108
+ const WIDE_EVENT_FIELDS = [
109
+ "cf.colo",
110
+ "cf.country",
111
+ "cf.httpProtocol",
112
+ "d1.durationMs",
113
+ "d1.primaryQueries",
114
+ "d1.queries",
115
+ "d1.recoveries",
116
+ "d1.region",
117
+ "d1.unrecovered"
118
+ ];
104
119
  const BUILD_SECRET_ENV_RE = /(?:^|_)(?:API_?KEY|AUTH_TOKEN|CLIENT_SECRET|CREDENTIALS?|ENCRYPTION_KEY|PASSWORD|PRIVATE_KEY|SECRET|SIGNING_KEY|TOKEN|SALT)(?:_|$)/i;
105
120
  const REQUIRED_BUILD_SECRET_NAMES = /* @__PURE__ */ new Set(["NUXT_SCRIPTS_PROXY_SECRET"]);
106
121
  function resolveModuleWorkersCachePolicy(options) {
@@ -212,6 +227,16 @@ function setupCloudflareModule(options, nuxt) {
212
227
  options,
213
228
  Boolean(nuxt.options.sourcemap.server)
214
229
  );
230
+ const registerWideEventFields = nuxt.hook;
231
+ registerWideEventFields("wide-events:fields", (registry) => {
232
+ registry.add("@harlan-zw/nuxt-cloudflare", [...WIDE_EVENT_FIELDS]);
233
+ });
234
+ if (Array.isArray(nuxt.options.modules) && hasNuxtModule("@harlan-zw/nuxt-wide-events", nuxt)) {
235
+ const wideEventsNitro = nuxt.options.nitro;
236
+ wideEventsNitro.plugins ??= [];
237
+ if (!wideEventsNitro.plugins.includes(wideEventsPluginPath))
238
+ wideEventsNitro.plugins.push(wideEventsPluginPath);
239
+ }
215
240
  let bindingTypeSignature;
216
241
  if (options.bindingTypes !== false) {
217
242
  const bindingTypesTemplate = addTypeTemplate({
@@ -0,0 +1,24 @@
1
+ import type { H3Event } from 'h3';
2
+ import type { NitroApp } from 'nitropack/types';
3
+ /**
4
+ * Contribute Cloudflare request context to the request's Wide Event.
5
+ *
6
+ * Two things worth one flat record per request, neither visible from
7
+ * application code:
8
+ *
9
+ * `cf.*` — which colo actually ran the isolate. A Worker's latency story is
10
+ * mostly "where did this run relative to its data", and the colo is the only
11
+ * field that answers it.
12
+ *
13
+ * `d1.*` — how many queries the request made, how many crossed to the primary
14
+ * rather than a replica, and whether the session had to recover. A request that
15
+ * quietly makes twenty serial primary round trips looks identical to a fast one
16
+ * in every other log line; these counters are what separate them.
17
+ *
18
+ * Registered by the module only when `@harlan-zw/nuxt-wide-events` is present,
19
+ * and the fields are declared through `addWideEventFields` at build time, so
20
+ * the consuming application never hand-lists them and cannot drift from them.
21
+ */
22
+ declare const _default: (nitroApp: NitroApp) => void;
23
+ export default _default;
24
+ export declare function recordCloudflareWideEventFields(event: H3Event): void;
@@ -0,0 +1,30 @@
1
+ import { addWideEventFields } from "#imports";
2
+ import { readD1Stats } from "../../../d1-stats";
3
+ export default (nitroApp) => {
4
+ nitroApp.hooks.hook("beforeResponse", (event) => {
5
+ recordCloudflareWideEventFields(event);
6
+ });
7
+ };
8
+ export function recordCloudflareWideEventFields(event) {
9
+ const fields = {};
10
+ const cf = event.context.cloudflare?.request?.cf;
11
+ if (cf) {
12
+ if (typeof cf.colo === "string")
13
+ fields["cf.colo"] = cf.colo;
14
+ if (typeof cf.country === "string")
15
+ fields["cf.country"] = cf.country;
16
+ if (typeof cf.httpProtocol === "string")
17
+ fields["cf.httpProtocol"] = cf.httpProtocol;
18
+ }
19
+ const d1 = readD1Stats(event.context);
20
+ if (d1) {
21
+ fields["d1.queries"] = d1.queries;
22
+ fields["d1.primaryQueries"] = d1.primaryQueries;
23
+ fields["d1.recoveries"] = d1.recoveries;
24
+ fields["d1.unrecovered"] = d1.unrecovered;
25
+ fields["d1.durationMs"] = Math.round(d1.durationMs);
26
+ fields["d1.region"] = d1.region;
27
+ }
28
+ if (Object.keys(fields).length)
29
+ addWideEventFields(event, fields);
30
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.0.14",
4
+ "version": "0.0.16",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",