@firebase-function-kits/firestore-bigquery-export 0.0.1 → 0.0.2-rc.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/CHANGELOG.md +1 -0
- package/README.md +303 -0
- package/lib/config.d.ts +33 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +569 -0
- package/lib/config.js.map +1 -0
- package/lib/events.d.ts +45 -0
- package/lib/events.d.ts.map +1 -0
- package/lib/events.js +154 -0
- package/lib/events.js.map +1 -0
- package/lib/export-config.d.ts +96 -0
- package/lib/export-config.d.ts.map +1 -0
- package/lib/export-config.js +77 -0
- package/lib/export-config.js.map +1 -0
- package/lib/handlers.d.ts +29 -0
- package/lib/handlers.d.ts.map +1 -0
- package/lib/handlers.js +165 -0
- package/lib/handlers.js.map +1 -0
- package/lib/index.d.ts +23 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +179 -0
- package/lib/index.js.map +1 -0
- package/lib/init.d.ts +16 -0
- package/lib/init.d.ts.map +1 -0
- package/lib/init.js +44 -0
- package/lib/init.js.map +1 -0
- package/lib/lib.d.ts +20 -0
- package/lib/lib.d.ts.map +1 -0
- package/lib/lib.js +47 -0
- package/lib/lib.js.map +1 -0
- package/lib/logs.d.ts +39 -0
- package/lib/logs.d.ts.map +1 -0
- package/lib/logs.js +186 -0
- package/lib/logs.js.map +1 -0
- package/lib/util.d.ts +23 -0
- package/lib/util.d.ts.map +1 -0
- package/lib/util.js +66 -0
- package/lib/util.js.map +1 -0
- package/npm-shrinkwrap.json +7016 -0
- package/package.json +37 -3
- package/src/config.ts +696 -0
- package/src/events.ts +146 -0
- package/src/export-config.ts +205 -0
- package/src/handlers.ts +211 -0
- package/src/index.ts +174 -0
- package/src/init.ts +45 -0
- package/src/lib.ts +55 -0
- package/src/logs.ts +233 -0
- package/src/util.ts +64 -0
- package/tests/config.test.ts +182 -0
- package/tests/events.test.ts +84 -0
- package/tests/export-config.test.ts +114 -0
- package/tests/handlers.test.ts +220 -0
- package/tests/init.test.ts +76 -0
- package/tests/util.test.ts +102 -0
- package/tsconfig.json +18 -0
- package/tsconfig.tsbuildinfo +1 -0
|
@@ -0,0 +1,182 @@
|
|
|
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 { describe, expect, test, vi } from "vitest";
|
|
18
|
+
|
|
19
|
+
vi.mock("firebase-functions/params", () => ({
|
|
20
|
+
Expression: class Expression<T> {
|
|
21
|
+
value(): T {
|
|
22
|
+
return this.runtimeValue();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
runtimeValue(): T {
|
|
26
|
+
throw new Error("Not implemented");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
toCEL(): string {
|
|
30
|
+
return `{{ ${this.toString()} }}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
toJSON(): string {
|
|
34
|
+
return this.toString();
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
defineString: (
|
|
38
|
+
_name: string,
|
|
39
|
+
opts?: { default?: string | { value(): string } }
|
|
40
|
+
) => ({
|
|
41
|
+
value: () =>
|
|
42
|
+
typeof opts?.default === "string"
|
|
43
|
+
? opts.default
|
|
44
|
+
: opts?.default?.value() ?? "",
|
|
45
|
+
toString: () => `params.${_name}`,
|
|
46
|
+
}),
|
|
47
|
+
defineInt: (_name: string, opts?: { default?: number }) => ({
|
|
48
|
+
value: () => opts?.default ?? 0,
|
|
49
|
+
toString: () => `params.${_name}`,
|
|
50
|
+
}),
|
|
51
|
+
defineBoolean: (_name: string, opts?: { default?: boolean }) => ({
|
|
52
|
+
value: () => opts?.default ?? false,
|
|
53
|
+
toString: () => `params.${_name}`,
|
|
54
|
+
}),
|
|
55
|
+
select: (options: unknown) => ({ select: { options } }),
|
|
56
|
+
expr: (
|
|
57
|
+
strings: TemplateStringsArray,
|
|
58
|
+
...values: ReadonlyArray<{ toString: () => string }>
|
|
59
|
+
) => ({
|
|
60
|
+
value: () =>
|
|
61
|
+
strings.reduce(
|
|
62
|
+
(acc, part, index) =>
|
|
63
|
+
`${acc}${values[index - 1]?.toString() ?? ""}${part}`
|
|
64
|
+
),
|
|
65
|
+
toString: () =>
|
|
66
|
+
strings.reduce(
|
|
67
|
+
(acc, part, index) =>
|
|
68
|
+
`${acc}${values[index - 1]?.toString() ?? ""}${part}`
|
|
69
|
+
),
|
|
70
|
+
}),
|
|
71
|
+
projectID: { value: () => "test-project" },
|
|
72
|
+
}));
|
|
73
|
+
|
|
74
|
+
import {
|
|
75
|
+
buildPartitioningConfig,
|
|
76
|
+
CONFIG_EXPRESSIONS,
|
|
77
|
+
clustering,
|
|
78
|
+
configFromEnv,
|
|
79
|
+
} from "../src/config";
|
|
80
|
+
import { resolveExportConfig } from "../src/export-config";
|
|
81
|
+
|
|
82
|
+
describe("clustering", () => {
|
|
83
|
+
test("splits a comma list", () => {
|
|
84
|
+
expect(clustering("a,b,c")).toEqual(["a", "b", "c"]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("caps at four columns", () => {
|
|
88
|
+
expect(clustering("a,b,c,d,e")).toEqual(["a", "b", "c", "d"]);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("empty or undefined becomes null", () => {
|
|
92
|
+
expect(clustering("")).toBeNull();
|
|
93
|
+
expect(clustering(undefined)).toBeNull();
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe("buildPartitioningConfig", () => {
|
|
98
|
+
const base = {
|
|
99
|
+
timePartitioningField: undefined,
|
|
100
|
+
timePartitioningFieldType: undefined,
|
|
101
|
+
timePartitioningFirestoreField: undefined,
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
test("no granularity and no fields => NONE", () => {
|
|
105
|
+
expect(
|
|
106
|
+
buildPartitioningConfig({ ...base, timePartitioning: null })
|
|
107
|
+
).toEqual({ granularity: "NONE" });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("granularity only", () => {
|
|
111
|
+
expect(
|
|
112
|
+
buildPartitioningConfig({ ...base, timePartitioning: "DAY" })
|
|
113
|
+
).toEqual({ granularity: "DAY" });
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("timestamp field shorthand", () => {
|
|
117
|
+
expect(
|
|
118
|
+
buildPartitioningConfig({
|
|
119
|
+
...base,
|
|
120
|
+
timePartitioning: "DAY",
|
|
121
|
+
timePartitioningField: "timestamp",
|
|
122
|
+
})
|
|
123
|
+
).toMatchObject({ granularity: "DAY", bigqueryColumnName: "timestamp" });
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("full custom field", () => {
|
|
127
|
+
expect(
|
|
128
|
+
buildPartitioningConfig({
|
|
129
|
+
timePartitioning: "DAY",
|
|
130
|
+
timePartitioningField: "created",
|
|
131
|
+
timePartitioningFieldType: "TIMESTAMP",
|
|
132
|
+
timePartitioningFirestoreField: "createdAt",
|
|
133
|
+
})
|
|
134
|
+
).toEqual({
|
|
135
|
+
granularity: "DAY",
|
|
136
|
+
bigqueryColumnName: "created",
|
|
137
|
+
bigqueryColumnType: "TIMESTAMP",
|
|
138
|
+
firestoreFieldName: "createdAt",
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("throws when fields are set without a granularity", () => {
|
|
143
|
+
expect(() =>
|
|
144
|
+
buildPartitioningConfig({
|
|
145
|
+
...base,
|
|
146
|
+
timePartitioning: null,
|
|
147
|
+
timePartitioningField: "created",
|
|
148
|
+
})
|
|
149
|
+
).toThrow();
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("throws on incomplete custom field", () => {
|
|
153
|
+
expect(() =>
|
|
154
|
+
buildPartitioningConfig({
|
|
155
|
+
timePartitioning: "DAY",
|
|
156
|
+
timePartitioningField: "created",
|
|
157
|
+
timePartitioningFieldType: undefined,
|
|
158
|
+
timePartitioningFirestoreField: "createdAt",
|
|
159
|
+
})
|
|
160
|
+
).toThrow();
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
describe("configFromEnv", () => {
|
|
165
|
+
test("maps params without inventing a region default", () => {
|
|
166
|
+
const config = configFromEnv();
|
|
167
|
+
expect(config.projectId).toBe("test-project");
|
|
168
|
+
expect(config.bqProjectId).toBe("test-project");
|
|
169
|
+
expect(config.databaseId).toBe("(default)");
|
|
170
|
+
expect(resolveExportConfig(config).location).toBe("");
|
|
171
|
+
expect(config.viewType).toBe("view");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test("exposes deploy-time expressions for trigger metadata", () => {
|
|
175
|
+
expect(CONFIG_EXPRESSIONS.collectionPath.toString()).toBe(
|
|
176
|
+
"params.COLLECTION_PATH"
|
|
177
|
+
);
|
|
178
|
+
expect(CONFIG_EXPRESSIONS.location.toString()).toBe(
|
|
179
|
+
"params.DATABASE_REGION"
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 Google LLC
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|
18
|
+
|
|
19
|
+
const { publish, channel } = vi.hoisted(() => {
|
|
20
|
+
const publish = vi.fn().mockResolvedValue(undefined);
|
|
21
|
+
const channel = vi.fn(() => ({ publish }));
|
|
22
|
+
return { publish, channel };
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
vi.mock("firebase-admin/eventarc", () => ({
|
|
26
|
+
getEventarc: () => ({ channel }),
|
|
27
|
+
}));
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
recordCompletionEvent,
|
|
31
|
+
recordErrorEvent,
|
|
32
|
+
recordStartEvent,
|
|
33
|
+
recordSuccessEvent,
|
|
34
|
+
setupEventChannel,
|
|
35
|
+
} from "../src/events";
|
|
36
|
+
|
|
37
|
+
const ORIGINAL = process.env.EVENTARC_CHANNEL;
|
|
38
|
+
|
|
39
|
+
beforeEach(() => vi.clearAllMocks());
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
if (ORIGINAL === undefined) delete process.env.EVENTARC_CHANNEL;
|
|
42
|
+
else process.env.EVENTARC_CHANNEL = ORIGINAL;
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
describe("no channel configured", () => {
|
|
46
|
+
test("publishers are a no-op when EVENTARC_CHANNEL is unset", async () => {
|
|
47
|
+
delete process.env.EVENTARC_CHANNEL;
|
|
48
|
+
setupEventChannel();
|
|
49
|
+
|
|
50
|
+
await recordStartEvent({ a: 1 });
|
|
51
|
+
await recordCompletionEvent({ a: 1 });
|
|
52
|
+
expect(publish).not.toHaveBeenCalled();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe("channel configured", () => {
|
|
57
|
+
beforeEach(() => {
|
|
58
|
+
process.env.EVENTARC_CHANNEL = "projects/p/locations/l/channels/c";
|
|
59
|
+
setupEventChannel();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("publishes the firestore-bigquery-export event type only", async () => {
|
|
63
|
+
await recordStartEvent({ a: 1 });
|
|
64
|
+
expect(publish).toHaveBeenCalledTimes(1);
|
|
65
|
+
expect(publish).toHaveBeenCalledWith(
|
|
66
|
+
expect.objectContaining({
|
|
67
|
+
type: "firebase.extensions.firestore-bigquery-export.v1.onStart",
|
|
68
|
+
})
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("error / success / completion map to their event types", async () => {
|
|
73
|
+
await recordErrorEvent(new Error("boom"));
|
|
74
|
+
await recordSuccessEvent({ subject: "doc1", data: { a: 1 } });
|
|
75
|
+
await recordCompletionEvent({ a: 1 });
|
|
76
|
+
|
|
77
|
+
const types = publish.mock.calls.map((c) => c[0].type);
|
|
78
|
+
expect(types).toEqual([
|
|
79
|
+
"firebase.extensions.firestore-bigquery-export.v1.onError",
|
|
80
|
+
"firebase.extensions.firestore-bigquery-export.v1.onSuccess",
|
|
81
|
+
"firebase.extensions.firestore-bigquery-export.v1.onCompletion",
|
|
82
|
+
]);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
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 { describe, expect, test } from "vitest";
|
|
18
|
+
import { resolveExportConfig, toTrackerConfig } from "../src/export-config";
|
|
19
|
+
|
|
20
|
+
describe("resolveExportConfig", () => {
|
|
21
|
+
const minimal = {
|
|
22
|
+
collectionPath: "users",
|
|
23
|
+
datasetId: "analytics",
|
|
24
|
+
tableId: "users",
|
|
25
|
+
location: "us-central1",
|
|
26
|
+
projectId: "test-project",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
test("applies defaults for omitted fields", () => {
|
|
30
|
+
const resolved = resolveExportConfig(minimal);
|
|
31
|
+
|
|
32
|
+
expect(resolved.projectId).toBe("test-project");
|
|
33
|
+
expect(resolved.datasetLocation).toBe("us");
|
|
34
|
+
expect(resolved.databaseId).toBe("(default)");
|
|
35
|
+
expect(resolved.viewType).toBe("view");
|
|
36
|
+
expect(resolved.wildcardIds).toBe(false);
|
|
37
|
+
expect(resolved.excludeOldData).toBe(false);
|
|
38
|
+
expect(resolved.clustering).toBeNull();
|
|
39
|
+
expect(resolved.logLevel).toBe("info");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("keeps caller-supplied values", () => {
|
|
43
|
+
const resolved = resolveExportConfig({
|
|
44
|
+
...minimal,
|
|
45
|
+
location: "europe-west2",
|
|
46
|
+
databaseId: "secondary",
|
|
47
|
+
wildcardIds: true,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
expect(resolved.location).toBe("europe-west2");
|
|
51
|
+
expect(resolved.databaseId).toBe("secondary");
|
|
52
|
+
expect(resolved.wildcardIds).toBe(true);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("carries required fields through", () => {
|
|
56
|
+
const resolved = resolveExportConfig(minimal);
|
|
57
|
+
expect(resolved.collectionPath).toBe("users");
|
|
58
|
+
expect(resolved.datasetId).toBe("analytics");
|
|
59
|
+
expect(resolved.tableId).toBe("users");
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe("toTrackerConfig", () => {
|
|
64
|
+
const base = {
|
|
65
|
+
collectionPath: "users",
|
|
66
|
+
datasetId: "analytics",
|
|
67
|
+
tableId: "users",
|
|
68
|
+
location: "us-central1",
|
|
69
|
+
projectId: "test-project",
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
test("derives materialized view flags from viewType", () => {
|
|
73
|
+
const plain = toTrackerConfig(resolveExportConfig(base));
|
|
74
|
+
expect(plain.useMaterializedView).toBe(false);
|
|
75
|
+
expect(plain.useIncrementalMaterializedView).toBe(false);
|
|
76
|
+
|
|
77
|
+
const incremental = toTrackerConfig(
|
|
78
|
+
resolveExportConfig({ ...base, viewType: "materialized_incremental" })
|
|
79
|
+
);
|
|
80
|
+
expect(incremental.useMaterializedView).toBe(true);
|
|
81
|
+
expect(incremental.useIncrementalMaterializedView).toBe(true);
|
|
82
|
+
|
|
83
|
+
const nonIncremental = toTrackerConfig(
|
|
84
|
+
resolveExportConfig({ ...base, viewType: "materialized_non_incremental" })
|
|
85
|
+
);
|
|
86
|
+
expect(nonIncremental.useMaterializedView).toBe(true);
|
|
87
|
+
expect(nonIncremental.useIncrementalMaterializedView).toBe(false);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("always skips init (initialization is handled lazily)", () => {
|
|
91
|
+
const tracker = toTrackerConfig(resolveExportConfig(base));
|
|
92
|
+
expect(tracker.skipInit).toBe(true);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("maps databaseId onto both firestore fields", () => {
|
|
96
|
+
const tracker = toTrackerConfig(
|
|
97
|
+
resolveExportConfig({ ...base, databaseId: "secondary" })
|
|
98
|
+
);
|
|
99
|
+
expect(tracker.databaseId).toBe("secondary");
|
|
100
|
+
expect(tracker.firestoreInstanceId).toBe("secondary");
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("uses projectId as the default BigQuery project", () => {
|
|
104
|
+
const tracker = toTrackerConfig(resolveExportConfig(base));
|
|
105
|
+
expect(tracker.bqProjectId).toBe("test-project");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("keeps an explicitly configured BigQuery project", () => {
|
|
109
|
+
const tracker = toTrackerConfig(
|
|
110
|
+
resolveExportConfig({ ...base, bqProjectId: "analytics-project" })
|
|
111
|
+
);
|
|
112
|
+
expect(tracker.bqProjectId).toBe("analytics-project");
|
|
113
|
+
});
|
|
114
|
+
});
|
|
@@ -0,0 +1,220 @@
|
|
|
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 { ChangeType } from "@firebaseextensions/firestore-bigquery-change-tracker";
|
|
18
|
+
import { beforeEach, describe, expect, test, vi } from "vitest";
|
|
19
|
+
import { resolveExportConfig } from "../src/export-config";
|
|
20
|
+
import {
|
|
21
|
+
type DocumentWriteEvent,
|
|
22
|
+
type HandlerContext,
|
|
23
|
+
handleDocumentWrite,
|
|
24
|
+
} from "../src/handlers";
|
|
25
|
+
|
|
26
|
+
vi.mock("../src/events");
|
|
27
|
+
vi.mock("../src/logs");
|
|
28
|
+
|
|
29
|
+
import * as events from "../src/events";
|
|
30
|
+
|
|
31
|
+
/** Fake Firestore snapshot with only the fields the handlers read. */
|
|
32
|
+
function snap(exists: boolean, id: string, data: unknown = {}) {
|
|
33
|
+
return { exists, id, data: () => data };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Fake document-write event. */
|
|
37
|
+
function writeEvent(
|
|
38
|
+
before: ReturnType<typeof snap>,
|
|
39
|
+
after: ReturnType<typeof snap>,
|
|
40
|
+
overrides: Partial<Record<string, unknown>> = {}
|
|
41
|
+
): DocumentWriteEvent {
|
|
42
|
+
return {
|
|
43
|
+
data: { before, after },
|
|
44
|
+
id: "evt-1",
|
|
45
|
+
time: "2026-01-01T00:00:00Z",
|
|
46
|
+
document: "users/doc1",
|
|
47
|
+
params: { documentId: "doc1" },
|
|
48
|
+
...overrides,
|
|
49
|
+
} as unknown as DocumentWriteEvent;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Builds a HandlerContext with spy tracker + config overrides. */
|
|
53
|
+
function makeCtx(
|
|
54
|
+
configOverrides: Record<string, unknown> = {}
|
|
55
|
+
): HandlerContext {
|
|
56
|
+
const tracker = {
|
|
57
|
+
record: vi.fn().mockResolvedValue(undefined),
|
|
58
|
+
serializeData: vi.fn((d: unknown) => d),
|
|
59
|
+
};
|
|
60
|
+
const config = {
|
|
61
|
+
...resolveExportConfig({
|
|
62
|
+
collectionPath: "users",
|
|
63
|
+
datasetId: "ds",
|
|
64
|
+
tableId: "tbl",
|
|
65
|
+
projectId: "test-project",
|
|
66
|
+
}),
|
|
67
|
+
...configOverrides,
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
tracker: tracker as unknown as HandlerContext["tracker"],
|
|
71
|
+
config: config as HandlerContext["config"],
|
|
72
|
+
ensureInitialized: vi.fn().mockResolvedValue(undefined),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
describe("handleDocumentWrite", () => {
|
|
77
|
+
beforeEach(() => vi.clearAllMocks());
|
|
78
|
+
|
|
79
|
+
test("returns early when the event has no data", async () => {
|
|
80
|
+
const ctx = makeCtx();
|
|
81
|
+
await handleDocumentWrite({ data: undefined } as DocumentWriteEvent, ctx);
|
|
82
|
+
expect(ctx.tracker.record).not.toHaveBeenCalled();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("CREATE records the new data, no old data", async () => {
|
|
86
|
+
const ctx = makeCtx();
|
|
87
|
+
const event = writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 }));
|
|
88
|
+
|
|
89
|
+
await handleDocumentWrite(event, ctx);
|
|
90
|
+
|
|
91
|
+
expect(ctx.tracker.record).toHaveBeenCalledTimes(1);
|
|
92
|
+
const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
|
|
93
|
+
.calls;
|
|
94
|
+
expect(recorded[0].operation).toBe(ChangeType.CREATE);
|
|
95
|
+
expect(recorded[0].data).toEqual({ a: 1 });
|
|
96
|
+
expect(recorded[0].oldData).toBeUndefined();
|
|
97
|
+
expect(events.recordStartEvent).toHaveBeenCalledTimes(1);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("UPDATE includes old data by default", async () => {
|
|
101
|
+
const ctx = makeCtx();
|
|
102
|
+
const event = writeEvent(
|
|
103
|
+
snap(true, "doc1", { a: 1 }),
|
|
104
|
+
snap(true, "doc1", { a: 2 })
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
await handleDocumentWrite(event, ctx);
|
|
108
|
+
|
|
109
|
+
const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
|
|
110
|
+
.calls;
|
|
111
|
+
expect(recorded[0].operation).toBe(ChangeType.UPDATE);
|
|
112
|
+
expect(recorded[0].data).toEqual({ a: 2 });
|
|
113
|
+
expect(recorded[0].oldData).toEqual({ a: 1 });
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("excludeOldData omits the previous state on update", async () => {
|
|
117
|
+
const ctx = makeCtx({ excludeOldData: true });
|
|
118
|
+
const event = writeEvent(
|
|
119
|
+
snap(true, "doc1", { a: 1 }),
|
|
120
|
+
snap(true, "doc1", { a: 2 })
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
await handleDocumentWrite(event, ctx);
|
|
124
|
+
|
|
125
|
+
const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
|
|
126
|
+
.calls;
|
|
127
|
+
expect(recorded[0].oldData).toBeUndefined();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("DELETE records no new data", async () => {
|
|
131
|
+
const ctx = makeCtx();
|
|
132
|
+
const event = writeEvent(snap(true, "doc1", { a: 1 }), snap(false, "doc1"));
|
|
133
|
+
|
|
134
|
+
await handleDocumentWrite(event, ctx);
|
|
135
|
+
|
|
136
|
+
const [[recorded]] = (ctx.tracker.record as ReturnType<typeof vi.fn>).mock
|
|
137
|
+
.calls;
|
|
138
|
+
expect(recorded[0].operation).toBe(ChangeType.DELETE);
|
|
139
|
+
expect(recorded[0].data).toBeUndefined();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("does not provision on the hot path", async () => {
|
|
143
|
+
const ctx = makeCtx();
|
|
144
|
+
await handleDocumentWrite(
|
|
145
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
146
|
+
ctx
|
|
147
|
+
);
|
|
148
|
+
expect(ctx.ensureInitialized).not.toHaveBeenCalled();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("wildcardIds gates whether path params are recorded", async () => {
|
|
152
|
+
const withIds = makeCtx({ wildcardIds: true });
|
|
153
|
+
await handleDocumentWrite(
|
|
154
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
155
|
+
withIds
|
|
156
|
+
);
|
|
157
|
+
const [[recordedWith]] = (
|
|
158
|
+
withIds.tracker.record as ReturnType<typeof vi.fn>
|
|
159
|
+
).mock.calls;
|
|
160
|
+
expect(recordedWith[0].pathParams).toEqual({ documentId: "doc1" });
|
|
161
|
+
|
|
162
|
+
const withoutIds = makeCtx({ wildcardIds: false });
|
|
163
|
+
await handleDocumentWrite(
|
|
164
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
165
|
+
withoutIds
|
|
166
|
+
);
|
|
167
|
+
const [[recordedWithout]] = (
|
|
168
|
+
withoutIds.tracker.record as ReturnType<typeof vi.fn>
|
|
169
|
+
).mock.calls;
|
|
170
|
+
expect(recordedWithout[0].pathParams).toBeNull();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("self-heals and retries the write when the inline write fails", async () => {
|
|
174
|
+
const ctx = makeCtx();
|
|
175
|
+
(ctx.tracker.record as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
|
|
176
|
+
new Error("bq down")
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
await handleDocumentWrite(
|
|
180
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
181
|
+
ctx
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
expect(ctx.ensureInitialized).toHaveBeenCalledTimes(1);
|
|
185
|
+
expect(ctx.tracker.record).toHaveBeenCalledTimes(2);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("rethrows when self-heal retry fails so runtime retry can replay", async () => {
|
|
189
|
+
const ctx = makeCtx();
|
|
190
|
+
(ctx.tracker.record as ReturnType<typeof vi.fn>)
|
|
191
|
+
.mockRejectedValueOnce(new Error("bq down"))
|
|
192
|
+
.mockRejectedValueOnce(new Error("still down"));
|
|
193
|
+
|
|
194
|
+
await expect(
|
|
195
|
+
handleDocumentWrite(
|
|
196
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
197
|
+
ctx
|
|
198
|
+
)
|
|
199
|
+
).rejects.toThrow("still down");
|
|
200
|
+
expect(ctx.ensureInitialized).toHaveBeenCalledTimes(1);
|
|
201
|
+
expect(events.recordErrorEvent).toHaveBeenCalled();
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test("rethrows when serialization fails", async () => {
|
|
205
|
+
const ctx = makeCtx();
|
|
206
|
+
(ctx.tracker.serializeData as ReturnType<typeof vi.fn>).mockImplementation(
|
|
207
|
+
() => {
|
|
208
|
+
throw new Error("bad data");
|
|
209
|
+
}
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
await expect(
|
|
213
|
+
handleDocumentWrite(
|
|
214
|
+
writeEvent(snap(false, "doc1"), snap(true, "doc1", { a: 1 })),
|
|
215
|
+
ctx
|
|
216
|
+
)
|
|
217
|
+
).rejects.toThrow("bad data");
|
|
218
|
+
expect(ctx.tracker.record).not.toHaveBeenCalled();
|
|
219
|
+
});
|
|
220
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
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 type { FirestoreBigQueryEventHistoryTracker } from "@firebaseextensions/firestore-bigquery-change-tracker";
|
|
18
|
+
import { describe, expect, test, vi } from "vitest";
|
|
19
|
+
import { createEnsureInitialized } from "../src/init";
|
|
20
|
+
|
|
21
|
+
function trackerWith(initialize: () => Promise<void>) {
|
|
22
|
+
return { initialize } as unknown as FirestoreBigQueryEventHistoryTracker;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe("createEnsureInitialized", () => {
|
|
26
|
+
test("initializes the tracker once across sequential calls", async () => {
|
|
27
|
+
const initialize = vi.fn().mockResolvedValue(undefined);
|
|
28
|
+
const ensureInitialized = createEnsureInitialized(trackerWith(initialize));
|
|
29
|
+
|
|
30
|
+
await ensureInitialized();
|
|
31
|
+
await ensureInitialized();
|
|
32
|
+
await ensureInitialized();
|
|
33
|
+
|
|
34
|
+
expect(initialize).toHaveBeenCalledTimes(1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("concurrent calls share a single in-flight initialization", async () => {
|
|
38
|
+
let release!: () => void;
|
|
39
|
+
const gate = new Promise<void>((resolve) => {
|
|
40
|
+
release = resolve;
|
|
41
|
+
});
|
|
42
|
+
const initialize = vi.fn().mockImplementation(() => gate);
|
|
43
|
+
const ensureInitialized = createEnsureInitialized(trackerWith(initialize));
|
|
44
|
+
|
|
45
|
+
const first = ensureInitialized();
|
|
46
|
+
const second = ensureInitialized();
|
|
47
|
+
release();
|
|
48
|
+
await Promise.all([first, second]);
|
|
49
|
+
|
|
50
|
+
expect(initialize).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("a failed initialization resets the guard so the next call retries", async () => {
|
|
54
|
+
const initialize = vi
|
|
55
|
+
.fn()
|
|
56
|
+
.mockRejectedValueOnce(new Error("transient"))
|
|
57
|
+
.mockResolvedValueOnce(undefined);
|
|
58
|
+
const ensureInitialized = createEnsureInitialized(trackerWith(initialize));
|
|
59
|
+
|
|
60
|
+
await expect(ensureInitialized()).rejects.toThrow("transient");
|
|
61
|
+
await expect(ensureInitialized()).resolves.toBeUndefined();
|
|
62
|
+
|
|
63
|
+
expect(initialize).toHaveBeenCalledTimes(2);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("a success is cached — no retry after resolution", async () => {
|
|
67
|
+
const initialize = vi.fn().mockResolvedValue(undefined);
|
|
68
|
+
const ensureInitialized = createEnsureInitialized(trackerWith(initialize));
|
|
69
|
+
|
|
70
|
+
await ensureInitialized();
|
|
71
|
+
initialize.mockClear();
|
|
72
|
+
await ensureInitialized();
|
|
73
|
+
|
|
74
|
+
expect(initialize).not.toHaveBeenCalled();
|
|
75
|
+
});
|
|
76
|
+
});
|