/// <reference types="@fastly/js-compute" />
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));

async function handleRequest(event) {
  const response = await fetch(event.request, { backend: "origin_0" });
  const pit = tarpit();
  return pit(response);
}

async function pause(delay = 100) {
  return new Promise((resolve) => setTimeout(resolve, delay));
}

function tarpit(millisecondDelay = 5000, bytesPerChunk = 1000) {
  const writableStrategy = new ByteLengthQueuingStrategy({
    highWaterMark: bytesPerChunk
  });

  const { readable, writable } = new TransformStream();
  const writer = writable.getWriter();

  async function processChunks(readStream) {
    const reader = readStream.getReader();
    while (true) {
      const { done, value: chunk } = await reader.read();
      if (done) {
        break;
      }
      await pause(millisecondDelay);
      writer.write(chunk);
    }
    writer.close();
    reader.releaseLock();
  }

  return function (response) {
    if (response.body) {
      processChunks(
        response.body.pipeThrough(
          new TransformStream(undefined, writableStrategy)
        )
      );
      return new Response(readable, response);
    }
    return response;
  };
}