-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
330 lines (306 loc) · 9.45 KB
/
index.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
import type { ChildProcess, ChildProcessByStdio } from 'node:child_process';
import type { Readable, Writable } from 'node:stream';
import stripAnsi from 'strip-ansi';
export enum Phase {
Stopped = 'stopped',
Stopping = 'stopping',
Starting = 'starting',
Started = 'started',
}
export type State = Readonly<
{ phase: Phase.Stopped } | { phase: Phase.Stopping | Phase.Starting | Phase.Started; pid: number }
>;
export interface Manager {
getState: () => State;
start: (timeout?: number) => Promise<number>;
stop: (timeout?: number) => Promise<void | number>;
}
// nano redux (no middleware or subscribers)
function createReducer<S, A>(params: { state: S; reducer: (state: S, action: A) => S }) {
const { reducer } = params;
let { state } = params;
return {
dispatch: (action: A) => {
state = reducer(state, action);
},
getState: (): S => state,
};
}
type InternalState = Readonly<
| { phase: Phase.Stopped }
| {
phase: Phase.Starting;
pid: number;
child: ChildProcess;
pending: { promise: Promise<number>; action: StartAction };
}
| {
phase: Phase.Stopping;
pid: number;
child: ChildProcess;
pending: { promise: Promise<number>; action: StopAction };
}
| { phase: Phase.Started; pid: number; child: ChildProcess }
>;
enum ActionType {
Start = 'start',
Stop = 'stop',
Complete = 'complete',
Fail = 'fail',
}
interface StartAction {
readonly type: ActionType.Start;
readonly timeout?: number;
}
interface StopAction {
readonly type: ActionType.Stop;
readonly timeout?: number;
}
interface CompleteAction {
readonly type: ActionType.Complete;
readonly action: StartAction | StopAction;
}
enum FailType {
Close = 'close',
Timeout = 'timeout',
}
interface FailAction {
readonly type: ActionType.Fail;
readonly action: StartAction | StopAction;
readonly reason: FailType;
}
function errorForFail(fail: FailAction): Error {
const { type: verb } = fail.action;
switch (fail.reason) {
case FailType.Close:
return new Error(`The process failed to ${verb} because it closed`);
case FailType.Timeout:
return new Error(`Timeout waiting for process to ${verb}`);
// no default
}
}
/**
* Takes a list of patterns and a starting pattern index.
* Returns the first index of the pattern that doesn't match.
* Patterns start testing after the previous match in the string.
*/
function nextPatternIndex(start = 0, patterns: RegExp[], str: string) {
let index = start;
let lastIndex = 0;
const sliced = patterns.slice(start);
for (const pattern of sliced) {
pattern.lastIndex = lastIndex;
if (!pattern.test(str)) return index;
lastIndex = pattern.lastIndex;
index++;
}
return -1;
}
/**
* Takes a list of patterns and iterates over them
* on every 'data' event from a node process object.
* Patterns are expected to match in the order they are given.
* When the patterns are all matched this returns true.
*/
function createIsStartedTest(isStartedPatterns?: ReadonlyArray<RegExp>) {
if (isStartedPatterns == null) return () => true;
// eslint-disable-next-line security/detect-non-literal-regexp
const patterns = isStartedPatterns.map((it) => new RegExp(it, 'g'));
let index = 0;
return function isStartedTest(chunk: { toString(): string } | null): boolean {
if (chunk) {
const str = stripAnsi(chunk.toString());
index = nextPatternIndex(index, patterns, str);
return index === -1;
}
return false;
};
}
function createLogger(getState: () => State, name: string) {
function prefix(): string {
const state = getState();
return state.phase !== Phase.Stopped ? `${name}(${state.phase}, ${state.pid}):` : `${name}(${state.phase}):`;
}
return {
info: (str: string) => console.info(prefix(), str),
warn: (str: string) => console.warn(prefix(), str),
error: (str: string) => console.error(prefix(), str),
};
}
function assertPid(child: ChildProcess): number {
if (child?.pid == null) throw new Error('Child process failed to spawn');
return child.pid;
}
export interface Options {
spawn: () => ChildProcessByStdio<Writable | null, Readable, Readable | null>;
isStartedPatterns?: ReadonlyArray<RegExp>;
logger?: typeof createLogger;
name?: string;
startTimeout?: number;
stopTimeout?: number;
}
export default function create(opts: Options): Manager {
const { spawn, isStartedPatterns, logger, name = 'ChildProcess', startTimeout, stopTimeout } = opts;
const { dispatch, getState } = createReducer({
state: { phase: Phase.Stopped },
reducer(state: InternalState, action: StartAction | StopAction | CompleteAction | FailAction): InternalState {
switch (action.type) {
case ActionType.Start:
return reduceStartAction(state, action);
case ActionType.Stop:
return reduceStopAction(state, action);
case ActionType.Complete:
return reduceCompleteAction(state, action);
case ActionType.Fail:
return reduceFailAction(state, action);
// no default
}
},
});
const log = (logger ?? createLogger)(getState, name);
function reduceStartAction(state: InternalState, action: StartAction): InternalState {
switch (state.phase) {
case Phase.Stopped:
case Phase.Stopping: {
log.info(`will ${action.type}`);
const child = spawn();
const pid = assertPid(child);
const isStartedTest = createIsStartedTest(isStartedPatterns);
const promise = isStartedTest(null)
? Promise.resolve(pid)
.finally(() => dispatch({ type: ActionType.Complete, action }))
: new Promise<number>(function (resolve, reject) {
function dataListener(chunk: { toString(): string }) {
if (isStartedTest(chunk)) {
finish({ type: ActionType.Complete, action });
resolve(pid);
}
}
function closeListener() {
const fail = { type: ActionType.Fail, action, reason: FailType.Close } as const;
finish(fail);
reject(errorForFail(fail));
}
function timeout() {
const fail = { type: ActionType.Fail, action, reason: FailType.Timeout } as const;
finish(fail);
child.kill();
reject(errorForFail(fail));
}
function finish(action: CompleteAction | FailAction) {
clearTimeout(timer);
child.off('close', closeListener);
child.stdout.off('data', dataListener);
dispatch(action);
}
const timer = setTimeout(timeout, action.timeout);
child.once('close', closeListener);
child.stdout.on('data', dataListener);
});
return { phase: Phase.Starting, pid, child, pending: { action, promise } };
}
default:
log.info(`already ${state.phase}`);
return state;
}
}
function reduceStopAction(state: InternalState, action: StopAction): InternalState {
switch (state.phase) {
case Phase.Started:
case Phase.Starting: {
log.info(`will ${action.type}`);
const { pid, child } = state;
const promise = new Promise<number>(function (resolve, reject) {
function closeListener() {
finish({ type: ActionType.Complete, action });
resolve(pid);
}
function timeout() {
const fail = { type: ActionType.Fail, action, reason: FailType.Timeout } as const;
finish(fail);
reject(errorForFail(fail));
}
function finish(action: CompleteAction | FailAction) {
clearTimeout(timer);
child.off('close', closeListener);
dispatch(action);
}
const timer = setTimeout(timeout, action.timeout);
child.once('close', closeListener);
child.kill();
});
return { phase: Phase.Stopping, pid, child, pending: { action, promise } };
}
default:
log.info(`already ${state.phase}`);
return state;
}
}
function reduceCompleteAction(state: InternalState, complete: CompleteAction): InternalState {
const { type: verb } = complete.action;
switch (state.phase) {
case Phase.Starting:
case Phase.Stopping:
if (state.pending.action === complete.action) {
log.info(`${verb} did complete`);
return verb === ActionType.Start
? { phase: Phase.Started, pid: state.pid, child: state.child }
: { phase: Phase.Stopped };
}
break;
// no default
}
console.log(complete, state);
log.warn(`${verb} did cancel (already ${state.phase})`);
return state;
}
function reduceFailAction(state: InternalState, fail: FailAction): InternalState {
const { type: verb } = fail.action;
switch (state.phase) {
case Phase.Starting:
case Phase.Stopping:
if (state.pending.action === fail.action) {
log.error(`${verb} failed (reason: ${fail.reason})`);
return verb === ActionType.Start
? { phase: Phase.Stopped }
: { phase: Phase.Started, pid: state.pid, child: state.child };
}
break;
// no default
}
log.warn(`${verb} did cancel (reason: ${fail.reason})`);
return state;
}
function assertPromise(phase: Phase.Starting | Phase.Stopping) {
const state = getState();
if (state.phase !== phase) {
throw new Error(`Unexpected phase ${state.phase}, expected ${phase}`);
}
return state.pending.promise;
}
return {
getState,
start: async (timeout = startTimeout) => {
const state = getState();
switch (state.phase) {
case Phase.Started:
log.info(`already ${state.phase}`);
return state.pid;
default:
dispatch({ type: ActionType.Start, timeout });
return await assertPromise(Phase.Starting);
}
},
stop: async (timeout = stopTimeout) => {
const state = getState();
switch (state.phase) {
case Phase.Stopped:
log.info(`already ${state.phase}`);
return;
default:
dispatch({ type: ActionType.Stop, timeout });
return await assertPromise(Phase.Stopping);
}
},
};
}