@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.6 → 0.0.2-rc.7

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 (50) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/README.md +163 -45
  3. package/lib/config.d.ts +3 -1
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +53 -7
  6. package/lib/config.js.map +1 -1
  7. package/lib/export-config.d.ts +14 -0
  8. package/lib/export-config.d.ts.map +1 -1
  9. package/lib/export-config.js +6 -0
  10. package/lib/export-config.js.map +1 -1
  11. package/lib/handlers.d.ts +38 -6
  12. package/lib/handlers.d.ts.map +1 -1
  13. package/lib/handlers.js +63 -18
  14. package/lib/handlers.js.map +1 -1
  15. package/lib/index.d.ts +13 -2
  16. package/lib/index.d.ts.map +1 -1
  17. package/lib/index.js +38 -6
  18. package/lib/index.js.map +1 -1
  19. package/lib/init.d.ts +1 -1
  20. package/lib/init.js +1 -1
  21. package/lib/lib.d.ts +1 -1
  22. package/lib/lib.d.ts.map +1 -1
  23. package/lib/lib.js +2 -1
  24. package/lib/lib.js.map +1 -1
  25. package/lib/logs.d.ts +1 -1
  26. package/lib/logs.d.ts.map +1 -1
  27. package/lib/logs.js +2 -1
  28. package/lib/logs.js.map +1 -1
  29. package/lib/tasks.d.ts +40 -0
  30. package/lib/tasks.d.ts.map +1 -0
  31. package/lib/tasks.js +107 -0
  32. package/lib/tasks.js.map +1 -0
  33. package/npm-shrinkwrap.json +593 -2069
  34. package/package.json +7 -7
  35. package/src/config.ts +65 -8
  36. package/src/export-config.ts +21 -0
  37. package/src/handlers.ts +96 -27
  38. package/src/index.ts +56 -7
  39. package/src/init.ts +1 -1
  40. package/src/lib.ts +2 -0
  41. package/src/logs.ts +3 -1
  42. package/src/tasks.ts +126 -0
  43. package/tests/config.test.ts +98 -10
  44. package/tests/export-config.test.ts +10 -0
  45. package/tests/handlers.test.ts +139 -10
  46. package/tests/index.test.ts +38 -2
  47. package/tests/required-apis.test.ts +55 -0
  48. package/tests/tasks.emulator.test.ts +131 -0
  49. package/tests/tasks.test.ts +229 -0
  50. 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.6",
3
+ "version": "0.0.2-rc.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/firebase/extensions.git",
@@ -31,16 +31,16 @@
31
31
  "serve": "firebase emulators:start --only functions"
32
32
  },
33
33
  "dependencies": {
34
- "@firebaseextensions/firestore-bigquery-change-tracker": "^2.1.0",
34
+ "@firebaseextensions/firestore-bigquery-change-tracker": "^2.2.1",
35
35
  "@google-cloud/bigquery": "^7.6.0",
36
- "firebase-admin": "^13.6.0",
36
+ "firebase-admin": "^14.2.0",
37
37
  "firebase-functions": "^7.3.3-rc.0",
38
38
  "generate-schema": "^2.6.0",
39
39
  "lodash": "^4.17.14"
40
40
  },
41
- "devDependencies": {
42
- "@types/lodash": "^4.17.0",
43
- "typescript": "^5.9.3",
44
- "vitest": "^3.2.4"
41
+ "overrides": {
42
+ "@firebaseextensions/firestore-bigquery-change-tracker": {
43
+ "firebase-functions": "$firebase-functions"
44
+ }
45
45
  }
46
46
  }
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,
@@ -102,6 +103,8 @@ export interface ConfigExpressions {
102
103
  datasetId: ConfigExpression<string>;
103
104
  tableId: ConfigExpression<string>;
104
105
  database: ConfigExpression<string>;
106
+ /** An `IntParam`, not a bare expression: the queue's `rateLimits` guards it with a CEL comparison. */
107
+ maxDispatchesPerSecond: IntParam;
105
108
  }
106
109
 
107
110
  /**
@@ -287,9 +290,39 @@ const params = {
287
290
  backupCollection: defineString("BACKUP_COLLECTION", {
288
291
  label: "Backup Collection Name",
289
292
  description:
290
- "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.",
291
294
  default: "",
292
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
+ }),
293
326
  transformFunction: defineString("TRANSFORM_FUNCTION", {
294
327
  label: "Transform function URL",
295
328
  description:
@@ -365,19 +398,21 @@ const params = {
365
398
 
366
399
  default: false,
367
400
  }),
368
- useNewSnapshotQuerySyntax: defineBoolean("USE_NEW_SNAPSHOT_QUERY_SYNTAX", {
401
+ useNewSnapshotQuerySyntax: defineString("USE_NEW_SNAPSHOT_QUERY_SYNTAX", {
369
402
  label: "Use new query syntax for snapshots",
370
403
  description:
371
404
  "If enabled, snapshots will be generated with the new query syntax, which should be more performant, and avoid potential resource limitations.",
372
405
 
373
- default: false,
406
+ default: "no",
407
+ input: select({ Yes: "yes", No: "no" }),
374
408
  }),
375
- excludeOldData: defineBoolean("EXCLUDE_OLD_DATA", {
409
+ excludeOldData: defineString("EXCLUDE_OLD_DATA", {
376
410
  label: "Exclude old data payloads",
377
411
  description:
378
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.",
379
413
 
380
- default: false,
414
+ default: "no",
415
+ input: select({ Yes: "yes", No: "no" }),
381
416
  }),
382
417
  viewType: defineString("VIEW_TYPE", {
383
418
  label: "View Type",
@@ -452,6 +487,7 @@ export const CONFIG_EXPRESSIONS: ConfigExpressions = {
452
487
  datasetId: params.datasetId,
453
488
  tableId: params.tableId,
454
489
  database: params.database,
490
+ maxDispatchesPerSecond: params.maxDispatchesPerSecond,
455
491
  };
456
492
 
457
493
  function timePartitioning(
@@ -599,11 +635,30 @@ function normalizePositiveInt(value: string): number | undefined {
599
635
  return normalized > 0 ? normalized : undefined;
600
636
  }
601
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
+
602
644
  /** Coerce an empty-string param value to `undefined`. */
603
645
  function optional(value: string): string | undefined {
604
646
  return value.length > 0 ? value : undefined;
605
647
  }
606
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
+
607
662
  /**
608
663
  * Resolves all deploy-time params into an {@link ExportConfig}.
609
664
  *
@@ -627,8 +682,8 @@ export function configFromEnv(): ExportConfig {
627
682
  projectId: projectID.value(),
628
683
  databaseId: optional(params.database.value()) || "(default)",
629
684
  wildcardIds: params.wildcardIds.value(),
630
- excludeOldData: params.excludeOldData.value(),
631
- useNewSnapshotQuerySyntax: params.useNewSnapshotQuerySyntax.value(),
685
+ excludeOldData: yesNo(params.excludeOldData.value()),
686
+ useNewSnapshotQuerySyntax: yesNo(params.useNewSnapshotQuerySyntax.value()),
632
687
  viewType: (optional(params.viewType.value()) || "view") as ViewType,
633
688
  partitioning: buildPartitioningConfig({
634
689
  timePartitioning: timePartitioning(tablePartitioning),
@@ -646,5 +701,7 @@ export function configFromEnv(): ExportConfig {
646
701
  transformFunction: optional(params.transformFunction.value()),
647
702
  kmsKeyName: optional(params.kmsKeyName.value()),
648
703
  logLevel: normalizeLogLevel(params.logLevel.value()),
704
+ maxDispatchesPerSecond: optionalInt(params.maxDispatchesPerSecond),
705
+ maxEnqueueAttempts: optionalInt(params.maxEnqueueAttempts),
649
706
  };
650
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
@@ -86,6 +89,17 @@ export interface ExportConfig {
86
89
 
87
90
  /** Log verbosity. Defaults to `info`. */
88
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>;
89
103
  }
90
104
 
91
105
  /** {@link ExportConfig} with all defaults applied. */
@@ -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[]>(
@@ -165,6 +181,11 @@ export function resolveExportConfig(
165
181
  transformFunction: resolveOptionalConfigValue(config.transformFunction),
166
182
  kmsKeyName: resolveOptionalConfigValue(config.kmsKeyName),
167
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,
168
189
  };
169
190
  }
170
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();
package/src/index.ts CHANGED
@@ -17,8 +17,8 @@
17
17
  /**
18
18
  * Main entry point. Exports the wired functions with deploy-time param
19
19
  * expressions, then resolves concrete config lazily at runtime. Re-export
20
- * `fsexportbigquery` and `initBigQuerySync` from your own functions codebase
21
- * entry; configuration comes from a `.env` (or
20
+ * `fsexportbigquery`, `syncBigQuery`, and `initBigQuerySync` from your own
21
+ * functions codebase entry; configuration comes from a `.env` (or
22
22
  * `.env.<projectId>`), which the Firebase CLI loads at deploy.
23
23
  *
24
24
  * Because this module initializes runtime dependencies lazily, deploy discovery
@@ -40,11 +40,21 @@ import {
40
40
  } from "firebase-functions/v2/lifecycle";
41
41
  import { CONFIG_EXPRESSIONS, configFromEnv } from "./config";
42
42
  import * as events from "./events";
43
- import { resolveExportConfig, toTrackerConfig } from "./export-config";
44
- import { type HandlerContext, handleDocumentWrite } from "./handlers";
43
+ import {
44
+ DEFAULT_MAX_DISPATCHES_PER_SECOND,
45
+ resolveExportConfig,
46
+ toTrackerConfig,
47
+ } from "./export-config";
48
+ import {
49
+ type HandlerContext,
50
+ type SerializedDocumentChange,
51
+ handleDocumentWrite,
52
+ handleSyncBigQueryTask,
53
+ } from "./handlers";
45
54
  import { createEnsureInitialized } from "./init";
46
55
  import * as logs from "./logs";
47
56
  import { firestoreLocationToFunctionRegion } from "./region";
57
+ import { enqueueSyncTask } from "./tasks";
48
58
 
49
59
  // Re-export the side-effect-free library surface (handlers and config types).
50
60
  export * from "./lib";
@@ -55,6 +65,11 @@ const LIFECYCLE_RETRY_CONFIG = {
55
65
  maxAttempts: 15,
56
66
  minBackoffSeconds: 60,
57
67
  } as const;
68
+ const SYNC_RETRY_CONFIG = {
69
+ maxAttempts: 5,
70
+ minBackoffSeconds: 60,
71
+ } as const;
72
+ const SYNC_MAX_CONCURRENT_DISPATCHES = 500;
58
73
  const REQUIRED_ROLES: ReadonlyArray<Role> = [
59
74
  "roles/bigquery.dataEditor",
60
75
  "roles/datastore.user",
@@ -62,8 +77,14 @@ const REQUIRED_ROLES: ReadonlyArray<Role> = [
62
77
  // Gen2 Firestore triggers need Eventarc receive and run.invoker on the function SA.
63
78
  "roles/eventarc.eventReceiver",
64
79
  "roles/run.invoker",
80
+ // The trigger enqueues failed writes onto its own syncBigQuery task queue.
81
+ "roles/cloudtasks.enqueuer",
65
82
  ];
66
83
  const REQUIRED_APIS = [
84
+ {
85
+ api: "firestore.googleapis.com",
86
+ reason: "Receives document change events from Cloud Firestore.",
87
+ },
67
88
  {
68
89
  api: "bigquery.googleapis.com",
69
90
  reason: "Mirrors data from your Cloud Firestore collection in BigQuery.",
@@ -112,6 +133,8 @@ function getHandlerContext(): HandlerContext {
112
133
  tracker,
113
134
  config,
114
135
  ensureInitialized,
136
+ enqueue: (change: SerializedDocumentChange) =>
137
+ enqueueSyncTask(change, config.maxEnqueueAttempts),
115
138
  };
116
139
 
117
140
  return ctx;
@@ -131,19 +154,45 @@ const functionRegion = firestoreLocationToFunctionRegion(
131
154
 
132
155
  /**
133
156
  * Firestore trigger: streams document writes on the watched collection into the
134
- * BigQuery changelog table. Failed executions are retried by the Firebase
135
- * Functions runtime.
157
+ * BigQuery changelog table. A failed inline write buffers through the
158
+ * `syncBigQuery` queue and the execution still succeeds. No runtime retry
159
+ * policy, as in the extension: a failure before the write is attempted fails
160
+ * the execution once, and a failed enqueue is logged and dropped.
136
161
  */
137
162
  export const fsexportbigquery = onDocumentWritten(
138
163
  {
139
164
  ...(functionRegion ? { region: functionRegion } : {}),
140
165
  document: expr`${CONFIG_EXPRESSIONS.collectionPath}/{documentId}`,
141
166
  database: CONFIG_EXPRESSIONS.database,
142
- retry: true,
143
167
  },
144
168
  (event) => handleDocumentWrite(event, getHandlerContext())
145
169
  );
146
170
 
171
+ /**
172
+ * Write-buffer task queue: re-attempts writes that failed inline, on Cloud
173
+ * Tasks' schedule (5 attempts, 60s minimum backoff, dispatch-throttled by
174
+ * `MAX_DISPATCHES_PER_SECOND`). After the last attempt the task is dropped;
175
+ * by then the tracker has written the row to `BACKUP_COLLECTION` on every
176
+ * terminal insert failure, when that collection is configured.
177
+ */
178
+ export const syncBigQuery = onTaskDispatched<SerializedDocumentChange>(
179
+ {
180
+ ...(functionRegion ? { region: functionRegion } : {}),
181
+ retryConfig: SYNC_RETRY_CONFIG,
182
+ rateLimits: {
183
+ maxConcurrentDispatches: SYNC_MAX_CONCURRENT_DISPATCHES, // A blank .env value reaches this deploy-time expression as 0, which
184
+ // Cloud Tasks would not accept; runtime falls back to the same default.
185
+ maxDispatchesPerSecond: CONFIG_EXPRESSIONS.maxDispatchesPerSecond
186
+ .lessThan(1)
187
+ .thenElse(
188
+ DEFAULT_MAX_DISPATCHES_PER_SECOND,
189
+ CONFIG_EXPRESSIONS.maxDispatchesPerSecond
190
+ ),
191
+ },
192
+ },
193
+ (req) => handleSyncBigQueryTask(req, getHandlerContext())
194
+ );
195
+
147
196
  async function handleBigQuerySyncInitialization(): Promise<void> {
148
197
  try {
149
198
  await getHandlerContext().ensureInitialized();
package/src/init.ts CHANGED
@@ -18,7 +18,7 @@ import type { FirestoreBigQueryEventHistoryTracker } from "@firebaseextensions/f
18
18
 
19
19
  /**
20
20
  * Builds the provisioning guard used by the `initBigQuerySync` endpoint and the
21
- * retry-path self-heal. The hot write path never calls it.
21
+ * lifecycle tasks. The write paths never call it.
22
22
  *
23
23
  * The returned function runs `tracker.initialize()` at most once per instance:
24
24
  * concurrent invocations on a cold instance share a single in-flight promise. A
package/src/lib.ts CHANGED
@@ -51,5 +51,7 @@ export {
51
51
  export {
52
52
  type DocumentWriteEvent,
53
53
  type HandlerContext,
54
+ type SerializedDocumentChange,
54
55
  handleDocumentWrite,
56
+ handleSyncBigQueryTask,
55
57
  } from "./handlers";
package/src/logs.ts CHANGED
@@ -208,7 +208,8 @@ export const logFailedEventAction = (
208
208
  document_name: string,
209
209
  event_id: string,
210
210
  operation: ChangeType,
211
- error: Error
211
+ error: Error,
212
+ retry_count?: number
212
213
  ) => {
213
214
  const changeTypeMap = {
214
215
  0: "CREATE",
@@ -222,6 +223,7 @@ export const logFailedEventAction = (
222
223
  event_id,
223
224
  operation: changeTypeMap[operation],
224
225
  error,
226
+ ...(retry_count === undefined ? {} : { retry_count }),
225
227
  });
226
228
  };
227
229