@kvbox/server 0.6.18 → 0.6.20

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.
@@ -1041,6 +1041,7 @@ function guestSocket(box, port, p) {
1041
1041
  }
1042
1042
 
1043
1043
  // src/core/drivers/firecracker/index.ts
1044
+ var MS_PER_TICK = 10;
1044
1045
  var firecrackerDriver = {
1045
1046
  name: "firecracker",
1046
1047
  diffSnapshots: true,
@@ -1056,7 +1057,17 @@ var firecrackerDriver = {
1056
1057
  shutdown,
1057
1058
  saveState,
1058
1059
  cleanup,
1059
- guestSocket
1060
+ guestSocket,
1061
+ async cpuMs(pid) {
1062
+ try {
1063
+ const stat8 = await readFile4(`/proc/${pid}/stat`, "utf8");
1064
+ const fields = stat8.slice(stat8.lastIndexOf(")") + 2).split(" ");
1065
+ const ticks = Number(fields[11]) + Number(fields[12]);
1066
+ return Number.isFinite(ticks) ? ticks * MS_PER_TICK : null;
1067
+ } catch {
1068
+ return null;
1069
+ }
1070
+ }
1060
1071
  },
1061
1072
  net: {
1062
1073
  prepare: ensureHostNetwork,
@@ -1080,6 +1091,15 @@ var firecrackerDriver = {
1080
1091
  return null;
1081
1092
  }
1082
1093
  },
1094
+ async bytes(boxId) {
1095
+ const dir = `/sys/class/net/${tapName(boxId)}/statistics`;
1096
+ try {
1097
+ const [rx, tx] = await Promise.all([readFile4(`${dir}/rx_bytes`, "utf8"), readFile4(`${dir}/tx_bytes`, "utf8")]);
1098
+ return { in: Number(tx), out: Number(rx) };
1099
+ } catch {
1100
+ return null;
1101
+ }
1102
+ },
1083
1103
  listeningPorts,
1084
1104
  openProxy,
1085
1105
  closeProxy,
@@ -1148,7 +1168,29 @@ var MIGRATIONS = [
1148
1168
  size_gib integer not null,
1149
1169
  by text not null
1150
1170
  );
1151
- create index volume_events_volume_at on volume_events (volume_id, at);`
1171
+ create index volume_events_volume_at on volume_events (volume_id, at);`,
1172
+ // Resources (observability layer 2): one row per box and five-minute slot it ran in, written when the
1173
+ // slot is over and deleted after a week. Not a ledger: nothing is billed from it.
1174
+ `create table resource_slots (
1175
+ box_id text not null,
1176
+ slot integer not null,
1177
+ owner text not null,
1178
+ name text not null,
1179
+ vcpu integer not null,
1180
+ cpu_ms integer not null,
1181
+ wall_ms integer not null,
1182
+ cpu_max_pct real not null,
1183
+ mem_samples integer not null,
1184
+ mem_sum_mib integer not null,
1185
+ mem_max_mib integer not null,
1186
+ mem_total_mib integer,
1187
+ disk_used_bytes integer,
1188
+ disk_total_bytes integer,
1189
+ net_in_bytes integer not null,
1190
+ net_out_bytes integer not null,
1191
+ primary key (box_id, slot)
1192
+ );
1193
+ create index resource_slots_slot on resource_slots (slot);`
1152
1194
  ];
1153
1195
  var handles = /* @__PURE__ */ new Map();
1154
1196
  function openDb(p = paths()) {
@@ -1193,7 +1235,7 @@ function renameLedgerRealm(from, to, p = paths()) {
1193
1235
  let rows = 0;
1194
1236
  db.exec("begin");
1195
1237
  try {
1196
- for (const table of ["usage_events", "volume_events"]) {
1238
+ for (const table of ["usage_events", "volume_events", "resource_slots"]) {
1197
1239
  const res = db.prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`).run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);
1198
1240
  rows += Number(res.changes);
1199
1241
  }
@@ -1290,6 +1332,12 @@ var MachineMetaSchema = z3.object({
1290
1332
  vcpu: z3.number().int(),
1291
1333
  memMib: z3.number().int(),
1292
1334
  createdAt: z3.string(),
1335
+ /**
1336
+ * When the guest last got its owner's variables at a start (#155): set at every cold boot and at a warm `new --from`
1337
+ * or fork (both hand the guest the list of that moment, core/machines/guest.ts); a wake or resume keeps it.
1338
+ * Absent: not booted since this field came.
1339
+ */
1340
+ bootedAt: z3.string().optional(),
1293
1341
  source: z3.string(),
1294
1342
  /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1295
1343
  base: z3.string(),
@@ -2028,6 +2076,7 @@ var WakeHookSchema = z6.object({
2028
2076
  createdAt: z6.string(),
2029
2077
  lastCalledAt: z6.string().nullable()
2030
2078
  });
2079
+ var WakeHookListSchema = z6.array(WakeHookSchema);
2031
2080
  var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z6.string() });
2032
2081
  var WakeHookCallSchema = z6.object({
2033
2082
  box: z6.string(),
@@ -2238,6 +2287,13 @@ var MachineSchema = z6.object({
2238
2287
  */
2239
2288
  latestBase: z6.string().optional(),
2240
2289
  createdAt: z6.string(),
2290
+ /**
2291
+ * When the guest last got its variables by a fresh start (#155): the host's clock at a cold boot (`new`, `start`
2292
+ * and the restarts behind rescale, update, volume attach), or at a warm `new --from`/fork, which hands the copy
2293
+ * its variables of that moment. A wake or resume keeps it. A variable changed after it waits for the next start.
2294
+ * Absent: a host before it, or a box not booted since.
2295
+ */
2296
+ bootedAt: z6.string().optional(),
2241
2297
  source: z6.string(),
2242
2298
  // "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
2243
2299
  status: BoxStatusSchema,
@@ -2302,7 +2358,9 @@ var VolumeSchema = z6.object({
2302
2358
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
2303
2359
  ownerKind: z6.enum(["user", "org"]).optional(),
2304
2360
  /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
2305
- host: z6.string().optional()
2361
+ host: z6.string().optional(),
2362
+ /** The country code of that host (`RO`, `US`), when its admin gave one (#140). Only the control plane fills it in. */
2363
+ country: z6.string().optional()
2306
2364
  });
2307
2365
  var MAX_VOLUME_GIB = 4096;
2308
2366
  var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
@@ -2573,6 +2631,7 @@ var LatestImagesSchema = z6.object({
2573
2631
  images: ImageIndexSchema.shape.images,
2574
2632
  checkedAt: z6.string().nullable()
2575
2633
  });
2634
+ var LatestServerSchema = z6.object({ version: z6.string().nullable(), checkedAt: z6.string().nullable() });
2576
2635
  var RecoveryReportSchema = z6.object({
2577
2636
  at: z6.string(),
2578
2637
  booted: z6.array(z6.string()),
@@ -2852,6 +2911,18 @@ var BalanceSchema = z6.object({
2852
2911
  balance: z6.number(),
2853
2912
  currency: z6.string(),
2854
2913
  topUps: z6.number(),
2914
+ /**
2915
+ * `topUps` split by where the money came from (#144), so a page can say "you added $X" and an org can
2916
+ * tell a top-up from a transfer: `topUps = added + welcome + transferredIn - transferredOut`. `added` is
2917
+ * card payments and an admin's top-ups (an admin's correction, negative, included); `welcome` the
2918
+ * welcome credit of a first card (`trial` rows); `transferredIn` what an owner moved into this org and
2919
+ * `transferredOut` what this user moved to their orgs, both positive. Promo credit is in none of them
2920
+ * (`promo`). Absent from a control plane older than these fields: 0.
2921
+ */
2922
+ added: z6.number().default(0),
2923
+ welcome: z6.number().default(0),
2924
+ transferredIn: z6.number().default(0),
2925
+ transferredOut: z6.number().default(0),
2855
2926
  spent: z6.number(),
2856
2927
  /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
2857
2928
  since: z6.string().nullable(),
@@ -4451,6 +4522,7 @@ function toMachine(meta, p = paths()) {
4451
4522
  ...meta.image !== void 0 ? { image: meta.image } : {},
4452
4523
  ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4453
4524
  createdAt: meta.createdAt,
4525
+ ...meta.bootedAt !== void 0 ? { bootedAt: meta.bootedAt } : {},
4454
4526
  source: meta.source,
4455
4527
  status: statusOf(meta, p),
4456
4528
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
@@ -5133,10 +5205,11 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
5133
5205
  const tap = await driver().net.create(meta, cfg);
5134
5206
  let pid;
5135
5207
  try {
5208
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5136
5209
  pid = await launch(meta, tap, cfg, keysB64, p);
5137
5210
  await openPorts(meta, cfg, p);
5138
5211
  void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
5139
- const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
5212
+ const started = { ...meta, pid, bootId: currentBootId(), bootedAt, sshKeysStale: void 0, paused: void 0 };
5140
5213
  await writeMachineMeta(started, p);
5141
5214
  recordState(started, "running", "start", p);
5142
5215
  void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
@@ -5197,10 +5270,11 @@ async function bootInto(box, prepare, origin, cfg, p) {
5197
5270
  const tap = await driver().net.create(box, cfg);
5198
5271
  tapCreated = true;
5199
5272
  const spec = { ...box, sshPort };
5273
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5200
5274
  pid = await launch(spec, tap, cfg, keysB64, p);
5201
5275
  await openPorts(spec, cfg, p);
5202
5276
  void pushEnvAfterBoot(spec, pid, m.vsock, p);
5203
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
5277
+ const meta = { ...spec, pid, bootId: currentBootId(), bootedAt, createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
5204
5278
  await writeMachineMeta(meta, p);
5205
5279
  recordState(meta, "running", "new", p, meta.createdAt);
5206
5280
  void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
@@ -5242,10 +5316,11 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
5242
5316
  const stale = await pushAuthorizedKeys(box, m.vsock, p);
5243
5317
  if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
5244
5318
  if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
5319
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5245
5320
  await pushEnv(box, m.vsock, p);
5246
5321
  await driver().net.attach(box, cfg);
5247
5322
  await openPorts(spec, cfg, p);
5248
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
5323
+ const meta = { ...spec, pid, bootId: currentBootId(), bootedAt, createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
5249
5324
  await writeMachineMeta(meta, p);
5250
5325
  recordState(meta, "running", "new", p, meta.createdAt);
5251
5326
  void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
@@ -5418,19 +5493,22 @@ async function cleanupProcess(meta, cfg, p) {
5418
5493
  }
5419
5494
  }
5420
5495
  var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
5496
+ return toMachine(await bringDown(ref, p, true), p);
5497
+ });
5498
+ async function bringDown(ref, p, compact) {
5421
5499
  const meta = await readMeta(ref, p);
5422
5500
  const cfg = await loadConfig(p);
5423
5501
  const m = p.machine(ref.owner, ref.name);
5424
5502
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
5425
5503
  await shutdown2(meta, cfg, p, 1e4);
5426
- await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
5504
+ if (compact) await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
5427
5505
  await rm7(m.hibernateDir, { recursive: true, force: true });
5428
5506
  await rm7(m.memBase, { force: true });
5429
5507
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
5430
5508
  await writeMachineMeta(stopped, p);
5431
5509
  recordState(stopped, "stopped", "stop", p);
5432
- return toMachine(stopped, p);
5433
- });
5510
+ return stopped;
5511
+ }
5434
5512
  async function destroyMachine(ref, p = paths()) {
5435
5513
  const gone = await destroyBox(ref, p);
5436
5514
  try {
@@ -6055,6 +6133,20 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
6055
6133
  return toMachine(running, p);
6056
6134
  });
6057
6135
 
6136
+ // src/core/machines/restart.ts
6137
+ var restartMachine = locked(async function restartMachine2(ref, p = paths(), force = false) {
6138
+ const meta = await readMeta(ref, p);
6139
+ if (vmAlive(meta) || isHibernated(meta, p)) {
6140
+ assertAssets(await loadConfig(p));
6141
+ await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
6142
+ await bringDown(ref, p, false);
6143
+ return startMachine(ref, p, force).catch((e) => {
6144
+ throw new KvboxError(`box ${shown(ref)} is stopped: it went down for the restart but could not boot again: ${e.message}`, e instanceof KvboxError ? e.exitCode : 1);
6145
+ });
6146
+ }
6147
+ return startMachine(ref, p, force);
6148
+ });
6149
+
6058
6150
  // src/core/machines/volumes.ts
6059
6151
  import { statSync as statSync5 } from "node:fs";
6060
6152
  import { rename as rename8, rm as rm13 } from "node:fs/promises";
@@ -7100,6 +7192,243 @@ function startIdleWatch(opts = {}) {
7100
7192
  };
7101
7193
  }
7102
7194
 
7195
+ // ../shared/src/resources.ts
7196
+ import { z as z9 } from "zod";
7197
+ var RESOURCE_SLOT_MS = 5 * 6e4;
7198
+ var RESOURCE_KEEP_DAYS = 7;
7199
+ var RESOURCE_KEEP_MS = RESOURCE_KEEP_DAYS * 864e5;
7200
+ var RESOURCE_SAMPLE_MS = 6e4;
7201
+ var emptyResources = (vcpu = 0) => ({
7202
+ vcpu,
7203
+ cpuMs: 0,
7204
+ wallMs: 0,
7205
+ cpuMaxPct: 0,
7206
+ memSamples: 0,
7207
+ memSumMib: 0,
7208
+ memMaxMib: 0,
7209
+ memTotalMib: null,
7210
+ diskUsedBytes: null,
7211
+ diskTotalBytes: null,
7212
+ netInBytes: 0,
7213
+ netOutBytes: 0
7214
+ });
7215
+ function cpuPct(cpuMs, wallMs, vcpu) {
7216
+ if (wallMs <= 0 || vcpu <= 0) return 0;
7217
+ return Math.min(100, Math.round(cpuMs / (wallMs * vcpu) * 1e3) / 10);
7218
+ }
7219
+ var whole = z9.number().int().nonnegative();
7220
+ var pct = z9.number().min(0).max(100);
7221
+ var small = whole.max(2 ** 31 - 1);
7222
+ var ResourceSlotRowSchema = z9.object({
7223
+ /** The host's box id. */
7224
+ boxId: z9.string(),
7225
+ owner: z9.string(),
7226
+ name: z9.string(),
7227
+ /** The slot's start, ms since the epoch. */
7228
+ slot: whole,
7229
+ vcpu: small,
7230
+ cpuMs: whole,
7231
+ wallMs: whole,
7232
+ cpuMaxPct: pct,
7233
+ memSamples: small,
7234
+ memSumMib: whole,
7235
+ memMaxMib: small,
7236
+ memTotalMib: small.nullable(),
7237
+ diskUsedBytes: whole.nullable(),
7238
+ diskTotalBytes: whole.nullable(),
7239
+ netInBytes: whole,
7240
+ netOutBytes: whole
7241
+ });
7242
+ var ResourceSlotsResponseSchema = z9.object({
7243
+ slots: z9.array(ResourceSlotRowSchema),
7244
+ next: whole
7245
+ });
7246
+ var ResourceSlotsPageSchema = z9.object({ slots: z9.array(z9.unknown()), next: whole });
7247
+ var figures = {
7248
+ /** Average and busiest minute, percent of the box's vCPUs; null when the CPU was not measured. */
7249
+ cpuPct: pct.nullable(),
7250
+ cpuMaxPct: pct.nullable(),
7251
+ /** Average and highest memory in use; null when the guest gave no answer (an image before base v0.7.0, or a guest that does not answer). */
7252
+ memUsedMib: whole.nullable(),
7253
+ memMaxMib: whole.nullable(),
7254
+ memTotalMib: whole.nullable(),
7255
+ /** The box's own disk as the guest last said. */
7256
+ diskUsedBytes: whole.nullable(),
7257
+ diskTotalBytes: whole.nullable(),
7258
+ netInBytes: whole,
7259
+ netOutBytes: whole
7260
+ };
7261
+ var ResourcePointSchema = z9.object({ at: z9.string(), ...figures });
7262
+ var ResourceReportSchema = z9.object({
7263
+ box: z9.string(),
7264
+ owner: z9.string(),
7265
+ since: z9.string(),
7266
+ until: z9.string(),
7267
+ stepMin: z9.number().int().positive(),
7268
+ /** The box's vCPUs as last measured; null without a row. */
7269
+ vcpu: whole.nullable(),
7270
+ totals: z9.object(figures),
7271
+ points: z9.array(ResourcePointSchema)
7272
+ });
7273
+
7274
+ // src/core/resourceSlots.ts
7275
+ var SWEEP_MS = 36e5;
7276
+ var sweptAt = /* @__PURE__ */ new Map();
7277
+ var fromRaw2 = (r) => ({
7278
+ boxId: r.box_id,
7279
+ owner: r.owner,
7280
+ name: r.name,
7281
+ slot: r.slot,
7282
+ vcpu: r.vcpu,
7283
+ cpuMs: r.cpu_ms,
7284
+ wallMs: r.wall_ms,
7285
+ cpuMaxPct: r.cpu_max_pct,
7286
+ memSamples: r.mem_samples,
7287
+ memSumMib: r.mem_sum_mib,
7288
+ memMaxMib: r.mem_max_mib,
7289
+ memTotalMib: r.mem_total_mib,
7290
+ diskUsedBytes: r.disk_used_bytes,
7291
+ diskTotalBytes: r.disk_total_bytes,
7292
+ netInBytes: r.net_in_bytes,
7293
+ netOutBytes: r.net_out_bytes
7294
+ });
7295
+ function insertResourceSlots(rows, now, p = paths()) {
7296
+ const db = openDb(p);
7297
+ if (rows.length > 0) {
7298
+ const insert = db.prepare(
7299
+ `insert or ignore into resource_slots
7300
+ (box_id, slot, owner, name, vcpu, cpu_ms, wall_ms, cpu_max_pct, mem_samples, mem_sum_mib, mem_max_mib, mem_total_mib, disk_used_bytes, disk_total_bytes, net_in_bytes, net_out_bytes)
7301
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
7302
+ );
7303
+ db.exec("begin");
7304
+ try {
7305
+ for (const r of rows) {
7306
+ insert.run(r.boxId, r.slot, r.owner, r.name, r.vcpu, r.cpuMs, r.wallMs, r.cpuMaxPct, r.memSamples, r.memSumMib, r.memMaxMib, r.memTotalMib, r.diskUsedBytes, r.diskTotalBytes, r.netInBytes, r.netOutBytes);
7307
+ }
7308
+ db.exec("commit");
7309
+ } catch (err) {
7310
+ db.exec("rollback");
7311
+ throw err;
7312
+ }
7313
+ }
7314
+ const swept = sweptAt.get(p.db);
7315
+ if (swept !== void 0 && now - swept < SWEEP_MS) return;
7316
+ sweptAt.set(p.db, now);
7317
+ db.prepare("delete from resource_slots where slot < ?").run(now - RESOURCE_KEEP_MS);
7318
+ }
7319
+ function resourceSlotsAfter(after, limit, scope, p = paths()) {
7320
+ const db = openDb(p);
7321
+ const where = scope === null ? "" : typeof scope === "string" ? "and owner = ?" : "and substr(owner, -length(?)) = ?";
7322
+ const args = scope === null ? [] : typeof scope === "string" ? [scope] : [`@${scope.realm}`, `@${scope.realm}`];
7323
+ const last = db.prepare(`select slot from resource_slots where slot > ? ${where} order by slot limit 1 offset ?`).get(after, ...args, Math.max(limit, 1) - 1);
7324
+ const rows = last === void 0 ? db.prepare(`select * from resource_slots where slot > ? ${where} order by slot, box_id`).all(after, ...args) : db.prepare(`select * from resource_slots where slot > ? and slot <= ? ${where} order by slot, box_id`).all(after, last.slot, ...args);
7325
+ return rows.map(fromRaw2);
7326
+ }
7327
+
7328
+ // src/core/resources.ts
7329
+ var GUEST_REPLY_MS = 3e3;
7330
+ var MAX_MIB = 2 ** 31 - 1;
7331
+ function believable(said) {
7332
+ const fits = (n, max) => Number.isSafeInteger(n) && n >= 0 && n <= max;
7333
+ return fits(said.memUsedMib, MAX_MIB) && fits(said.memTotalMib, MAX_MIB) && fits(said.diskUsedBytes, Number.MAX_SAFE_INTEGER) && fits(said.diskTotalBytes, Number.MAX_SAFE_INTEGER);
7334
+ }
7335
+ var RETRY_SLOTS = 12;
7336
+ function startResourceWatch(opts = {}) {
7337
+ const intervalMs = opts.intervalMs ?? RESOURCE_SAMPLE_MS;
7338
+ const p = opts.p ?? paths();
7339
+ const list = opts.list ?? (() => listMachines(null, p));
7340
+ const cpuMs = opts.cpuMs ?? ((pid) => driver().vm.cpuMs(pid));
7341
+ const bytes = opts.bytes ?? ((id) => driver().net.bytes(id));
7342
+ const guest = opts.guest ?? ((box) => stats(p.machine(box.owner, box.name).vsock, GUEST_REPLY_MS));
7343
+ const write = opts.write ?? ((rows, t) => insertResourceSlots(rows, t, p));
7344
+ const now = opts.now ?? Date.now;
7345
+ const log2 = opts.log ?? ((line) => log.info(line));
7346
+ const last = /* @__PURE__ */ new Map();
7347
+ const open4 = /* @__PURE__ */ new Map();
7348
+ let finished = [];
7349
+ let timer;
7350
+ let stopped = false;
7351
+ const measure = async (box) => {
7352
+ const at = now();
7353
+ const [cpu, net, answer2] = await Promise.all([cpuMs(box.pid), bytes(box.id), guest(box).catch(() => null)]);
7354
+ return { box, at, cpu, net, said: answer2 !== null && believable(answer2) ? answer2 : null };
7355
+ };
7356
+ const round2 = async () => {
7357
+ const running = (await list()).filter((box) => box.status === "running" && typeof box.pid === "number");
7358
+ const measured = await Promise.all(running.map(measure));
7359
+ const t = now();
7360
+ const slot = Math.floor(t / RESOURCE_SLOT_MS) * RESOURCE_SLOT_MS;
7361
+ const ended = /* @__PURE__ */ new Map();
7362
+ for (const [id, row] of open4) {
7363
+ if (row.slot >= slot) continue;
7364
+ ended.set(id, row);
7365
+ open4.delete(id);
7366
+ }
7367
+ const seen = /* @__PURE__ */ new Set();
7368
+ for (const { box, at, cpu, net, said } of measured) {
7369
+ seen.add(box.id);
7370
+ let row = open4.get(box.id);
7371
+ if (!row) open4.set(box.id, row = { boxId: box.id, owner: box.owner, name: box.name, slot, ...emptyResources(box.vcpu) });
7372
+ row.vcpu = box.vcpu;
7373
+ const before = last.get(box.id);
7374
+ if (before && before.pid === box.pid && at > before.at) {
7375
+ const span = at - before.at;
7376
+ const old = ended.get(box.id);
7377
+ const parts = [];
7378
+ if (old) parts.push([old, Math.max(0, Math.min(at, old.slot + RESOURCE_SLOT_MS) - before.at)]);
7379
+ const justBefore = !old && slot - before.at <= RESOURCE_SAMPLE_MS;
7380
+ parts.push([row, justBefore ? span : Math.max(0, at - Math.max(before.at, slot))]);
7381
+ const used = cpu !== null && before.cpuMs !== null && cpu >= before.cpuMs ? Math.round(cpu - before.cpuMs) : null;
7382
+ const moved = net !== null && before.net !== null && net.in >= before.net.in && net.out >= before.net.out ? { in: net.in - before.net.in, out: net.out - before.net.out } : null;
7383
+ for (const [into, ms] of parts) {
7384
+ if (ms <= 0) continue;
7385
+ const share = ms / span;
7386
+ if (used !== null) {
7387
+ into.cpuMs += Math.round(used * share);
7388
+ into.wallMs += ms;
7389
+ into.cpuMaxPct = Math.max(into.cpuMaxPct, cpuPct(used, span, box.vcpu));
7390
+ }
7391
+ if (moved !== null) {
7392
+ into.netInBytes += Math.round(moved.in * share);
7393
+ into.netOutBytes += Math.round(moved.out * share);
7394
+ }
7395
+ }
7396
+ }
7397
+ if (said !== null) {
7398
+ row.memSamples += 1;
7399
+ row.memSumMib += said.memUsedMib;
7400
+ row.memMaxMib = Math.max(row.memMaxMib, said.memUsedMib);
7401
+ row.memTotalMib = said.memTotalMib;
7402
+ row.diskUsedBytes = said.diskUsedBytes;
7403
+ row.diskTotalBytes = said.diskTotalBytes;
7404
+ }
7405
+ last.set(box.id, { pid: box.pid, at, cpuMs: cpu, net });
7406
+ }
7407
+ for (const id of last.keys()) if (!seen.has(id)) last.delete(id);
7408
+ finished.push(...ended.values());
7409
+ try {
7410
+ write(finished, t);
7411
+ finished = [];
7412
+ } catch (err) {
7413
+ log2(`warning: ${finished.length} resource row(s) not written, trying again next round: ${err.message}`);
7414
+ finished = finished.filter((row) => row.slot >= slot - RETRY_SLOTS * RESOURCE_SLOT_MS);
7415
+ }
7416
+ };
7417
+ const schedule = () => {
7418
+ if (stopped) return;
7419
+ timer = setTimeout(() => void round2().catch((err) => log2(`warning: resource watch: ${err.message}`)).finally(schedule), intervalMs);
7420
+ timer.unref();
7421
+ };
7422
+ schedule();
7423
+ return {
7424
+ stop: () => {
7425
+ stopped = true;
7426
+ clearTimeout(timer);
7427
+ },
7428
+ round: round2
7429
+ };
7430
+ }
7431
+
7103
7432
  // src/core/relayWatch.ts
7104
7433
  var report = { restarts: 0, lastRestartAt: null };
7105
7434
  function relayWatchReport() {
@@ -7431,7 +7760,7 @@ import { createServer as createHttpsServer } from "node:https";
7431
7760
  import { createAdaptorServer } from "@hono/node-server";
7432
7761
 
7433
7762
  // src/app.ts
7434
- import { Hono as Hono12 } from "hono";
7763
+ import { Hono as Hono13 } from "hono";
7435
7764
 
7436
7765
  // ../shared/src/version.ts
7437
7766
  import { createRequire } from "node:module";
@@ -7446,7 +7775,7 @@ function versionOf(srcFileUrl, injected) {
7446
7775
  }
7447
7776
 
7448
7777
  // src/version.ts
7449
- var VERSION = versionOf(import.meta.url, true ? "0.6.18" : void 0);
7778
+ var VERSION = versionOf(import.meta.url, true ? "0.6.20" : void 0);
7450
7779
 
7451
7780
  // src/caller.ts
7452
7781
  import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
@@ -7927,6 +8256,10 @@ function machineRoutes() {
7927
8256
  const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
7928
8257
  return c.json(await startMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
7929
8258
  });
8259
+ r.post("/:name/restart", async (c) => {
8260
+ const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
8261
+ return c.json(await restartMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
8262
+ });
7930
8263
  r.post("/:name/pause", async (c) => c.json(await pauseMachine(parseRef(c.req.param("name"), c.get("owner")))));
7931
8264
  r.post("/:name/resume", async (c) => c.json(await resumeMachine(parseRef(c.req.param("name"), c.get("owner")))));
7932
8265
  r.post("/:name/hibernate", async (c) => c.json(await hibernateMachine(parseRef(c.req.param("name"), c.get("owner")))));
@@ -8023,7 +8356,7 @@ function machineRoutes() {
8023
8356
 
8024
8357
  // src/routes/runs.ts
8025
8358
  import { Hono as Hono7 } from "hono";
8026
- import { z as z9 } from "zod";
8359
+ import { z as z10 } from "zod";
8027
8360
  var refusal3 = (c, err) => {
8028
8361
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
8029
8362
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
@@ -8031,10 +8364,10 @@ var refusal3 = (c, err) => {
8031
8364
  if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
8032
8365
  throw err;
8033
8366
  };
8034
- var OutputQuery = z9.object({
8035
- stream: z9.enum(RUN_STREAMS).default("stdout"),
8036
- offset: z9.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
8037
- limit: z9.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
8367
+ var OutputQuery = z10.object({
8368
+ stream: z10.enum(RUN_STREAMS).default("stdout"),
8369
+ offset: z10.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
8370
+ limit: z10.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
8038
8371
  });
8039
8372
  function runRoutes(wake = wakeBox) {
8040
8373
  const r = new Hono7();
@@ -8105,11 +8438,32 @@ function sshRoutes(opts = {}) {
8105
8438
  return r;
8106
8439
  }
8107
8440
 
8108
- // src/routes/usage.ts
8441
+ // src/routes/resources.ts
8109
8442
  import { Hono as Hono10 } from "hono";
8110
8443
  var PULL_LIMIT = 1e3;
8111
- function usageRoutes(opts = {}) {
8444
+ function resourceRoutes(opts = {}) {
8112
8445
  const r = new Hono10();
8446
+ r.get("/slots", (c) => {
8447
+ const after = whole2(c.req.query("after") ?? "0", "after");
8448
+ const limit = Math.min(whole2(c.req.query("limit") ?? String(PULL_LIMIT), "limit") || PULL_LIMIT, PULL_LIMIT);
8449
+ const scope = opts.controlPlane === void 0 ? null : c.get("listScope");
8450
+ const slots = resourceSlotsAfter(after, limit, scope);
8451
+ const body = { slots, next: slots.length === 0 ? after : slots[slots.length - 1].slot };
8452
+ return c.json(body);
8453
+ });
8454
+ return r;
8455
+ }
8456
+ function whole2(value, name) {
8457
+ const n = Number(value);
8458
+ if (!Number.isInteger(n) || n < 0) throw new KvboxError(`${name}: expected a whole number, got "${value}"`);
8459
+ return n;
8460
+ }
8461
+
8462
+ // src/routes/usage.ts
8463
+ import { Hono as Hono11 } from "hono";
8464
+ var PULL_LIMIT2 = 1e3;
8465
+ function usageRoutes(opts = {}) {
8466
+ const r = new Hono11();
8113
8467
  r.get("/", async (c) => {
8114
8468
  let window;
8115
8469
  try {
@@ -8120,31 +8474,31 @@ function usageRoutes(opts = {}) {
8120
8474
  return c.json(await usageReport(c.get("listScope"), window));
8121
8475
  });
8122
8476
  r.get("/events", async (c) => {
8123
- const after = whole(c.req.query("after") ?? "0", "after");
8124
- const limit = Math.min(whole(c.req.query("limit") ?? String(PULL_LIMIT), "limit") || PULL_LIMIT, PULL_LIMIT);
8477
+ const after = whole3(c.req.query("after") ?? "0", "after");
8478
+ const limit = Math.min(whole3(c.req.query("limit") ?? String(PULL_LIMIT2), "limit") || PULL_LIMIT2, PULL_LIMIT2);
8125
8479
  const scope = opts.controlPlane === void 0 ? null : c.get("listScope");
8126
8480
  const events = usageEventsAfter(after, limit, scope);
8127
8481
  return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1].id });
8128
8482
  });
8129
8483
  r.get("/volume-events", async (c) => {
8130
- const after = whole(c.req.query("after") ?? "0", "after");
8131
- const limit = Math.min(whole(c.req.query("limit") ?? String(PULL_LIMIT), "limit") || PULL_LIMIT, PULL_LIMIT);
8484
+ const after = whole3(c.req.query("after") ?? "0", "after");
8485
+ const limit = Math.min(whole3(c.req.query("limit") ?? String(PULL_LIMIT2), "limit") || PULL_LIMIT2, PULL_LIMIT2);
8132
8486
  const scope = opts.controlPlane === void 0 ? null : c.get("listScope");
8133
8487
  const events = volumeEventsAfter(after, limit, scope);
8134
8488
  return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1].id });
8135
8489
  });
8136
8490
  return r;
8137
8491
  }
8138
- function whole(value, name) {
8492
+ function whole3(value, name) {
8139
8493
  const n = Number(value);
8140
8494
  if (!Number.isInteger(n) || n < 0) throw new KvboxError(`${name}: expected a whole number, got "${value}"`);
8141
8495
  return n;
8142
8496
  }
8143
8497
 
8144
8498
  // src/routes/volumes.ts
8145
- import { Hono as Hono11 } from "hono";
8499
+ import { Hono as Hono12 } from "hono";
8146
8500
  function volumeRoutes() {
8147
- const r = new Hono11();
8501
+ const r = new Hono12();
8148
8502
  r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
8149
8503
  r.post("/", async (c) => {
8150
8504
  const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
@@ -8174,7 +8528,7 @@ function volumeRoutes() {
8174
8528
 
8175
8529
  // src/app.ts
8176
8530
  function createApp(opts = {}) {
8177
- const app = new Hono12();
8531
+ const app = new Hono13();
8178
8532
  app.use(resolveCaller(opts));
8179
8533
  app.get("/health", async (c) => {
8180
8534
  const cfg = await loadConfig();
@@ -8207,6 +8561,7 @@ function createApp(opts = {}) {
8207
8561
  app.route("/ssh", sshRoutes(opts));
8208
8562
  app.route("/backup-store", backupStoreRoutes(opts));
8209
8563
  app.route("/usage", usageRoutes(opts));
8564
+ app.route("/resources", resourceRoutes(opts));
8210
8565
  app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
8211
8566
  app.onError((err, c) => {
8212
8567
  if (err instanceof NotFoundError) return c.json({ error: err.message }, 404);
@@ -8449,6 +8804,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
8449
8804
  bindDns();
8450
8805
  startRelayWatch();
8451
8806
  startIdleWatch();
8807
+ startResourceWatch();
8452
8808
  startBackupStoreWatch();
8453
8809
  const recovery2 = await bootRecovered(settled, paths());
8454
8810
  if (recovery2) {
@@ -8624,7 +8980,7 @@ import { Command as Command11 } from "commander";
8624
8980
 
8625
8981
  // src/core/realm.ts
8626
8982
  import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as rm17, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
8627
- import { z as z10 } from "zod";
8983
+ import { z as z11 } from "zod";
8628
8984
  var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8629
8985
  async function ownersIn(root, from, suffix = "") {
8630
8986
  const entries = await readdir7(root).catch((err) => {
@@ -8690,7 +9046,7 @@ async function plan(from, to, p) {
8690
9046
  for (const oldOwner of await ownersIn(p.volumes, from)) {
8691
9047
  await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
8692
9048
  for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
8693
- const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z10.string().optional() }), `volume ${oldOwner}/${name}`);
9049
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z11.string().optional() }), `volume ${oldOwner}/${name}`);
8694
9050
  out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
8695
9051
  }
8696
9052
  }