iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / itx / src / context / answer-body.tsmain at 949894f

// answer-body.ts — WHEN AN ANSWER HAS ENDED. A call whose answer is a Response or a stream has
// answered with its first byte still to come: the body arrives later, over whatever the call used
// (a held connection's socket, a lent stub's session). `untilBodyEnds` hands the answer on with
// its body watched, and says once how the body ended. No workerd import: the unit test runs it in
// Node (answer-body.test.ts).

/** How long a body may stay with nobody asking for its next chunk before it counts as left
 *  unread. A reader of a live stream asks again at once, also when the chunk is slow to come. */
export const ANSWER_BODY_UNREAD_AFTER_MS = 60_000;

/** `closed`: read to its end. `errored`: its source failed. `cancelled`: its reader dropped it.
 *  `unread`: nobody asked for a chunk for `ANSWER_BODY_UNREAD_AFTER_MS`; the body itself is left
 *  as it is, and a reader that comes back still gets it. */
export type BodyEnd = "closed" | "errored" | "cancelled" | "unread";

/** `answer` as it is, unless it is a Response with a body or a stream: then the same answer with
 *  its body watched. `ended` is called once: at once (`null`) for an answer with no body, else
 *  when the body ends. */
export function untilBodyEnds(
  answer: unknown,
  ended: (how: BodyEnd | null) => void,
  unreadAfterMs = ANSWER_BODY_UNREAD_AFTER_MS,
): unknown {
  if (answer instanceof Response && answer.body)
    return new Response(watched(answer.body, ended, unreadAfterMs), answer);
  if (answer instanceof ReadableStream) return watched(answer, ended, unreadAfterMs);
  ended(null);
  return answer;
}

function watched(
  body: ReadableStream<Uint8Array>,
  ended: (how: BodyEnd) => void,
  unreadAfterMs: number,
): ReadableStream<Uint8Array> {
  const reader = body.getReader();
  let over = false;
  let unread: ReturnType<typeof setTimeout> | undefined;
  const end = (how: BodyEnd) => {
    clearTimeout(unread);
    if (over) return;
    over = true;
    ended(how);
  };
  const nobodyAsks = () => {
    unread = setTimeout(() => end("unread"), unreadAfterMs);
  };
  nobodyAsks();
  // No queue of its own: `pull` runs only while a read waits, so a pull is a reader that asks.
  // A byte stream, as the body was: Workers RPC carries no other kind of stream.
  return new ReadableStream(
    {
      type: "bytes",
      async pull(controller) {
        clearTimeout(unread);
        let next: ReadableStreamReadResult<Uint8Array>;
        try {
          // a byte stream takes no empty chunk
          do next = await reader.read();
          while (!next.done && next.value.byteLength === 0);
        } catch (error) {
          end("errored");
          throw error;
        }
        if (next.done) {
          end("closed");
          controller.close();
          return;
        }
        controller.enqueue(next.value);
        if (!over) nobodyAsks();
      },
      async cancel(reason) {
        end("cancelled");
        await reader.cancel(reason);
      },
    },
    { highWaterMark: 0 },
  );
}