~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
58 lines · 2.7 KB Raw History
// A proxy between the server and the PLC directory, which counts the
// server's requests to it, by method and path, and how many were in flight
// at once, records the requests each connection carried, and may hold each
// up a while (spec/LIMITS.md, "The PLC directory"), or be down
// (spec/LIFECYCLE.md).

import { createServer } from 'node:http'

/// Start a proxy to the directory at `target`. Answers `{url, counts,
/// connections, inFlight, maxInFlight, delayMs, down, close}`; each of
/// `connections`, in the order they were made, is the list of its
/// requests, as `<method> <path>`. Set `delayMs` to hold each request up
/// that long before it is passed on, `maxInFlight` to 0 to count afresh,
/// and `down` to `'refuse'` to close each connection unanswered or to
/// `'error'` to answer each `500`, as a directory that cannot be read.
export async function startPlcProxy(target) {
  const proxy = { counts: new Map(), connections: [], inFlight: 0, maxInFlight: 0, delayMs: 0, down: null }
  const carried = new WeakMap()
  const s = createServer(async (req, res) => {
    const key = `${req.method} ${decodeURIComponent(req.url)}`
    proxy.counts.set(key, (proxy.counts.get(key) ?? 0) + 1)
    carried.get(req.socket)?.push(key)
    if (proxy.down === 'refuse') return req.socket.destroy()
    if (proxy.down === 'error') {
      res.writeHead(500)
      return res.end('down')
    }
    proxy.inFlight += 1
    proxy.maxInFlight = Math.max(proxy.maxInFlight, proxy.inFlight)
    try {
      const chunks = []
      for await (const c of req) chunks.push(c)
      if (proxy.delayMs) await new Promise((ok) => setTimeout(ok, proxy.delayMs))
      const headers = { ...req.headers }
      for (const h of ['host', 'content-length', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'expect']) delete headers[h]
      const r = await fetch(`${target}${req.url}`, { method: req.method, headers, body: chunks.length ? Buffer.concat(chunks) : undefined })
      const body = Buffer.from(await r.arrayBuffer())
      res.writeHead(r.status, { 'content-type': r.headers.get('content-type') ?? 'application/octet-stream' })
      res.end(body)
    } catch (err) {
      res.writeHead(502)
      res.end(String(err))
    } finally {
      proxy.inFlight -= 1
    }
  })
  s.on('connection', (socket) => {
    const requests = []
    carried.set(socket, requests)
    proxy.connections.push(requests)
  })
  await new Promise((ok) => s.listen(0, '127.0.0.1', ok))
  proxy.url = `http://127.0.0.1:${s.address().port}`
  /// The requests counted whose path, decoded, is `path`, of any method.
  proxy.countOf = (path) => [...proxy.counts].filter(([k]) => k.split(' ')[1] === path).reduce((n, [, c]) => n + c, 0)
  proxy.close = () => s.close()
  return proxy
}