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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/README.md +163 -45
  3. package/lib/config.d.ts +3 -1
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +53 -7
  6. package/lib/config.js.map +1 -1
  7. package/lib/export-config.d.ts +14 -0
  8. package/lib/export-config.d.ts.map +1 -1
  9. package/lib/export-config.js +6 -0
  10. package/lib/export-config.js.map +1 -1
  11. package/lib/handlers.d.ts +38 -6
  12. package/lib/handlers.d.ts.map +1 -1
  13. package/lib/handlers.js +63 -18
  14. package/lib/handlers.js.map +1 -1
  15. package/lib/index.d.ts +13 -2
  16. package/lib/index.d.ts.map +1 -1
  17. package/lib/index.js +38 -6
  18. package/lib/index.js.map +1 -1
  19. package/lib/init.d.ts +1 -1
  20. package/lib/init.js +1 -1
  21. package/lib/lib.d.ts +1 -1
  22. package/lib/lib.d.ts.map +1 -1
  23. package/lib/lib.js +2 -1
  24. package/lib/lib.js.map +1 -1
  25. package/lib/logs.d.ts +1 -1
  26. package/lib/logs.d.ts.map +1 -1
  27. package/lib/logs.js +2 -1
  28. package/lib/logs.js.map +1 -1
  29. package/lib/tasks.d.ts +40 -0
  30. package/lib/tasks.d.ts.map +1 -0
  31. package/lib/tasks.js +107 -0
  32. package/lib/tasks.js.map +1 -0
  33. package/npm-shrinkwrap.json +593 -2069
  34. package/package.json +7 -7
  35. package/src/config.ts +65 -8
  36. package/src/export-config.ts +21 -0
  37. package/src/handlers.ts +96 -27
  38. package/src/index.ts +56 -7
  39. package/src/init.ts +1 -1
  40. package/src/lib.ts +2 -0
  41. package/src/logs.ts +3 -1
  42. package/src/tasks.ts +126 -0
  43. package/tests/config.test.ts +98 -10
  44. package/tests/export-config.test.ts +10 -0
  45. package/tests/handlers.test.ts +139 -10
  46. package/tests/index.test.ts +38 -2
  47. package/tests/required-apis.test.ts +55 -0
  48. package/tests/tasks.emulator.test.ts +131 -0
  49. package/tests/tasks.test.ts +229 -0
  50. package/tsconfig.tsbuildinfo +1 -1
@@ -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
+ });
@@ -0,0 +1,229 @@
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 { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
19
+
20
+ vi.mock("firebase-admin/functions", () => ({
21
+ getFunctions: vi.fn(),
22
+ }));
23
+
24
+ import { getFunctions } from "firebase-admin/functions";
25
+ import type { SerializedDocumentChange } from "../src/handlers";
26
+ import { enqueueSyncTask, syncQueuePath } from "../src/tasks";
27
+
28
+ function sha256(value: string): string {
29
+ return createHash("sha256").update(value).digest("hex");
30
+ }
31
+
32
+ function makeChange(
33
+ overrides: Partial<SerializedDocumentChange> = {}
34
+ ): SerializedDocumentChange {
35
+ return {
36
+ timestamp: "2026-01-01T00:00:00.000Z",
37
+ eventId: "evt-1",
38
+ fullResourceName: "projects/p/databases/(default)/documents/c/d",
39
+ changeType: "CREATE",
40
+ documentId: "d",
41
+ params: null,
42
+ data: { a: 1 },
43
+ oldData: undefined,
44
+ ...overrides,
45
+ } as SerializedDocumentChange;
46
+ }
47
+
48
+ const ENV_KEYS = ["DATABASE_REGION", "FUNCTION_REGION"] as const;
49
+ const originalEnv: Record<string, string | undefined> = {};
50
+
51
+ beforeEach(() => {
52
+ for (const key of ENV_KEYS) {
53
+ originalEnv[key] = process.env[key];
54
+ delete process.env[key];
55
+ }
56
+ });
57
+
58
+ afterEach(() => {
59
+ for (const key of ENV_KEYS) {
60
+ if (originalEnv[key] === undefined) {
61
+ delete process.env[key];
62
+ } else {
63
+ process.env[key] = originalEnv[key];
64
+ }
65
+ }
66
+ vi.useRealTimers();
67
+ vi.clearAllMocks();
68
+ });
69
+
70
+ describe("syncQueuePath", () => {
71
+ test("derives the region from DATABASE_REGION, mapping multi-regions", () => {
72
+ process.env.DATABASE_REGION = "nam5";
73
+ expect(syncQueuePath()).toBe(
74
+ "locations/us-central1/functions/syncBigQuery"
75
+ );
76
+ });
77
+
78
+ test("passes a regional DATABASE_REGION through", () => {
79
+ process.env.DATABASE_REGION = "europe-west2";
80
+ expect(syncQueuePath()).toBe(
81
+ "locations/europe-west2/functions/syncBigQuery"
82
+ );
83
+ });
84
+
85
+ test("prefers the CLI-set FUNCTION_REGION, the region the function is deployed in", () => {
86
+ // On a first interactive deploy the functions land in us-central1 while
87
+ // DATABASE_REGION already names the target region; the queue is where
88
+ // the functions are.
89
+ process.env.FUNCTION_REGION = "us-central1";
90
+ process.env.DATABASE_REGION = "europe-west2";
91
+ expect(syncQueuePath()).toBe(
92
+ "locations/us-central1/functions/syncBigQuery"
93
+ );
94
+ });
95
+
96
+ test("falls back to DATABASE_REGION when FUNCTION_REGION is unset", () => {
97
+ process.env.DATABASE_REGION = "europe-west2";
98
+ expect(syncQueuePath()).toBe(
99
+ "locations/europe-west2/functions/syncBigQuery"
100
+ );
101
+ });
102
+
103
+ test("returns the bare name when neither region variable is set, leaving the location to the SDK default", () => {
104
+ expect(syncQueuePath()).toBe("syncBigQuery");
105
+ });
106
+
107
+ test("treats empty region variables as unset", () => {
108
+ process.env.DATABASE_REGION = "";
109
+ process.env.FUNCTION_REGION = "";
110
+ expect(syncQueuePath()).toBe("syncBigQuery");
111
+ });
112
+ });
113
+
114
+ describe("enqueueSyncTask", () => {
115
+ function mockQueue(enqueue: ReturnType<typeof vi.fn>) {
116
+ const taskQueue = vi.fn(() => ({ enqueue }));
117
+ vi.mocked(getFunctions).mockReturnValue({
118
+ taskQueue,
119
+ } as unknown as ReturnType<typeof getFunctions>);
120
+ return taskQueue;
121
+ }
122
+
123
+ beforeEach(() => {
124
+ process.env.DATABASE_REGION = "us-central1";
125
+ });
126
+
127
+ test("targets the bare function name; the admin SDK adds the kit prefix", async () => {
128
+ const enqueue = vi.fn().mockResolvedValue(undefined);
129
+ const taskQueue = mockQueue(enqueue);
130
+
131
+ const change = makeChange();
132
+ await enqueueSyncTask(change, 3);
133
+
134
+ expect(taskQueue).toHaveBeenCalledWith(
135
+ "locations/us-central1/functions/syncBigQuery"
136
+ );
137
+ expect(enqueue).toHaveBeenCalledTimes(1);
138
+ expect(enqueue).toHaveBeenCalledWith(change, { id: sha256("evt-1") });
139
+ });
140
+
141
+ test("hashes the event id into the task id so a retry cannot double-buffer", async () => {
142
+ const enqueue = vi.fn().mockResolvedValue(undefined);
143
+ mockQueue(enqueue);
144
+
145
+ await enqueueSyncTask(makeChange({ eventId: "a/b:c d" }), 3);
146
+
147
+ expect(enqueue).toHaveBeenCalledWith(expect.anything(), {
148
+ id: sha256("a/b:c d"),
149
+ });
150
+ });
151
+
152
+ test("event ids that differ only in punctuation get distinct task ids", async () => {
153
+ const enqueue = vi.fn().mockResolvedValue(undefined);
154
+ mockQueue(enqueue);
155
+
156
+ await enqueueSyncTask(makeChange({ eventId: "a.b" }), 3);
157
+ await enqueueSyncTask(makeChange({ eventId: "a/b" }), 3);
158
+
159
+ const ids = enqueue.mock.calls.map((call) => call[1].id);
160
+ expect(ids[0]).not.toBe(ids[1]);
161
+ for (const id of ids) expect(id).toMatch(/^[a-f0-9]{64}$/);
162
+ });
163
+
164
+ test("treats an already-enqueued task as success", async () => {
165
+ const enqueue = vi.fn().mockRejectedValue(
166
+ // Shaped like firebase-admin's PrefixedFirebaseError: `<prefix>/<code>`.
167
+ Object.assign(new Error("exists"), {
168
+ code: "functions/task-already-exists",
169
+ })
170
+ );
171
+ mockQueue(enqueue);
172
+
173
+ await expect(enqueueSyncTask(makeChange(), 3)).resolves.toBeUndefined();
174
+ expect(enqueue).toHaveBeenCalledTimes(1);
175
+ });
176
+
177
+ test("a non-positive attempt budget still enqueues once", async () => {
178
+ const enqueue = vi.fn().mockResolvedValue(undefined);
179
+ mockQueue(enqueue);
180
+
181
+ await enqueueSyncTask(makeChange(), 0);
182
+
183
+ expect(enqueue).toHaveBeenCalledTimes(1);
184
+ });
185
+
186
+ test("a NaN or non-integer attempt budget still enqueues once", async () => {
187
+ const enqueue = vi.fn().mockResolvedValue(undefined);
188
+ mockQueue(enqueue);
189
+
190
+ await enqueueSyncTask(makeChange(), NaN);
191
+ await enqueueSyncTask(makeChange(), Infinity);
192
+
193
+ expect(enqueue).toHaveBeenCalledTimes(2);
194
+ });
195
+
196
+ test("retries a failed enqueue after a backoff and then succeeds", async () => {
197
+ vi.useFakeTimers();
198
+ const enqueue = vi
199
+ .fn()
200
+ .mockRejectedValueOnce(new Error("blip"))
201
+ .mockResolvedValueOnce(undefined);
202
+ mockQueue(enqueue);
203
+
204
+ const pending = enqueueSyncTask(makeChange(), 3);
205
+ await vi.runAllTimersAsync();
206
+ await pending;
207
+
208
+ expect(enqueue).toHaveBeenCalledTimes(2);
209
+ });
210
+
211
+ test("throws the last error once every attempt fails", async () => {
212
+ vi.useFakeTimers();
213
+ const enqueue = vi
214
+ .fn()
215
+ .mockRejectedValueOnce(new Error("first"))
216
+ .mockRejectedValueOnce(new Error("second"))
217
+ .mockRejectedValue(new Error("last"));
218
+ mockQueue(enqueue);
219
+
220
+ const pending = enqueueSyncTask(makeChange(), 3);
221
+ // Attach the rejection expectation before advancing timers so the
222
+ // rejection is never unhandled.
223
+ const assertion = expect(pending).rejects.toThrow("last");
224
+ await vi.runAllTimersAsync();
225
+ await assertion;
226
+
227
+ expect(enqueue).toHaveBeenCalledTimes(3);
228
+ });
229
+ });
@@ -1 +1 @@
1
- {"root":["./src/config.ts","./src/events.ts","./src/export-config.ts","./src/handlers.ts","./src/index.ts","./src/init.ts","./src/lib.ts","./src/logs.ts","./src/region.ts","./src/util.ts"],"version":"5.9.3"}
1
+ {"root":["./src/config.ts","./src/events.ts","./src/export-config.ts","./src/handlers.ts","./src/index.ts","./src/init.ts","./src/lib.ts","./src/logs.ts","./src/region.ts","./src/tasks.ts","./src/util.ts"],"version":"5.9.3"}