/
bigqueryIndex.ts
424 lines (389 loc) · 11.7 KB
/
bigqueryIndex.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
export const dependencies = {
"@google-cloud/bigquery": "^5.5.0",
};
const get = (obj, path, defaultValue = undefined) => {
const travel = (regexp) =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce(
(res, key) => (res !== null && res !== undefined ? res[key] : res),
obj
);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
const filterSnapshot = (
field: { docPath: string; snapshot: any },
preservedKeys: string[]
) => {
return {
docPath: field.docPath,
...preservedKeys.reduce((acc: any, currentKey: string) => {
const value = get(field.snapshot, currentKey);
if (value) {
return { ...acc, snapshot: { [currentKey]: value, ...acc.snapshot } };
} else return acc;
}, {}),
};
};
// returns object of fieldsToSync
const rowReducer = (fieldsToSync, row) =>
fieldsToSync.reduce(
(
acc: any,
curr: string | { fieldName: string; snapshotFields: string[] }
) => {
if (typeof curr === "string") {
if (row[curr] && typeof row[curr].toDate === "function") {
return {
...acc,
[curr]: row[curr].toDate().getTime() / 1000,
};
} else if (row[curr] !== undefined || row[curr] !== null) {
return { ...acc, [curr]: row[curr] };
} else {
return acc;
}
} else {
if (row[curr.fieldName] && curr.snapshotFields) {
return {
...acc,
[curr.fieldName]: row[curr.fieldName].map((snapshot) =>
filterSnapshot(snapshot, curr.snapshotFields)
),
};
} else {
return acc;
}
}
},
{}
);
const significantDifference = (fieldsToSync, change) => {
const beforeData = change.before.data();
const afterData = change.after.data();
return fieldsToSync.reduce((acc, field) => {
const key = typeof field === "string" ? field : field.fieldName;
if (JSON.stringify(beforeData[key]) !== JSON.stringify(afterData[key]))
return true;
else return acc;
}, false);
};
const transformToSQLData = (value: any, ftType: string) => {
if (value === null || value === undefined) {
return {
value: `null`,
type: "STRING",
};
}
const sanitise = (x: string) =>
x?.replace?.(/\"/g, '\\"')?.replace?.(/\n/g, "\\n") ?? "";
switch (ftType) {
case "SIMPLE_TEXT":
case "LONG_TEXT":
case "EMAIL":
case "PHONE_NUMBER":
case "CODE":
case "RICH_TEXT":
case "ID":
case "SINGLE_SELECT":
case "URL":
return {
value: `"${sanitise(value)}"`,
type: "STRING",
};
case "JSON": // JSON
case "FILE": // JSON
case "IMAGE": // JSON
case "USER": // JSON
case "COLOR": // JSON
case "DOCUMENT_SELECT":
case "SERVICE_SELECT":
case "ACTION":
case "AGGREGATE":
case "MULTI_SELECT": // array
return {
value: `"${sanitise(JSON.stringify(value))}"`,
type: "STRING",
};
case "CHECK_BOX":
return {
value: value ? `true` : `false`,
type: "BOOLEAN",
};
case "NUMBER":
case "PERCENTAGE":
case "RATING":
case "SLIDER":
return {
value: Number(value),
type: "NUMERIC",
};
case "DATE":
case "DATE_TIME":
case "DURATION":
if (!value?.toDate) {
return {
value: `null`,
type: "TIMESTAMP",
};
}
return {
value: `timestamp("${value?.toDate?.()}")`,
type: "TIMESTAMP",
};
case "LAST":
case "STATUS":
case "SUB_TABLE":
default:
// unknown or meaningless to sync
return {
value: `null`,
type: "STRING",
};
}
};
const transformToSQLValue = (ftValue: any, ftType: string) => {
const { value } = transformToSQLData(ftValue, ftType);
return value;
};
const transformToSQLType = (ftType: string) => {
const { type } = transformToSQLData("", ftType);
return type;
};
const bigqueryIndex = async (payload, sparkContext) => {
const { objectID, index, fieldsToSync, projectID, datasetLocation } = payload;
const { triggerType, change, fieldTypes } = sparkContext;
const record = rowReducer(fieldsToSync, sparkContext.row);
const { BigQuery } = require("@google-cloud/bigquery");
const bigquery = new BigQuery();
const _projectID = projectID ?? process.env.GCLOUD_PROJECT;
const tableFullName = `${_projectID}.firetable.${index}`;
console.log(
`projectID: ${_projectID}, index: ${index}, tableFullName: ${tableFullName}`
);
// create dataset with exact name "firetable" if not exists
async function preprocessDataset() {
const dataset = bigquery.dataset("firetable", {
location: datasetLocation ?? "US",
});
const res = await dataset.exists();
const exists = res[0];
if (!exists) {
console.log("Dataset 'firetable' does not exist, creating dataset...");
await dataset.create();
console.log("Dataset 'firetable' created.");
} else {
console.log("Dataset 'firetable' exists.");
}
}
async function preprocessTable() {
const dataset = bigquery.dataset("firetable");
const table = dataset.table(index);
const res = await table.exists();
const exists = res[0];
if (!exists) {
console.log(
`Table '${index}' does not exist in dataset 'firetable', creating dataset...`
);
await table.create();
console.log(`Table '${index}' created in dataset 'firetable'.`);
} else {
console.log(`Table ${index} exists in 'firetable'.`);
}
}
async function preprocessSchema() {
const dataset = bigquery.dataset("firetable");
const table = dataset.table(index);
const generatedTypes = Object.keys(fieldTypes)
.filter((field) => fieldsToSync.includes(field))
.reduce((acc, cur) => {
return {
[cur]: transformToSQLType(fieldTypes[cur]),
...acc,
};
}, {});
const generatedSchema = [
{ name: "objectID", type: "STRING", mode: "REQUIRED" },
...Object.keys(generatedTypes).map((key) => {
return {
name: key,
type: generatedTypes[key],
mode: "NULLABLE",
};
}),
];
const pushSchema = async () => {
console.log("pushing schema:", generatedSchema);
const metadata = {
schema: generatedSchema,
};
await table.setMetadata(metadata);
console.log("schema pushed.");
};
const existingRes = await table.getMetadata();
const existingSchema = existingRes[0].schema?.fields;
if (!existingSchema) {
console.log("Existing schema does not exist, pushing schema...");
await pushSchema();
return;
}
// check if schema update is needed
const objectIDFilter = (field) => field.name !== "objectID";
const schemaIdentical =
Object.keys(generatedTypes).length ===
existingSchema.filter(objectIDFilter).length &&
existingSchema
.filter(objectIDFilter)
.every((field) => generatedTypes[field.name] === field.type);
if (schemaIdentical) {
// no change to schema
console.log("Existing schema detected, no update needeed.");
return;
}
// check schema compatibility (only new field is accpted)
const compatible =
Object.keys(generatedTypes).length >
existingSchema.filter(objectIDFilter).length &&
existingSchema
.filter(objectIDFilter)
.filter((field) => Object.keys(generatedTypes).includes(field.name))
.every((field) => generatedTypes[field.name] === field.type);
if (!compatible) {
const errorMessage =
"New update to field types is not compatible with existing schema. Please manually remove the current bigquery table or update spark index";
console.log(errorMessage);
throw errorMessage;
} else {
console.log(
"New field types detected and it is compatible with current schema."
);
}
// push schema
await pushSchema();
}
// return if the objectID exists in bool
async function exist() {
const query = `SELECT objectID FROM ${tableFullName}
WHERE objectID="${objectID}"
;`;
console.log(query);
const res = await bigquery.query(query);
const rows = res?.[0];
return !!rows?.length;
}
function getTypeKnownRecord(data) {
const knownTypes = Object.keys(fieldTypes);
const givenKeys = Object.keys(data);
const knownKeys = givenKeys.filter((key) => knownTypes.includes(key));
const unknownKeys = givenKeys.filter((key) => !knownTypes.includes(key));
const knownRecord = Object.keys(data)
.filter((key) => knownKeys.includes(key))
.reduce((obj, key) => {
return {
...obj,
[key]: data[key],
};
}, {});
if (unknownKeys?.length > 0) {
console.log(
"The following fields do not exist in Firetable and are ignored.",
unknownKeys
);
}
return knownRecord;
}
async function insert(data) {
const keys = Object.keys(data).join(",");
const values = Object.keys(data)
.map((key) => transformToSQLValue(data[key], fieldTypes[key]))
.join(",");
const query = `INSERT INTO ${tableFullName}
(objectID, ${keys})
VALUES ("${objectID}", ${values})
;`;
console.log(query);
await executeQuery(query);
}
// execute a query, if rate limited, sleep and try again until success
// ATTENTION: cloud function might timeout the function execution time at 60,000ms
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function executeQuery(query, delayDepth = 1) {
try {
const res = await bigquery.query(query);
console.log(res);
} catch (error) {
if (
error?.errors?.length === 1 &&
(error?.errors?.[0]?.reason === "rateLimitExceeded" ||
error?.errors?.[0]?.reason === "quotaExceeded")
) {
const delay = Math.round(
Math.floor(Math.random() * 3_000 * (delayDepth % 20) + 1000)
);
console.log(`API rate limited, try again in ${delay}ms`);
await sleep(delay);
await executeQuery(query, delayDepth + 1);
} else {
console.log(error?.errors ?? error);
}
}
if (delayDepth === 1) {
console.log("Query finished.");
}
}
async function update(data) {
const values = Object.keys(data)
.map((key) => `${key}=${transformToSQLValue(data[key], fieldTypes[key])}`)
.join(",");
const query = `UPDATE ${tableFullName}
SET ${values}
WHERE objectID="${objectID}"
;`;
console.log(query);
await executeQuery(query);
}
async function insertOrUpdate(data) {
const objectExists = await exist();
if (objectExists) {
await update(data);
} else {
await insert(data);
}
}
async function remove() {
const query = `DELETE FROM ${tableFullName}
WHERE objectID="${objectID}"
;`;
console.log(query);
await executeQuery(query);
}
// preprocess before starting index logic
await preprocessDataset();
await preprocessTable();
await preprocessSchema();
// only proceed with fields that have known types
const typeKnownRecord = getTypeKnownRecord(record);
switch (triggerType) {
case "delete":
await remove();
break;
case "update":
if (
significantDifference([...fieldsToSync, "_ft_forcedUpdateAt"], change)
) {
await insertOrUpdate(typeKnownRecord);
} else {
console.log("significantDifference is false, no update needed.");
}
break;
case "create":
await insertOrUpdate(typeKnownRecord);
break;
default:
break;
}
return true;
};
export default bigqueryIndex;