File size: 3,951 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { ChildProcess, spawn } from 'child_process'
import split2 from 'split2'
import treeKill from 'tree-kill'
import pidusage from 'pidusage-tree'
import { PREVIOUS, reportMeasurement } from './describe.js'

export interface Command {
  ok(): Promise<void>
  kill(): Promise<void>
  end(): Promise<number>
  waitForOutput(regex: RegExp): Promise<RegExpMatchArray>
  reportMemUsage(
    metricName: string,
    options: {
      relativeTo?: string | typeof PREVIOUS
      scenario?: string
      props?: Record<string, string | number | null>
    }
  ): Promise<void>
  stdout: string
  stderr: string
  output: string
}

const shellOutput = !!process.env.SHELL_OUTPUT

class CommandImpl {
  stdout: string = ''
  stderr: string = ''
  output: string = ''
  exitPromise: Promise<number>
  waitingForOutput: (() => void)[] = []
  constructor(private process: ChildProcess) {
    process.stdout?.pipe(split2()).on('data', (data) => {
      const str = data.toString()
      this.stdout += str + '\n'
      this.output += str + '\n'
      if (shellOutput) {
        console.log(`[STDOUT] ${str}`)
      }
      if (this.waitingForOutput.length !== 0) {
        const waitingForOutput = this.waitingForOutput
        this.waitingForOutput = []
        for (const fn of waitingForOutput) {
          fn()
        }
      }
    })
    process.stderr?.pipe(split2()).on('data', (data) => {
      const str = data.toString()
      this.stderr += str + '\n'
      this.output += str + '\n'
      if (shellOutput) {
        console.log(`[STDERR] ${str}`)
      }
      if (this.waitingForOutput.length !== 0) {
        const waitingForOutput = this.waitingForOutput
        this.waitingForOutput = []
        for (const fn of waitingForOutput) {
          fn()
        }
      }
    })
    this.exitPromise = new Promise<number>((resolve, reject) => {
      process.on('error', reject)
      process.on('exit', resolve)
    })
  }

  async ok() {
    const exitCode = await this.exitPromise
    if (exitCode !== 0) {
      throw new Error(
        `Command exited with code ${exitCode}\n\nOutput:\n${this.output}`
      )
    }
  }

  async end() {
    return await this.exitPromise
  }

  async kill() {
    const pid = this.process.pid!
    await new Promise<void>((resolve, reject) =>
      treeKill(pid, (err) => {
        if (err) reject(err)
        else resolve()
      })
    )
    await this.exitPromise
  }

  async waitForOutput(regex: RegExp) {
    let start = this.output.length
    while (true) {
      const match = this.output.slice(start).match(regex)
      if (match) {
        return match
      }
      const waitResult = await Promise.race([
        this.exitPromise,
        new Promise<void>((resolve) => {
          this.waitingForOutput.push(resolve)
        }).then(() => 'output'),
      ])
      if (waitResult !== 'output') {
        throw new Error(
          `Command exited with code ${waitResult}\n\nOutput:\n${this.output}`
        )
      }
    }
  }

  async reportMemUsage(
    metricName: string,
    options: {
      relativeTo?: string | typeof PREVIOUS
      scenario?: string
      props?: Record<string, string | number | null>
    } = {}
  ) {
    try {
      const pid = this.process.pid!
      const report = await pidusage(pid)
      const memUsage = Object.values(report)
        .filter((x) => x)
        .map((x) => (x as any).memory)
        .reduce((a, b) => a + b, 0)
      await reportMeasurement(metricName, memUsage, 'bytes', options)
    } catch (e) {
      // ignore
    }
  }
}

export function command(
  command: string,
  args: string[],
  options: {
    env?: Record<string, string>
    cwd?: string
  } = {}
): Command {
  const process = spawn(command, args, {
    shell: true,
    ...options,
    stdio: ['ignore', 'pipe', 'pipe'],
  })
  if (shellOutput) {
    console.log(
      `[SHELL] ${command} ${args.join(' ')} ${JSON.stringify(options)}`
    )
  }
  return new CommandImpl(process)
}