@kvbox/server 0.6.19 → 0.6.21

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.
@@ -1332,6 +1332,12 @@ var MachineMetaSchema = z3.object({
1332
1332
  vcpu: z3.number().int(),
1333
1333
  memMib: z3.number().int(),
1334
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(),
1335
1341
  source: z3.string(),
1336
1342
  /** Version of the image the box's overlay stacks on: assets/rootfs-<version>.ext4 for the base one. */
1337
1343
  base: z3.string(),
@@ -2070,6 +2076,7 @@ var WakeHookSchema = z6.object({
2070
2076
  createdAt: z6.string(),
2071
2077
  lastCalledAt: z6.string().nullable()
2072
2078
  });
2079
+ var WakeHookListSchema = z6.array(WakeHookSchema);
2073
2080
  var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z6.string() });
2074
2081
  var WakeHookCallSchema = z6.object({
2075
2082
  box: z6.string(),
@@ -2280,6 +2287,13 @@ var MachineSchema = z6.object({
2280
2287
  */
2281
2288
  latestBase: z6.string().optional(),
2282
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(),
2283
2297
  source: z6.string(),
2284
2298
  // "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
2285
2299
  status: BoxStatusSchema,
@@ -2344,7 +2358,9 @@ var VolumeSchema = z6.object({
2344
2358
  /** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
2345
2359
  ownerKind: z6.enum(["user", "org"]).optional(),
2346
2360
  /** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
2347
- 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()
2348
2364
  });
2349
2365
  var MAX_VOLUME_GIB = 4096;
2350
2366
  var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
@@ -2615,6 +2631,7 @@ var LatestImagesSchema = z6.object({
2615
2631
  images: ImageIndexSchema.shape.images,
2616
2632
  checkedAt: z6.string().nullable()
2617
2633
  });
2634
+ var LatestServerSchema = z6.object({ version: z6.string().nullable(), checkedAt: z6.string().nullable() });
2618
2635
  var RecoveryReportSchema = z6.object({
2619
2636
  at: z6.string(),
2620
2637
  booted: z6.array(z6.string()),
@@ -2894,6 +2911,18 @@ var BalanceSchema = z6.object({
2894
2911
  balance: z6.number(),
2895
2912
  currency: z6.string(),
2896
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),
2897
2926
  spent: z6.number(),
2898
2927
  /** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
2899
2928
  since: z6.string().nullable(),
@@ -4060,7 +4089,7 @@ import { setTimeout as sleep3 } from "node:timers/promises";
4060
4089
  // src/core/agent.ts
4061
4090
  import { connect } from "node:net";
4062
4091
  var AGENT_PORT = 52;
4063
- async function agentCall(udsPath, req, timeoutMs = 5e3) {
4092
+ async function agentCall(udsPath, req, timeoutMs = 5e3, connectMs = timeoutMs) {
4064
4093
  const reply = await new Promise((resolve3, reject) => {
4065
4094
  const sock = connect(udsPath);
4066
4095
  let buf = "";
@@ -4069,7 +4098,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
4069
4098
  sock.destroy();
4070
4099
  reject(err);
4071
4100
  };
4072
- sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));
4101
+ sock.setTimeout(connectMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${connectMs} ms`)));
4073
4102
  sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
4074
4103
  sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
4075
4104
  `));
@@ -4082,6 +4111,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
4082
4111
  if (!handshaken) {
4083
4112
  if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
4084
4113
  handshaken = true;
4114
+ sock.setTimeout(timeoutMs);
4085
4115
  sock.write(JSON.stringify(req) + "\n");
4086
4116
  } else {
4087
4117
  sock.end();
@@ -4152,6 +4182,19 @@ async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
4152
4182
  if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
4153
4183
  return { size: size2, offset, data };
4154
4184
  }
4185
+ var FREEZE_BASE = "v0.19.0";
4186
+ var FREEZE_TIMEOUT_MS = 2e4;
4187
+ var FREEZE_CONNECT_MS = 3e3;
4188
+ var isAgentRefusal = (err) => /^kvbox-agent: /.test(err.message ?? "");
4189
+ async function freezeDisks(udsPath, disks, thawAfterSec, timeoutMs = FREEZE_TIMEOUT_MS) {
4190
+ const reply = await agentCall(udsPath, { op: "freeze", box: disks.box === true, volumes: [...disks.volumes ?? []], thawAfterSec }, timeoutMs, FREEZE_CONNECT_MS);
4191
+ const frozen = reply["frozen"];
4192
+ return Array.isArray(frozen) ? frozen.filter((m) => typeof m === "string") : [];
4193
+ }
4194
+ async function thawDisks(udsPath, timeoutMs) {
4195
+ const thawed = (await agentCall(udsPath, { op: "thaw" }, timeoutMs))["thawed"];
4196
+ return Array.isArray(thawed) ? thawed.filter((m) => typeof m === "string") : [];
4197
+ }
4155
4198
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
4156
4199
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
4157
4200
  var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
@@ -4493,6 +4536,7 @@ function toMachine(meta, p = paths()) {
4493
4536
  ...meta.image !== void 0 ? { image: meta.image } : {},
4494
4537
  ...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
4495
4538
  createdAt: meta.createdAt,
4539
+ ...meta.bootedAt !== void 0 ? { bootedAt: meta.bootedAt } : {},
4496
4540
  source: meta.source,
4497
4541
  status: statusOf(meta, p),
4498
4542
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
@@ -5175,10 +5219,11 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
5175
5219
  const tap = await driver().net.create(meta, cfg);
5176
5220
  let pid;
5177
5221
  try {
5222
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5178
5223
  pid = await launch(meta, tap, cfg, keysB64, p);
5179
5224
  await openPorts(meta, cfg, p);
5180
5225
  void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
5181
- const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
5226
+ const started = { ...meta, pid, bootId: currentBootId(), bootedAt, sshKeysStale: void 0, paused: void 0 };
5182
5227
  await writeMachineMeta(started, p);
5183
5228
  recordState(started, "running", "start", p);
5184
5229
  void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
@@ -5239,10 +5284,11 @@ async function bootInto(box, prepare, origin, cfg, p) {
5239
5284
  const tap = await driver().net.create(box, cfg);
5240
5285
  tapCreated = true;
5241
5286
  const spec = { ...box, sshPort };
5287
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5242
5288
  pid = await launch(spec, tap, cfg, keysB64, p);
5243
5289
  await openPorts(spec, cfg, p);
5244
5290
  void pushEnvAfterBoot(spec, pid, m.vsock, p);
5245
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
5291
+ const meta = { ...spec, pid, bootId: currentBootId(), bootedAt, createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
5246
5292
  await writeMachineMeta(meta, p);
5247
5293
  recordState(meta, "running", "new", p, meta.createdAt);
5248
5294
  void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
@@ -5284,10 +5330,11 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
5284
5330
  const stale = await pushAuthorizedKeys(box, m.vsock, p);
5285
5331
  if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
5286
5332
  if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
5333
+ const bootedAt = (/* @__PURE__ */ new Date()).toISOString();
5287
5334
  await pushEnv(box, m.vsock, p);
5288
5335
  await driver().net.attach(box, cfg);
5289
5336
  await openPorts(spec, cfg, p);
5290
- const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
5337
+ const meta = { ...spec, pid, bootId: currentBootId(), bootedAt, createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
5291
5338
  await writeMachineMeta(meta, p);
5292
5339
  recordState(meta, "running", "new", p, meta.createdAt);
5293
5340
  void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
@@ -5460,19 +5507,22 @@ async function cleanupProcess(meta, cfg, p) {
5460
5507
  }
5461
5508
  }
5462
5509
  var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
5510
+ return toMachine(await bringDown(ref, p, true), p);
5511
+ });
5512
+ async function bringDown(ref, p, compact) {
5463
5513
  const meta = await readMeta(ref, p);
5464
5514
  const cfg = await loadConfig(p);
5465
5515
  const m = p.machine(ref.owner, ref.name);
5466
5516
  if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
5467
5517
  await shutdown2(meta, cfg, p, 1e4);
5468
- await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
5518
+ if (compact) await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
5469
5519
  await rm7(m.hibernateDir, { recursive: true, force: true });
5470
5520
  await rm7(m.memBase, { force: true });
5471
5521
  const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
5472
5522
  await writeMachineMeta(stopped, p);
5473
5523
  recordState(stopped, "stopped", "stop", p);
5474
- return toMachine(stopped, p);
5475
- });
5524
+ return stopped;
5525
+ }
5476
5526
  async function destroyMachine(ref, p = paths()) {
5477
5527
  const gone = await destroyBox(ref, p);
5478
5528
  try {
@@ -6097,6 +6147,20 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
6097
6147
  return toMachine(running, p);
6098
6148
  });
6099
6149
 
6150
+ // src/core/machines/restart.ts
6151
+ var restartMachine = locked(async function restartMachine2(ref, p = paths(), force = false) {
6152
+ const meta = await readMeta(ref, p);
6153
+ if (vmAlive(meta) || isHibernated(meta, p)) {
6154
+ assertAssets(await loadConfig(p));
6155
+ await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
6156
+ await bringDown(ref, p, false);
6157
+ return startMachine(ref, p, force).catch((e) => {
6158
+ 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);
6159
+ });
6160
+ }
6161
+ return startMachine(ref, p, force);
6162
+ });
6163
+
6100
6164
  // src/core/machines/volumes.ts
6101
6165
  import { statSync as statSync5 } from "node:fs";
6102
6166
  import { rename as rename8, rm as rm13 } from "node:fs/promises";
@@ -6357,7 +6421,7 @@ async function stageBackup(ref, req, p = paths()) {
6357
6421
  const meta2 = await readBox2(ref, p);
6358
6422
  const m = p.machine(meta2.owner, meta2.name);
6359
6423
  await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);
6360
- await frozenClone(meta2, m.overlay, s.disk, p);
6424
+ await frozenClone(meta2, m.overlay, s.disk, { box: true }, p);
6361
6425
  const envText2 = existsSync13(m.env) ? await readFile9(m.env, "utf8") : null;
6362
6426
  return { meta: meta2, envText: envText2 };
6363
6427
  });
@@ -6379,13 +6443,33 @@ async function stageBackup(ref, req, p = paths()) {
6379
6443
  throw err;
6380
6444
  }
6381
6445
  }
6382
- async function frozenClone(box, from, to, p) {
6446
+ var THAW_AFTER_SEC = 30;
6447
+ async function frozenClone(box, from, to, disks, p) {
6383
6448
  if (!vmAlive(box) || box.paused) return driver().disk.clone(from, to);
6384
- await driver().vm.pause(box, p);
6449
+ const vsock = p.machine(box.owner, box.name).vsock;
6450
+ const freeze = await freezeForCopy(box, vsock, disks);
6385
6451
  try {
6386
- await driver().disk.clone(from, to);
6452
+ await driver().vm.pause(box, p);
6453
+ try {
6454
+ await driver().disk.clone(from, to);
6455
+ } finally {
6456
+ await resumeAfterCopy(box, p);
6457
+ }
6387
6458
  } finally {
6388
- await resumeAfterCopy(box, p);
6459
+ if (freeze !== "none") await thawDisks(vsock, freeze === "unsure" ? FREEZE_TIMEOUT_MS + 5e3 : void 0).catch((err) => log.warn(`box ${shown(box)}: thaw after a backup's copy failed (${err.message}); its guest thaws by itself within ${THAW_AFTER_SEC} s`));
6460
+ }
6461
+ }
6462
+ async function freezeForCopy(box, vsock, disks) {
6463
+ try {
6464
+ return (await freezeDisks(vsock, disks, THAW_AFTER_SEC)).length > 0 ? "frozen" : "none";
6465
+ } catch (err) {
6466
+ if (isUnknownOp(err)) {
6467
+ log.debug(`box ${shown(box)}: its image is from before base ${FREEZE_BASE}, which cannot freeze a disk; copied as it is`);
6468
+ return "none";
6469
+ }
6470
+ if (isNoAgent(err)) return "none";
6471
+ log.warn(`box ${shown(box)}: its disk was not frozen for a backup's copy (${err.message}); copied as it is`);
6472
+ return isAgentRefusal(err) ? "none" : "unsure";
6389
6473
  }
6390
6474
  }
6391
6475
  async function stageVolumeBackup(ref, req, p = paths()) {
@@ -6410,7 +6494,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
6410
6494
  await withBoxLock(box, async () => {
6411
6495
  const meta = await readBox2(box, p);
6412
6496
  if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);
6413
- await frozenClone(meta, from, s.disk, p);
6497
+ await frozenClone(meta, from, s.disk, { volumes: [ref.name] }, p);
6414
6498
  });
6415
6499
  }
6416
6500
  const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
@@ -7725,7 +7809,7 @@ function versionOf(srcFileUrl, injected) {
7725
7809
  }
7726
7810
 
7727
7811
  // src/version.ts
7728
- var VERSION = versionOf(import.meta.url, true ? "0.6.19" : void 0);
7812
+ var VERSION = versionOf(import.meta.url, true ? "0.6.21" : void 0);
7729
7813
 
7730
7814
  // src/caller.ts
7731
7815
  import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
@@ -8206,6 +8290,10 @@ function machineRoutes() {
8206
8290
  const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
8207
8291
  return c.json(await startMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
8208
8292
  });
8293
+ r.post("/:name/restart", async (c) => {
8294
+ const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
8295
+ return c.json(await restartMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
8296
+ });
8209
8297
  r.post("/:name/pause", async (c) => c.json(await pauseMachine(parseRef(c.req.param("name"), c.get("owner")))));
8210
8298
  r.post("/:name/resume", async (c) => c.json(await resumeMachine(parseRef(c.req.param("name"), c.get("owner")))));
8211
8299
  r.post("/:name/hibernate", async (c) => c.json(await hibernateMachine(parseRef(c.req.param("name"), c.get("owner")))));