@firebase-function-kits/firestore-bigquery-export 0.0.2-rc.9 → 0.1.1

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/README.md CHANGED
@@ -4,451 +4,393 @@ 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
- It listens for document writes on a collection, serializes each change, and
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.
7
+ Each document write is serialized and inserted into a BigQuery changelog table.
8
+ Failed writes buffer through a Cloud Tasks queue (`syncBigQuery`) and are
9
+ retried.
10
+
11
+ Terms used below: a **codebase** is a directory of Cloud Functions source the
12
+ Firebase CLI deploys as a unit. A **kit** is this package declared by a `kit`
13
+ entry in `firebase.json`. An **instance** is one configured copy of the kit,
14
+ with its own `.env` and four functions; the CLI deploys each instance as a
15
+ codebase named after its instance id.
12
16
 
13
17
  ## Install
14
18
 
19
+ This assumes the latest Firebase CLI is installed and signed in, and that you
20
+ run the commands from your Firebase project directory (the one containing
21
+ `firebase.json`; `firebase init` creates it), linked to your project
22
+ (`firebase use <project-id>`). You also need Cloud Firestore on
23
+ the Blaze plan and Node.js 24 (22 or later is supported).
24
+
25
+ **Guided installer.** This creates the codebase under `function-kits/<kit-name>/`,
26
+ adds the `kit` entry to `firebase.json`, and prompts for each setting, writing
27
+ the answers to `function-kits/<kit-name>/config-<instance-id>/.env.<project-id>`:
28
+
29
+ ```sh
30
+ firebase functions:kits:install --package @firebase-function-kits/firestore-bigquery-export@latest
31
+ ```
32
+
33
+ It also asks for `FUNCTION_DEFAULT_REGION`. Enter the region your functions
34
+ will run in (`us-central1` for `nam5`; see [Region](#region)).
35
+
36
+ **Your own codebase.** From the `functions/` directory that `firebase init
37
+ functions` creates, install the kit plus `firebase-functions` and
38
+ `firebase-admin` as direct dependencies, on the major versions the kit uses
39
+ (currently 7 and 14). The kit's shrinkwrap nests its own copies, which the CLI
40
+ can't see: without them the deploy fails with `Couldn't find firebase-functions
41
+ package in your source code`.
42
+
15
43
  ```sh
16
- npm install @firebase-function-kits/firestore-bigquery-export
44
+ npm install @firebase-function-kits/firestore-bigquery-export@0.1.0 firebase-functions@7 firebase-admin@14
45
+ npm install --save-dev typescript@5
17
46
  ```
18
47
 
19
48
  ## Required IAM
20
49
 
21
- Deploy needs these Google Cloud roles and APIs for the function's service
22
- account. Firebase CLI 15.23.0 or later creates that account, grants the roles
23
- below, enables the listed APIs, and attaches the account to every function in
24
- this kit. Do not set a custom runtime service account for this codebase — it
25
- conflicts with that automatic setup.
26
-
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 |
36
-
37
- If the dataset lives in a different project (`BIGQUERY_PROJECT_ID`), grant the
38
- managed runtime service account the `bigquery.*` roles on that project. For a
39
- CMEK dataset, also grant the BigQuery service account access to your KMS key.
50
+ Nothing to do by hand. On the first deploy the CLI asks you to confirm these
51
+ roles (`This codebase uses declarative security … Continue? (y/N)`), then
52
+ creates a service account for the kit, grants them, and enables the APIs. Don't
53
+ set a custom runtime service account.
54
+
55
+ Without a terminal (for example in CI), there's no one to answer, so confirm
56
+ with `--force`. It accepts every prompt, so limit it to one instance:
57
+
58
+ ```sh
59
+ firebase deploy --only functions:<instance-id> --force
60
+ ```
61
+
62
+ | Role / API | Why |
63
+ | ------------------------------ | --------------------------------------------------------- |
64
+ | `roles/bigquery.dataEditor` | create the dataset, table and views; insert rows |
65
+ | `roles/bigquery.user` | run BigQuery jobs and materialized views |
66
+ | `roles/datastore.user` | write failed rows to `BACKUP_COLLECTION` (always granted) |
67
+ | `roles/eventarc.eventReceiver` | receive Firestore trigger events |
68
+ | `roles/run.invoker` | let Eventarc and Cloud Tasks invoke the functions |
69
+ | `roles/cloudtasks.enqueuer` | enqueue failed writes onto `syncBigQuery` |
70
+ | `firestore.googleapis.com` | receive document change events |
71
+ | `bigquery.googleapis.com` | write to BigQuery |
72
+
73
+ Setting `EVENTARC_CHANNEL` also adds `roles/eventarc.publisher` and
74
+ `eventarcpublishing.googleapis.com`. For a dataset in another project, grant
75
+ the kit's service account the `bigquery.*` roles there. For a CMEK dataset,
76
+ grant the BigQuery service account access to your KMS key.
40
77
 
41
78
  ## Usage
42
79
 
43
- Export the four functions from your functions codebase entry:
80
+ With your own codebase, this layout keeps the codebase and the instance's
81
+ `.env` in the `functions/` directory that `firebase init functions` creates:
82
+
83
+ ```text
84
+ my-project/
85
+ .firebaserc
86
+ firebase.json
87
+ functions/
88
+ package.json # "main": "lib/index.js", "engines": { "node": "24" }, "scripts": { "build": "tsc" }
89
+ tsconfig.json # compiles src/ to lib/
90
+ .env
91
+ src/index.ts
92
+ ```
44
93
 
45
94
  ```ts
46
95
  // functions/src/index.ts
47
96
  export {
48
- fsexportbigquery,
49
- syncBigQuery,
50
- initBigQuerySync,
51
- setupBigQuerySync,
97
+ fsexportbigquery, // Firestore trigger
98
+ syncBigQuery, // retries failed writes from the queue
99
+ initBigQuerySync, // creates BigQuery resources after the first deploy
100
+ setupBigQuerySync, // updates them after later deploys
52
101
  } from "@firebase-function-kits/firestore-bigquery-export";
53
102
  ```
54
103
 
55
- and configure them with a `.env` (or `.env.<projectId>`):
56
-
57
104
  ```sh
105
+ # functions/.env — set these before the first deploy
58
106
  COLLECTION_PATH=users
59
- DATASET_ID=analytics
107
+ DATASET_ID=firestore_export
60
108
  TABLE_ID=users
61
- DATABASE_REGION=europe-west2
109
+ DATABASE_REGION=nam5 # your Firestore database's location
110
+ DATASET_LOCATION=us # keep BigQuery data near the database
111
+ BACKUP_COLLECTION=users_bigquery_failures
62
112
  ```
63
113
 
64
- - `fsexportbigquery` is the Firestore trigger.
65
- - `syncBigQuery` is the write-buffer task queue that retries failed writes.
66
- - `initBigQuerySync` is the first-deploy provisioning lifecycle task.
67
- - `setupBigQuerySync` is the reconfigure provisioning lifecycle task.
68
-
69
- Importing the package without exporting its functions deploys nothing — the CLI
70
- only deploys what your entry file exports.
114
+ Any setting you leave out is asked for at deploy (see
115
+ [Configuration](#configuration)). Without `BACKUP_COLLECTION`, rows that fail
116
+ every retry are lost.
71
117
 
72
118
  ## Deploy
73
119
 
74
- The package's `firebase.json` declares a `kit` stanza (Firebase CLI 15.25.1 or
75
- later, behind the `kits` experiment):
120
+ In the `functions` entry `firebase init` created, add `kit` and `instances` and
121
+ remove `codebase` (a `kit` entry can't have one):
76
122
 
77
123
  ```json
78
124
  {
79
125
  "functions": [
80
126
  {
81
- "source": ".",
127
+ "source": "functions",
82
128
  "kit": "firestore-bigquery-export",
83
- "instances": {
84
- "default": "."
85
- }
129
+ "instances": { "default": "functions" },
130
+ "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"]
86
131
  }
87
132
  ]
88
133
  }
89
134
  ```
90
135
 
91
- `instances` maps each instance id to the directory (relative to
92
- `firebase.json`) holding that instance's `.env`. The CLI prefixes every
93
- function and task queue name with `kit-<instance id>-`, so the functions above
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.
136
+ `kit` is any name you choose (up to 40 lowercase letters, digits, `_`, `-`).
137
+ `instances` maps each instance id to the directory holding its `.env`. Function
138
+ names get a `kit-<instance-id>-` prefix, so this deploys
139
+ `kit-default-fsexportbigquery` and so on. Commands that take a codebase take
140
+ the instance id.
103
141
 
104
142
  ```sh
105
- firebase experiments:enable kits
106
- firebase deploy --only functions
143
+ firebase deploy --only functions # all instances
144
+ firebase deploy --only functions:<instance-id> # one instance
145
+ ```
146
+
147
+ Deploy with the **latest** Firebase CLI. Older versions can fail to deploy the
148
+ kit or deploy it with problems.
149
+
150
+ **Check that it works.** The first deploy runs `initBigQuerySync`, which creates
151
+ the dataset with a `<TABLE_ID>_raw_changelog` table (one row per change) and a
152
+ `<TABLE_ID>_raw_latest` view (current state per document). This takes a
153
+ minute or two; wait until `firebase functions:log --only
154
+ kit-<instance-id>-initBigQuerySync` shows the view. Then, in the
155
+ [Firebase console](https://console.firebase.google.com/), add a document to
156
+ your `COLLECTION_PATH` collection. With the `.env` from [Usage](#usage), add
157
+ this to `users`:
158
+
159
+ ```text
160
+ Document ID: alice
161
+ Fields: name (string) = Alice
162
+ age (number) = 30
163
+ ```
164
+
165
+ Then run this in the
166
+ [BigQuery console](https://console.cloud.google.com/bigquery):
167
+
168
+ ```sql
169
+ SELECT document_id, operation, data, timestamp
170
+ FROM `<project-id>.<DATASET_ID>.<TABLE_ID>_raw_changelog`
171
+ ORDER BY timestamp DESC LIMIT 10
107
172
  ```
108
173
 
109
- Deploy a single instance with `firebase deploy --only functions:<instance id>`.
174
+ For the example document, the table is
175
+ `<project-id>.firestore_export.users_raw_changelog`, and the newest row has
176
+ `document_id` `alice`, `operation` `CREATE` and `data`
177
+ `{"name":"Alice","age":30}`.
178
+
179
+ The row can take a minute to appear. If it's missing, wait until `firebase
180
+ functions:log --only kit-<instance-id>-fsexportbigquery` shows `Firestore event
181
+ received by onDocumentWritten trigger` (at `LOG_LEVEL=info`), then query again.
110
182
 
111
183
  ## Configuration
112
184
 
113
- Set these values in a `.env` (or `.env.<projectId>`) file. The Firebase CLI
114
- loads them at deploy time and prompts for any required values that are missing.
115
- `PROJECT_ID` is supplied by the Firebase CLI.
116
-
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) |
185
+ Settings go in the instance's `.env` (or `.env.<project-id>`). If a setting
186
+ isn't there, the deploy asks you for it, suggesting the default, and saves your
187
+ answer to `.env.<project-id>`.
188
+
189
+ A setting with **No** under "Can be blank" fails the deploy on a line like
190
+ `DATASET_ID=`. Give it a value, or remove the line and answer the prompt.
191
+
192
+ | Env var | Default | Can be blank | Description |
193
+ | ----------------------------------- | ------------------ | ------------ | ------------------------------------------------------------------ |
194
+ | `DATABASE_REGION` | (none) | Yes | Firestore location; places the functions. No default: always set |
195
+ | `COLLECTION_PATH` | `posts` | No | Collection to export; `{wildcard}` segments match subcollections |
196
+ | `DATASET_ID` | `firestore_export` | No | BigQuery dataset |
197
+ | `TABLE_ID` | `posts` | No | Prefix of the changelog table and view |
198
+ | `DATASET_LOCATION` | `us` | No | Dataset location; used only when the dataset is created |
199
+ | `DATABASE` | `(default)` | No | Firestore database id |
200
+ | `BIGQUERY_PROJECT_ID` | project id | No | Dataset project, if different |
201
+ | `BACKUP_COLLECTION` | (empty) | Yes | Firestore collection for rows whose insert failed. Recommended. |
202
+ | `MAX_DISPATCHES_PER_SECOND` | `100` | Yes | `syncBigQuery` dispatch rate (1-500) |
203
+ | `MAX_ENQUEUE_ATTEMPTS` | `3` | Yes | Enqueue attempts before giving up (1-10) |
204
+ | `TRANSFORM_FUNCTION` | (empty) | Yes | URL of an HTTP function that transforms rows before insert |
205
+ | `TABLE_PARTITIONING` | `NONE` | Yes | `HOUR`, `DAY`, `MONTH`, `YEAR` or `NONE` |
206
+ | `TIME_PARTITIONING_FIELD` | (empty) | Yes | Partitioning column name |
207
+ | `TIME_PARTITIONING_FIELD_TYPE` | `omit` | Yes | `TIMESTAMP`, `DATETIME`, `DATE` or `omit` |
208
+ | `TIME_PARTITIONING_FIRESTORE_FIELD` | (empty) | Yes | Firestore field to partition on |
209
+ | `CLUSTERING` | (empty) | Yes | Up to 4 comma-separated columns, e.g. `data,document_id,timestamp` |
210
+ | `WILDCARD_IDS` | `false` | Yes | Add a `path_params` column of `{wildcard}` values as JSON |
211
+ | `USE_NEW_SNAPSHOT_QUERY_SYNTAX` | `no` | No | `yes` / `no` |
212
+ | `EXCLUDE_OLD_DATA` | `no` | Yes | Skip the previous document state on updates (`yes` / `no`) |
213
+ | `VIEW_TYPE` | `view` | No | `view`, `materialized_incremental`, `materialized_non_incremental` |
214
+ | `MAX_STALENESS` | (empty) | Yes | Materialized views: e.g. `INTERVAL "8:0:0" HOUR TO SECOND` |
215
+ | `REFRESH_INTERVAL_MINUTES` | (empty) | Yes | Materialized views: refresh interval in minutes |
216
+ | `KMS_KEY_NAME` | (empty) | Yes | `projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>` |
217
+ | `LOG_LEVEL` | `info` | No | `debug`, `info`, `warn`, `error`, `silent` |
218
+ | `EVENTARC_CHANNEL` | (unset) | Yes | Channel for the kit's [events](#events); unset or blank disables |
219
+ | `EXT_SELECTED_EVENTS` | (unset) | Yes | Event types to publish; unset publishes all, blank publishes none |
145
220
 
146
221
  ## Multiple instances
147
222
 
148
- To export several collections, add one entry per instance to the `instances`
149
- map, each pointing at its own config directory with its own `.env`:
223
+ Add one entry per instance, each with its own config directory and `.env`.
224
+ Instance ids must be unique across the project.
150
225
 
151
226
  ```json
152
- {
153
- "functions": [
154
- {
155
- "source": ".",
156
- "kit": "firestore-bigquery-export",
157
- "instances": {
158
- "users": "instances/users",
159
- "orders": "instances/orders"
160
- }
161
- }
162
- ]
163
- }
227
+ "instances": { "users": "instances/users", "orders": "instances/orders" }
164
228
  ```
165
229
 
166
- Instance ids must be unique across all kit stanzas in the project, and every
167
- instance's function names are namespaced by its `kit-<instance id>-` prefix, so
168
- the instances cannot collide.
169
-
170
230
  ## Events
171
231
 
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.
232
+ With `EVENTARC_CHANNEL` set, the functions publish `onStart` and `onError` from
233
+ the trigger and `onSuccess` from `syncBigQuery`. Each event is published under
234
+ both `firebase.extensions.firestore-bigquery-export.v1.*` and the extension's
235
+ legacy `firebase.extensions.firestore-counter.v1.*`; write new triggers against
236
+ the first. `EXT_SELECTED_EVENTS` filters by exact type, legacy copies included.
237
+ A config exported from the extension carries its `EXT_SELECTED_EVENTS` over, so
238
+ check it lists what you expect.
185
239
 
186
240
  ## Provisioning
187
241
 
188
- The BigQuery dataset, table, and views are created by `tracker.initialize()`
189
- through the shared provisioning path used by both task functions. Both tasks
190
- are idempotent and retry on transient BigQuery failures (up to 15 attempts,
191
- 60s minimum backoff).
192
-
193
- Deploy wiring (declared in the package):
194
-
195
- - First deploy runs `initBigQuerySync` automatically (`afterFirstDeploy`).
196
- - Later deploys run `setupBigQuerySync` automatically (`afterRedeploy`).
197
-
198
- `initBigQuerySync` and `setupBigQuerySync` call the same handler; they exist as
199
- separate task functions so first-deploy and redeploy can target different
200
- queues, matching the extension's install vs update/configure split.
242
+ `initBigQuerySync` runs after the first deploy and `setupBigQuerySync` after
243
+ later ones, creating or updating the dataset, table and view (15 attempts, 60s
244
+ backoff). A redeploy with no changes is skipped, and so is
245
+ `setupBigQuerySync`. Writes never create resources: if they're missing, writes
246
+ fail into the queue and backup collection until a lifecycle task runs.
201
247
 
202
- If automatic post-deploy enqueue did not run, enqueue a task yourself. The
203
- snippets below use the `default` instance; substitute your instance id in the
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
209
- `initBigQuerySync` after a first deploy and `setupBigQuerySync` after a
210
- redeploy or schema-related config change (`TABLE_PARTITIONING`, `CLUSTERING`,
211
- `WILDCARD_IDS`, `VIEW_TYPE`, and related fields).
248
+ To run one by hand, run this from your codebase directory with `firebase-admin`
249
+ installed and application-default credentials (`gcloud auth
250
+ application-default login`). You need `roles/cloudtasks.enqueuer`, plus
251
+ `roles/iam.serviceAccountUser` on the kit's service account, which signs the
252
+ task; `KIT_SA` looks that account up:
212
253
 
213
254
  ```sh
255
+ export GOOGLE_CLOUD_PROJECT=<project-id> FUNCTION_REGION=us-central1
256
+ export KIT_SA=$(gcloud functions describe kit-<instance-id>-setupBigQuerySync \
257
+ --region "$FUNCTION_REGION" --format 'value(serviceConfig.serviceAccountEmail)')
214
258
  node -e '
215
259
  const { initializeApp } = require("firebase-admin/app");
216
260
  const { getFunctions } = require("firebase-admin/functions");
217
- initializeApp();
261
+ initializeApp({ serviceAccountId: process.env.KIT_SA });
218
262
  getFunctions()
219
- .taskQueue("locations/'"$FUNCTION_REGION"'/functions/kit-default-initBigQuerySync")
263
+ .taskQueue("locations/'"$FUNCTION_REGION"'/functions/kit-<instance-id>-setupBigQuerySync")
220
264
  .enqueue({})
221
- .then(() => console.log("init task enqueued"));
265
+ .then(() => console.log("enqueued"));
222
266
  '
223
267
  ```
224
268
 
225
- Run it from your functions directory (it uses the installed `firebase-admin`)
226
- with application-default credentials and `GOOGLE_CLOUD_PROJECT` set. The caller
227
- needs `roles/cloudtasks.enqueuer`.
269
+ ## Failure handling
228
270
 
229
- Under the hood the task queue is an authenticated HTTP endpoint, so for a quick
230
- manual run you can also POST to it directly — note this skips the queue, so a
231
- failure is not retried:
271
+ 1. The trigger inserts the row inline. If that fails, the row is written to
272
+ `BACKUP_COLLECTION` (when set) and the change is enqueued on `syncBigQuery`.
273
+ 2. `syncBigQuery` tries up to 5 times, at least 60s apart, and writes to
274
+ `BACKUP_COLLECTION` after each failed try. After the last one, the task is
275
+ dropped. If every instance is busy, Cloud Run refuses the try with a 429
276
+ before the kit's code runs, so no backup row is written.
277
+ 3. If the enqueue also fails, the trigger logs an error, publishes `onError`
278
+ and gives up. The event isn't redelivered.
279
+
280
+ Backup documents are keyed by event id, with the changelog columns under
281
+ `json`. Load those `json` objects into a temp table with the changelog's schema
282
+ (for example, export the collection and `bq load` the `json` field). Some are
283
+ left by failures that later succeeded, so merge them back with an anti-join on
284
+ `event_id`:
232
285
 
233
- ```sh
234
- URL=$(gcloud functions describe kit-default-initBigQuerySync \
235
- --region "$FUNCTION_REGION" --gen2 --format='value(url)')
286
+ ```sql
287
+ MERGE `<project-id>.<dataset>.<table>_raw_changelog` AS target
288
+ USING `<project-id>.<dataset>.<backup-temp-table>` AS backup
289
+ ON target.event_id = backup.event_id
290
+ WHEN NOT MATCHED THEN
291
+ INSERT (timestamp, event_id, document_name, document_id, operation, data, old_data)
292
+ VALUES (backup.timestamp, backup.event_id, backup.document_name,
293
+ backup.document_id, backup.operation, backup.data, backup.old_data)
294
+ ```
295
+
296
+ With `WILDCARD_IDS=true`, add `path_params` to both lists. With a custom
297
+ partition field, add your `TIME_PARTITIONING_FIELD` column too. For example,
298
+ with both and `TIME_PARTITIONING_FIELD=created_at`:
236
299
 
237
- curl -fsS -X POST -H "Content-Type: application/json" -d '{"data":{}}' \
238
- -H "Authorization: Bearer $(gcloud auth print-identity-token --audiences="$URL")" "$URL"
300
+ ```sql
301
+ MERGE `<project-id>.<dataset>.<table>_raw_changelog` AS target
302
+ USING `<project-id>.<dataset>.<backup-temp-table>` AS backup
303
+ ON target.event_id = backup.event_id
304
+ WHEN NOT MATCHED THEN
305
+ INSERT (timestamp, event_id, document_name, document_id, operation, data, old_data,
306
+ path_params, created_at)
307
+ VALUES (backup.timestamp, backup.event_id, backup.document_name,
308
+ backup.document_id, backup.operation, backup.data, backup.old_data,
309
+ backup.path_params, backup.created_at)
239
310
  ```
240
311
 
241
- The Firestore write path never provisions on the hot path. If resources are
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.
312
+ Limits, all shared with the extension:
247
313
 
248
- ## Failure handling
314
+ - Failures before the insert (for example a broken `TRANSFORM_FUNCTION`) aren't
315
+ backed up.
316
+ - Changes over 1 MB can't be enqueued. `EXCLUDE_OLD_DATA=yes` halves update
317
+ payloads.
318
+ - The changelog can contain duplicate `event_id`s; the latest view is
319
+ unaffected.
320
+ - Deleting or moving the functions leaves their Cloud Tasks queues behind as
321
+ `DISABLED`.
249
322
 
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:
323
+ ## Migrating from the extension
284
324
 
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
- }
325
+ Run the migration from your Firebase project directory, naming the extension
326
+ instance to replace (without `--ext-instance`, it asks you to pick one):
327
+
328
+ ```sh
329
+ firebase ext:migrate --ext-instance <instance-id>
300
330
  ```
301
331
 
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:
332
+ It exports the instance's configuration, deploys the kit, then offers to
333
+ uninstall the extension. Writes made while the new trigger warms up can reach
334
+ neither exporter. To avoid the gap, answer no to the uninstall prompt, confirm
335
+ the kit logs every write (see [Check that it works](#deploy)), then uninstall:
306
336
 
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)
337
+ ```sh
338
+ firebase ext:uninstall <instance-id> --immediate
315
339
  ```
316
340
 
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.
341
+ Running both at once is safe: BigQuery deduplicates on the shared event id
342
+ (best effort), and the latest view is unaffected by any duplicate.
343
+
344
+ To recover writes already missed, re-import with
345
+ [`fs-bq-import-collection`](https://github.com/firebase/extensions/blob/master/firestore-bigquery-export/guides/IMPORT_EXISTING_DOCUMENTS.md),
346
+ pointed at the kit's dataset and table prefix, while writes are paused. It
347
+ imports every document's current value as an `IMPORT` row; deletes and
348
+ superseded updates can't be recovered.
344
349
 
345
350
  ## Differences from the Stream Firestore to BigQuery extension
346
351
 
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.
352
+ - **Region.** The extension's install-time Cloud Functions location is gone.
353
+ See [Region](#region).
354
+ - **`DATASET_LOCATION` can change**, but only takes effect when a dataset is
355
+ created. To move, set a new `DATASET_ID` too, then backfill.
356
+ - **No companion tools.** `fs-bq-import-collection`, `gen-schema-view` and the
357
+ cross-project grant scripts stay in the extension repository and work on the
358
+ kit's tables.
359
+ - **A failed `onStart` publish** only logs a warning; the extension failed the
360
+ execution.
361
+ - **Same runtime settings.** Concurrency 1, extension-sized CPU, internal-only
362
+ trigger ingress, 540s task timeouts, 100 trigger instances and 500 for
363
+ `syncBigQuery` (about 84 vCPU of regional Cloud Run quota). Raise
364
+ `setGlobalOptions({ maxInstances })` for more trigger throughput.
365
+ - **`ext:migrate` carries global options.** Its generated entry file applies the
366
+ extension's memory, timeout, ingress and instance limits through
367
+ `setGlobalOptions`, wherever a function doesn't set its own. Check the
368
+ `EXT_MIGRATED_SYSTEM_*` values in `.env`.
369
+
370
+ ### Region
371
+
372
+ Functions deploy to the region derived from `DATABASE_REGION`: regional
373
+ locations as-is, `nam5` and `nam7` to `us-central1`, `eur3` to `europe-west1`.
374
+ The trigger still fires in the database's region. Set `DATABASE_REGION` in
375
+ `.env` before the first deploy; a value given at the deploy prompt only applies
376
+ from the next deploy.
377
+
378
+ With `DATABASE_REGION=` left blank, functions go to `FUNCTION_DEFAULT_REGION`
379
+ in installer- or migrate-generated codebases, and otherwise to `us-central1`
380
+ (or their current region). Changing region deletes and recreates the functions
381
+ and their queue.
436
382
 
437
383
  ## API surface
438
384
 
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.
450
-
451
- The change-tracker engine is an internal dependency and is not exported.
385
+ - **Main entry** (`@firebase-function-kits/firestore-bigquery-export`): the
386
+ four functions and everything from the library entry. Importing it also
387
+ registers the `afterFirstDeploy` / `afterRedeploy` tasks.
388
+ - **Library entry** (`@firebase-function-kits/firestore-bigquery-export/lib`):
389
+ `handleDocumentWrite` and `handleSyncBigQueryTask` for registering triggers
390
+ yourself, plus `ExportConfig`, `ResolvedExportConfig`, `resolveExportConfig`,
391
+ `toTrackerConfig`, `ViewType`, `DocumentWriteEvent`, `HandlerContext`,
392
+ `SerializedDocumentChange`, `ChangeType`, and the types
393
+ `ChangeTrackerConfig` and `FirestoreBigQueryEventHistoryTracker`.
452
394
 
453
395
  ## License
454
396