forked from frank-zsy/clickhouse-github-log-importer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimporter_worker.js
60 lines (55 loc) · 1.74 KB
/
importer_worker.js
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
/* eslint-disable @typescript-eslint/no-var-requires */
const { parentPort } = require('worker_threads');
const { existsSync, createReadStream } = require('fs');
const ParseFuncMap = require('./parser');
const { createGunzip } = require('zlib');
const { createInterface } = require('readline');
const { createClient } = require('@clickhouse/client');
const { Readable } = require('stream');
async function insertRecords(filePath, dbConfig) {
return new Promise(async resolve => {
try {
if (!existsSync(filePath)) {
resolve(true);
return;
}
// open file stream
const unzip = createGunzip();
const fileStream = createReadStream(filePath).pipe(unzip).on('error', resolve);
const rl = createInterface({
input: fileStream,
crlfDelay: Infinity,
});
const stream = new Readable({
objectMode: true,
read: () => { /* stub */ },
});
rl.on('line', line => {
try {
const item = JSON.parse(line);
const row = ParseFuncMap.get(item.type)?.call(undefined, item);
if (row) { stream.push(row); }
} catch {
console.log(`Error on parse record, line=${line}`);
}
});
rl.on('close', () => { stream.push(null); });
// open database stream
const client = createClient(dbConfig.serverConfig);
await client.insert({
table: dbConfig.table,
values: stream,
format: 'JSONEachRow',
});
await client.close();
resolve(true);
} catch (e) {
console.error(e);
resolve(false);
}
});
}
parentPort?.on('message', async param => {
const result = await insertRecords(param.filePath, param.dbConfig);
parentPort?.postMessage(result);
});