File size: 6,202 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { spawn } from 'node:child_process';
import { PassThrough } from 'node:stream';

import { describe, expect, test } from 'vitest';

import { SSHProcess } from '#/ssh';

/**
 * Build a minimal fake ssh2 ClientChannel that satisfies SSHProcess's needs:
 *
 * - behaves as a Readable (for stdout) via PassThrough
 * - exposes .stderr as a Readable via a second PassThrough
 * - records .signal() and .close() calls
 * - emits 'close' / 'exit' on-demand
 */
function createFakeChannel(): {
  channel: unknown;
  signalCalls: string[];
  closeCalls: number;
  emitClose: () => void;
  emitExit: (code: number) => void;
} {
  const stdout = new PassThrough();
  const stderr = new PassThrough();
  const signalCalls: string[] = [];
  let closeCalls = 0;

  // Listeners registered via channel.on(...)
  const listeners = new Map<string, Array<(...args: unknown[]) => void>>();

  const channel = Object.assign(stdout, {
    stderr,
    signal(name: string): void {
      signalCalls.push(name);
    },
    close(): void {
      closeCalls++;
    },
    // Override .on to capture lifecycle listeners ('close', 'exit') while
    // still letting the underlying Readable receive 'data'/'end'/'error'.
    on(event: string, cb: (...args: unknown[]) => void): unknown {
      if (event === 'close' || event === 'exit') {
        let arr = listeners.get(event);
        if (!arr) {
          arr = [];
          listeners.set(event, arr);
        }
        arr.push(cb);
        return channel;
      }
      return PassThrough.prototype.on.call(stdout, event, cb);
    },
  });

  function emit(event: string, ...args: unknown[]): void {
    const arr = listeners.get(event);
    if (!arr) return;
    for (const cb of arr) {
      cb(...args);
    }
  }

  return {
    channel,
    signalCalls,
    get closeCalls() {
      return closeCalls;
    },
    emitClose: () => {
      emit('close');
    },
    emitExit: (code: number) => {
      emit('exit', code);
    },
  };
}

function createChildBackedChannel(): { channel: unknown } {
  const child = spawn(process.execPath, [
    '-e',
    [
      "process.on('SIGTERM', () => {",
      "  console.log('cleanup done');",
      '  process.exit(42);',
      '});',
      "console.log('ready');",
      'setInterval(() => {}, 1000);',
    ].join('\n'),
  ]);

  const stdout = new PassThrough();
  child.stdout.pipe(stdout);

  const channel = Object.assign(stdout, {
    stderr: child.stderr,
    signal(name: string): void {
      child.kill(`SIG${name}` as NodeJS.Signals);
    },
    close(): void {
      child.kill('SIGTERM');
    },
    on(event: string, listener: (...args: unknown[]) => void): unknown {
      if (event === 'exit' || event === 'close') {
        child.on(event, listener as (...args: [number | null]) => void);
        return channel;
      }
      return PassThrough.prototype.on.call(stdout, event, listener);
    },
  });

  return { channel };
}

describe('SSHProcess.kill()', () => {
  test('kill("SIGTERM") sends "TERM" to channel.signal (strips SIG prefix)', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    await proc.kill('SIGTERM');

    expect(fake.signalCalls).toEqual(['TERM']);
    expect(fake.closeCalls).toBe(0);
  });

  test('kill("SIGINT") sends "INT"', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    await proc.kill('SIGINT');

    expect(fake.signalCalls).toEqual(['INT']);
  });

  test('kill("SIGKILL") sends "KILL"', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    await proc.kill('SIGKILL');

    expect(fake.signalCalls).toEqual(['KILL']);
  });

  test('kill() with no signal defaults to "TERM"', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    await proc.kill();

    expect(fake.signalCalls).toEqual(['TERM']);
  });

  test('kill() with a signal that does not start with "SIG" is passed through unchanged', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    // Cast through unknown because NodeJS.Signals is a string-literal type.
    await proc.kill('USR1' as unknown as NodeJS.Signals);

    expect(fake.signalCalls).toEqual(['USR1']);
  });

  test('wait() resolves with the exit code emitted before close', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    // Fire exit first, then close.
    fake.emitExit(42);
    fake.emitClose();

    const code = await proc.wait();
    expect(code).toBe(42);
    expect(proc.exitCode).toBe(42);
  });

  test('wait() resolves with 1 (abnormal) when close arrives without exit', async () => {
    const fake = createFakeChannel();
    const proc = new SSHProcess(fake.channel as never);

    fake.emitClose();

    const code = await proc.wait();
    expect(code).toBe(1);
    expect(proc.exitCode).toBe(1);
  });

  test.skipIf(process.platform === 'win32')('kill(SIGTERM) preserves cleanup output and the real exit status', async () => {
    const { channel } = createChildBackedChannel();
    const proc = new SSHProcess(channel as never);
    const stdoutChunks: Buffer[] = [];

    proc.stdout.on('data', (chunk: Buffer) => {
      stdoutChunks.push(Buffer.from(chunk));
    });
    const stdoutEnded = new Promise<void>((resolve) => {
      proc.stdout.on('end', () => {
        resolve();
      });
    });

    const firstChunk = await new Promise<Buffer>((resolve) => {
      proc.stdout.once('data', (chunk: Buffer) => {
        resolve(chunk);
      });
    });
    expect(firstChunk.toString()).toContain('ready');

    await proc.kill('SIGTERM');

    const exitCode = await proc.wait();
    await Promise.race([
      stdoutEnded,
      new Promise<void>((resolve) => {
        setTimeout(resolve, 250);
      }),
    ]);
    const stdout = Buffer.concat(stdoutChunks).toString('utf-8');

    expect(exitCode).toBe(42);
    expect(proc.exitCode).toBe(42);
    expect(stdout).toContain('ready');
    expect(stdout).toContain('cleanup done');
  }, 10000);
});