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

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.12",
3
+ "version": "0.0.2-rc.14",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/firebase/extensions.git",
@@ -33,6 +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.4.0",
37
+ "firebase-functions": "^7.4.0",
36
38
  "generate-schema": "^2.6.0",
37
39
  "lodash": "^4.17.14"
38
40
  },
@@ -40,16 +42,5 @@
40
42
  "@firebaseextensions/firestore-bigquery-change-tracker": {
41
43
  "firebase-functions": "$firebase-functions"
42
44
  }
43
- },
44
- "devDependencies": {
45
- "@types/lodash": "^4.17.0",
46
- "firebase-admin": "^14.4.0",
47
- "firebase-functions": "^7.3.3-rc.3",
48
- "typescript": "^5.9.3",
49
- "vitest": "^3.2.4"
50
- },
51
- "peerDependencies": {
52
- "firebase-admin": "^14.3.0",
53
- "firebase-functions": "^7.3.3-rc.3"
54
45
  }
55
46
  }
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,6 +14,7 @@
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
 
@@ -50,21 +51,35 @@ export const setupEventChannel = () => {
50
51
  : undefined;
51
52
  };
52
53
 
54
+ /**
55
+ * Publishes an event, logging and swallowing any failure.
56
+ *
57
+ * A deleted or unreachable Eventarc channel must not fail the invocation: the
58
+ * BigQuery export is the contract, event delivery is best effort.
59
+ */
60
+ const publish = async (event: eventArc.CloudEvent): Promise<void> => {
61
+ if (!eventChannel) return;
62
+
63
+ try {
64
+ await eventChannel.publish(event);
65
+ } catch (err) {
66
+ logger.warn(`Failed to publish Eventarc event ${event.type}`, err);
67
+ }
68
+ };
69
+
53
70
  /**
54
71
  * Publishes a "start" event using both OLD and NEW event types.
55
72
  *
56
73
  * @param data The payload to send with the event. Can be a string or an object.
57
- * @returns A Promise resolving when both events are published.
74
+ * @returns A Promise resolving once both publishes have been attempted.
58
75
  */
59
76
  export const recordStartEvent = async (data: string | object) => {
60
- if (!eventChannel) return Promise.resolve();
61
-
62
77
  const eventTypes = getEventTypes("onStart");
63
78
 
64
79
  // Publish events for both OLD and NEW event types
65
- return Promise.all(
80
+ await Promise.all(
66
81
  eventTypes.map((type) =>
67
- eventChannel.publish({
82
+ publish({
68
83
  type,
69
84
  data,
70
85
  })
@@ -77,17 +92,15 @@ export const recordStartEvent = async (data: string | object) => {
77
92
  *
78
93
  * @param err The Error object containing the error message.
79
94
  * @param subject (Optional) Subject identifier related to the error event.
80
- * @returns A Promise resolving when both events are published.
95
+ * @returns A Promise resolving once both publishes have been attempted.
81
96
  */
82
97
  export const recordErrorEvent = async (err: Error, subject?: string) => {
83
- if (!eventChannel) return Promise.resolve();
84
-
85
98
  const eventTypes = getEventTypes("onError");
86
99
 
87
100
  // Publish events for both OLD and NEW event types
88
- return Promise.all(
101
+ await Promise.all(
89
102
  eventTypes.map((type) =>
90
- eventChannel.publish({
103
+ publish({
91
104
  type,
92
105
  data: { message: err.message },
93
106
  subject,
@@ -102,7 +115,7 @@ export const recordErrorEvent = async (err: Error, subject?: string) => {
102
115
  * @param params An object containing the subject and the event data.
103
116
  * @param params.subject A string representing the subject of the event.
104
117
  * @param params.data The payload to send with the event.
105
- * @returns A Promise resolving when both events are published.
118
+ * @returns A Promise resolving once both publishes have been attempted.
106
119
  */
107
120
  export const recordSuccessEvent = async ({
108
121
  subject,
@@ -111,14 +124,12 @@ export const recordSuccessEvent = async ({
111
124
  subject: string;
112
125
  data: string | object;
113
126
  }) => {
114
- if (!eventChannel) return Promise.resolve();
115
-
116
127
  const eventTypes = getEventTypes("onSuccess");
117
128
 
118
129
  // Publish events for both OLD and NEW event types
119
- return Promise.all(
130
+ await Promise.all(
120
131
  eventTypes.map((type) =>
121
- eventChannel.publish({
132
+ publish({
122
133
  type,
123
134
  subject,
124
135
  data,
@@ -131,17 +142,15 @@ export const recordSuccessEvent = async ({
131
142
  * Publishes a "completion" event using both OLD and NEW event types.
132
143
  *
133
144
  * @param data The payload to send with the event. Can be a string or an object.
134
- * @returns A Promise resolving when both events are published.
145
+ * @returns A Promise resolving once both publishes have been attempted.
135
146
  */
136
147
  export const recordCompletionEvent = async (data: string | object) => {
137
- if (!eventChannel) return Promise.resolve();
138
-
139
148
  const eventTypes = getEventTypes("onCompletion");
140
149
 
141
150
  // Publish events for both OLD and NEW event types
142
- return Promise.all(
151
+ await Promise.all(
143
152
  eventTypes.map((type) =>
144
- eventChannel.publish({
153
+ publish({
145
154
  type,
146
155
  data,
147
156
  })
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
 
@@ -94,6 +99,10 @@ const REQUIRED_APIS = [
94
99
  api: "bigquery.googleapis.com",
95
100
  reason: "Mirrors data from your Cloud Firestore collection in BigQuery.",
96
101
  },
102
+ {
103
+ api: "eventarcpublishing.googleapis.com",
104
+ reason: "Publishes the extension's custom events to its Eventarc channel.",
105
+ },
97
106
  ] as const;
98
107
 
99
108
  for (const role of REQUIRED_ROLES) {
@@ -147,8 +156,9 @@ function getHandlerContext(): HandlerContext {
147
156
 
148
157
  /*
149
158
  * Read at module load: the CLI populates `.env` values into the discovery
150
- * process env (firebase-tools >= 15.28.0), and the region option cannot be a
151
- * 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
152
162
  * falls back to its default. The Eventarc trigger region needs no handling:
153
163
  * the CLI pins it to the database's own region regardless of where the
154
164
  * function runs.
@@ -157,6 +167,33 @@ const functionRegion = firestoreLocationToFunctionRegion(
157
167
  process.env.DATABASE_REGION
158
168
  );
159
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
+
160
197
  /**
161
198
  * Firestore trigger: streams document writes on the watched collection into the
162
199
  * BigQuery changelog table. A failed inline write buffers through the
@@ -166,7 +203,7 @@ const functionRegion = firestoreLocationToFunctionRegion(
166
203
  */
167
204
  export const fsexportbigquery = onDocumentWritten(
168
205
  {
169
- ...(functionRegion ? { region: functionRegion } : {}),
206
+ ...EVENT_FUNCTION_OPTIONS,
170
207
  document: expr`${CONFIG_EXPRESSIONS.collectionPath}/{documentId}`,
171
208
  database: CONFIG_EXPRESSIONS.database,
172
209
  },
@@ -178,12 +215,15 @@ export const fsexportbigquery = onDocumentWritten(
178
215
  * Tasks' schedule (5 attempts, 60s minimum backoff, dispatch-throttled by
179
216
  * `MAX_DISPATCHES_PER_SECOND`). After the last attempt the task is dropped;
180
217
  * by then the tracker has written the row to `BACKUP_COLLECTION` on every
181
- * 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.
182
221
  */
183
222
  export const syncBigQuery = onTaskDispatched<SerializedDocumentChange>(
184
223
  {
185
- ...(functionRegion ? { region: functionRegion } : {}),
224
+ ...TASK_FUNCTION_OPTIONS,
186
225
  retryConfig: SYNC_RETRY_CONFIG,
226
+ maxInstances: SYNC_MAX_CONCURRENT_DISPATCHES,
187
227
  rateLimits: {
188
228
  maxConcurrentDispatches: SYNC_MAX_CONCURRENT_DISPATCHES, // A blank .env value reaches this deploy-time expression as 0, which
189
229
  // Cloud Tasks would not accept; runtime falls back to the same default.
@@ -217,10 +257,7 @@ async function handleBigQuerySyncInitialization(): Promise<void> {
217
257
  * authenticated HTTP POST, without queue retries.
218
258
  */
219
259
  export const initBigQuerySync = onTaskDispatched(
220
- {
221
- ...(functionRegion ? { region: functionRegion } : {}),
222
- retryConfig: LIFECYCLE_RETRY_CONFIG,
223
- },
260
+ LIFECYCLE_TASK_OPTIONS,
224
261
  handleBigQuerySyncInitialization
225
262
  );
226
263
 
@@ -229,9 +266,6 @@ export const initBigQuerySync = onTaskDispatched(
229
266
  * so BigQuery resources are reconciled after parameter changes.
230
267
  */
231
268
  export const setupBigQuerySync = onTaskDispatched(
232
- {
233
- ...(functionRegion ? { region: functionRegion } : {}),
234
- retryConfig: LIFECYCLE_RETRY_CONFIG,
235
- },
269
+ LIFECYCLE_TASK_OPTIONS,
236
270
  handleBigQuerySyncInitialization
237
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
+ });
@@ -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
  });