@kvbox/server 0.5.32 → 0.5.34

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.
@@ -546,6 +546,8 @@ var MachineSchema = z3.object({
546
546
  ownerKind: z3.enum(["user", "org"]).optional(),
547
547
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
548
548
  autoHibernateSec: z3.number().int().positive().optional(),
549
+ /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
550
+ idleCheck: z3.string().optional(),
549
551
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
550
552
  volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
551
553
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
@@ -667,7 +669,9 @@ var RescaleMachineRequest = z3.object({
667
669
  });
668
670
  var SetMachineRequest = z3.object({
669
671
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
670
- autoHibernateSec: z3.number().int().min(0).optional()
672
+ autoHibernateSec: z3.number().int().min(0).optional(),
673
+ /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
674
+ idleCheck: z3.union([z3.literal(""), z3.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
671
675
  });
672
676
  var SnapshotSchema = z3.object({
673
677
  name: z3.string(),
@@ -1436,6 +1440,12 @@ var MachineMetaSchema = z4.object({
1436
1440
  ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1437
1441
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1438
1442
  autoHibernateSec: z4.number().int().positive().optional(),
1443
+ /**
1444
+ * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
1445
+ * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
1446
+ * changes it. The one place the host looks. Absent: the traffic rule.
1447
+ */
1448
+ idleCheck: z4.string().optional(),
1439
1449
  /**
1440
1450
  * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1441
1451
  * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
@@ -1713,6 +1723,16 @@ import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSyn
1713
1723
  import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1714
1724
  import { setTimeout as sleep } from "node:timers/promises";
1715
1725
 
1726
+ // ../shared/src/duration.ts
1727
+ var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1728
+ function parseDuration(text) {
1729
+ const t = text.trim().toLowerCase();
1730
+ if (!/^(\d+[mhd])+$/.test(t)) return void 0;
1731
+ let sec = 0;
1732
+ for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
1733
+ return sec;
1734
+ }
1735
+
1716
1736
  // src/core/agent.ts
1717
1737
  import { connect } from "node:net";
1718
1738
  var AGENT_PORT = 52;
@@ -1777,6 +1797,9 @@ async function dropVolumes(udsPath, timeoutMs) {
1777
1797
  function setEnv(udsPath, vars, timeoutMs) {
1778
1798
  return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1779
1799
  }
1800
+ async function idle(udsPath, script, timeoutMs = 15e3) {
1801
+ return (await agentCall(udsPath, { op: "idle", path: script }, timeoutMs))["idle"] === true;
1802
+ }
1780
1803
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1781
1804
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1782
1805
  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 ?? "");
@@ -2036,8 +2059,16 @@ async function assertOverlayCapable(file, image, version) {
2036
2059
  if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);
2037
2060
  }
2038
2061
  var ImageManifestSchema = z6.object({
2039
- /** false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection). */
2040
- autoHibernate: z6.boolean().optional(),
2062
+ /**
2063
+ * false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection).
2064
+ * A duration (`"10m"`, #102): a new box's idle time unless the caller gave one, instead of the host's default.
2065
+ */
2066
+ autoHibernate: z6.union([z6.boolean(), z6.string().refine((s) => parseDuration(s) !== void 0, "a duration like 10m, 4h or 1d")]).optional(),
2067
+ /**
2068
+ * A script inside the box that says whether it is idle (#102), exit 0 = idle: a new box's `idleCheck`
2069
+ * (meta.json), which auto-hibernate asks through kvbox-agent instead of watching the traffic.
2070
+ */
2071
+ idle: z6.string().optional(),
2041
2072
  /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */
2042
2073
  env: z6.record(z6.string(), z6.string()).optional(),
2043
2074
  /** Variables the host fills with a random password when the caller gave none. */
@@ -2905,14 +2936,17 @@ function toMachine(meta, p = paths()) {
2905
2936
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
2906
2937
  ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
2907
2938
  ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
2939
+ ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
2908
2940
  ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
2909
2941
  ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
2910
2942
  };
2911
2943
  }
2912
2944
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2913
2945
  function autoHibernateFor(req, cfg, manifest = {}) {
2914
- if (req.autoHibernateSec === void 0 && manifest.autoHibernate === false) return void 0;
2915
- return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2946
+ if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
2947
+ if (manifest.autoHibernate === false) return void 0;
2948
+ if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
2949
+ return cfg.autoHibernateSec || void 0;
2916
2950
  }
2917
2951
  async function readAllMeta(p) {
2918
2952
  const metas = [];
@@ -3109,7 +3143,7 @@ async function createMachine(req, owner, p = paths()) {
3109
3143
  await createOverlay(m.overlay, size.diskGib);
3110
3144
  if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
3111
3145
  },
3112
- { source: "base", autoHibernateSec, url: maskedUrl(manifest, vars) },
3146
+ { source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
3113
3147
  cfg,
3114
3148
  p
3115
3149
  );
@@ -3199,7 +3233,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
3199
3233
  await placeholderDrives(m.dir, snap.volumes ?? []);
3200
3234
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
3201
3235
  },
3202
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), url: maskedUrl(manifest, vars) },
3236
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
3203
3237
  cfg,
3204
3238
  p
3205
3239
  );
@@ -3278,7 +3312,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3278
3312
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
3279
3313
  const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };
3280
3314
  const srcEnv = p.machine(src.owner, src.name).env;
3281
- const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, url: src.url };
3315
+ const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url };
3282
3316
  if (!warm) {
3283
3317
  return bootInto(
3284
3318
  box,
@@ -3696,6 +3730,7 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
3696
3730
  const meta = await readMeta(ref, p);
3697
3731
  const next = { ...meta };
3698
3732
  if (req.autoHibernateSec !== void 0) next.autoHibernateSec = req.autoHibernateSec || void 0;
3733
+ if (req.idleCheck !== void 0) next.idleCheck = req.idleCheck || void 0;
3699
3734
  await writeMachineMeta(next, p);
3700
3735
  return toMachine(next, p);
3701
3736
  });
@@ -4023,6 +4058,10 @@ async function tapTraffic(id) {
4023
4058
  return null;
4024
4059
  }
4025
4060
  }
4061
+ async function boxIdle(box, p) {
4062
+ if (box.idleCheck === void 0) return null;
4063
+ return idle(p.machine(box.owner, box.name).vsock, box.idleCheck);
4064
+ }
4026
4065
  async function hibernateIfRunning(box, p) {
4027
4066
  const ref = { owner: box.owner, name: box.name };
4028
4067
  return withBoxLock(ref, async () => {
@@ -4036,41 +4075,55 @@ function startIdleWatch(opts = {}) {
4036
4075
  const p = opts.p ?? paths();
4037
4076
  const list = opts.list ?? (() => listMachines(null, p));
4038
4077
  const traffic = opts.traffic ?? tapTraffic;
4078
+ const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
4039
4079
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
4040
4080
  const busy = opts.busy ?? ((box) => boxBusy(box));
4041
4081
  const now = opts.now ?? Date.now;
4042
4082
  const log = opts.log ?? ((line) => console.log(line));
4043
4083
  const seen = /* @__PURE__ */ new Map();
4084
+ const checkErrors = /* @__PURE__ */ new Map();
4044
4085
  let timer;
4045
4086
  let stopped = false;
4046
4087
  const inflight = /* @__PURE__ */ new Set();
4047
4088
  const hibernateOne = async (box, quiet, bytes, t) => {
4048
4089
  inflight.add(box.id);
4090
+ const byImage = bytes < 0;
4049
4091
  try {
4050
- if (await hibernate(box)) log(`box ${box.owner}/${box.name}: no network traffic for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4092
+ if (await hibernate(box)) log(`box ${box.owner}/${box.name}: ${byImage ? "idle by its own check" : "no network traffic"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4051
4093
  seen.delete(box.id);
4052
4094
  } catch (err) {
4053
- log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min without traffic: ${err.message}`);
4095
+ log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? "idle" : "without traffic"}: ${err.message}`);
4054
4096
  seen.set(box.id, { bytes, since: t });
4055
4097
  } finally {
4056
4098
  inflight.delete(box.id);
4057
4099
  }
4058
4100
  };
4101
+ const askIdle = (box) => guestIdle(box).then(
4102
+ (v) => (checkErrors.delete(box.id), v),
4103
+ (err) => {
4104
+ if (checkErrors.get(box.id) !== err.message) log(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? ""} failed, so it counts as busy and does not hibernate: ${err.message}`);
4105
+ checkErrors.set(box.id, err.message);
4106
+ return false;
4107
+ }
4108
+ );
4059
4109
  const check = async () => {
4060
4110
  const started = [];
4061
4111
  const watched = /* @__PURE__ */ new Set();
4112
+ const due = [];
4062
4113
  for (const box of await list()) {
4063
4114
  if (!box.autoHibernateSec || box.status !== "running" || box.links?.length) continue;
4064
- if (inflight.has(box.id)) {
4065
- watched.add(box.id);
4066
- continue;
4067
- }
4068
- const bytes = await traffic(box.id);
4115
+ if (inflight.has(box.id)) watched.add(box.id);
4116
+ else due.push(box);
4117
+ }
4118
+ const verdicts = await Promise.all(due.map(askIdle));
4119
+ for (const [i, box] of due.entries()) {
4120
+ const verdict = verdicts[i] ?? null;
4121
+ const bytes = verdict === null ? await traffic(box.id) : -1;
4069
4122
  if (bytes === null) continue;
4070
4123
  watched.add(box.id);
4071
4124
  const t = now();
4072
4125
  const last = seen.get(box.id);
4073
- if (!last || last.bytes !== bytes || busy(box)) {
4126
+ if (!last || last.bytes !== bytes || verdict === false || busy(box)) {
4074
4127
  seen.set(box.id, { bytes, since: t });
4075
4128
  continue;
4076
4129
  }
@@ -4079,6 +4132,7 @@ function startIdleWatch(opts = {}) {
4079
4132
  started.push(hibernateOne(box, Math.round((t - last.since) / 6e4), bytes, t));
4080
4133
  }
4081
4134
  for (const id of seen.keys()) if (!watched.has(id)) seen.delete(id);
4135
+ for (const id of checkErrors.keys()) if (!watched.has(id)) checkErrors.delete(id);
4082
4136
  return started;
4083
4137
  };
4084
4138
  const round2 = async () => {
@@ -4180,7 +4234,7 @@ function versionOf(srcFileUrl, injected) {
4180
4234
  }
4181
4235
 
4182
4236
  // src/version.ts
4183
- var VERSION = versionOf(import.meta.url, true ? "0.5.32" : void 0);
4237
+ var VERSION = versionOf(import.meta.url, true ? "0.5.34" : void 0);
4184
4238
 
4185
4239
  // src/caller.ts
4186
4240
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";