@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.0 → 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 +5 -1
  2. package/README.md +281 -60
  3. package/lib/config.d.ts +3 -2
  4. package/lib/config.d.ts.map +1 -1
  5. package/lib/config.js +295 -70
  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 +6396 -0
  43. package/package.json +15 -5
  44. package/src/config.ts +359 -72
  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
package/CHANGELOG.md CHANGED
@@ -1 +1,5 @@
1
- - Initial release
1
+ - fix: `USE_NEW_SNAPSHOT_QUERY_SYNTAX` and `EXCLUDE_OLD_DATA` take the extension's `yes` / `no` values again, so a config exported from the extension works unchanged. `WILDCARD_IDS` is unchanged: the extension already used `true` / `false` there.
2
+ - feat: reinstate the extension's Cloud Tasks write buffer. A failed inline BigQuery write now enqueues onto a new `syncBigQuery` task queue (5 attempts, 60s minimum backoff, throttled by the restored `MAX_DISPATCHES_PER_SECOND` param, default 100) instead of replaying the Firestore event through Eventarc redelivery for up to 24 hours; `MAX_ENQUEUE_ATTEMPTS` (default 3) is also back. The `onSuccess` event returns with the queue handler. Two behavior changes against earlier release candidates: a row that exhausts the queue is dropped unless `BACKUP_COLLECTION` is set (extension parity - the tracker backs the row up on every terminal insert failure, so configure a backup collection), and deleting or moving the functions can leave the Cloud Tasks queue behind. A failed enqueue is logged at error level, published as an `onError` event, and dropped, as in the extension; the trigger no longer declares `retry: true`, so nothing is redelivered through Eventarc. Export the new `syncBigQuery` function from your codebase entry, and deploy with Firebase CLI 15.28.0+ so the trigger can address its own queue (`FIREBASE_KIT_INSTANCE_ID`); requires firebase-admin 14.2.0+.
3
+ - fix: restore explicit function placement from `DATABASE_REGION`, now with the Firestore-location-to-Cloud-Run-region mapping. The `DATABASE_REGION` parameter is back and all three functions deploy to the region derived from it: regional locations pass through unchanged, and the multi-region locations map to a Cloud Run region (`nam5`/`nam7` to `us-central1`, `eur3` to `europe-west1`) instead of failing the deploy. With the parameter unset the functions still declare no region and the CLI falls back as before (`us-central1` by default, `FIREBASE_FUNCTIONS_DEFAULT_REGION` to override). Placement requires firebase-tools >= 15.28.0 (older CLIs do not load `.env` at discovery and keep the fallback). If your `.env` already carries `DATABASE_REGION` from an extension migration, upgrading to this version moves the functions to the mapped region on your next deploy, which deletes and recreates them.
4
+ - fix: stop deploying functions to the `DATABASE_REGION` value. Firestore multi-region locations (`eur3`, `nam5`, `nam7`) are not Cloud Run regions, so any multi-region database made every deploy fail. The `DATABASE_REGION` parameter is removed; the functions now declare no region and deploy to `us-central1` by default (set `FIREBASE_FUNCTIONS_DEFAULT_REGION` when deploying to choose another region), while the Firestore trigger is always pinned to the database's own region. `ExportConfig.location` is removed from the library surface.
5
+ - Initial release of kit, see README for differences between the legacy extension and this kit
package/README.md CHANGED
@@ -1,18 +1,19 @@
1
- # @firebase/firestore-bigquery-export
1
+ # @firebase-function-kits/firestore-bigquery-export
2
2
 
3
3
  Stream a Cloud Firestore collection to BigQuery. This is the Stream Firestore to
4
4
  BigQuery Firebase Extension as an npm package you add to your own Firebase
5
5
  Functions codebase and deploy.
6
6
 
7
7
  It listens for document writes on a collection, serializes each change, and
8
- writes it to a BigQuery changelog table. Failed writes are retried through a
9
- Firebase Functions runtime retry policy. The functions run in your own Firebase
10
- project; there is no hosted version, so you deploy them yourself.
8
+ writes it to a BigQuery changelog table. Failed writes buffer through a Cloud
9
+ Tasks queue (`syncBigQuery`), which retries them on its own throttled schedule.
10
+ The functions run in your own Firebase project; there is no hosted version, so
11
+ you deploy them yourself.
11
12
 
12
13
  ## Install
13
14
 
14
15
  ```sh
15
- npm install @firebase/firestore-bigquery-export
16
+ npm install @firebase-function-kits/firestore-bigquery-export
16
17
  ```
17
18
 
18
19
  ## Required IAM
@@ -23,14 +24,15 @@ below, enables the listed APIs, and attaches the account to every function in
23
24
  this kit. Do not set a custom runtime service account for this codebase — it
24
25
  conflicts with that automatic setup.
25
26
 
26
- | Role / API | Why |
27
- |---|---|
28
- | `roles/bigquery.dataEditor` | create dataset/table/views; insert rows |
29
- | `roles/bigquery.user` | run BigQuery jobs and materialized views |
30
- | `roles/datastore.user` | write failed-row records back to Firestore (only if you configure a backup collection) |
31
- | `roles/eventarc.eventReceiver` | receive Gen2 Firestore trigger events |
32
- | `roles/run.invoker` | allow Eventarc to invoke the Gen2 Cloud Run service |
33
- | `bigquery.googleapis.com` | mirror Firestore collection changes in BigQuery |
27
+ | Role / API | Why |
28
+ | ------------------------------ | -------------------------------------------------------------------------------------- |
29
+ | `roles/bigquery.dataEditor` | create dataset/table/views; insert rows |
30
+ | `roles/bigquery.user` | run BigQuery jobs and materialized views |
31
+ | `roles/datastore.user` | write failed-row records back to Firestore (only if you configure a backup collection) |
32
+ | `roles/eventarc.eventReceiver` | receive Gen2 Firestore trigger events |
33
+ | `roles/run.invoker` | allow Eventarc to invoke the Gen2 Cloud Run service |
34
+ | `roles/cloudtasks.enqueuer` | enqueue failed writes onto the kit's own `syncBigQuery` task queue |
35
+ | `bigquery.googleapis.com` | mirror Firestore collection changes in BigQuery |
34
36
 
35
37
  If the dataset lives in a different project (`BIGQUERY_PROJECT_ID`), grant the
36
38
  managed runtime service account the `bigquery.*` roles on that project. For a
@@ -38,15 +40,16 @@ CMEK dataset, also grant the BigQuery service account access to your KMS key.
38
40
 
39
41
  ## Usage
40
42
 
41
- Export the three functions from your functions codebase entry:
43
+ Export the four functions from your functions codebase entry:
42
44
 
43
45
  ```ts
44
46
  // functions/src/index.ts
45
47
  export {
46
48
  fsexportbigquery,
49
+ syncBigQuery,
47
50
  initBigQuerySync,
48
51
  setupBigQuerySync,
49
- } from "@firebase/firestore-bigquery-export";
52
+ } from "@firebase-function-kits/firestore-bigquery-export";
50
53
  ```
51
54
 
52
55
  and configure them with a `.env` (or `.env.<projectId>`):
@@ -59,6 +62,7 @@ DATABASE_REGION=europe-west2
59
62
  ```
60
63
 
61
64
  - `fsexportbigquery` is the Firestore trigger.
65
+ - `syncBigQuery` is the write-buffer task queue that retries failed writes.
62
66
  - `initBigQuerySync` is the first-deploy provisioning lifecycle task.
63
67
  - `setupBigQuerySync` is the reconfigure provisioning lifecycle task.
64
68
 
@@ -87,8 +91,15 @@ later, behind the `kits` experiment):
87
91
  `instances` maps each instance id to the directory (relative to
88
92
  `firebase.json`) holding that instance's `.env`. The CLI prefixes every
89
93
  function and task queue name with `kit-<instance id>-`, so the functions above
90
- deploy as `kit-default-fsexportbigquery`, `kit-default-initBigQuerySync`, and
91
- `kit-default-setupBigQuerySync`.
94
+ deploy as `kit-default-fsexportbigquery`, `kit-default-syncBigQuery`,
95
+ `kit-default-initBigQuerySync`, and `kit-default-setupBigQuerySync`.
96
+
97
+ Deploy with Firebase CLI 15.28.0 or later: it sets the
98
+ `FIREBASE_KIT_INSTANCE_ID` env var on the deployed functions, which the trigger
99
+ needs to address its own `syncBigQuery` queue. On functions deployed with an
100
+ older CLI, enqueues fail (logged at error level and published as an `onError`
101
+ event; the event is dropped, as in the extension) until you redeploy with a
102
+ newer CLI.
92
103
 
93
104
  ```sh
94
105
  firebase experiments:enable kits
@@ -103,30 +114,34 @@ Set these values in a `.env` (or `.env.<projectId>`) file. The Firebase CLI
103
114
  loads them at deploy time and prompts for any required values that are missing.
104
115
  `PROJECT_ID` is supplied by the Firebase CLI.
105
116
 
106
- | Field | Env var | Required | Default | Description |
107
- |---|---|---|---|---|
108
- | `collectionPath` | `COLLECTION_PATH` | no | `posts` | Collection or collection-group path |
109
- | `datasetId` | `DATASET_ID` | no | `firestore_export` | BigQuery dataset |
110
- | `tableId` | `TABLE_ID` | no | `posts` | BigQuery changelog table |
111
- | `databaseRegion` | `DATABASE_REGION` | yes | — | Region for the trigger and queues |
112
- | `datasetLocation` | `DATASET_LOCATION` | no | `us` | BigQuery dataset location |
113
- | `database` | `DATABASE` | no | `(default)` | Firestore database id |
114
- | `bigqueryProjectId` | `BIGQUERY_PROJECT_ID` | no | project id | Dataset project, if different |
115
- | `backupCollection` | `BACKUP_COLLECTION` | no | (empty) | Firestore collection for failed rows |
116
- | `transformFunction` | `TRANSFORM_FUNCTION` | no | (empty) | Optional transform Cloud Function |
117
- | `tablePartitioning` | `TABLE_PARTITIONING` | no | `NONE` | Table partitioning strategy |
118
- | `timePartitioningField` | `TIME_PARTITIONING_FIELD` | no | (empty) | Time-partitioning column name |
119
- | `timePartitioningFieldType` | `TIME_PARTITIONING_FIELD_TYPE` | no | `omit` | Time-partitioning field type |
120
- | `timePartitioningFirestoreField` | `TIME_PARTITIONING_FIRESTORE_FIELD` | no | (empty) | Firestore field for partitioning |
121
- | `clustering` | `CLUSTERING` | no | (empty) | Clustering columns (max 4) |
122
- | `wildcardIds` | `WILDCARD_IDS` | no | `false` | Store path-param values as columns |
123
- | `useNewSnapshotQuerySyntax` | `USE_NEW_SNAPSHOT_QUERY_SYNTAX` | no | `false` | Use newer snapshot query syntax |
124
- | `excludeOldData` | `EXCLUDE_OLD_DATA` | no | `false` | Skip previous document state on updates |
125
- | `viewType` | `VIEW_TYPE` | no | `view` | `view`, `materialized_incremental`, `materialized_non_incremental` |
126
- | `maxStaleness` | `MAX_STALENESS` | no | (empty) | Materialized view max staleness |
127
- | `refreshIntervalMinutes` | `REFRESH_INTERVAL_MINUTES` | no | (empty) | Materialized view refresh interval |
128
- | `kmsKeyName` | `KMS_KEY_NAME` | no | (empty) | CMEK key for the dataset |
129
- | `logLevel` | `LOG_LEVEL` | no | `info` | `debug`, `info`, `warn`, `error`, `silent` |
117
+ | Field | Env var | Required | Default | Description |
118
+ | -------------------------------- | ----------------------------------- | -------- | ------------------ | ------------------------------------------------------------------ |
119
+ | `collectionPath` | `COLLECTION_PATH` | no | `posts` | Collection or collection-group path |
120
+ | `datasetId` | `DATASET_ID` | no | `firestore_export` | BigQuery dataset |
121
+ | `tableId` | `TABLE_ID` | no | `posts` | BigQuery changelog table |
122
+ | `databaseRegion` | `DATABASE_REGION` | yes | (prompted) | Firestore database location; also places the functions |
123
+ | `datasetLocation` | `DATASET_LOCATION` | no | `us` | BigQuery dataset location |
124
+ | `database` | `DATABASE` | no | `(default)` | Firestore database id |
125
+ | `bigqueryProjectId` | `BIGQUERY_PROJECT_ID` | no | project id | Dataset project, if different |
126
+ | `backupCollection` | `BACKUP_COLLECTION` | no | (empty) | Strongly recommended: collection for rows whose BigQuery insert failed |
127
+ | `maxDispatchesPerSecond` | `MAX_DISPATCHES_PER_SECOND` | no | `100` | `syncBigQuery` queue dispatch rate (1-500) |
128
+ | `maxEnqueueAttempts` | `MAX_ENQUEUE_ATTEMPTS` | no | `3` | In-process enqueue attempts before giving up (1-10) |
129
+ | `transformFunction` | `TRANSFORM_FUNCTION` | no | (empty) | Optional transform Cloud Function |
130
+ | `tablePartitioning` | `TABLE_PARTITIONING` | no | `NONE` | Table partitioning strategy |
131
+ | `timePartitioningField` | `TIME_PARTITIONING_FIELD` | no | (empty) | Time-partitioning column name |
132
+ | `timePartitioningFieldType` | `TIME_PARTITIONING_FIELD_TYPE` | no | `omit` | Time-partitioning field type |
133
+ | `timePartitioningFirestoreField` | `TIME_PARTITIONING_FIRESTORE_FIELD` | no | (empty) | Firestore field for partitioning |
134
+ | `clustering` | `CLUSTERING` | no | (empty) | Clustering columns (max 4) |
135
+ | `wildcardIds` | `WILDCARD_IDS` | no | `false` | Store path-param values as columns |
136
+ | `useNewSnapshotQuerySyntax` | `USE_NEW_SNAPSHOT_QUERY_SYNTAX` | no | `no` | Use newer snapshot query syntax (`yes` / `no`) |
137
+ | `excludeOldData` | `EXCLUDE_OLD_DATA` | no | `no` | Skip previous document state on updates (`yes` / `no`) |
138
+ | `viewType` | `VIEW_TYPE` | no | `view` | `view`, `materialized_incremental`, `materialized_non_incremental` |
139
+ | `maxStaleness` | `MAX_STALENESS` | no | (empty) | Materialized view max staleness |
140
+ | `refreshIntervalMinutes` | `REFRESH_INTERVAL_MINUTES` | no | (empty) | Materialized view refresh interval |
141
+ | `kmsKeyName` | `KMS_KEY_NAME` | no | (empty) | CMEK key for the dataset |
142
+ | `logLevel` | `LOG_LEVEL` | no | `info` | `debug`, `info`, `warn`, `error`, `silent` |
143
+ | (env only) | `EVENTARC_CHANNEL` | no | (empty) | Eventarc channel to publish lifecycle events on; unset disables events |
144
+ | (env only) | `EXT_SELECTED_EVENTS` | no | (empty) | Comma-separated allowlist of event types to publish (see Events) |
130
145
 
131
146
  ## Multiple instances
132
147
 
@@ -154,9 +169,19 @@ the instances cannot collide.
154
169
 
155
170
  ## Events
156
171
 
157
- When `EVENTARC_CHANNEL` is configured, the function publishes lifecycle events
158
- such as `onStart`, `onError`, `onSuccess`, and `onCompletion` under
159
- `firebase.extensions.firestore-bigquery-export.v1.*`.
172
+ When `EVENTARC_CHANNEL` is configured, the functions publish lifecycle events
173
+ under `firebase.extensions.firestore-bigquery-export.v1.*`: `onStart` and
174
+ `onError` from the write path, and `onSuccess` from the `syncBigQuery` task
175
+ when a buffered write lands (matching the extension, which only emitted
176
+ `onSuccess` from its queue handler).
177
+
178
+ Publishing is filtered by `EXT_SELECTED_EVENTS`: the value is split on commas
179
+ and only exactly matching event types are published, silently. An empty value
180
+ suppresses every event, and a value carrying only another product's types
181
+ (the extension offered more than one namespace to tick) publishes nothing. A
182
+ config exported from the extension brings its `EXT_SELECTED_EVENTS` along, so
183
+ check it lists the `firebase.extensions.firestore-bigquery-export.v1.*` types
184
+ you expect, `onSuccess` included.
160
185
 
161
186
  ## Provisioning
162
187
 
@@ -176,7 +201,11 @@ queues, matching the extension's install vs update/configure split.
176
201
 
177
202
  If automatic post-deploy enqueue did not run, enqueue a task yourself. The
178
203
  snippets below use the `default` instance; substitute your instance id in the
179
- `kit-<instance id>-` prefix if you named yours differently. Prefer
204
+ `kit-<instance id>-` prefix if you named yours differently, and set
205
+ `FUNCTION_REGION` to the task functions' region: your `DATABASE_REGION`, with
206
+ `nam5`/`nam7` mapped to `us-central1` and `eur3` to `europe-west1`, or
207
+ `us-central1` if `DATABASE_REGION` is unset and you did not override the
208
+ deploy region. Prefer
180
209
  `initBigQuerySync` after a first deploy and `setupBigQuerySync` after a
181
210
  redeploy or schema-related config change (`TABLE_PARTITIONING`, `CLUSTERING`,
182
211
  `WILDCARD_IDS`, `VIEW_TYPE`, and related fields).
@@ -187,7 +216,7 @@ const { initializeApp } = require("firebase-admin/app");
187
216
  const { getFunctions } = require("firebase-admin/functions");
188
217
  initializeApp();
189
218
  getFunctions()
190
- .taskQueue("locations/'"$DATABASE_REGION"'/functions/kit-default-initBigQuerySync")
219
+ .taskQueue("locations/'"$FUNCTION_REGION"'/functions/kit-default-initBigQuerySync")
191
220
  .enqueue({})
192
221
  .then(() => console.log("init task enqueued"));
193
222
  '
@@ -203,29 +232,221 @@ failure is not retried:
203
232
 
204
233
  ```sh
205
234
  URL=$(gcloud functions describe kit-default-initBigQuerySync \
206
- --region "$DATABASE_REGION" --gen2 --format='value(url)')
235
+ --region "$FUNCTION_REGION" --gen2 --format='value(url)')
207
236
 
208
237
  curl -fsS -X POST -H "Content-Type: application/json" -d '{"data":{}}' \
209
238
  -H "Authorization: Bearer $(gcloud auth print-identity-token --audiences="$URL")" "$URL"
210
239
  ```
211
240
 
212
241
  The Firestore write path never provisions on the hot path. If resources are
213
- missing when a write arrives, the inline write fails, the handler calls
214
- `ensureInitialized()` once as a self-heal and retries the write, and a remaining
215
- failure is surfaced to the function runtime retry policy (`retry: true` on
216
- `fsexportbigquery`).
242
+ missing when a write arrives, the inline write fails and the change buffers
243
+ through the `syncBigQuery` queue, which re-attempts the write on Cloud Tasks'
244
+ schedule. The queue handler does not provision, as in the extension: if the
245
+ resources are still missing the retries fail and the row lands in
246
+ `BACKUP_COLLECTION`; run the lifecycle task (redeploy) to recreate them.
247
+
248
+ ## Failure handling
249
+
250
+ The write path mirrors the extension's Cloud Tasks buffer:
251
+
252
+ 1. The trigger attempts the BigQuery insert inline. On success, done.
253
+ 2. On failure, it enqueues the serialized change onto the `syncBigQuery` queue
254
+ (up to `MAX_ENQUEUE_ATTEMPTS` in-process attempts with backoff, keyed by
255
+ event id so a retried enqueue cannot buffer the same event twice) and the
256
+ execution succeeds. The trigger declares no retry policy, as in the
257
+ extension: a failure _before_ the write is attempted (serializing the
258
+ change, publishing the `onStart` event) fails the execution once and the
259
+ event is not redelivered.
260
+ 3. `syncBigQuery` re-attempts the write on the queue's schedule: 5 attempts,
261
+ 60 seconds minimum backoff, throttled to `MAX_DISPATCHES_PER_SECOND`
262
+ dispatches per second (500 concurrent max).
263
+ 4. On every terminal insert failure the tracker writes the row to
264
+ `BACKUP_COLLECTION` (when configured), keyed by the event id, before the
265
+ task fails. After the fifth attempt the task is dropped. **Without a backup collection, the row is dropped with the task** -
266
+ configure `BACKUP_COLLECTION`.
267
+ 5. If the enqueue itself fails (BigQuery AND Cloud Tasks both failing), the
268
+ trigger logs at error level, publishes an `onError` event, and the
269
+ execution succeeds: the event is dropped, exactly as the extension did in
270
+ this window.
271
+
272
+ ### Recovering parked rows
273
+
274
+ Rows in `BACKUP_COLLECTION` are changelog-shaped documents, not plain document
275
+ snapshots, so `fs-bq-import-collection` cannot consume them. Treat them as
276
+ "possibly failed": a transient failure that later succeeded on retry also
277
+ leaves one behind, and nothing cleans them up. To recover after an outage,
278
+ load the backup docs into a temp table and `MERGE` them into the changelog
279
+ table with a `WHEN NOT MATCHED` condition on `event_id` (the anti-join is
280
+ mandatory because of those stale rows).
281
+
282
+ Each backup document is keyed by the event id and shaped like the streaming
283
+ insert row the tracker sent, plus the error:
284
+
285
+ ```json
286
+ {
287
+ "insertId": "<event id>",
288
+ "json": {
289
+ "timestamp": "...",
290
+ "event_id": "<event id>",
291
+ "document_name": "...",
292
+ "document_id": "...",
293
+ "operation": "CREATE",
294
+ "data": "<JSON string>",
295
+ "old_data": "<JSON string or null>",
296
+ "path_params": "<JSON string, only with WILDCARD_IDS>"
297
+ },
298
+ "error_details": "..."
299
+ }
300
+ ```
301
+
302
+ The changelog columns sit under `json`, not at the top level. Load the `json`
303
+ objects of the backup documents into a temp table with the changelog's schema
304
+ (for example by exporting the collection and running `bq load` on the `json`
305
+ field), then:
306
+
307
+ ```sql
308
+ MERGE `<project>.<dataset>.<table>_raw_changelog` AS target
309
+ USING `<project>.<dataset>.<temp table>` AS backup
310
+ ON target.event_id = backup.event_id
311
+ WHEN NOT MATCHED THEN
312
+ INSERT (timestamp, event_id, document_name, document_id, operation, data, old_data)
313
+ VALUES (backup.timestamp, backup.event_id, backup.document_name,
314
+ backup.document_id, backup.operation, backup.data, backup.old_data)
315
+ ```
316
+
317
+ Add `path_params` and any partition column to both lists if your table has
318
+ them.
319
+
320
+ ### Known limits
321
+
322
+ - A task queue is a project-level resource created for each task function.
323
+ Deleting the functions (or moving them to another region) disables the old
324
+ queue rather than removing it; it shows as `DISABLED` in the Cloud Tasks
325
+ console until you delete it there.
326
+ - A row whose insert still fails on the last queue attempt with no
327
+ `BACKUP_COLLECTION` configured is gone. This matches the extension; it is
328
+ the reason the backup collection is strongly recommended.
329
+ - The changelog can carry a duplicate `event_id`. BigQuery's `insertId`
330
+ dedupe on streaming inserts is best effort for about a minute and the
331
+ queue's minimum backoff is 60 seconds, so an insert that landed but reported
332
+ an error can be written again by the retry. The `_raw_latest` view keys on
333
+ `document_name` and takes the newest change, so duplicates do not affect it;
334
+ the `MERGE` above assumes them.
335
+ - `BACKUP_COLLECTION` captures rows whose BigQuery insert fails. A failure
336
+ earlier in the tracker, such as a `TRANSFORM_FUNCTION` endpoint that is down
337
+ or returns malformed JSON, throws before the insert and is not backed up.
338
+ Same as the extension.
339
+ - A change whose serialized payload exceeds the Cloud Tasks task size limit
340
+ (1 MB) cannot be enqueued: the row is logged and dropped, and never reaches
341
+ `BACKUP_COLLECTION`. An update carries both `data` and `old_data`, so large
342
+ documents get there first; `EXCLUDE_OLD_DATA=yes` halves the payload. Same as
343
+ the extension.
344
+
345
+ ## Differences from the Stream Firestore to BigQuery extension
346
+
347
+ This kit is the extension repackaged as an npm package, but a few things behave
348
+ differently. If you are moving from an installed extension instance, read this
349
+ section before you deploy.
350
+
351
+ ### Failed writes: same buffer
352
+
353
+ The kit keeps the extension's write-path architecture: a failed BigQuery write
354
+ buffers through the `syncBigQuery` Cloud Tasks queue, with the same shape (5
355
+ attempts, 60s minimum backoff, `MAX_DISPATCHES_PER_SECOND` throttling) and the
356
+ same knobs (`MAX_DISPATCHES_PER_SECOND`, `MAX_ENQUEUE_ATTEMPTS`) - your
357
+ migrated `.env` values carry over unchanged.
358
+
359
+ When the enqueue itself fails, the kit does what the extension does: logs at
360
+ error level, publishes an `onError` event, and drops the event. The trigger
361
+ declares no retry policy, so nothing is redelivered through Eventarc.
362
+
363
+ Earlier release candidates of this kit had no queue: they retried every failed
364
+ write through Eventarc redelivery for up to 24 hours and never lost a row
365
+ inside that window. That property is gone by design - a row that exhausts the
366
+ queue without a configured `BACKUP_COLLECTION` is dropped, exactly as in the
367
+ extension. Set `BACKUP_COLLECTION`.
368
+
369
+ ### Events
370
+
371
+ Events are published under `firebase.extensions.firestore-bigquery-export.v1.*`
372
+ only. The extension also published a duplicate copy of every event under
373
+ `firebase.extensions.firestore-counter.v1.*`, a historical naming mistake kept
374
+ for backwards compatibility. If you have Eventarc triggers listening on those
375
+ `firestore-counter` types, point them at the `firestore-bigquery-export` types.
376
+
377
+ ### Wildcard columns include the document ID
378
+
379
+ With `WILDCARD_IDS=true`, the wildcard column now contains a `documentId` key
380
+ alongside the path parameters from your collection path. The extension wrote
381
+ the path parameters only.
382
+
383
+ ### DATABASE_REGION places the functions
384
+
385
+ The extension's `LOCATION` parameter is gone. Instead, the kit deploys its
386
+ functions to the region derived from `DATABASE_REGION`: regional Firestore
387
+ locations (`europe-west2`, `us-east1`, ...) are used as-is, and the
388
+ multi-region locations map to a Cloud Run region inside them - `nam5` and
389
+ `nam7` to `us-central1`, `eur3` to `europe-west1`. Multi-region values are
390
+ never used directly: they are not Cloud Run regions and would fail the deploy.
391
+ The Firestore trigger itself always fires in the database's own region,
392
+ whatever region the function runs in.
393
+
394
+ If you copied `DATABASE_REGION` into your `.env` from an extension install,
395
+ it is honored: the functions deploy near your database.
396
+
397
+ Placement needs firebase-tools 15.28.0 or later - older CLIs do not load
398
+ `.env` values during deploy discovery, so the functions silently fall back to
399
+ the no-region behavior below. Two consequences worth knowing before you
400
+ deploy. Upgrading the CLI (or this kit, if your `.env` already carried
401
+ `DATABASE_REGION`) can itself trigger the region move described below on your
402
+ next deploy. And on a fresh interactive install the value you enter at the
403
+ prompt only takes effect from the second deploy: the first deploy computes
404
+ regions before the prompt runs, so it lands in `us-central1` and the next
405
+ deploy moves the functions.
406
+
407
+ With `DATABASE_REGION` unset or empty, the functions declare no region and the
408
+ Firebase CLI resolves one at deploy time: a function keeps the region it is
409
+ already deployed in, and on a first deploy lands in `us-central1` unless you
410
+ set the `FIREBASE_FUNCTIONS_DEFAULT_REGION` environment variable when running
411
+ `firebase deploy`. Careful with that variable: it applies to every no-region
412
+ function in the deploy, not just this kit. Note that changing an existing
413
+ install's function region (via this variable or `DATABASE_REGION`) deletes and
414
+ recreates the functions in the new region - new URLs, a recreated task queue,
415
+ and any in-flight tasks are lost.
416
+
417
+ ### Defaults
418
+
419
+ Two settings now have defaults rather than being passed through empty:
420
+ `DATASET_LOCATION` defaults to `us`, and `BIGQUERY_PROJECT_ID` defaults to the
421
+ project the functions are deployed to.
422
+
423
+ ### Tooling that is not included
424
+
425
+ The extension shipped companion scripts that this package does not:
426
+
427
+ - `fs-bq-import-collection`, for backfilling documents that already existed
428
+ before the export started.
429
+ - `gen-schema-view`, for generating strongly typed BigQuery views over the
430
+ changelog.
431
+ - The cross-project access grant scripts.
432
+
433
+ `IMPORT_COLLECTION_PATH` is not a setting here. If you rely on any of these,
434
+ keep using the versions from the extension repository. They operate on the same
435
+ BigQuery changelog table, so they still work against data this kit writes.
217
436
 
218
437
  ## API surface
219
438
 
220
- - **Main entry** (`@firebase/firestore-bigquery-export`): exports
221
- `fsexportbigquery`, `initBigQuerySync`, and `setupBigQuerySync`, and
222
- registers the first-deploy / redeploy provisioning hooks. Runtime config is
223
- resolved lazily on first invocation. Use this entry from Firebase
224
- deploy/emulator/runtime. For your own triggers, import from `./lib` instead.
225
- - **Library entry** (`./lib`): `handleDocumentWrite`, the raw handler for owning
226
- trigger registration yourself, plus the config types and helpers
227
- (`ExportConfig`, `resolveExportConfig`, `toTrackerConfig`) for building its
228
- injected `HandlerContext`. Safe to import anywhere.
439
+ - **Main entry** (`@firebase-function-kits/firestore-bigquery-export`): exports
440
+ `fsexportbigquery`, `syncBigQuery`, `initBigQuerySync`, and
441
+ `setupBigQuerySync`, and registers the first-deploy / redeploy provisioning
442
+ hooks. Runtime config is resolved lazily on first invocation. Use this entry
443
+ from Firebase deploy/emulator/runtime. For your own triggers, import from
444
+ `./lib` instead.
445
+ - **Library entry** (`./lib`): `handleDocumentWrite` and
446
+ `handleSyncBigQueryTask`, the raw handlers for owning trigger registration
447
+ yourself, plus the config types and helpers (`ExportConfig`,
448
+ `resolveExportConfig`, `toTrackerConfig`, `SerializedDocumentChange`) for
449
+ building their injected `HandlerContext`. Safe to import anywhere.
229
450
 
230
451
  The change-tracker engine is an internal dependency and is not exported.
231
452
 
package/lib/config.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import type { ChangeTrackerConfig, TimePartitioningGranularity } from "@firebaseextensions/firestore-bigquery-change-tracker";
2
- import type { Expression } from "firebase-functions/params";
2
+ import type { Expression, IntParam } from "firebase-functions/params";
3
3
  import type { ExportConfig } from "./export-config";
4
4
  type ConfigExpression<T extends string | number | boolean> = Expression<T>;
5
5
  export interface ConfigExpressions {
6
6
  collectionPath: ConfigExpression<string>;
7
7
  datasetId: ConfigExpression<string>;
8
8
  tableId: ConfigExpression<string>;
9
- location: ConfigExpression<string>;
10
9
  database: ConfigExpression<string>;
10
+ /** An `IntParam`, not a bare expression: the queue's `rateLimits` guards it with a CEL comparison. */
11
+ maxDispatchesPerSecond: IntParam;
11
12
  }
12
13
  export declare const CONFIG_EXPRESSIONS: ConfigExpressions;
13
14
  export declare function clustering(clusters: string | undefined): string[];
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,mBAAmB,EAEnB,2BAA2B,EAC5B,MAAM,uDAAuD,CAAC;AAE/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAO5D,OAAO,KAAK,EAAE,YAAY,EAAY,MAAM,iBAAiB,CAAC;AAG9D,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;AAkH3E,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACpC,OAAO,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAClC,QAAQ,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACnC,QAAQ,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;CACpC;AAiED,eAAO,MAAM,kBAAkB,EAAE,iBAMhC,CAAC;AAiBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,YAEtD;AA4BD,wBAAgB,uBAAuB,CAAC,MAAM,EAAE;IAC9C,gBAAgB,EAAE,2BAA2B,GAAG,IAAI,CAAC;IACrD,qBAAqB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9C,8BAA8B,EAAE,MAAM,GAAG,SAAS,CAAC;CACpD,GAAG,mBAAmB,CAAC,cAAc,CAAC,CAuEtC;AA6BD;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,IAAI,YAAY,CAiC5C"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,mBAAmB,EAEnB,2BAA2B,EAC5B,MAAM,uDAAuD,CAAC;AAE/D,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAQtE,OAAO,KAAK,EAAE,YAAY,EAAY,MAAM,iBAAiB,CAAC;AAG9D,KAAK,gBAAgB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;AAmE3E,MAAM,WAAW,iBAAiB;IAChC,cAAc,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACzC,SAAS,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACpC,OAAO,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAClC,QAAQ,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACnC,sGAAsG;IACtG,sBAAsB,EAAE,QAAQ,CAAC;CAClC;AAyXD,eAAO,MAAM,kBAAkB,EAAE,iBAMhC,CAAC;AAiBF,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,YAEtD;AA4BD,wBAAgB,uBAAuB,CAAC,MAAM,EAAE;IAC9C,gBAAgB,EAAE,2BAA2B,GAAG,IAAI,CAAC;IACrD,qBAAqB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9C,8BAA8B,EAAE,MAAM,GAAG,SAAS,CAAC;CACpD,GAAG,mBAAmB,CAAC,cAAc,CAAC,CAuEtC;AAgDD;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,IAAI,YAAY,CAkC5C"}