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

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firebase-function-kits/firestore-bigquery-export",
3
- "version": "0.0.2-rc.8",
3
+ "version": "0.1.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/firebase/extensions.git",
@@ -33,8 +33,8 @@
33
33
  "dependencies": {
34
34
  "@firebaseextensions/firestore-bigquery-change-tracker": "^2.2.1",
35
35
  "@google-cloud/bigquery": "^7.6.0",
36
- "firebase-admin": "^14.2.0",
37
- "firebase-functions": "^7.3.3-rc.0",
36
+ "firebase-admin": "^14.4.0",
37
+ "firebase-functions": "^7.4.0",
38
38
  "generate-schema": "^2.6.0",
39
39
  "lodash": "^4.17.14"
40
40
  },
package/src/config.ts CHANGED
@@ -120,17 +120,21 @@ const params = {
120
120
  "Override the default project for BigQuery instance. This can allow updates to be directed to to a BigQuery instance on another GCP project.",
121
121
 
122
122
  default: projectID,
123
+ // `required: true` in the extension, which refuses an empty answer.
124
+ input: { text: { nonEmpty: true } },
123
125
  }),
124
126
  database: defineString("DATABASE", {
125
127
  label: "Firestore Instance ID",
126
128
  description:
127
129
  'The Firestore database to use. Use "(default)" for the default database. You can view your available Firestore databases at https://console.cloud.google.com/firestore/databases.',
128
130
  default: "(default)",
129
- input: { text: { example: "(default)" } },
131
+ // `required: true` in the extension, which refuses an empty answer.
132
+ input: { text: { example: "(default)", nonEmpty: true } },
130
133
  }),
131
134
  // Declared so the CLI prompts for the value and persists it to `.env`; the
132
- // function region option cannot be a param expression, so the entry point
133
- // reads the same variable from `process.env` at module load instead.
135
+ // location to Cloud Run region lookup needs a nested ternary the CLI's CEL
136
+ // subset cannot express, so the entry point reads the same variable from
137
+ // `process.env` at module load instead.
134
138
  databaseRegion: defineString("DATABASE_REGION", {
135
139
  label: "Firestore Instance Location",
136
140
  description:
@@ -705,3 +709,46 @@ export function configFromEnv(): ExportConfig {
705
709
  maxEnqueueAttempts: optionalInt(params.maxEnqueueAttempts),
706
710
  };
707
711
  }
712
+
713
+ // Params the published extension marks `required: true`. A value the user never
714
+ // supplied is absent from process.env; one they deliberately blanked is present
715
+ // and empty. Only the second is a misconfiguration, so the guard below reads
716
+ // process.env rather than `.value()`, which reports both as "".
717
+ // DATABASE_REGION is `required: true` upstream but deliberately omitted here:
718
+ // an explicit empty value is a supported setting that leaves the function
719
+ // without a declared region, so the CLI resolves one at deploy time.
720
+ const REQUIRED_PARAMS = [
721
+ "DATASET_LOCATION",
722
+ "BIGQUERY_PROJECT_ID",
723
+ "DATABASE",
724
+ "COLLECTION_PATH",
725
+ "DATASET_ID",
726
+ "TABLE_ID",
727
+ "VIEW_TYPE",
728
+ "USE_NEW_SNAPSHOT_QUERY_SYNTAX",
729
+ "LOG_LEVEL",
730
+ ] as const;
731
+
732
+ /**
733
+ * Rejects required params that were explicitly set to an empty value.
734
+ *
735
+ * `.env` values bypass the CLI's prompt-time validation and take precedence
736
+ * over a param's declared default, so an empty entry otherwise reaches the
737
+ * handlers silently. Called at module scope so deploy-time discovery fails
738
+ * before the function ships, rather than on the first event.
739
+ */
740
+ export function assertRequiredParams(
741
+ names: ReadonlyArray<string> = REQUIRED_PARAMS
742
+ ): void {
743
+ const blank = names.filter((name) => {
744
+ const raw = process.env[name];
745
+ return raw !== undefined && raw.trim() === "";
746
+ });
747
+
748
+ if (blank.length > 0) {
749
+ throw new Error(
750
+ `Required parameters are set to an empty value: ${blank.join(", ")}. ` +
751
+ "Set them in your .env file, or remove the entries to use their defaults."
752
+ );
753
+ }
754
+ }
package/src/events.ts CHANGED
@@ -14,21 +14,33 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  import * as eventArc from "firebase-admin/eventarc";
17
+ import { logger } from "firebase-functions";
17
18
 
18
19
  const { getEventarc } = eventArc;
19
20
 
20
21
  /**
21
- * Builds the Eventarc event type for this extension.
22
+ * Generates both the OLD and NEW event types to maintain backward compatibility.
23
+ *
24
+ * Old Event Type: firebase.extensions.firestore-counter.v1.{eventName}
25
+ * New Event Type: firebase.extensions.firestore-bigquery-export.v1.{eventName}
22
26
  *
23
27
  * @param eventName The name of the event (e.g., "onStart", "onError", etc.)
24
- * @returns The event type string.
28
+ * @returns An array containing both the old and new event types
25
29
  */
26
30
  const getEventTypes = (eventName: string) => [
27
- `firebase.extensions.firestore-bigquery-export.v1.${eventName}`,
31
+ `firebase.extensions.firestore-counter.v1.${eventName}`, // OLD Event Type for backward compatibility
32
+ `firebase.extensions.firestore-bigquery-export.v1.${eventName}`, // NEW Event Type following the updated convention
28
33
  ];
29
34
 
30
35
  let eventChannel: eventArc.Channel | undefined;
31
36
 
37
+ /**
38
+ * The Eventarc channel named by `EVENTARC_CHANNEL`, or `undefined` when the
39
+ * variable is unset or blank, which disables event publishing.
40
+ */
41
+ export const configuredEventChannel = (): string | undefined =>
42
+ process.env.EVENTARC_CHANNEL?.trim() || undefined;
43
+
32
44
  /**
33
45
  * Sets up the Eventarc channel.
34
46
  *
@@ -39,28 +51,43 @@ let eventChannel: eventArc.Channel | undefined;
39
51
  * @function setupEventChannel
40
52
  */
41
53
  export const setupEventChannel = () => {
42
- eventChannel = process.env.EVENTARC_CHANNEL
43
- ? getEventarc().channel(process.env.EVENTARC_CHANNEL, {
54
+ const channel = configuredEventChannel();
55
+ eventChannel = channel
56
+ ? getEventarc().channel(channel, {
44
57
  allowedEventTypes: process.env.EXT_SELECTED_EVENTS,
45
58
  })
46
59
  : undefined;
47
60
  };
48
61
 
62
+ /**
63
+ * Publishes an event, logging and swallowing any failure.
64
+ *
65
+ * A deleted or unreachable Eventarc channel must not fail the invocation: the
66
+ * BigQuery export is the contract, event delivery is best effort.
67
+ */
68
+ const publish = async (event: eventArc.CloudEvent): Promise<void> => {
69
+ if (!eventChannel) return;
70
+
71
+ try {
72
+ await eventChannel.publish(event);
73
+ } catch (err) {
74
+ logger.warn(`Failed to publish Eventarc event ${event.type}`, err);
75
+ }
76
+ };
77
+
49
78
  /**
50
79
  * Publishes a "start" event using both OLD and NEW event types.
51
80
  *
52
81
  * @param data The payload to send with the event. Can be a string or an object.
53
- * @returns A Promise resolving when both events are published.
82
+ * @returns A Promise resolving once both publishes have been attempted.
54
83
  */
55
84
  export const recordStartEvent = async (data: string | object) => {
56
- if (!eventChannel) return Promise.resolve();
57
-
58
85
  const eventTypes = getEventTypes("onStart");
59
86
 
60
87
  // Publish events for both OLD and NEW event types
61
- return Promise.all(
88
+ await Promise.all(
62
89
  eventTypes.map((type) =>
63
- eventChannel.publish({
90
+ publish({
64
91
  type,
65
92
  data,
66
93
  })
@@ -73,17 +100,15 @@ export const recordStartEvent = async (data: string | object) => {
73
100
  *
74
101
  * @param err The Error object containing the error message.
75
102
  * @param subject (Optional) Subject identifier related to the error event.
76
- * @returns A Promise resolving when both events are published.
103
+ * @returns A Promise resolving once both publishes have been attempted.
77
104
  */
78
105
  export const recordErrorEvent = async (err: Error, subject?: string) => {
79
- if (!eventChannel) return Promise.resolve();
80
-
81
106
  const eventTypes = getEventTypes("onError");
82
107
 
83
108
  // Publish events for both OLD and NEW event types
84
- return Promise.all(
109
+ await Promise.all(
85
110
  eventTypes.map((type) =>
86
- eventChannel.publish({
111
+ publish({
87
112
  type,
88
113
  data: { message: err.message },
89
114
  subject,
@@ -98,7 +123,7 @@ export const recordErrorEvent = async (err: Error, subject?: string) => {
98
123
  * @param params An object containing the subject and the event data.
99
124
  * @param params.subject A string representing the subject of the event.
100
125
  * @param params.data The payload to send with the event.
101
- * @returns A Promise resolving when both events are published.
126
+ * @returns A Promise resolving once both publishes have been attempted.
102
127
  */
103
128
  export const recordSuccessEvent = async ({
104
129
  subject,
@@ -107,14 +132,12 @@ export const recordSuccessEvent = async ({
107
132
  subject: string;
108
133
  data: string | object;
109
134
  }) => {
110
- if (!eventChannel) return Promise.resolve();
111
-
112
135
  const eventTypes = getEventTypes("onSuccess");
113
136
 
114
137
  // Publish events for both OLD and NEW event types
115
- return Promise.all(
138
+ await Promise.all(
116
139
  eventTypes.map((type) =>
117
- eventChannel.publish({
140
+ publish({
118
141
  type,
119
142
  subject,
120
143
  data,
@@ -127,17 +150,15 @@ export const recordSuccessEvent = async ({
127
150
  * Publishes a "completion" event using both OLD and NEW event types.
128
151
  *
129
152
  * @param data The payload to send with the event. Can be a string or an object.
130
- * @returns A Promise resolving when both events are published.
153
+ * @returns A Promise resolving once both publishes have been attempted.
131
154
  */
132
155
  export const recordCompletionEvent = async (data: string | object) => {
133
- if (!eventChannel) return Promise.resolve();
134
-
135
156
  const eventTypes = getEventTypes("onCompletion");
136
157
 
137
158
  // Publish events for both OLD and NEW event types
138
- return Promise.all(
159
+ await Promise.all(
139
160
  eventTypes.map((type) =>
140
- eventChannel.publish({
161
+ publish({
141
162
  type,
142
163
  data,
143
164
  })
package/src/handlers.ts CHANGED
@@ -111,8 +111,6 @@ async function enqueueForSync(
111
111
  try {
112
112
  await ctx.enqueue(change);
113
113
  } catch (enqueueErr) {
114
- // Log before publishing: the log line is the only trace of the dropped
115
- // row, and the event publish can itself reject.
116
114
  logs.logFailedEventAction(
117
115
  "Failed to enqueue event to Cloud Tasks from onWrite handler",
118
116
  change.fullResourceName,
@@ -183,18 +181,13 @@ export async function handleDocumentWrite(
183
181
  throw err;
184
182
  }
185
183
 
186
- try {
187
- await events.recordStartEvent({
188
- documentId,
189
- changeType,
190
- before: { data: data.before.data() },
191
- after: { data: data.after.data() },
192
- context,
193
- });
194
- } catch (err) {
195
- logs.error(false, "Failed to record start event", err);
196
- throw err;
197
- }
184
+ await events.recordStartEvent({
185
+ documentId,
186
+ changeType,
187
+ before: { data: data.before.data() },
188
+ after: { data: data.after.data() },
189
+ context,
190
+ });
198
191
 
199
192
  const change: SerializedDocumentChange = {
200
193
  timestamp: context.time,
@@ -256,25 +249,19 @@ export async function handleSyncBigQueryTask(
256
249
  throw err;
257
250
  }
258
251
 
259
- try {
260
- await events.recordSuccessEvent({
261
- subject: change.documentId,
262
- data: {
263
- timestamp: change.timestamp,
264
- operation: change.changeType,
265
- documentName: change.fullResourceName,
266
- documentId: change.documentId,
267
- pathParams: change.params,
268
- eventId: change.eventId,
269
- data: change.data,
270
- oldData: change.oldData,
271
- },
272
- });
273
- } catch (err) {
274
- // The row is already in BigQuery. Rethrowing would have Cloud Tasks retry
275
- // the insert past the dedupe window and duplicate it.
276
- logs.error(false, "Failed to record success event", err as Error);
277
- }
252
+ await events.recordSuccessEvent({
253
+ subject: change.documentId,
254
+ data: {
255
+ timestamp: change.timestamp,
256
+ operation: change.changeType,
257
+ documentName: change.fullResourceName,
258
+ documentId: change.documentId,
259
+ pathParams: change.params,
260
+ eventId: change.eventId,
261
+ data: change.data,
262
+ oldData: change.oldData,
263
+ },
264
+ });
278
265
 
279
266
  logs.complete();
280
267
  }
package/src/index.ts CHANGED
@@ -38,7 +38,11 @@ import {
38
38
  afterFirstDeploy,
39
39
  afterRedeploy,
40
40
  } from "firebase-functions/v2/lifecycle";
41
- import { CONFIG_EXPRESSIONS, configFromEnv } from "./config";
41
+ import {
42
+ assertRequiredParams,
43
+ CONFIG_EXPRESSIONS,
44
+ configFromEnv,
45
+ } from "./config";
42
46
  import * as events from "./events";
43
47
  import {
44
48
  DEFAULT_MAX_DISPATCHES_PER_SECOND,
@@ -56,6 +60,7 @@ import * as logs from "./logs";
56
60
  import { firestoreLocationToFunctionRegion } from "./region";
57
61
  import { enqueueSyncTask } from "./tasks";
58
62
 
63
+ assertRequiredParams();
59
64
  // Re-export the side-effect-free library surface (handlers and config types).
60
65
  export * from "./lib";
61
66
 
@@ -99,6 +104,15 @@ for (const { api, reason } of REQUIRED_APIS) {
99
104
  requiresAPI(api, reason);
100
105
  }
101
106
 
107
+ // Declining a `requiresAPI` prompt aborts the deploy, and nothing publishes without a channel.
108
+ if (events.configuredEventChannel()) {
109
+ requiresRole("roles/eventarc.publisher");
110
+ requiresAPI(
111
+ "eventarcpublishing.googleapis.com",
112
+ "Publishes the extension's custom events to its Eventarc channel."
113
+ );
114
+ }
115
+
102
116
  afterFirstDeploy({
103
117
  task: { function: INIT_BIGQUERY_SYNC_FUNCTION, body: { data: {} } },
104
118
  });
@@ -142,8 +156,9 @@ function getHandlerContext(): HandlerContext {
142
156
 
143
157
  /*
144
158
  * Read at module load: the CLI populates `.env` values into the discovery
145
- * process env (firebase-tools >= 15.28.0), and the region option cannot be a
146
- * param expression. When unset, no function declares a region and the CLI
159
+ * process env (firebase-tools >= 15.28.0), and the location to Cloud Run region
160
+ * lookup needs a nested ternary the CLI's CEL subset cannot express. When
161
+ * unset, no function declares a region and the CLI
147
162
  * falls back to its default. The Eventarc trigger region needs no handling:
148
163
  * the CLI pins it to the database's own region regardless of where the
149
164
  * function runs.
@@ -152,6 +167,33 @@ const functionRegion = firestoreLocationToFunctionRegion(
152
167
  process.env.DATABASE_REGION
153
168
  );
154
169
 
170
+ /** Region placement shared by every function; empty when `DATABASE_REGION` is unset. */
171
+ const REGION_OPTION = functionRegion
172
+ ? ({ region: functionRegion } as const)
173
+ : {};
174
+
175
+ /** Options of the Firestore trigger, matching the extension's deployed trigger. */
176
+ const EVENT_FUNCTION_OPTIONS = {
177
+ ...REGION_OPTION,
178
+ concurrency: 1,
179
+ cpu: "gcf_gen1",
180
+ ingressSettings: "ALLOW_INTERNAL_ONLY",
181
+ } as const;
182
+
183
+ /** Options shared by the task-queue functions, matching the extension's 1st gen task functions. */
184
+ const TASK_FUNCTION_OPTIONS = {
185
+ ...REGION_OPTION,
186
+ concurrency: 1,
187
+ cpu: "gcf_gen1",
188
+ timeoutSeconds: 540,
189
+ } as const;
190
+
191
+ /** Options of the two lifecycle tasks, which share one retry config. */
192
+ const LIFECYCLE_TASK_OPTIONS = {
193
+ ...TASK_FUNCTION_OPTIONS,
194
+ retryConfig: LIFECYCLE_RETRY_CONFIG,
195
+ } as const;
196
+
155
197
  /**
156
198
  * Firestore trigger: streams document writes on the watched collection into the
157
199
  * BigQuery changelog table. A failed inline write buffers through the
@@ -161,7 +203,7 @@ const functionRegion = firestoreLocationToFunctionRegion(
161
203
  */
162
204
  export const fsexportbigquery = onDocumentWritten(
163
205
  {
164
- ...(functionRegion ? { region: functionRegion } : {}),
206
+ ...EVENT_FUNCTION_OPTIONS,
165
207
  document: expr`${CONFIG_EXPRESSIONS.collectionPath}/{documentId}`,
166
208
  database: CONFIG_EXPRESSIONS.database,
167
209
  },
@@ -173,12 +215,15 @@ export const fsexportbigquery = onDocumentWritten(
173
215
  * Tasks' schedule (5 attempts, 60s minimum backoff, dispatch-throttled by
174
216
  * `MAX_DISPATCHES_PER_SECOND`). After the last attempt the task is dropped;
175
217
  * by then the tracker has written the row to `BACKUP_COLLECTION` on every
176
- * terminal insert failure, when that collection is configured.
218
+ * terminal insert failure, when that collection is configured. A task refused
219
+ * with 429s at the instance ceiling never runs the handler, so no backup row
220
+ * is written for it.
177
221
  */
178
222
  export const syncBigQuery = onTaskDispatched<SerializedDocumentChange>(
179
223
  {
180
- ...(functionRegion ? { region: functionRegion } : {}),
224
+ ...TASK_FUNCTION_OPTIONS,
181
225
  retryConfig: SYNC_RETRY_CONFIG,
226
+ maxInstances: SYNC_MAX_CONCURRENT_DISPATCHES,
182
227
  rateLimits: {
183
228
  maxConcurrentDispatches: SYNC_MAX_CONCURRENT_DISPATCHES, // A blank .env value reaches this deploy-time expression as 0, which
184
229
  // Cloud Tasks would not accept; runtime falls back to the same default.
@@ -212,10 +257,7 @@ async function handleBigQuerySyncInitialization(): Promise<void> {
212
257
  * authenticated HTTP POST, without queue retries.
213
258
  */
214
259
  export const initBigQuerySync = onTaskDispatched(
215
- {
216
- ...(functionRegion ? { region: functionRegion } : {}),
217
- retryConfig: LIFECYCLE_RETRY_CONFIG,
218
- },
260
+ LIFECYCLE_TASK_OPTIONS,
219
261
  handleBigQuerySyncInitialization
220
262
  );
221
263
 
@@ -224,9 +266,6 @@ export const initBigQuerySync = onTaskDispatched(
224
266
  * so BigQuery resources are reconciled after parameter changes.
225
267
  */
226
268
  export const setupBigQuerySync = onTaskDispatched(
227
- {
228
- ...(functionRegion ? { region: functionRegion } : {}),
229
- retryConfig: LIFECYCLE_RETRY_CONFIG,
230
- },
269
+ LIFECYCLE_TASK_OPTIONS,
231
270
  handleBigQuerySyncInitialization
232
271
  );
package/src/region.ts CHANGED
@@ -24,14 +24,17 @@ const MULTI_REGION_TO_FUNCTION_REGION: Record<string, string> = {
24
24
 
25
25
  /**
26
26
  * Maps a Firestore database location to the Cloud Run region the functions
27
- * should deploy to. Regional locations pass through unchanged; an unset or
28
- * empty location returns `undefined`, meaning the functions declare no region.
27
+ * should deploy to. The lookup is case-insensitive and ignores surrounding
28
+ * whitespace, as the CLI's own region handling is. Regional locations pass
29
+ * through lowercased; an unset or blank location returns `undefined`, meaning
30
+ * the functions declare no region.
29
31
  */
30
32
  export function firestoreLocationToFunctionRegion(
31
33
  location: string | undefined
32
34
  ): string | undefined {
33
- if (!location) {
35
+ const normalized = location?.trim().toLowerCase();
36
+ if (!normalized) {
34
37
  return undefined;
35
38
  }
36
- return MULTI_REGION_TO_FUNCTION_REGION[location] ?? location;
39
+ return MULTI_REGION_TO_FUNCTION_REGION[normalized] ?? normalized;
37
40
  }
@@ -0,0 +1,43 @@
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 { declaredParams } from "firebase-functions/params";
18
+ import { describe, expect, test } from "vitest";
19
+ import "../src/config";
20
+
21
+ // config.test.ts fakes firebase-functions/params and drops the declaration
22
+ // options, so these cases read the real declarations instead.
23
+ function text(name: string): Record<string, unknown> {
24
+ const param = declaredParams.find((candidate) => candidate.name === name) as
25
+ | { options?: { input?: { text?: Record<string, unknown> } } }
26
+ | undefined;
27
+
28
+ return param?.options?.input?.text ?? {};
29
+ }
30
+
31
+ /**
32
+ * Compatibility requirement: extension.yaml marks both params `required: true`,
33
+ * so the extension's installer refuses an empty answer and re-prompts. The CLI
34
+ * enforces that for a kit only when the declaration says `nonEmpty`.
35
+ */
36
+ describe("params the extension marks required", () => {
37
+ test.each(["BIGQUERY_PROJECT_ID", "DATABASE"])(
38
+ "%s refuses an empty value at the prompt",
39
+ (name) => {
40
+ expect(text(name).nonEmpty).toBe(true);
41
+ }
42
+ );
43
+ });
@@ -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
+ });