JOHN SILLVESTOR commited on
Commit
a2d9690
·
verified ·
1 Parent(s): 8f61e2f

Engine upgrade: SingleFlight request coalescing and NVMe slice caching

Browse files
Files changed (1) hide show
  1. server.js +142 -6
server.js CHANGED
@@ -27,7 +27,9 @@ const PIPE_MS = 45000;
27
  const PIPE_MAX_MS = 30 * 60 * 1000;
28
  const IP_STREAM_MAX = 5;
29
  const UID_STREAM_MAX = 3;
30
- const GLOBAL_PIPE_MAX = 96;
 
 
31
  const HOT_BYTES_MAX = 2048 * MB;
32
  const BODY_MAX = 262144;
33
  const FILE_TTL = 20 * 60 * 1000;
@@ -1297,7 +1299,7 @@ async function warmHot(bot, rec, msgId) {
1297
  if (headEnd >= 0 && !(hit && hit.head && hit.head.length >= headEnd + 1)) {
1298
  jobs.push((async () => {
1299
  const parts = [];
1300
- for await (const c of rangeChunks(bot, rec, 0, headEnd, () => parts.reduce((n, b) => n + b.length, 0) >= HOT_HEAD)) {
1301
  parts.push(c);
1302
  }
1303
  if (parts.length) hotFill(id, 0, Buffer.concat(parts), rec.size);
@@ -1307,7 +1309,7 @@ async function warmHot(bot, rec, msgId) {
1307
  if (rec.size > HOT_HEAD && !(hit && hit.tail)) {
1308
  jobs.push((async () => {
1309
  const parts = [];
1310
- for await (const c of rangeChunks(bot, rec, tailOff, rec.size - 1, () => false)) {
1311
  parts.push(c);
1312
  }
1313
  if (parts.length) {
@@ -1329,13 +1331,141 @@ async function warmHot(bot, rec, msgId) {
1329
  return p;
1330
  }
1331
 
1332
- async function* rangeChunks(bot, rec, start, end, stop) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1333
  let at = start;
1334
  while (at <= end) {
1335
  if (stop && stop()) break;
1336
  const aligned = Math.floor(at / CHUNK_SIZE) * CHUNK_SIZE;
1337
  let skip = at - aligned;
1338
  const need = end - at + 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1339
  const it = bot.client.iterDownload(rec.loc || rec.doc, {
1340
  offset: aligned,
1341
  limit: skip + need,
@@ -1373,6 +1503,10 @@ async function* rangeChunks(bot, rec, start, end, stop) {
1373
  async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId) {
1374
  bot.load++;
1375
  const t0 = Date.now();
 
 
 
 
1376
  try {
1377
  if (res.socket) {
1378
  res.socket.setNoDelay(true);
@@ -1382,7 +1516,7 @@ async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId)
1382
  res.writeHead(status, headers);
1383
  if (typeof res.flushHeaders === "function") res.flushHeaders();
1384
  const budget = pipeBudget(start, end);
1385
- const stop = () => pipeDead(req, res) || Date.now() - t0 > budget;
1386
  let pos = start;
1387
  const prefix = hotPrefix(msgId, pos, end);
1388
  if (prefix && prefix.length) {
@@ -1391,7 +1525,7 @@ async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId)
1391
  if (!ok) await waitDrain(req, res);
1392
  }
1393
  if (pos > end || stop()) return;
1394
- const gen = rangeChunks(bot, rec, pos, end, stop);
1395
  let at = pos;
1396
  for await (const buf of gen) {
1397
  if (stop()) break;
@@ -1401,6 +1535,8 @@ async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId)
1401
  if (!ok) await waitDrain(req, res);
1402
  }
1403
  } finally {
 
 
1404
  bot.load = Math.max(0, bot.load - 1);
1405
  if (!res.writableEnded && !res.destroyed) {
1406
  try { res.end(); } catch {}
 
27
  const PIPE_MAX_MS = 30 * 60 * 1000;
28
  const IP_STREAM_MAX = 5;
29
  const UID_STREAM_MAX = 3;
30
+ const GLOBAL_PIPE_MAX = 240;
31
+ const DISK_SLICE_DIR = "/tmp/dlk_slice";
32
+ const DISK_MAX_BYTES = 28 * 1024 * 1024 * 1024;
33
  const HOT_BYTES_MAX = 2048 * MB;
34
  const BODY_MAX = 262144;
35
  const FILE_TTL = 20 * 60 * 1000;
 
1299
  if (headEnd >= 0 && !(hit && hit.head && hit.head.length >= headEnd + 1)) {
1300
  jobs.push((async () => {
1301
  const parts = [];
1302
+ for await (const c of rangeChunks(bot, rec, 0, headEnd, () => parts.reduce((n, b) => n + b.length, 0) >= HOT_HEAD, id)) {
1303
  parts.push(c);
1304
  }
1305
  if (parts.length) hotFill(id, 0, Buffer.concat(parts), rec.size);
 
1309
  if (rec.size > HOT_HEAD && !(hit && hit.tail)) {
1310
  jobs.push((async () => {
1311
  const parts = [];
1312
+ for await (const c of rangeChunks(bot, rec, tailOff, rec.size - 1, () => false, id)) {
1313
  parts.push(c);
1314
  }
1315
  if (parts.length) {
 
1331
  return p;
1332
  }
1333
 
1334
+ class SingleFlight {
1335
+ constructor() {
1336
+ this.active = new Map();
1337
+ }
1338
+ do(key, fn) {
1339
+ if (this.active.has(key)) return this.active.get(key);
1340
+ const p = (async () => {
1341
+ try {
1342
+ return await fn();
1343
+ } finally {
1344
+ this.active.delete(key);
1345
+ }
1346
+ })();
1347
+ this.active.set(key, p);
1348
+ return p;
1349
+ }
1350
+ }
1351
+ const chunkFlight = new SingleFlight();
1352
+ let diskBytesUsed = 0;
1353
+
1354
+ function sliceFilePath(msgId, offset) {
1355
+ return path.join(DISK_SLICE_DIR, String(msgId), String(offset) + ".bin");
1356
+ }
1357
+
1358
+ async function readDiskSlice(msgId, offset) {
1359
+ try {
1360
+ return await fs.promises.readFile(sliceFilePath(msgId, offset));
1361
+ } catch {
1362
+ return null;
1363
+ }
1364
+ }
1365
+
1366
+ async function trimDiskCache() {
1367
+ try {
1368
+ const files = [];
1369
+ const dirs = await fs.promises.readdir(DISK_SLICE_DIR, { withFileTypes: true });
1370
+ for (const d of dirs) {
1371
+ if (d.isDirectory()) {
1372
+ const sub = path.join(DISK_SLICE_DIR, d.name);
1373
+ const list = await fs.promises.readdir(sub);
1374
+ for (const f of list) {
1375
+ const fp = path.join(sub, f);
1376
+ try {
1377
+ const st = await fs.promises.stat(fp);
1378
+ files.push({ path: fp, size: st.size, mtime: st.mtimeMs });
1379
+ } catch {}
1380
+ }
1381
+ }
1382
+ }
1383
+ files.sort((a, b) => a.mtime - b.mtime);
1384
+ let total = files.reduce((n, f) => n + f.size, 0);
1385
+ diskBytesUsed = total;
1386
+ if (total <= DISK_MAX_BYTES) return;
1387
+ const target = Math.floor(DISK_MAX_BYTES * 0.75);
1388
+ for (const f of files) {
1389
+ if (total <= target) break;
1390
+ try {
1391
+ await fs.promises.unlink(f.path);
1392
+ total -= f.size;
1393
+ } catch {}
1394
+ }
1395
+ diskBytesUsed = Math.max(0, total);
1396
+ } catch {}
1397
+ }
1398
+
1399
+ async function writeDiskSlice(msgId, offset, buffer) {
1400
+ if (!buffer || !buffer.length) return;
1401
+ try {
1402
+ const file = sliceFilePath(msgId, offset);
1403
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
1404
+ await fs.promises.writeFile(file, buffer);
1405
+ diskBytesUsed += buffer.length;
1406
+ if (diskBytesUsed > DISK_MAX_BYTES) {
1407
+ trimDiskCache().catch(() => {});
1408
+ }
1409
+ } catch {}
1410
+ }
1411
+
1412
+ async function fetchSliceChunk(bot, rec, msgId, aligned) {
1413
+ const disk = await readDiskSlice(msgId, aligned);
1414
+ if (disk && disk.length) return disk;
1415
+ const flightKey = String(msgId) + ":" + String(aligned);
1416
+ return chunkFlight.do(flightKey, async () => {
1417
+ const recheck = await readDiskSlice(msgId, aligned);
1418
+ if (recheck && recheck.length) return recheck;
1419
+ const it = bot.client.iterDownload(rec.loc || rec.doc, {
1420
+ offset: aligned,
1421
+ limit: CHUNK_SIZE,
1422
+ requestSize: CHUNK_SIZE,
1423
+ dcId: rec.dcId
1424
+ });
1425
+ const parts = [];
1426
+ for await (const chunk of it) {
1427
+ parts.push(Buffer.from(chunk));
1428
+ }
1429
+ const full = Buffer.concat(parts);
1430
+ if (full.length) {
1431
+ writeDiskSlice(msgId, aligned, full).catch(() => {});
1432
+ }
1433
+ return full;
1434
+ });
1435
+ }
1436
+
1437
+ async function* rangeChunks(bot, rec, start, end, stop, msgId) {
1438
  let at = start;
1439
  while (at <= end) {
1440
  if (stop && stop()) break;
1441
  const aligned = Math.floor(at / CHUNK_SIZE) * CHUNK_SIZE;
1442
  let skip = at - aligned;
1443
  const need = end - at + 1;
1444
+ let piece = null;
1445
+ if (msgId != null) {
1446
+ try {
1447
+ piece = await fetchSliceChunk(bot, rec, msgId, aligned);
1448
+ } catch {}
1449
+ }
1450
+ if (piece && piece.length) {
1451
+ let buf = piece;
1452
+ if (skip > 0) {
1453
+ if (buf.length <= skip) {
1454
+ at += buf.length;
1455
+ continue;
1456
+ }
1457
+ buf = buf.subarray(skip);
1458
+ skip = 0;
1459
+ }
1460
+ const left = end - at + 1;
1461
+ if (buf.length > left) buf = buf.subarray(0, left);
1462
+ if (buf.length) {
1463
+ at += buf.length;
1464
+ yield buf;
1465
+ }
1466
+ if (at > end || (stop && stop())) break;
1467
+ continue;
1468
+ }
1469
  const it = bot.client.iterDownload(rec.loc || rec.doc, {
1470
  offset: aligned,
1471
  limit: skip + need,
 
1503
  async function pipeRange(bot, rec, start, end, req, res, status, headers, msgId) {
1504
  bot.load++;
1505
  const t0 = Date.now();
1506
+ let clientClosed = false;
1507
+ const onDead = () => { clientClosed = true; };
1508
+ req.once("close", onDead);
1509
+ res.once("close", onDead);
1510
  try {
1511
  if (res.socket) {
1512
  res.socket.setNoDelay(true);
 
1516
  res.writeHead(status, headers);
1517
  if (typeof res.flushHeaders === "function") res.flushHeaders();
1518
  const budget = pipeBudget(start, end);
1519
+ const stop = () => clientClosed || pipeDead(req, res) || Date.now() - t0 > budget;
1520
  let pos = start;
1521
  const prefix = hotPrefix(msgId, pos, end);
1522
  if (prefix && prefix.length) {
 
1525
  if (!ok) await waitDrain(req, res);
1526
  }
1527
  if (pos > end || stop()) return;
1528
+ const gen = rangeChunks(bot, rec, pos, end, stop, msgId);
1529
  let at = pos;
1530
  for await (const buf of gen) {
1531
  if (stop()) break;
 
1535
  if (!ok) await waitDrain(req, res);
1536
  }
1537
  } finally {
1538
+ req.off("close", onDead);
1539
+ res.off("close", onDead);
1540
  bot.load = Math.max(0, bot.load - 1);
1541
  if (!res.writableEnded && !res.destroyed) {
1542
  try { res.end(); } catch {}