@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.12 → 0.0.2-rc.13

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.
@@ -0,0 +1,119 @@
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
+ /**
18
+ * The handler is driven with a real `../src/events` against an Eventarc
19
+ * channel that rejects every publish, as a deleted channel does with
20
+ * PERMISSION_DENIED. The export must still reach BigQuery.
21
+ */
22
+
23
+ import { ChangeType } from "@firebaseextensions/firestore-bigquery-change-tracker";
24
+ import type { Request } from "firebase-functions/tasks";
25
+ import { logger } from "firebase-functions";
26
+ import { beforeEach, expect, test, vi } from "vitest";
27
+
28
+ const publish = vi
29
+ .fn()
30
+ .mockRejectedValue(
31
+ Object.assign(new Error("Permission denied"), { code: 403 })
32
+ );
33
+
34
+ vi.mock("firebase-admin/eventarc", () => ({
35
+ getEventarc: () => ({ channel: () => ({ publish }) }),
36
+ }));
37
+ vi.mock("../src/logs");
38
+
39
+ import * as events from "../src/events";
40
+ import { resolveExportConfig } from "../src/export-config";
41
+ import {
42
+ type DocumentWriteEvent,
43
+ type HandlerContext,
44
+ type SerializedDocumentChange,
45
+ handleDocumentWrite,
46
+ handleSyncBigQueryTask,
47
+ } from "../src/handlers";
48
+
49
+ function snap(exists: boolean, id: string, data: unknown = {}) {
50
+ return { exists, id, data: () => data };
51
+ }
52
+
53
+ function makeCtx(): HandlerContext {
54
+ return {
55
+ tracker: {
56
+ record: vi.fn().mockResolvedValue(undefined),
57
+ serializeData: vi.fn((d: unknown) => d),
58
+ },
59
+ config: resolveExportConfig({
60
+ collectionPath: "users",
61
+ datasetId: "ds",
62
+ tableId: "tbl",
63
+ projectId: "test-project",
64
+ }),
65
+ } as unknown as HandlerContext;
66
+ }
67
+
68
+ beforeEach(() => {
69
+ vi.clearAllMocks();
70
+ vi.spyOn(logger, "warn").mockImplementation(() => {});
71
+ process.env.EVENTARC_CHANNEL = "projects/p/locations/l/channels/firebase";
72
+ events.setupEventChannel();
73
+ });
74
+
75
+ test("a document write still exports when every Eventarc publish is denied", async () => {
76
+ const ctx = makeCtx();
77
+ const event = {
78
+ data: { before: snap(false, "doc1"), after: snap(true, "doc1", { a: 1 }) },
79
+ id: "evt-1",
80
+ time: "2026-01-01T00:00:00Z",
81
+ document: "users/doc1",
82
+ params: { documentId: "doc1" },
83
+ } as unknown as DocumentWriteEvent;
84
+
85
+ await expect(handleDocumentWrite(event, ctx)).resolves.toBeUndefined();
86
+
87
+ expect(publish).toHaveBeenCalled();
88
+ expect(logger.warn).toHaveBeenCalled();
89
+ const record = vi.mocked(ctx.tracker.record);
90
+ expect(record).toHaveBeenCalledTimes(1);
91
+ expect(record.mock.calls[0][0][0].operation).toBe(ChangeType.CREATE);
92
+ });
93
+
94
+ test("a dispatched task does not retry when the onSuccess publish is denied", async () => {
95
+ const ctx = makeCtx();
96
+ const change: SerializedDocumentChange = {
97
+ timestamp: "2026-01-01T00:00:00Z",
98
+ eventId: "evt-1",
99
+ fullResourceName:
100
+ "projects/test-project/databases/(default)/documents/users/doc1",
101
+ changeType: ChangeType.CREATE,
102
+ documentId: "doc1",
103
+ params: null,
104
+ data: { a: 1 },
105
+ oldData: undefined,
106
+ };
107
+ const req = {
108
+ data: change,
109
+ retryCount: 0,
110
+ } as Request<SerializedDocumentChange>;
111
+
112
+ // A rethrow here would have Cloud Tasks retry the insert past the insertId
113
+ // dedupe window and duplicate the row.
114
+ await expect(handleSyncBigQueryTask(req, ctx)).resolves.toBeUndefined();
115
+
116
+ expect(publish).toHaveBeenCalled();
117
+ expect(logger.warn).toHaveBeenCalled();
118
+ expect(vi.mocked(ctx.tracker.record)).toHaveBeenCalledTimes(1);
119
+ });
@@ -14,6 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
+ import { logger } from "firebase-functions";
17
18
  import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
18
19
 
19
20
  const { publish, channel } = vi.hoisted(() => {
@@ -96,3 +97,30 @@ describe("channel configured", () => {
96
97
  });
97
98
  });
98
99
  });
100
+
101
+ describe("publish failures", () => {
102
+ afterEach(() => {
103
+ publish.mockReset();
104
+ publish.mockResolvedValue(undefined);
105
+ });
106
+
107
+ test("a rejected publish is logged and never reaches the caller", async () => {
108
+ const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
109
+ publish.mockRejectedValue(
110
+ Object.assign(new Error("Permission denied"), { code: 403 })
111
+ );
112
+ process.env.EVENTARC_CHANNEL = "projects/p/locations/l/channels/c";
113
+ setupEventChannel();
114
+
115
+ await expect(recordStartEvent({ a: 1 })).resolves.toBeUndefined();
116
+ await expect(recordErrorEvent(new Error("boom"))).resolves.toBeUndefined();
117
+ await expect(
118
+ recordSuccessEvent({ subject: "s", data: {} })
119
+ ).resolves.toBeUndefined();
120
+ await expect(recordCompletionEvent({ a: 1 })).resolves.toBeUndefined();
121
+
122
+ // Two event types per call: the old and the new.
123
+ expect(warn).toHaveBeenCalledTimes(8);
124
+ warn.mockRestore();
125
+ });
126
+ });
@@ -332,18 +332,4 @@ describe("handleSyncBigQueryTask", () => {
332
332
  // belong to Cloud Tasks alone.
333
333
  expect(ctx.enqueue).not.toHaveBeenCalled();
334
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
335
  });
@@ -41,4 +41,22 @@ describe("firestoreLocationToFunctionRegion", () => {
41
41
  test("returns undefined for an empty location", () => {
42
42
  expect(firestoreLocationToFunctionRegion("")).toBeUndefined();
43
43
  });
44
+
45
+ test("returns undefined for a whitespace-only location", () => {
46
+ expect(firestoreLocationToFunctionRegion(" ")).toBeUndefined();
47
+ });
48
+
49
+ test.each([
50
+ ["NAM5", "us-central1"],
51
+ ["Eur3", "europe-west1"],
52
+ [" nam7 ", "us-central1"],
53
+ ])("normalizes %s before the multi-region lookup", (location, region) => {
54
+ expect(firestoreLocationToFunctionRegion(location)).toBe(region);
55
+ });
56
+
57
+ test("lowercases and trims a regional location", () => {
58
+ expect(firestoreLocationToFunctionRegion(" Europe-West2 ")).toBe(
59
+ "europe-west2"
60
+ );
61
+ });
44
62
  });
@@ -46,10 +46,14 @@ test.each([
46
46
  "bigquery.googleapis.com",
47
47
  "Mirrors data from your Cloud Firestore collection in BigQuery.",
48
48
  ],
49
+ [
50
+ "eventarcpublishing.googleapis.com",
51
+ "Publishes the extension's custom events to its Eventarc channel.",
52
+ ],
49
53
  ])("declares %s", (api, reason) => {
50
54
  expect(requiresAPI).toHaveBeenCalledWith(api, reason);
51
55
  });
52
56
 
53
- test("declares exactly the two APIs", () => {
54
- expect(requiresAPI).toHaveBeenCalledTimes(2);
57
+ test("declares exactly the 3 APIs the kit needs", () => {
58
+ expect(requiresAPI).toHaveBeenCalledTimes(3);
55
59
  });
@@ -0,0 +1,138 @@
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, beforeAll, describe, expect, test, vi } from "vitest";
18
+ import { declaredParams } from "firebase-functions/params";
19
+
20
+ const REQUIRED = [
21
+ "DATASET_LOCATION",
22
+ "BIGQUERY_PROJECT_ID",
23
+ "DATABASE",
24
+ "COLLECTION_PATH",
25
+ "DATASET_ID",
26
+ "TABLE_ID",
27
+ "VIEW_TYPE",
28
+ "USE_NEW_SNAPSHOT_QUERY_SYNTAX",
29
+ "LOG_LEVEL",
30
+ ];
31
+
32
+ const OPTIONAL = [
33
+ "DATABASE_REGION",
34
+ "BACKUP_COLLECTION",
35
+ "MAX_DISPATCHES_PER_SECOND",
36
+ "MAX_ENQUEUE_ATTEMPTS",
37
+ ];
38
+
39
+ let assertRequiredParams: (names?: ReadonlyArray<string>) => void;
40
+
41
+ beforeAll(async () => {
42
+ // Some kits resolve the instance id at import; the CLI injects it for real
43
+ // instances, so supply one before loading the module under test.
44
+ process.env.FIREBASE_KIT_INSTANCE_ID ??= "test-instance";
45
+ ({ assertRequiredParams } = await import("../src/config"));
46
+ });
47
+
48
+ afterEach(() => {
49
+ vi.unstubAllEnvs();
50
+ });
51
+
52
+ describe("assertRequiredParams", () => {
53
+ test("passes when no params have been supplied yet", () => {
54
+ expect(() => assertRequiredParams()).not.toThrow();
55
+ });
56
+
57
+ test("passes when every required param holds a value", () => {
58
+ for (const name of REQUIRED) {
59
+ vi.stubEnv(name, "set");
60
+ }
61
+
62
+ expect(() => assertRequiredParams()).not.toThrow();
63
+ });
64
+
65
+ test("rejects required params blanked in .env, naming each one", () => {
66
+ for (const name of REQUIRED) {
67
+ vi.stubEnv(name, "");
68
+ }
69
+
70
+ expect(() => assertRequiredParams()).toThrow(REQUIRED.join(", "));
71
+ });
72
+
73
+ test("rejects a whitespace-only value, which the CLI prompt accepts", () => {
74
+ vi.stubEnv(REQUIRED[0], " ");
75
+
76
+ expect(() => assertRequiredParams()).toThrow(REQUIRED[0]);
77
+ });
78
+
79
+ test("ignores optional params left blank", () => {
80
+ for (const name of OPTIONAL) {
81
+ vi.stubEnv(name, "");
82
+ }
83
+
84
+ expect(() => assertRequiredParams()).not.toThrow();
85
+ });
86
+ });
87
+
88
+ type Declaration = {
89
+ name: string;
90
+ options?: {
91
+ default?: unknown;
92
+ input?: {
93
+ text?: { nonEmpty?: boolean; validationRegex?: string | RegExp };
94
+ multiSelect?: { nonEmpty?: boolean };
95
+ };
96
+ };
97
+ };
98
+
99
+ // The CLI writes whatever a prompt resolves to into .env, an empty answer
100
+ // included, so a required param the prompt accepts empty reaches
101
+ // assertRequiredParams as a blank entry the user never typed.
102
+ function promptAcceptsEmpty({ options }: Declaration): boolean {
103
+ const fallback = options?.default;
104
+ if (fallback !== undefined && String(fallback).trim() !== "") {
105
+ return false;
106
+ }
107
+
108
+ const input = options?.input;
109
+ if (!input) {
110
+ return true;
111
+ }
112
+ if (input.multiSelect) {
113
+ return input.multiSelect.nonEmpty !== true;
114
+ }
115
+ if (!input.text) {
116
+ return false;
117
+ }
118
+ if (input.text.nonEmpty) {
119
+ return false;
120
+ }
121
+ if (input.text.validationRegex) {
122
+ return new RegExp(input.text.validationRegex).test("");
123
+ }
124
+ return true;
125
+ }
126
+
127
+ describe("required param declarations", () => {
128
+ test("the CLI prompt cannot resolve any of them to an empty value", () => {
129
+ const declarations = declaredParams as unknown as Declaration[];
130
+
131
+ for (const name of REQUIRED) {
132
+ const declaration = declarations.find((param) => param.name === name);
133
+
134
+ expect(declaration, name).toBeDefined();
135
+ expect(promptAcceptsEmpty(declaration as Declaration), name).toBe(false);
136
+ }
137
+ });
138
+ });