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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +236 -84
  3. package/lib/config.d.ts +3 -2
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +58 -57
  6. package/lib/config.js.map +1 -1
  7. package/lib/events.d.ts.map +1 -1
  8. package/lib/events.js.map +1 -1
  9. package/lib/export-config.d.ts +19 -5
  10. package/lib/export-config.d.ts.map +1 -1
  11. package/lib/export-config.js +6 -1
  12. package/lib/export-config.js.map +1 -1
  13. package/lib/handlers.d.ts +38 -6
  14. package/lib/handlers.d.ts.map +1 -1
  15. package/lib/handlers.js +63 -18
  16. package/lib/handlers.js.map +1 -1
  17. package/lib/index.d.ts +13 -2
  18. package/lib/index.d.ts.map +1 -1
  19. package/lib/index.js +51 -12
  20. package/lib/index.js.map +1 -1
  21. package/lib/init.d.ts +1 -1
  22. package/lib/init.js +1 -1
  23. package/lib/init.js.map +1 -1
  24. package/lib/lib.d.ts +1 -1
  25. package/lib/lib.d.ts.map +1 -1
  26. package/lib/lib.js +2 -1
  27. package/lib/lib.js.map +1 -1
  28. package/lib/logs.d.ts +2 -2
  29. package/lib/logs.d.ts.map +1 -1
  30. package/lib/logs.js +4 -3
  31. package/lib/logs.js.map +1 -1
  32. package/lib/region.d.ts +7 -0
  33. package/lib/region.d.ts.map +1 -0
  34. package/lib/region.js +37 -0
  35. package/lib/region.js.map +1 -0
  36. package/lib/tasks.d.ts +40 -0
  37. package/lib/tasks.d.ts.map +1 -0
  38. package/lib/tasks.js +107 -0
  39. package/lib/tasks.js.map +1 -0
  40. package/lib/util.d.ts.map +1 -1
  41. package/lib/util.js.map +1 -1
  42. package/npm-shrinkwrap.json +160 -780
  43. package/package.json +10 -4
  44. package/src/config.ts +70 -59
  45. package/src/export-config.ts +26 -6
  46. package/src/handlers.ts +96 -27
  47. package/src/index.ts +71 -13
  48. package/src/init.ts +1 -1
  49. package/src/lib.ts +2 -0
  50. package/src/logs.ts +5 -3
  51. package/src/region.ts +37 -0
  52. package/src/tasks.ts +126 -0
  53. package/tests/config.test.ts +101 -14
  54. package/tests/export-config.test.ts +10 -4
  55. package/tests/handlers.test.ts +139 -10
  56. package/tests/index.test.ts +162 -0
  57. package/tests/region.test.ts +44 -0
  58. package/tests/required-apis.test.ts +55 -0
  59. package/tests/tasks.emulator.test.ts +131 -0
  60. package/tests/tasks.test.ts +229 -0
  61. package/tsconfig.tsbuildinfo +1 -1
@@ -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
+ });
@@ -0,0 +1,131 @@
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 { createHash } from "node:crypto";
18
+ import { createServer, type Server } from "node:http";
19
+ import type { AddressInfo } from "node:net";
20
+ import {
21
+ afterAll,
22
+ afterEach,
23
+ beforeAll,
24
+ beforeEach,
25
+ describe,
26
+ expect,
27
+ test,
28
+ } from "vitest";
29
+ import type { SerializedDocumentChange } from "../src/handlers";
30
+
31
+ // Real firebase-admin against a local Cloud Tasks emulator host: the kit
32
+ // prefix and the default location are resolved by the SDK, which the unit
33
+ // suite mocks away.
34
+ const INSTANCE_ID = "test-instance";
35
+ const REGION_KEYS = ["DATABASE_REGION", "FUNCTION_REGION"] as const;
36
+
37
+ let server: Server;
38
+ let requests: { path: string; body: string }[] = [];
39
+ const originalEnv: Record<string, string | undefined> = {};
40
+
41
+ beforeAll(async () => {
42
+ server = createServer((request, response) => {
43
+ let body = "";
44
+ request.on("data", (chunk) => (body += chunk));
45
+ request.on("end", () => {
46
+ requests.push({ path: request.url ?? "", body });
47
+ response.writeHead(200, { "content-type": "application/json" });
48
+ response.end("{}");
49
+ });
50
+ });
51
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
52
+ const { port } = server.address() as AddressInfo;
53
+ process.env.CLOUD_TASKS_EMULATOR_HOST = `127.0.0.1:${port}`;
54
+ process.env.FIREBASE_KIT_INSTANCE_ID = INSTANCE_ID;
55
+ const { initializeApp } = await import("firebase-admin/app");
56
+ initializeApp({
57
+ projectId: "test-project",
58
+ serviceAccountId: "tasks@test-project.iam.gserviceaccount.com",
59
+ credential: {
60
+ getAccessToken: async () => ({
61
+ access_token: "owner",
62
+ expires_in: 3600,
63
+ }),
64
+ },
65
+ });
66
+ });
67
+
68
+ afterAll(async () => {
69
+ await new Promise<void>((resolve) => server.close(() => resolve()));
70
+ });
71
+
72
+ beforeEach(() => {
73
+ requests = [];
74
+ for (const key of REGION_KEYS) {
75
+ originalEnv[key] = process.env[key];
76
+ delete process.env[key];
77
+ }
78
+ });
79
+
80
+ afterEach(() => {
81
+ for (const key of REGION_KEYS) {
82
+ if (originalEnv[key] === undefined) {
83
+ delete process.env[key];
84
+ } else {
85
+ process.env[key] = originalEnv[key];
86
+ }
87
+ }
88
+ });
89
+
90
+ function change(eventId: string): SerializedDocumentChange {
91
+ return {
92
+ timestamp: "2026-01-01T00:00:00.000Z",
93
+ eventId,
94
+ fullResourceName: "projects/p/databases/(default)/documents/c/d",
95
+ changeType: "CREATE",
96
+ documentId: "d",
97
+ params: null,
98
+ data: { a: 1 },
99
+ oldData: undefined,
100
+ } as SerializedDocumentChange;
101
+ }
102
+
103
+ function queueUrl(region: string): string {
104
+ return `/projects/test-project/locations/${region}/queues/kit-${INSTANCE_ID}-syncBigQuery/tasks`;
105
+ }
106
+
107
+ describe("enqueueSyncTask against the Admin SDK", () => {
108
+ test("targets the kit-prefixed queue in FUNCTION_REGION", async () => {
109
+ process.env.FUNCTION_REGION = "europe-west2";
110
+ const { enqueueSyncTask } = await import("../src/tasks");
111
+ await enqueueSyncTask(change("evt-1"), 1);
112
+ expect(requests.map((r) => r.path)).toEqual([queueUrl("europe-west2")]);
113
+ });
114
+
115
+ test("falls back to the SDK default location with no region variables", async () => {
116
+ const { enqueueSyncTask } = await import("../src/tasks");
117
+ await enqueueSyncTask(change("evt-1"), 1);
118
+ expect(requests.map((r) => r.path)).toEqual([queueUrl("us-central1")]);
119
+ });
120
+
121
+ test("names the task by the hashed event id", async () => {
122
+ process.env.FUNCTION_REGION = "us-central1";
123
+ const { enqueueSyncTask } = await import("../src/tasks");
124
+ await enqueueSyncTask(change("a/b:c d"), 1);
125
+ const task = JSON.parse(requests[0].body).task as { name: string };
126
+ expect(task.name).toBe(
127
+ `projects/test-project/locations/us-central1/queues/kit-${INSTANCE_ID}-syncBigQuery/tasks/` +
128
+ createHash("sha256").update("a/b:c d").digest("hex")
129
+ );
130
+ });
131
+ });