-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
316 lines (276 loc) · 8.12 KB
/
Copy pathindex.js
File metadata and controls
316 lines (276 loc) · 8.12 KB
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
#! /usr/bin/env node
/*
----
DWH MIXPANEL
by AK
purpose: stream events/users/groups/tables into mixpanel... from the warehouse!
----
*/
/*
-----------
MIDDLEWARE
these are the main 'connectors'
for all the sources
-----------
*/
import createStream from "./middleware/mixpanel.js";
import bigQuery from './middleware/bigquery.js';
import snowflake from './middleware/snowflake.js';
import athena from './middleware/athena.js';
import azure from "./middleware/azure.js";
import salesforce from "./middleware/salesforce.js";
/*
----
DEPS
----
*/
import esMain from 'es-main';
import cli from './components/cli.js';
import messageBus from './components/emitter.js';
import Config from "./components/config.js";
import env from './components/env.js';
import u from 'ak-tools';
import mp from 'mixpanel-import';
import { pEvent } from 'p-event';
import { resolve } from 'path';
import _ from "lodash";
import c from 'ansi-colors';
/*
--------
PIPELINE
--------
*/
/**
* stream a SQL query from your data warehouse into mixpanel!
* @example
* const results = await dwhMixpanel(params)
* console.log(results.mixpanel) // { duration: 3461, success: 420, responses: [], errors: [] }
* @param {import('./index.d.ts').Params} params your streaming configuration
* @returns {Promise<import('./index.d.ts').Summary>} summary of the job containing metadata about time/throughput/responses
*/
async function main(params) {
// * TRACKING
const track = u.tracker('dwh-mixpanel');
const runId = u.uid();
track('start', { runId });
// * ENV VARS
const envVars = env();
// * CONFIG
const config = new Config(
_.merge(
u.clone(params), //params take precedence over env
u.clone(envVars)
)
);
if (config.verbose) u.cLog(c.red('\nSTART!'));
const emitter = messageBus();
listeners(emitter);
const { type, version, warehouse } = config;
const props = { runId, type, version, warehouse };
try {
config.validate();
props.type = config.type;
props.warehouse = config.warehouse;
props.version = config.version;
track('valid', props);
}
catch (e) {
track('invalid config', { ...props, reason: e });
console.error(`configuration is invalid! reason:\n\n\t${e}\n\nquitting...\n\n`);
process.exit(0);
}
// don't allow strict mode imports if no insert_id it supplied
if (config.type === 'event' && config.options.strict && !config.mappings.insert_id_col) {
if (config.verbose) u.cLog('\tstrict mode imports are not possible without $insert_id; turning strict mode off...');
config.options.strict = false;
delete config.mappings.insert_id_col;
}
config.etlTime.start();
//* MIXPANEL STREAM
const mpStream = createStream(config, emitter);
//* DWH STREAM
let dwh;
try {
switch (config.warehouse) {
case 'bigquery':
dwh = await bigQuery(config, mpStream, emitter);
break;
case 'snowflake':
dwh = await snowflake(config, mpStream, emitter);
break;
case 'athena':
dwh = await athena(config, mpStream, emitter);
break;
case 'azure':
dwh = await azure(config, mpStream, emitter);
break;
case 'salesforce':
dwh = await salesforce(config, mpStream, emitter);
break;
default:
if (config.verbose) u.cLog(`i do not know how to access ${config.warehouse}... sorry`);
mpStream.destroy();
track('unsupported warehouse', props);
throw new Error('unsupported warehouse', { cause: config.warehouse, config });
}
}
catch (e) {
track('warehouse error', { ...props, msg: e.message });
if (config.verbose) {
console.log(c.redBright.bold(`\n${config.warehouse.toUpperCase()} ERROR:`));
console.log(c.redBright.bold(e.message));
}
// else {
// u.cLog(e, `${config.warehouse} error: ${e.message}`, `CRITICAL`);
// }
mpStream.destroy();
throw e;
}
// ? SPECIAL CASE: lookup tables cannot be streamed as batches
if (config.type === 'table') {
mpStream.destroy();
emitter.emit('mp import start', config);
const tableImport = await mp(config.mpAuth(), dwh, { ...config.mpOpts(), logs: false });
config.store(tableImport, 'mp');
emitter.emit('mp import end', config);
}
else {
// * WAIT
try {
await pEvent(emitter, 'mp import end');
mpStream.destroy();
} catch (e) {
u.cLog(e, c.red('UNKNOWN FAILURE'), 'CRITICAL');
throw e;
}
}
// * LOGS + CLEANUP
const result = config.summary();
if (config.options.logFile) {
try {
const fileName = resolve(config.options.logFile);
const logFile = await u.touch(fileName, result, true, false, true);
if (config.verbose) {
u.cLog(c.gray(`logs written to ${logFile}\n\n`));
}
}
catch (e) {
if (config.verbose) {
u.cLog(c.red('failed to write logs'));
u.cLog(result, `RESULT`, 'INFO');
}
}
}
track('end', props);
return result;
}
/*
---------
LISTENERS
---------
*/
function listeners(emitter) {
emitter.once('dwh query start', (config) => {
config.queryTime.start();
if (config.verbose) u.cLog(c.cyan(`\n${config.dwh} query start`));
});
emitter.once('dwh query end', (config) => {
config.queryTime.end(false);
if (config.verbose) {
u.cLog(c.cyan(`${config.dwh} query end`));
u.cLog(c.cyan(`\t${config.warehouse} took ${config.queryTime.report(false).human}\n`));
}
});
emitter.once('dwh stream start', (config) => {
config.streamTime.start();
if (config.verbose) {
// u.cLog(`\n${config.dwh} stream start`);
u.cLog(c.magenta(`\nstreaming started! (${config.dwhStore.rows > 0 ? u.comma(config.dwhStore.rows) : "unknown number of"} ${config.type}s)\n`));
config.progress({ total: config.dwhStore.rows, startValue: 0 });
}
});
emitter.once('dwh stream end', (config) => {
config.streamTime.end(false);
if (config.verbose) {
// u.cLog(`${config.dwh} stream end`);
// u.cLog(`\t${config.warehouse} took ${config.streamTime.report(false).human}\n`);
}
});
emitter.once('mp import start', (config) => {
config.importTime.start();
if (config.verbose) {
// u.cLog(`\nmixpanel import start`);
config.progress({ total: config.dwhStore.rows, startValue: 0 }, 'mp');
}
});
emitter.once('mp import end', (config) => {
config.importTime.end(false);
config.etlTime.end(false);
const summary = config.summary();
const successRate = u.round(summary.mixpanel.success / summary.mixpanel.total * 100, 2);
const importTime = config.importTime.report(false).delta;
const evPerSec = Math.floor((config.inCount / importTime) * 1000);
if (config.verbose) {
config.progress(); //stop progress bars
// u.cLog(`\nmixpanel import end`);
// u.cLog(`\tmixpanel took ${config.importTime.report(false).human}\n`);
u.cLog(c.magenta('\nstreaming ended!'));
u.cLog(c.red(`\nCOMPLETE!`));
u.cLog(c.yellow(`\tprocessed ${u.comma(summary.mixpanel.total)} ${config.type}s in ${summary.time.job.human}`));
u.cLog(c.yellow(`\t(${successRate}% success rate; ~${u.comma(evPerSec)} EPS)`));
u.cLog(`\ncheck out your data!\n` + c.blue.underline(`https://mixpanel.com/project/${config.mpAuth().project}\n`));
}
});
emitter.on('dwh batch', (config) => {
if (config.verbose) {
try {
config.progress(1, 'dwh');
}
catch (e) {
//noop
}
}
});
emitter.on('mp batch', (config, numImported) => {
if (config.verbose) {
try {
config.progress(numImported, 'mp');
}
catch (e) {
//noop
}
}
});
}
/*
--------
EXPORTS
--------
*/
export default main;
//this fires when the module is run as a standalone script
if (esMain(import.meta)) {
cli().then(answers => {
const { params, run } = answers;
//multiline fix for priv keys
if (answers.params.auth?.private_key) answers.params.auth.private_key = answers.params.auth.private_key.replaceAll("\\n", "\n");
if (run) {
params.options.verbose = true;
return main(params);
}
else {
u.cLog('\nnothing left to do\n\no_0\n\n');
process.exit(0);
}
}).then(() => {
//noop
}).catch((e) => {
u.cLog(`\nuh oh! something didn't work...\nthe error message is:\n\n\t${e.message}\n\n`);
u.cLog(`take a closer look at your config file and try again (it's usually credentials!)\n`);
u.cLog(`if you continue to be stuck, file an issue:\nhttps://github.com/ak--47/dwh-mixpanel/issues\n\n`);
process.exit(1);
}).finally(() => {
u.cLog('\n\nhave a great day!\n\n');
process.exit(0);
});
}