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

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 +632 -477
  34. package/package.json +8 -3
  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/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
+ }
@@ -33,19 +33,17 @@ vi.mock("firebase-functions/params", () => ({
33
33
  toJSON(): string {
34
34
  return this.toString();
35
35
  }
36
- },
37
- defineString: (
38
- _name: string,
39
- opts?: { default?: string | { value(): string } }
40
- ) => ({
41
- value: () =>
42
- typeof opts?.default === "string"
43
- ? opts.default
44
- : opts?.default?.value() ?? "",
36
+ }, // Mirrors the real StringParam: the env var or "", never the declared
37
+ // default, which only the CLI prompt consults.
38
+ defineString: (_name: string) => ({
39
+ value: () => process.env[_name] || "",
45
40
  toString: () => `params.${_name}`,
46
41
  }),
42
+ // Mirrors the real IntParam: a missing or blank env var resolves to 0, and
43
+ // the declared default never reaches runtime.
47
44
  defineInt: (_name: string, opts?: { default?: number }) => ({
48
- value: () => opts?.default ?? 0,
45
+ name: _name,
46
+ value: () => Number.parseInt(process.env[_name] || "0", 10) || 0,
49
47
  toString: () => `params.${_name}`,
50
48
  }),
51
49
  defineBoolean: (_name: string, opts?: { default?: boolean }) => ({
@@ -163,12 +161,73 @@ describe("buildPartitioningConfig", () => {
163
161
 
164
162
  describe("configFromEnv", () => {
165
163
  test("maps params", () => {
164
+ // The CLI resolves the param's default into the env at deploy.
165
+ vi.stubEnv("BIGQUERY_PROJECT_ID", "test-project");
166
166
  const config = configFromEnv();
167
167
  expect(config.projectId).toBe("test-project");
168
168
  expect(config.bqProjectId).toBe("test-project");
169
169
  expect(config.databaseId).toBe("(default)");
170
170
  expect(config.viewType).toBe("view");
171
171
  expect(resolveExportConfig(config)).not.toHaveProperty("location");
172
+ vi.unstubAllEnvs();
173
+ });
174
+
175
+ test("reports unset queue params as undefined so the documented defaults apply", () => {
176
+ // IntParam.value() resolves an unset var to 0, which would defeat the
177
+ // `?? 100` / `?? 3` fallbacks in resolveExportConfig.
178
+ const config = configFromEnv();
179
+ expect(config.maxDispatchesPerSecond).toBeUndefined();
180
+ expect(config.maxEnqueueAttempts).toBeUndefined();
181
+
182
+ const resolved = resolveExportConfig(config);
183
+ expect(resolved.maxDispatchesPerSecond).toBe(100);
184
+ expect(resolved.maxEnqueueAttempts).toBe(3);
185
+ });
186
+
187
+ test("reports a blank queue param as undefined", () => {
188
+ vi.stubEnv("MAX_ENQUEUE_ATTEMPTS", " ");
189
+ expect(configFromEnv().maxEnqueueAttempts).toBeUndefined();
190
+ vi.unstubAllEnvs();
191
+ });
192
+
193
+ test("passes an explicit queue param through", () => {
194
+ vi.stubEnv("MAX_ENQUEUE_ATTEMPTS", "7");
195
+ vi.stubEnv("MAX_DISPATCHES_PER_SECOND", "250");
196
+ const config = configFromEnv();
197
+ expect(config.maxEnqueueAttempts).toBe(7);
198
+ expect(config.maxDispatchesPerSecond).toBe(250);
199
+ vi.unstubAllEnvs();
200
+ });
201
+
202
+ test("yes/no selects default to off", () => {
203
+ const config = configFromEnv();
204
+ expect(config.useNewSnapshotQuerySyntax).toBe(false);
205
+ expect(config.excludeOldData).toBe(false);
206
+ });
207
+
208
+ test("yes/no selects enable on the extension's literal yes", () => {
209
+ vi.stubEnv("USE_NEW_SNAPSHOT_QUERY_SYNTAX", "yes");
210
+ vi.stubEnv("EXCLUDE_OLD_DATA", "yes");
211
+ const config = configFromEnv();
212
+ expect(config.useNewSnapshotQuerySyntax).toBe(true);
213
+ expect(config.excludeOldData).toBe(true);
214
+ vi.unstubAllEnvs();
215
+ });
216
+ test("yes/no selects forgive the label's case and surrounding whitespace", () => {
217
+ vi.stubEnv("USE_NEW_SNAPSHOT_QUERY_SYNTAX", "Yes");
218
+ vi.stubEnv("EXCLUDE_OLD_DATA", " yes ");
219
+ const config = configFromEnv();
220
+ expect(config.useNewSnapshotQuerySyntax).toBe(true);
221
+ expect(config.excludeOldData).toBe(true);
222
+ vi.unstubAllEnvs();
223
+ });
224
+
225
+ test("yes/no selects treat no and anything else as off", () => {
226
+ vi.stubEnv("USE_NEW_SNAPSHOT_QUERY_SYNTAX", "no");
227
+ vi.stubEnv("EXCLUDE_OLD_DATA", "true");
228
+ expect(configFromEnv().useNewSnapshotQuerySyntax).toBe(false);
229
+ expect(configFromEnv().excludeOldData).toBe(false);
230
+ vi.unstubAllEnvs();
172
231
  });
173
232
 
174
233
  test("exposes deploy-time expressions for trigger metadata", () => {
@@ -176,6 +235,35 @@ describe("configFromEnv", () => {
176
235
  "params.COLLECTION_PATH"
177
236
  );
178
237
  expect(CONFIG_EXPRESSIONS.database.toString()).toBe("params.DATABASE");
238
+ expect(CONFIG_EXPRESSIONS.maxDispatchesPerSecond.toString()).toBe(
239
+ "params.MAX_DISPATCHES_PER_SECOND"
240
+ );
179
241
  expect(CONFIG_EXPRESSIONS).not.toHaveProperty("location");
180
242
  });
181
243
  });
244
+
245
+ describe("resolveExportConfig queue defaults", () => {
246
+ test("applies the extension's queue defaults when unset", () => {
247
+ const resolved = resolveExportConfig({
248
+ collectionPath: "users",
249
+ datasetId: "ds",
250
+ tableId: "tbl",
251
+ projectId: "p",
252
+ });
253
+ expect(resolved.maxDispatchesPerSecond).toBe(100);
254
+ expect(resolved.maxEnqueueAttempts).toBe(3);
255
+ });
256
+
257
+ test("passes explicit queue values through", () => {
258
+ const resolved = resolveExportConfig({
259
+ collectionPath: "users",
260
+ datasetId: "ds",
261
+ tableId: "tbl",
262
+ projectId: "p",
263
+ maxDispatchesPerSecond: 250,
264
+ maxEnqueueAttempts: 5,
265
+ });
266
+ expect(resolved.maxDispatchesPerSecond).toBe(250);
267
+ expect(resolved.maxEnqueueAttempts).toBe(5);
268
+ });
269
+ });
@@ -107,4 +107,14 @@ describe("toTrackerConfig", () => {
107
107
  );
108
108
  expect(tracker.bqProjectId).toBe("analytics-project");
109
109
  });
110
+
111
+ test("wires the backup collection into the tracker (queue exhaustion durability)", () => {
112
+ const tracker = toTrackerConfig(
113
+ resolveExportConfig({ ...base, backupCollectionId: "bq_failures" })
114
+ );
115
+ expect(tracker.backupTableId).toBe("bq_failures");
116
+
117
+ const withoutBackup = toTrackerConfig(resolveExportConfig(base));
118
+ expect(withoutBackup.backupTableId).toBeUndefined();
119
+ });
110
120
  });
@@ -15,12 +15,15 @@
15
15
  */
16
16
 
17
17
  import { ChangeType } from "@firebaseextensions/firestore-bigquery-change-tracker";
18
+ import type { Request } from "firebase-functions/tasks";
18
19
  import { beforeEach, describe, expect, test, vi } from "vitest";
19
20
  import { resolveExportConfig } from "../src/export-config";
20
21
  import {
21
22
  type DocumentWriteEvent,
22
23
  type HandlerContext,
24
+ type SerializedDocumentChange,
23
25
  handleDocumentWrite,
26
+ handleSyncBigQueryTask,
24
27
  } from "../src/handlers";
25
28
 
26
29
  vi.mock("../src/events");
@@ -70,6 +73,33 @@ function makeCtx(
70
73
  tracker: tracker as unknown as HandlerContext["tracker"],
71
74
  config: config as HandlerContext["config"],
72
75
  ensureInitialized: vi.fn().mockResolvedValue(undefined),
76
+ enqueue: vi.fn().mockResolvedValue(undefined),
77
+ };
78
+ }
79
+
80
+ /** Fake dispatched task request carrying a serialized change. */
81
+ function taskRequest(
82
+ change: SerializedDocumentChange,
83
+ retryCount = 0
84
+ ): Request<SerializedDocumentChange> {
85
+ return { data: change, retryCount } as Request<SerializedDocumentChange>;
86
+ }
87
+
88
+ /** A serialized change as it would arrive in a task payload. */
89
+ function serializedChange(
90
+ overrides: Partial<SerializedDocumentChange> = {}
91
+ ): SerializedDocumentChange {
92
+ return {
93
+ timestamp: "2026-01-01T00:00:00Z",
94
+ eventId: "evt-1",
95
+ fullResourceName:
96
+ "projects/test-project/databases/(default)/documents/users/doc1",
97
+ changeType: ChangeType.CREATE,
98
+ documentId: "doc1",
99
+ params: null,
100
+ data: { a: 1 },
101
+ oldData: undefined,
102
+ ...overrides,
73
103
  };
74
104
  }
75
105
 
@@ -170,7 +200,7 @@ describe("handleDocumentWrite", () => {
170
200
  expect(recordedWithout[0].pathParams).toBeNull();
171
201
  });
172
202
 
173
- test("self-heals and retries the write when the inline write fails", async () => {
203
+ test("a failed inline write buffers through the queue and the execution succeeds", async () => {
174
204
  const ctx = makeCtx();
175
205
  (ctx.tracker.record as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
176
206
  new Error("bq down")
@@ -181,24 +211,68 @@ describe("handleDocumentWrite", () => {
181
211
  ctx
182
212
  );
183
213
 
184
- expect(ctx.ensureInitialized).toHaveBeenCalledTimes(1);
185
- expect(ctx.tracker.record).toHaveBeenCalledTimes(2);
214
+ expect(ctx.tracker.record).toHaveBeenCalledTimes(1);
215
+ expect(ctx.enqueue).toHaveBeenCalledTimes(1);
216
+ expect(ctx.ensureInitialized).not.toHaveBeenCalled();
186
217
  });
187
218
 
188
- test("rethrows when self-heal retry fails so runtime retry can replay", async () => {
219
+ test("a successful inline write enqueues nothing", async () => {
189
220
  const ctx = makeCtx();
190
- (ctx.tracker.record as ReturnType<typeof vi.fn>)
191
- .mockRejectedValueOnce(new Error("bq down"))
192
- .mockRejectedValueOnce(new Error("still down"));
221
+
222
+ await handleDocumentWrite(
223
+ writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
224
+ ctx
225
+ );
226
+
227
+ expect(ctx.enqueue).not.toHaveBeenCalled();
228
+ });
229
+
230
+ test("the enqueued change equals what the inline path tried to write", async () => {
231
+ const ctx = makeCtx();
232
+ (ctx.tracker.record as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
233
+ new Error("bq down")
234
+ );
235
+
236
+ await handleDocumentWrite(
237
+ writeEvent(snap(true, "doc1", { a: 1 }), snap(true, "doc1", { a: 2 })),
238
+ ctx
239
+ );
240
+
241
+ const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
242
+ .calls;
243
+ const [[enqueued]] = (ctx.enqueue as ReturnType<typeof vi.fn>).mock.calls;
244
+ expect(enqueued).toMatchObject({
245
+ timestamp: recorded[0].timestamp,
246
+ eventId: recorded[0].eventId,
247
+ fullResourceName: recorded[0].documentName,
248
+ changeType: recorded[0].operation,
249
+ documentId: recorded[0].documentId,
250
+ params: recorded[0].pathParams,
251
+ data: recorded[0].data,
252
+ oldData: recorded[0].oldData,
253
+ });
254
+ // The payload must survive the JSON round trip through Cloud Tasks.
255
+ expect(JSON.parse(JSON.stringify(enqueued))).toEqual(enqueued);
256
+ });
257
+
258
+ test("a failed enqueue is recorded and logged, then the execution succeeds", async () => {
259
+ // Extension parity: no retry policy on the trigger, so a rethrow would
260
+ // only fail the execution once and drop the event anyway.
261
+ const ctx = makeCtx();
262
+ (ctx.tracker.record as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
263
+ new Error("bq down")
264
+ );
265
+ (ctx.enqueue as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
266
+ new Error("tasks down")
267
+ );
193
268
 
194
269
  await expect(
195
270
  handleDocumentWrite(
196
271
  writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
197
272
  ctx
198
273
  )
199
- ).rejects.toThrow("still down");
200
- expect(ctx.ensureInitialized).toHaveBeenCalledTimes(1);
201
- expect(events.recordErrorEvent).toHaveBeenCalled();
274
+ ).resolves.toBeUndefined();
275
+ expect(events.recordErrorEvent).toHaveBeenCalledTimes(1);
202
276
  });
203
277
 
204
278
  test("rethrows when serialization fails", async () => {
@@ -218,3 +292,58 @@ describe("handleDocumentWrite", () => {
218
292
  expect(ctx.tracker.record).not.toHaveBeenCalled();
219
293
  });
220
294
  });
295
+
296
+ describe("handleSyncBigQueryTask", () => {
297
+ beforeEach(() => vi.clearAllMocks());
298
+
299
+ test("records the buffered change and emits a success event", async () => {
300
+ const ctx = makeCtx();
301
+ const change = serializedChange();
302
+
303
+ await handleSyncBigQueryTask(taskRequest(change), ctx);
304
+
305
+ // Extension parity: no provisioning on the write path.
306
+ expect(ctx.ensureInitialized).not.toHaveBeenCalled();
307
+ const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
308
+ .calls;
309
+ expect(recorded[0]).toMatchObject({
310
+ timestamp: change.timestamp,
311
+ operation: change.changeType,
312
+ documentName: change.fullResourceName,
313
+ documentId: change.documentId,
314
+ eventId: change.eventId,
315
+ data: change.data,
316
+ });
317
+ expect(events.recordSuccessEvent).toHaveBeenCalledTimes(1);
318
+ expect(ctx.enqueue).not.toHaveBeenCalled();
319
+ });
320
+
321
+ test("rethrows a failed write so Cloud Tasks retries", async () => {
322
+ const ctx = makeCtx();
323
+ (ctx.tracker.record as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
324
+ new Error("still down")
325
+ );
326
+
327
+ await expect(
328
+ handleSyncBigQueryTask(taskRequest(serializedChange(), 2), ctx)
329
+ ).rejects.toThrow("still down");
330
+ expect(events.recordSuccessEvent).not.toHaveBeenCalled();
331
+ // Re-enqueueing from the task would seed a trigger-queue loop; retries
332
+ // belong to Cloud Tasks alone.
333
+ expect(ctx.enqueue).not.toHaveBeenCalled();
334
+ });
335
+
336
+ test("does not rethrow when the success event fails after the row lands", async () => {
337
+ // The row is already in BigQuery; a Cloud Tasks retry would land past the
338
+ // insertId dedupe window and duplicate it.
339
+ const ctx = makeCtx();
340
+ (
341
+ events.recordSuccessEvent as ReturnType<typeof vi.fn>
342
+ ).mockRejectedValueOnce(new Error("channel down"));
343
+
344
+ await expect(
345
+ handleSyncBigQueryTask(taskRequest(serializedChange()), ctx)
346
+ ).resolves.toBeUndefined();
347
+ expect(ctx.tracker.record).toHaveBeenCalledTimes(1);
348
+ });
349
+ });
@@ -35,6 +35,7 @@ type FunctionOptions = Record<string, unknown>;
35
35
 
36
36
  interface ExportedOptions {
37
37
  trigger: FunctionOptions;
38
+ /** Options of syncBigQuery, initBigQuerySync, setupBigQuerySync, in order. */
38
39
  tasks: FunctionOptions[];
39
40
  }
40
41
 
@@ -66,10 +67,10 @@ async function loadExportedOptions(
66
67
  const taskCalls = vi.mocked(onTaskDispatched).mock.calls;
67
68
  const trigger = triggerCalls[triggerCalls.length - 1][0] as FunctionOptions;
68
69
  const tasks = taskCalls
69
- .slice(-2)
70
+ .slice(-3)
70
71
  .map((call) => call[0] as unknown as FunctionOptions);
71
72
 
72
- expect(tasks).toHaveLength(2);
73
+ expect(tasks).toHaveLength(3);
73
74
  return { trigger, tasks };
74
75
  }
75
76
 
@@ -123,4 +124,39 @@ describe("exported function options", () => {
123
124
  const document = trigger.document as { toCEL(): string };
124
125
  expect(document.toCEL()).toContain("params.COLLECTION_PATH");
125
126
  });
127
+
128
+ test("the trigger declares no retry policy, matching the extension", async () => {
129
+ const { trigger } = await loadExportedOptions();
130
+ expect(trigger.retry).toBeUndefined();
131
+ });
132
+
133
+ test("syncBigQuery pins the extension's queue shape", async () => {
134
+ const { tasks } = await loadExportedOptions();
135
+ const [syncTask] = tasks;
136
+
137
+ expect(syncTask.retryConfig).toEqual({
138
+ maxAttempts: 5,
139
+ minBackoffSeconds: 60,
140
+ });
141
+
142
+ const rateLimits = syncTask.rateLimits as Record<string, unknown>;
143
+ expect(rateLimits.maxConcurrentDispatches).toBe(500); // Concurrency comes from the gen2 defaults (80 per instance), so no
144
+ // instance cap is declared.
145
+ expect(syncTask.maxInstances).toBeUndefined();
146
+ // A blank .env value is 0 at deploy; the ternary restores the default.
147
+ expect(String(rateLimits.maxDispatchesPerSecond)).toBe(
148
+ "params.MAX_DISPATCHES_PER_SECOND < 1 ? 100 : params.MAX_DISPATCHES_PER_SECOND"
149
+ );
150
+ });
151
+
152
+ test("the lifecycle tasks keep their own retry config", async () => {
153
+ const { tasks } = await loadExportedOptions();
154
+ for (const opts of tasks.slice(1)) {
155
+ expect(opts.retryConfig).toEqual({
156
+ maxAttempts: 15,
157
+ minBackoffSeconds: 60,
158
+ });
159
+ expect(opts).not.toHaveProperty("rateLimits");
160
+ }
161
+ });
126
162
  });
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Copyright 2026 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 { beforeAll, expect, test, vi } from "vitest";
18
+
19
+ const { requiresAPI } = vi.hoisted(() => ({ requiresAPI: vi.fn() }));
20
+
21
+ vi.mock("firebase-functions/firestore", () => ({
22
+ onDocumentWritten: vi.fn(() => ({})),
23
+ }));
24
+ vi.mock("firebase-functions/tasks", () => ({
25
+ onTaskDispatched: vi.fn(() => ({})),
26
+ }));
27
+ vi.mock("firebase-functions/v2", () => ({
28
+ requiresAPI,
29
+ requiresRole: vi.fn(),
30
+ }));
31
+ vi.mock("firebase-functions/v2/lifecycle", () => ({
32
+ afterFirstDeploy: vi.fn(),
33
+ afterRedeploy: vi.fn(),
34
+ }));
35
+
36
+ beforeAll(async () => {
37
+ await import("../src/index");
38
+ });
39
+
40
+ test.each([
41
+ [
42
+ "firestore.googleapis.com",
43
+ "Receives document change events from Cloud Firestore.",
44
+ ],
45
+ [
46
+ "bigquery.googleapis.com",
47
+ "Mirrors data from your Cloud Firestore collection in BigQuery.",
48
+ ],
49
+ ])("declares %s", (api, reason) => {
50
+ expect(requiresAPI).toHaveBeenCalledWith(api, reason);
51
+ });
52
+
53
+ test("declares exactly the two APIs", () => {
54
+ expect(requiresAPI).toHaveBeenCalledTimes(2);
55
+ });