-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproc_manager.ts
More file actions
683 lines (636 loc) · 20.8 KB
/
proc_manager.ts
File metadata and controls
683 lines (636 loc) · 20.8 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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import { AnsiParser } from 'ansi-parser/interfaces/ansi-parser';
import { decodeAnsiBytes, defaultAnsiParser } from 'ansi-parser/src';
import cp from 'cross-spawn';
import ttyGlobal from 'tty';
import { envVarNames } from '../constants/ipc';
import crossKillGlobal from './cross_kill';
import { applyActionToSty, defaultStyContext, restoreSty, StyContext } from './sty';
interface CrossSpawnParams {
command: string;
args: string[];
cwd?: string;
env?: NodeJS.ProcessEnv | undefined;
}
type CrossProcessReadable = {
readonly on: (name: 'data', handler: (buf: Buffer) => void) => void;
readonly off: (name: 'data', handler: (buf: Buffer) => void) => void;
};
type CrossProcess = {
readonly pid?: number | undefined;
readonly once: (name: 'exit', handler: (exitCode: number | null) => void) => void;
readonly stdout: CrossProcessReadable;
readonly stderr: CrossProcessReadable;
};
export type CrossSpawn = (params: CrossSpawnParams) => CrossProcess;
export type ProcStatus = 'waiting' | 'running' | 'killed' | 'finished';
export interface ProcOwn {
readonly command: string;
readonly cwd: string;
readonly npmPath: string;
}
export interface ProcOwnInternal {
command: string;
cwd: string;
npmPath: string;
// $raw?: childProcess.ChildProcessWithoutNullStreams;
$raw?: CrossProcess;
}
export interface LogOwn {
readonly currentSty: StyContext;
readonly currentParser: AnsiParser;
}
export interface LogOwnInternal {
currentSty: StyContext;
currentParser: AnsiParser;
}
export interface LogLineMain {
timestamp?: Date;
read: boolean;
id: number;
content: LogContent;
}
export interface LogLineMainReadonly {
readonly timestamp?: Date;
readonly content: LogContentReadonly;
}
export interface LogLine {
title: string;
main: LogLineMain;
}
export interface LogLineReadonly {
readonly title: string;
readonly main: LogLineMain;
}
export type LogLines = LogLine[];
export type LogLinesReadonly = readonly LogLineReadonly[];
export type LogContent = Array<
| {
readonly type: 'style';
readonly bytes: Uint8Array;
}
| {
readonly type: 'print';
readonly byte: number;
}
>;
export type LogContentReadonly = Readonly<LogContent>;
export interface LogAccumulated {
readonly lineCount: number;
readonly lines: LogLinesReadonly;
}
export interface LogAccumulatedInternal {
lineCount: number;
lines: LogLines;
$unreadLines: Set<LogLine>;
$lastLineToTitle: Record<string, LogLine>;
}
export type ProcNodeType = 'none' | 'serial' | 'parallel';
export interface ProcNode {
readonly name: string;
readonly type: ProcNodeType;
readonly parent?: ProcNode;
readonly procOwn?: ProcOwn;
readonly logOwn?: LogOwn;
readonly exitCode?: number | null;
readonly children: readonly ProcNode[];
readonly token: string;
readonly status: ProcStatus;
readonly logAccumulated: LogAccumulated;
readonly logOmitted: boolean;
readonly addUpdateListener: AddUpdateListener;
readonly removeUpdateListener: RemoveUpdateListener;
readonly ignored: boolean;
}
export interface ProcNodeInternal {
name: string;
type: ProcNodeType;
parent?: ProcNodeInternal;
procOwn?: ProcOwnInternal;
logOwn?: LogOwnInternal;
children: ProcNodeInternal[];
token: string;
status: ProcStatus;
exitCode?: number | null;
logAccumulated: LogAccumulatedInternal;
logOmitted: boolean;
npmPath?: string;
addUpdateListener: AddUpdateListener;
removeUpdateListener: RemoveUpdateListener;
ignored: boolean;
$notifyUpdate: () => void;
}
export type ProcNodeInternalInitial = Omit<
ProcNodeInternal,
'token' | 'addUpdateListener' | 'removeUpdateListener' | '$notifyUpdate'
>;
export type FindNodeByToken = (token?: string | undefined) => ProcNode | undefined;
export type FindNodeByTokenInternal = (token?: string | undefined) => ProcNodeInternal | undefined;
export type CreateNodeParams = Omit<
ProcNode,
| 'parent'
| 'children'
| 'token'
| 'addUpdateListener'
| 'removeUpdateListener'
| 'logAccumulated'
| 'logOwn'
| 'logOmitted'
| 'ignored'
> & { parentToken?: string | undefined };
export type CreateNode = (createNodeParams: CreateNodeParams) => ProcNode | null;
export type RestartNode = (node?: ProcNode | null | undefined) => void;
export type RestartAllNode = (node?: ProcNode | null | undefined) => void;
export type KillNode = (node?: ProcNode | null | undefined) => void;
export type KillAllNode = (node?: ProcNode | null | undefined) => void;
export type UpdateListener = () => void;
export type AddUpdateListener = (updateListener: UpdateListener) => void;
export type RemoveUpdateListener = (updateListener: UpdateListener) => void;
export type MarkNodeAsRead = (node?: ProcNode | null | undefined) => void;
export interface ProcManager {
readonly createNode: CreateNode;
readonly restartNode: RestartNode;
readonly restartAllNode: RestartAllNode;
readonly killNode: KillNode;
readonly killAllNode: KillAllNode;
readonly rootNode: ProcNode;
readonly addUpdateListener: AddUpdateListener;
readonly removeUpdateListener: RemoveUpdateListener;
readonly findNodeByToken: FindNodeByToken;
readonly markNodeAsRead: MarkNodeAsRead;
}
const $createEmptyLogAccumulated = (): LogAccumulatedInternal => {
return {
lineCount: 0,
lines: [],
$unreadLines: new Set(),
$lastLineToTitle: {},
};
};
export const createEmptyLogAccumulated = (): LogAccumulated => {
return $createEmptyLogAccumulated();
};
const crossSpawnGlobal: CrossSpawn = ({ env, cwd, args, command }) => {
return cp.spawn(command, args, {
stdio: ['pipe', 'pipe', 'pipe'],
env,
cwd,
});
};
export interface CreateProcManagerParams {
isColorSupported: boolean;
enableUnreadMarker: boolean;
historyAlwaysKeepHeadSize: number;
historyCacheSize: number;
// for test
tty?: typeof ttyGlobal;
crossSpawn?: CrossSpawn;
crossKill?: typeof crossKillGlobal;
}
export const createProcManager = ({
isColorSupported,
enableUnreadMarker,
historyAlwaysKeepHeadSize,
historyCacheSize,
crossKill: crossKill0,
crossSpawn: crossSpawn0,
}: CreateProcManagerParams): ProcManager => {
const crossSpawn: CrossSpawn = crossSpawn0 ?? crossSpawnGlobal;
const crossKill = crossKill0 ?? crossKillGlobal;
const RESET = isColorSupported ? '\x1b[0m' : '';
const YELLOW = isColorSupported ? '\x1b[33m' : '';
const $updateListenerSet = new Set<UpdateListener>();
// Call when tree structure changed.
const $notifyUpdate = (): void => {
[...$updateListenerSet].forEach((listener) => {
listener();
});
};
const $tokenToNodeMap = new Map<string, ProcNodeInternal>();
const $checkSerial = (node: ProcNodeInternalInitial) => {
if (node.status === 'running' && node.type === 'serial' && node.children.length > 0) {
if (node.children[0].status === 'waiting') {
$startRunning(node.children[0]);
} else {
for (let i = 0; i + 1 < node.children.length; i += 1) {
if (node.children[i].status === 'finished' && node.children[i + 1].status === 'waiting') {
$startRunning(node.children[i + 1]);
}
}
}
}
};
const $createNode = (nodeInitial: ProcNodeInternalInitial): ProcNodeInternal => {
const $updateListenerSet = new Set<UpdateListener>();
const addUpdateListener: AddUpdateListener = (listener) => {
$updateListenerSet.add(listener);
};
const removeUpdateListener: RemoveUpdateListener = (listener) => {
$updateListenerSet.delete(listener);
};
const token = (() => {
while (true) {
const tmpToken = Math.random().toString().slice(2, 14);
if ($tokenToNodeMap.has(tmpToken)) continue;
return tmpToken;
}
})();
const node: ProcNodeInternal = {
...nodeInitial,
addUpdateListener,
removeUpdateListener,
token,
$notifyUpdate: (): void => {
const children = node.children.filter((child) => !child.ignored);
if (children.length > 0) {
node.status = (() => {
const statuses = children.map((child) => child.status);
const allKilled = Math.max(...statuses.map((s) => (s === 'killed' ? 0 : 1))) === 0;
const allFinished = Math.max(...statuses.map((s) => (s === 'finished' ? 0 : 1))) === 0;
const allWaiting = Math.max(...statuses.map((s) => (s === 'waiting' ? 0 : 1))) === 0;
if (node.procOwn && allKilled) return 'killed';
if (allFinished) return 'finished';
if (allWaiting) return 'waiting';
return 'running';
})();
node.exitCode = children.reduce((accum, n) => accum || n.exitCode, null as null | number | undefined);
}
$checkSerial(node);
if (children.length > 0) {
const knownTitle: Record<string, boolean> = {};
node.logAccumulated.lineCount = 0;
const beingAdded: LogLines = [];
for (const child of children) {
node.logAccumulated.lineCount += child.logAccumulated.lineCount;
let title = child.name;
let titleCnt = 0;
while (knownTitle[title]) {
titleCnt += 1;
title = `${child.name}(${titleCnt})`;
}
knownTitle[title] = true;
const childLines = child.logAccumulated.lines;
const realLen =
childLines.length === 0
? 0
: childLines[childLines.length - 1].main.timestamp
? childLines.length
: childLines.length - 1;
if (realLen > 0) {
const lastLine = node.logAccumulated.$lastLineToTitle[title] as LogLine | undefined;
let from = 0;
if (lastLine) {
from = realLen;
while (
from >= 1 &&
childLines[from - 1].main.id !== -1 &&
childLines[from - 1].main.id !== lastLine.main.id
)
from -= 1;
}
node.logAccumulated.$lastLineToTitle[title] = childLines[realLen - 1];
beingAdded.push(...childLines.slice(from, realLen).map((e) => ({ title, main: e.main })));
}
}
const lines = node.logAccumulated.lines;
const beingAddedSorted = beingAdded.sort((a, b) => a.main.timestamp!.getTime() - b.main.timestamp!.getTime());
lines.push(...beingAddedSorted);
if (enableUnreadMarker) {
const unreadLines = node.logAccumulated.$unreadLines;
beingAddedSorted.forEach((e) => {
unreadLines.add(e);
});
}
}
// This should be done before wiping out the history.
node.parent?.$notifyUpdate();
// Wiping out the history.
{
const lines = node.logAccumulated.lines;
const headSize = Math.max(0, historyAlwaysKeepHeadSize);
const tailSize = Math.max(1, historyCacheSize + 1);
if (lines.length > headSize + tailSize) {
node.logOmitted = true;
const head = node.logAccumulated.lines.slice(0, headSize);
let tail = node.logAccumulated.lines.slice(headSize);
if (enableUnreadMarker) {
const unreadLines = node.logAccumulated.$unreadLines;
tail.slice(0, -tailSize).forEach((line) => {
unreadLines.delete(line);
});
}
tail = tail.slice(-tailSize);
node.logAccumulated.lines = [
...head,
{
title: '[NOTIOS]',
main: {
id: -1,
read: true,
timestamp: new Date(0),
content: [
{
type: 'style',
bytes: Uint8Array.from(Buffer.from(`${RESET}${YELLOW}`)),
} as const,
...[...Buffer.from(`[NOTIOS] HISTORY DROPPED`)].map((b) => ({ type: 'print', byte: b } as const)),
{
type: 'style',
bytes: Uint8Array.from(Buffer.from(`${RESET}`)),
} as const,
],
},
},
...tail,
];
}
}
[...$updateListenerSet].forEach((listener) => {
listener();
});
},
};
$tokenToNodeMap.set(token, node);
return node;
};
const $appendLogToNode = (newLog: Buffer, node: ProcNodeInternal) => {
if (!node.logOwn) throw new Error('[INTERNAL UNREACHABLE ERROR]: appending to log-accumulate-only node');
const [newParser, actions] = decodeAnsiBytes(node.logOwn.currentParser, new Uint8Array(newLog));
node.logOwn.currentParser = newParser;
for (const action of actions) {
const lines = node.logAccumulated.lines;
const unreadLines = node.logAccumulated.$unreadLines;
if (lines.length === 0) {
const title = '';
const logLine: LogLine = {
main: {
timestamp: undefined,
read: false,
id: node.logAccumulated.lineCount,
content: [],
},
title,
};
lines.push(logLine);
if (enableUnreadMarker) {
unreadLines.add(logLine);
}
node.logAccumulated.$lastLineToTitle[title] = logLine;
}
const lastLine = lines[lines.length - 1];
const checkTimestamp = (line: LogLine) => {
if (!line.main.timestamp) {
line.main.timestamp = new Date();
node.logAccumulated.lineCount += 1;
}
};
switch (action.actionType) {
case 'print':
checkTimestamp(lastLine);
lastLine.main.content.push({
type: 'print',
byte: action.byte,
});
break;
case 'controll':
switch (action.char) {
case '\t':
checkTimestamp(lastLine);
lastLine.main.content.push({
type: 'print',
byte: 0x20,
});
break;
case '\n': {
checkTimestamp(lastLine);
const title = '';
const logLine: LogLine = {
main: {
timestamp: undefined,
read: false,
id: node.logAccumulated.lineCount,
content: [
{
type: 'style',
bytes: restoreSty(node.logOwn.currentSty),
},
],
},
title,
};
lines.push(logLine);
if (enableUnreadMarker) {
unreadLines.add(logLine);
}
node.logAccumulated.$lastLineToTitle[title] = logLine;
break;
}
default:
// ignore
break;
}
break;
default:
node.logOwn.currentSty = applyActionToSty(node.logOwn.currentSty, action);
lastLine.main.content.push({
type: 'style',
bytes: restoreSty(node.logOwn.currentSty),
});
break;
}
}
};
const $createEmptyLogOwn = (): LogOwnInternal => {
return {
currentSty: defaultStyContext(),
currentParser: defaultAnsiParser(),
};
};
const rootNode = $createNode({
name: '<root>',
status: 'waiting',
type: 'none',
logOwn: $createEmptyLogOwn(),
logAccumulated: $createEmptyLogAccumulated(),
logOmitted: false,
children: [],
ignored: false,
});
const findNodeByToken: FindNodeByTokenInternal = (token) => {
if (typeof token === 'string') {
return $tokenToNodeMap.get(token);
}
return rootNode;
};
const $startRunning = (node: ProcNodeInternal) => {
node.status = 'running';
if (!node.procOwn) {
$checkSerial(node);
return;
}
const nodeStdout = $createNode({
name: '<out>',
status: 'running',
type: 'none',
logOwn: $createEmptyLogOwn(),
logAccumulated: $createEmptyLogAccumulated(),
logOmitted: false,
children: [],
ignored: false,
});
const nodeStderr = $createNode({
name: '<err>',
status: 'running',
type: 'none',
logOwn: $createEmptyLogOwn(),
logAccumulated: $createEmptyLogAccumulated(),
logOmitted: false,
children: [],
ignored: false,
});
node.children = [nodeStdout, nodeStderr, ...node.children];
nodeStdout.parent = node;
nodeStderr.parent = node;
$notifyUpdate();
const p = crossSpawn({
command: node.procOwn.npmPath,
args: ['run', node.name],
// stdio: ['pipe', 'pipe', 'pipe'],
cwd: node.procOwn.cwd,
env: {
...process.env,
...(isColorSupported
? {
npm_config_color: 'always',
NO_COLOR: undefined,
FORCE_COLOR: 'true',
CARGO_TERM_COLOR: 'always',
}
: {
npm_config_color: 'false',
NO_COLOR: 'true',
FORCE_COLOR: '0',
CARGO_TERM_COLOR: 'none',
}),
[envVarNames.rootToken]: rootNode.token,
[envVarNames.parentToken]: node.token,
},
});
node.procOwn.$raw = p;
node.$notifyUpdate();
const stdoutDataListener = (buf: Buffer) => {
$appendLogToNode(buf, nodeStdout);
nodeStdout.$notifyUpdate();
};
const stderrDataListener = (buf: Buffer) => {
$appendLogToNode(buf, nodeStderr);
nodeStderr.$notifyUpdate();
};
p.stdout.on('data', stdoutDataListener);
p.stderr.on('data', stderrDataListener);
p.once('exit', (exitCode) => {
if (nodeStdout.status === 'running') {
nodeStdout.status = 'finished';
}
if (nodeStderr.status === 'running') {
nodeStderr.status = 'finished';
}
nodeStdout.exitCode = exitCode;
nodeStderr.exitCode = exitCode;
nodeStdout.$notifyUpdate();
nodeStderr.$notifyUpdate();
p.stdout.off('data', stdoutDataListener);
p.stderr.off('data', stderrDataListener);
});
};
const createNode: CreateNode = ({ parentToken, ...params }) => {
// Just ignore if spawn request is from older world.
const parentNode: ProcNodeInternal | undefined = findNodeByToken(parentToken);
if (parentNode == null) return null;
const node = $createNode({
...params,
logOwn: $createEmptyLogOwn(),
logAccumulated: $createEmptyLogAccumulated(),
logOmitted: false,
children: [],
ignored: false,
});
parentNode.children.push(node);
node.parent = parentNode;
if (params.procOwn && params.status === 'running') {
$startRunning(node);
}
return node;
};
const addUpdateListener: AddUpdateListener = (listener) => {
$updateListenerSet.add(listener);
};
const removeUpdateListener: RemoveUpdateListener = (listener) => {
$updateListenerSet.delete(listener);
};
const restartNode: RestartNode = (node) => {
if (!node) return;
const inode: ProcNodeInternal = node as any;
if (!inode.procOwn) return;
if (inode.status !== 'finished' && inode.status !== 'killed') return;
inode.children[0].ignored = true;
inode.children[1].ignored = true;
$startRunning(inode);
$appendLogToNode(Buffer.from(`${RESET}${YELLOW}[NOTIOS] MANUALLY RESTARTED${RESET}\n`), inode.children[0]);
};
const restartAllNode: RestartAllNode = (node) => {
if (!node) return;
restartNode(node);
node.children.forEach((c) => {
restartAllNode(c);
});
};
const killNode: KillNode = (node) => {
if (!node) return;
const inode: ProcNodeInternal = node as any;
if (!inode.procOwn) return;
if (!inode.procOwn.$raw) return;
if (inode.status !== 'running') return;
crossKill(inode.procOwn.$raw.pid);
delete inode.procOwn.$raw;
inode.status = 'killed';
inode.children[0].status = 'killed';
inode.children[1].status = 'killed';
$appendLogToNode(Buffer.from(`\n${RESET}${YELLOW}[NOTIOS] MANUALLY KILLED${RESET}\n`), inode.children[0]);
inode.$notifyUpdate();
};
const killAllNode: KillAllNode = (node) => {
if (!node) return;
killNode(node);
node.children.forEach((c) => {
killAllNode(c);
});
};
const markNodeAsRead: MarkNodeAsRead = (node) => {
if (!enableUnreadMarker) return;
if (!node) return;
const inode: ProcNodeInternal = node as any;
const internal = (inode: ProcNodeInternal) => {
[...inode.logAccumulated.$unreadLines].forEach((line) => {
line.main.read = true;
});
inode.logAccumulated.$unreadLines.clear();
inode.children.forEach((c) => {
internal(c);
});
};
internal(inode);
inode.$notifyUpdate();
};
return {
createNode,
restartNode,
restartAllNode,
killNode,
killAllNode,
rootNode,
addUpdateListener,
removeUpdateListener,
findNodeByToken,
markNodeAsRead,
};
};