File size: 6,452 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
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
import { createConnection } from 'node:net'
import { Writable } from 'node:stream'
import type { StackFrame } from '../compiled/stacktrace-parser'
import { parse as parseStackTrace } from '../compiled/stacktrace-parser'
import { getProperError } from './error'

export type StructuredError = {
  name: string
  message: string
  stack: StackFrame[]
  cause: StructuredError | undefined
}

export function structuredError(e: unknown): StructuredError {
  e = getProperError(e)

  return {
    name: e.name,
    message: e.message,
    stack: typeof e.stack === 'string' ? parseStackTrace(e.stack) : [],
    cause: e.cause ? structuredError(getProperError(e.cause)) : undefined,
  }
}

type State =
  | {
      type: 'waiting'
    }
  | {
      type: 'packet'
      length: number
    }

export type Ipc<TIncoming, TOutgoing> = {
  recv(): Promise<TIncoming>
  send(message: TOutgoing): Promise<void>
  sendError(error: Error | string): Promise<never>
  sendReady(): Promise<void>
}

function createIpc<TIncoming, TOutgoing>(
  port: number
): Ipc<TIncoming, TOutgoing> {
  const socket = createConnection({
    port,
    host: '127.0.0.1',
  })

  /**
   * A writable stream that writes to the socket.
   * We don't write directly to the socket because we need to
   * handle backpressure and wait for the socket to be drained
   * before writing more data.
   */
  const socketWritable = new Writable({
    write(chunk, _enc, cb) {
      if (socket.write(chunk)) {
        cb()
      } else {
        socket.once('drain', cb)
      }
    },
    final(cb) {
      socket.end(cb)
    },
  })

  const packetQueue: Buffer[] = []
  const recvPromiseResolveQueue: Array<(message: TIncoming) => void> = []

  function pushPacket(packet: Buffer) {
    const recvPromiseResolve = recvPromiseResolveQueue.shift()
    if (recvPromiseResolve != null) {
      recvPromiseResolve(JSON.parse(packet.toString('utf8')) as TIncoming)
    } else {
      packetQueue.push(packet)
    }
  }

  let state: State = { type: 'waiting' }
  let buffer: Buffer = Buffer.alloc(0)
  socket.once('connect', () => {
    socket.on('data', (chunk) => {
      buffer = Buffer.concat([buffer, chunk])

      loop: while (true) {
        switch (state.type) {
          case 'waiting': {
            if (buffer.length >= 4) {
              const length = buffer.readUInt32BE(0)
              buffer = buffer.subarray(4)
              state = { type: 'packet', length }
            } else {
              break loop
            }
            break
          }
          case 'packet': {
            if (buffer.length >= state.length) {
              const packet = buffer.subarray(0, state.length)
              buffer = buffer.subarray(state.length)
              state = { type: 'waiting' }
              pushPacket(packet)
            } else {
              break loop
            }
            break
          }
          default:
            invariant(state, (state) => `Unknown state type: ${state?.type}`)
        }
      }
    })
  })
  // When the socket is closed, this process is no longer needed.
  // This might happen e. g. when parent process is killed or
  // node.js pool is garbage collected.
  socket.once('close', () => {
    process.exit(0)
  })

  // TODO(lukesandberg): some of the messages being sent are very large and contain lots
  //  of redundant information.  Consider adding gzip compression to our stream.
  function doSend(message: string): Promise<void> {
    return new Promise((resolve, reject) => {
      // Reserve 4 bytes for our length prefix, we will over-write after encoding.
      const packet = Buffer.from('0000' + message, 'utf8')
      packet.writeUInt32BE(packet.length - 4, 0)
      socketWritable.write(packet, (err) => {
        process.stderr.write(`TURBOPACK_OUTPUT_D\n`)
        process.stdout.write(`TURBOPACK_OUTPUT_D\n`)
        if (err != null) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }

  function send(message: any): Promise<void> {
    return doSend(JSON.stringify(message))
  }
  function sendReady(): Promise<void> {
    return doSend('')
  }

  return {
    async recv() {
      const packet = packetQueue.shift()
      if (packet != null) {
        return JSON.parse(packet.toString('utf8')) as TIncoming
      }

      const result = await new Promise<TIncoming>((resolve) => {
        recvPromiseResolveQueue.push((result) => {
          resolve(result)
        })
      })

      return result
    },

    send(message: TOutgoing) {
      return send(message)
    },

    sendReady,

    async sendError(error: Error): Promise<never> {
      try {
        await send({
          type: 'error',
          ...structuredError(error),
        })
      } catch (err) {
        console.error('failed to send error back to rust:', err)
        // ignore and exit anyway
        process.exit(1)
      }

      process.exit(0)
    },
  }
}

const PORT = process.argv[2]

export const IPC = createIpc<unknown, unknown>(parseInt(PORT, 10))

process.on('uncaughtException', (err) => {
  IPC.sendError(err)
})

const improveConsole = (name: string, stream: string, addStack: boolean) => {
  // @ts-ignore
  const original = console[name]
  // @ts-ignore
  const stdio = process[stream]
  // @ts-ignore
  console[name] = (...args: any[]) => {
    stdio.write(`TURBOPACK_OUTPUT_B\n`)
    original(...args)
    if (addStack) {
      const stack = new Error().stack?.replace(/^.+\n.+\n/, '') + '\n'
      stdio.write('TURBOPACK_OUTPUT_S\n')
      stdio.write(stack)
    }
    stdio.write('TURBOPACK_OUTPUT_E\n')
  }
}

improveConsole('error', 'stderr', true)
improveConsole('warn', 'stderr', true)
improveConsole('count', 'stdout', true)
improveConsole('trace', 'stderr', false)
improveConsole('log', 'stdout', true)
improveConsole('group', 'stdout', true)
improveConsole('groupCollapsed', 'stdout', true)
improveConsole('table', 'stdout', true)
improveConsole('debug', 'stdout', true)
improveConsole('info', 'stdout', true)
improveConsole('dir', 'stdout', true)
improveConsole('dirxml', 'stdout', true)
improveConsole('timeEnd', 'stdout', true)
improveConsole('timeLog', 'stdout', true)
improveConsole('timeStamp', 'stdout', true)
improveConsole('assert', 'stderr', true)

/**
 * Utility function to ensure all variants of an enum are handled.
 */
function invariant(never: never, computeMessage: (arg: any) => string): never {
  throw new Error(`Invariant: ${computeMessage(never)}`)
}