@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.0 → 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 +5 -1
  2. package/README.md +281 -60
  3. package/lib/config.d.ts +3 -2
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +295 -70
  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 +6396 -0
  43. package/package.json +15 -5
  44. package/src/config.ts +359 -72
  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/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,10 +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";
56
+ import { firestoreLocationToFunctionRegion } from "./region";
57
+ import { enqueueSyncTask } from "./tasks";
47
58
 
48
59
  // Re-export the side-effect-free library surface (handlers and config types).
49
60
  export * from "./lib";
@@ -54,6 +65,11 @@ const LIFECYCLE_RETRY_CONFIG = {
54
65
  maxAttempts: 15,
55
66
  minBackoffSeconds: 60,
56
67
  } as const;
68
+ const SYNC_RETRY_CONFIG = {
69
+ maxAttempts: 5,
70
+ minBackoffSeconds: 60,
71
+ } as const;
72
+ const SYNC_MAX_CONCURRENT_DISPATCHES = 500;
57
73
  const REQUIRED_ROLES: ReadonlyArray<Role> = [
58
74
  "roles/bigquery.dataEditor",
59
75
  "roles/datastore.user",
@@ -61,8 +77,14 @@ const REQUIRED_ROLES: ReadonlyArray<Role> = [
61
77
  // Gen2 Firestore triggers need Eventarc receive and run.invoker on the function SA.
62
78
  "roles/eventarc.eventReceiver",
63
79
  "roles/run.invoker",
80
+ // The trigger enqueues failed writes onto its own syncBigQuery task queue.
81
+ "roles/cloudtasks.enqueuer",
64
82
  ];
65
83
  const REQUIRED_APIS = [
84
+ {
85
+ api: "firestore.googleapis.com",
86
+ reason: "Receives document change events from Cloud Firestore.",
87
+ },
66
88
  {
67
89
  api: "bigquery.googleapis.com",
68
90
  reason: "Mirrors data from your Cloud Firestore collection in BigQuery.",
@@ -111,30 +133,66 @@ function getHandlerContext(): HandlerContext {
111
133
  tracker,
112
134
  config,
113
135
  ensureInitialized,
136
+ enqueue: (change: SerializedDocumentChange) =>
137
+ enqueueSyncTask(change, config.maxEnqueueAttempts),
114
138
  };
115
139
 
116
140
  return ctx;
117
141
  }
118
142
 
119
- const functionOptions = {
120
- region: CONFIG_EXPRESSIONS.location,
121
- };
143
+ /*
144
+ * Read at module load: the CLI populates `.env` values into the discovery
145
+ * process env (firebase-tools >= 15.28.0), and the region option cannot be a
146
+ * param expression. When unset, no function declares a region and the CLI
147
+ * falls back to its default. The Eventarc trigger region needs no handling:
148
+ * the CLI pins it to the database's own region regardless of where the
149
+ * function runs.
150
+ */
151
+ const functionRegion = firestoreLocationToFunctionRegion(
152
+ process.env.DATABASE_REGION
153
+ );
122
154
 
123
155
  /**
124
156
  * Firestore trigger: streams document writes on the watched collection into the
125
- * BigQuery changelog table. Failed executions are retried by the Firebase
126
- * 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.
127
161
  */
128
162
  export const fsexportbigquery = onDocumentWritten(
129
163
  {
130
- ...functionOptions,
164
+ ...(functionRegion ? { region: functionRegion } : {}),
131
165
  document: expr`${CONFIG_EXPRESSIONS.collectionPath}/{documentId}`,
132
166
  database: CONFIG_EXPRESSIONS.database,
133
- retry: true,
134
167
  },
135
168
  (event) => handleDocumentWrite(event, getHandlerContext())
136
169
  );
137
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
+
138
196
  async function handleBigQuerySyncInitialization(): Promise<void> {
139
197
  try {
140
198
  await getHandlerContext().ensureInitialized();
@@ -155,7 +213,7 @@ async function handleBigQuerySyncInitialization(): Promise<void> {
155
213
  */
156
214
  export const initBigQuerySync = onTaskDispatched(
157
215
  {
158
- ...functionOptions,
216
+ ...(functionRegion ? { region: functionRegion } : {}),
159
217
  retryConfig: LIFECYCLE_RETRY_CONFIG,
160
218
  },
161
219
  handleBigQuerySyncInitialization
@@ -167,7 +225,7 @@ export const initBigQuerySync = onTaskDispatched(
167
225
  */
168
226
  export const setupBigQuerySync = onTaskDispatched(
169
227
  {
170
- ...functionOptions,
228
+ ...(functionRegion ? { region: functionRegion } : {}),
171
229
  retryConfig: LIFECYCLE_RETRY_CONFIG,
172
230
  },
173
231
  handleBigQuerySyncInitialization
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
@@ -180,8 +180,8 @@ export const init = (config?: unknown) => {
180
180
  logger.info("Initializing with configuration", config);
181
181
  };
182
182
 
183
- export const start = (config?: unknown) => {
184
- logger.info("Started execution with configuration", config);
183
+ export const start = () => {
184
+ logger.info("Started execution of extension");
185
185
  };
186
186
 
187
187
  export const timestampMissingValue = (fieldName: string) => {
@@ -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
 
package/src/region.ts ADDED
@@ -0,0 +1,37 @@
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // Firestore multi-region locations are not Cloud Run regions; deploying a
18
+ // function to one hard-fails, so they map to a region inside the multi-region.
19
+ const MULTI_REGION_TO_FUNCTION_REGION: Record<string, string> = {
20
+ nam5: "us-central1",
21
+ nam7: "us-central1",
22
+ eur3: "europe-west1",
23
+ };
24
+
25
+ /**
26
+ * Maps a Firestore database location to the Cloud Run region the functions
27
+ * should deploy to. Regional locations pass through unchanged; an unset or
28
+ * empty location returns `undefined`, meaning the functions declare no region.
29
+ */
30
+ export function firestoreLocationToFunctionRegion(
31
+ location: string | undefined
32
+ ): string | undefined {
33
+ if (!location) {
34
+ return undefined;
35
+ }
36
+ return MULTI_REGION_TO_FUNCTION_REGION[location] ?? location;
37
+ }
package/src/tasks.ts ADDED
@@ -0,0 +1,126 @@
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { createHash } from "node:crypto";
18
+ import { getFunctions } from "firebase-admin/functions";
19
+ import type { SerializedDocumentChange } from "./handlers";
20
+ import { firestoreLocationToFunctionRegion } from "./region";
21
+
22
+ /** Export name of the write-buffer task function. */
23
+ export const SYNC_BIGQUERY_FUNCTION = "syncBigQuery";
24
+
25
+ const MAX_BACKOFF_MS = 5000;
26
+ const BACKOFF_BASE_MS = 100;
27
+ const JITTER_MS = 100;
28
+
29
+ // Hashed rather than sanitized: a lossy mapping could collapse two event ids
30
+ // into one task id, and Cloud Tasks wants ids uniformly distributed.
31
+ function taskIdFor(change: SerializedDocumentChange): string {
32
+ return createHash("sha256").update(change.eventId).digest("hex");
33
+ }
34
+
35
+ /**
36
+ * Resolves the queue resource path for a task function of this kit instance.
37
+ *
38
+ * The name is deliberately unprefixed: firebase-admin >= 14.2.0 resolves the
39
+ * deployed `kit-<instance id>-` prefix itself from the
40
+ * `FIREBASE_KIT_INSTANCE_ID` env var, which the CLI sets on every deployed kit
41
+ * function. All functions of a kit instance deploy to one region, so the
42
+ * enqueuing function's own region is the queue's region.
43
+ *
44
+ * The CLI-set `FUNCTION_REGION` wins because it is the region the function
45
+ * was actually deployed to; a `DATABASE_REGION`-derived region can disagree
46
+ * with it on a first deploy or when the variable is unset, and is only the
47
+ * fallback for local runs where the CLI has not populated the environment.
48
+ * With neither set, the bare function name is returned and the Admin SDK
49
+ * applies its default location, `us-central1`, which is also where the CLI
50
+ * places functions that declare no region.
51
+ *
52
+ * @param functionName - The export name of the task function.
53
+ * @returns The queue resource path, `locations/<region>/functions/<name>`,
54
+ * or the bare `<name>` when no region is known.
55
+ */
56
+ export function syncQueuePath(
57
+ functionName: string = SYNC_BIGQUERY_FUNCTION
58
+ ): string {
59
+ const region =
60
+ process.env.FUNCTION_REGION ||
61
+ firestoreLocationToFunctionRegion(process.env.DATABASE_REGION);
62
+
63
+ return region
64
+ ? `locations/${region}/functions/${functionName}`
65
+ : functionName;
66
+ }
67
+
68
+ function backoffMs(attempt: number, jitter: number): number {
69
+ return (
70
+ Math.min(Math.pow(2, attempt) * BACKOFF_BASE_MS, MAX_BACKOFF_MS) + jitter
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Enqueues a payload onto the `syncBigQuery` queue, retrying transient enqueue
76
+ * failures in-process with exponential backoff and jitter.
77
+ *
78
+ * The task id is derived from the event id, so a retried enqueue of an event
79
+ * that already reached Cloud Tasks is rejected rather than buffered twice.
80
+ *
81
+ * @param payload - The serialized change to enqueue.
82
+ * @param maxAttempts - How many enqueue attempts to make before giving up.
83
+ * Anything but a positive integer means a single attempt: resolving without
84
+ * an enqueue would report success for an event that was never buffered.
85
+ * @throws The last enqueue error, once every attempt has failed.
86
+ */
87
+ export async function enqueueSyncTask(
88
+ payload: SerializedDocumentChange,
89
+ maxAttempts: number
90
+ ): Promise<void> {
91
+ const queue = getFunctions().taskQueue(syncQueuePath());
92
+ const id = taskIdFor(payload);
93
+
94
+ // Math.max(1, NaN) is NaN and would skip the loop entirely.
95
+ const attemptBudget =
96
+ Number.isInteger(maxAttempts) && maxAttempts >= 1 ? maxAttempts : 1;
97
+ const jitter = Math.random() * JITTER_MS;
98
+ let attempts = 0;
99
+
100
+ while (attempts < attemptBudget) {
101
+ if (attempts > 0) {
102
+ await new Promise((resolve) =>
103
+ setTimeout(resolve, backoffMs(attempts, jitter))
104
+ );
105
+ }
106
+
107
+ attempts++;
108
+ try {
109
+ await queue.enqueue(payload, { id });
110
+ return;
111
+ } catch (enqueueErr) {
112
+ // The event is already buffered; a second task would double-write the row.
113
+ // firebase-admin prefixes its codes: `functions/task-already-exists`.
114
+ if (
115
+ (enqueueErr as { code?: string })?.code ===
116
+ "functions/task-already-exists"
117
+ ) {
118
+ return;
119
+ }
120
+
121
+ if (attempts >= attemptBudget) {
122
+ throw enqueueErr;
123
+ }
124
+ }
125
+ }
126
+ }