Truly independent web browser
<!DOCTYPE html>
<script src="../include.js"></script>
<script>
// With a read always pending and the chunks 300 ms apart, each chunk reaches the stream in a pull task of its
// own, and the close follows the last bytes through the same queue. So a read's reaction and a timer it queues
// run before the next chunk's pull task; a run slow enough to let a chunk in first is retried with the chunks a
// second apart.
asyncTest(async done => {
const httpServer = httpTestServer();
const body = "A".repeat(16) + "B".repeat(16) + "C".repeat(16);
const url = await httpServer.createEcho("GET", `/delivery-order-${crypto.randomUUID()}`, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/octet-stream",
},
body,
});
const readAll = async chunkDelayMs => {
const response = await fetch(`${url}?chunks=16,16,16&chunk_delay_ms=${chunkDelayMs}`);
const reader = response.body.getReader();
const events = [];
const chunks = [];
for (;;) {
const { value, done: streamDone } = await reader.read();
if (streamDone) {
events.push("close");
break;
}
const index = chunks.push(new TextDecoder().decode(value));
events.push(`read ${index}`);
queueMicrotask(() => events.push(`microtask after read ${index}`));
setTimeout(() => events.push(`timer after read ${index}`), 0);
}
await new Promise(resolve => setTimeout(resolve, 50));
return { events, chunks };
};
const beforeNextRead = ({ events, chunks }, kind) =>
chunks.every((_, i) => i + 1 === chunks.length || events.indexOf(`${kind} after read ${i + 1}`) < events.indexOf(`read ${i + 2}`));
let run = await readAll(300);
if (!beforeNextRead(run, "timer"))
run = await readAll(1000);
const { events, chunks } = run;
const position = event => events.indexOf(event);
println(`reads resolve in chunk order: ${chunks.join("") === body && chunks.every((chunk, i) => chunk[0] === "ABC"[i])}`);
println(`a read's microtask ran before the next read resolved: ${beforeNextRead(run, "microtask")}`);
println(`a read's timer fired before the next read resolved: ${beforeNextRead(run, "timer")}`);
println(`close followed the last bytes: ${position("close") > position(`microtask after read ${chunks.length}`)}`);
done();
});
</script>