@plitzi/sdk-runtime 0.39.2 → 0.39.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @plitzi/sdk-runtime
2
2
 
3
+ ## 0.39.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 35415a1: Released with every `@plitzi` package at this version. What changed in each, and what to do when you upgrade, is in
8
+ `@plitzi/cli`'s `CHANGELOG.md`: one copy of the notes, not one per package.
9
+ - Updated dependencies [35415a1]
10
+ - @plitzi/sdk-kernel@0.39.4
11
+ - @plitzi/sdk-shared@0.39.4
12
+
13
+ ## 0.39.3
14
+
15
+ ### Patch Changes
16
+
17
+ - @plitzi/sdk-kernel@0.39.3
18
+ - @plitzi/sdk-shared@0.39.3
19
+
3
20
  ## 0.39.2
4
21
 
5
22
  ### Patch Changes
@@ -4,7 +4,8 @@ import { SHUTDOWN_GRACE_MS, bearerMatches, frameText, shutdownOf, watchConnectio
4
4
  import http from "node:http";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { logQueryOf, readLogTail, serverLog } from "@plitzi/sdk-kernel/log";
7
- import { STATS_LOGS_PATH, STATS_PATH, cpuLimitCores, createStatsRecorder, sampleProcessMemory, withStopping } from "@plitzi/sdk-kernel/stats";
7
+ import { METRICS_CONTENT_TYPE, STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH, cpuLimitCores, createStatsRecorder, metricsText, sampleProcessMemory, withStopping } from "@plitzi/sdk-kernel/stats";
8
+ import { TRACEPARENT, readTraceparent, runInTrace, spanOf } from "@plitzi/sdk-kernel/trace";
8
9
  import { createHash, createHmac, pbkdf2, randomBytes } from "node:crypto";
9
10
  import { promisify } from "node:util";
10
11
  import { readFileSync } from "node:fs";
@@ -1305,6 +1306,197 @@ var guestPrelude = () => {
1305
1306
  return prelude;
1306
1307
  };
1307
1308
  /**
1309
+ * An invocation's clock: what its time is, what its CPU is, and what of the clock was the runner's.
1310
+ *
1311
+ * Its own time is what it waited on that it asked for, and the CPU it was charged — what it would take on a runner of
1312
+ * its own. Never the runner's: a turn waited for, a place behind other isolates in isolated-vm's threads (one per core:
1313
+ * a spinner holds one until it ends), a core it was ready for and did not get. Counted from the clock, a route that
1314
+ * slept 200 ms on a crowded runner was stopped at its 10 s.
1315
+ *
1316
+ * Pure over `now`: it reads no isolate. Its CPU is handed in once the code begins (`begin`) — the isolate's share of the
1317
+ * process's (`createCpuMeter`) — beside what the runner spent on its behalf (`chargeHost`).
1318
+ */
1319
+ var createRunClock = ({ now = Date.now } = {}) => {
1320
+ const startedAt = now();
1321
+ /** Its share of the process's CPU from the moment its code began; nothing is its CPU before. */
1322
+ let meteredCpu;
1323
+ /** What the runner spent on the run's behalf — a PBKDF2 derivation — which the isolate's clock never sees. */
1324
+ let hostCpuMs = 0;
1325
+ /** How long it waited on what it asked of the platform — calls, sleeps — counted once while it waits on several. */
1326
+ let awaitedMs = 0;
1327
+ let awaitingSince;
1328
+ let waits = 0;
1329
+ /**
1330
+ * A sleep counts what it asked for: the timer that wakes it is the runner's, on its main thread, and a crowded runner
1331
+ * woke a 200 ms sleep seconds late — counted, a route was stopped at its 10 s. Its lateness, of the sleeps that ended
1332
+ * and of the ones still past their time, is the runner's.
1333
+ */
1334
+ let lateMs = 0;
1335
+ const sleeping = /* @__PURE__ */ new Set();
1336
+ /** What of its time was the runner's, and told the platform so far: its wait for the answer grows by it. */
1337
+ let toldWaitedMs = 0;
1338
+ const lateAt = (at) => [...sleeping].reduce((late, sleep) => late + Math.max(0, at - sleep.from - sleep.wanted), lateMs);
1339
+ const chargedCpu = () => (meteredCpu?.() ?? 0) + hostCpuMs;
1340
+ const ownMs = () => {
1341
+ if (!meteredCpu) return 0;
1342
+ const at = now();
1343
+ const awaitedNow = awaitedMs + (awaitingSince === void 0 ? 0 : at - awaitingSince);
1344
+ return Math.max(0, awaitedNow - lateAt(at)) + chargedCpu();
1345
+ };
1346
+ return {
1347
+ /** Its code began: what came before — the isolate made, the bundle compiled — is the platform's time. */
1348
+ begin: (charged) => {
1349
+ meteredCpu = charged;
1350
+ },
1351
+ chargeHost: (ms) => {
1352
+ hostCpuMs += ms;
1353
+ },
1354
+ hostCpuMs: () => hostCpuMs,
1355
+ chargedCpu,
1356
+ ownMs,
1357
+ /** It began waiting on something it asked of the platform. */
1358
+ waitBegins: () => {
1359
+ if (waits === 0) awaitingSince = now();
1360
+ waits++;
1361
+ },
1362
+ waitEnds: () => {
1363
+ waits--;
1364
+ if (waits === 0 && awaitingSince !== void 0) {
1365
+ awaitedMs += now() - awaitingSince;
1366
+ awaitingSince = void 0;
1367
+ }
1368
+ },
1369
+ /** How many answers of the platform it waits for now. */
1370
+ waits: () => waits,
1371
+ /**
1372
+ * A sleep of `ms`: past the time it has left it ends the run there, by its time limit — never cut short to fit: cut,
1373
+ * the code woke at the limit and, the watchdog a look behind, finished as if it had slept.
1374
+ */
1375
+ sleep: (ms, wallMs) => {
1376
+ const left = wallMs - ownMs();
1377
+ const wanted = Math.max(0, ms);
1378
+ if (wanted >= left) return {
1379
+ wakes: false,
1380
+ stopInMs: Math.max(0, left)
1381
+ };
1382
+ const sleep = {
1383
+ from: now(),
1384
+ wanted
1385
+ };
1386
+ sleeping.add(sleep);
1387
+ return {
1388
+ wakes: true,
1389
+ wanted,
1390
+ woke: () => {
1391
+ sleeping.delete(sleep);
1392
+ lateMs += Math.max(0, now() - sleep.from - wanted);
1393
+ }
1394
+ };
1395
+ },
1396
+ /** The limit its time or its CPU went past, the CPU first — or nothing. */
1397
+ overLimit: ({ cpuMs, wallMs }) => {
1398
+ if (chargedCpu() > cpuMs) return "cpu";
1399
+ return ownMs() > wallMs ? "wall" : void 0;
1400
+ },
1401
+ /**
1402
+ * What of the clock was the runner's since it was last told, once that is a tell's worth — every moment that was
1403
+ * not its own: its isolate made, a turn, a place behind others, a core. Told the platform, whose wait for the answer
1404
+ * would otherwise run out on time the code never had.
1405
+ */
1406
+ untoldWaitedMs: () => {
1407
+ const runners = now() - startedAt - ownMs();
1408
+ if (runners - toldWaitedMs < 100) return;
1409
+ const untold = runners - toldWaitedMs;
1410
+ toldWaitedMs = runners;
1411
+ return untold;
1412
+ },
1413
+ elapsedMs: () => now() - startedAt
1414
+ };
1415
+ };
1416
+ // src/runner/stops.ts
1417
+ /** Why a runner gave an invocation back that was within its own memory: the runner's, never the code's. */
1418
+ var SHED_SAID = "The functions runner ran short of memory and gave this invocation back before it took the whole runner down: another runner takes it";
1419
+ /** Past its memory: how much, and the size to ask for instead — the one thing its author can change. */
1420
+ var memoryStopMessage = (memoryMb) => {
1421
+ const size = functionSizeOfMemory(memoryMb);
1422
+ const larger = size ? largerFunctionSize(size) : void 0;
1423
+ const ran = size ? ` (a ${size} task)` : "";
1424
+ return larger ? `Went over its ${String(memoryMb)} MB of memory${ran}: a task that needs more asks to be larger in its limits ({ size: '${larger}' }), as far as its plan allows` : `Went over its ${String(memoryMb)} MB of memory${ran}, the most a task runs with: hold less of it at once`;
1425
+ };
1426
+ var stopMessage = (reason, limits) => {
1427
+ switch (reason) {
1428
+ case "cpu": return `Stopped after ${String(limits.cpuMs)} ms of CPU`;
1429
+ case "wall": return `Did not finish within ${String(limits.wallMs)} ms`;
1430
+ case "memory": return memoryStopMessage(limits.memoryMb);
1431
+ case "output": return `Answered more than the ${String(limits.outputBytes)} bytes it may`;
1432
+ case "calls": return `Made more than the ${String(limits.calls)} calls to the platform it may`;
1433
+ case "aborted": return "The run was aborted";
1434
+ }
1435
+ };
1436
+ /** How a stop reads to the platform: a limit of its own as itself; given back by the runner, as `busy`. */
1437
+ var failureOfStop = (reason, limits) => reason === "shed" ? new FunctionFailure("busy", SHED_SAID) : new FunctionFailure(reason, stopMessage(reason, limits));
1438
+ /**
1439
+ * What an invocation that threw failed with. A failure of its own, with nothing stopped, as itself; else the reason it
1440
+ * was stopped for — isolated-vm's own timeout is only ever given `wallMs`, so its error is the time limit, a synchronous
1441
+ * stretch that outlasted it; an isolate disposed with no reason of ours is V8 out of the isolate's memory, which took it
1442
+ * down itself — and the code's own error when there was none.
1443
+ */
1444
+ var failureOfThrown = (error, { stopped, disposed, limits }) => {
1445
+ if (error instanceof FunctionFailure && !stopped) return error;
1446
+ const timedOut = error instanceof Error && error.message === "Script execution timed out.";
1447
+ const reason = stopped ?? (timedOut ? "wall" : disposed ? "memory" : void 0);
1448
+ return reason ? failureOfStop(reason, limits) : new FunctionFailure("error", error instanceof Error ? error.message : String(error));
1449
+ };
1450
+ /** The first reason an invocation is stopped for, kept: what stops it after that changes nothing it says. */
1451
+ var createStops = (dispose) => {
1452
+ let stopped;
1453
+ return {
1454
+ stop: (reason) => {
1455
+ stopped ??= reason;
1456
+ dispose();
1457
+ },
1458
+ stopped: () => stopped
1459
+ };
1460
+ };
1461
+ // src/runner/turnHolder.ts
1462
+ /**
1463
+ * The turn at running JavaScript one invocation holds, if any. It gives it up while it waits on the platform and takes
1464
+ * one again before it hears back (`waitingOn`): a turn waited for is the runner's time, and an isolate that waits holds
1465
+ * none another could run in.
1466
+ */
1467
+ var createTurnHolder = (turns) => {
1468
+ let holding;
1469
+ /** A turn asked for and not yet given: two answers back at once ask once. */
1470
+ let taking;
1471
+ /** Ended: a turn handed to it after that goes straight back. */
1472
+ let ended = false;
1473
+ const take = async () => {
1474
+ if (holding !== void 0) return;
1475
+ taking ??= turns.take().then((id) => {
1476
+ taking = void 0;
1477
+ if (ended) turns.give(id);
1478
+ else holding = id;
1479
+ });
1480
+ await taking;
1481
+ };
1482
+ const give = () => {
1483
+ if (holding !== void 0) {
1484
+ turns.give(holding);
1485
+ holding = void 0;
1486
+ }
1487
+ };
1488
+ return {
1489
+ take,
1490
+ give,
1491
+ holds: () => holding !== void 0,
1492
+ /** It ended: the turn it holds goes back, and so does one handed to it from now on. */
1493
+ end: () => {
1494
+ ended = true;
1495
+ give();
1496
+ }
1497
+ };
1498
+ };
1499
+ /**
1308
1500
  * Turns at running JavaScript, handed out in the order they were asked for: as many running at once as the runner has
1309
1501
  * cores — what keeps them from fighting for its CPU. A turn held past a slice no longer counts against them while others
1310
1502
  * wait: a long run shares the CPU with the next, as a scheduler would, rather than holding every other isolate up. Long
@@ -1344,8 +1536,6 @@ var createTurns = (size) => {
1344
1536
  };
1345
1537
  };
1346
1538
  // src/runner/isolate.ts
1347
- /** Why a runner gave an invocation back that was within its own memory: the runner's, never the code's. */
1348
- var SHED_SAID = "The functions runner ran short of memory and gave this invocation back before it took the whole runner down: another runner takes it";
1349
1539
  /** What reading a bundle's declaration may spend: its top level runs, and nothing else. */
1350
1540
  var DESCRIBE_LIMITS = {
1351
1541
  cpuMs: 1e3,
@@ -1360,15 +1550,6 @@ var DESCRIBE_LIMITS = {
1360
1550
  */
1361
1551
  var describeAnswer = (call) => typeof call === "object" && call !== null && "op" in call && call.op === "log" ? Promise.resolve(void 0) : Promise.reject(/* @__PURE__ */ new Error("Nothing is reachable while a bundle is read"));
1362
1552
  var WATCHDOG_MS = 5;
1363
- /** How much of an invocation's time is the runner's before the platform is told, so its wait for the answer grows. */
1364
- var TELL_WAITED_MS = 100;
1365
- /**
1366
- * What isolated-vm throws when a `timeout` it was given runs out. Its timeout is wall time while the isolate runs, not
1367
- * CPU: a runner whose isolates share its CPU stretched a 5 ms route past a 100 ms "CPU limit" under load. So it is given
1368
- * the wall limit, a backstop; the CPU limit is the watchdog's, which reads the isolate's share of the process's CPU
1369
- * (`createCpuMeter`).
1370
- */
1371
- var ISOLATE_TIMEOUT = "Script execution timed out.";
1372
1553
  /** How long code that listens to `ctx.signal` gets to stop by itself before the isolate is disposed under it. */
1373
1554
  var ABORT_GRACE_MS = 50;
1374
1555
  var NO_NODE_SNAPSHOT = "--no-node-snapshot";
@@ -1391,23 +1572,6 @@ var loadIvm = async () => {
1391
1572
  */
1392
1573
  var cachedDataOf = (ivm, compiled) => "cachedData" in compiled && compiled.cachedData instanceof ivm.ExternalCopy ? compiled.cachedData : void 0;
1393
1574
  var messageOf = (error) => error instanceof Error ? error.message : String(error);
1394
- /** Past its memory: how much, and the size to ask for instead — the one thing its author can change. */
1395
- var memoryStopMessage = (memoryMb) => {
1396
- const size = functionSizeOfMemory(memoryMb);
1397
- const larger = size ? largerFunctionSize(size) : void 0;
1398
- const ran = size ? ` (a ${size} task)` : "";
1399
- return larger ? `Went over its ${String(memoryMb)} MB of memory${ran}: a task that needs more asks to be larger in its limits ({ size: '${larger}' }), as far as its plan allows` : `Went over its ${String(memoryMb)} MB of memory${ran}, the most a task runs with: hold less of it at once`;
1400
- };
1401
- var stopMessage = (reason, limits) => {
1402
- switch (reason) {
1403
- case "cpu": return `Stopped after ${String(limits.cpuMs)} ms of CPU`;
1404
- case "wall": return `Did not finish within ${String(limits.wallMs)} ms`;
1405
- case "memory": return memoryStopMessage(limits.memoryMb);
1406
- case "output": return `Answered more than the ${String(limits.outputBytes)} bytes it may`;
1407
- case "calls": return `Made more than the ${String(limits.calls)} calls to the platform it may`;
1408
- case "aborted": return "The run was aborted";
1409
- }
1410
- };
1411
1575
  /**
1412
1576
  * The most a PBKDF2 derivation may ask for. The runner does the work, outside the isolate's clock, so each is bounded
1413
1577
  * here and its time is charged to the run's CPU: a million rounds is past any password guidance, and 1024 bits past
@@ -1551,14 +1715,11 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turn
1551
1715
  snapshot
1552
1716
  });
1553
1717
  const timers = /* @__PURE__ */ new Set();
1554
- /** Why it was stopped: a limit of its own, an abort — or `shed`, given back by a runner short of memory. */
1555
- let stopped;
1718
+ const clock = createRunClock();
1719
+ const turn = createTurnHolder(turns);
1556
1720
  let calls = 0;
1557
- const startedAt = Date.now();
1558
1721
  /** The CPU the isolate was measured at, kept as it is read: a disposed isolate has none left to ask. */
1559
1722
  let isolateCpuMs = 0;
1560
- /** What the runner spent on the run's behalf — a PBKDF2 derivation — which the isolate's clock never sees. */
1561
- let hostCpuMs = 0;
1562
1723
  /**
1563
1724
  * The isolate's CPU once it was ready — the guest and the bundle compiled, the first time on a runner without V8's
1564
1725
  * cache of them: the platform's work, not the space's code. Its time is the code's own from there.
@@ -1569,84 +1730,25 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turn
1569
1730
  return isolateCpuMs;
1570
1731
  };
1571
1732
  /** Whether it ran since the last look: what it was measured at moved. */
1572
- const readCpu = () => (readyCpuMs === void 0 ? 0 : readIsolateCpu() - readyCpuMs) + hostCpuMs;
1573
- /** Its share of the process's CPU from the moment it was ready (`createCpuMeter`), and what the runner spent for it. */
1733
+ const readCpu = () => (readyCpuMs === void 0 ? 0 : readIsolateCpu() - readyCpuMs) + clock.hostCpuMs();
1574
1734
  let metered;
1575
- const chargedCpu = () => (metered?.charged() ?? 0) + hostCpuMs;
1576
- /** Whether its code began: what came before — the isolate made, the bundle compiled — is the platform's time. */
1577
- let codeBegan = false;
1578
- /** How long it waited on what it asked of the platform — calls, sleeps — counted once while it waits on several. */
1579
- let awaitedMs = 0;
1580
- let awaitingSince;
1581
- /**
1582
- * Its own time: what it waited on that it asked for, and the CPU it took — what it would take on a runner of its own.
1583
- * Never the runner's: a turn waited for, a place behind other isolates in isolated-vm's threads (one per core: a
1584
- * spinner holds one until it ends), a core it was ready for and did not get. Counted from the clock, a route that
1585
- * slept 200 ms on a crowded runner was stopped at its 10 s.
1586
- */
1587
- /**
1588
- * A sleep counts what it asked for: the timer that wakes it is the runner's, on its main thread, and a crowded runner
1589
- * woke a 200 ms sleep seconds late — counted, a route was stopped at its 10 s. Its lateness, of the sleeps that ended
1590
- * and of the ones still past their time, is the runner's.
1591
- */
1592
- let lateMs = 0;
1593
- const sleeping = /* @__PURE__ */ new Set();
1594
- const lateNow = (now) => [...sleeping].reduce((late, sleep) => late + Math.max(0, now - sleep.from - sleep.wanted), lateMs);
1595
- const ownMs = () => {
1596
- if (!codeBegan) return 0;
1597
- const now = Date.now();
1598
- const awaitedNow = awaitedMs + (awaitingSince === void 0 ? 0 : now - awaitingSince);
1599
- return Math.max(0, awaitedNow - lateNow(now)) + chargedCpu();
1600
- };
1601
- /** The turn at running JavaScript this isolate holds, if any, and how many answers of the platform it waits for. */
1602
- let holding;
1603
- let awaited = 0;
1604
1735
  /** What its CPU read when the watchdog last looked: still, while it waits, it is not running. */
1605
1736
  let lastCpuMs = 0;
1606
- /** A turn asked for and not yet given: two answers back at once ask once. */
1607
- let taking;
1608
- /** Ended: a turn handed to it after that goes straight back. */
1609
- let ended = false;
1610
- /** What of its time was the runner's, and told the platform so far: its wait for the answer grows by it. */
1611
- let toldWaitedMs = 0;
1612
- const takeTurn = async () => {
1613
- if (holding !== void 0) return;
1614
- taking ??= turns.take().then((id) => {
1615
- taking = void 0;
1616
- if (ended) turns.give(id);
1617
- else holding = id;
1618
- });
1619
- await taking;
1620
- };
1621
- const giveTurn = () => {
1622
- if (holding !== void 0) {
1623
- turns.give(holding);
1624
- holding = void 0;
1625
- }
1626
- };
1737
+ const { stop, stopped } = createStops(() => {
1738
+ readCpu();
1739
+ if (!isolate.isDisposed) isolate.dispose();
1740
+ });
1627
1741
  /** Something it asked of the platform, its turn given up while it waits and taken again before it hears back. */
1628
1742
  const waitingOn = async (work) => {
1629
- if (awaited === 0) awaitingSince = Date.now();
1630
- awaited++;
1631
- giveTurn();
1743
+ clock.waitBegins();
1744
+ turn.give();
1632
1745
  try {
1633
1746
  return await work();
1634
1747
  } finally {
1635
- awaited--;
1636
- if (awaited === 0 && awaitingSince !== void 0) {
1637
- awaitedMs += Date.now() - awaitingSince;
1638
- awaitingSince = void 0;
1639
- }
1640
- await takeTurn();
1748
+ clock.waitEnds();
1749
+ await turn.take();
1641
1750
  }
1642
1751
  };
1643
- const stop = (reason) => {
1644
- stopped ??= reason;
1645
- readCpu();
1646
- if (!isolate.isDisposed) isolate.dispose();
1647
- };
1648
- /** How a stop reads to the platform: a limit of its own as itself; given back by the runner, as `busy`. */
1649
- const failureOf = (reason) => reason === "shed" ? new FunctionFailure("busy", SHED_SAID) : new FunctionFailure(reason, stopMessage(reason, limits));
1650
1752
  const running = {
1651
1753
  heldBytes: () => {
1652
1754
  if (isolate.isDisposed) return 0;
@@ -1669,15 +1771,11 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turn
1669
1771
  };
1670
1772
  const watchdog = setInterval(() => {
1671
1773
  const cpuMs = readCpu();
1672
- if (!isolate.isDisposed && chargedCpu() > limits.cpuMs) stop("cpu");
1673
- const own = ownMs();
1674
- if (!isolate.isDisposed && own > limits.wallMs) stop("wall");
1675
- const runners = Date.now() - startedAt - own;
1676
- if (onWaited && runners - toldWaitedMs >= TELL_WAITED_MS) {
1677
- onWaited(runners - toldWaitedMs);
1678
- toldWaitedMs = runners;
1679
- }
1680
- if (holding !== void 0 && awaited > 0 && cpuMs === lastCpuMs) giveTurn();
1774
+ const over = isolate.isDisposed ? void 0 : clock.overLimit(limits);
1775
+ if (over) stop(over);
1776
+ const untold = onWaited ? clock.untoldWaitedMs() : void 0;
1777
+ if (onWaited && untold !== void 0) onWaited(untold);
1778
+ if (turn.holds() && clock.waits() > 0 && cpuMs === lastCpuMs) turn.give();
1681
1779
  lastCpuMs = cpuMs;
1682
1780
  }, WATCHDOG_MS);
1683
1781
  let driver;
@@ -1712,29 +1810,22 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turn
1712
1810
  });
1713
1811
  }));
1714
1812
  global.setSync("__plitziSleep", new ivm.Reference((ms) => {
1715
- const left = limits.wallMs - ownMs();
1716
- const wanted = Math.max(0, ms);
1717
- if (wanted >= left) {
1718
- later(Math.max(0, left), () => stop("wall"));
1813
+ const plan = clock.sleep(ms, limits.wallMs);
1814
+ if (!plan.wakes) {
1815
+ later(plan.stopInMs, () => stop("wall"));
1719
1816
  return waitingOn(() => new Promise(() => void 0));
1720
1817
  }
1721
- const sleep = {
1722
- from: Date.now(),
1723
- wanted
1724
- };
1725
- sleeping.add(sleep);
1726
1818
  return waitingOn(() => new Promise((resolve) => {
1727
- later(wanted, () => {
1728
- sleeping.delete(sleep);
1729
- lateMs += Math.max(0, Date.now() - sleep.from - wanted);
1819
+ later(plan.wanted, () => {
1820
+ plan.woke();
1730
1821
  resolve();
1731
1822
  });
1732
1823
  }));
1733
1824
  }));
1734
1825
  global.setSync("__plitziRandom", new ivm.Callback((length) => [...randomBytes(Math.min(Math.max(0, length), 65536))]));
1735
1826
  global.setSync("__plitziCrypto", new ivm.Reference((message) => waitingOn(() => cryptoAnswer(message, (ms) => {
1736
- hostCpuMs += ms;
1737
- if (chargedCpu() > limits.cpuMs) stop("cpu");
1827
+ clock.chargeHost(ms);
1828
+ if (clock.chargedCpu() > limits.cpuMs) stop("cpu");
1738
1829
  }))));
1739
1830
  const guestScript = isolate.compileScriptSync(BOOTSTRAP, {
1740
1831
  filename: "plitzi:guest",
@@ -1752,39 +1843,41 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 33554432, turns: turn
1752
1843
  module.instantiateSync(context, (specifier) => {
1753
1844
  throw new Error(`"${specifier}" cannot be imported: a bundle is one module`);
1754
1845
  });
1755
- await takeTurn();
1846
+ await turn.take();
1756
1847
  readyCpuMs = readIsolateCpu();
1757
- metered = cpu.meter(readIsolateCpu);
1758
- codeBegan = true;
1848
+ const meter = cpu.meter(readIsolateCpu);
1849
+ metered = meter;
1850
+ clock.begin(() => meter.charged());
1759
1851
  await module.evaluate();
1760
1852
  const definition = module.namespace.getSync("default", { reference: true });
1761
1853
  if (definition.typeof !== "object") throw new FunctionFailure("error", "The functions bundle exports no definition: each file at the top of functions/ exports one by default — export default defineFunctions({ tasks: [ … ] })");
1762
1854
  const text = await drive(driver, definition);
1763
1855
  if (Buffer.byteLength(text) > limits.outputBytes) stop("output");
1764
- if (stopped) throw failureOf(stopped);
1856
+ const stoppedFor = stopped();
1857
+ if (stoppedFor) throw failureOfStop(stoppedFor, limits);
1765
1858
  const outcome = JSON.parse(text);
1766
1859
  if (typeof outcome !== "object" || outcome === null || !("ok" in outcome)) throw new FunctionFailure("error", "The runtime answered something that is not an outcome");
1767
1860
  if (outcome.ok !== true) throw new FunctionFailure("refused" in outcome && outcome.refused === true ? "refused" : "error", "error" in outcome ? String(outcome.error) : "The function failed");
1768
1861
  return "value" in outcome ? outcome.value : null;
1769
1862
  } catch (error) {
1770
- if (error instanceof FunctionFailure && !stopped) throw error;
1771
- const timedOut = error instanceof Error && error.message === ISOLATE_TIMEOUT;
1772
- const reason = stopped ?? (timedOut ? "wall" : isolate.isDisposed ? "memory" : void 0);
1773
- throw reason ? failureOf(reason) : new FunctionFailure("error", messageOf(error));
1863
+ throw failureOfThrown(error, {
1864
+ stopped: stopped(),
1865
+ disposed: isolate.isDisposed,
1866
+ limits
1867
+ });
1774
1868
  } finally {
1775
1869
  live.delete(running);
1776
1870
  metered?.end();
1777
1871
  onUsage?.({
1778
- cpuMs: Math.round(chargedCpu()),
1779
- wallMs: Date.now() - startedAt,
1872
+ cpuMs: Math.round(clock.chargedCpu()),
1873
+ wallMs: clock.elapsedMs(),
1780
1874
  calls
1781
1875
  });
1782
1876
  clearInterval(watchdog);
1783
1877
  timers.forEach((timer) => clearTimeout(timer));
1784
1878
  signal?.removeEventListener("abort", onAbort);
1785
1879
  if (!isolate.isDisposed) isolate.dispose();
1786
- ended = true;
1787
- giveTurn();
1880
+ turn.end();
1788
1881
  release();
1789
1882
  }
1790
1883
  };
@@ -1887,7 +1980,11 @@ var KEPT_LOOK_MS = 100;
1887
1980
  var BACKGROUND_SHARE = .75;
1888
1981
  /** How an invocation that did not answer reads to the stats: a limit, its code refusing, or a failure. */
1889
1982
  var endOf = (reason) => isFunctionLimit(reason) ? { limit: reason } : reason === "refused" ? { refused: true } : { failed: reason };
1890
- var serveConnection = (socket, runner, stats) => {
1983
+ /**
1984
+ * One invocation over its socket. `trace` is the worker's — the span the connection was opened in — so everything the
1985
+ * invocation does and logs is that run's: a socket's messages come from its own connection, outside any request.
1986
+ */
1987
+ var serveConnection = (socket, runner, stats, trace) => {
1891
1988
  const pending = /* @__PURE__ */ new Map();
1892
1989
  const controller = new AbortController();
1893
1990
  let nextCall = 1;
@@ -1903,9 +2000,13 @@ var serveConnection = (socket, runner, stats) => {
1903
2000
  let takenLimits;
1904
2001
  const finish = (message) => {
1905
2002
  if (invokedAt !== void 0) {
2003
+ const tookMs = Date.now() - invokedAt;
1906
2004
  stats.inFlight.count -= 1;
1907
- stats.recorder.run(Date.now() - invokedAt, message.type === "failed" ? endOf(message.reason) : void 0, label);
2005
+ stats.recorder.run(tookMs, message.type === "failed" ? endOf(message.reason) : void 0, label);
1908
2006
  invokedAt = void 0;
2007
+ const what = label ? `${label.kind} ${label.name} space=${String(label.spaceId)}` : "an invocation";
2008
+ if (message.type === "failed" && "failed" in endOf(message.reason)) serverLog.warn("Functions", `${what} failed (${message.reason}) ${String(tookMs)}ms`);
2009
+ else serverLog.debug("Functions", `${what} ${message.type === "failed" ? message.reason : "answered"} ${String(tookMs)}ms`);
1909
2010
  }
1910
2011
  if (takenLimits) {
1911
2012
  stats.ended(takenLimits);
@@ -1987,7 +2088,7 @@ var serveConnection = (socket, runner, stats) => {
1987
2088
  call
1988
2089
  });
1989
2090
  });
1990
- socket.on("message", (data) => {
2091
+ const onMessage = (data) => {
1991
2092
  const message = readRequestMessage(frameText(data));
1992
2093
  if (!message) {
1993
2094
  finish({
@@ -2042,6 +2143,11 @@ var serveConnection = (socket, runner, stats) => {
2042
2143
  error: error instanceof Error ? error.message : String(error)
2043
2144
  });
2044
2145
  });
2146
+ };
2147
+ socket.on("message", (data) => {
2148
+ runInTrace(trace, () => {
2149
+ onMessage(data);
2150
+ });
2045
2151
  });
2046
2152
  /** An invocation taken — now, or once there is room for it — and run. */
2047
2153
  const start = async (message) => {
@@ -2244,6 +2350,15 @@ var startFunctionsRunnerService = async ({ secret, port = 8790, host = "0.0.0.0"
2244
2350
  return;
2245
2351
  }
2246
2352
  const asked = new URL(req.url ?? "/", "http://runner");
2353
+ if (req.method === "GET" && asked.pathname === STATS_METRICS_PATH) {
2354
+ const allowed = bearerMatches(req.headers.authorization, secret);
2355
+ res.writeHead(allowed ? 200 : 401, {
2356
+ "content-type": allowed ? METRICS_CONTENT_TYPE : "application/json; charset=utf-8",
2357
+ "cache-control": "no-store"
2358
+ });
2359
+ res.end(allowed ? metricsText(withStopping(recorder.snapshot(), stopping)) : JSON.stringify({ error: `${asked.pathname} is read with the runner's secret` }));
2360
+ return;
2361
+ }
2247
2362
  if (req.method === "GET" && (asked.pathname === STATS_PATH || asked.pathname === STATS_LOGS_PATH)) {
2248
2363
  const allowed = bearerMatches(req.headers.authorization, secret);
2249
2364
  res.writeHead(allowed ? 200 : 401, {
@@ -2276,6 +2391,7 @@ var startFunctionsRunnerService = async ({ secret, port = 8790, host = "0.0.0.0"
2276
2391
  socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
2277
2392
  return;
2278
2393
  }
2394
+ const trace = spanOf(readTraceparent(req.headers[TRACEPARENT]));
2279
2395
  sockets.handleUpgrade(req, socket, head, (ws) => serveConnection(ws, engine, {
2280
2396
  recorder,
2281
2397
  inFlight,
@@ -2287,7 +2403,7 @@ var startFunctionsRunnerService = async ({ secret, port = 8790, host = "0.0.0.0"
2287
2403
  release(limits);
2288
2404
  letIn();
2289
2405
  }
2290
- }));
2406
+ }, trace));
2291
2407
  });
2292
2408
  const connections = watchConnections(server);
2293
2409
  await new Promise((resolve, reject) => {
@@ -1,4 +1,4 @@
1
- import { c as describeFunctions, n as startFunctionsRunnerService, s as createFunctionsDriver } from "../chunks/service-DDDJomiH.mjs";
1
+ import { c as describeFunctions, n as startFunctionsRunnerService, s as createFunctionsDriver } from "../chunks/service-BciHswSg.mjs";
2
2
  import { ActionRefusal, FunctionFailure, PLATFORM_HEADERS, RUNTIME_DESCRIBE_PATH, changeKv, changeListEntry, endpointFor, endpointProblem, isActionRefusal, requestFromWire, responseOf, wireResponseFrom, wireResponseOf } from "@plitzi/sdk-shared/functions";
3
3
  import { webRequestOf, writeWebResponse } from "@plitzi/sdk-kernel/http";
4
4
  import { reachSpaceInside } from "@plitzi/sdk-kernel/outbound";
@@ -12,11 +12,19 @@ import { reachSpaceInside } from "@plitzi/sdk-kernel/outbound";
12
12
  *
13
13
  * The bundle a request names is not asked for: the code is the one this runtime was started with.
14
14
  */
15
+ /** How long code that listens to `ctx.signal` gets to stop by itself once aborted — the sandbox's own grace. */
16
+ var ABORT_GRACE_MS = 50;
15
17
  var createRuntimeRunner = (definition = {}) => ({
16
18
  describe: () => Promise.resolve(describeFunctions(definition)),
17
- invoke: async ({ invocation, answer, signal }) => {
19
+ invoke: async ({ invocation, answer, signal, onUsage }) => {
20
+ const startedAt = Date.now();
21
+ let calls = 0;
22
+ const counted = (call) => {
23
+ calls += 1;
24
+ return answer(call);
25
+ };
18
26
  const driver = createFunctionsDriver({
19
- call: answer,
27
+ call: counted,
20
28
  signal,
21
29
  responseOf: (wire) => responseOf(wireResponseFrom(wire)),
22
30
  requestOf: requestFromWire,
@@ -35,11 +43,32 @@ var createRuntimeRunner = (definition = {}) => ({
35
43
  changeListEntry,
36
44
  refusal: (message) => new ActionRefusal(message)
37
45
  });
46
+ const graceMs = invocation.kind === "job" ? invocation.graceMs : ABORT_GRACE_MS;
47
+ let stop;
48
+ let cut;
49
+ const aborted = new Promise((_resolve, reject) => {
50
+ stop = () => {
51
+ cut = setTimeout(() => {
52
+ reject(new FunctionFailure("aborted", typeof signal.reason === "string" ? signal.reason : "Aborted"));
53
+ }, graceMs);
54
+ };
55
+ if (signal.aborted) stop();
56
+ else signal.addEventListener("abort", stop, { once: true });
57
+ });
38
58
  try {
39
- return await driver.invoke(definition, invocation);
59
+ return await Promise.race([driver.invoke(definition, invocation), aborted]);
40
60
  } catch (error) {
61
+ if (error instanceof FunctionFailure) throw error;
41
62
  if (isActionRefusal(error)) throw new FunctionFailure("refused", error.message);
42
- throw error;
63
+ throw new FunctionFailure("error", error instanceof Error ? error.message : String(error));
64
+ } finally {
65
+ clearTimeout(cut);
66
+ if (stop) signal.removeEventListener("abort", stop);
67
+ onUsage?.({
68
+ cpuMs: 0,
69
+ wallMs: Date.now() - startedAt,
70
+ calls
71
+ });
43
72
  }
44
73
  }
45
74
  });
@@ -1,11 +1,2 @@
1
1
  import { FunctionsDefinition, FunctionRunner } from '@plitzi/sdk-shared/functions';
2
- /** A refusal, however it was made: the platform's class, or a bundle's own copy of it — known by its name. */
3
- /**
4
- * A runtime's functions as a runner: the same protocol as the sandbox's, answered by code loaded in this process. The
5
- * driver is the sandbox's own (`createFunctionsDriver`), so a task behaves the same in both — its `ctx` is calls to the
6
- * platform, `ctx.kv.change` the same loop, a refusal the same answer. What it does not share is the isolate: there are
7
- * no limits here but the platform's clock, since this process is the space's alone — and a route's answer streams.
8
- *
9
- * The bundle a request names is not asked for: the code is the one this runtime was started with.
10
- */
11
2
  export declare const createRuntimeRunner: (definition?: FunctionsDefinition) => FunctionRunner;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `@plitzi/sdk-runtime`: the contract a space's own code is written against, and what runs it with no access (RFC 0032).
2
+ * `@plitzi/sdk-runtime`: the contract a space's own code is written against, and what runs it with no access (docs/en/server-packages.md).
3
3
  *
4
4
  * The root is the contract alone — what a space's functions and its runtime import, the same file whether a self-hosted
5
5
  * server loads it natively or the platform runs it in its sandbox:
@@ -1 +1 @@
1
- export { r as PBKDF2_MAX_BITS, i as PBKDF2_MAX_ITERATIONS, o as createCpuMeter, a as createIsolateRunner, t as invocationFootprintMb, n as startFunctionsRunnerService } from "../chunks/service-DDDJomiH.mjs";
1
+ export { r as PBKDF2_MAX_BITS, i as PBKDF2_MAX_ITERATIONS, o as createCpuMeter, a as createIsolateRunner, t as invocationFootprintMb, n as startFunctionsRunnerService } from "../chunks/service-BciHswSg.mjs";
@@ -0,0 +1,53 @@
1
+ import { FunctionLimits } from '@plitzi/sdk-shared/functions';
2
+ /** How much of an invocation's time is the runner's before the platform is told, so its wait for the answer grows. */
3
+ export declare const TELL_WAITED_MS = 100;
4
+ /** A sleep the code asked for: how long it waits, or that it waits past its time and is stopped at it. */
5
+ export type SleepPlan = {
6
+ wakes: true;
7
+ wanted: number;
8
+ woke: () => void;
9
+ } | {
10
+ wakes: false;
11
+ stopInMs: number;
12
+ };
13
+ /**
14
+ * An invocation's clock: what its time is, what its CPU is, and what of the clock was the runner's.
15
+ *
16
+ * Its own time is what it waited on that it asked for, and the CPU it was charged — what it would take on a runner of
17
+ * its own. Never the runner's: a turn waited for, a place behind other isolates in isolated-vm's threads (one per core:
18
+ * a spinner holds one until it ends), a core it was ready for and did not get. Counted from the clock, a route that
19
+ * slept 200 ms on a crowded runner was stopped at its 10 s.
20
+ *
21
+ * Pure over `now`: it reads no isolate. Its CPU is handed in once the code begins (`begin`) — the isolate's share of the
22
+ * process's (`createCpuMeter`) — beside what the runner spent on its behalf (`chargeHost`).
23
+ */
24
+ export declare const createRunClock: ({ now }?: {
25
+ now?: () => number;
26
+ }) => {
27
+ /** Its code began: what came before — the isolate made, the bundle compiled — is the platform's time. */
28
+ begin: (charged: () => number) => void;
29
+ chargeHost: (ms: number) => void;
30
+ hostCpuMs: () => number;
31
+ chargedCpu: () => number;
32
+ ownMs: () => number;
33
+ /** It began waiting on something it asked of the platform. */
34
+ waitBegins: () => void;
35
+ waitEnds: () => void;
36
+ /** How many answers of the platform it waits for now. */
37
+ waits: () => number;
38
+ /**
39
+ * A sleep of `ms`: past the time it has left it ends the run there, by its time limit — never cut short to fit: cut,
40
+ * the code woke at the limit and, the watchdog a look behind, finished as if it had slept.
41
+ */
42
+ sleep: (ms: number, wallMs: number) => SleepPlan;
43
+ /** The limit its time or its CPU went past, the CPU first — or nothing. */
44
+ overLimit: ({ cpuMs, wallMs }: Pick<FunctionLimits, "cpuMs" | "wallMs">) => "cpu" | "wall" | undefined;
45
+ /**
46
+ * What of the clock was the runner's since it was last told, once that is a tell's worth — every moment that was
47
+ * not its own: its isolate made, a turn, a place behind others, a core. Told the platform, whose wait for the answer
48
+ * would otherwise run out on time the code never had.
49
+ */
50
+ untoldWaitedMs: () => number | undefined;
51
+ elapsedMs: () => number;
52
+ };
53
+ export type RunClock = ReturnType<typeof createRunClock>;
@@ -0,0 +1,31 @@
1
+ import { FunctionFailure, FunctionLimits, FunctionStopReason } from '@plitzi/sdk-shared/functions';
2
+ /** Why an invocation was stopped: a limit of its own, an abort — or `shed`, given back by a runner short of memory. */
3
+ export type StopReason = FunctionStopReason | 'shed';
4
+ /** Why a runner gave an invocation back that was within its own memory: the runner's, never the code's. */
5
+ export declare const SHED_SAID: string;
6
+ /**
7
+ * What isolated-vm throws when a `timeout` it was given runs out. Its timeout is wall time while the isolate runs, not
8
+ * CPU: a runner whose isolates share its CPU stretched a 5 ms route past a 100 ms "CPU limit" under load. So it is given
9
+ * the wall limit, a backstop; the CPU limit is the watchdog's, which reads the isolate's share of the process's CPU
10
+ * (`createCpuMeter`).
11
+ */
12
+ export declare const ISOLATE_TIMEOUT = "Script execution timed out.";
13
+ export declare const stopMessage: (reason: FunctionStopReason, limits: FunctionLimits) => string;
14
+ /** How a stop reads to the platform: a limit of its own as itself; given back by the runner, as `busy`. */
15
+ export declare const failureOfStop: (reason: StopReason, limits: FunctionLimits) => FunctionFailure;
16
+ /**
17
+ * What an invocation that threw failed with. A failure of its own, with nothing stopped, as itself; else the reason it
18
+ * was stopped for — isolated-vm's own timeout is only ever given `wallMs`, so its error is the time limit, a synchronous
19
+ * stretch that outlasted it; an isolate disposed with no reason of ours is V8 out of the isolate's memory, which took it
20
+ * down itself — and the code's own error when there was none.
21
+ */
22
+ export declare const failureOfThrown: (error: unknown, { stopped, disposed, limits }: {
23
+ stopped: StopReason | undefined;
24
+ disposed: boolean;
25
+ limits: FunctionLimits;
26
+ }) => FunctionFailure;
27
+ /** The first reason an invocation is stopped for, kept: what stops it after that changes nothing it says. */
28
+ export declare const createStops: (dispose: () => void) => {
29
+ stop: (reason: StopReason) => void;
30
+ stopped: () => StopReason | undefined;
31
+ };
@@ -0,0 +1,18 @@
1
+ /** Where turns come from: the runner's (`createTurns`), handed out in the order they were asked for. */
2
+ export type TurnSource = {
3
+ take: () => Promise<number>;
4
+ give: (id: number) => void;
5
+ };
6
+ /**
7
+ * The turn at running JavaScript one invocation holds, if any. It gives it up while it waits on the platform and takes
8
+ * one again before it hears back (`waitingOn`): a turn waited for is the runner's time, and an isolate that waits holds
9
+ * none another could run in.
10
+ */
11
+ export declare const createTurnHolder: (turns: TurnSource) => {
12
+ take: () => Promise<void>;
13
+ give: () => void;
14
+ holds: () => boolean;
15
+ /** It ended: the turn it holds goes back, and so does one handed to it from now on. */
16
+ end: () => void;
17
+ };
18
+ export type TurnHolder = ReturnType<typeof createTurnHolder>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-runtime",
3
- "version": "0.39.2",
3
+ "version": "0.39.4",
4
4
  "license": "AGPL-3.0",
5
5
  "description": "The contract a space's own code is written against, and what runs it with no access: the functions runner, its isolates, and the host of a space's runtime.",
6
6
  "files": [
@@ -38,8 +38,8 @@
38
38
  "build:prod": "vite build && node scripts/prelude.mjs && node scripts/functions-api.mjs"
39
39
  },
40
40
  "dependencies": {
41
- "@plitzi/sdk-kernel": "0.39.2",
42
- "@plitzi/sdk-shared": "0.39.2",
41
+ "@plitzi/sdk-kernel": "0.39.4",
42
+ "@plitzi/sdk-shared": "0.39.4",
43
43
  "ws": "^8.22.2"
44
44
  },
45
45
  "peerDependencies": {