-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom-backend-task.ts
549 lines (473 loc) Β· 16.4 KB
/
custom-backend-task.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import * as util from "util"
import * as ChildProcess from 'child_process'
const execProm = util.promisify(ChildProcess.exec)
import { promises as fsp } from 'fs'
import * as fsSync from 'fs';
import { getPorts } from './get-port';
import * as Postgres from './postgresql';
import { homedir } from 'os'
import { resolve, dirname } from "path"
import * as H from './helpers';
const homeDir = homedir();
export async function print(logEntry: string): Promise<string> {
await H.log(logEntry);
return logEntry;
}
export async function printDebug(logEntry: string): Promise<string> {
await H.logDebug(logEntry);
return logEntry;
}
export async function requireEnv(name: string): Promise<string> {
const result = process.env[name];
if (result) {
return result;
} else {
throw `β requireEnv: No environment variable called ${name}
Available:
${Object.keys(process.env).join("\n")}
`;
}
}
export async function readEnv(name: string): Promise<string | null> {
const result = process.env[name];
if (result) {
return result;
} else {
return null;
}
}
export async function environmentPlatform(name: string): Promise<string> {
return process.platform;
}
export async function readFile(path: string): Promise<string> {
try {
const data = await fsp.readFile(resolvePath(path), 'utf8');
H.logDebug(`π readFile: ${resolvePath(path)}`);
return data;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β readFile: Could not read ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function writeFile({ path, contents }: { path: string, contents: string }): Promise<string> {
try {
const data = await fsp.writeFile(resolvePath(path), contents);
H.logDebug(`βοΈ writeFile: ${resolvePath(path)}`);
return contents;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β writeFile: Could not write ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function appendFile({ path, contents }: { path: string, contents: string }): Promise<string> {
try {
const data = await fsp.appendFile(resolvePath(path), contents);
H.logDebug(`βοΈ appendFile: ${resolvePath(path)}`);
return contents;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β appendFile: Could not append ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function touchFile({ path }: { path: string }): Promise<null> {
try {
const time = new Date();
await fsp.utimes(resolvePath(path), time, time).catch(async function (err) {
if (err.code !== 'ENOENT') {
throw err;
}
let fh = await fsp.open(resolvePath(path), 'a');
await fh.close();
H.logDebug(`π touchFile: ${resolvePath(path)}`);
});
return null;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β touchFile: Could not append ${resolvePath(path)}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function replaceInFile({ path, find, replace }: { path: string, find: string, replace: string }): Promise<string> {
try {
const newContents = await readFile(resolvePath(path)).then(contents => contents.replace(find, replace));
H.logDebug(`π replaceInFile: ${resolvePath(path)} (${find}) -> (${replace})`);
await writeFile({ path: resolvePath(path), contents: newContents });
return newContents;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β replaceInFile: Could not replace in ${path}: ${err}
Searching for ${find}
Replacing with ${replace}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function makeDirectory(path: string): Promise<string> {
try {
const data = await fsp.mkdir(resolvePath(path), { recursive: true });
H.logDebug(`π makeDirectory ${resolvePath(path)}`);
return "";
} catch (err) {
const cwd = process.cwd();
throw new Error(`β makeDirectory: Could not make directory ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function makeDirectories(paths: string[]): Promise<string> {
await Promise.all(paths.map(makeDirectory));
return "";
}
export async function changeDirectory(path: string): Promise<string> {
try {
process.chdir(resolvePath(path));
H.logDebug(`π changeDirectory ${resolvePath(path)}`);
return "";
} catch (err) {
const cwd = process.cwd();
throw new Error(`β changeDirectory: Could not change to directory ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function currentDirectory(): Promise<string> {
try {
const cwd = process.cwd();
H.logDebug(`π currentDirectory ${cwd}`);
return cwd;
} catch (err) {
const cwd = process.cwd();
throw new Error(`β currentDirectory: Could not get currentDirectory: ${err}
Current working directory: ${cwd}
`);
}
}
export async function remove(path: string): Promise<string> {
try {
const exists = await doesPathExist(resolvePath(path));
if (!exists) return "";
await fsp.rm(resolvePath(path), { recursive: true });
H.logDebug(`ποΈ remove: ${resolvePath(path)}`);
return "";
} catch (err) {
const cwd = process.cwd();
throw new Error(`β remove: Could not remove path ${path}: ${err}
Current working directory: ${cwd}
Resolved path: ${resolvePath(path)}
`);
}
}
export async function removeAll(paths: string[]): Promise<string> {
await Promise.all(paths.map(removeOrContinue));
return "";
}
export async function removeOrContinue(path: string): Promise<string> {
try {
await fsp.rm(resolvePath(path), { recursive: true });
H.logDebug(`ποΈ removeOrContinue: ${resolvePath(path)}`);
return "";
} catch (err) {
H.logDebug(`ποΈ βοΈ removeOrContinue: ${resolvePath(path)}`);
return "";
}
}
/*
Mimics the expected behaviour of cp on *nix systems
cp some/file.txt somedest -> somedest/file.txt
cp some/file.txt somedest/ -> somedest/file.txt
cp somesource somedest -> somedest/somesource # copies the directory
cp somesource/ somedest -> somedest/* # copies the contents of the directory
cp somesource/ somedest/ -> somedest/* # copies the contents of the directory
*/
export async function copy({ src, dest }: { src: string, dest: string }): Promise<string> {
try {
const resolvedSrc = resolvePath(src);
const resolvedDest = resolvePath(dest);
const srcStat = await fsp.stat(resolvedSrc); // This also ensures our source exists
const destStat: fsSync.Stats | null = await fsp.stat(resolvedDest).catch(() => null);
if (srcStat.isFile()) {
if (destStat && destStat.isDirectory()) {
let destPath = resolvedDest + '/' + src.split('/').pop();
if (resolvedDest.endsWith('/')) { destPath = resolvedDest + src.split('/').pop() }
H.logDebug(`βοΈ copy: ${resolvedSrc} -> ${destPath}`);
await fsp.cp(resolvedSrc, destPath);
return destPath;
}
// Otherwise we've already got a target filename, so use that
H.logDebug(`βοΈ copy: ${resolvedSrc} -> ${resolvedDest}`);
await fsp.cp(resolvedSrc, resolvedDest, { recursive: true });
return resolvedDest;
} else if (dest.endsWith('/')) {
// We're copying a directory, not its contents, so name it in the dest
const srcDir = src.split('/').pop();
const destPath = resolvedDest.endsWith(srcDir) ? resolvedDest : resolvedDest + '/' + src.split('/').pop();
await fsp.mkdir(destPath, { recursive: true });
H.logDebug(`βοΈ copy: ${resolvedSrc} -> ${destPath}`);
await fsp.cp(resolvedSrc, destPath, { recursive: true });
return destPath;
} else {
H.logDebug(`βοΈ copy: ${resolvedSrc} -> ${resolvedDest}`);
await fsp.cp(resolvedSrc, resolvedDest, { recursive: true });
return resolvedDest;
}
} catch (err) {
const cwd = process.cwd();
throw new Error(`β copy: Could not copy ${src} to ${dest}: ${err}
Current working directory: ${cwd}
Resolved src: ${resolvePath(src)}
Resolved dest: ${resolvePath(dest)}
`);
}
}
export async function move({ src, dest }: { src: string, dest: string }): Promise<string> {
try {
await fsp.rename(resolvePath(src), resolvePath(dest));
H.logDebug(`βοΈ move: ${resolvePath(src)} -> ${resolvePath(dest)}`);
return "";
} catch (err) {
const cwd = process.cwd();
throw new Error(`β move: Could not move ${src} to ${dest}: ${err}
Current working directory: ${cwd}
Resolved src: ${resolvePath(src)}
Resolved dest: ${resolvePath(dest)}
`);
}
}
export async function symlink({ src, dest }: { src: string, dest: string }): Promise<string> {
try {
await fsp.symlink(resolvePath(src), resolvePath(dest));
H.logDebug(`π symlink: ${resolvePath(src)} -> ${resolvePath(dest)}`);
return resolvePath(dest);
} catch (err) {
const cwd = process.cwd();
throw new Error(`β symlink: Could not symlink ${src} to ${dest}: ${err}
Current working directory: ${cwd}
Resolved src: ${resolvePath(src)}
Resolved dest: ${resolvePath(dest)}
`);
}
}
export async function homeDirectory(): Promise<string> {
try {
H.logDebug(`π homeDirectory`);
return homedir();
} catch (err) {
const cwd = process.cwd();
// Is this even possible as an error?
throw new Error(`β homeDirectory: Could not get home directory: ${err}
Current working directory: ${cwd}
`);
}
}
export async function doesPathExist(path: string): Promise<boolean> {
try {
const data = await fsp.stat(resolvePath(path));
H.logDebug(`π β
doesPathExist: ${path} `);
return true;
} catch (err) {
H.logDebug(`π β doesPathExist: ${path} `);
return false;
}
}
export async function getFreePort(): Promise<number> {
try {
const freePort = await getPorts();
return freePort;
} catch (err) {
throw new Error(`getFreePort: Could not get port: ${err}`);
}
}
// This can be done manually by calling exec or execStream
// export async function bash(command: string): Promise<ExecResult> {
// return exec({ bin: 'bash', args: ['-c', command] });
// }
type ExecResult = { exitCode: number, stdout: string, stderr: string };
export async function exec(p: { bin: string, args: string[] }): Promise<ExecResult> {
const { bin, args } = p;
H.logDebug(`π€ exec: ${resolvePath(bin)} ${args.map(resolvePath).join(" ")}`);
const res = await execA(resolvePath(bin), args.map(resolvePath)).catch((error) => {
H.logDebug('ββββ exec error', error);
process.exit();
});
// H.log(`res:`, res);
return res;
}
async function execA(bin: string, args: string[]): Promise<ExecResult> {
let result;
// H.logDebug(`execA running ${bin} ${args}`);
try {
// result = await execProm(bin + ' ' + args.join(" "), {}, (err, stdout, stderr) => {
// if (err) { console.error(err); return; }
// if (stderr) console.warn(stderr);
// if (stdout) H.log(stdout);
// H.log('HEEEEERE', err, { exitCode: err?.code ?? 0, stdout, stderr });
// return { exitCode: err?.code ?? 0, stdout, stderr };
// }).catch((err: ExecResult) => {
// H.log('ββββ exec error', err);
// return err;
// });
result = await execProm(bin + ' ' + args.join(" ")).catch((err: ExecResult) => {
H.logDebug('ββββ exec error', err);
return err;
});
// H.logDebug('ending`!!!!', result)
// execProm doesn't give us an exitCode on success, so we presume 0
// @TODO this is obviously wrong
result.exitCode = 0;
} catch(ex) {
// Shouldn't be possible but it is JS after all
H.logDebug('ββββ impossible error', ex);
throw Error(ex);
}
return result;
}
export async function execStreamQuiet(params: { bin: string, args: string[] }): Promise<ExecResult> {
return execStream(params, false);
}
export async function execStream(params: { bin: string, args: string[] }, printOutput: boolean = true): Promise<ExecResult> {
return new Promise(resolve => {
const { bin, args } = params;
let stdout = '';
let stderr = '';
H.logDebug(`π€π° execStream: ${resolvePath(bin)} ${args.map(resolvePath).join(" ")}`);
const p = ChildProcess.spawn(resolvePath(bin), args.map(resolvePath), {
cwd: process.cwd(),
env: process.env
});
p.stdout.on('data', function (data) {
if (printOutput) {
H.log(data.toString());
} else {
H.logDebug(data.toString());
}
stdout += data.toString();
});
p.stderr.on('data', function (data) {
if (printOutput) {
H.log(data.toString());
} else {
H.logDebug(data.toString());
}
stderr += data.toString();
});
p.on('exit', function (code, signal) {
if (code == 0 ) {
H.logDebug(`β
execStream: ${bin} exited with code ${code.toString()} and signal ${signal}`);
} else {
H.logDebug(`β execStream: ${bin} exited with code ${code.toString()} and signal ${signal}`);
}
return resolve({ exitCode: code, stdout, stderr });
});
p.on('error', function (error) {
H.logDebug(`β execStream: ${bin} encountered an error ${error}`);
return resolve({ exitCode: null, stdout, stderr });
});
p.on('close', function (code, signal) {
H.logDebug(`β execStream: ${bin} closed with code ${code} and signal ${signal}`);
});
});
}
async function execRaw(command: string): Promise<ExecResult> {
let result;
try {
result = await execProm(command).catch((err: ExecResult) => {
return err;
});
// execProm doesn't give us an exitCode on success, so we presume 0
result.exitCode = 0;
} catch(ex) {
// Shouldn't be possible but it is JS after all
throw Error(ex);
}
return result;
}
/**
* Run a shell command in a completely detached process that may live on after the parent process dies.
* Returns the PID of the detached process.
*/
export async function execDetached(params: { bin: string, args: string[] }): Promise<number> {
H.logDebug(`π€π§ββοΈ execDetached: ${resolvePath(params.bin)} ${params.args.map(resolvePath).join(" ")}`);
const sout = await fsp.open(H.runLogPath + '-spawn', 'a') as any;
const serr = await fsp.open(H.runLogPath + '-spawn', 'a') as any;
process.on('exit', async () => {
// @TODO is there a reason these couldn't just be inline after the unref() ?
fsSync.closeSync(sout);
fsSync.closeSync(serr);
});
const child = ChildProcess.spawn(params.bin, params.args, {
detached: true,
// stdio: 'ignore'
stdio: ['ignore', sout, serr]
});
child.unref();
return child.pid;
}
function resolvePath(path: string): string {
if (!path) return path;
// H.log('trying to resolve path', path);
if (path.match(/^~\//)) return path.replace(/^~/, homeDir);
return path;
}
export async function exit(): Promise<void> {
H.logDebug('π exit');
process.exit();
}
export async function die(code: number): Promise<void> {
H.logDebug(`π die: ${code}`);
process.exit(code);
}
export async function sleep(ms: number): Promise<void> {
return new Promise(r => setTimeout(r, ms));
}
export async function postgresRawQuery(data: { sql: string }): Promise<any> {
H.logDebug(`πΏ postgresRawQuery:`, data);
const str = await Postgres.db.raw(data.sql).then((result: any) => {
H.logDebug('results was', result);
if (result.length > 0) {
const rows = result.filter((row: any) => row.command === 'SELECT')[0];
H.logDebug('rows', rows);
if (rows?.rows) return JSON.stringify(rows.rows);
return JSON.stringify(result);
} else {
return JSON.stringify(result.rows);
}
}).catch(err => {
H.logDebug('postgresRawQuery', err);
Postgres.cleanup();
throw Error(err);
});
return str;
}
export async function postgresRawQueryJSON(data: { sql: string }): Promise<any> {
H.logDebug(`πΏ postgresRawQueryJSON:`, data);
const str = await Postgres.db.raw(data.sql).then((result: any) => {
// H.logDebug('results was', result);
if (result.length > 0) {
const rows = result.filter((row: any) => row.command === 'SELECT')[0];
// H.logDebug('rows', rows.rows);
return rows.rows;
} else {
// H.logDebug('rows', result.rows);
return result.rows;
}
}).catch(err => {
H.logDebug('postgresRawQuery', err);
Postgres.cleanup();
throw Error(err);
});
return str;
}