JOHN SILLVESTOR commited on
Commit
48168c8
·
verified ·
1 Parent(s): 695dd98

Engine upgrade: SingleFlight request coalescing and NVMe slice caching

Browse files
Files changed (1) hide show
  1. server.js +162 -26
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;
@@ -680,7 +682,7 @@ async function accessLevel(uid) {
680
  if (sub === LVL_MISS) return "registered";
681
  if (vipActive(sub)) lvl = "subscribed";
682
  lvlCache.set(uid, { lvl, ts: Date.now() });
683
- } catch {}
684
  return lvl;
685
  }
686
 
@@ -752,7 +754,7 @@ async function startBot(token, idx) {
752
  existing.load = 0;
753
  existing.coolUntil = 0;
754
  if (old && old !== client) {
755
- try { old.disconnect(); } catch {}
756
  }
757
  return;
758
  }
@@ -971,7 +973,7 @@ function durationFromMp4(buf) {
971
  if (s > 1 && s < 86400) return s;
972
  }
973
  }
974
- } catch {}
975
  from = i + 4;
976
  }
977
  return 0;
@@ -1015,7 +1017,7 @@ async function fillDuration(bot, rec, msgId) {
1015
  }
1016
  const pendingHot = inflightHot.get(id);
1017
  if (pendingHot) {
1018
- try { await pendingHot; } catch {}
1019
  const h = hotMap.get(id);
1020
  if (h && h.tail) {
1021
  const d = durationFromMp4(h.tail);
@@ -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,9 +1535,11 @@ 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 {}
1407
  }
1408
  }
1409
  }
@@ -1468,7 +1604,7 @@ async function handleGenerate(req, res, url) {
1468
  const rec = got.rec;
1469
  if (rec.hash && rec.hash !== hash) return json(res, 400, { error: "hash" });
1470
  warmHot(bot, rec, msgId);
1471
- fillDuration(bot, rec, msgId).catch(() => {});
1472
  const cachedDur = durCache.get(String(msgId));
1473
  if (cachedDur > 1) rec.duration = cachedDur;
1474
  const playMime = httpVideoType(rec.mime, rec.name);
@@ -1610,7 +1746,7 @@ async function handleStream(req, res, url, msgId) {
1610
  res.writeHead(502);
1611
  res.end();
1612
  } else if (!res.writableEnded && !res.destroyed) {
1613
- try { res.end(); } catch {}
1614
  }
1615
  }
1616
  } finally {
@@ -1628,10 +1764,10 @@ async function handleVipStatus(req, res) {
1628
  if (g) {
1629
  lvl = await accessLevel(g);
1630
  let sub = null;
1631
- try { sub = await rtdb("users/" + g + "/subscription", "GET"); } catch {}
1632
  return json(res, 200, { accessLevel: lvl, subscription: publicSub(sub) });
1633
  }
1634
- } catch {}
1635
  json(res, 200, { accessLevel: lvl });
1636
  }
1637
 
@@ -1676,7 +1812,7 @@ async function withPayLock(id, fn) {
1676
  let done;
1677
  const cur = new Promise((r) => { done = r; });
1678
  payLocks.set(id, prev ? prev.then(() => cur, () => cur) : cur);
1679
- if (prev) await prev.catch(() => {});
1680
  try {
1681
  return await fn();
1682
  } finally {
@@ -1798,10 +1934,10 @@ async function handleVipConfirm(req, res) {
1798
  return json(res, 400, { error: "Payment failed", paid: false });
1799
  }
1800
  if (d.payment_status !== "paid") return json(res, 402, { error: "unpaid", paid: false });
1801
- try { await fulfillPaid(d); } catch {}
1802
  lvlCache.delete(idp.sub);
1803
  let sub = null;
1804
- try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch {}
1805
  if (!vipActive(sub)) return json(res, 402, { error: "unpaid", paid: false });
1806
  json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: publicSub(sub) });
1807
  }
@@ -1815,7 +1951,7 @@ async function grantVip(uid, planKey) {
1815
  const old = await rtdb("users/" + uid + "/subscription", "GET");
1816
  const oldExp = vipExpirySec(old);
1817
  if (vipActive(old) && oldExp > start) start = oldExp;
1818
- } catch {}
1819
  const sub = {
1820
  status: "active",
1821
  plan: planKey,
@@ -1859,7 +1995,7 @@ async function orderSeen(id) {
1859
  paidOrders.set(id, Date.now());
1860
  return true;
1861
  }
1862
- } catch {}
1863
  return false;
1864
  }
1865
 
@@ -1871,7 +2007,7 @@ async function markOrder(id, uid, planKey) {
1871
  uid: uid,
1872
  plan: planKey
1873
  });
1874
- } catch {}
1875
  }
1876
 
1877
  async function fulfillPaid(ses) {
@@ -1912,7 +2048,7 @@ async function handleStripeWebhook(req, res) {
1912
  try {
1913
  const ses = await stripeSession(id);
1914
  if (ses) await fulfillPaid(ses);
1915
- } catch {}
1916
  }
1917
  json(res, 200, { ok: true });
1918
  }
@@ -2110,8 +2246,8 @@ function handleHome(req, res) {
2110
  }
2111
 
2112
  async function onReq(req, res) {
2113
- req.on("error", () => {});
2114
- res.on("error", () => {});
2115
  sweepBots();
2116
  let url;
2117
  try { url = new URL(req.url, "http://local"); } catch {
@@ -2171,7 +2307,7 @@ async function main() {
2171
  process.stderr.write("no bots online\n");
2172
  process.exit(1);
2173
  }
2174
- setInterval(() => { reviveBots().catch(() => {}); }, 20000);
2175
  const srv = http.createServer({
2176
  keepAlive: true,
2177
  keepAliveTimeout: 25000,
@@ -2183,7 +2319,7 @@ async function main() {
2183
  srv.on("clientError", (err, sock) => {
2184
  try {
2185
  if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
2186
- } catch {}
2187
  });
2188
  srv.listen(PORT, "0.0.0.0");
2189
  }
 
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;
 
682
  if (sub === LVL_MISS) return "registered";
683
  if (vipActive(sub)) lvl = "subscribed";
684
  lvlCache.set(uid, { lvl, ts: Date.now() });
685
+ } catch { }
686
  return lvl;
687
  }
688
 
 
754
  existing.load = 0;
755
  existing.coolUntil = 0;
756
  if (old && old !== client) {
757
+ try { old.disconnect(); } catch { }
758
  }
759
  return;
760
  }
 
973
  if (s > 1 && s < 86400) return s;
974
  }
975
  }
976
+ } catch { }
977
  from = i + 4;
978
  }
979
  return 0;
 
1017
  }
1018
  const pendingHot = inflightHot.get(id);
1019
  if (pendingHot) {
1020
+ try { await pendingHot; } catch { }
1021
  const h = hotMap.get(id);
1022
  if (h && h.tail) {
1023
  const d = durationFromMp4(h.tail);
 
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 { }
1543
  }
1544
  }
1545
  }
 
1604
  const rec = got.rec;
1605
  if (rec.hash && rec.hash !== hash) return json(res, 400, { error: "hash" });
1606
  warmHot(bot, rec, msgId);
1607
+ fillDuration(bot, rec, msgId).catch(() => { });
1608
  const cachedDur = durCache.get(String(msgId));
1609
  if (cachedDur > 1) rec.duration = cachedDur;
1610
  const playMime = httpVideoType(rec.mime, rec.name);
 
1746
  res.writeHead(502);
1747
  res.end();
1748
  } else if (!res.writableEnded && !res.destroyed) {
1749
+ try { res.end(); } catch { }
1750
  }
1751
  }
1752
  } finally {
 
1764
  if (g) {
1765
  lvl = await accessLevel(g);
1766
  let sub = null;
1767
+ try { sub = await rtdb("users/" + g + "/subscription", "GET"); } catch { }
1768
  return json(res, 200, { accessLevel: lvl, subscription: publicSub(sub) });
1769
  }
1770
+ } catch { }
1771
  json(res, 200, { accessLevel: lvl });
1772
  }
1773
 
 
1812
  let done;
1813
  const cur = new Promise((r) => { done = r; });
1814
  payLocks.set(id, prev ? prev.then(() => cur, () => cur) : cur);
1815
+ if (prev) await prev.catch(() => { });
1816
  try {
1817
  return await fn();
1818
  } finally {
 
1934
  return json(res, 400, { error: "Payment failed", paid: false });
1935
  }
1936
  if (d.payment_status !== "paid") return json(res, 402, { error: "unpaid", paid: false });
1937
+ try { await fulfillPaid(d); } catch { }
1938
  lvlCache.delete(idp.sub);
1939
  let sub = null;
1940
+ try { sub = await rtdb("users/" + idp.sub + "/subscription", "GET"); } catch { }
1941
  if (!vipActive(sub)) return json(res, 402, { error: "unpaid", paid: false });
1942
  json(res, 200, { ok: true, paid: true, accessLevel: "subscribed", subscription: publicSub(sub) });
1943
  }
 
1951
  const old = await rtdb("users/" + uid + "/subscription", "GET");
1952
  const oldExp = vipExpirySec(old);
1953
  if (vipActive(old) && oldExp > start) start = oldExp;
1954
+ } catch { }
1955
  const sub = {
1956
  status: "active",
1957
  plan: planKey,
 
1995
  paidOrders.set(id, Date.now());
1996
  return true;
1997
  }
1998
+ } catch { }
1999
  return false;
2000
  }
2001
 
 
2007
  uid: uid,
2008
  plan: planKey
2009
  });
2010
+ } catch { }
2011
  }
2012
 
2013
  async function fulfillPaid(ses) {
 
2048
  try {
2049
  const ses = await stripeSession(id);
2050
  if (ses) await fulfillPaid(ses);
2051
+ } catch { }
2052
  }
2053
  json(res, 200, { ok: true });
2054
  }
 
2246
  }
2247
 
2248
  async function onReq(req, res) {
2249
+ req.on("error", () => { });
2250
+ res.on("error", () => { });
2251
  sweepBots();
2252
  let url;
2253
  try { url = new URL(req.url, "http://local"); } catch {
 
2307
  process.stderr.write("no bots online\n");
2308
  process.exit(1);
2309
  }
2310
+ setInterval(() => { reviveBots().catch(() => { }); }, 20000);
2311
  const srv = http.createServer({
2312
  keepAlive: true,
2313
  keepAliveTimeout: 25000,
 
2319
  srv.on("clientError", (err, sock) => {
2320
  try {
2321
  if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
2322
+ } catch { }
2323
  });
2324
  srv.listen(PORT, "0.0.0.0");
2325
  }