@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.1 → 0.0.2-rc.10

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 (61) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +236 -84
  3. package/lib/config.d.ts +3 -2
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +58 -57
  6. package/lib/config.js.map +1 -1
  7. package/lib/events.d.ts.map +1 -1
  8. package/lib/events.js.map +1 -1
  9. package/lib/export-config.d.ts +19 -5
  10. package/lib/export-config.d.ts.map +1 -1
  11. package/lib/export-config.js +6 -1
  12. package/lib/export-config.js.map +1 -1
  13. package/lib/handlers.d.ts +38 -6
  14. package/lib/handlers.d.ts.map +1 -1
  15. package/lib/handlers.js +63 -18
  16. package/lib/handlers.js.map +1 -1
  17. package/lib/index.d.ts +13 -2
  18. package/lib/index.d.ts.map +1 -1
  19. package/lib/index.js +51 -12
  20. package/lib/index.js.map +1 -1
  21. package/lib/init.d.ts +1 -1
  22. package/lib/init.js +1 -1
  23. package/lib/init.js.map +1 -1
  24. package/lib/lib.d.ts +1 -1
  25. package/lib/lib.d.ts.map +1 -1
  26. package/lib/lib.js +2 -1
  27. package/lib/lib.js.map +1 -1
  28. package/lib/logs.d.ts +2 -2
  29. package/lib/logs.d.ts.map +1 -1
  30. package/lib/logs.js +4 -3
  31. package/lib/logs.js.map +1 -1
  32. package/lib/region.d.ts +7 -0
  33. package/lib/region.d.ts.map +1 -0
  34. package/lib/region.js +37 -0
  35. package/lib/region.js.map +1 -0
  36. package/lib/tasks.d.ts +40 -0
  37. package/lib/tasks.d.ts.map +1 -0
  38. package/lib/tasks.js +107 -0
  39. package/lib/tasks.js.map +1 -0
  40. package/lib/util.d.ts.map +1 -1
  41. package/lib/util.js.map +1 -1
  42. package/npm-shrinkwrap.json +160 -780
  43. package/package.json +10 -4
  44. package/src/config.ts +70 -59
  45. package/src/export-config.ts +26 -6
  46. package/src/handlers.ts +96 -27
  47. package/src/index.ts +71 -13
  48. package/src/init.ts +1 -1
  49. package/src/lib.ts +2 -0
  50. package/src/logs.ts +5 -3
  51. package/src/region.ts +37 -0
  52. package/src/tasks.ts +126 -0
  53. package/tests/config.test.ts +101 -14
  54. package/tests/export-config.test.ts +10 -4
  55. package/tests/handlers.test.ts +139 -10
  56. package/tests/index.test.ts +162 -0
  57. package/tests/region.test.ts +44 -0
  58. package/tests/required-apis.test.ts +55 -0
  59. package/tests/tasks.emulator.test.ts +131 -0
  60. package/tests/tasks.test.ts +229 -0
  61. package/tsconfig.tsbuildinfo +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firebase-function-kits/firestore-bigquery-export",
3
- "version": "0.0.2-rc.1",
3
+ "version": "0.0.2-rc.10",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/firebase/extensions.git",
@@ -31,15 +31,21 @@
31
31
  "serve": "firebase emulators:start --only functions"
32
32
  },
33
33
  "dependencies": {
34
- "@firebaseextensions/firestore-bigquery-change-tracker": "^2.0.4",
34
+ "@firebaseextensions/firestore-bigquery-change-tracker": "^2.2.1",
35
35
  "@google-cloud/bigquery": "^7.6.0",
36
- "firebase-admin": "^14.1.0",
37
- "firebase-functions": "7.3.2",
36
+ "firebase-admin": "^14.2.0",
37
+ "firebase-functions": "^7.3.3-rc.1",
38
38
  "generate-schema": "^2.6.0",
39
39
  "lodash": "^4.17.14"
40
40
  },
41
+ "overrides": {
42
+ "@firebaseextensions/firestore-bigquery-change-tracker": {
43
+ "firebase-functions": "$firebase-functions"
44
+ }
45
+ },
41
46
  "devDependencies": {
42
47
  "@types/lodash": "^4.17.0",
48
+ "typescript": "^5.9.3",
43
49
  "vitest": "^3.2.4"
44
50
  }
45
51
  }
package/src/config.ts CHANGED
@@ -20,9 +20,10 @@ import type {
20
20
  TimePartitioningGranularity,
21
21
  } from "@firebaseextensions/firestore-bigquery-change-tracker";
22
22
  import { LogLevel } from "@firebaseextensions/firestore-bigquery-change-tracker";
23
- import type { Expression } from "firebase-functions/params";
23
+ import type { Expression, IntParam } from "firebase-functions/params";
24
24
  import {
25
25
  defineBoolean,
26
+ defineInt,
26
27
  defineString,
27
28
  projectID,
28
29
  select,
@@ -78,53 +79,6 @@ const DATASET_LOCATION_OPTIONS = [
78
79
  "us-south1",
79
80
  "us-east5",
80
81
  ] as const;
81
- const DATABASE_REGION_OPTIONS = [
82
- "eur3",
83
- "nam5",
84
- "nam7",
85
- "us-central1",
86
- "us-west1",
87
- "us-west2",
88
- "us-west3",
89
- "us-west4",
90
- "us-east1",
91
- "us-east4",
92
- "us-east5",
93
- "us-south1",
94
- "northamerica-northeast1",
95
- "northamerica-northeast2",
96
- "northamerica-south1",
97
- "southamerica-east1",
98
- "southamerica-west1",
99
- "europe-west1",
100
- "europe-west2",
101
- "europe-west3",
102
- "europe-west4",
103
- "europe-west6",
104
- "europe-west8",
105
- "europe-west9",
106
- "europe-west10",
107
- "europe-west12",
108
- "europe-southwest1",
109
- "europe-north1",
110
- "europe-north2",
111
- "europe-central2",
112
- "me-central1",
113
- "me-central2",
114
- "me-west1",
115
- "asia-south1",
116
- "asia-south2",
117
- "asia-southeast1",
118
- "asia-southeast2",
119
- "asia-east1",
120
- "asia-east2",
121
- "asia-northeast1",
122
- "asia-northeast2",
123
- "asia-northeast3",
124
- "australia-southeast1",
125
- "australia-southeast2",
126
- "africa-south1",
127
- ] as const;
128
82
  const TABLE_PARTITIONING_OPTIONS = [
129
83
  "HOUR",
130
84
  "DAY",
@@ -148,8 +102,9 @@ export interface ConfigExpressions {
148
102
  collectionPath: ConfigExpression<string>;
149
103
  datasetId: ConfigExpression<string>;
150
104
  tableId: ConfigExpression<string>;
151
- location: ConfigExpression<string>;
152
105
  database: ConfigExpression<string>;
106
+ /** An `IntParam`, not a bare expression: the queue's `rateLimits` guards it with a CEL comparison. */
107
+ maxDispatchesPerSecond: IntParam;
153
108
  }
154
109
 
155
110
  /**
@@ -173,10 +128,13 @@ const params = {
173
128
  default: "(default)",
174
129
  input: { text: { example: "(default)" } },
175
130
  }),
131
+ // Declared so the CLI prompts for the value and persists it to `.env`; the
132
+ // function region option cannot be a param expression, so the entry point
133
+ // reads the same variable from `process.env` at module load instead.
176
134
  databaseRegion: defineString("DATABASE_REGION", {
177
135
  label: "Firestore Instance Location",
178
136
  description:
179
- "Where is the Firestore database located? You can check your current database location at https://console.cloud.google.com/firestore/databases.",
137
+ "Where is the Firestore database located? You can check your current database location at https://console.cloud.google.com/firestore/databases. The functions in this kit deploy to the Cloud Run region closest to this location.",
180
138
 
181
139
  input: select({
182
140
  "Multi-region (Europe - Belgium and Netherlands)": "eur3",
@@ -216,6 +174,7 @@ const params = {
216
174
  "Delhi (asia-south2)": "asia-south2",
217
175
  "Singapore (asia-southeast1)": "asia-southeast1",
218
176
  "Jakarta (asia-southeast2)": "asia-southeast2",
177
+ "Kuala Lumpur (asia-southeast3)": "asia-southeast3",
219
178
  "Taiwan (asia-east1)": "asia-east1",
220
179
  "Hong Kong (asia-east2)": "asia-east2",
221
180
  "Tokyo (asia-northeast1)": "asia-northeast1",
@@ -331,9 +290,39 @@ const params = {
331
290
  backupCollection: defineString("BACKUP_COLLECTION", {
332
291
  label: "Backup Collection Name",
333
292
  description:
334
- "This (optional) parameter will allow you to specify a collection for which failed BigQuery updates will be written to.",
293
+ "Strongly recommended. The Firestore collection where rows whose BigQuery insert is rejected are written, on the inline attempt and on each queue attempt; without it, those rows are dropped once the queue gives up. A change that cannot be enqueued at all is not backed up. See the README for how to reconcile backed-up rows into BigQuery.",
335
294
  default: "",
336
295
  }),
296
+ maxDispatchesPerSecond: defineInt("MAX_DISPATCHES_PER_SECOND", {
297
+ label: "Maximum number of synced documents per second",
298
+ description:
299
+ "This parameter will set the maximum number of synchronized documents per second with BQ. Please note, any other external updates to a Big Query table will be included within this quota. Ensure that you have set a low enough number to compensate. Defaults to 100.",
300
+
301
+ default: 100,
302
+ input: {
303
+ text: {
304
+ example: "100",
305
+
306
+ validationRegex: /^([1-9]|[1-9][0-9]|[1-4][0-9]{2}|500)$/,
307
+ validationErrorMessage: "Please select a number between 1 and 500",
308
+ },
309
+ },
310
+ }),
311
+ maxEnqueueAttempts: defineInt("MAX_ENQUEUE_ATTEMPTS", {
312
+ label: "Maximum number of enqueue attempts",
313
+ description:
314
+ "This parameter will set the maximum number of attempts to enqueue a document to cloud tasks for export to BigQuery.",
315
+
316
+ default: 3,
317
+ input: {
318
+ text: {
319
+ example: "3",
320
+
321
+ validationRegex: /^(10|[1-9])$/,
322
+ validationErrorMessage: "Please select an integer between 1 and 10",
323
+ },
324
+ },
325
+ }),
337
326
  transformFunction: defineString("TRANSFORM_FUNCTION", {
338
327
  label: "Transform function URL",
339
328
  description:
@@ -409,19 +398,21 @@ const params = {
409
398
 
410
399
  default: false,
411
400
  }),
412
- useNewSnapshotQuerySyntax: defineBoolean("USE_NEW_SNAPSHOT_QUERY_SYNTAX", {
401
+ useNewSnapshotQuerySyntax: defineString("USE_NEW_SNAPSHOT_QUERY_SYNTAX", {
413
402
  label: "Use new query syntax for snapshots",
414
403
  description:
415
404
  "If enabled, snapshots will be generated with the new query syntax, which should be more performant, and avoid potential resource limitations.",
416
405
 
417
- default: false,
406
+ default: "no",
407
+ input: select({ Yes: "yes", No: "no" }),
418
408
  }),
419
- excludeOldData: defineBoolean("EXCLUDE_OLD_DATA", {
409
+ excludeOldData: defineString("EXCLUDE_OLD_DATA", {
420
410
  label: "Exclude old data payloads",
421
411
  description:
422
412
  "If enabled, table rows will never contain old data (document snapshot before the Firestore onDocumentUpdate event: `change.before.data()`). The reduction in data should be more performant, and avoid potential resource limitations.",
423
413
 
424
- default: false,
414
+ default: "no",
415
+ input: select({ Yes: "yes", No: "no" }),
425
416
  }),
426
417
  viewType: defineString("VIEW_TYPE", {
427
418
  label: "View Type",
@@ -495,8 +486,8 @@ export const CONFIG_EXPRESSIONS: ConfigExpressions = {
495
486
  collectionPath: params.collectionPath,
496
487
  datasetId: params.datasetId,
497
488
  tableId: params.tableId,
498
- location: params.databaseRegion,
499
489
  database: params.database,
490
+ maxDispatchesPerSecond: params.maxDispatchesPerSecond,
500
491
  };
501
492
 
502
493
  function timePartitioning(
@@ -644,11 +635,30 @@ function normalizePositiveInt(value: string): number | undefined {
644
635
  return normalized > 0 ? normalized : undefined;
645
636
  }
646
637
 
638
+ // The extension's select emits `yes` / `no`; its label is `Yes`, and the CLI
639
+ // copies .env values verbatim, so case and whitespace are forgiven.
640
+ function yesNo(value: string): boolean {
641
+ return value.trim().toLowerCase() === "yes";
642
+ }
643
+
647
644
  /** Coerce an empty-string param value to `undefined`. */
648
645
  function optional(value: string): string | undefined {
649
646
  return value.length > 0 ? value : undefined;
650
647
  }
651
648
 
649
+ /**
650
+ * Reads an int param, reporting a missing or blank env var as `undefined`.
651
+ *
652
+ * `IntParam.value()` is `parseInt(env || "0", 10) || 0` and never consults the
653
+ * declared default, so an unset param has to reach `resolveExportConfig` as
654
+ * `undefined` for the documented default to apply. An explicit `0` is a real
655
+ * setting and is preserved.
656
+ */
657
+ function optionalInt(param: IntParam): number | undefined {
658
+ const raw = process.env[param.name]?.trim();
659
+ return raw === undefined || raw === "" ? undefined : param.value();
660
+ }
661
+
652
662
  /**
653
663
  * Resolves all deploy-time params into an {@link ExportConfig}.
654
664
  *
@@ -667,14 +677,13 @@ export function configFromEnv(): ExportConfig {
667
677
  collectionPath: params.collectionPath.value(),
668
678
  datasetId: params.datasetId.value(),
669
679
  tableId: params.tableId.value(),
670
- location: params.databaseRegion.value(),
671
680
  datasetLocation: optional(params.datasetLocation.value()),
672
681
  bqProjectId: optional(params.bigqueryProjectId.value()),
673
682
  projectId: projectID.value(),
674
683
  databaseId: optional(params.database.value()) || "(default)",
675
684
  wildcardIds: params.wildcardIds.value(),
676
- excludeOldData: params.excludeOldData.value(),
677
- useNewSnapshotQuerySyntax: params.useNewSnapshotQuerySyntax.value(),
685
+ excludeOldData: yesNo(params.excludeOldData.value()),
686
+ useNewSnapshotQuerySyntax: yesNo(params.useNewSnapshotQuerySyntax.value()),
678
687
  viewType: (optional(params.viewType.value()) || "view") as ViewType,
679
688
  partitioning: buildPartitioningConfig({
680
689
  timePartitioning: timePartitioning(tablePartitioning),
@@ -692,5 +701,7 @@ export function configFromEnv(): ExportConfig {
692
701
  transformFunction: optional(params.transformFunction.value()),
693
702
  kmsKeyName: optional(params.kmsKeyName.value()),
694
703
  logLevel: normalizeLogLevel(params.logLevel.value()),
704
+ maxDispatchesPerSecond: optionalInt(params.maxDispatchesPerSecond),
705
+ maxEnqueueAttempts: optionalInt(params.maxEnqueueAttempts),
695
706
  };
696
707
  }
@@ -19,6 +19,9 @@ import type {
19
19
  } from "@firebaseextensions/firestore-bigquery-change-tracker";
20
20
  import type { Expression } from "firebase-functions/params";
21
21
 
22
+ /** Dispatch rate of the `syncBigQuery` queue when `MAX_DISPATCHES_PER_SECOND` is unset. */
23
+ export const DEFAULT_MAX_DISPATCHES_PER_SECOND = 100;
24
+
22
25
  type TrackerLogLevel = "debug" | "info" | "warn" | "error" | "silent";
23
26
  type ConfigValue<T extends string | number | boolean | string[]> =
24
27
  | T
@@ -34,7 +37,7 @@ export type ViewType =
34
37
  * The export configuration. The main entry point builds it from deploy-time
35
38
  * params; handler consumers can construct it directly.
36
39
  *
37
- * `collectionPath`, `datasetId`, `tableId`, `location`, and `projectId` are
40
+ * `collectionPath`, `datasetId`, `tableId`, and `projectId` are
38
41
  * required; everything else has a sensible default.
39
42
  */
40
43
  export interface ExportConfig {
@@ -46,8 +49,6 @@ export interface ExportConfig {
46
49
  /** BigQuery changelog table id. */
47
50
  tableId: ConfigValue<string>;
48
51
 
49
- /** Region for the trigger and task queue. */
50
- location: ConfigValue<string>;
51
52
  /** BigQuery dataset location, e.g. `us`, `eu`. Defaults to `us`. */
52
53
  datasetLocation?: ConfigValue<string>;
53
54
  /** Project that owns the BigQuery dataset, if different from the function's
@@ -71,7 +72,10 @@ export interface ExportConfig {
71
72
  partitioning?: ChangeTrackerConfig["partitioning"];
72
73
  /** Clustering columns (max 4). */
73
74
  clustering?: string[] | null;
74
- /** Materialized-view max staleness interval, e.g. `0-0 0 4:0:0`. */
75
+ /**
76
+ * Materialized-view max staleness interval, e.g.
77
+ * `INTERVAL "8:0:0" HOUR TO SECOND`.
78
+ */
75
79
  maxStaleness?: ConfigValue<string>;
76
80
  /** Incremental materialized-view refresh interval in minutes. */
77
81
  refreshIntervalMinutes?: ConfigValue<number>;
@@ -85,6 +89,17 @@ export interface ExportConfig {
85
89
 
86
90
  /** Log verbosity. Defaults to `info`. */
87
91
  logLevel?: ConfigValue<TrackerLogLevel | LogLevel>;
92
+
93
+ /**
94
+ * Cloud Tasks dispatch rate for the `syncBigQuery` queue, in tasks per
95
+ * second. Defaults to `100`.
96
+ */
97
+ maxDispatchesPerSecond?: ConfigValue<number>;
98
+ /**
99
+ * How many times the trigger tries to enqueue a failed write onto the
100
+ * `syncBigQuery` queue before giving up. Defaults to `3`.
101
+ */
102
+ maxEnqueueAttempts?: ConfigValue<number>;
88
103
  }
89
104
 
90
105
  /** {@link ExportConfig} with all defaults applied. */
@@ -92,7 +107,6 @@ export interface ResolvedExportConfig {
92
107
  collectionPath: string;
93
108
  datasetId: string;
94
109
  tableId: string;
95
- location: string;
96
110
  datasetLocation: string;
97
111
  bqProjectId?: string;
98
112
  projectId: string;
@@ -109,6 +123,8 @@ export interface ResolvedExportConfig {
109
123
  transformFunction?: string;
110
124
  kmsKeyName?: string;
111
125
  logLevel: TrackerLogLevel;
126
+ maxDispatchesPerSecond: number;
127
+ maxEnqueueAttempts: number;
112
128
  }
113
129
 
114
130
  function isExpression<T extends string | number | boolean | string[]>(
@@ -146,7 +162,6 @@ export function resolveExportConfig(
146
162
  collectionPath: resolveConfigValue(config.collectionPath),
147
163
  datasetId: resolveConfigValue(config.datasetId),
148
164
  tableId: resolveConfigValue(config.tableId),
149
- location: resolveConfigValue(config.location),
150
165
  datasetLocation: resolveOptionalConfigValue(config.datasetLocation) ?? "us",
151
166
  bqProjectId: resolveOptionalConfigValue(config.bqProjectId),
152
167
  projectId,
@@ -166,6 +181,11 @@ export function resolveExportConfig(
166
181
  transformFunction: resolveOptionalConfigValue(config.transformFunction),
167
182
  kmsKeyName: resolveOptionalConfigValue(config.kmsKeyName),
168
183
  logLevel: (logLevel as TrackerLogLevel) ?? "info",
184
+ maxDispatchesPerSecond:
185
+ resolveOptionalConfigValue(config.maxDispatchesPerSecond) ??
186
+ DEFAULT_MAX_DISPATCHES_PER_SECOND,
187
+ maxEnqueueAttempts:
188
+ resolveOptionalConfigValue(config.maxEnqueueAttempts) ?? 3,
169
189
  };
170
190
  }
171
191
 
package/src/handlers.ts CHANGED
@@ -24,13 +24,18 @@ import type {
24
24
  DocumentSnapshot,
25
25
  FirestoreEvent,
26
26
  } from "firebase-functions/firestore";
27
+ import type { Request } from "firebase-functions/tasks";
27
28
  import * as events from "./events";
28
29
  import type { ResolvedExportConfig } from "./export-config";
29
30
  import * as logs from "./logs";
30
31
  import { getChangeType, getDocumentId } from "./util";
31
32
 
32
- /** Serialized Firestore change ready to write to BigQuery. */
33
- interface SerializedDocumentChange {
33
+ /**
34
+ * Serialized Firestore change ready to write to BigQuery. Also the
35
+ * `syncBigQuery` task payload: it is built from already-serialized data, so it
36
+ * survives the JSON round trip through Cloud Tasks unchanged.
37
+ */
38
+ export interface SerializedDocumentChange {
34
39
  timestamp: string;
35
40
  eventId: string;
36
41
  fullResourceName: string;
@@ -55,11 +60,15 @@ export interface HandlerContext {
55
60
  tracker: FirestoreBigQueryEventHistoryTracker;
56
61
  config: ResolvedExportConfig;
57
62
  /**
58
- * Provisions the BigQuery dataset/table/views once per instance. Only called
59
- * after an inline write failure as a self-heal; the hot path relies on
60
- * out-of-band provisioning (`initBigQuerySync` / `setupBigQuerySync`).
63
+ * Provisions the BigQuery resources. Used by the lifecycle tasks only; the
64
+ * write paths never call it.
61
65
  */
62
66
  ensureInitialized: () => Promise<void>;
67
+ /**
68
+ * Enqueues a failed change onto the `syncBigQuery` task queue. Rejects with
69
+ * the enqueue error once its own retry budget is exhausted.
70
+ */
71
+ enqueue: (change: SerializedDocumentChange) => Promise<void>;
63
72
  }
64
73
 
65
74
  /**
@@ -87,38 +96,38 @@ async function recordEventToBigQuery(
87
96
  }
88
97
 
89
98
  /**
90
- * Gives a failed inline write one self-heal attempt before surfacing it to the
91
- * Firestore trigger retry policy.
99
+ * Buffers a failed inline write through the `syncBigQuery` task queue. A
100
+ * terminal enqueue failure is logged and published as an `onError` event, then
101
+ * dropped, exactly as the extension did: with no retry policy on the trigger a
102
+ * rethrow would only fail the execution once and drop it anyway.
92
103
  *
93
- * @param change - The serialized change to write.
104
+ * @param change - The serialized change to enqueue.
94
105
  * @param ctx - The handler context.
95
106
  */
96
- async function retryAfterSelfHeal(
107
+ async function enqueueForSync(
97
108
  change: SerializedDocumentChange,
98
109
  ctx: HandlerContext
99
110
  ): Promise<void> {
100
111
  try {
101
- await ctx.ensureInitialized();
102
- await recordEventToBigQuery(change, ctx.tracker);
103
- } catch (retryErr) {
104
- await events.recordErrorEvent(retryErr as Error);
105
-
112
+ await ctx.enqueue(change);
113
+ } catch (enqueueErr) {
114
+ // Log before publishing: the log line is the only trace of the dropped
115
+ // row, and the event publish can itself reject.
106
116
  logs.logFailedEventAction(
107
- "Failed to write event to BigQuery from onWrite handler after self-heal",
117
+ "Failed to enqueue event to Cloud Tasks from onWrite handler",
108
118
  change.fullResourceName,
109
119
  change.eventId,
110
120
  change.changeType,
111
- retryErr as Error
121
+ enqueueErr as Error
112
122
  );
113
-
114
- throw retryErr;
123
+ await events.recordErrorEvent(enqueueErr as Error);
115
124
  }
116
125
  }
117
126
 
118
127
  /**
119
128
  * Handles a Firestore document write: serializes the change and writes it to
120
- * BigQuery. Failed writes are surfaced to the trigger retry policy after one
121
- * self-heal attempt.
129
+ * BigQuery. A failed inline write is buffered through the `syncBigQuery` task
130
+ * queue; a failed enqueue is logged and dropped.
122
131
  *
123
132
  * @param event - The Firestore document-write event.
124
133
  * @param ctx - The handler context.
@@ -130,12 +139,10 @@ export async function handleDocumentWrite(
130
139
  const { data, ...context } = event;
131
140
  if (!data) return;
132
141
 
133
- logs.start();
134
-
135
- // No provisioning on the hot path: BigQuery resources are provisioned
136
- // out-of-band (afterFirstDeploy / afterRedeploy tasks). If they are missing,
137
- // the inline write fails, self-heals once, then falls back to the trigger
138
- // retry policy.
142
+ logs.start(); // No provisioning on the hot path, and none on the queue path either: only
143
+ // the lifecycle tasks create BigQuery resources. A missing dataset or table
144
+ // fails the inline write and every queue attempt the same way until a
145
+ // redeploy runs the lifecycle task; BACKUP_COLLECTION is the only net.
139
146
  const { config, tracker } = ctx;
140
147
  const changeType = getChangeType(data);
141
148
  const documentId = getDocumentId(data);
@@ -204,7 +211,69 @@ export async function handleDocumentWrite(
204
211
  await recordEventToBigQuery(change, tracker);
205
212
  } catch (err) {
206
213
  logs.failedToWriteToBigQueryImmediately(err as Error);
207
- await retryAfterSelfHeal(change, ctx);
214
+ await enqueueForSync(change, ctx);
215
+ }
216
+
217
+ logs.complete();
218
+ }
219
+
220
+ /**
221
+ * Handles a `syncBigQuery` task: re-attempts a buffered write. No provisioning
222
+ * runs here, as in the extension: that stays in the lifecycle tasks, so a
223
+ * recovery burst does not fan `initialize()` out across every cold instance.
224
+ * A failed write rethrows so Cloud Tasks retries on the queue's schedule; the
225
+ * tracker parks the row in the backup collection before each terminal
226
+ * rethrow.
227
+ *
228
+ * @param req - The dispatched task request carrying the serialized change.
229
+ * @param ctx - The handler context.
230
+ */
231
+ export async function handleSyncBigQueryTask(
232
+ req: Request<SerializedDocumentChange>,
233
+ ctx: HandlerContext
234
+ ): Promise<void> {
235
+ const change = req.data;
236
+
237
+ logs.logEventAction(
238
+ "Firestore event received by onDispatch trigger",
239
+ change.fullResourceName,
240
+ change.eventId,
241
+ change.changeType
242
+ );
243
+
244
+ try {
245
+ await recordEventToBigQuery(change, ctx.tracker);
246
+ } catch (err) {
247
+ logs.logFailedEventAction(
248
+ "Failed to write event to BigQuery from onDispatch handler",
249
+ change.fullResourceName,
250
+ change.eventId,
251
+ change.changeType,
252
+ err as Error,
253
+ req.retryCount
254
+ );
255
+
256
+ throw err;
257
+ }
258
+
259
+ try {
260
+ await events.recordSuccessEvent({
261
+ subject: change.documentId,
262
+ data: {
263
+ timestamp: change.timestamp,
264
+ operation: change.changeType,
265
+ documentName: change.fullResourceName,
266
+ documentId: change.documentId,
267
+ pathParams: change.params,
268
+ eventId: change.eventId,
269
+ data: change.data,
270
+ oldData: change.oldData,
271
+ },
272
+ });
273
+ } catch (err) {
274
+ // The row is already in BigQuery. Rethrowing would have Cloud Tasks retry
275
+ // the insert past the dedupe window and duplicate it.
276
+ logs.error(false, "Failed to record success event", err as Error);
208
277
  }
209
278
 
210
279
  logs.complete();