@kvbox/cli 0.6.2 → 0.6.3

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/dist/kvbox.js CHANGED
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
164
164
  }
165
165
 
166
166
  // src/version.ts
167
- var VERSION = versionOf(import.meta.url, true ? "0.6.2" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.6.3" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command37 } from "commander";
@@ -767,6 +767,28 @@ var ResizeVolumeRequest = z2.object({
767
767
  });
768
768
  var RunScriptRequest = z2.object({ input: z2.unknown().optional() });
769
769
  var ScriptOutputSchema = z2.object({ output: z2.unknown() });
770
+ var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
771
+ var StartRunRequest = z2.object({
772
+ id: z2.string().regex(BOX_RUN_ID_RE),
773
+ command: z2.string().min(1).max(8192),
774
+ /** The command and everything it started are killed after this long. */
775
+ timeoutSec: z2.number().int().min(1).max(86400)
776
+ });
777
+ var StartRunAnswerSchema = z2.object({
778
+ id: z2.string(),
779
+ /** False: a run of this id was already there. */
780
+ started: z2.boolean(),
781
+ /** The box was asleep and this request woke it. */
782
+ woke: z2.boolean()
783
+ });
784
+ var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
785
+ var BoxRunSchema = z2.object({
786
+ id: z2.string(),
787
+ state: z2.enum(BOX_RUN_STATES),
788
+ /** With `exited`; 128 + the signal for a command a signal ended. */
789
+ exitCode: z2.number().int().optional()
790
+ });
791
+ var RunRefusalSchema = z2.object({ error: z2.string(), code: z2.string().optional() });
770
792
  var EnvVarSchema = z2.object({
771
793
  name: z2.string(),
772
794
  value: z2.string().optional(),
@@ -1496,8 +1518,11 @@ var GrowManagedRequest = z4.object({ storageGib: z4.number().int() });
1496
1518
 
1497
1519
  // ../shared/src/cron.ts
1498
1520
  import { z as z5 } from "zod";
1521
+ var DEFAULT_CRON_COMMAND_TIMEOUT_SEC = 600;
1522
+ var MAX_CRON_COMMAND_TIMEOUT_SEC = 3600;
1523
+ var CRON_RUN_LOG_DIR = "/var/log/kvbox/runs";
1499
1524
  var CRON_METHODS = ["GET", "POST"];
1500
- var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost"];
1525
+ var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost", "still-running", "box-outdated"];
1501
1526
  var CronServiceSchema = z5.object({
1502
1527
  owner: z5.string(),
1503
1528
  ownerKind: z5.enum(["user", "org"]),
@@ -1510,20 +1535,16 @@ var CronServiceSchema = z5.object({
1510
1535
  /** What it costs while it exists; on the answer to `POST /cron` only. */
1511
1536
  price: z5.object({ perMonth: z5.number(), currency: z5.string() }).optional()
1512
1537
  });
1513
- var CronTriggerSchema = z5.object({
1538
+ var triggerCommon = {
1514
1539
  id: z5.string(),
1515
1540
  service: z5.string(),
1516
1541
  owner: z5.string(),
1517
- /** The box the request goes to; a trigger is removed with its box. */
1542
+ /** The box it acts on; a trigger is removed with its box. */
1518
1543
  box: z5.string(),
1519
1544
  /** Five fields, `minute hour day-of-month month day-of-week`. */
1520
1545
  expr: z5.string(),
1521
1546
  /** An IANA zone (`Europe/Bucharest`) the expression is read in; `UTC` unless said. */
1522
1547
  timezone: z5.string(),
1523
- method: z5.enum(CRON_METHODS),
1524
- port: z5.number().int(),
1525
- /** Path and query, starting with `/`. */
1526
- path: z5.string(),
1527
1548
  /** False: paused, it fires again when resumed. */
1528
1549
  enabled: z5.boolean(),
1529
1550
  /** When it fires next (ISO); null while paused. */
@@ -1532,15 +1553,36 @@ var CronTriggerSchema = z5.object({
1532
1553
  lastOutcome: z5.enum(CRON_OUTCOMES).nullable(),
1533
1554
  createdBy: z5.string().nullable(),
1534
1555
  createdAt: z5.string()
1556
+ };
1557
+ var CronHttpTriggerSchema = z5.object({
1558
+ ...triggerCommon,
1559
+ kind: z5.literal("http"),
1560
+ method: z5.enum(CRON_METHODS),
1561
+ port: z5.number().int(),
1562
+ /** Path and query, starting with `/`. */
1563
+ path: z5.string()
1535
1564
  });
1565
+ var CronCommandTriggerSchema = z5.object({
1566
+ ...triggerCommon,
1567
+ kind: z5.literal("command"),
1568
+ /** Run by a login shell as the box's user, in its home. */
1569
+ command: z5.string(),
1570
+ /** The command is stopped after this long. */
1571
+ timeoutSec: z5.number().int()
1572
+ });
1573
+ var CronTriggerSchema = z5.discriminatedUnion("kind", [CronHttpTriggerSchema, CronCommandTriggerSchema]);
1536
1574
  var CronRunSchema = z5.object({
1537
1575
  /** The slot this run was for (ISO); a run asked for by hand has the moment it was asked. */
1538
1576
  scheduledFor: z5.string(),
1539
1577
  startedAt: z5.string(),
1540
1578
  /** Null while `running`, and for a run that was never sent. */
1541
1579
  durationMs: z5.number().int().nullable(),
1542
- /** The box's HTTP status; null when it never answered. */
1580
+ /** The box's HTTP status; null when it never answered, and for a command. */
1543
1581
  status: z5.number().int().nullable(),
1582
+ /** A command's exit code (128 + the signal when one ended it); null until it ends, and for a request. */
1583
+ exitCode: z5.number().int().nullable(),
1584
+ /** The file in the box that holds what a command printed; null for a request and for a command that never started. */
1585
+ output: z5.string().nullable(),
1544
1586
  outcome: z5.enum(CRON_OUTCOMES),
1545
1587
  /** Why it did not end `ok`, in a line. */
1546
1588
  error: z5.string().nullable(),
@@ -1556,6 +1598,9 @@ var CronCatalogSchema = z5.object({
1556
1598
  minIntervalSeconds: z5.number().int(),
1557
1599
  /** How long a box has to answer, in seconds. */
1558
1600
  timeoutSeconds: z5.number().int(),
1601
+ /** How long a command may run: unless the trigger says, and at most. */
1602
+ commandTimeoutSeconds: z5.number().int(),
1603
+ maxCommandTimeoutSeconds: z5.number().int(),
1559
1604
  docs: z5.string().optional()
1560
1605
  });
1561
1606
  var CreateCronServiceRequest = z5.object({ name: z5.string() });
@@ -1563,12 +1608,16 @@ var CreateCronTriggerRequest = z5.object({
1563
1608
  box: z5.string().min(1),
1564
1609
  expr: z5.string().min(1),
1565
1610
  timezone: z5.string().optional(),
1611
+ /** A request: `port`, with `method` and `path`. */
1566
1612
  method: z5.enum(CRON_METHODS).optional(),
1567
- port: z5.number().int().min(1).max(65535),
1568
- path: z5.string().optional()
1613
+ port: z5.number().int().min(1).max(65535).optional(),
1614
+ path: z5.string().optional(),
1615
+ /** Or a command, with `timeoutSec`; exactly one of `port` and `command`. */
1616
+ command: z5.string().optional(),
1617
+ timeoutSec: z5.number().int().optional()
1569
1618
  });
1570
1619
  var UpdateCronTriggerRequest = z5.object({ enabled: z5.boolean() });
1571
- var cronTarget = (t) => `${t.method} ${t.box}:${t.port}${t.path}`;
1620
+ var cronTarget = (t) => t.kind === "command" ? `${t.box}$ ${t.command}` : `${t.method} ${t.box}:${t.port}${t.path}`;
1572
1621
 
1573
1622
  // ../shared/src/storage.ts
1574
1623
  import { z as z6 } from "zod";
@@ -6482,7 +6531,9 @@ function outcomeText(outcome) {
6482
6531
  "box-stopped": "skipped: box stopped",
6483
6532
  "host-down": "host unreachable",
6484
6533
  "host-outdated": "host needs an update",
6485
- lost: "lost"
6534
+ lost: "lost",
6535
+ "still-running": "skipped: still running",
6536
+ "box-outdated": "box image too old"
6486
6537
  };
6487
6538
  const text2 = words[outcome];
6488
6539
  return outcome === "ok" ? color.green(text2) : outcome === "running" ? color.dim(text2) : color.red(text2);
@@ -6492,7 +6543,7 @@ function printTriggers(triggers) {
6492
6543
  triggers.map((t) => ({
6493
6544
  id: t.id,
6494
6545
  schedule: scheduleText(t),
6495
- request: cronTarget(t),
6546
+ action: cronTarget(t),
6496
6547
  next: t.enabled ? t.nextRunAt ? until(t.nextRunAt) : "never" : color.yellow("paused"),
6497
6548
  "last run": t.lastRunAt && t.lastOutcome ? `${outcomeText(t.lastOutcome)} ${color.dim(age(t.lastRunAt))}` : "-"
6498
6549
  }))
@@ -6503,7 +6554,7 @@ function printRows2(rows2) {
6503
6554
  for (const [label, value] of rows2) process.stdout.write(`${color.dim(label.padEnd(width2))} ${value}
6504
6555
  `);
6505
6556
  }
6506
- var noTriggers = (service) => info(`cron service ${service} has no triggers yet; add one with: kvbox cron trigger add ${service} <box> "0 6 * * *" --port 3000`);
6557
+ var noTriggers = (service) => info(`cron service ${service} has no triggers yet; add one with: kvbox cron trigger add ${service} <box> "0 6 * * *" --port 3000 (or --run "<command>")`);
6507
6558
 
6508
6559
  // src/commands/cron/create.ts
6509
6560
  var createCommand7 = new Command76("create").description("make a cron service: a named set of triggers").argument("<name>", "what to call it (lowercase letters, digits and '-')").option("--json", "print as JSON").action(async (name, opts, cmd) => {
@@ -6591,7 +6642,6 @@ import { Command as Command87 } from "commander";
6591
6642
  // src/commands/cron/trigger/add.ts
6592
6643
  import { Command as Command80 } from "commander";
6593
6644
  function portOf(value) {
6594
- if (value === void 0) throw new KvboxError("say which port your app listens on in the box: --port 3000");
6595
6645
  const n = Number(value);
6596
6646
  if (!Number.isInteger(n) || n < 1 || n > 65535) throw new KvboxError(`--port ${value}: a port is a number from 1 to 65535`);
6597
6647
  return n;
@@ -6601,17 +6651,35 @@ function methodOf(value) {
6601
6651
  if (!CRON_METHODS.includes(method)) throw new KvboxError(`--method ${value}: a trigger sends ${CRON_METHODS.join(" or ")}`);
6602
6652
  return method;
6603
6653
  }
6604
- var addCommand3 = new Command80("add").description("add a trigger: on a schedule, send a request to a port of a box").argument("<service>", "cron service name").argument("<box>", "the box the request goes to").argument("<expr>", 'cron expression in quotes, five fields: "0 6 * * *" is every day at 06:00').option("--port <n>", "the port your app listens on in the box (required)").option("--path <path>", "path and query to request", "/").option("--method <method>", `HTTP method: ${CRON_METHODS.join(" or ")}`, "POST").option("--tz <zone>", "time zone the schedule is read in, like Europe/Bucharest", "UTC").option("--json", "print as JSON").action(async (service, box, expr, opts, cmd) => {
6605
- const port = portOf(opts.port);
6606
- const method = methodOf(opts.method);
6654
+ function timeoutOf(value) {
6655
+ const t = value.trim().toLowerCase();
6656
+ const units = { s: 1, m: 60, h: 3600 };
6657
+ let sec = 0;
6658
+ for (const [, n, unit] of t.matchAll(/(\d+)([smh])/g)) sec += Number(n) * units[unit];
6659
+ if (!/^(\d+[smh])+$/.test(t) || sec < 1) throw new KvboxError(`--timeout ${value}: give a duration like 90s, 10m or 1h`);
6660
+ if (sec > MAX_CRON_COMMAND_TIMEOUT_SEC) throw new KvboxError(`--timeout ${value}: a command may run for ${MAX_CRON_COMMAND_TIMEOUT_SEC / 60} minutes at most`);
6661
+ return sec;
6662
+ }
6663
+ var addCommand3 = new Command80("add").description("add a trigger: on a schedule, call a port of a box or run a command in it").argument("<service>", "cron service name").argument("<box>", "the box it acts on").argument("<expr>", 'cron expression in quotes, five fields: "0 6 * * *" is every day at 06:00').option("--port <n>", "call this port, the one your app listens on in the box").option("--path <path>", "with --port: path and query to request (default: /)").option("--method <method>", `with --port: HTTP method, ${CRON_METHODS.join(" or ")} (default: POST)`).option("--run <command>", 'or run this command in the box, in quotes: "node ~/app/embed.js"').option("--timeout <duration>", `with --run: stop the command after this long (90s, 10m, 1h; default: ${DEFAULT_CRON_COMMAND_TIMEOUT_SEC / 60}m)`).option("--tz <zone>", "time zone the schedule is read in, like Europe/Bucharest", "UTC").option("--json", "print as JSON").action(async (service, box, expr, opts, cmd) => {
6664
+ let action;
6665
+ if (opts.run !== void 0) {
6666
+ if (opts.port !== void 0 || opts.path !== void 0 || opts.method !== void 0) throw new KvboxError("a trigger runs a command or calls a port: use --run, or --port with --path and --method, not both");
6667
+ if (opts.run.trim() === "") throw new KvboxError('--run needs the command, in quotes: --run "node ~/app/embed.js"');
6668
+ action = { command: opts.run, ...opts.timeout === void 0 ? {} : { timeoutSec: timeoutOf(opts.timeout) } };
6669
+ } else {
6670
+ if (opts.timeout !== void 0) throw new KvboxError("--timeout is for --run; a request to a port has a fixed time to answer");
6671
+ if (opts.port === void 0) throw new KvboxError('say what the trigger does: --port 3000 to call your app in the box, or --run "<command>" to run a command in it');
6672
+ action = { port: portOf(opts.port), method: methodOf(opts.method ?? "POST"), path: opts.path ?? "/" };
6673
+ }
6607
6674
  const client = await cronClient(cmd);
6608
6675
  try {
6609
- const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz, method, port, path: opts.path });
6676
+ const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz, ...action });
6610
6677
  if (opts.json) {
6611
6678
  json(trigger);
6612
6679
  return;
6613
6680
  }
6614
6681
  info(`${color.green("\u2713")} trigger ${color.bold(trigger.id)} added: ${cronTarget(trigger)} on ${scheduleText(trigger)}`);
6682
+ if (trigger.kind === "command") info(color.dim(`Stopped after ${trigger.timeoutSec % 60 === 0 ? `${trigger.timeoutSec / 60} min` : `${trigger.timeoutSec} s`} if still going. What it prints stays in the box: ${CRON_RUN_LOG_DIR}/`));
6615
6683
  if (trigger.nextRunAt) info(color.dim(`First run ${until(trigger.nextRunAt)}. Try it now: kvbox cron trigger run ${refFor(service, client)} ${trigger.id}`));
6616
6684
  } finally {
6617
6685
  await client.close();
@@ -6725,11 +6793,13 @@ var runsCommand = new Command86("runs").aliases(["logs"]).description("show how
6725
6793
  runs.map((r) => ({
6726
6794
  when: age(r.startedAt),
6727
6795
  result: outcomeText(r.outcome),
6728
- status: r.status ?? "-",
6796
+ status: r.status ?? (r.exitCode === null ? "-" : `exit ${r.exitCode}`),
6729
6797
  took: r.durationMs === null ? "-" : r.durationMs < 1e3 ? `${r.durationMs} ms` : `${(r.durationMs / 1e3).toFixed(1)} s`,
6730
6798
  note: [r.woke ? "woke the box" : "", r.error ?? ""].filter(Boolean).join("; ") || color.dim("-")
6731
6799
  }))
6732
6800
  );
6801
+ const last = runs.find((r) => r.output !== null);
6802
+ if (last) info(color.dim(`A command's output stays in the box, one file per run; the newest: kvbox exec <box> -- cat ${last.output}`));
6733
6803
  } finally {
6734
6804
  await client.close();
6735
6805
  }