@kvbox/cli 0.6.6 → 0.6.8
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 +1105 -579
- package/dist/kvbox.js.map +1 -1
- package/package.json +3 -2
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.
|
|
167
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.8" : void 0);
|
|
168
168
|
|
|
169
169
|
// src/commands/vm/index.ts
|
|
170
170
|
import { Command as Command37 } from "commander";
|
|
@@ -283,7 +283,7 @@ function paths(home = kvboxHome()) {
|
|
|
283
283
|
* disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names
|
|
284
284
|
* it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.
|
|
285
285
|
*/
|
|
286
|
-
volumeDrive: (
|
|
286
|
+
volumeDrive: (volume2) => join(dir, volumeDriveRel(volume2))
|
|
287
287
|
};
|
|
288
288
|
},
|
|
289
289
|
/** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */
|
|
@@ -328,11 +328,11 @@ function paths(home = kvboxHome()) {
|
|
|
328
328
|
}
|
|
329
329
|
};
|
|
330
330
|
}
|
|
331
|
-
function volumeDriveRel(
|
|
332
|
-
return `volume-${
|
|
331
|
+
function volumeDriveRel(volume2) {
|
|
332
|
+
return `volume-${volume2}.ext4`;
|
|
333
333
|
}
|
|
334
|
-
function volumeMountPath(
|
|
335
|
-
return `/mnt/${
|
|
334
|
+
function volumeMountPath(volume2) {
|
|
335
|
+
return `/mnt/${volume2}`;
|
|
336
336
|
}
|
|
337
337
|
|
|
338
338
|
// src/session.ts
|
|
@@ -672,7 +672,13 @@ var StartRunRequest = z.object({
|
|
|
672
672
|
id: z.string().regex(BOX_RUN_ID_RE),
|
|
673
673
|
command: z.string().min(1).max(8192),
|
|
674
674
|
/** The command and everything it started are killed after this long. */
|
|
675
|
-
timeoutSec: z.number().int().min(1).max(86400)
|
|
675
|
+
timeoutSec: z.number().int().min(1).max(86400),
|
|
676
|
+
/**
|
|
677
|
+
* The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
|
|
678
|
+
* (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
|
|
679
|
+
* without having run anything.
|
|
680
|
+
*/
|
|
681
|
+
output: z.boolean().optional()
|
|
676
682
|
});
|
|
677
683
|
var StartRunAnswerSchema = z.object({
|
|
678
684
|
id: z.string(),
|
|
@@ -694,6 +700,39 @@ var BoxRunSchema = z.object({
|
|
|
694
700
|
durationMs: z.number().int().nonnegative().optional()
|
|
695
701
|
});
|
|
696
702
|
var RunRefusalSchema = z.object({ error: z.string(), code: z.string().optional() });
|
|
703
|
+
var RUN_OUTPUT_MAX_BYTES = 1 << 20;
|
|
704
|
+
var RUN_STREAMS = ["stdout", "stderr"];
|
|
705
|
+
var RunOutputSchema = z.object({
|
|
706
|
+
id: z.string(),
|
|
707
|
+
stream: z.enum(RUN_STREAMS),
|
|
708
|
+
offset: z.number().int().nonnegative(),
|
|
709
|
+
size: z.number().int().nonnegative(),
|
|
710
|
+
data: z.string()
|
|
711
|
+
});
|
|
712
|
+
var DEFAULT_EXEC_TIMEOUT_SEC = 600;
|
|
713
|
+
var ExecRequest = z.object({
|
|
714
|
+
command: z.string().min(1).max(8192),
|
|
715
|
+
/** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
|
|
716
|
+
timeoutSec: z.number().int().min(1).max(86400).optional()
|
|
717
|
+
});
|
|
718
|
+
var ExecStartSchema = z.object({
|
|
719
|
+
id: z.string(),
|
|
720
|
+
/** The box was asleep and this request woke it. */
|
|
721
|
+
woke: z.boolean()
|
|
722
|
+
});
|
|
723
|
+
var ExecSchema = z.object({
|
|
724
|
+
id: z.string(),
|
|
725
|
+
state: z.enum(BOX_RUN_STATES),
|
|
726
|
+
/** With `exited`; 128 + the signal for a command a signal ended. */
|
|
727
|
+
exitCode: z.number().int().optional(),
|
|
728
|
+
/** With `exited` and `timeout`: how long the command itself ran. */
|
|
729
|
+
durationMs: z.number().int().nonnegative().optional(),
|
|
730
|
+
stdout: z.string().optional(),
|
|
731
|
+
stderr: z.string().optional(),
|
|
732
|
+
stdoutBytes: z.number().int().nonnegative().optional(),
|
|
733
|
+
stderrBytes: z.number().int().nonnegative().optional(),
|
|
734
|
+
truncated: z.boolean().optional()
|
|
735
|
+
});
|
|
697
736
|
var EnvVarSchema = z.object({
|
|
698
737
|
name: z.string(),
|
|
699
738
|
value: z.string().optional(),
|
|
@@ -1052,7 +1091,7 @@ var VolumeEventsResponseSchema = z.object({
|
|
|
1052
1091
|
events: z.array(VolumeEventRowSchema),
|
|
1053
1092
|
next: z.number().int()
|
|
1054
1093
|
});
|
|
1055
|
-
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
|
|
1094
|
+
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated"];
|
|
1056
1095
|
var ApiErrorCodeSchema = z.enum(API_ERROR_CODES);
|
|
1057
1096
|
var ApiErrorSchema = z.object({
|
|
1058
1097
|
error: z.string(),
|
|
@@ -1373,10 +1412,10 @@ function isLoopback(hostname) {
|
|
|
1373
1412
|
return hostname === "localhost" || hostname.startsWith("127.") || hostname === "[::1]";
|
|
1374
1413
|
}
|
|
1375
1414
|
function normalizeUrl(input) {
|
|
1376
|
-
const
|
|
1415
|
+
const withScheme2 = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
|
|
1377
1416
|
let url;
|
|
1378
1417
|
try {
|
|
1379
|
-
url = new URL(
|
|
1418
|
+
url = new URL(withScheme2);
|
|
1380
1419
|
} catch {
|
|
1381
1420
|
throw new KvboxError(`not a URL: ${input}`);
|
|
1382
1421
|
}
|
|
@@ -1474,16 +1513,16 @@ async function forgetCertOf(p) {
|
|
|
1474
1513
|
}
|
|
1475
1514
|
async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
|
|
1476
1515
|
if (client.target.kind !== "cloud") return "local";
|
|
1477
|
-
const
|
|
1478
|
-
const session =
|
|
1479
|
-
if (!
|
|
1516
|
+
const fromEnv2 = client.target.env === true;
|
|
1517
|
+
const session = fromEnv2 ? null : await readSession(p);
|
|
1518
|
+
if (!fromEnv2 && !session) return "local";
|
|
1480
1519
|
if (session) {
|
|
1481
1520
|
const expires = session.sshCertExpires ? new Date(session.sshCertExpires).getTime() : 0;
|
|
1482
1521
|
const onDisk = await readFile2(p.sshCert, "utf8").then(() => true, () => false);
|
|
1483
1522
|
const names2 = opts.owner === void 0 || (session.sshCertPrincipals ?? []).includes(opts.owner);
|
|
1484
1523
|
if (onDisk && expires - now > RENEW_BEFORE_MS && names2 && !opts.force) return "kept";
|
|
1485
1524
|
}
|
|
1486
|
-
const publicKey =
|
|
1525
|
+
const publicKey = fromEnv2 ? await ensureSshKey(p) : await readFile2(`${p.sshKey}.pub`, "utf8").catch(() => null);
|
|
1487
1526
|
if (publicKey === null) throw new KvboxError(`could not renew your SSH certificate: no key at ${p.sshKey}.pub; run: kvbox login`);
|
|
1488
1527
|
let signed;
|
|
1489
1528
|
try {
|
|
@@ -1507,35 +1546,524 @@ async function ensureCert(client, p = paths(), now = Date.now(), opts = {}) {
|
|
|
1507
1546
|
import { spawn } from "child_process";
|
|
1508
1547
|
import { openSync } from "fs";
|
|
1509
1548
|
import { mkdir as mkdir3, readFile as readFile3, stat } from "fs/promises";
|
|
1510
|
-
import { setTimeout as
|
|
1549
|
+
import { setTimeout as sleep2 } from "timers/promises";
|
|
1511
1550
|
import { Agent, request } from "undici";
|
|
1512
|
-
import { z as z7 } from "zod";
|
|
1513
1551
|
|
|
1514
|
-
// ../
|
|
1552
|
+
// ../sdk/src/machines.ts
|
|
1553
|
+
import { z as z3 } from "zod";
|
|
1554
|
+
|
|
1555
|
+
// ../sdk/src/errors.ts
|
|
1556
|
+
var KvboxSdkError = class extends Error {
|
|
1557
|
+
constructor(message, options) {
|
|
1558
|
+
super(message, options);
|
|
1559
|
+
this.name = "KvboxSdkError";
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
var KvboxApiError = class extends KvboxSdkError {
|
|
1563
|
+
status;
|
|
1564
|
+
code;
|
|
1565
|
+
apiError;
|
|
1566
|
+
constructor(status2, message, opts = {}) {
|
|
1567
|
+
super(message);
|
|
1568
|
+
this.name = "KvboxApiError";
|
|
1569
|
+
this.status = status2;
|
|
1570
|
+
this.code = opts.code;
|
|
1571
|
+
this.apiError = opts.apiError ?? true;
|
|
1572
|
+
}
|
|
1573
|
+
};
|
|
1574
|
+
var UnauthorizedError = class extends KvboxApiError {
|
|
1575
|
+
constructor(status2, message, opts = {}) {
|
|
1576
|
+
super(status2, message, opts);
|
|
1577
|
+
this.name = "UnauthorizedError";
|
|
1578
|
+
}
|
|
1579
|
+
};
|
|
1580
|
+
var PaymentRequiredError = class extends KvboxApiError {
|
|
1581
|
+
constructor(status2, message, opts = {}) {
|
|
1582
|
+
super(status2, message, opts);
|
|
1583
|
+
this.name = "PaymentRequiredError";
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
var NotFoundError = class extends KvboxApiError {
|
|
1587
|
+
constructor(status2, message, opts = {}) {
|
|
1588
|
+
super(status2, message, opts);
|
|
1589
|
+
this.name = "NotFoundError";
|
|
1590
|
+
}
|
|
1591
|
+
};
|
|
1592
|
+
var ConflictError = class extends KvboxApiError {
|
|
1593
|
+
constructor(status2, message, opts = {}) {
|
|
1594
|
+
super(status2, message, opts);
|
|
1595
|
+
this.name = "ConflictError";
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
var BoxOutdatedError = class extends ConflictError {
|
|
1599
|
+
constructor(status2, message, opts = {}) {
|
|
1600
|
+
super(status2, message, opts);
|
|
1601
|
+
this.name = "BoxOutdatedError";
|
|
1602
|
+
}
|
|
1603
|
+
};
|
|
1604
|
+
function apiError(status2, message, opts = {}) {
|
|
1605
|
+
switch (status2) {
|
|
1606
|
+
case 401:
|
|
1607
|
+
return new UnauthorizedError(status2, message, opts);
|
|
1608
|
+
case 402:
|
|
1609
|
+
return new PaymentRequiredError(status2, message, opts);
|
|
1610
|
+
case 404:
|
|
1611
|
+
return new NotFoundError(status2, message, opts);
|
|
1612
|
+
case 409:
|
|
1613
|
+
return opts.code === "box-outdated" ? new BoxOutdatedError(status2, message, opts) : new ConflictError(status2, message, opts);
|
|
1614
|
+
default:
|
|
1615
|
+
return new KvboxApiError(status2, message, opts);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
var KvboxConnectionError = class extends KvboxSdkError {
|
|
1619
|
+
code;
|
|
1620
|
+
constructor(message, code, options) {
|
|
1621
|
+
super(message, options);
|
|
1622
|
+
this.name = "KvboxConnectionError";
|
|
1623
|
+
this.code = code;
|
|
1624
|
+
}
|
|
1625
|
+
};
|
|
1626
|
+
var KvboxTimeoutError = class extends KvboxSdkError {
|
|
1627
|
+
timeoutMs;
|
|
1628
|
+
constructor(message, timeoutMs) {
|
|
1629
|
+
super(message);
|
|
1630
|
+
this.name = "KvboxTimeoutError";
|
|
1631
|
+
this.timeoutMs = timeoutMs;
|
|
1632
|
+
}
|
|
1633
|
+
};
|
|
1634
|
+
var KvboxResponseError = class extends KvboxSdkError {
|
|
1635
|
+
status;
|
|
1636
|
+
reason;
|
|
1637
|
+
constructor(status2, message, reason = "not-json", options) {
|
|
1638
|
+
super(message, options);
|
|
1639
|
+
this.name = "KvboxResponseError";
|
|
1640
|
+
this.status = status2;
|
|
1641
|
+
this.reason = reason;
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
|
|
1645
|
+
// ../sdk/src/machines.ts
|
|
1646
|
+
var FORK_TIMEOUT_MS = 66e4;
|
|
1647
|
+
var listQuery = (opts) => opts.all ? "?all=1" : "";
|
|
1648
|
+
var box = (name, rest = "") => `/machines/${encodeURIComponent(name)}${rest}`;
|
|
1649
|
+
var sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
1650
|
+
var passing = (err) => err instanceof KvboxConnectionError || err instanceof KvboxTimeoutError || err instanceof KvboxApiError && [502, 503, 504].includes(err.status);
|
|
1651
|
+
var Machines = class {
|
|
1652
|
+
constructor(transport) {
|
|
1653
|
+
this.transport = transport;
|
|
1654
|
+
this.ports = {
|
|
1655
|
+
add: (name, req, opts = {}) => this.transport.request("POST", box(name, "/ports"), MachineSchema, { body: req, org: opts.org }),
|
|
1656
|
+
remove: (name, req, opts = {}) => this.transport.request("DELETE", box(name, "/ports"), MachineSchema, { body: req, org: opts.org })
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
transport;
|
|
1660
|
+
/** Publish and close a box's ports. */
|
|
1661
|
+
ports;
|
|
1662
|
+
/** Every box the caller can read (their own and their orgs'), sorted by owner then name. */
|
|
1663
|
+
list(opts = {}) {
|
|
1664
|
+
return this.transport.request("GET", `/machines${listQuery(opts)}`, z3.array(MachineSchema), { org: opts.org });
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* One box, found in the listing (the API has no route for a single box). `slug/name` looks in that
|
|
1668
|
+
* slug only. A bare name is the caller's own box first, else the only org box of that name; one in
|
|
1669
|
+
* two orgs is an error that asks for `slug/name` or `org`. None: `NotFoundError`.
|
|
1670
|
+
*/
|
|
1671
|
+
get(name, opts = {}) {
|
|
1672
|
+
return this.find(name, opts.org);
|
|
1673
|
+
}
|
|
1674
|
+
/** `get`, its listing call limited to `timeoutMs` (default: the client's). */
|
|
1675
|
+
async find(name, orgOpt, timeoutMs) {
|
|
1676
|
+
const slash = name.indexOf("/");
|
|
1677
|
+
const [org, bare] = slash === -1 ? [orgOpt, name] : [name.slice(0, slash), name.slice(slash + 1)];
|
|
1678
|
+
const listing = await this.transport.request("GET", "/machines", z3.array(MachineSchema), { org, timeoutMs });
|
|
1679
|
+
const named = listing.filter((m) => m.name === bare && (slash === -1 || slugOf2(m.owner) === org));
|
|
1680
|
+
if (named.length <= 1) {
|
|
1681
|
+
if (named[0] !== void 0) return named[0];
|
|
1682
|
+
throw new NotFoundError(404, `box ${name}: not found`);
|
|
1683
|
+
}
|
|
1684
|
+
const own = named.filter((m) => m.ownerKind === "user");
|
|
1685
|
+
if (own.length === 1) return own[0];
|
|
1686
|
+
throw new KvboxSdkError(`box ${name} exists in ${named.map((m) => slugOf2(m.owner)).join(", ")}; say which with slug/name or the org option`);
|
|
1687
|
+
}
|
|
1688
|
+
/**
|
|
1689
|
+
* Make a box and boot it. The answer comes once the VM has started (status `running`); the guest
|
|
1690
|
+
* system inside is still booting for a few seconds after (see `waitUntilReady`). A box from an
|
|
1691
|
+
* image that serves something answers `connect` (its URL with the password) this once.
|
|
1692
|
+
* `org` (this call's, else the client's): the new box goes to that org, else to the caller's own slug.
|
|
1693
|
+
*/
|
|
1694
|
+
create(req = {}, opts = {}) {
|
|
1695
|
+
return this.transport.request("POST", "/machines", MachineSchema, { body: req, org: opts.org });
|
|
1696
|
+
}
|
|
1697
|
+
/** Remove the box and its disk. */
|
|
1698
|
+
async remove(name, opts = {}) {
|
|
1699
|
+
await this.transport.request("DELETE", box(name), z3.undefined(), { org: opts.org });
|
|
1700
|
+
}
|
|
1701
|
+
/** Boot a stopped box. */
|
|
1702
|
+
start(name, opts = {}) {
|
|
1703
|
+
return this.transport.request("POST", box(name, "/start"), MachineSchema, { body: opts.force ? { force: true } : void 0, org: opts.org });
|
|
1704
|
+
}
|
|
1705
|
+
/** Shut the box down; its disk stays. */
|
|
1706
|
+
stop(name, opts = {}) {
|
|
1707
|
+
return this.transport.request("POST", box(name, "/stop"), MachineSchema, { org: opts.org });
|
|
1708
|
+
}
|
|
1709
|
+
/** Freeze the running box in memory (standby). */
|
|
1710
|
+
pause(name, opts = {}) {
|
|
1711
|
+
return this.transport.request("POST", box(name, "/pause"), MachineSchema, { org: opts.org });
|
|
1712
|
+
}
|
|
1713
|
+
/** Unfreeze a box in standby. */
|
|
1714
|
+
resume(name, opts = {}) {
|
|
1715
|
+
return this.transport.request("POST", box(name, "/resume"), MachineSchema, { org: opts.org });
|
|
1716
|
+
}
|
|
1717
|
+
/** Write the box's memory to disk and free it; `wake` brings the box back where it was. */
|
|
1718
|
+
hibernate(name, opts = {}) {
|
|
1719
|
+
return this.transport.request("POST", box(name, "/hibernate"), MachineSchema, { org: opts.org });
|
|
1720
|
+
}
|
|
1721
|
+
/** Bring a hibernated box back, processes and all. */
|
|
1722
|
+
wake(name, opts = {}) {
|
|
1723
|
+
return this.transport.request("POST", box(name, "/wake"), MachineSchema, { body: opts.force ? { force: true } : void 0, org: opts.org });
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* A copy of box `name` on the same host. The copy goes to `org` (the client's, or this call's),
|
|
1727
|
+
* else to the caller's own slug; the source is found without it, so name it `slug/name` when it is an org's.
|
|
1728
|
+
*/
|
|
1729
|
+
fork(name, req = {}, opts = {}) {
|
|
1730
|
+
const timeoutMs = opts.timeoutMs ?? Math.max(FORK_TIMEOUT_MS, this.transport.timeoutMs);
|
|
1731
|
+
return this.transport.request("POST", box(name, "/fork"), MachineSchema, { body: req, org: opts.org, timeoutMs });
|
|
1732
|
+
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Resolve with the box once it is `running`, looking every `intervalMs`.
|
|
1735
|
+
*
|
|
1736
|
+
* What "ready" means: `create`, `start` and `fork` already answer once the VM is started (status
|
|
1737
|
+
* `running`, an address and, through the cloud, `ssh`), and `wake`/`resume` once its memory is
|
|
1738
|
+
* back. What the API does not tell is the guest's own boot: sshd and kvbox-agent listen a few
|
|
1739
|
+
* seconds after a cold start, and nothing in a box's listing says when. So this waits for what the
|
|
1740
|
+
* listing does say: status `running` (a box whose host has not answered lately is `unknown` until
|
|
1741
|
+
* it does; any other status may still change, for instance while someone else starts it). A
|
|
1742
|
+
* command run in the box right after should still allow for the guest's few seconds.
|
|
1743
|
+
* Not found is thrown at once; nothing answering, or a 502/503/504, is waited through.
|
|
1744
|
+
*/
|
|
1745
|
+
async waitUntilReady(name, opts = {}) {
|
|
1746
|
+
const timeoutMs = opts.timeoutMs ?? 12e4;
|
|
1747
|
+
const intervalMs = opts.intervalMs ?? 1e3;
|
|
1748
|
+
const deadline = Date.now() + timeoutMs;
|
|
1749
|
+
let last;
|
|
1750
|
+
for (; ; ) {
|
|
1751
|
+
try {
|
|
1752
|
+
const m = await this.find(name, opts.org, Math.max(1, Math.min(deadline - Date.now(), this.transport.timeoutMs)));
|
|
1753
|
+
if (m.status === "running") return m;
|
|
1754
|
+
last = m.status;
|
|
1755
|
+
} catch (err) {
|
|
1756
|
+
if (!passing(err)) throw err;
|
|
1757
|
+
last = err.message;
|
|
1758
|
+
}
|
|
1759
|
+
const left = deadline - Date.now();
|
|
1760
|
+
if (left <= 0) throw new KvboxTimeoutError(`box ${name} was not running within ${Math.round(timeoutMs / 1e3)}s (last: ${last})`, timeoutMs);
|
|
1761
|
+
await sleep(Math.min(intervalMs, left));
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Run `command` in the box and resolve once it is over, with its exit code and output.
|
|
1766
|
+
*
|
|
1767
|
+
* The command runs as the box's user (`kvbox`) in its home, through a login shell (`bash -lc`) with
|
|
1768
|
+
* the owner's environment variables: one string, as you would type it after `kvbox exec web --`.
|
|
1769
|
+
* No terminal and no stdin. A hibernated or paused box is woken first; a stopped one is refused
|
|
1770
|
+
* (`ConflictError`), and so is a box whose image is from before base v0.16.0 (`BoxOutdatedError`).
|
|
1771
|
+
* A slug that may not spend gets a `PaymentRequiredError`.
|
|
1772
|
+
*
|
|
1773
|
+
* `timeoutMs` (default 600 000, at most 24 h) is the command's time limit, in whole seconds on the
|
|
1774
|
+
* box: then it and everything it started are killed, and the result has `timedOut` and no exit
|
|
1775
|
+
* code. The SDK waits a minute past it before giving up with a `KvboxTimeoutError`. `stdout` and
|
|
1776
|
+
* `stderr` are the first MiB of each, as UTF-8 text; `truncated` says one was longer.
|
|
1777
|
+
* The command is polled every `pollMs` (default 1000); a moment without the API is waited through.
|
|
1778
|
+
*/
|
|
1779
|
+
async exec(name, command, opts = {}) {
|
|
1780
|
+
const timeoutSec = execTimeoutSec(opts.timeoutMs);
|
|
1781
|
+
const pollMs = opts.pollMs ?? 1e3;
|
|
1782
|
+
const { id } = await this.startExec(name, command, opts);
|
|
1783
|
+
const startedAt = Date.now();
|
|
1784
|
+
const deadline = startedAt + timeoutSec * 1e3 + EXEC_GRACE_MS;
|
|
1785
|
+
let last;
|
|
1786
|
+
for (; ; ) {
|
|
1787
|
+
try {
|
|
1788
|
+
const run3 = await this.getExec(name, id, { org: opts.org });
|
|
1789
|
+
if (run3.state === "unknown") throw new KvboxSdkError(`box ${name} no longer knows command ${id}: it restarted while the command ran`);
|
|
1790
|
+
if (run3.state !== "running") {
|
|
1791
|
+
return {
|
|
1792
|
+
exitCode: run3.exitCode ?? null,
|
|
1793
|
+
timedOut: run3.state === "timeout",
|
|
1794
|
+
stdout: run3.stdout ?? "",
|
|
1795
|
+
stderr: run3.stderr ?? "",
|
|
1796
|
+
truncated: run3.truncated ?? false,
|
|
1797
|
+
durationMs: run3.durationMs ?? Date.now() - startedAt
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
last = "running";
|
|
1801
|
+
} catch (err) {
|
|
1802
|
+
if (!passing(err)) throw err;
|
|
1803
|
+
last = err.message;
|
|
1804
|
+
}
|
|
1805
|
+
const left = deadline - Date.now();
|
|
1806
|
+
if (left <= 0) throw new KvboxTimeoutError(`command ${id} in box ${name} had not ended within ${Math.round((deadline - startedAt) / 1e3)}s (last: ${last})`, deadline - startedAt);
|
|
1807
|
+
await sleep(Math.min(pollMs, left));
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Start `command` in the box and answer at once with its `id` (what `exec` does first): for a
|
|
1812
|
+
* command you do not wait on, or one you look at later with `getExec`. `woke`: the box was asleep.
|
|
1813
|
+
* A box that is still waking (503) is asked again, for up to five minutes: its own time, not the command's.
|
|
1814
|
+
*/
|
|
1815
|
+
async startExec(name, command, opts = {}) {
|
|
1816
|
+
const timeoutSec = execTimeoutSec(opts.timeoutMs);
|
|
1817
|
+
const deadline = Date.now() + EXEC_WAKE_MS;
|
|
1818
|
+
for (; ; ) {
|
|
1819
|
+
try {
|
|
1820
|
+
return await this.transport.request("POST", box(name, "/exec"), ExecStartSchema, { body: { command, timeoutSec }, org: opts.org });
|
|
1821
|
+
} catch (err) {
|
|
1822
|
+
if (!(err instanceof KvboxApiError && err.status === 503) || Date.now() + (opts.pollMs ?? 1e3) >= deadline) throw err;
|
|
1823
|
+
await sleep(opts.pollMs ?? 1e3);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
/**
|
|
1828
|
+
* How a command started with `exec` or `startExec` stands; once it is over, with its output (see `Exec`).
|
|
1829
|
+
* A box that went to sleep since is woken to answer, so a slug that may not spend gets a `PaymentRequiredError`.
|
|
1830
|
+
*/
|
|
1831
|
+
getExec(name, id, opts = {}) {
|
|
1832
|
+
return this.transport.request("GET", box(name, `/exec/${encodeURIComponent(id)}`), ExecSchema, { org: opts.org });
|
|
1833
|
+
}
|
|
1834
|
+
};
|
|
1835
|
+
var EXEC_GRACE_MS = 6e4;
|
|
1836
|
+
var EXEC_WAKE_MS = 5 * 6e4;
|
|
1837
|
+
var MAX_EXEC_TIMEOUT_SEC = 86400;
|
|
1838
|
+
function execTimeoutSec(timeoutMs) {
|
|
1839
|
+
if (timeoutMs === void 0) return DEFAULT_EXEC_TIMEOUT_SEC;
|
|
1840
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new KvboxSdkError(`timeoutMs must be a number of milliseconds, not ${String(timeoutMs)}`);
|
|
1841
|
+
return Math.min(Math.max(Math.ceil(timeoutMs / 1e3), 1), MAX_EXEC_TIMEOUT_SEC);
|
|
1842
|
+
}
|
|
1843
|
+
var slugOf2 = (owner) => {
|
|
1844
|
+
const at = owner.indexOf("@");
|
|
1845
|
+
return at === -1 ? owner : owner.slice(0, at);
|
|
1846
|
+
};
|
|
1847
|
+
|
|
1848
|
+
// ../sdk/src/snapshots.ts
|
|
1515
1849
|
import { z as z4 } from "zod";
|
|
1850
|
+
var Snapshots = class {
|
|
1851
|
+
constructor(transport) {
|
|
1852
|
+
this.transport = transport;
|
|
1853
|
+
}
|
|
1854
|
+
transport;
|
|
1855
|
+
/** Every snapshot the caller can read. */
|
|
1856
|
+
list(opts = {}) {
|
|
1857
|
+
return this.transport.request("GET", `/snapshots${listQuery(opts)}`, z4.array(SnapshotSchema), { org: opts.org });
|
|
1858
|
+
}
|
|
1859
|
+
/** Snapshot box `req.box` as `req.name` (`replace`: retake one that exists). The box is paused while it is taken. */
|
|
1860
|
+
create(req, opts = {}) {
|
|
1861
|
+
return this.transport.request("POST", "/snapshots", SnapshotSchema, { body: req, org: opts.org });
|
|
1862
|
+
}
|
|
1863
|
+
async remove(name, opts = {}) {
|
|
1864
|
+
await this.transport.request("DELETE", `/snapshots/${encodeURIComponent(name)}`, z4.undefined(), { org: opts.org });
|
|
1865
|
+
}
|
|
1866
|
+
};
|
|
1867
|
+
|
|
1868
|
+
// ../sdk/src/transport.ts
|
|
1869
|
+
import { z as z5 } from "zod";
|
|
1870
|
+
var Transport = class {
|
|
1871
|
+
baseUrl;
|
|
1872
|
+
org;
|
|
1873
|
+
apiKey;
|
|
1874
|
+
fetch;
|
|
1875
|
+
/** A request's default limit. */
|
|
1876
|
+
timeoutMs;
|
|
1877
|
+
constructor(opts) {
|
|
1878
|
+
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
1879
|
+
this.apiKey = opts.apiKey;
|
|
1880
|
+
this.org = opts.org;
|
|
1881
|
+
this.fetch = opts.fetch;
|
|
1882
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1883
|
+
}
|
|
1884
|
+
/** `host:port` of the base URL, for messages. */
|
|
1885
|
+
get host() {
|
|
1886
|
+
try {
|
|
1887
|
+
return new URL(this.baseUrl).host;
|
|
1888
|
+
} catch {
|
|
1889
|
+
return this.baseUrl;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* `method path`, the answer parsed with `schema` (an empty body is `undefined`, so a 204 takes
|
|
1894
|
+
* `z.undefined()`; one that does not fit is a `KvboxResponseError`). A status outside 200-299 is a
|
|
1895
|
+
* `KvboxApiError` (redirects are not followed).
|
|
1896
|
+
*/
|
|
1897
|
+
async request(method, path, schema, opts = {}) {
|
|
1898
|
+
const { status: status2, text: text2 } = await this.send(method, path, opts);
|
|
1899
|
+
if (status2 < 200 || status2 >= 300) {
|
|
1900
|
+
const parsed2 = LooseApiErrorSchema.safeParse(safeJson(text2) ?? {});
|
|
1901
|
+
if (!parsed2.success) throw apiError(status2, `${this.host} answered ${status2}`, { apiError: false });
|
|
1902
|
+
const code = ApiErrorCodeSchema.safeParse(parsed2.data.code);
|
|
1903
|
+
throw apiError(status2, parsed2.data.error, { code: code.success ? code.data : void 0 });
|
|
1904
|
+
}
|
|
1905
|
+
const json2 = text2 === "" ? void 0 : safeJson(text2);
|
|
1906
|
+
if (text2 !== "" && json2 === void 0) throw new KvboxResponseError(status2, `${this.host} answered ${status2} with something that is not JSON`);
|
|
1907
|
+
const parsed = schema.safeParse(json2);
|
|
1908
|
+
if (!parsed.success) throw new KvboxResponseError(status2, `${this.host} answered ${method} ${path} with something this SDK does not expect: ${parsed.error.message}`, "schema", { cause: parsed.error });
|
|
1909
|
+
return parsed.data;
|
|
1910
|
+
}
|
|
1911
|
+
/** The raw answer: status and body text. Where a request that is not plain JSON (a stream) would start. */
|
|
1912
|
+
async send(method, path, opts) {
|
|
1913
|
+
const headers = {};
|
|
1914
|
+
if (opts.body !== void 0) headers["content-type"] = "application/json";
|
|
1915
|
+
if (this.apiKey !== void 0 && this.apiKey !== "") headers["authorization"] = `Bearer ${this.apiKey}`;
|
|
1916
|
+
const org = opts.org ?? this.org;
|
|
1917
|
+
if (org !== void 0) headers["x-kvbox-org"] = org;
|
|
1918
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
|
|
1919
|
+
const timedOut = () => new KvboxTimeoutError(`${this.host} did not answer ${method} ${path} within ${Math.round(timeoutMs / 1e3)}s`, timeoutMs);
|
|
1920
|
+
let res;
|
|
1921
|
+
try {
|
|
1922
|
+
res = await this.fetch(this.baseUrl + path, {
|
|
1923
|
+
method,
|
|
1924
|
+
headers,
|
|
1925
|
+
...opts.body === void 0 ? {} : { body: JSON.stringify(opts.body) },
|
|
1926
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
1927
|
+
redirect: "manual"
|
|
1928
|
+
});
|
|
1929
|
+
} catch (err) {
|
|
1930
|
+
if (isTimeout(err)) throw timedOut();
|
|
1931
|
+
const code = errorCode(err);
|
|
1932
|
+
throw new KvboxConnectionError(`could not reach ${this.host}${code === void 0 ? "" : ` (${code})`}`, code, { cause: err });
|
|
1933
|
+
}
|
|
1934
|
+
try {
|
|
1935
|
+
return { status: res.status, text: await res.text() };
|
|
1936
|
+
} catch (err) {
|
|
1937
|
+
if (isTimeout(err)) throw timedOut();
|
|
1938
|
+
const code = errorCode(err);
|
|
1939
|
+
throw new KvboxResponseError(res.status, `${this.host} answered ${res.status} but the answer was cut off${code === void 0 ? "" : ` (${code})`}`, "cut-off", { cause: err });
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
};
|
|
1943
|
+
var LooseApiErrorSchema = z5.object({ error: z5.string(), code: z5.string().optional() });
|
|
1944
|
+
function safeJson(text2) {
|
|
1945
|
+
try {
|
|
1946
|
+
return JSON.parse(text2);
|
|
1947
|
+
} catch {
|
|
1948
|
+
return void 0;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
var isTimeout = (err) => err instanceof Error && (err.name === "TimeoutError" || err.cause instanceof Error && err.cause.name === "TimeoutError");
|
|
1952
|
+
function errorCode(err) {
|
|
1953
|
+
for (let e = err, depth = 0; e !== void 0 && e !== null && depth < 4; e = e.cause, depth++) {
|
|
1954
|
+
const code = e.code;
|
|
1955
|
+
if (typeof code === "string") return code;
|
|
1956
|
+
}
|
|
1957
|
+
return void 0;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// ../sdk/src/volumes.ts
|
|
1961
|
+
import { z as z6 } from "zod";
|
|
1962
|
+
var volume = (name, rest = "") => `/volumes/${encodeURIComponent(name)}${rest}`;
|
|
1963
|
+
var Volumes = class {
|
|
1964
|
+
constructor(transport) {
|
|
1965
|
+
this.transport = transport;
|
|
1966
|
+
}
|
|
1967
|
+
transport;
|
|
1968
|
+
list(opts = {}) {
|
|
1969
|
+
return this.transport.request("GET", `/volumes${listQuery(opts)}`, z6.array(VolumeSchema), { org: opts.org });
|
|
1970
|
+
}
|
|
1971
|
+
/**
|
|
1972
|
+
* Make a volume of `sizeGib` GiB. Through the cloud `box` is required: the volume is made on that
|
|
1973
|
+
* box's host (it attaches only to a box there). It is not attached yet: call `attach`.
|
|
1974
|
+
*/
|
|
1975
|
+
create(req, opts = {}) {
|
|
1976
|
+
return this.transport.request("POST", "/volumes", VolumeSchema, { body: req, org: opts.org });
|
|
1977
|
+
}
|
|
1978
|
+
/** Attach the volume to `box`; a running box restarts to take it, a hibernated one is refused. The answer is the box. */
|
|
1979
|
+
attach(name, box2, opts = {}) {
|
|
1980
|
+
return this.transport.request("POST", volume(name, "/attach"), MachineSchema, { body: { box: box2 }, org: opts.org });
|
|
1981
|
+
}
|
|
1982
|
+
/** Detach it from `box` (restarting a running box); the data stays on the volume. */
|
|
1983
|
+
detach(name, box2, opts = {}) {
|
|
1984
|
+
return this.transport.request("POST", volume(name, "/detach"), MachineSchema, { body: { box: box2 }, org: opts.org });
|
|
1985
|
+
}
|
|
1986
|
+
/** Grow the volume to `sizeGib` (never shrinks); a running box that holds it restarts. */
|
|
1987
|
+
grow(name, sizeGib, opts = {}) {
|
|
1988
|
+
return this.transport.request("POST", volume(name, "/resize"), VolumeSchema, { body: { sizeGib }, org: opts.org });
|
|
1989
|
+
}
|
|
1990
|
+
/** Remove the volume and its data; it must be detached first. */
|
|
1991
|
+
async remove(name, opts = {}) {
|
|
1992
|
+
await this.transport.request("DELETE", volume(name), z6.undefined(), { org: opts.org });
|
|
1993
|
+
}
|
|
1994
|
+
};
|
|
1995
|
+
|
|
1996
|
+
// ../sdk/src/client.ts
|
|
1997
|
+
var DEFAULT_BASE_URL = "https://api.kvbox.sh";
|
|
1998
|
+
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
1999
|
+
function fromEnv(name) {
|
|
2000
|
+
try {
|
|
2001
|
+
const env = globalThis.process?.env;
|
|
2002
|
+
const value = env?.[name]?.trim();
|
|
2003
|
+
return value === void 0 || value === "" ? void 0 : value;
|
|
2004
|
+
} catch {
|
|
2005
|
+
return void 0;
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
var withScheme = (url) => /^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`;
|
|
2009
|
+
var Kvbox = class {
|
|
2010
|
+
machines;
|
|
2011
|
+
snapshots;
|
|
2012
|
+
volumes;
|
|
2013
|
+
transport;
|
|
2014
|
+
constructor(opts = {}) {
|
|
2015
|
+
this.transport = new Transport({
|
|
2016
|
+
baseUrl: withScheme(opts.baseUrl ?? fromEnv("KVBOX_URL") ?? DEFAULT_BASE_URL),
|
|
2017
|
+
apiKey: opts.apiKey ?? fromEnv("KVBOX_TOKEN"),
|
|
2018
|
+
org: opts.org,
|
|
2019
|
+
fetch: opts.fetch ?? ((url, init) => globalThis.fetch(url, init)),
|
|
2020
|
+
timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
2021
|
+
});
|
|
2022
|
+
this.machines = new Machines(this.transport);
|
|
2023
|
+
this.snapshots = new Snapshots(this.transport);
|
|
2024
|
+
this.volumes = new Volumes(this.transport);
|
|
2025
|
+
}
|
|
2026
|
+
/** The API this client talks to, without a trailing slash. */
|
|
2027
|
+
get baseUrl() {
|
|
2028
|
+
return this.transport.baseUrl;
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Any route of the API, for what the namespaces do not cover yet: `method path`, the JSON answer
|
|
2032
|
+
* checked with `schema` (an empty answer is `undefined`). Errors are the SDK's, as everywhere.
|
|
2033
|
+
*/
|
|
2034
|
+
request(method, path, schema, opts = {}) {
|
|
2035
|
+
return this.transport.request(method, path, schema, opts);
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
|
|
2039
|
+
// src/client.ts
|
|
2040
|
+
import { z as z11 } from "zod";
|
|
2041
|
+
|
|
2042
|
+
// ../shared/src/managed.ts
|
|
2043
|
+
import { z as z8 } from "zod";
|
|
1516
2044
|
|
|
1517
2045
|
// ../shared/src/usage.ts
|
|
1518
|
-
import { z as
|
|
1519
|
-
var PricingSchema =
|
|
1520
|
-
currency:
|
|
1521
|
-
vcpuHour:
|
|
1522
|
-
ramGibHour:
|
|
1523
|
-
diskGibHour:
|
|
1524
|
-
volumeHour:
|
|
1525
|
-
volumeGibHour:
|
|
1526
|
-
diskIncludedGib:
|
|
2046
|
+
import { z as z7 } from "zod";
|
|
2047
|
+
var PricingSchema = z7.object({
|
|
2048
|
+
currency: z7.string().min(1),
|
|
2049
|
+
vcpuHour: z7.number().nonnegative(),
|
|
2050
|
+
ramGibHour: z7.number().nonnegative(),
|
|
2051
|
+
diskGibHour: z7.number().nonnegative(),
|
|
2052
|
+
volumeHour: z7.number().nonnegative().default(0),
|
|
2053
|
+
volumeGibHour: z7.number().nonnegative().default(0),
|
|
2054
|
+
diskIncludedGib: z7.number().int().nonnegative().default(0),
|
|
1527
2055
|
/**
|
|
1528
2056
|
* Object storage (#182): an hour of a slug's storage existing, whatever it holds, which covers its
|
|
1529
2057
|
* hidden box and the first `storageIncludedGib` of its size; each GiB above that is `storageGibHour`.
|
|
1530
2058
|
* A price list from before object storage charges nothing for it.
|
|
1531
2059
|
*/
|
|
1532
|
-
storageHour:
|
|
1533
|
-
storageGibHour:
|
|
1534
|
-
storageIncludedGib:
|
|
2060
|
+
storageHour: z7.number().nonnegative().default(0),
|
|
2061
|
+
storageGibHour: z7.number().nonnegative().default(0),
|
|
2062
|
+
storageIncludedGib: z7.number().int().nonnegative().default(0),
|
|
1535
2063
|
/** The cron service (#190): an hour of one cron service existing, whatever it holds or fires. A price list from before it charges nothing. */
|
|
1536
|
-
cronHour:
|
|
2064
|
+
cronHour: z7.number().nonnegative().default(0)
|
|
1537
2065
|
});
|
|
1538
|
-
var PriceListSchema = PricingSchema.extend({ welcomeCredit:
|
|
2066
|
+
var PriceListSchema = PricingSchema.extend({ welcomeCredit: z7.number().nonnegative() });
|
|
1539
2067
|
var HOUR_MS = 36e5;
|
|
1540
2068
|
var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
|
|
1541
2069
|
function costOf(t, pricing) {
|
|
@@ -1563,250 +2091,250 @@ function sumUsage(items, pricing) {
|
|
|
1563
2091
|
var DAY_MS = 24 * HOUR_MS;
|
|
1564
2092
|
|
|
1565
2093
|
// ../shared/src/managed.ts
|
|
1566
|
-
var PriceSchema =
|
|
1567
|
-
var ManagedCatalogEntrySchema =
|
|
2094
|
+
var PriceSchema = z8.object({ perMonth: z8.number(), storagePerMonth: z8.number(), currency: z8.string() });
|
|
2095
|
+
var ManagedCatalogEntrySchema = z8.object({
|
|
1568
2096
|
/** The kind, as in `/managed/<kind>`: `postgres`. */
|
|
1569
|
-
kind:
|
|
2097
|
+
kind: z8.string(),
|
|
1570
2098
|
/** The CLI command for it: `pg` (`kvbox pg create …`). */
|
|
1571
|
-
command:
|
|
1572
|
-
title:
|
|
1573
|
-
description:
|
|
2099
|
+
command: z8.string(),
|
|
2100
|
+
title: z8.string(),
|
|
2101
|
+
description: z8.string(),
|
|
1574
2102
|
/** The version a new one runs, as shown: `18`. */
|
|
1575
|
-
version:
|
|
2103
|
+
version: z8.string(),
|
|
1576
2104
|
/** The port a linked box reaches it on. */
|
|
1577
|
-
port:
|
|
2105
|
+
port: z8.number().int(),
|
|
1578
2106
|
/** The port `public on` opens behind a host port: `port` again unless the kind serves TLS on another. */
|
|
1579
|
-
publicPort:
|
|
2107
|
+
publicPort: z8.number().int(),
|
|
1580
2108
|
/** Its guide, as a URL. */
|
|
1581
|
-
docs:
|
|
1582
|
-
storage:
|
|
2109
|
+
docs: z8.string().optional(),
|
|
2110
|
+
storage: z8.object({ defaultGib: z8.number().int(), minGib: z8.number().int(), maxGib: z8.number().int() }),
|
|
1583
2111
|
/**
|
|
1584
2112
|
* What create takes of this kind alone, beside what every kind takes (name, password, storage, near): a
|
|
1585
2113
|
* flag and a form field each, all optional, `default` in words.
|
|
1586
2114
|
*/
|
|
1587
|
-
options:
|
|
2115
|
+
options: z8.array(z8.object({ name: z8.string(), title: z8.string(), description: z8.string(), default: z8.string() })),
|
|
1588
2116
|
/** A month of it running with the default storage, and each further GB of storage. */
|
|
1589
|
-
price: PriceSchema.extend({ storageGibPerMonth:
|
|
2117
|
+
price: PriceSchema.extend({ storageGibPerMonth: z8.number() }),
|
|
1590
2118
|
/** Whether a host answering now can run it. */
|
|
1591
|
-
available:
|
|
2119
|
+
available: z8.boolean()
|
|
1592
2120
|
});
|
|
1593
|
-
var CreateManagedRequest =
|
|
1594
|
-
name:
|
|
2121
|
+
var CreateManagedRequest = z8.object({
|
|
2122
|
+
name: z8.string(),
|
|
1595
2123
|
/** The kind's own options by name (its catalog entry lists them); the kind checks them. */
|
|
1596
|
-
options:
|
|
1597
|
-
password:
|
|
1598
|
-
storageGib:
|
|
2124
|
+
options: z8.record(z8.string(), z8.string()).optional(),
|
|
2125
|
+
password: z8.string().optional(),
|
|
2126
|
+
storageGib: z8.number().int().optional(),
|
|
1599
2127
|
/** Place it on the host of this box, so the box can be linked to it. */
|
|
1600
|
-
near:
|
|
2128
|
+
near: z8.string().optional()
|
|
1601
2129
|
});
|
|
1602
|
-
var ManagedHealthSchema =
|
|
2130
|
+
var ManagedHealthSchema = z8.object({
|
|
1603
2131
|
/** Its first start has finished: it has set itself up on its storage. */
|
|
1604
|
-
ready:
|
|
2132
|
+
ready: z8.boolean(),
|
|
1605
2133
|
/** It accepts connections. */
|
|
1606
|
-
accepting:
|
|
1607
|
-
version:
|
|
2134
|
+
accepting: z8.boolean(),
|
|
2135
|
+
version: z8.string(),
|
|
1608
2136
|
/** The storage volume: what is used of it and its size. */
|
|
1609
|
-
storageUsedBytes:
|
|
1610
|
-
storageTotalBytes:
|
|
2137
|
+
storageUsedBytes: z8.number().optional(),
|
|
2138
|
+
storageTotalBytes: z8.number().optional(),
|
|
1611
2139
|
/** What else the kind reports, ready to show: `{title: "Connections", value: "3"}`. */
|
|
1612
|
-
facts:
|
|
2140
|
+
facts: z8.array(z8.object({ title: z8.string(), value: z8.string() }))
|
|
1613
2141
|
});
|
|
1614
|
-
var UrlsSchema =
|
|
1615
|
-
var ManagedSchema =
|
|
1616
|
-
kind:
|
|
1617
|
-
name:
|
|
2142
|
+
var UrlsSchema = z8.object({ private: z8.string(), public: z8.string().optional() });
|
|
2143
|
+
var ManagedSchema = z8.object({
|
|
2144
|
+
kind: z8.string(),
|
|
2145
|
+
name: z8.string(),
|
|
1618
2146
|
/** The owning slug, bare. */
|
|
1619
|
-
owner:
|
|
1620
|
-
ownerKind:
|
|
2147
|
+
owner: z8.string(),
|
|
2148
|
+
ownerKind: z8.enum(["user", "org"]),
|
|
1621
2149
|
/** `running`, `stopped` (storage only is charged), `hibernated` or `standby` (out of credit), `unknown` (its host does not answer). */
|
|
1622
2150
|
status: BoxStatusSchema,
|
|
1623
2151
|
/** The catalog version: `18`. */
|
|
1624
|
-
version:
|
|
2152
|
+
version: z8.string(),
|
|
1625
2153
|
/** What the kind keeps of its create options, defaults filled in: `{database, user}` for Postgres, `{}` for a kind with none. */
|
|
1626
|
-
settings:
|
|
1627
|
-
storageGib:
|
|
2154
|
+
settings: z8.record(z8.string(), z8.string()),
|
|
2155
|
+
storageGib: z8.number().int(),
|
|
1628
2156
|
/** Where a linked box reaches it: `<name>.<slug>.kvbox` (resolves from a box of any slug it is linked to) and the port. */
|
|
1629
|
-
private:
|
|
2157
|
+
private: z8.object({ host: z8.string(), port: z8.number().int() }),
|
|
1630
2158
|
/** Where the internet reaches it, null while it is not public. The port is its own for its whole life. */
|
|
1631
|
-
public:
|
|
2159
|
+
public: z8.object({ host: z8.string(), port: z8.number().int() }).nullable(),
|
|
1632
2160
|
/** The boxes linked to it, as the caller would name them. */
|
|
1633
|
-
links:
|
|
2161
|
+
links: z8.array(z8.string()),
|
|
1634
2162
|
/** The name of the host it runs on, for `--near` and links. */
|
|
1635
|
-
host:
|
|
1636
|
-
country:
|
|
1637
|
-
createdBy:
|
|
1638
|
-
createdAt:
|
|
2163
|
+
host: z8.string(),
|
|
2164
|
+
country: z8.string().optional(),
|
|
2165
|
+
createdBy: z8.string().nullable(),
|
|
2166
|
+
createdAt: z8.string(),
|
|
1639
2167
|
/** Connection strings with the password as `****`. */
|
|
1640
2168
|
urls: UrlsSchema,
|
|
1641
2169
|
price: PriceSchema,
|
|
1642
2170
|
/** Only in `GET /managed/<kind>/<name>` (asked live): null when it is not running or did not answer. */
|
|
1643
2171
|
health: ManagedHealthSchema.nullable().optional()
|
|
1644
2172
|
});
|
|
1645
|
-
var ManagedSecretSchema =
|
|
2173
|
+
var ManagedSecretSchema = z8.object({ password: z8.string(), urls: UrlsSchema });
|
|
1646
2174
|
var CreatedManagedSchema = ManagedSchema.extend({ secret: ManagedSecretSchema });
|
|
1647
|
-
var ResetPasswordRequest =
|
|
1648
|
-
var SetPublicRequest =
|
|
1649
|
-
var ManagedLinkRequest =
|
|
1650
|
-
var GrowManagedRequest =
|
|
2175
|
+
var ResetPasswordRequest = z8.object({ password: z8.string().optional() });
|
|
2176
|
+
var SetPublicRequest = z8.object({ on: z8.boolean() });
|
|
2177
|
+
var ManagedLinkRequest = z8.object({ box: z8.string() });
|
|
2178
|
+
var GrowManagedRequest = z8.object({ storageGib: z8.number().int() });
|
|
1651
2179
|
|
|
1652
2180
|
// ../shared/src/cron.ts
|
|
1653
|
-
import { z as
|
|
2181
|
+
import { z as z9 } from "zod";
|
|
1654
2182
|
var DEFAULT_CRON_COMMAND_TIMEOUT_SEC = 600;
|
|
1655
2183
|
var MAX_CRON_COMMAND_TIMEOUT_SEC = 3600;
|
|
1656
2184
|
var CRON_RUN_LOG_DIR = "/var/log/kvbox/runs";
|
|
1657
2185
|
var CRON_METHODS = ["GET", "POST"];
|
|
1658
2186
|
var CRON_OUTCOMES = ["running", "ok", "failed", "timeout", "no-credit", "box-stopped", "host-down", "host-outdated", "lost", "still-running", "box-outdated"];
|
|
1659
|
-
var CronServiceSchema =
|
|
1660
|
-
owner:
|
|
1661
|
-
ownerKind:
|
|
1662
|
-
name:
|
|
2187
|
+
var CronServiceSchema = z9.object({
|
|
2188
|
+
owner: z9.string(),
|
|
2189
|
+
ownerKind: z9.enum(["user", "org"]),
|
|
2190
|
+
name: z9.string(),
|
|
1663
2191
|
/** Runs kept per trigger. */
|
|
1664
|
-
keepRuns:
|
|
1665
|
-
triggers:
|
|
1666
|
-
createdBy:
|
|
1667
|
-
createdAt:
|
|
2192
|
+
keepRuns: z9.number().int(),
|
|
2193
|
+
triggers: z9.number().int(),
|
|
2194
|
+
createdBy: z9.string().nullable(),
|
|
2195
|
+
createdAt: z9.string(),
|
|
1668
2196
|
/** What it costs while it exists; on the answer to `POST /cron` only. */
|
|
1669
|
-
price:
|
|
2197
|
+
price: z9.object({ perMonth: z9.number(), currency: z9.string() }).optional()
|
|
1670
2198
|
});
|
|
1671
2199
|
var triggerCommon = {
|
|
1672
|
-
id:
|
|
1673
|
-
service:
|
|
1674
|
-
owner:
|
|
2200
|
+
id: z9.string(),
|
|
2201
|
+
service: z9.string(),
|
|
2202
|
+
owner: z9.string(),
|
|
1675
2203
|
/** The box it acts on; a trigger is removed with its box. */
|
|
1676
|
-
box:
|
|
2204
|
+
box: z9.string(),
|
|
1677
2205
|
/** Five fields, `minute hour day-of-month month day-of-week`. */
|
|
1678
|
-
expr:
|
|
2206
|
+
expr: z9.string(),
|
|
1679
2207
|
/** An IANA zone (`Europe/Bucharest`) the expression is read in; `UTC` unless said. */
|
|
1680
|
-
timezone:
|
|
2208
|
+
timezone: z9.string(),
|
|
1681
2209
|
/** False: paused, it fires again when resumed. */
|
|
1682
|
-
enabled:
|
|
2210
|
+
enabled: z9.boolean(),
|
|
1683
2211
|
/** When it fires next (ISO); null while paused. */
|
|
1684
|
-
nextRunAt:
|
|
1685
|
-
lastRunAt:
|
|
1686
|
-
lastOutcome:
|
|
1687
|
-
createdBy:
|
|
1688
|
-
createdAt:
|
|
2212
|
+
nextRunAt: z9.string().nullable(),
|
|
2213
|
+
lastRunAt: z9.string().nullable(),
|
|
2214
|
+
lastOutcome: z9.enum(CRON_OUTCOMES).nullable(),
|
|
2215
|
+
createdBy: z9.string().nullable(),
|
|
2216
|
+
createdAt: z9.string()
|
|
1689
2217
|
};
|
|
1690
|
-
var CronHttpTriggerSchema =
|
|
2218
|
+
var CronHttpTriggerSchema = z9.object({
|
|
1691
2219
|
...triggerCommon,
|
|
1692
|
-
kind:
|
|
1693
|
-
method:
|
|
1694
|
-
port:
|
|
2220
|
+
kind: z9.literal("http"),
|
|
2221
|
+
method: z9.enum(CRON_METHODS),
|
|
2222
|
+
port: z9.number().int(),
|
|
1695
2223
|
/** Path and query, starting with `/`. */
|
|
1696
|
-
path:
|
|
2224
|
+
path: z9.string()
|
|
1697
2225
|
});
|
|
1698
|
-
var CronCommandTriggerSchema =
|
|
2226
|
+
var CronCommandTriggerSchema = z9.object({
|
|
1699
2227
|
...triggerCommon,
|
|
1700
|
-
kind:
|
|
2228
|
+
kind: z9.literal("command"),
|
|
1701
2229
|
/** Run by a login shell as the box's user, in its home. */
|
|
1702
|
-
command:
|
|
2230
|
+
command: z9.string(),
|
|
1703
2231
|
/** The command is stopped after this long. */
|
|
1704
|
-
timeoutSec:
|
|
2232
|
+
timeoutSec: z9.number().int()
|
|
1705
2233
|
});
|
|
1706
|
-
var CronTriggerSchema =
|
|
1707
|
-
var CronRunSchema =
|
|
2234
|
+
var CronTriggerSchema = z9.discriminatedUnion("kind", [CronHttpTriggerSchema, CronCommandTriggerSchema]);
|
|
2235
|
+
var CronRunSchema = z9.object({
|
|
1708
2236
|
/** The slot this run was for (ISO); a run asked for by hand has the moment it was asked. */
|
|
1709
|
-
scheduledFor:
|
|
1710
|
-
startedAt:
|
|
2237
|
+
scheduledFor: z9.string(),
|
|
2238
|
+
startedAt: z9.string(),
|
|
1711
2239
|
/** Null while `running`, and for a run that was never sent. */
|
|
1712
|
-
durationMs:
|
|
2240
|
+
durationMs: z9.number().int().nullable(),
|
|
1713
2241
|
/** The box's HTTP status; null when it never answered, and for a command. */
|
|
1714
|
-
status:
|
|
2242
|
+
status: z9.number().int().nullable(),
|
|
1715
2243
|
/** A command's exit code (128 + the signal when one ended it); null until it ends, and for a request. */
|
|
1716
|
-
exitCode:
|
|
1717
|
-
/** The
|
|
1718
|
-
output:
|
|
1719
|
-
outcome:
|
|
2244
|
+
exitCode: z9.number().int().nullable(),
|
|
2245
|
+
/** The files in the box that hold what a command printed (a shell pattern, `cron-<n>.*`); null for a request and for a command that never started. */
|
|
2246
|
+
output: z9.string().nullable(),
|
|
2247
|
+
outcome: z9.enum(CRON_OUTCOMES),
|
|
1720
2248
|
/** Why it did not end `ok`, in a line. */
|
|
1721
|
-
error:
|
|
2249
|
+
error: z9.string().nullable(),
|
|
1722
2250
|
/** The box was hibernated and this run woke it. */
|
|
1723
|
-
woke:
|
|
2251
|
+
woke: z9.boolean()
|
|
1724
2252
|
});
|
|
1725
|
-
var CronCatalogSchema =
|
|
1726
|
-
price:
|
|
1727
|
-
maxServices:
|
|
1728
|
-
maxTriggers:
|
|
1729
|
-
keepRuns:
|
|
2253
|
+
var CronCatalogSchema = z9.object({
|
|
2254
|
+
price: z9.object({ perMonth: z9.number(), currency: z9.string() }),
|
|
2255
|
+
maxServices: z9.number().int(),
|
|
2256
|
+
maxTriggers: z9.number().int(),
|
|
2257
|
+
keepRuns: z9.number().int(),
|
|
1730
2258
|
/** The shortest time between two runs of one trigger, in seconds. */
|
|
1731
|
-
minIntervalSeconds:
|
|
2259
|
+
minIntervalSeconds: z9.number().int(),
|
|
1732
2260
|
/** How long a box has to answer, in seconds. */
|
|
1733
|
-
timeoutSeconds:
|
|
2261
|
+
timeoutSeconds: z9.number().int(),
|
|
1734
2262
|
/** How long a command may run: unless the trigger says, and at most. */
|
|
1735
|
-
commandTimeoutSeconds:
|
|
1736
|
-
maxCommandTimeoutSeconds:
|
|
1737
|
-
docs:
|
|
1738
|
-
});
|
|
1739
|
-
var CreateCronServiceRequest =
|
|
1740
|
-
var CreateCronTriggerRequest =
|
|
1741
|
-
box:
|
|
1742
|
-
expr:
|
|
1743
|
-
timezone:
|
|
2263
|
+
commandTimeoutSeconds: z9.number().int(),
|
|
2264
|
+
maxCommandTimeoutSeconds: z9.number().int(),
|
|
2265
|
+
docs: z9.string().optional()
|
|
2266
|
+
});
|
|
2267
|
+
var CreateCronServiceRequest = z9.object({ name: z9.string() });
|
|
2268
|
+
var CreateCronTriggerRequest = z9.object({
|
|
2269
|
+
box: z9.string().min(1),
|
|
2270
|
+
expr: z9.string().min(1),
|
|
2271
|
+
timezone: z9.string().optional(),
|
|
1744
2272
|
/** A request: `port`, with `method` and `path`. */
|
|
1745
|
-
method:
|
|
1746
|
-
port:
|
|
1747
|
-
path:
|
|
2273
|
+
method: z9.enum(CRON_METHODS).optional(),
|
|
2274
|
+
port: z9.number().int().min(1).max(65535).optional(),
|
|
2275
|
+
path: z9.string().optional(),
|
|
1748
2276
|
/** Or a command, with `timeoutSec`; exactly one of `port` and `command`. */
|
|
1749
|
-
command:
|
|
1750
|
-
timeoutSec:
|
|
2277
|
+
command: z9.string().optional(),
|
|
2278
|
+
timeoutSec: z9.number().int().optional()
|
|
1751
2279
|
});
|
|
1752
|
-
var UpdateCronTriggerRequest =
|
|
2280
|
+
var UpdateCronTriggerRequest = z9.object({ enabled: z9.boolean() });
|
|
1753
2281
|
var cronTarget = (t) => t.kind === "command" ? `${t.box}$ ${t.command}` : `${t.method} ${t.box}:${t.port}${t.path}`;
|
|
1754
2282
|
|
|
1755
2283
|
// ../shared/src/storage.ts
|
|
1756
|
-
import { z as
|
|
1757
|
-
var RegionSchema =
|
|
1758
|
-
var ObjectStorageSchema =
|
|
1759
|
-
owner:
|
|
1760
|
-
ownerKind:
|
|
2284
|
+
import { z as z10 } from "zod";
|
|
2285
|
+
var RegionSchema = z10.object({ name: z10.string(), country: z10.string().nullable() });
|
|
2286
|
+
var ObjectStorageSchema = z10.object({
|
|
2287
|
+
owner: z10.string(),
|
|
2288
|
+
ownerKind: z10.enum(["user", "org"]),
|
|
1761
2289
|
/** `https://s3-<slug>.<domain>`: what an S3 client is given, with path-style addressing. Null while the address is not claimed. */
|
|
1762
|
-
endpoint:
|
|
2290
|
+
endpoint: z10.string().nullable(),
|
|
1763
2291
|
/** The S3 region every client of it signs with (`ro-west-1`): its host's when it was made. */
|
|
1764
|
-
region:
|
|
2292
|
+
region: z10.string(),
|
|
1765
2293
|
/** The most it may hold. */
|
|
1766
|
-
sizeGib:
|
|
2294
|
+
sizeGib: z10.number().int(),
|
|
1767
2295
|
/** `running` when it answers; `unknown` while its host is not heard from. */
|
|
1768
2296
|
status: BoxStatusSchema,
|
|
1769
2297
|
/** With `?live=1`, when the storage answered: what is on its disk, and the disk's real size. */
|
|
1770
|
-
usedBytes:
|
|
1771
|
-
totalBytes:
|
|
1772
|
-
host:
|
|
1773
|
-
country:
|
|
1774
|
-
buckets:
|
|
1775
|
-
price:
|
|
1776
|
-
createdAt:
|
|
1777
|
-
});
|
|
1778
|
-
var BucketSchema =
|
|
1779
|
-
name:
|
|
1780
|
-
owner:
|
|
1781
|
-
ownerKind:
|
|
1782
|
-
endpoint:
|
|
1783
|
-
region:
|
|
1784
|
-
keys:
|
|
1785
|
-
objects:
|
|
1786
|
-
bytes:
|
|
1787
|
-
createdBy:
|
|
1788
|
-
createdAt:
|
|
1789
|
-
});
|
|
1790
|
-
var CreateBucketRequest =
|
|
1791
|
-
name:
|
|
1792
|
-
sizeGib:
|
|
1793
|
-
near:
|
|
1794
|
-
region:
|
|
1795
|
-
});
|
|
1796
|
-
var CreatedBucketSchema = BucketSchema.extend({ storage: ObjectStorageSchema, storageCreated:
|
|
2298
|
+
usedBytes: z10.number().optional(),
|
|
2299
|
+
totalBytes: z10.number().optional(),
|
|
2300
|
+
host: z10.string(),
|
|
2301
|
+
country: z10.string().optional(),
|
|
2302
|
+
buckets: z10.number().int(),
|
|
2303
|
+
price: z10.object({ perMonth: z10.number(), currency: z10.string() }),
|
|
2304
|
+
createdAt: z10.string()
|
|
2305
|
+
});
|
|
2306
|
+
var BucketSchema = z10.object({
|
|
2307
|
+
name: z10.string(),
|
|
2308
|
+
owner: z10.string(),
|
|
2309
|
+
ownerKind: z10.enum(["user", "org"]),
|
|
2310
|
+
endpoint: z10.string().nullable(),
|
|
2311
|
+
region: z10.string(),
|
|
2312
|
+
keys: z10.number().int(),
|
|
2313
|
+
objects: z10.number().optional(),
|
|
2314
|
+
bytes: z10.number().optional(),
|
|
2315
|
+
createdBy: z10.string().nullable(),
|
|
2316
|
+
createdAt: z10.string()
|
|
2317
|
+
});
|
|
2318
|
+
var CreateBucketRequest = z10.object({
|
|
2319
|
+
name: z10.string(),
|
|
2320
|
+
sizeGib: z10.number().int().optional(),
|
|
2321
|
+
near: z10.string().optional(),
|
|
2322
|
+
region: z10.string().optional()
|
|
2323
|
+
});
|
|
2324
|
+
var CreatedBucketSchema = BucketSchema.extend({ storage: ObjectStorageSchema, storageCreated: z10.boolean() });
|
|
1797
2325
|
var BucketInfoSchema = BucketSchema.extend({ storage: ObjectStorageSchema });
|
|
1798
|
-
var BucketKeySchema =
|
|
1799
|
-
id:
|
|
1800
|
-
name:
|
|
1801
|
-
bucket:
|
|
1802
|
-
owner:
|
|
1803
|
-
readOnly:
|
|
1804
|
-
createdBy:
|
|
1805
|
-
createdAt:
|
|
1806
|
-
});
|
|
1807
|
-
var CreateBucketKeyRequest =
|
|
1808
|
-
var CreatedBucketKeySchema = BucketKeySchema.extend({ secret:
|
|
1809
|
-
var GrowStorageRequest =
|
|
2326
|
+
var BucketKeySchema = z10.object({
|
|
2327
|
+
id: z10.string(),
|
|
2328
|
+
name: z10.string(),
|
|
2329
|
+
bucket: z10.string(),
|
|
2330
|
+
owner: z10.string(),
|
|
2331
|
+
readOnly: z10.boolean(),
|
|
2332
|
+
createdBy: z10.string().nullable(),
|
|
2333
|
+
createdAt: z10.string()
|
|
2334
|
+
});
|
|
2335
|
+
var CreateBucketKeyRequest = z10.object({ name: z10.string().optional(), readOnly: z10.boolean().optional() });
|
|
2336
|
+
var CreatedBucketKeySchema = BucketKeySchema.extend({ secret: z10.string(), endpoint: z10.string().nullable(), region: z10.string() });
|
|
2337
|
+
var GrowStorageRequest = z10.object({ sizeGib: z10.number().int() });
|
|
1810
2338
|
|
|
1811
2339
|
// src/kvm.ts
|
|
1812
2340
|
import { accessSync, constants, readFileSync, statSync } from "fs";
|
|
@@ -1882,11 +2410,11 @@ function orgOption(opts) {
|
|
|
1882
2410
|
async function resolveTarget(opts, p = paths()) {
|
|
1883
2411
|
if (!opts.local) {
|
|
1884
2412
|
const org = orgOption(opts);
|
|
1885
|
-
const
|
|
1886
|
-
if (
|
|
1887
|
-
const asking = new ServerClient({ kind: "cloud", ...
|
|
2413
|
+
const fromEnv2 = envLogin();
|
|
2414
|
+
if (fromEnv2) {
|
|
2415
|
+
const asking = new ServerClient({ kind: "cloud", ...fromEnv2, env: true }, { autoStart: false });
|
|
1888
2416
|
const user = await asking.me().finally(() => asking.close());
|
|
1889
|
-
return { kind: "cloud", ...
|
|
2417
|
+
return { kind: "cloud", ...fromEnv2, env: true, user: user.username, ...org === void 0 ? {} : { org } };
|
|
1890
2418
|
}
|
|
1891
2419
|
const session = await readSession(p);
|
|
1892
2420
|
if (session) return { kind: "cloud", url: session.url, token: session.token, user: session.user, ...org === void 0 ? {} : { org } };
|
|
@@ -1898,35 +2426,42 @@ var ServerClient = class {
|
|
|
1898
2426
|
constructor(target, opts = {}) {
|
|
1899
2427
|
this.target = target;
|
|
1900
2428
|
this.autoStart = opts.autoStart ?? true;
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
}
|
|
2429
|
+
const limits = { headersTimeout: 0, bodyTimeout: 0 };
|
|
2430
|
+
this.dispatcher = target.kind === "local" ? new Agent({ ...limits, connect: { socketPath: target.socketPath } }) : new Agent(limits);
|
|
2431
|
+
const dispatcher = this.dispatcher;
|
|
2432
|
+
const fetch2 = async (url, init) => {
|
|
2433
|
+
const res = await request(url, { dispatcher, method: init.method, headers: init.headers, body: init.body ?? null, signal: init.signal ?? null });
|
|
2434
|
+
return { status: res.statusCode, text: () => res.body.text() };
|
|
2435
|
+
};
|
|
2436
|
+
this.sdk = new Kvbox({
|
|
2437
|
+
baseUrl: target.kind === "local" ? "http://kvbox" : target.url,
|
|
2438
|
+
// never the environment's: the target already says which key, if any (`--local` has none)
|
|
2439
|
+
apiKey: target.kind === "cloud" ? target.token : "",
|
|
2440
|
+
fetch: fetch2
|
|
2441
|
+
});
|
|
1908
2442
|
}
|
|
1909
2443
|
target;
|
|
1910
2444
|
dispatcher;
|
|
1911
|
-
|
|
2445
|
+
/** The SDK, which sends every request (one copy of the HTTP code); this class keeps the CLI's wording. */
|
|
2446
|
+
sdk;
|
|
1912
2447
|
autoStart;
|
|
1913
2448
|
startedOnce = false;
|
|
1914
2449
|
async call(method, path, schema, body, org = this.target.kind === "cloud" ? this.target.org : void 0, timeoutMs) {
|
|
1915
|
-
const headers = {};
|
|
1916
|
-
if (body !== void 0) headers["content-type"] = "application/json";
|
|
1917
|
-
if (this.target.kind === "cloud" && this.target.token !== "") headers["authorization"] = `Bearer ${this.target.token}`;
|
|
1918
|
-
if (this.target.kind === "cloud" && org !== void 0) headers["x-kvbox-org"] = org;
|
|
1919
|
-
let res;
|
|
1920
2450
|
try {
|
|
1921
|
-
|
|
1922
|
-
dispatcher: this.dispatcher,
|
|
1923
|
-
method,
|
|
1924
|
-
headers,
|
|
1925
|
-
body: body === void 0 ? null : JSON.stringify(body),
|
|
1926
|
-
...timeoutMs !== void 0 ? { headersTimeout: timeoutMs, bodyTimeout: timeoutMs } : {}
|
|
1927
|
-
});
|
|
2451
|
+
return await this.sdk.request(method, path, schema, { body, org: this.target.kind === "cloud" ? org : void 0, timeoutMs });
|
|
1928
2452
|
} catch (err) {
|
|
1929
|
-
|
|
2453
|
+
return this.failed(err, () => this.call(method, path, schema, body, org, timeoutMs));
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
/** The SDK's error in the CLI's words; nothing listening locally starts the daemon once and `retry`s (architecture: "auto-start"). */
|
|
2457
|
+
async failed(err, retry) {
|
|
2458
|
+
const where = this.target.kind === "cloud" ? hostOf(this.target.url) : "kvbox-server";
|
|
2459
|
+
if (err instanceof KvboxTimeoutError) {
|
|
2460
|
+
if (this.target.kind === "local") throw new KvboxError(`kvbox-server did not answer within ${Math.round(err.timeoutMs / 1e3)}s`);
|
|
2461
|
+
throw new CallError(cloudDown(this.target.url, "timeout"), 0);
|
|
2462
|
+
}
|
|
2463
|
+
if (err instanceof KvboxConnectionError) {
|
|
2464
|
+
const code = err.code ?? (err.cause instanceof Error ? err.cause.message : err.message);
|
|
1930
2465
|
if (this.target.kind === "local") {
|
|
1931
2466
|
if (this.autoStart && !this.startedOnce) {
|
|
1932
2467
|
this.startedOnce = true;
|
|
@@ -1934,31 +2469,29 @@ var ServerClient = class {
|
|
|
1934
2469
|
await spin("starting kvbox-server\u2026", startLocalServer(paths(), 5e3)).catch((err2) => {
|
|
1935
2470
|
throw noLogin && err2 instanceof KvboxError && err2.message === NOT_A_HOST_HINT ? new KvboxError(NOT_LOGGED_IN) : err2;
|
|
1936
2471
|
});
|
|
1937
|
-
return
|
|
2472
|
+
return retry();
|
|
1938
2473
|
}
|
|
1939
|
-
throw new KvboxError(`kvbox-server is not running (${
|
|
2474
|
+
throw new KvboxError(`kvbox-server is not running (${code}); start it with: kvbox-server start -d`);
|
|
1940
2475
|
}
|
|
1941
|
-
throw new CallError(cloudDown(this.target.url,
|
|
2476
|
+
throw new CallError(cloudDown(this.target.url, code), 0);
|
|
1942
2477
|
}
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
if (res.statusCode >= 300) {
|
|
1946
|
-
const parsed = ApiErrorSchema.safeParse(safeJson(text2) ?? {});
|
|
1947
|
-
if (!parsed.success) throw new CallError(`${where} answered ${res.statusCode}`, res.statusCode);
|
|
2478
|
+
if (err instanceof KvboxApiError) {
|
|
2479
|
+
if (!err.apiError) throw new CallError(`${where} answered ${err.status}`, err.status);
|
|
1948
2480
|
if (this.target.kind === "cloud" && this.target.token !== "") {
|
|
1949
|
-
if (
|
|
2481
|
+
if (err.status === 401) {
|
|
1950
2482
|
throw new KvboxError(this.target.env ? `${where} refused the API key in KVBOX_TOKEN: it was removed or has expired` : "session expired: kvbox login");
|
|
1951
2483
|
}
|
|
1952
|
-
if (
|
|
1953
|
-
throw new KvboxError(`${
|
|
2484
|
+
if (err.status === 404 && this.target.org !== void 0 && err.message === `org ${this.target.org}: not found`) {
|
|
2485
|
+
throw new KvboxError(`${err.message} (you are not in it, or it is gone)`);
|
|
1954
2486
|
}
|
|
1955
2487
|
}
|
|
1956
|
-
throw new CallError(
|
|
2488
|
+
throw new CallError(err.message, err.status, err.status === 501 ? 2 : 1);
|
|
1957
2489
|
}
|
|
1958
|
-
if (
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
2490
|
+
if (err instanceof KvboxResponseError) {
|
|
2491
|
+
if (err.reason === "schema") throw err.cause;
|
|
2492
|
+
throw new KvboxError(err.reason === "cut-off" ? `${where} answered ${err.status} but the answer was cut off` : `${where} answered ${err.status} with something that is not JSON`);
|
|
2493
|
+
}
|
|
2494
|
+
throw err;
|
|
1962
2495
|
}
|
|
1963
2496
|
health() {
|
|
1964
2497
|
return this.call("GET", "/health", HealthSchema);
|
|
@@ -1971,7 +2504,7 @@ var ServerClient = class {
|
|
|
1971
2504
|
* `all`: every box on the platform (platform admins only, #78).
|
|
1972
2505
|
*/
|
|
1973
2506
|
listMachines(opts = {}) {
|
|
1974
|
-
return this.call("GET", `/machines${allQuery(opts)}`,
|
|
2507
|
+
return this.call("GET", `/machines${allQuery(opts)}`, z11.array(MachineSchema), void 0, opts.org);
|
|
1975
2508
|
}
|
|
1976
2509
|
createMachine(req) {
|
|
1977
2510
|
return this.call("POST", "/machines", MachineSchema, req);
|
|
@@ -2025,10 +2558,10 @@ var ServerClient = class {
|
|
|
2025
2558
|
}
|
|
2026
2559
|
/** Backups, the control plane's only: a box's disk in object storage. Newest first. */
|
|
2027
2560
|
listBackups() {
|
|
2028
|
-
return this.call("GET", "/backups",
|
|
2561
|
+
return this.call("GET", "/backups", z11.array(BackupSchema));
|
|
2029
2562
|
}
|
|
2030
2563
|
boxBackups(name) {
|
|
2031
|
-
return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`,
|
|
2564
|
+
return this.call("GET", `/machines/${encodeURIComponent(name)}/backups`, z11.array(BackupSchema));
|
|
2032
2565
|
}
|
|
2033
2566
|
boxBackup(name, id) {
|
|
2034
2567
|
return this.call("GET", `/machines/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, BackupSchema);
|
|
@@ -2039,10 +2572,10 @@ var ServerClient = class {
|
|
|
2039
2572
|
}
|
|
2040
2573
|
/** A volume's backups (#168): the same as a box's, of the volume's disk. Newest first. */
|
|
2041
2574
|
listVolumeBackups() {
|
|
2042
|
-
return this.call("GET", "/backups?kind=volume",
|
|
2575
|
+
return this.call("GET", "/backups?kind=volume", z11.array(VolumeBackupSchema));
|
|
2043
2576
|
}
|
|
2044
2577
|
volumeBackups(name) {
|
|
2045
|
-
return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups`,
|
|
2578
|
+
return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups`, z11.array(VolumeBackupSchema));
|
|
2046
2579
|
}
|
|
2047
2580
|
volumeBackup(name, id) {
|
|
2048
2581
|
return this.call("GET", `/volumes/${encodeURIComponent(name)}/backups/${encodeURIComponent(id)}`, VolumeBackupSchema);
|
|
@@ -2061,7 +2594,7 @@ var ServerClient = class {
|
|
|
2061
2594
|
}
|
|
2062
2595
|
/** Wake hooks (#101), the control plane's only: a URL and a secret that wake the box. */
|
|
2063
2596
|
boxHooks(name) {
|
|
2064
|
-
return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`,
|
|
2597
|
+
return this.call("GET", `/machines/${encodeURIComponent(name)}/hooks`, z11.array(WakeHookSchema));
|
|
2065
2598
|
}
|
|
2066
2599
|
createBoxHook(name) {
|
|
2067
2600
|
return this.call("POST", `/machines/${encodeURIComponent(name)}/hooks`, CreatedWakeHookSchema);
|
|
@@ -2089,7 +2622,7 @@ var ServerClient = class {
|
|
|
2089
2622
|
}
|
|
2090
2623
|
/** Every readable box's subdomains, one entry each. */
|
|
2091
2624
|
listSubdomains() {
|
|
2092
|
-
return this.call("GET", "/subdomains",
|
|
2625
|
+
return this.call("GET", "/subdomains", z11.array(SubdomainSchema));
|
|
2093
2626
|
}
|
|
2094
2627
|
/** Custom domains (#89), the control plane's only: serve the box at the user's own name. */
|
|
2095
2628
|
addDomain(name, req) {
|
|
@@ -2100,7 +2633,7 @@ var ServerClient = class {
|
|
|
2100
2633
|
}
|
|
2101
2634
|
/** Every readable box's custom domains. */
|
|
2102
2635
|
listDomains() {
|
|
2103
|
-
return this.call("GET", "/domains",
|
|
2636
|
+
return this.call("GET", "/domains", z11.array(DomainSchema));
|
|
2104
2637
|
}
|
|
2105
2638
|
/** A running box's own load, memory and disk, asked of its guest (#67). */
|
|
2106
2639
|
machineStats(name) {
|
|
@@ -2129,22 +2662,22 @@ var ServerClient = class {
|
|
|
2129
2662
|
return this.call("POST", "/billing/redeem", RedeemResponseSchema, { code });
|
|
2130
2663
|
}
|
|
2131
2664
|
deleteMachine(name) {
|
|
2132
|
-
return this.call("DELETE", `/machines/${encodeURIComponent(name)}`,
|
|
2665
|
+
return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z11.undefined());
|
|
2133
2666
|
}
|
|
2134
2667
|
/** Like `listMachines`, for snapshots. */
|
|
2135
2668
|
listSnapshots(opts = {}) {
|
|
2136
|
-
return this.call("GET", `/snapshots${allQuery(opts)}`,
|
|
2669
|
+
return this.call("GET", `/snapshots${allQuery(opts)}`, z11.array(SnapshotSchema), void 0, opts.org);
|
|
2137
2670
|
}
|
|
2138
2671
|
createSnapshot(req) {
|
|
2139
2672
|
return this.call("POST", "/snapshots", SnapshotSchema, req);
|
|
2140
2673
|
}
|
|
2141
2674
|
deleteSnapshot(name) {
|
|
2142
|
-
return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`,
|
|
2675
|
+
return this.call("DELETE", `/snapshots/${encodeURIComponent(name)}`, z11.undefined());
|
|
2143
2676
|
}
|
|
2144
2677
|
// ---- environment variables (#88), a control plane only: the caller's slug, or `--org`'s ----
|
|
2145
2678
|
/** `org`: that org's list instead of `--org`'s (or the caller's own). */
|
|
2146
2679
|
listEnv(org) {
|
|
2147
|
-
return this.call("GET", "/vars",
|
|
2680
|
+
return this.call("GET", "/vars", z11.array(EnvVarSchema), void 0, org);
|
|
2148
2681
|
}
|
|
2149
2682
|
setEnv(name, req) {
|
|
2150
2683
|
return this.call("PUT", `/vars/${encodeURIComponent(name)}`, EnvChangeSchema, req);
|
|
@@ -2164,13 +2697,13 @@ var ServerClient = class {
|
|
|
2164
2697
|
}
|
|
2165
2698
|
// ---- volumes (#52) ----
|
|
2166
2699
|
listVolumes(opts = {}) {
|
|
2167
|
-
return this.call("GET", `/volumes${allQuery(opts)}`,
|
|
2700
|
+
return this.call("GET", `/volumes${allQuery(opts)}`, z11.array(VolumeSchema), void 0, opts.org);
|
|
2168
2701
|
}
|
|
2169
2702
|
createVolume(req) {
|
|
2170
2703
|
return this.call("POST", "/volumes", VolumeSchema, req);
|
|
2171
2704
|
}
|
|
2172
2705
|
deleteVolume(name) {
|
|
2173
|
-
return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`,
|
|
2706
|
+
return this.call("DELETE", `/volumes/${encodeURIComponent(name)}`, z11.undefined());
|
|
2174
2707
|
}
|
|
2175
2708
|
/** Both answer with the box as it is afterwards (restarted when it was running). */
|
|
2176
2709
|
attachVolume(name, req) {
|
|
@@ -2185,7 +2718,7 @@ var ServerClient = class {
|
|
|
2185
2718
|
}
|
|
2186
2719
|
// ---- cron service (#190): the control plane's alone ----
|
|
2187
2720
|
listCronServices(opts = {}) {
|
|
2188
|
-
return this.call("GET", `/cron${allQuery(opts)}`,
|
|
2721
|
+
return this.call("GET", `/cron${allQuery(opts)}`, z11.array(CronServiceSchema), void 0, opts.org);
|
|
2189
2722
|
}
|
|
2190
2723
|
createCronService(name) {
|
|
2191
2724
|
return this.call("POST", "/cron", CronServiceSchema, { name });
|
|
@@ -2194,10 +2727,10 @@ var ServerClient = class {
|
|
|
2194
2727
|
return this.call("GET", `/cron/${encodeURIComponent(name)}`, CronServiceSchema);
|
|
2195
2728
|
}
|
|
2196
2729
|
deleteCronService(name) {
|
|
2197
|
-
return this.call("DELETE", `/cron/${encodeURIComponent(name)}`,
|
|
2730
|
+
return this.call("DELETE", `/cron/${encodeURIComponent(name)}`, z11.undefined());
|
|
2198
2731
|
}
|
|
2199
2732
|
listCronTriggers(service) {
|
|
2200
|
-
return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers`,
|
|
2733
|
+
return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers`, z11.array(CronTriggerSchema));
|
|
2201
2734
|
}
|
|
2202
2735
|
addCronTrigger(service, req) {
|
|
2203
2736
|
return this.call("POST", `/cron/${encodeURIComponent(service)}/triggers`, CronTriggerSchema, req);
|
|
@@ -2207,18 +2740,18 @@ var ServerClient = class {
|
|
|
2207
2740
|
return this.call("PATCH", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`, CronTriggerSchema, { enabled: enabled2 });
|
|
2208
2741
|
}
|
|
2209
2742
|
deleteCronTrigger(service, id) {
|
|
2210
|
-
return this.call("DELETE", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`,
|
|
2743
|
+
return this.call("DELETE", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}`, z11.undefined());
|
|
2211
2744
|
}
|
|
2212
2745
|
/** Marks it due: kvbox-cron fires it within a few seconds. */
|
|
2213
2746
|
runCronTrigger(service, id) {
|
|
2214
2747
|
return this.call("POST", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/run`, CronTriggerSchema);
|
|
2215
2748
|
}
|
|
2216
2749
|
listCronRuns(service, id, limit) {
|
|
2217
|
-
return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/runs${limit === void 0 ? "" : `?limit=${limit}`}`,
|
|
2750
|
+
return this.call("GET", `/cron/${encodeURIComponent(service)}/triggers/${encodeURIComponent(id)}/runs${limit === void 0 ? "" : `?limit=${limit}`}`, z11.array(CronRunSchema));
|
|
2218
2751
|
}
|
|
2219
2752
|
// ---- object storage (#182): the control plane's alone ----
|
|
2220
2753
|
listBuckets(opts = {}) {
|
|
2221
|
-
return this.call("GET", `/buckets${allQuery(opts)}`,
|
|
2754
|
+
return this.call("GET", `/buckets${allQuery(opts)}`, z11.array(BucketSchema), void 0, opts.org);
|
|
2222
2755
|
}
|
|
2223
2756
|
/** The first bucket of a slug also makes its storage: a box boots twice, so this may take a couple of minutes. */
|
|
2224
2757
|
createBucket(req) {
|
|
@@ -2228,19 +2761,19 @@ var ServerClient = class {
|
|
|
2228
2761
|
return this.call("GET", `/buckets/${encodeURIComponent(name)}`, BucketInfoSchema);
|
|
2229
2762
|
}
|
|
2230
2763
|
deleteBucket(name, force = false) {
|
|
2231
|
-
return this.call("DELETE", `/buckets/${encodeURIComponent(name)}${force ? "?force=1" : ""}`,
|
|
2764
|
+
return this.call("DELETE", `/buckets/${encodeURIComponent(name)}${force ? "?force=1" : ""}`, z11.undefined());
|
|
2232
2765
|
}
|
|
2233
2766
|
listBucketKeys(name) {
|
|
2234
|
-
return this.call("GET", `/buckets/${encodeURIComponent(name)}/keys`,
|
|
2767
|
+
return this.call("GET", `/buckets/${encodeURIComponent(name)}/keys`, z11.array(BucketKeySchema));
|
|
2235
2768
|
}
|
|
2236
2769
|
createBucketKey(name, req) {
|
|
2237
2770
|
return this.call("POST", `/buckets/${encodeURIComponent(name)}/keys`, CreatedBucketKeySchema, req);
|
|
2238
2771
|
}
|
|
2239
2772
|
deleteBucketKey(name, id) {
|
|
2240
|
-
return this.call("DELETE", `/buckets/${encodeURIComponent(name)}/keys/${encodeURIComponent(id)}`,
|
|
2773
|
+
return this.call("DELETE", `/buckets/${encodeURIComponent(name)}/keys/${encodeURIComponent(id)}`, z11.undefined());
|
|
2241
2774
|
}
|
|
2242
2775
|
listStorage(opts = {}) {
|
|
2243
|
-
return this.call("GET", `/storage${allQuery(opts)}`,
|
|
2776
|
+
return this.call("GET", `/storage${allQuery(opts)}`, z11.array(ObjectStorageSchema), void 0, opts.org);
|
|
2244
2777
|
}
|
|
2245
2778
|
growStorage(sizeGib) {
|
|
2246
2779
|
return this.call("POST", "/storage/grow", ObjectStorageSchema, { sizeGib });
|
|
@@ -2250,11 +2783,11 @@ var ServerClient = class {
|
|
|
2250
2783
|
return `/managed/${encodeURIComponent(kind)}${name === void 0 ? "" : `/${encodeURIComponent(name)}`}${rest}`;
|
|
2251
2784
|
}
|
|
2252
2785
|
managedCatalog() {
|
|
2253
|
-
return this.call("GET", "/managed/catalog",
|
|
2786
|
+
return this.call("GET", "/managed/catalog", z11.array(ManagedCatalogEntrySchema));
|
|
2254
2787
|
}
|
|
2255
2788
|
/** One kind's services, or every kind's when `kind` is left out. */
|
|
2256
2789
|
listManaged(kind, opts = {}) {
|
|
2257
|
-
return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`,
|
|
2790
|
+
return this.call("GET", `${kind === void 0 ? "/managed" : this.managedPath(kind)}${allQuery(opts)}`, z11.array(ManagedSchema), void 0, opts.org);
|
|
2258
2791
|
}
|
|
2259
2792
|
createManaged(kind, req) {
|
|
2260
2793
|
return this.call("POST", this.managedPath(kind), CreatedManagedSchema, req);
|
|
@@ -2264,7 +2797,7 @@ var ServerClient = class {
|
|
|
2264
2797
|
return this.call("GET", this.managedPath(kind, name), ManagedSchema);
|
|
2265
2798
|
}
|
|
2266
2799
|
deleteManaged(kind, name) {
|
|
2267
|
-
return this.call("DELETE", this.managedPath(kind, name),
|
|
2800
|
+
return this.call("DELETE", this.managedPath(kind, name), z11.undefined());
|
|
2268
2801
|
}
|
|
2269
2802
|
managedPassword(kind, name) {
|
|
2270
2803
|
return this.call("GET", this.managedPath(kind, name, "/password"), ManagedSecretSchema);
|
|
@@ -2275,11 +2808,11 @@ var ServerClient = class {
|
|
|
2275
2808
|
setManagedPublic(kind, name, on) {
|
|
2276
2809
|
return this.call("POST", this.managedPath(kind, name, "/public"), ManagedSchema, { on });
|
|
2277
2810
|
}
|
|
2278
|
-
linkManaged(kind, name,
|
|
2279
|
-
return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
|
|
2811
|
+
linkManaged(kind, name, box2) {
|
|
2812
|
+
return this.call("POST", this.managedPath(kind, name, "/links"), ManagedSchema, { box: box2 });
|
|
2280
2813
|
}
|
|
2281
|
-
unlinkManaged(kind, name,
|
|
2282
|
-
return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box });
|
|
2814
|
+
unlinkManaged(kind, name, box2) {
|
|
2815
|
+
return this.call("DELETE", this.managedPath(kind, name, "/links"), ManagedSchema, { box: box2 });
|
|
2283
2816
|
}
|
|
2284
2817
|
growManaged(kind, name, storageGib) {
|
|
2285
2818
|
return this.call("POST", this.managedPath(kind, name, "/grow"), ManagedSchema, { storageGib });
|
|
@@ -2302,24 +2835,24 @@ var ServerClient = class {
|
|
|
2302
2835
|
return this.call("POST", "/login/device/token", DeviceLoginPollSchema, { deviceCode });
|
|
2303
2836
|
}
|
|
2304
2837
|
logout() {
|
|
2305
|
-
return this.call("POST", "/logout",
|
|
2838
|
+
return this.call("POST", "/logout", z11.unknown()).then(() => void 0);
|
|
2306
2839
|
}
|
|
2307
2840
|
me() {
|
|
2308
2841
|
return this.call("GET", "/me", MeResponseSchema);
|
|
2309
2842
|
}
|
|
2310
2843
|
// ---- API keys (`kvbox key …`, #189) ----
|
|
2311
2844
|
listApiKeys() {
|
|
2312
|
-
return this.call("GET", "/keys",
|
|
2845
|
+
return this.call("GET", "/keys", z11.array(ApiKeySchema));
|
|
2313
2846
|
}
|
|
2314
2847
|
createApiKey(req) {
|
|
2315
2848
|
return this.call("POST", "/keys", CreatedApiKeySchema, req);
|
|
2316
2849
|
}
|
|
2317
2850
|
deleteApiKey(name) {
|
|
2318
|
-
return this.call("DELETE", `/keys/${encodeURIComponent(name)}`,
|
|
2851
|
+
return this.call("DELETE", `/keys/${encodeURIComponent(name)}`, z11.unknown()).then(() => void 0);
|
|
2319
2852
|
}
|
|
2320
2853
|
// ---- orgs (`kvbox org …`) ----
|
|
2321
2854
|
listOrgs() {
|
|
2322
|
-
return this.call("GET", "/orgs",
|
|
2855
|
+
return this.call("GET", "/orgs", z11.array(OrgMembershipSchema));
|
|
2323
2856
|
}
|
|
2324
2857
|
createOrg(req) {
|
|
2325
2858
|
return this.call("POST", "/orgs", CloudOrgSchema, req);
|
|
@@ -2328,16 +2861,16 @@ var ServerClient = class {
|
|
|
2328
2861
|
return this.call("GET", `/orgs/${encodeURIComponent(slug)}`, OrgDetailSchema);
|
|
2329
2862
|
}
|
|
2330
2863
|
deleteOrg(slug) {
|
|
2331
|
-
return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`,
|
|
2864
|
+
return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}`, z11.undefined());
|
|
2332
2865
|
}
|
|
2333
2866
|
addMember(slug, req) {
|
|
2334
|
-
return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`,
|
|
2867
|
+
return this.call("POST", `/orgs/${encodeURIComponent(slug)}/members`, z11.undefined(), req);
|
|
2335
2868
|
}
|
|
2336
2869
|
setRole(slug, username, role) {
|
|
2337
|
-
return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`,
|
|
2870
|
+
return this.call("PATCH", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z11.unknown(), { role }).then(() => void 0);
|
|
2338
2871
|
}
|
|
2339
2872
|
removeMember(slug, username) {
|
|
2340
|
-
return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`,
|
|
2873
|
+
return this.call("DELETE", `/orgs/${encodeURIComponent(slug)}/members/${encodeURIComponent(username)}`, z11.undefined());
|
|
2341
2874
|
}
|
|
2342
2875
|
/** Sign this machine's key again (#51); the key must be one the user logged in with. */
|
|
2343
2876
|
sshCert(req) {
|
|
@@ -2371,15 +2904,8 @@ function cloudDown(url, code) {
|
|
|
2371
2904
|
const hint = host.endsWith("kvbox.sh") ? "check status.kvbox.sh" : "use --local for this machine, or kvbox logout";
|
|
2372
2905
|
return `${host} is not available or is down (${code}). You are logged in there, so kvbox talks to it instead of this machine; ${hint}`;
|
|
2373
2906
|
}
|
|
2374
|
-
function
|
|
2375
|
-
|
|
2376
|
-
return JSON.parse(text2);
|
|
2377
|
-
} catch {
|
|
2378
|
-
return void 0;
|
|
2379
|
-
}
|
|
2380
|
-
}
|
|
2381
|
-
async function wakeUp(client, box, name) {
|
|
2382
|
-
switch (box.status) {
|
|
2907
|
+
async function wakeUp(client, box2, name) {
|
|
2908
|
+
switch (box2.status) {
|
|
2383
2909
|
case "standby":
|
|
2384
2910
|
info(`box ${name} is in standby; resuming it`);
|
|
2385
2911
|
return spin(`resuming ${name}\u2026`, client.resumeMachine(name));
|
|
@@ -2390,7 +2916,7 @@ async function wakeUp(client, box, name) {
|
|
|
2390
2916
|
info(`box ${name} is stopped; starting it`);
|
|
2391
2917
|
return spin(`booting ${name}\u2026`, client.startMachine(name));
|
|
2392
2918
|
default:
|
|
2393
|
-
return
|
|
2919
|
+
return box2;
|
|
2394
2920
|
}
|
|
2395
2921
|
}
|
|
2396
2922
|
function boxesFor(client, text2) {
|
|
@@ -2402,10 +2928,10 @@ var me = (client) => client.target.kind === "cloud" ? client.target.user : void
|
|
|
2402
2928
|
async function clientFor(opts, client = {}) {
|
|
2403
2929
|
return new ServerClient(await resolveTarget(opts), client);
|
|
2404
2930
|
}
|
|
2405
|
-
function sshEndpoint(
|
|
2406
|
-
if (target.kind === "local" || direct) return { host:
|
|
2407
|
-
if (
|
|
2408
|
-
return { ...
|
|
2931
|
+
function sshEndpoint(box2, target, direct = false) {
|
|
2932
|
+
if (target.kind === "local" || direct) return { host: box2.ip, port: 22, user: BOX_SSH_USER };
|
|
2933
|
+
if (box2.ssh === void 0) throw new KvboxError(`box ${box2.name} has no public SSH port`);
|
|
2934
|
+
return { ...box2.ssh, alias: `${box2.id}.${box2.ssh.host}` };
|
|
2409
2935
|
}
|
|
2410
2936
|
function sshArgs(ep, p = paths()) {
|
|
2411
2937
|
const hostKey = ep.alias === void 0 ? ["-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null"] : ["-o", "StrictHostKeyChecking=accept-new", "-o", `UserKnownHostsFile=${p.sshKnownHosts}`, "-o", `HostKeyAlias=${ep.alias}`];
|
|
@@ -2513,12 +3039,12 @@ async function serving(p, timeoutMs, check) {
|
|
|
2513
3039
|
await probe.close();
|
|
2514
3040
|
}
|
|
2515
3041
|
}
|
|
2516
|
-
await
|
|
3042
|
+
await sleep2(100);
|
|
2517
3043
|
}
|
|
2518
3044
|
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
2519
3045
|
}
|
|
2520
|
-
function subdomainPath(
|
|
2521
|
-
return `/machines/${encodeURIComponent(
|
|
3046
|
+
function subdomainPath(box2, path, sub) {
|
|
3047
|
+
return `/machines/${encodeURIComponent(box2)}/subdomain${path}${sub !== void 0 ? `?sub=${encodeURIComponent(sub)}` : ""}`;
|
|
2522
3048
|
}
|
|
2523
3049
|
|
|
2524
3050
|
// src/prompt.ts
|
|
@@ -2793,7 +3319,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
|
|
|
2793
3319
|
}
|
|
2794
3320
|
try {
|
|
2795
3321
|
const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}${opts.base !== void 0 && opts.base !== "base" ? ` from image ${opts.base}` : ""}\u2026`;
|
|
2796
|
-
const
|
|
3322
|
+
const box2 = await spin(what, client.createMachine({
|
|
2797
3323
|
...name !== void 0 ? { name } : {},
|
|
2798
3324
|
...opts.size !== void 0 ? { size: opts.size } : {},
|
|
2799
3325
|
...opts.from !== void 0 ? { from: opts.from } : {},
|
|
@@ -2805,54 +3331,54 @@ var newCommand = new Command("new").description("boot a new box from an image (t
|
|
|
2805
3331
|
...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
|
|
2806
3332
|
...opts.force ? { force: true } : {}
|
|
2807
3333
|
}));
|
|
2808
|
-
if (autoHibernateSec && !
|
|
2809
|
-
if (opts.base !== void 0 && opts.base !== "base" &&
|
|
2810
|
-
warn(`box ${
|
|
3334
|
+
if (autoHibernateSec && !box2.autoHibernateSec) warn(`box ${name ?? box2.name}: its host runs a kvbox-server too old for auto-hibernate; it will not hibernate on its own`);
|
|
3335
|
+
if (opts.base !== void 0 && opts.base !== "base" && box2.image === void 0) {
|
|
3336
|
+
warn(`box ${box2.name}: its host runs a kvbox-server too old for images; it booted the base image, not ${opts.base}`);
|
|
2811
3337
|
}
|
|
2812
3338
|
if (env.length > 0) {
|
|
2813
|
-
const kept = await keptVars(client, displayName(
|
|
2814
|
-
if (kept === "too old") warn(`box ${
|
|
2815
|
-
else if (kept !== true) warn(`box ${
|
|
3339
|
+
const kept = await keptVars(client, displayName(box2, me(client)), env.map((v) => v.name));
|
|
3340
|
+
if (kept === "too old") warn(`box ${box2.name}: its host runs a kvbox-server too old for a box's own variables; it has none of the -e ones`);
|
|
3341
|
+
else if (kept !== true) warn(`box ${box2.name}: could not check its -e variables (${kept}); kvbox env ls --box ${displayName(box2, me(client))} shows them`);
|
|
2816
3342
|
}
|
|
2817
3343
|
if (opts.json) {
|
|
2818
|
-
json(
|
|
3344
|
+
json(box2);
|
|
2819
3345
|
return;
|
|
2820
3346
|
}
|
|
2821
3347
|
const user = client.target.kind === "cloud" ? client.target.user : void 0;
|
|
2822
|
-
process.stdout.write(`${
|
|
3348
|
+
process.stdout.write(`${box2.name}
|
|
2823
3349
|
`);
|
|
2824
|
-
info(`${color.green("\u2713")} ${describe(
|
|
2825
|
-
if (opts.from !== void 0) info(` connect with: kvbox connect ${displayName(
|
|
2826
|
-
else info(` connect with: kvbox connect ${displayName(
|
|
2827
|
-
if (
|
|
2828
|
-
if (
|
|
2829
|
-
info(` reach it at: ${
|
|
2830
|
-
info(` from another box once linked: kvbox vm link <box> ${displayName(
|
|
2831
|
-
info(` its variables: kvbox env ls --box ${displayName(
|
|
2832
|
-
}
|
|
2833
|
-
if (
|
|
2834
|
-
info(` wake it on queued jobs: kvbox vm hook create ${displayName(
|
|
3350
|
+
info(`${color.green("\u2713")} ${describe(box2, user)}`);
|
|
3351
|
+
if (opts.from !== void 0) info(` connect with: kvbox connect ${displayName(box2, user)} (already up: everything that ran in the snapshot is running)`);
|
|
3352
|
+
else info(` connect with: kvbox connect ${displayName(box2, user)} (SSH is up a couple of seconds after boot)`);
|
|
3353
|
+
if (box2.autoHibernateSec) info(` it ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}`);
|
|
3354
|
+
if (box2.connect !== void 0) {
|
|
3355
|
+
info(` reach it at: ${box2.connect}`);
|
|
3356
|
+
info(` from another box once linked: kvbox vm link <box> ${displayName(box2, user)} --port <port>`);
|
|
3357
|
+
info(` its variables: kvbox env ls --box ${displayName(box2, user)}`);
|
|
3358
|
+
}
|
|
3359
|
+
if (box2.image === "gh-runner") {
|
|
3360
|
+
info(` wake it on queued jobs: kvbox vm hook create ${displayName(box2, user)}`);
|
|
2835
3361
|
info(` then add it on GitHub: Settings \u2192 Webhooks \u2192 Add webhook (the hook's URL and secret, content type application/json, event Workflow jobs)`);
|
|
2836
3362
|
}
|
|
2837
3363
|
} finally {
|
|
2838
3364
|
await client.close();
|
|
2839
3365
|
}
|
|
2840
3366
|
});
|
|
2841
|
-
async function keptVars(client,
|
|
3367
|
+
async function keptVars(client, box2, names2) {
|
|
2842
3368
|
try {
|
|
2843
|
-
const have = new Set((await client.boxEnv(
|
|
3369
|
+
const have = new Set((await client.boxEnv(box2)).vars.map((v) => v.name));
|
|
2844
3370
|
return names2.every((n) => have.has(n)) ? true : "too old";
|
|
2845
3371
|
} catch (err) {
|
|
2846
3372
|
const message = err.message;
|
|
2847
3373
|
return /no route:|too old/.test(message) ? "too old" : message;
|
|
2848
3374
|
}
|
|
2849
3375
|
}
|
|
2850
|
-
function displayName(
|
|
2851
|
-
return user !== void 0 && slugOf(
|
|
3376
|
+
function displayName(box2, user) {
|
|
3377
|
+
return user !== void 0 && slugOf(box2.owner) !== user ? `${slugOf(box2.owner)}/${box2.name}` : box2.name;
|
|
2852
3378
|
}
|
|
2853
|
-
function describe(
|
|
2854
|
-
const from =
|
|
2855
|
-
return `box ${color.bold(displayName(
|
|
3379
|
+
function describe(box2, user) {
|
|
3380
|
+
const from = box2.source.startsWith("snapshot:") ? ` from snapshot ${shortRef(box2.source.slice("snapshot:".length), box2.owner)}` : box2.source.startsWith("fork:") ? `, a fork of ${shortRef(box2.source.slice("fork:".length), box2.owner)}` : "";
|
|
3381
|
+
return `box ${color.bold(displayName(box2, user))} is ${box2.status} at ${box2.ip}${from}: ${box2.vcpu} vCPU, ${gb(box2.memMib * 1024 ** 2)} RAM, ${gb(box2.diskBytes)} disk`;
|
|
2856
3382
|
}
|
|
2857
3383
|
function autoHibernateText(sec, idleCheck) {
|
|
2858
3384
|
if (!sec) return "never hibernates on its own";
|
|
@@ -2897,13 +3423,13 @@ var connectCommand = new Command2("connect").alias("cn").description("open a she
|
|
|
2897
3423
|
let owner;
|
|
2898
3424
|
try {
|
|
2899
3425
|
const name = nameArg ?? await pickBox(client);
|
|
2900
|
-
let
|
|
2901
|
-
if (!
|
|
2902
|
-
cert = await ensureCert(client, void 0, void 0, { owner:
|
|
2903
|
-
owner =
|
|
2904
|
-
const wasRunning =
|
|
2905
|
-
if (!wasRunning)
|
|
2906
|
-
ep = sshEndpoint(
|
|
3426
|
+
let box2 = pickRef(await boxesFor(client, name), name, me(client));
|
|
3427
|
+
if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
3428
|
+
cert = await ensureCert(client, void 0, void 0, { owner: box2.owner });
|
|
3429
|
+
owner = box2.owner;
|
|
3430
|
+
const wasRunning = box2.status === "running";
|
|
3431
|
+
if (!wasRunning) box2 = await wakeUp(client, box2, displayName(box2, me(client)));
|
|
3432
|
+
ep = sshEndpoint(box2, client.target, opts.direct);
|
|
2907
3433
|
if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
|
|
2908
3434
|
else if (opts.direct) await checkDirect(ep);
|
|
2909
3435
|
} finally {
|
|
@@ -2976,14 +3502,14 @@ var execCommand = new Command3("exec").description("run a command in a box and e
|
|
|
2976
3502
|
let cert;
|
|
2977
3503
|
let owner;
|
|
2978
3504
|
try {
|
|
2979
|
-
let
|
|
2980
|
-
if (!
|
|
2981
|
-
if (
|
|
2982
|
-
cert = await ensureCert(client, void 0, void 0, { owner:
|
|
2983
|
-
owner =
|
|
2984
|
-
const wasRunning =
|
|
2985
|
-
if (!wasRunning)
|
|
2986
|
-
ep = sshEndpoint(
|
|
3505
|
+
let box2 = pickRef(await boxesFor(client, name), name, me(client));
|
|
3506
|
+
if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
3507
|
+
if (box2.status === "stopped") throw new KvboxError(`box ${name} is stopped (kvbox start ${name})`);
|
|
3508
|
+
cert = await ensureCert(client, void 0, void 0, { owner: box2.owner });
|
|
3509
|
+
owner = box2.owner;
|
|
3510
|
+
const wasRunning = box2.status === "running";
|
|
3511
|
+
if (!wasRunning) box2 = await wakeUp(client, box2, displayName(box2, me(client)));
|
|
3512
|
+
ep = sshEndpoint(box2, client.target, opts.direct);
|
|
2987
3513
|
if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
|
|
2988
3514
|
else if (opts.direct) await checkDirect(ep);
|
|
2989
3515
|
} finally {
|
|
@@ -3025,22 +3551,22 @@ var forkCommand = new Command4("fork").description("copy a box, running or stopp
|
|
|
3025
3551
|
const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
|
|
3026
3552
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3027
3553
|
try {
|
|
3028
|
-
const
|
|
3554
|
+
const box2 = await spin(`forking ${source}\u2026`, client.forkMachine(source, {
|
|
3029
3555
|
...name !== void 0 ? { name } : {},
|
|
3030
3556
|
...opts.size !== void 0 ? { size: opts.size } : {},
|
|
3031
3557
|
...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
|
|
3032
3558
|
...opts.force ? { force: true } : {}
|
|
3033
3559
|
}));
|
|
3034
3560
|
if (opts.json) {
|
|
3035
|
-
json(
|
|
3561
|
+
json(box2);
|
|
3036
3562
|
return;
|
|
3037
3563
|
}
|
|
3038
3564
|
const user = me(client);
|
|
3039
|
-
process.stdout.write(`${
|
|
3565
|
+
process.stdout.write(`${box2.name}
|
|
3040
3566
|
`);
|
|
3041
|
-
info(`${color.green("\u2713")} ${describe(
|
|
3042
|
-
info(` connect with: kvbox connect ${displayName(
|
|
3043
|
-
info(` it ${autoHibernateText(
|
|
3567
|
+
info(`${color.green("\u2713")} ${describe(box2, user)}`);
|
|
3568
|
+
info(` connect with: kvbox connect ${displayName(box2, user)}`);
|
|
3569
|
+
info(` it ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}; published ports and HTTPS names stay with ${source}`);
|
|
3044
3570
|
} finally {
|
|
3045
3571
|
await client.close();
|
|
3046
3572
|
}
|
|
@@ -3105,14 +3631,14 @@ function subdomainJson(sub, user) {
|
|
|
3105
3631
|
return { box: boxOf(sub, user), subdomain: sub.subdomain, port: sub.port, url: sub.url, routes: sub.routes };
|
|
3106
3632
|
}
|
|
3107
3633
|
function httpsRowsOf(sub, user) {
|
|
3108
|
-
const
|
|
3109
|
-
return [{ box, guestPort: sub.port, proto: "https", url: sub.url }, ...sub.routes.map((r) => ({ box, guestPort: r.port, proto: "https", url: r.url, name: r.name }))];
|
|
3634
|
+
const box2 = boxOf(sub, user);
|
|
3635
|
+
return [{ box: box2, guestPort: sub.port, proto: "https", url: sub.url }, ...sub.routes.map((r) => ({ box: box2, guestPort: r.port, proto: "https", url: r.url, name: r.name }))];
|
|
3110
3636
|
}
|
|
3111
3637
|
function requireCloud(client) {
|
|
3112
3638
|
if (client.target.kind !== "cloud") throw new KvboxError("HTTPS names need the kvbox cloud: kvbox login (this host's own socket has none)");
|
|
3113
3639
|
}
|
|
3114
|
-
function rowsOf(
|
|
3115
|
-
return (
|
|
3640
|
+
function rowsOf(box2, user, only) {
|
|
3641
|
+
return (box2.ports ?? []).filter(only ?? (() => true)).map((f) => ({ box: displayName(box2, user), ...f }));
|
|
3116
3642
|
}
|
|
3117
3643
|
function reaches(row, short = false) {
|
|
3118
3644
|
if (row.address !== void 0) return `${row.address}:${row.hostPort}`;
|
|
@@ -3136,51 +3662,51 @@ var getCommand = new Command6("get").description("show one box in full: status,
|
|
|
3136
3662
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3137
3663
|
try {
|
|
3138
3664
|
const user = me(client);
|
|
3139
|
-
const
|
|
3140
|
-
const subs = client.target.kind === "cloud" ? await subdomainsOf(client,
|
|
3665
|
+
const box2 = await findBox(client, name);
|
|
3666
|
+
const subs = client.target.kind === "cloud" ? await subdomainsOf(client, box2) : [];
|
|
3141
3667
|
if (opts.json) {
|
|
3142
|
-
json({ ...
|
|
3668
|
+
json({ ...box2, ...subs.length > 0 ? { subdomains: subs.map((s) => subdomainJson(s, user)) } : {} });
|
|
3143
3669
|
return;
|
|
3144
3670
|
}
|
|
3145
|
-
const rows2 = getRows(
|
|
3671
|
+
const rows2 = getRows(box2, subs, user);
|
|
3146
3672
|
const width2 = Math.max(...rows2.map(([k]) => k.length));
|
|
3147
3673
|
for (const [k, v] of rows2) info(`${color.dim(k.padStart(width2))} ${v}`);
|
|
3148
3674
|
} finally {
|
|
3149
3675
|
await client.close();
|
|
3150
3676
|
}
|
|
3151
3677
|
});
|
|
3152
|
-
async function subdomainsOf(client,
|
|
3678
|
+
async function subdomainsOf(client, box2) {
|
|
3153
3679
|
try {
|
|
3154
|
-
const slug = slugOf(
|
|
3155
|
-
return (await client.listSubdomains()).filter((s) => s.box ===
|
|
3680
|
+
const slug = slugOf(box2.owner);
|
|
3681
|
+
return (await client.listSubdomains()).filter((s) => s.box === box2.name && s.owner === slug);
|
|
3156
3682
|
} catch (err) {
|
|
3157
3683
|
warn(`HTTPS name not shown: ${err.message}`);
|
|
3158
3684
|
return [];
|
|
3159
3685
|
}
|
|
3160
3686
|
}
|
|
3161
|
-
function getRows(
|
|
3687
|
+
function getRows(box2, subs, user) {
|
|
3162
3688
|
const rows2 = [
|
|
3163
|
-
["name", color.bold(displayName(
|
|
3164
|
-
["status", status(
|
|
3689
|
+
["name", color.bold(displayName(box2, user))],
|
|
3690
|
+
["status", status(box2.status)]
|
|
3165
3691
|
];
|
|
3166
|
-
if (user !== void 0) rows2.push(["owner", ownerCell(
|
|
3167
|
-
if (
|
|
3168
|
-
rows2.push(["size", `${shape(
|
|
3169
|
-
rows2.push(["address",
|
|
3170
|
-
rows2.push(["ssh",
|
|
3692
|
+
if (user !== void 0) rows2.push(["owner", ownerCell(box2, user)]);
|
|
3693
|
+
if (box2.status !== "unknown") {
|
|
3694
|
+
rows2.push(["size", `${shape(box2.vcpu, box2.memMib, box2.diskBytes)} ${color.dim(`(${gb(box2.diskUsedBytes)} used)`)}`]);
|
|
3695
|
+
rows2.push(["address", box2.ssh?.host ?? (box2.ip === "" ? "-" : box2.ip)]);
|
|
3696
|
+
rows2.push(["ssh", box2.ssh ? `ssh -p ${box2.ssh.port} ${box2.ssh.user}@${box2.ssh.host}` : `kvbox connect ${displayName(box2, user)}`]);
|
|
3171
3697
|
}
|
|
3172
|
-
if (
|
|
3698
|
+
if (box2.url !== void 0) rows2.push(["connect", `${box2.url} ${color.dim("(password shown once, at new)")}`]);
|
|
3173
3699
|
const urls = subs.flatMap((sub) => [`${sub.url} ${color.dim(`(port ${sub.port})`)}`, ...sub.routes.map((r) => `${r.url} ${color.dim(`(port ${r.port})`)}`)]);
|
|
3174
3700
|
rows2.push(["url", urls.length === 0 ? "-" : urls.join(", ")]);
|
|
3175
|
-
const ports = rowsOf(
|
|
3701
|
+
const ports = rowsOf(box2, user).map((r) => `${r.guestPort}/${r.proto} \u2192 ${reaches(r, true)}`);
|
|
3176
3702
|
rows2.push(["ports", ports.length === 0 ? "-" : ports.join(", ")]);
|
|
3177
|
-
rows2.push(["volumes",
|
|
3178
|
-
const quiet =
|
|
3179
|
-
rows2.push(["auto-hibernate",
|
|
3180
|
-
if (!
|
|
3181
|
-
rows2.push(["source",
|
|
3182
|
-
rows2.push(["base",
|
|
3183
|
-
rows2.push(["created", `${age(
|
|
3703
|
+
rows2.push(["volumes", box2.volumes?.length ? box2.volumes.map((v) => `${v.name} ${color.dim(`(${v.sizeGib} GB at ${v.mountPath})`)}`).join(", ") : "-"]);
|
|
3704
|
+
const quiet = box2.idleCheck === void 0 ? "without network traffic" : `idle by ${box2.idleCheck}`;
|
|
3705
|
+
rows2.push(["auto-hibernate", box2.autoHibernateSec ? `after ${duration(box2.autoHibernateSec)} ${quiet}` : "off"]);
|
|
3706
|
+
if (!box2.autoHibernateSec && box2.idleCheck !== void 0) rows2.push(["idle check", `${box2.idleCheck} ${color.dim("(used once auto-hibernate is on)")}`]);
|
|
3707
|
+
rows2.push(["source", box2.source]);
|
|
3708
|
+
rows2.push(["base", box2.image === void 0 ? box2.base : `${box2.image} ${box2.base}`]);
|
|
3709
|
+
rows2.push(["created", `${age(box2.createdAt)} ${color.dim(`(${box2.createdAt})`)}`]);
|
|
3184
3710
|
return rows2;
|
|
3185
3711
|
}
|
|
3186
3712
|
|
|
@@ -3189,8 +3715,8 @@ import { Command as Command7 } from "commander";
|
|
|
3189
3715
|
var hibernateCommand = new Command7("hibernate").description("save a box's memory to disk and free its RAM (kvbox wake continues it where it left off)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
3190
3716
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3191
3717
|
try {
|
|
3192
|
-
const
|
|
3193
|
-
if (opts.json) json(
|
|
3718
|
+
const box2 = await spin(`hibernating ${name} (saving its memory to disk)\u2026`, client.hibernateMachine(name));
|
|
3719
|
+
if (opts.json) json(box2);
|
|
3194
3720
|
else info(`${color.green("\u2713")} box ${name} hibernated (memory saved to disk, RAM freed; kvbox wake ${name} continues it where it left off)`);
|
|
3195
3721
|
} finally {
|
|
3196
3722
|
await client.close();
|
|
@@ -3208,19 +3734,19 @@ var linkCommand = new Command8("link").description("let one box reach a port of
|
|
|
3208
3734
|
const port = parseLinkPort(opts.port);
|
|
3209
3735
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3210
3736
|
try {
|
|
3211
|
-
const
|
|
3737
|
+
const box2 = await spin(`linking ${from} to ${name}:${port}\u2026`, client.addLink(name, { from, port }));
|
|
3212
3738
|
const user = me(client);
|
|
3213
|
-
const shown = displayName(
|
|
3739
|
+
const shown = displayName(box2, user);
|
|
3214
3740
|
if (opts.json) {
|
|
3215
3741
|
json({ from, box: shown, port });
|
|
3216
3742
|
return;
|
|
3217
3743
|
}
|
|
3218
3744
|
const fromName = from.slice(from.lastIndexOf("/") + 1);
|
|
3219
|
-
const link2 =
|
|
3220
|
-
const apart = link2 !== void 0 ? link2.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(
|
|
3221
|
-
const host = apart ? `${
|
|
3745
|
+
const link2 = box2.links?.find((l) => l.port === port && l.from.slice(l.from.lastIndexOf("/") + 1) === fromName);
|
|
3746
|
+
const apart = link2 !== void 0 ? link2.from.includes("/") : from.includes("/") && from.split("/")[0] !== slugOf(box2.owner);
|
|
3747
|
+
const host = apart ? `${box2.name}.${slugOf(box2.owner)}.kvbox` : `${box2.name}.kvbox`;
|
|
3222
3748
|
info(`${color.green("\u2713")} box ${color.bold(from)} can reach ${color.bold(`${host}:${port}`)}`);
|
|
3223
|
-
if (
|
|
3749
|
+
if (box2.status !== "running") info(` box ${shown} is ${box2.status}: the link opens when it runs`);
|
|
3224
3750
|
} finally {
|
|
3225
3751
|
await client.close();
|
|
3226
3752
|
}
|
|
@@ -3237,12 +3763,12 @@ var linksCommand = new Command9("links").description("list the links between box
|
|
|
3237
3763
|
const unlisted = name === void 0 || name.includes("/") || user === void 0 ? name : `${client.target.kind === "cloud" ? client.target.org ?? user : user}/${name}`;
|
|
3238
3764
|
const wanted = picked === void 0 ? unlisted : `${slugOf(picked.owner)}/${picked.name}`;
|
|
3239
3765
|
const rows2 = machines.flatMap((b) => {
|
|
3240
|
-
const
|
|
3241
|
-
const slug =
|
|
3766
|
+
const box2 = displayName(b, user);
|
|
3767
|
+
const slug = box2.includes("/") ? box2.split("/")[0] : void 0;
|
|
3242
3768
|
return (b.links ?? []).map((l) => {
|
|
3243
3769
|
const source = l.from.includes("/") ? l.from : `${slugOf(b.owner)}/${l.from}`;
|
|
3244
3770
|
const from = slug !== void 0 && !l.from.includes("/") ? `${slug}/${l.from}` : l.from;
|
|
3245
|
-
const row = { from: user !== void 0 && from.startsWith(`${user}/`) ? from.slice(user.length + 1) : from, box, port: l.port };
|
|
3771
|
+
const row = { from: user !== void 0 && from.startsWith(`${user}/`) ? from.slice(user.length + 1) : from, box: box2, port: l.port };
|
|
3246
3772
|
return { row, ends: [`${slugOf(b.owner)}/${b.name}`, source] };
|
|
3247
3773
|
});
|
|
3248
3774
|
}).filter((r) => wanted === void 0 || r.ends.includes(wanted)).map((r) => r.row).sort((a, b) => a.box.localeCompare(b.box) || a.from.localeCompare(b.from) || a.port - b.port);
|
|
@@ -3265,8 +3791,8 @@ import { Command as Command10 } from "commander";
|
|
|
3265
3791
|
var pauseCommand = new Command10("pause").description("freeze a box in place (memory and processes kept, no CPU used; kvbox resume continues it instantly)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
3266
3792
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3267
3793
|
try {
|
|
3268
|
-
const
|
|
3269
|
-
if (opts.json) json(
|
|
3794
|
+
const box2 = await spin(`pausing ${name}\u2026`, client.pauseMachine(name));
|
|
3795
|
+
if (opts.json) json(box2);
|
|
3270
3796
|
else info(`${color.green("\u2713")} box ${name} is in standby (frozen in place; kvbox resume ${name} continues it)`);
|
|
3271
3797
|
} finally {
|
|
3272
3798
|
await client.close();
|
|
@@ -3358,16 +3884,16 @@ var claimCommand = new Command11("claim").description(`give a box an HTTPS addre
|
|
|
3358
3884
|
const [port] = parsePorts([portText]);
|
|
3359
3885
|
const user = me(client);
|
|
3360
3886
|
const found = await findBox(client, name);
|
|
3361
|
-
const
|
|
3362
|
-
const sub = await spin(`claiming ${subdomain}\u2026`, client.claimSubdomain(
|
|
3887
|
+
const box2 = displayName(found, user);
|
|
3888
|
+
const sub = await spin(`claiming ${subdomain}\u2026`, client.claimSubdomain(box2, { name: subdomain, port }));
|
|
3363
3889
|
if (opts.json) {
|
|
3364
3890
|
json(subdomainJson(sub, me(client)));
|
|
3365
3891
|
return;
|
|
3366
3892
|
}
|
|
3367
|
-
info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(
|
|
3368
|
-
info(` more ports under it: kvbox vm proxy add ${
|
|
3369
|
-
info(` another address for this box: kvbox vm proxy claim ${
|
|
3370
|
-
if (found.status !== "running") info(` box ${
|
|
3893
|
+
info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box2)} port ${sub.port}`);
|
|
3894
|
+
info(` more ports under it: kvbox vm proxy add ${box2} <port> --name <name> \u2192 https://<name>.${sub.url.replace(/^https:\/\//, "")}`);
|
|
3895
|
+
info(` another address for this box: kvbox vm proxy claim ${box2} <subdomain> --port <port>`);
|
|
3896
|
+
if (found.status !== "running") info(` box ${box2} is ${found.status}: the address answers once it runs`);
|
|
3371
3897
|
} finally {
|
|
3372
3898
|
await client.close();
|
|
3373
3899
|
}
|
|
@@ -3393,21 +3919,21 @@ var addCommand = new Command12("add").description("publish box ports on the inte
|
|
|
3393
3919
|
const user = me(client);
|
|
3394
3920
|
if (opts.name !== void 0) requireCloud(client);
|
|
3395
3921
|
const found = await findBox(client, name);
|
|
3396
|
-
const
|
|
3922
|
+
const box2 = displayName(found, user);
|
|
3397
3923
|
if (opts.name !== void 0) {
|
|
3398
3924
|
const route = opts.name;
|
|
3399
|
-
const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(
|
|
3925
|
+
const sub = await spin(`publishing ${guestPorts[0]} on ${name} as ${route}\u2026`, client.addSubdomainRoute(box2, { name: route, port: guestPorts[0] }, opts.sub));
|
|
3400
3926
|
const url = sub.routes.find((r) => r.name === route).url;
|
|
3401
3927
|
if (opts.json) {
|
|
3402
|
-
json({ box, guestPort: guestPorts[0], proto: "https", url, name: route });
|
|
3928
|
+
json({ box: box2, guestPort: guestPorts[0], proto: "https", url, name: route });
|
|
3403
3929
|
return;
|
|
3404
3930
|
}
|
|
3405
|
-
info(`${color.green("\u2713")} ${color.bold(url)} \u2192 box ${color.bold(
|
|
3931
|
+
info(`${color.green("\u2713")} ${color.bold(url)} \u2192 box ${color.bold(box2)} port ${guestPorts[0]}`);
|
|
3406
3932
|
info(" the first name under a subdomain waits for its certificate, about a minute");
|
|
3407
|
-
if (found.status !== "running") info(` box ${
|
|
3933
|
+
if (found.status !== "running") info(` box ${box2} is ${found.status}: the address answers once it runs`);
|
|
3408
3934
|
return;
|
|
3409
3935
|
}
|
|
3410
|
-
const updated = await spin(`publishing ${guestPorts.join(", ")} on ${name}\u2026`, client.addPorts(
|
|
3936
|
+
const updated = await spin(`publishing ${guestPorts.join(", ")} on ${name}\u2026`, client.addPorts(box2, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
|
|
3411
3937
|
const rows2 = rowsOf(updated, user, (f) => f.proto === proto && guestPorts.includes(f.guestPort));
|
|
3412
3938
|
if (opts.json) {
|
|
3413
3939
|
json(rows2);
|
|
@@ -3461,15 +3987,15 @@ var releaseCommand = new Command14("release").description("give up one of a box'
|
|
|
3461
3987
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3462
3988
|
try {
|
|
3463
3989
|
requireCloud(client);
|
|
3464
|
-
const
|
|
3465
|
-
if (!await confirm(`Give up ${opts.sub !== void 0 ? `${opts.sub}, one of box ${
|
|
3990
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
3991
|
+
if (!await confirm(`Give up ${opts.sub !== void 0 ? `${opts.sub}, one of box ${box2}'s HTTPS addresses,` : `box ${box2}'s HTTPS address`} and every name under it? Anyone may claim it after.`, opts.yes ?? false)) {
|
|
3466
3992
|
info("cancelled");
|
|
3467
3993
|
process.exitCode = 1;
|
|
3468
3994
|
return;
|
|
3469
3995
|
}
|
|
3470
|
-
const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(
|
|
3996
|
+
const sub = await spin(`releasing ${name}'s address\u2026`, client.releaseSubdomain(box2, opts.sub));
|
|
3471
3997
|
const names2 = sub.routes.length === 0 ? "" : ` and ${sub.routes.length} name${sub.routes.length > 1 ? "s" : ""} under it`;
|
|
3472
|
-
info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(
|
|
3998
|
+
info(`${color.green("\u2713")} ${sub.url.replace(/^https:\/\//, "")}${names2} no longer reach box ${color.bold(box2)}`);
|
|
3473
3999
|
} finally {
|
|
3474
4000
|
await client.close();
|
|
3475
4001
|
}
|
|
@@ -3491,19 +4017,19 @@ var rmCommand = new Command15("rm").description("stop publishing box ports, or a
|
|
|
3491
4017
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3492
4018
|
try {
|
|
3493
4019
|
if (opts.name !== void 0) requireCloud(client);
|
|
3494
|
-
const
|
|
3495
|
-
const question = opts.name !== void 0 ? `Stop serving ${opts.name} under box ${
|
|
4020
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4021
|
+
const question = opts.name !== void 0 ? `Stop serving ${opts.name} under box ${box2}'s subdomain?` : `Stop publishing port${guestPorts.length > 1 ? "s" : ""} ${guestPorts.join(", ")} of box ${box2}?`;
|
|
3496
4022
|
if (!await confirm(question, opts.yes ?? false)) {
|
|
3497
4023
|
info("cancelled");
|
|
3498
4024
|
process.exitCode = 1;
|
|
3499
4025
|
return;
|
|
3500
4026
|
}
|
|
3501
4027
|
if (opts.name !== void 0) {
|
|
3502
|
-
const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(
|
|
3503
|
-
info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(
|
|
4028
|
+
const sub = await spin(`freeing ${opts.name} on ${name}\u2026`, client.removeSubdomainRoute(box2, opts.name, opts.sub));
|
|
4029
|
+
info(`${color.green("\u2713")} ${opts.name}.${sub.url.replace(/^https:\/\//, "")} no longer reaches box ${color.bold(box2)}`);
|
|
3504
4030
|
return;
|
|
3505
4031
|
}
|
|
3506
|
-
await spin(`closing ${guestPorts.join(", ")} on ${name}\u2026`, client.removePorts(
|
|
4032
|
+
await spin(`closing ${guestPorts.join(", ")} on ${name}\u2026`, client.removePorts(box2, { ports: guestPorts.map((guestPort) => ({ guestPort, proto })) }));
|
|
3507
4033
|
info(`${color.green("\u2713")} box ${color.bold(name)} no longer publishes ${guestPorts.join(", ")} (${proto})`);
|
|
3508
4034
|
} finally {
|
|
3509
4035
|
await client.close();
|
|
@@ -3517,13 +4043,13 @@ var setPortCommand = new Command16("set-port").description("point a box's HTTPS
|
|
|
3517
4043
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3518
4044
|
try {
|
|
3519
4045
|
requireCloud(client);
|
|
3520
|
-
const
|
|
3521
|
-
const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(
|
|
4046
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4047
|
+
const sub = await spin(`pointing ${name} at port ${port}\u2026`, client.setSubdomainPort(box2, { port }, opts.sub));
|
|
3522
4048
|
if (opts.json) {
|
|
3523
4049
|
json(subdomainJson(sub, me(client)));
|
|
3524
4050
|
return;
|
|
3525
4051
|
}
|
|
3526
|
-
info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(
|
|
4052
|
+
info(`${color.green("\u2713")} ${color.bold(sub.url)} \u2192 box ${color.bold(box2)} port ${sub.port}`);
|
|
3527
4053
|
} finally {
|
|
3528
4054
|
await client.close();
|
|
3529
4055
|
}
|
|
@@ -3549,13 +4075,13 @@ var createCommand = new Command18("create").description("make a URL that wakes t
|
|
|
3549
4075
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3550
4076
|
try {
|
|
3551
4077
|
requireCloud2(client);
|
|
3552
|
-
const
|
|
3553
|
-
const hook = await client.createBoxHook(
|
|
4078
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4079
|
+
const hook = await client.createBoxHook(box2);
|
|
3554
4080
|
if (opts.json) {
|
|
3555
4081
|
json(hook);
|
|
3556
4082
|
return;
|
|
3557
4083
|
}
|
|
3558
|
-
info(`${color.green("\u2713")} hook ${hook.id} wakes box ${color.bold(
|
|
4084
|
+
info(`${color.green("\u2713")} hook ${hook.id} wakes box ${color.bold(box2)}`);
|
|
3559
4085
|
info(` url: ${hook.url}`);
|
|
3560
4086
|
info(` secret: ${hook.secret} ${color.dim("(shown only now)")}`);
|
|
3561
4087
|
info("");
|
|
@@ -3574,14 +4100,14 @@ var lsCommand3 = new Command19("ls").alias("list").description("list a box's wak
|
|
|
3574
4100
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3575
4101
|
try {
|
|
3576
4102
|
requireCloud2(client);
|
|
3577
|
-
const
|
|
3578
|
-
const hooks = await client.boxHooks(
|
|
4103
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4104
|
+
const hooks = await client.boxHooks(box2);
|
|
3579
4105
|
if (opts.json) {
|
|
3580
4106
|
json(hooks);
|
|
3581
4107
|
return;
|
|
3582
4108
|
}
|
|
3583
4109
|
if (hooks.length === 0) {
|
|
3584
|
-
info(`box ${
|
|
4110
|
+
info(`box ${box2} has no wake hooks; make one with: kvbox vm hook create ${box2}`);
|
|
3585
4111
|
return;
|
|
3586
4112
|
}
|
|
3587
4113
|
table(hooks.map((h) => ({ id: h.id, url: h.url, "last called": h.lastCalledAt ? age(h.lastCalledAt) : color.dim("never"), by: h.createdBy ?? "-", created: age(h.createdAt) })));
|
|
@@ -3596,18 +4122,18 @@ var rmCommand2 = new Command20("rm").alias("remove").description("remove a wake
|
|
|
3596
4122
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3597
4123
|
try {
|
|
3598
4124
|
requireCloud2(client);
|
|
3599
|
-
const
|
|
3600
|
-
if (!await confirm(`Remove hook ${id} of box ${
|
|
4125
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4126
|
+
if (!await confirm(`Remove hook ${id} of box ${box2}? Whatever calls its URL stops waking the box.`, opts.yes ?? false)) {
|
|
3601
4127
|
info("cancelled");
|
|
3602
4128
|
process.exitCode = 1;
|
|
3603
4129
|
return;
|
|
3604
4130
|
}
|
|
3605
|
-
const hook = await client.removeBoxHook(
|
|
4131
|
+
const hook = await client.removeBoxHook(box2, id);
|
|
3606
4132
|
if (opts.json) {
|
|
3607
4133
|
json(hook);
|
|
3608
4134
|
return;
|
|
3609
4135
|
}
|
|
3610
|
-
info(`${color.green("\u2713")} hook ${hook.id} removed; its URL no longer wakes box ${color.bold(
|
|
4136
|
+
info(`${color.green("\u2713")} hook ${hook.id} removed; its URL no longer wakes box ${color.bold(box2)}`);
|
|
3611
4137
|
} finally {
|
|
3612
4138
|
await client.close();
|
|
3613
4139
|
}
|
|
@@ -3624,7 +4150,7 @@ import { Command as Command25 } from "commander";
|
|
|
3624
4150
|
import { Command as Command22 } from "commander";
|
|
3625
4151
|
|
|
3626
4152
|
// src/commands/vm/backup/shared.ts
|
|
3627
|
-
import { setTimeout as
|
|
4153
|
+
import { setTimeout as sleep3 } from "timers/promises";
|
|
3628
4154
|
function requireCloud3(client) {
|
|
3629
4155
|
if (client.target.kind !== "cloud") throw new KvboxError("backups need the kvbox cloud: kvbox login (this host's own socket has none)");
|
|
3630
4156
|
}
|
|
@@ -3646,11 +4172,11 @@ async function untilSettled(ask, what, id, where, opts = {}) {
|
|
|
3646
4172
|
if (failed >= tries) throw lostTrack(`could not ask how it is doing: ${err.message}`);
|
|
3647
4173
|
}
|
|
3648
4174
|
if (Date.now() >= until2) throw lostTrack("it is taking longer than a backup is given");
|
|
3649
|
-
await
|
|
4175
|
+
await sleep3(pollMs);
|
|
3650
4176
|
}
|
|
3651
4177
|
}
|
|
3652
|
-
function untilDone(client,
|
|
3653
|
-
return untilSettled(() => client.boxBackup(
|
|
4178
|
+
function untilDone(client, box2, id, opts = {}) {
|
|
4179
|
+
return untilSettled(() => client.boxBackup(box2, id), `box ${box2}`, id, `kvbox vm backup ls ${box2}`, opts);
|
|
3654
4180
|
}
|
|
3655
4181
|
function sizeLine(b) {
|
|
3656
4182
|
const data = b.dataBytes === null ? "?" : gb(b.dataBytes);
|
|
@@ -3664,23 +4190,23 @@ var createCommand2 = new Command22("create").description("back up a box's disk t
|
|
|
3664
4190
|
try {
|
|
3665
4191
|
requireCloud3(client);
|
|
3666
4192
|
const found = await findBox(client, name);
|
|
3667
|
-
const
|
|
3668
|
-
const started = await client.createBoxBackup(
|
|
4193
|
+
const box2 = displayName(found, me(client));
|
|
4194
|
+
const started = await client.createBoxBackup(box2);
|
|
3669
4195
|
if (!opts.wait) {
|
|
3670
4196
|
if (opts.json) json(started);
|
|
3671
4197
|
else {
|
|
3672
|
-
info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(
|
|
3673
|
-
info(color.dim(` status: kvbox vm backup ls ${
|
|
4198
|
+
info(`${color.green("\u2713")} backup ${started.id} of box ${color.bold(box2)} started; it runs in the background`);
|
|
4199
|
+
info(color.dim(` status: kvbox vm backup ls ${box2}`));
|
|
3674
4200
|
}
|
|
3675
4201
|
return;
|
|
3676
4202
|
}
|
|
3677
|
-
const done = await spin(`backing up ${
|
|
4203
|
+
const done = await spin(`backing up ${box2}\u2026`, untilDone(client, box2, started.id));
|
|
3678
4204
|
if (opts.json) json(done);
|
|
3679
|
-
if (done.status === "failed") throw new KvboxError(`backup ${done.id} of box ${
|
|
4205
|
+
if (done.status === "failed") throw new KvboxError(`backup ${done.id} of box ${box2} failed: ${done.error ?? "no reason given"}`);
|
|
3680
4206
|
if (opts.json) return;
|
|
3681
|
-
info(`${color.green("\u2713")} backup ${done.id} of box ${color.bold(
|
|
4207
|
+
info(`${color.green("\u2713")} backup ${done.id} of box ${color.bold(box2)}: ${sizeLine(done)}`);
|
|
3682
4208
|
if ((found.volumes?.length ?? 0) > 0) info(color.dim(` not included: volume${found.volumes.length > 1 ? "s" : ""} ${found.volumes.map((v) => v.name).join(", ")}`));
|
|
3683
|
-
info(color.dim(` restore with: kvbox vm backup restore ${
|
|
4209
|
+
info(color.dim(` restore with: kvbox vm backup restore ${box2} ${done.id}`));
|
|
3684
4210
|
} finally {
|
|
3685
4211
|
await client.close();
|
|
3686
4212
|
}
|
|
@@ -3692,21 +4218,21 @@ var lsCommand4 = new Command23("ls").alias("list").description("list backups: ev
|
|
|
3692
4218
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3693
4219
|
try {
|
|
3694
4220
|
requireCloud3(client);
|
|
3695
|
-
const
|
|
3696
|
-
const list =
|
|
4221
|
+
const box2 = name === void 0 ? void 0 : displayName(await findBox(client, name), me(client));
|
|
4222
|
+
const list = box2 === void 0 ? await client.listBackups() : await client.boxBackups(box2);
|
|
3697
4223
|
if (opts.json) {
|
|
3698
4224
|
json(list);
|
|
3699
4225
|
return;
|
|
3700
4226
|
}
|
|
3701
4227
|
if (list.length === 0) {
|
|
3702
|
-
info(
|
|
4228
|
+
info(box2 === void 0 ? "no backups yet; make one with: kvbox vm backup create <box>" : `box ${box2} has no backups; make one with: kvbox vm backup create ${box2}`);
|
|
3703
4229
|
return;
|
|
3704
4230
|
}
|
|
3705
4231
|
const anyError = list.some((b) => b.error !== null);
|
|
3706
4232
|
table(
|
|
3707
4233
|
list.map((b) => ({
|
|
3708
4234
|
id: b.id,
|
|
3709
|
-
...
|
|
4235
|
+
...box2 === void 0 ? { box: b.owner === me(client) ? b.box : `${b.owner}/${b.box}` } : {},
|
|
3710
4236
|
status: b.status === "ready" ? color.green(b.status) : b.status === "failed" ? color.red(b.status) : color.yellow(b.status),
|
|
3711
4237
|
data: b.dataBytes === null ? "-" : gbShort(b.dataBytes),
|
|
3712
4238
|
uploaded: b.uploadedBytes === null ? "-" : gbShort(b.uploadedBytes),
|
|
@@ -3727,20 +4253,20 @@ var restoreCommand = new Command24("restore").description("put a backup back: th
|
|
|
3727
4253
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3728
4254
|
try {
|
|
3729
4255
|
requireCloud3(client);
|
|
3730
|
-
const
|
|
3731
|
-
const backup = await client.boxBackup(
|
|
3732
|
-
const question = `Restore box ${
|
|
4256
|
+
const box2 = displayName(await findBox(client, name), me(client));
|
|
4257
|
+
const backup = await client.boxBackup(box2, id);
|
|
4258
|
+
const question = `Restore box ${box2} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to its disk since is lost, and a running box restarts.`;
|
|
3733
4259
|
if (!await confirm(question, opts.yes ?? false)) {
|
|
3734
4260
|
info("cancelled");
|
|
3735
4261
|
process.exitCode = 1;
|
|
3736
4262
|
return;
|
|
3737
4263
|
}
|
|
3738
|
-
const machine = await spin(`restoring ${
|
|
4264
|
+
const machine = await spin(`restoring ${box2} from ${backup.id}\u2026`, client.restoreBoxBackup(box2, id));
|
|
3739
4265
|
if (opts.json) {
|
|
3740
4266
|
json(machine);
|
|
3741
4267
|
return;
|
|
3742
4268
|
}
|
|
3743
|
-
info(`${color.green("\u2713")} box ${color.bold(
|
|
4269
|
+
info(`${color.green("\u2713")} box ${color.bold(box2)} restored from backup ${backup.id}; it is ${machine.status}`);
|
|
3744
4270
|
} finally {
|
|
3745
4271
|
await client.close();
|
|
3746
4272
|
}
|
|
@@ -3765,17 +4291,17 @@ var rescaleCommand = new Command26("rescale").description("change a box's vCPUs,
|
|
|
3765
4291
|
try {
|
|
3766
4292
|
const before = pickRef(await boxesFor(client, name), name, me(client));
|
|
3767
4293
|
if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
3768
|
-
const
|
|
4294
|
+
const box2 = await spin(`rescaling ${name}\u2026`, client.rescaleMachine(displayName(before, me(client)), body));
|
|
3769
4295
|
if (opts.json) {
|
|
3770
|
-
json(
|
|
4296
|
+
json(box2);
|
|
3771
4297
|
return;
|
|
3772
4298
|
}
|
|
3773
|
-
const same =
|
|
4299
|
+
const same = box2.vcpu === before.vcpu && box2.memMib === before.memMib && box2.diskBytes === before.diskBytes;
|
|
3774
4300
|
if (same) {
|
|
3775
4301
|
info(`box ${name} already has that shape; nothing changed`);
|
|
3776
4302
|
return;
|
|
3777
4303
|
}
|
|
3778
|
-
info(`${color.green("\u2713")} ${describe(
|
|
4304
|
+
info(`${color.green("\u2713")} ${describe(box2)}`);
|
|
3779
4305
|
if (before.status === "running") info(" it was restarted: processes that were running are gone, files are intact");
|
|
3780
4306
|
} finally {
|
|
3781
4307
|
await client.close();
|
|
@@ -3802,8 +4328,8 @@ import { Command as Command27 } from "commander";
|
|
|
3802
4328
|
var resumeCommand = new Command27("resume").description("continue a box that is in standby (kvbox pause)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
3803
4329
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3804
4330
|
try {
|
|
3805
|
-
const
|
|
3806
|
-
if (opts.json) json(
|
|
4331
|
+
const box2 = await spin(`resuming ${name}\u2026`, client.resumeMachine(name));
|
|
4332
|
+
if (opts.json) json(box2);
|
|
3807
4333
|
else info(`${color.green("\u2713")} box ${name} resumed`);
|
|
3808
4334
|
} finally {
|
|
3809
4335
|
await client.close();
|
|
@@ -3815,16 +4341,16 @@ import { Command as Command28 } from "commander";
|
|
|
3815
4341
|
var rmCommand3 = new Command28("rm").description("destroy a box (its disk is deleted; snapshots are kept)").argument("<name>", "box name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
3816
4342
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3817
4343
|
try {
|
|
3818
|
-
const
|
|
3819
|
-
if (!
|
|
3820
|
-
const ref = displayName(
|
|
4344
|
+
const box2 = pickRef(await boxesFor(client, name), name, me(client));
|
|
4345
|
+
if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
4346
|
+
const ref = displayName(box2, me(client));
|
|
3821
4347
|
if (!await confirm(`Destroy box ${ref} and its disk?`, opts.yes ?? false)) {
|
|
3822
4348
|
info("cancelled");
|
|
3823
4349
|
process.exitCode = 1;
|
|
3824
4350
|
return;
|
|
3825
4351
|
}
|
|
3826
4352
|
await spin(`destroying ${ref}\u2026`, client.deleteMachine(ref));
|
|
3827
|
-
const volumes =
|
|
4353
|
+
const volumes = box2.volumes?.map((v) => v.name) ?? [];
|
|
3828
4354
|
info(`${color.green("\u2713")} box ${ref} destroyed${volumes.length > 0 ? `; its volume${volumes.length > 1 ? "s" : ""} ${volumes.join(", ")} ${volumes.length > 1 ? "are" : "is"} kept, detached` : ""}`);
|
|
3829
4355
|
} finally {
|
|
3830
4356
|
await client.close();
|
|
@@ -3921,20 +4447,20 @@ var setCommand = new Command29("set").description("change a box's settings, e.g.
|
|
|
3921
4447
|
const found = pickRef(await boxesFor(client, name), name, me(client));
|
|
3922
4448
|
if (!found) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
3923
4449
|
if (swapMib !== void 0 && found.status === "stopped") throw new KvboxError(`box ${name} is stopped; --swap is set up inside the box (kvbox start ${name})`);
|
|
3924
|
-
let
|
|
4450
|
+
let box2 = found;
|
|
3925
4451
|
if (hostSettings) {
|
|
3926
|
-
|
|
3927
|
-
if (!idleCheckKept(idleCheck,
|
|
4452
|
+
box2 = await spin(`updating ${name}\u2026`, client.setMachine(displayName(found, me(client)), { ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {}, ...idleCheck !== void 0 ? { idleCheck } : {} }));
|
|
4453
|
+
if (!idleCheckKept(idleCheck, box2)) {
|
|
3928
4454
|
throw new KvboxError(`box ${name}: its host runs a kvbox-server too old for --idle-check; it needs updating first${autoHibernateSec !== void 0 ? " (--auto-hibernate was applied)" : ""}`);
|
|
3929
4455
|
}
|
|
3930
4456
|
}
|
|
3931
|
-
const swap = swapMib === void 0 ? void 0 : await setSwap(client,
|
|
4457
|
+
const swap = swapMib === void 0 ? void 0 : await setSwap(client, box2, name, swapMib, cmd);
|
|
3932
4458
|
if (opts.json) {
|
|
3933
|
-
json(swap === void 0 ?
|
|
4459
|
+
json(swap === void 0 ? box2 : { ...box2, swap });
|
|
3934
4460
|
return;
|
|
3935
4461
|
}
|
|
3936
|
-
if (hostSettings) info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(
|
|
3937
|
-
if (idleCheck && !
|
|
4462
|
+
if (hostSettings) info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(box2.autoHibernateSec, box2.idleCheck)}`);
|
|
4463
|
+
if (idleCheck && !box2.autoHibernateSec) info(color.dim(` the idle check is used once auto-hibernate is on: kvbox vm set ${name} --auto-hibernate 10m`));
|
|
3938
4464
|
if (swap) info(`${color.green("\u2713")} box ${color.bold(name)}: ${swapText(swap)}`);
|
|
3939
4465
|
} finally {
|
|
3940
4466
|
await client.close();
|
|
@@ -3943,8 +4469,8 @@ var setCommand = new Command29("set").description("change a box's settings, e.g.
|
|
|
3943
4469
|
async function setSwap(client, found, name, mib, cmd) {
|
|
3944
4470
|
const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
|
|
3945
4471
|
const wasRunning = found.status === "running";
|
|
3946
|
-
const
|
|
3947
|
-
const ep = sshEndpoint(
|
|
4472
|
+
const box2 = wasRunning ? found : await wakeUp(client, found, displayName(found, me(client)));
|
|
4473
|
+
const ep = sshEndpoint(box2, client.target);
|
|
3948
4474
|
if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
|
|
3949
4475
|
const what = mib === 0 ? `removing ${name}'s swap\u2026` : `setting up ${mib >= 1024 ? `${mib / 1024}G` : `${mib}M`} of swap in ${name}\u2026`;
|
|
3950
4476
|
let result = await spin(what, runSwap(ep, mib));
|
|
@@ -3966,8 +4492,8 @@ function swapText(s) {
|
|
|
3966
4492
|
const size = s.sizeMib % 1024 === 0 ? `${s.sizeMib / 1024} GB` : `${s.sizeMib} MB`;
|
|
3967
4493
|
return `${size} swap (${s.usedMib} MB used, zswap ${s.zswap ? "on" : "off"})`;
|
|
3968
4494
|
}
|
|
3969
|
-
function idleCheckKept(asked,
|
|
3970
|
-
return asked === void 0 || (
|
|
4495
|
+
function idleCheckKept(asked, box2) {
|
|
4496
|
+
return asked === void 0 || (box2.idleCheck ?? "") === asked;
|
|
3971
4497
|
}
|
|
3972
4498
|
function parseIdleCheck(text2) {
|
|
3973
4499
|
const t = text2.trim();
|
|
@@ -3981,9 +4507,9 @@ import { Command as Command30 } from "commander";
|
|
|
3981
4507
|
var startCommand = new Command30("start").description("boot a stopped box again (same name, IP and disk)").argument("<name>", "box name").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
3982
4508
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3983
4509
|
try {
|
|
3984
|
-
const
|
|
3985
|
-
if (opts.json) json(
|
|
3986
|
-
else info(`${color.green("\u2713")} ${describe(
|
|
4510
|
+
const box2 = await spin(`booting ${name}\u2026`, client.startMachine(name, opts.force ?? false));
|
|
4511
|
+
if (opts.json) json(box2);
|
|
4512
|
+
else info(`${color.green("\u2713")} ${describe(box2)}`);
|
|
3987
4513
|
} finally {
|
|
3988
4514
|
await client.close();
|
|
3989
4515
|
}
|
|
@@ -3994,8 +4520,8 @@ import { Command as Command31 } from "commander";
|
|
|
3994
4520
|
var stopCommand = new Command31("stop").description("shut a box down (its disk is kept; start it again with kvbox start)").argument("<name>", "box name").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
3995
4521
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
3996
4522
|
try {
|
|
3997
|
-
const
|
|
3998
|
-
if (opts.json) json(
|
|
4523
|
+
const box2 = await spin(`shutting ${name} down\u2026`, client.stopMachine(name));
|
|
4524
|
+
if (opts.json) json(box2);
|
|
3999
4525
|
else info(`${color.green("\u2713")} box ${name} stopped (disk kept; kvbox start ${name} boots it again)`);
|
|
4000
4526
|
} finally {
|
|
4001
4527
|
await client.close();
|
|
@@ -4092,16 +4618,16 @@ var updateCommand = new Command34("update").description("move a box onto the cur
|
|
|
4092
4618
|
try {
|
|
4093
4619
|
const before = pickRef(await boxesFor(client, name), name, me(client));
|
|
4094
4620
|
if (!before) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
4095
|
-
const
|
|
4621
|
+
const box2 = await spin(`updating ${name}\u2026`, client.updateMachine(displayName(before, me(client))));
|
|
4096
4622
|
if (opts.json) {
|
|
4097
|
-
json(
|
|
4623
|
+
json(box2);
|
|
4098
4624
|
return;
|
|
4099
4625
|
}
|
|
4100
|
-
if (
|
|
4101
|
-
info(`box ${name} is already on base image ${
|
|
4626
|
+
if (box2.base === before.base) {
|
|
4627
|
+
info(`box ${name} is already on base image ${box2.base}`);
|
|
4102
4628
|
} else {
|
|
4103
4629
|
const restarted = before.status === "running" ? " (restarted: processes that were running are gone, files are intact)" : "";
|
|
4104
|
-
info(`${color.green("\u2713")} box ${color.bold(name)} now runs on base image ${
|
|
4630
|
+
info(`${color.green("\u2713")} box ${color.bold(name)} now runs on base image ${box2.base} (was ${before.base})${restarted}`);
|
|
4105
4631
|
}
|
|
4106
4632
|
} finally {
|
|
4107
4633
|
await client.close();
|
|
@@ -4161,8 +4687,8 @@ import { Command as Command36 } from "commander";
|
|
|
4161
4687
|
var wakeCommand = new Command36("wake").description("continue a hibernated box where it left off (same name, IP and disk)").argument("<name>", "box name").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
4162
4688
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4163
4689
|
try {
|
|
4164
|
-
const
|
|
4165
|
-
if (opts.json) json(
|
|
4690
|
+
const box2 = await spin(`waking ${name} (loading its memory from disk)\u2026`, client.wakeMachine(name, opts.force ?? false));
|
|
4691
|
+
if (opts.json) json(box2);
|
|
4166
4692
|
else info(`${color.green("\u2713")} box ${name} is awake, running where it left off`);
|
|
4167
4693
|
} finally {
|
|
4168
4694
|
await client.close();
|
|
@@ -4177,7 +4703,7 @@ var vmAliases = [newCommand, lsCommand, getCommand, connectCommand, execCommand,
|
|
|
4177
4703
|
// src/commands/login.ts
|
|
4178
4704
|
import { hostname as osHostname2 } from "os";
|
|
4179
4705
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
4180
|
-
import { setTimeout as
|
|
4706
|
+
import { setTimeout as sleep4 } from "timers/promises";
|
|
4181
4707
|
import { Writable } from "stream";
|
|
4182
4708
|
import { Command as Command38 } from "commander";
|
|
4183
4709
|
|
|
@@ -4259,7 +4785,7 @@ async function storeLogin(url, res, p) {
|
|
|
4259
4785
|
await writeSession(session, p);
|
|
4260
4786
|
return session;
|
|
4261
4787
|
}
|
|
4262
|
-
var terminalIo = { say: info, sleep:
|
|
4788
|
+
var terminalIo = { say: info, sleep: sleep4, open: openBrowser, wait: (message, work) => spin(message, work) };
|
|
4263
4789
|
async function runDeviceLogin(url, p = paths(), hostname = osHostname2(), io = terminalIo) {
|
|
4264
4790
|
const publicKey = await ensureSshKey(p, hostname);
|
|
4265
4791
|
const client = new ServerClient({ kind: "cloud", url, token: "" }, { autoStart: false });
|
|
@@ -4525,13 +5051,13 @@ var lsCommand6 = new Command45("ls").description("list snapshots (yours and your
|
|
|
4525
5051
|
|
|
4526
5052
|
// src/commands/snapshots/new.ts
|
|
4527
5053
|
import { Command as Command46 } from "commander";
|
|
4528
|
-
var newCommand2 = new Command46("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (
|
|
5054
|
+
var newCommand2 = new Command46("new").description("freeze a running box (memory + disk) into a snapshot; the box keeps running").argument("<box>", "box name").argument("<name>", "snapshot name").option("--replace", "retake a snapshot that exists under this name; the old one stays until the new one is complete").option("--json", "print the snapshot as JSON").action(async (box2, name, opts, cmd) => {
|
|
4529
5055
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4530
5056
|
try {
|
|
4531
|
-
const req = { box, name, ...opts.replace ? { replace: true } : {} };
|
|
4532
|
-
const snap = await spin(`saving snapshot ${name} from box ${
|
|
5057
|
+
const req = { box: box2, name, ...opts.replace ? { replace: true } : {} };
|
|
5058
|
+
const snap = await spin(`saving snapshot ${name} from box ${box2} (memory + disk)\u2026`, client.createSnapshot(req));
|
|
4533
5059
|
if (opts.json) json(snap);
|
|
4534
|
-
else info(`${color.green("\u2713")} snapshot ${name} ${opts.replace ? "retaken" : "saved"} from box ${
|
|
5060
|
+
else info(`${color.green("\u2713")} snapshot ${name} ${opts.replace ? "retaken" : "saved"} from box ${box2} (${gb(snap.sizeBytes)} on disk); start a warm clone with: kvbox new --from ${name}`);
|
|
4535
5061
|
} finally {
|
|
4536
5062
|
await client.close();
|
|
4537
5063
|
}
|
|
@@ -4937,7 +5463,7 @@ import { Command as Command58, InvalidArgumentError as InvalidArgumentError2, Op
|
|
|
4937
5463
|
// src/commands/deploy/config.ts
|
|
4938
5464
|
import { readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
|
|
4939
5465
|
import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
|
|
4940
|
-
import { z as
|
|
5466
|
+
import { z as z12 } from "zod";
|
|
4941
5467
|
|
|
4942
5468
|
// src/commands/deploy/templates/docker.ts
|
|
4943
5469
|
import { readFile as readFile4 } from "fs/promises";
|
|
@@ -5361,21 +5887,21 @@ function detectTemplates(pkg, dir = NO_FACTS) {
|
|
|
5361
5887
|
var DEPLOY_AUTO_HIBERNATE_SEC = 3600;
|
|
5362
5888
|
var CONFIG_FILE = "kvbox.json";
|
|
5363
5889
|
var BOX_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
5364
|
-
var DeployConfigSchema =
|
|
5365
|
-
template:
|
|
5366
|
-
name:
|
|
5890
|
+
var DeployConfigSchema = z12.object({
|
|
5891
|
+
template: z12.enum(TEMPLATE_IDS),
|
|
5892
|
+
name: z12.string().regex(BOX_NAME_RE, "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit"),
|
|
5367
5893
|
/** The org whose box it is; absent for the user's own. */
|
|
5368
|
-
org:
|
|
5894
|
+
org: z12.string().regex(ORG_SLUG_RE, "not an org slug").optional(),
|
|
5369
5895
|
/** The HTTPS name (`<subdomain>.kvbox.app`); absent when deploying to this machine's own host. */
|
|
5370
|
-
subdomain:
|
|
5896
|
+
subdomain: z12.string().check((ctx) => {
|
|
5371
5897
|
const problem = subdomainProblem(ctx.value);
|
|
5372
5898
|
if (problem) ctx.issues.push({ code: "custom", message: problem, input: ctx.value });
|
|
5373
5899
|
}).optional(),
|
|
5374
|
-
size:
|
|
5900
|
+
size: z12.enum(SIZE_NAMES).optional(),
|
|
5375
5901
|
/** The build output directory, relative to the app; the template's default when absent. */
|
|
5376
|
-
dist:
|
|
5902
|
+
dist: z12.string().optional(),
|
|
5377
5903
|
/** The port a Next.js app or Node server serves; the template's (3000) when absent. */
|
|
5378
|
-
port:
|
|
5904
|
+
port: z12.number().int().min(1).max(65535).optional()
|
|
5379
5905
|
});
|
|
5380
5906
|
var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
|
|
5381
5907
|
var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
|
|
@@ -5387,38 +5913,38 @@ var POSTGRES_PORT = 5432;
|
|
|
5387
5913
|
var POSTGRES_IMAGE = "postgres:17";
|
|
5388
5914
|
var POSTGRES_ENV = "DATABASE_URL";
|
|
5389
5915
|
var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
|
|
5390
|
-
var ServiceSchema =
|
|
5391
|
-
template:
|
|
5916
|
+
var ServiceSchema = z12.strictObject({
|
|
5917
|
+
template: z12.enum([...TEMPLATE_IDS, POSTGRES]),
|
|
5392
5918
|
/** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
|
|
5393
|
-
dir:
|
|
5919
|
+
dir: z12.string().min(1).optional(),
|
|
5394
5920
|
/** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
|
|
5395
|
-
image:
|
|
5921
|
+
image: z12.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
|
|
5396
5922
|
/** The volume (a key of `volumes`) a postgres service keeps its data on. */
|
|
5397
|
-
volume:
|
|
5923
|
+
volume: z12.string().optional(),
|
|
5398
5924
|
/** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
|
|
5399
|
-
env:
|
|
5925
|
+
env: z12.string().optional(),
|
|
5400
5926
|
/** A docker service's build context, relative to kvbox.json, when it is not `dir` (a monorepo built from its root); the Dockerfile stays in `dir`. */
|
|
5401
|
-
context:
|
|
5402
|
-
dist:
|
|
5927
|
+
context: z12.string().min(1).optional(),
|
|
5928
|
+
dist: z12.string().optional(),
|
|
5403
5929
|
/**
|
|
5404
5930
|
* A command run once per deploy in the service's new version (a docker service: in a container of
|
|
5405
5931
|
* the new image; node, nextjs: in the new source, installed and built), with the box's variables,
|
|
5406
5932
|
* before it replaces the running one. Migrations, mostly. A failing one stops that service's deploy.
|
|
5407
5933
|
*/
|
|
5408
|
-
release:
|
|
5934
|
+
release: z12.string().optional(),
|
|
5409
5935
|
/** The box port of a service with its own server; the template's (3000) when absent. */
|
|
5410
|
-
port:
|
|
5936
|
+
port: z12.number().int().min(1).max(65535).optional(),
|
|
5411
5937
|
/** The URL paths that go to this service, each with everything under it; the prefix is kept. */
|
|
5412
|
-
paths:
|
|
5938
|
+
paths: z12.array(z12.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
|
|
5413
5939
|
});
|
|
5414
|
-
var StackConfigSchema =
|
|
5940
|
+
var StackConfigSchema = z12.strictObject({
|
|
5415
5941
|
name: DeployConfigSchema.shape.name.optional(),
|
|
5416
5942
|
org: DeployConfigSchema.shape.org,
|
|
5417
5943
|
subdomain: DeployConfigSchema.shape.subdomain,
|
|
5418
5944
|
size: DeployConfigSchema.shape.size,
|
|
5419
5945
|
/** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
|
|
5420
|
-
volumes:
|
|
5421
|
-
services:
|
|
5946
|
+
volumes: z12.record(z12.string(), z12.string()).optional(),
|
|
5947
|
+
services: z12.record(z12.string(), ServiceSchema)
|
|
5422
5948
|
});
|
|
5423
5949
|
function volumeGib(text2) {
|
|
5424
5950
|
const mib = parseMib(text2);
|
|
@@ -5650,14 +6176,14 @@ async function findOrCreate(client, config) {
|
|
|
5650
6176
|
const user = me(client);
|
|
5651
6177
|
const slug = config.org ?? user;
|
|
5652
6178
|
const named = (await client.listMachines()).filter((b) => b.name === config.name);
|
|
5653
|
-
let
|
|
6179
|
+
let box2 = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
|
|
5654
6180
|
let created = false;
|
|
5655
|
-
if (!
|
|
5656
|
-
|
|
6181
|
+
if (!box2) {
|
|
6182
|
+
box2 = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
|
|
5657
6183
|
created = true;
|
|
5658
|
-
info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${
|
|
6184
|
+
info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box2.vcpu} vCPU, ${gb(box2.memMib * 1024 ** 2)} RAM, ${gb(box2.diskBytes)} disk`);
|
|
5659
6185
|
}
|
|
5660
|
-
return { box, ref: displayName(
|
|
6186
|
+
return { box: box2, ref: displayName(box2, user), created };
|
|
5661
6187
|
}
|
|
5662
6188
|
async function existingAddresses(client, config) {
|
|
5663
6189
|
const slug = config.org ?? me(client);
|
|
@@ -5671,8 +6197,8 @@ async function refuseOtherAddress(client, config) {
|
|
|
5671
6197
|
`box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
|
|
5672
6198
|
);
|
|
5673
6199
|
}
|
|
5674
|
-
async function address(client,
|
|
5675
|
-
const subs = (await client.listSubdomains()).filter((s) => s.box ===
|
|
6200
|
+
async function address(client, box2, ref, config, port) {
|
|
6201
|
+
const subs = (await client.listSubdomains()).filter((s) => s.box === box2.name && s.owner === slugOf(box2.owner));
|
|
5676
6202
|
const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
|
|
5677
6203
|
if (have) {
|
|
5678
6204
|
if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
|
|
@@ -5875,7 +6401,7 @@ async function deployStack(d) {
|
|
|
5875
6401
|
if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, { ...config, name: config.name });
|
|
5876
6402
|
let saved = config;
|
|
5877
6403
|
if (JSON.stringify(saved) !== JSON.stringify(d.stack)) await writeConfig(dir, saved);
|
|
5878
|
-
const
|
|
6404
|
+
const box2 = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
|
|
5879
6405
|
const all = [];
|
|
5880
6406
|
for (const service of picked) {
|
|
5881
6407
|
if (service.postgres) continue;
|
|
@@ -5892,7 +6418,7 @@ async function deployStack(d) {
|
|
|
5892
6418
|
all.push({ service, template, built, size: await shipping.measure(built.outDir, built.exclude) });
|
|
5893
6419
|
}
|
|
5894
6420
|
info("");
|
|
5895
|
-
const { box: found, ref, created } = await findOrCreate(client,
|
|
6421
|
+
const { box: found, ref, created } = await findOrCreate(client, box2);
|
|
5896
6422
|
const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
|
|
5897
6423
|
const wasRunning = !created && found.status === "running";
|
|
5898
6424
|
const machine = created || wasRunning ? found : await wakeUp(client, found, ref);
|
|
@@ -5932,7 +6458,7 @@ ${front.output.trim()}`);
|
|
|
5932
6458
|
const missing = picked.length < services.length ? await neverShipped(ep, services.filter((s) => !picked.includes(s))) : [];
|
|
5933
6459
|
let url = `http://${machine.ip}`;
|
|
5934
6460
|
if (cloud) {
|
|
5935
|
-
const got = await address(client, machine, ref,
|
|
6461
|
+
const got = await address(client, machine, ref, box2, FRONT_PORT);
|
|
5936
6462
|
url = got.url;
|
|
5937
6463
|
if (got.subdomain !== saved.subdomain) await writeConfig(dir, { ...saved, subdomain: got.subdomain });
|
|
5938
6464
|
}
|
|
@@ -6148,14 +6674,14 @@ async function settle(d) {
|
|
|
6148
6674
|
const volumes = { ...stack.volumes };
|
|
6149
6675
|
const services = { ...stack.services };
|
|
6150
6676
|
for (const key of open.volumes) {
|
|
6151
|
-
let
|
|
6677
|
+
let volume2 = volumeNameFor(name, volumes, accountVolumes);
|
|
6152
6678
|
let gib = `${VOLUME_GIB}GB`;
|
|
6153
6679
|
if (ask) {
|
|
6154
|
-
|
|
6680
|
+
volume2 = await text(`Volume for ${key}'s data`, { default: volume2, validate: (a) => !VOLUME_NAME_RE.test(a) ? VOLUME_NAME_RULE : volumes[a] !== void 0 ? "already a volume of this stack" : accountVolumes.has(a) ? `already a volume of yours, another box's data; to reuse it on purpose, name it in ${CONFIG_FILE}` : void 0 });
|
|
6155
6681
|
gib = await text("Volume size", { default: gib, validate: (a) => volumeGib(a) === void 0 ? "whole GB, like 10GB" : void 0 });
|
|
6156
6682
|
}
|
|
6157
|
-
volumes[
|
|
6158
|
-
services[key] = { ...services[key], volume };
|
|
6683
|
+
volumes[volume2] = gib;
|
|
6684
|
+
services[key] = { ...services[key], volume: volume2 };
|
|
6159
6685
|
}
|
|
6160
6686
|
if (ask) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
|
|
6161
6687
|
`);
|
|
@@ -6170,20 +6696,20 @@ async function settle(d) {
|
|
|
6170
6696
|
};
|
|
6171
6697
|
}
|
|
6172
6698
|
var VOLUME_GIB = 10;
|
|
6173
|
-
function defaultVolumes(
|
|
6699
|
+
function defaultVolumes(box2, stackVolumes, account, keys) {
|
|
6174
6700
|
const taken = { ...stackVolumes };
|
|
6175
6701
|
return keys.map((key) => {
|
|
6176
|
-
const v = volumeNameFor(
|
|
6702
|
+
const v = volumeNameFor(box2, taken, account);
|
|
6177
6703
|
taken[v] = `${VOLUME_GIB}GB`;
|
|
6178
6704
|
return [key, v];
|
|
6179
6705
|
});
|
|
6180
6706
|
}
|
|
6181
|
-
function volumeNameFor(
|
|
6707
|
+
function volumeNameFor(box2, taken, account = /* @__PURE__ */ new Set()) {
|
|
6182
6708
|
const free = (n) => taken[n] === void 0 && !account.has(n);
|
|
6183
|
-
const base = `${
|
|
6709
|
+
const base = `${box2.slice(0, 9).replace(/-+$/, "")}-db`;
|
|
6184
6710
|
if (free(base)) return base;
|
|
6185
6711
|
for (let i = 2; ; i++) {
|
|
6186
|
-
const n = `${
|
|
6712
|
+
const n = `${box2.slice(0, 8).replace(/-+$/, "")}-db${i}`;
|
|
6187
6713
|
if (free(n)) return n;
|
|
6188
6714
|
}
|
|
6189
6715
|
}
|
|
@@ -6228,22 +6754,22 @@ var deployCommand = new Command58("deploy").description("put the app in this dir
|
|
|
6228
6754
|
const { box: found, ref, created } = await findOrCreate(client, config);
|
|
6229
6755
|
const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
|
|
6230
6756
|
const wasRunning = !created && found.status === "running";
|
|
6231
|
-
const
|
|
6232
|
-
const ep = sshEndpoint(
|
|
6757
|
+
const box2 = created || wasRunning ? found : await wakeUp(client, found, ref);
|
|
6758
|
+
const ep = sshEndpoint(box2, client.target);
|
|
6233
6759
|
if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
|
|
6234
6760
|
const port = config.port ?? template.port;
|
|
6235
6761
|
const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port), built.exclude);
|
|
6236
6762
|
const there = built.boxBuild ? "installing and building there" : "installing there";
|
|
6237
6763
|
const doing = built.dist === void 0 ? `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref} and ${there}, a minute or two\u2026` : `shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}\u2026`;
|
|
6238
6764
|
let result = await spin(doing, shipIt);
|
|
6239
|
-
if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert,
|
|
6765
|
+
if (result.status === SSH_FAILED3 && await renewAfterRefusal(client, cert, box2.owner)) {
|
|
6240
6766
|
info("renewed your SSH certificate, trying again\u2026");
|
|
6241
6767
|
result = await spin(doing, shipIt);
|
|
6242
6768
|
}
|
|
6243
6769
|
refuseFailedShip(result, { ref, template, port, built });
|
|
6244
|
-
let url = `http://${
|
|
6770
|
+
let url = `http://${box2.ip}${port === 80 ? "" : `:${port}`}`;
|
|
6245
6771
|
if (cloud) {
|
|
6246
|
-
const got = await address(client,
|
|
6772
|
+
const got = await address(client, box2, ref, config, port);
|
|
6247
6773
|
url = got.url;
|
|
6248
6774
|
if (got.subdomain !== config.subdomain) await writeConfig(dir, { ...config, subdomain: got.subdomain, ...built.dist !== void 0 && built.dist !== config.dist ? { dist: built.dist } : {} });
|
|
6249
6775
|
}
|
|
@@ -6358,23 +6884,23 @@ import { Command as Command69 } from "commander";
|
|
|
6358
6884
|
|
|
6359
6885
|
// src/commands/volume/attach.ts
|
|
6360
6886
|
import { Command as Command59 } from "commander";
|
|
6361
|
-
function describeMount(machine,
|
|
6362
|
-
const path = machine.volumes?.find((v) =>
|
|
6363
|
-
return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${
|
|
6887
|
+
function describeMount(machine, volume2, box2) {
|
|
6888
|
+
const path = machine.volumes?.find((v) => volume2 === v.name || volume2.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume2.slice(volume2.lastIndexOf("/") + 1));
|
|
6889
|
+
return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box2} is ${machine.status}; the volume is at ${path} once it runs`;
|
|
6364
6890
|
}
|
|
6365
6891
|
var attachCommand = new Command59("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
|
|
6366
6892
|
if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
|
|
6367
6893
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
6368
6894
|
try {
|
|
6369
|
-
const
|
|
6370
|
-
const
|
|
6371
|
-
const machine = await spin(`attaching volume ${
|
|
6895
|
+
const volume2 = volumeArg ?? (await pickVolume(client, (v) => v.attachedTo === null, "no volume is free to attach (kvbox volume ls); make one with kvbox volume new")).ref;
|
|
6896
|
+
const box2 = boxArg ?? await pickBox(client);
|
|
6897
|
+
const machine = await spin(`attaching volume ${volume2} to box ${box2} (a running box is restarted)\u2026`, client.attachVolume(volume2, { box: box2 }));
|
|
6372
6898
|
if (opts.json) {
|
|
6373
6899
|
json(machine);
|
|
6374
6900
|
return;
|
|
6375
6901
|
}
|
|
6376
|
-
info(`${color.green("\u2713")} volume ${
|
|
6377
|
-
info(describeMount(machine,
|
|
6902
|
+
info(`${color.green("\u2713")} volume ${volume2} attached to box ${box2}`);
|
|
6903
|
+
info(describeMount(machine, volume2, box2));
|
|
6378
6904
|
} finally {
|
|
6379
6905
|
await client.close();
|
|
6380
6906
|
}
|
|
@@ -6385,25 +6911,25 @@ import { Command as Command63 } from "commander";
|
|
|
6385
6911
|
|
|
6386
6912
|
// src/commands/volume/backup/create.ts
|
|
6387
6913
|
import { Command as Command60 } from "commander";
|
|
6388
|
-
var createCommand4 = new Command60("create").description("back up a volume's disk to the kvbox cloud (encrypted)").argument("<volume>", "volume name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (
|
|
6914
|
+
var createCommand4 = new Command60("create").description("back up a volume's disk to the kvbox cloud (encrypted)").argument("<volume>", "volume name").option("--wait", "stay until the backup is ready (by default it runs in the background)").option("--json", "print the backup as JSON").action(async (volume2, opts, cmd) => {
|
|
6389
6915
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6390
6916
|
try {
|
|
6391
6917
|
requireCloud3(client);
|
|
6392
|
-
const started = await client.createVolumeBackup(
|
|
6918
|
+
const started = await client.createVolumeBackup(volume2);
|
|
6393
6919
|
if (!opts.wait) {
|
|
6394
6920
|
if (opts.json) json(started);
|
|
6395
6921
|
else {
|
|
6396
|
-
info(`${color.green("\u2713")} backup ${started.id} of volume ${color.bold(
|
|
6397
|
-
info(color.dim(` status: kvbox volume backup ls ${
|
|
6922
|
+
info(`${color.green("\u2713")} backup ${started.id} of volume ${color.bold(volume2)} started; it runs in the background`);
|
|
6923
|
+
info(color.dim(` status: kvbox volume backup ls ${volume2}`));
|
|
6398
6924
|
}
|
|
6399
6925
|
return;
|
|
6400
6926
|
}
|
|
6401
|
-
const done = await spin(`backing up volume ${
|
|
6927
|
+
const done = await spin(`backing up volume ${volume2}\u2026`, untilSettled(() => client.volumeBackup(volume2, started.id), `volume ${volume2}`, started.id, `kvbox volume backup ls ${volume2}`));
|
|
6402
6928
|
if (opts.json) json(done);
|
|
6403
|
-
if (done.status === "failed") throw new KvboxError(`backup ${done.id} of volume ${
|
|
6929
|
+
if (done.status === "failed") throw new KvboxError(`backup ${done.id} of volume ${volume2} failed: ${done.error ?? "no reason given"}`);
|
|
6404
6930
|
if (opts.json) return;
|
|
6405
|
-
info(`${color.green("\u2713")} backup ${done.id} of volume ${color.bold(
|
|
6406
|
-
info(color.dim(` restore with: kvbox volume backup restore ${
|
|
6931
|
+
info(`${color.green("\u2713")} backup ${done.id} of volume ${color.bold(volume2)}: ${sizeLine(done)}`);
|
|
6932
|
+
info(color.dim(` restore with: kvbox volume backup restore ${volume2} ${done.id}`));
|
|
6407
6933
|
} finally {
|
|
6408
6934
|
await client.close();
|
|
6409
6935
|
}
|
|
@@ -6411,24 +6937,24 @@ var createCommand4 = new Command60("create").description("back up a volume's dis
|
|
|
6411
6937
|
|
|
6412
6938
|
// src/commands/volume/backup/ls.ts
|
|
6413
6939
|
import { Command as Command61 } from "commander";
|
|
6414
|
-
var lsCommand9 = new Command61("ls").alias("list").description("list volume backups: every volume's, or one volume's").argument("[volume]", "volume name (default: every volume)").option("--json", "print as JSON").action(async (
|
|
6940
|
+
var lsCommand9 = new Command61("ls").alias("list").description("list volume backups: every volume's, or one volume's").argument("[volume]", "volume name (default: every volume)").option("--json", "print as JSON").action(async (volume2, opts, cmd) => {
|
|
6415
6941
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6416
6942
|
try {
|
|
6417
6943
|
requireCloud3(client);
|
|
6418
|
-
const list =
|
|
6944
|
+
const list = volume2 === void 0 ? await client.listVolumeBackups() : await client.volumeBackups(volume2);
|
|
6419
6945
|
if (opts.json) {
|
|
6420
6946
|
json(list);
|
|
6421
6947
|
return;
|
|
6422
6948
|
}
|
|
6423
6949
|
if (list.length === 0) {
|
|
6424
|
-
info(
|
|
6950
|
+
info(volume2 === void 0 ? "no volume backups yet; make one with: kvbox volume backup create <volume>" : `volume ${volume2} has no backups; make one with: kvbox volume backup create ${volume2}`);
|
|
6425
6951
|
return;
|
|
6426
6952
|
}
|
|
6427
6953
|
const anyError = list.some((b) => b.error !== null);
|
|
6428
6954
|
table(
|
|
6429
6955
|
list.map((b) => ({
|
|
6430
6956
|
id: b.id,
|
|
6431
|
-
...
|
|
6957
|
+
...volume2 === void 0 ? { volume: b.owner === me(client) ? b.volume : `${b.owner}/${b.volume}` } : {},
|
|
6432
6958
|
status: b.status === "ready" ? color.green(b.status) : b.status === "failed" ? color.red(b.status) : color.yellow(b.status),
|
|
6433
6959
|
data: b.dataBytes === null ? "-" : gbShort(b.dataBytes),
|
|
6434
6960
|
uploaded: b.uploadedBytes === null ? "-" : gbShort(b.uploadedBytes),
|
|
@@ -6445,23 +6971,23 @@ var lsCommand9 = new Command61("ls").alias("list").description("list volume back
|
|
|
6445
6971
|
|
|
6446
6972
|
// src/commands/volume/backup/restore.ts
|
|
6447
6973
|
import { Command as Command62 } from "commander";
|
|
6448
|
-
var restoreCommand2 = new Command62("restore").description("put a backup back: the volume's data becomes the backup's (a running box holding it restarts)").argument("<volume>", "volume name").argument("<id>", "the backup's id (kvbox volume backup ls <volume>)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the volume as JSON").action(async (
|
|
6974
|
+
var restoreCommand2 = new Command62("restore").description("put a backup back: the volume's data becomes the backup's (a running box holding it restarts)").argument("<volume>", "volume name").argument("<id>", "the backup's id (kvbox volume backup ls <volume>)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the volume as JSON").action(async (volume2, id, opts, cmd) => {
|
|
6449
6975
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
6450
6976
|
try {
|
|
6451
6977
|
requireCloud3(client);
|
|
6452
|
-
const backup = await client.volumeBackup(
|
|
6453
|
-
const question = `Restore volume ${
|
|
6978
|
+
const backup = await client.volumeBackup(volume2, id);
|
|
6979
|
+
const question = `Restore volume ${volume2} from backup ${backup.id} (${age(backup.createdAt)} ago, ${sizeLine(backup)})? Everything written to it since is lost, and a running box that holds it restarts.`;
|
|
6454
6980
|
if (!await confirm(question, opts.yes ?? false)) {
|
|
6455
6981
|
info("cancelled");
|
|
6456
6982
|
process.exitCode = 1;
|
|
6457
6983
|
return;
|
|
6458
6984
|
}
|
|
6459
|
-
const restored = await spin(`restoring volume ${
|
|
6985
|
+
const restored = await spin(`restoring volume ${volume2} from ${backup.id}\u2026`, client.restoreVolumeBackup(volume2, id));
|
|
6460
6986
|
if (opts.json) {
|
|
6461
6987
|
json(restored);
|
|
6462
6988
|
return;
|
|
6463
6989
|
}
|
|
6464
|
-
info(`${color.green("\u2713")} volume ${color.bold(
|
|
6990
|
+
info(`${color.green("\u2713")} volume ${color.bold(volume2)} restored from backup ${backup.id}${restored.attachedTo ? color.dim(` (box ${restored.attachedTo} was restarted if it was running)`) : ""}`);
|
|
6465
6991
|
} finally {
|
|
6466
6992
|
await client.close();
|
|
6467
6993
|
}
|
|
@@ -6526,21 +7052,21 @@ var detachCommand = new Command65("detach").description("detach a volume from a
|
|
|
6526
7052
|
if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
|
|
6527
7053
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
6528
7054
|
try {
|
|
6529
|
-
let
|
|
6530
|
-
let
|
|
6531
|
-
if (
|
|
6532
|
-
const found =
|
|
6533
|
-
if (!found) throw new KvboxError(`volume ${
|
|
6534
|
-
if (found.attachedTo === null) throw new KvboxError(`volume ${
|
|
6535
|
-
|
|
6536
|
-
|
|
7055
|
+
let volume2 = volumeArg;
|
|
7056
|
+
let box2 = boxArg;
|
|
7057
|
+
if (volume2 === void 0 || box2 === void 0) {
|
|
7058
|
+
const found = volume2 === void 0 ? await pickVolume(client, (v) => v.attachedTo !== null, "no volume is attached to a box (kvbox volume ls)") : pickRef(await spin("finding the volume\u2026", client.listVolumes()), volume2, me(client), "volume");
|
|
7059
|
+
if (!found) throw new KvboxError(`volume ${volume2}: not found (kvbox volume ls)`);
|
|
7060
|
+
if (found.attachedTo === null) throw new KvboxError(`volume ${volume2}: not attached to a box`);
|
|
7061
|
+
volume2 ??= refOf(found, me(client));
|
|
7062
|
+
box2 ??= refOf({ name: found.attachedTo, owner: found.owner }, me(client));
|
|
6537
7063
|
}
|
|
6538
|
-
const machine = await spin(`detaching volume ${
|
|
7064
|
+
const machine = await spin(`detaching volume ${volume2} from box ${box2} (a running box is restarted)\u2026`, client.detachVolume(volume2, { box: box2 }));
|
|
6539
7065
|
if (opts.json) {
|
|
6540
7066
|
json(machine);
|
|
6541
7067
|
return;
|
|
6542
7068
|
}
|
|
6543
|
-
info(`${color.green("\u2713")} volume ${
|
|
7069
|
+
info(`${color.green("\u2713")} volume ${volume2} detached from box ${box2}; its data is kept${machine.status === "running" ? " (the box was restarted)" : ""}`);
|
|
6544
7070
|
} finally {
|
|
6545
7071
|
await client.close();
|
|
6546
7072
|
}
|
|
@@ -7001,7 +7527,7 @@ function timeoutOf(value) {
|
|
|
7001
7527
|
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`);
|
|
7002
7528
|
return sec;
|
|
7003
7529
|
}
|
|
7004
|
-
var addCommand3 = new Command84("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,
|
|
7530
|
+
var addCommand3 = new Command84("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, box2, expr, opts, cmd) => {
|
|
7005
7531
|
let action;
|
|
7006
7532
|
if (opts.run !== void 0) {
|
|
7007
7533
|
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");
|
|
@@ -7014,7 +7540,7 @@ var addCommand3 = new Command84("add").description("add a trigger: on a schedule
|
|
|
7014
7540
|
}
|
|
7015
7541
|
const client = await cronClient(cmd);
|
|
7016
7542
|
try {
|
|
7017
|
-
const trigger = await client.addCronTrigger(service, { box, expr, timezone: opts.tz, ...action });
|
|
7543
|
+
const trigger = await client.addCronTrigger(service, { box: box2, expr, timezone: opts.tz, ...action });
|
|
7018
7544
|
if (opts.json) {
|
|
7019
7545
|
json(trigger);
|
|
7020
7546
|
return;
|
|
@@ -7140,7 +7666,7 @@ var runsCommand = new Command90("runs").aliases(["logs"]).description("show how
|
|
|
7140
7666
|
}))
|
|
7141
7667
|
);
|
|
7142
7668
|
const last = runs.find((r) => r.output !== null);
|
|
7143
|
-
if (last) info(color.dim(`A command's output stays in the box
|
|
7669
|
+
if (last) info(color.dim(`A command's output stays in the box; the newest: kvbox exec <box> -- cat ${last.output}`));
|
|
7144
7670
|
} finally {
|
|
7145
7671
|
await client.close();
|
|
7146
7672
|
}
|
|
@@ -7162,7 +7688,7 @@ import { Command as Command105 } from "commander";
|
|
|
7162
7688
|
|
|
7163
7689
|
// src/commands/managed/create.ts
|
|
7164
7690
|
import { Command as Command94 } from "commander";
|
|
7165
|
-
import { setTimeout as
|
|
7691
|
+
import { setTimeout as sleep5 } from "timers/promises";
|
|
7166
7692
|
|
|
7167
7693
|
// src/commands/managed/shared.ts
|
|
7168
7694
|
import "commander";
|
|
@@ -7264,7 +7790,7 @@ var createCommand9 = (spec) => {
|
|
|
7264
7790
|
const made = await spin(`creating ${spec.title} database ${name}\u2026`, client.createManaged(spec.kind, req));
|
|
7265
7791
|
const shown = shownName3(made, me(client));
|
|
7266
7792
|
const ready = await spin(`starting ${spec.title}\u2026`, async () => {
|
|
7267
|
-
for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await
|
|
7793
|
+
for (const until2 = Date.now() + READY_WAIT_MS; Date.now() < until2; await sleep5(READY_STEP_MS)) {
|
|
7268
7794
|
const now = await client.getManaged(spec.kind, shown).catch(() => void 0);
|
|
7269
7795
|
if (now?.health?.ready && now.health.accepting) return true;
|
|
7270
7796
|
}
|
|
@@ -7317,16 +7843,16 @@ var infoCommand3 = (spec) => new Command96("info").alias("get").description("sho
|
|
|
7317
7843
|
|
|
7318
7844
|
// src/commands/managed/link.ts
|
|
7319
7845
|
import { Command as Command97 } from "commander";
|
|
7320
|
-
var linkCommand2 = (spec) => new Command97("link").description("let a box reach a database privately (same host)").argument("<db>", "the database").argument("<box>", "the box that connects to it").option("--json", "print as JSON").action(async (name,
|
|
7846
|
+
var linkCommand2 = (spec) => new Command97("link").description("let a box reach a database privately (same host)").argument("<db>", "the database").argument("<box>", "the box that connects to it").option("--json", "print as JSON").action(async (name, box2, opts, cmd) => {
|
|
7321
7847
|
const client = await managedClient(cmd);
|
|
7322
7848
|
try {
|
|
7323
|
-
const m = await spin(`linking ${
|
|
7849
|
+
const m = await spin(`linking ${box2} to ${name}\u2026`, client.linkManaged(spec.kind, name, box2));
|
|
7324
7850
|
if (opts.json) {
|
|
7325
7851
|
json(m);
|
|
7326
7852
|
return;
|
|
7327
7853
|
}
|
|
7328
|
-
info(`${color.green("\u2713")} box ${
|
|
7329
|
-
info(` inside ${
|
|
7854
|
+
info(`${color.green("\u2713")} box ${box2} can reach database ${name}`);
|
|
7855
|
+
info(` inside ${box2}: ${m.urls.private} ${color.dim(`(the password: kvbox ${spec.command} password ${name})`)}`);
|
|
7330
7856
|
} finally {
|
|
7331
7857
|
await client.close();
|
|
7332
7858
|
}
|
|
@@ -7450,12 +7976,12 @@ var stopCommand2 = (spec) => new Command103("stop").description("shut a database
|
|
|
7450
7976
|
|
|
7451
7977
|
// src/commands/managed/unlink.ts
|
|
7452
7978
|
import { Command as Command104 } from "commander";
|
|
7453
|
-
var unlinkCommand2 = (spec) => new Command104("unlink").description("stop a box from reaching a database").argument("<db>", "the database").argument("<box>", "the box that was linked to it").option("--json", "print as JSON").action(async (name,
|
|
7979
|
+
var unlinkCommand2 = (spec) => new Command104("unlink").description("stop a box from reaching a database").argument("<db>", "the database").argument("<box>", "the box that was linked to it").option("--json", "print as JSON").action(async (name, box2, opts, cmd) => {
|
|
7454
7980
|
const client = await managedClient(cmd);
|
|
7455
7981
|
try {
|
|
7456
|
-
const m = await spin(`unlinking ${
|
|
7982
|
+
const m = await spin(`unlinking ${box2} from ${name}\u2026`, client.unlinkManaged(spec.kind, name, box2));
|
|
7457
7983
|
if (opts.json) json(m);
|
|
7458
|
-
else info(`${color.green("\u2713")} box ${
|
|
7984
|
+
else info(`${color.green("\u2713")} box ${box2} no longer reaches database ${name}`);
|
|
7459
7985
|
} finally {
|
|
7460
7986
|
await client.close();
|
|
7461
7987
|
}
|
|
@@ -7496,15 +8022,15 @@ function reach(boxes, verb) {
|
|
|
7496
8022
|
return boxes === 1 ? `1 box ${verb}s it when it next starts` : `${boxes} boxes ${verb} it when they next start`;
|
|
7497
8023
|
}
|
|
7498
8024
|
async function findBox2(client, name) {
|
|
7499
|
-
const
|
|
7500
|
-
if (!
|
|
7501
|
-
return { box, ref: displayName(
|
|
8025
|
+
const box2 = pickRef(await boxesFor(client, name), name, me(client));
|
|
8026
|
+
if (!box2) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
|
|
8027
|
+
return { box: box2, ref: displayName(box2, me(client)) };
|
|
7502
8028
|
}
|
|
7503
8029
|
function boxReach(running, verb) {
|
|
7504
8030
|
return running ? `it ${verb} it when it next starts (kvbox stop, kvbox start)` : `it ${verb} it when it starts`;
|
|
7505
8031
|
}
|
|
7506
|
-
function firstBootHint(
|
|
7507
|
-
if (
|
|
8032
|
+
function firstBootHint(box2, name) {
|
|
8033
|
+
if (box2.image === "postgres" && /^POSTGRES_(USER|PASSWORD|DB)$/.test(name)) {
|
|
7508
8034
|
return `${name} is read once, when the box first boots: the database keeps the user, password and database it was made with (change them with psql in the box)`;
|
|
7509
8035
|
}
|
|
7510
8036
|
return void 0;
|
|
@@ -7515,9 +8041,9 @@ var lsCommand16 = new Command107("ls").alias("list").description("list the varia
|
|
|
7515
8041
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
7516
8042
|
try {
|
|
7517
8043
|
if (opts.box !== void 0) {
|
|
7518
|
-
const { box, ref } = await findBox2(client, opts.box);
|
|
8044
|
+
const { box: box2, ref } = await findBox2(client, opts.box);
|
|
7519
8045
|
const own = await client.boxEnv(ref);
|
|
7520
|
-
const slug = slugOf(
|
|
8046
|
+
const slug = slugOf(box2.owner);
|
|
7521
8047
|
const theirs = client.target.kind === "cloud" ? await client.listEnv(slug === me(client) ? void 0 : slug) : [];
|
|
7522
8048
|
const mine = new Set(own.vars.map((v) => v.name));
|
|
7523
8049
|
const inherited = theirs.filter((v) => !mine.has(v.name));
|
|
@@ -7660,18 +8186,18 @@ var addCommand4 = new Command111("add").description("serve a box at a domain of
|
|
|
7660
8186
|
try {
|
|
7661
8187
|
requireCloud5(client);
|
|
7662
8188
|
const user = me(client);
|
|
7663
|
-
const
|
|
7664
|
-
const d = await spin(`adding ${domain}\u2026`, client.addDomain(
|
|
8189
|
+
const box2 = displayName(await findBox(client, name), user);
|
|
8190
|
+
const d = await spin(`adding ${domain}\u2026`, client.addDomain(box2, { domain, ...port !== void 0 ? { port } : {} }));
|
|
7665
8191
|
if (opts.json) {
|
|
7666
8192
|
json(domainJson(d, user));
|
|
7667
8193
|
return;
|
|
7668
8194
|
}
|
|
7669
8195
|
if (d.status === "live") {
|
|
7670
|
-
info(`${color.green("\u2713")} ${color.bold(d.url)} \u2192 box ${color.bold(
|
|
8196
|
+
info(`${color.green("\u2713")} ${color.bold(d.url)} \u2192 box ${color.bold(box2)} port ${d.port}`);
|
|
7671
8197
|
info(" the certificate is made on the first visit, which can take a few seconds");
|
|
7672
8198
|
return;
|
|
7673
8199
|
}
|
|
7674
|
-
info(`${color.green("\u2713")} ${domain} added for box ${color.bold(
|
|
8200
|
+
info(`${color.green("\u2713")} ${domain} added for box ${color.bold(box2)} port ${d.port}, waiting for its DNS`);
|
|
7675
8201
|
const zone = zoneOf(domain);
|
|
7676
8202
|
info(`
|
|
7677
8203
|
At the company that runs the DNS of ${zone}, add:
|
|
@@ -7727,14 +8253,14 @@ var rmCommand15 = new Command113("rm").alias("remove").description("stop serving
|
|
|
7727
8253
|
requireCloud5(client);
|
|
7728
8254
|
const found = (await client.listDomains()).find((d) => d.domain === domain);
|
|
7729
8255
|
if (!found) throw new KvboxError(`domain ${domain}: not found (kvbox domain ls)`);
|
|
7730
|
-
const
|
|
7731
|
-
if (!await confirm(`Stop serving box ${
|
|
8256
|
+
const box2 = boxOf2(found, me(client));
|
|
8257
|
+
if (!await confirm(`Stop serving box ${box2} at ${domain}?`, opts.yes ?? false)) {
|
|
7732
8258
|
info("cancelled");
|
|
7733
8259
|
process.exitCode = 1;
|
|
7734
8260
|
return;
|
|
7735
8261
|
}
|
|
7736
8262
|
await spin(`removing ${domain}\u2026`, client.removeDomain(`${found.owner}/${found.box}`, domain));
|
|
7737
|
-
info(`${color.green("\u2713")} ${domain} no longer serves box ${
|
|
8263
|
+
info(`${color.green("\u2713")} ${domain} no longer serves box ${box2} (you can remove its DNS record)`);
|
|
7738
8264
|
} finally {
|
|
7739
8265
|
await client.close();
|
|
7740
8266
|
}
|