summaryrefslogtreecommitdiff
path: root/test/web/parallel_reads.mjs
blob: a95976b243790682cc1c8d8bf1d9cdd66e9a3d82 (plain) (blame)
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
// Read-only stress check: concurrent multi-frame website reads must be exact.
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';

const [base, root] = process.argv.slice(2);
if (!base || !root) throw new Error('usage: node parallel_reads.mjs URL DIRECTORY');
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const fileUrl = name => base.replace(/\/$/, '') + '/' + name.split(path.sep).map(encodeURIComponent).join('/');
const files = [];
async function collect(dir, rel = '') {
  for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
    const name = path.join(rel, entry.name), full = path.join(dir, entry.name);
    if (entry.isDirectory()) await collect(full, name);
    else if (entry.isFile()) {
      const bytes = await fs.readFile(full);
      if (bytes.length >= 65536) files.push({ name, size: bytes.length, hash: hash(bytes) });
    }
  }
}
await collect(root);
assert.ok(files.length > 0, 'need at least one multi-frame file');
for (let round = 0; round < 5; round++) {
  const reads = Array.from({ length: 16 }, async (_, i) => {
    const file = files[(round * 16 + i) % files.length];
    const response = await fetch(fileUrl(file.name));
    assert.equal(response.status, 200, file.name);
    const bytes = Buffer.from(await response.arrayBuffer());
    assert.equal(bytes.length, file.size, `truncated: ${file.name}`);
    assert.equal(hash(bytes), file.hash, `corrupt: ${file.name}`);
  });
  // Mix synchronous stats with reads, and abandon owned responses midway.
  const canceled = Array.from({ length: 8 }, async (_, i) => {
    const response = await fetch(fileUrl(files[i % files.length].name));
    assert.equal(response.status, 200);
    const reader = response.body.getReader();
    await reader.read();
    await reader.cancel();
  });
  const head = fetch(fileUrl(files[0].name), { method: 'HEAD' }).then(r => assert.equal(r.status, 200));
  await Promise.all([...reads, ...canceled, head]);
}
console.log(`parallel_reads: 80 exact multi-frame responses, 16 concurrent, 40 cancellations and mixed HEAD (${files.length} source files)`);