@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
@@ -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 }) => ({
@@ -162,21 +160,110 @@ describe("buildPartitioningConfig", () => {
162
160
  });
163
161
 
164
162
  describe("configFromEnv", () => {
165
- test("maps params without inventing a region default", () => {
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
- expect(resolveExportConfig(config).location).toBe("");
171
170
  expect(config.viewType).toBe("view");
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", () => {
175
234
  expect(CONFIG_EXPRESSIONS.collectionPath.toString()).toBe(
176
235
  "params.COLLECTION_PATH"
177
236
  );
178
- expect(CONFIG_EXPRESSIONS.location.toString()).toBe(
179
- "params.DATABASE_REGION"
237
+ expect(CONFIG_EXPRESSIONS.database.toString()).toBe("params.DATABASE");
238
+ expect(CONFIG_EXPRESSIONS.maxDispatchesPerSecond.toString()).toBe(
239
+ "params.MAX_DISPATCHES_PER_SECOND"
180
240
  );
241
+ expect(CONFIG_EXPRESSIONS).not.toHaveProperty("location");
242
+ });
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);
181
268
  });
182
269
  });
@@ -22,7 +22,6 @@ describe("resolveExportConfig", () => {
22
22
  collectionPath: "users",
23
23
  datasetId: "analytics",
24
24
  tableId: "users",
25
- location: "us-central1",
26
25
  projectId: "test-project",
27
26
  };
28
27
 
@@ -42,12 +41,10 @@ describe("resolveExportConfig", () => {
42
41
  test("keeps caller-supplied values", () => {
43
42
  const resolved = resolveExportConfig({
44
43
  ...minimal,
45
- location: "europe-west2",
46
44
  databaseId: "secondary",
47
45
  wildcardIds: true,
48
46
  });
49
47
 
50
- expect(resolved.location).toBe("europe-west2");
51
48
  expect(resolved.databaseId).toBe("secondary");
52
49
  expect(resolved.wildcardIds).toBe(true);
53
50
  });
@@ -65,7 +62,6 @@ describe("toTrackerConfig", () => {
65
62
  collectionPath: "users",
66
63
  datasetId: "analytics",
67
64
  tableId: "users",
68
- location: "us-central1",
69
65
  projectId: "test-project",
70
66
  };
71
67
 
@@ -111,4 +107,14 @@ describe("toTrackerConfig", () => {
111
107
  );
112
108
  expect(tracker.bqProjectId).toBe("analytics-project");
113
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
+ });
114
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
+ });
@@ -0,0 +1,162 @@
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 { afterEach, describe, expect, test, vi } from "vitest";
18
+
19
+ vi.mock("firebase-functions/firestore", () => ({
20
+ onDocumentWritten: vi.fn(() => ({})),
21
+ }));
22
+ vi.mock("firebase-functions/tasks", () => ({
23
+ onTaskDispatched: vi.fn(() => ({})),
24
+ }));
25
+ vi.mock("firebase-functions/v2", () => ({
26
+ requiresAPI: vi.fn(),
27
+ requiresRole: vi.fn(),
28
+ }));
29
+ vi.mock("firebase-functions/v2/lifecycle", () => ({
30
+ afterFirstDeploy: vi.fn(),
31
+ afterRedeploy: vi.fn(),
32
+ }));
33
+
34
+ type FunctionOptions = Record<string, unknown>;
35
+
36
+ interface ExportedOptions {
37
+ trigger: FunctionOptions;
38
+ /** Options of syncBigQuery, initBigQuerySync, setupBigQuerySync, in order. */
39
+ tasks: FunctionOptions[];
40
+ }
41
+
42
+ const originalDatabaseRegion = process.env.DATABASE_REGION;
43
+
44
+ afterEach(() => {
45
+ if (originalDatabaseRegion === undefined) {
46
+ delete process.env.DATABASE_REGION;
47
+ } else {
48
+ process.env.DATABASE_REGION = originalDatabaseRegion;
49
+ }
50
+ });
51
+
52
+ async function loadExportedOptions(
53
+ databaseRegion?: string
54
+ ): Promise<ExportedOptions> {
55
+ vi.resetModules();
56
+ if (databaseRegion === undefined) {
57
+ delete process.env.DATABASE_REGION;
58
+ } else {
59
+ process.env.DATABASE_REGION = databaseRegion;
60
+ }
61
+
62
+ await import("../src/index");
63
+ const { onDocumentWritten } = await import("firebase-functions/firestore");
64
+ const { onTaskDispatched } = await import("firebase-functions/tasks");
65
+
66
+ const triggerCalls = vi.mocked(onDocumentWritten).mock.calls;
67
+ const taskCalls = vi.mocked(onTaskDispatched).mock.calls;
68
+ const trigger = triggerCalls[triggerCalls.length - 1][0] as FunctionOptions;
69
+ const tasks = taskCalls
70
+ .slice(-3)
71
+ .map((call) => call[0] as unknown as FunctionOptions);
72
+
73
+ expect(tasks).toHaveLength(3);
74
+ return { trigger, tasks };
75
+ }
76
+
77
+ function allOptions({ trigger, tasks }: ExportedOptions): FunctionOptions[] {
78
+ return [trigger, ...tasks];
79
+ }
80
+
81
+ describe("exported function options", () => {
82
+ test.each([
83
+ ["nam5", "us-central1"],
84
+ ["nam7", "us-central1"],
85
+ ["eur3", "europe-west1"],
86
+ ])(
87
+ "multi-region DATABASE_REGION %s deploys every function to %s",
88
+ async (databaseRegion, expectedRegion) => {
89
+ const options = await loadExportedOptions(databaseRegion);
90
+ for (const opts of allOptions(options)) {
91
+ expect(opts.region).toBe(expectedRegion);
92
+ }
93
+ }
94
+ );
95
+
96
+ test("regional DATABASE_REGION passes through to every function", async () => {
97
+ const options = await loadExportedOptions("europe-west1");
98
+ for (const opts of allOptions(options)) {
99
+ expect(opts.region).toBe("europe-west1");
100
+ }
101
+ });
102
+
103
+ test("unset DATABASE_REGION leaves every function without a region", async () => {
104
+ const options = await loadExportedOptions();
105
+ for (const opts of allOptions(options)) {
106
+ expect(opts).not.toHaveProperty("region");
107
+ }
108
+ });
109
+
110
+ test("empty DATABASE_REGION leaves every function without a region", async () => {
111
+ const options = await loadExportedOptions("");
112
+ for (const opts of allOptions(options)) {
113
+ expect(opts).not.toHaveProperty("region");
114
+ }
115
+ });
116
+
117
+ test("the trigger binds to the configured database instance", async () => {
118
+ const { trigger } = await loadExportedOptions();
119
+ expect(String(trigger.database)).toBe("params.DATABASE");
120
+ });
121
+
122
+ test("the trigger watches the configured collection path", async () => {
123
+ const { trigger } = await loadExportedOptions();
124
+ const document = trigger.document as { toCEL(): string };
125
+ expect(document.toCEL()).toContain("params.COLLECTION_PATH");
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
+ });
162
+ });
@@ -0,0 +1,44 @@
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 { describe, expect, test } from "vitest";
18
+
19
+ import { firestoreLocationToFunctionRegion } from "../src/region";
20
+
21
+ describe("firestoreLocationToFunctionRegion", () => {
22
+ test.each([
23
+ ["nam5", "us-central1"],
24
+ ["nam7", "us-central1"],
25
+ ["eur3", "europe-west1"],
26
+ ])("maps the multi-region location %s to %s", (location, region) => {
27
+ expect(firestoreLocationToFunctionRegion(location)).toBe(region);
28
+ });
29
+
30
+ test.each(["us-central1", "europe-west1", "asia-northeast1", "us-east1"])(
31
+ "passes the regional location %s through unchanged",
32
+ (location) => {
33
+ expect(firestoreLocationToFunctionRegion(location)).toBe(location);
34
+ }
35
+ );
36
+
37
+ test("returns undefined for an unset location", () => {
38
+ expect(firestoreLocationToFunctionRegion(undefined)).toBeUndefined();
39
+ });
40
+
41
+ test("returns undefined for an empty location", () => {
42
+ expect(firestoreLocationToFunctionRegion("")).toBeUndefined();
43
+ });
44
+ });
@@ -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
+ });