@b3os/cli 0.2.0 → 0.2.1
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/README.md +1 -0
- package/dist/commands/app.d.ts +5 -0
- package/dist/commands/app.js +373 -28
- package/dist/commands/app.js.map +1 -1
- package/dist/commands/auth.d.ts +18 -0
- package/dist/commands/auth.js +47 -12
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/manifest.js +24 -13
- package/dist/commands/manifest.js.map +1 -1
- package/dist/commands/tool.d.ts +46 -0
- package/dist/commands/tool.js +197 -0
- package/dist/commands/tool.js.map +1 -0
- package/dist/main.d.ts +1 -1
- package/dist/main.js +1 -1
- package/dist/manifest/apply.d.ts +4 -0
- package/dist/manifest/apply.js +2 -0
- package/dist/manifest/apply.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -80,6 +80,7 @@ routines that run as it and asks before it revokes the token (`--yes` without a
|
|
|
80
80
|
| `requests [ls\|get <req_id>]` | your request log with timing (`--status 2xx\|4xx\|5xx`, `--product`, `--operation-id`, `--sandbox-id`, `--since`) |
|
|
81
81
|
| `webhooks secret\|rotate\|test\|deliveries --url URL` | webhook signing secrets (printed once on stdout), rotation with a grace period, a signed test delivery |
|
|
82
82
|
| `action search\|describe\|call` | marketplace actions (`call io.b3os/github/create-issue@1 --input @issue.json`) |
|
|
83
|
+
| `tool publish <dir>`, `tool earnings` | hosted tools (a preview, on for every organization in the beta; no tool is published yet): `publish` uploads a tool's build (`<dir>/dist/`, made by `node packages/packs/src/cli/tool.ts build`): the archive when the registry lacks it, then the pack, and prints each action's exact pin and a `b3os action call` line (a key with `actions:tools:publish`, named exactly, and `actions:write`); `earnings --namespace NS --period YYYY-MM` prints the month's earnings line with B3OS's rate and why |
|
|
83
84
|
| `mcp install --client claude\|cursor\|codex` | adds the B3OS MCP server to the client (below) |
|
|
84
85
|
| `mcp serve [--packs a,b] [--routines a,b\|all] [--toolsets a,b]` | the stdio MCP server in this process |
|
|
85
86
|
| `mcp tools [--toolsets a,b]` | the tools the server lists (the shared table both MCP servers serve) |
|
package/dist/commands/app.d.ts
CHANGED
|
@@ -1,2 +1,7 @@
|
|
|
1
1
|
import type { CliCommand } from "../registry.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Whether `url` is what `b3os app open` may hand a browser: exactly `https://<label>.<app domain>/`, with at most a
|
|
4
|
+
* `?b3os_link=` of a link token's shape (apps/edge/src/apphosts/link.ts LINK_TOKEN).
|
|
5
|
+
*/
|
|
6
|
+
export declare function openable(url: string, label: string): boolean;
|
|
2
7
|
export declare const commands: CliCommand[];
|
package/dist/commands/app.js
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
// b3os app status | logs | down: an application is the objects `b3os apply` tagged with its name (`b3os.app`), so
|
|
2
2
|
// these commands read and delete by tag (NOTES/deploy-platform/phase1-plan.md 1.3, last paragraph). No server-side
|
|
3
|
-
// application object exists in phase 1.
|
|
3
|
+
// application object exists in phase 1. Its addresses (`<label>.b3os.io`, D2) are the edge's: status reads them,
|
|
4
|
+
// open and link use them, and down stops them before it retires anything.
|
|
4
5
|
import { existsSync } from "node:fs";
|
|
5
6
|
import { dirname, resolve } from "node:path";
|
|
6
|
-
import { deployAfter, revCommit, serviceHealth, serviceProcess, validDepId, validDeployId } from "@b3os/deploy";
|
|
7
|
+
import { BLOCKED_WORDS, clockOf, deployAfter, listHosts, noHostsRoutes, ownAddress, parseRecreated, revCommit, routeHosts, StepError, serviceHealth, serviceProcess, sleep, validDepId, validDeployId, } from "@b3os/deploy";
|
|
8
|
+
import { APP_DOMAIN, LABEL, ROUTE_SETTLE_MS, ROUTE_STALE_MAX_MS } from "@b3os/deploy/hosts";
|
|
7
9
|
import { CliError, EXIT, intFlag, parse, splitSub, UsageError } from "../ctx.js";
|
|
8
10
|
import { all, listTagged, planRollback, retire, TAG } from "../manifest/apply.js";
|
|
9
11
|
import { loadManifest, MANIFEST_FILE } from "../manifest/load.js";
|
|
10
12
|
import * as git from "../manifest/source.js";
|
|
13
|
+
import { openBrowser, WINDOWS_OPENER_NOTE } from "./auth.js";
|
|
11
14
|
import { runPlanned } from "./manifest.js";
|
|
12
15
|
import { sandboxRequests } from "./requests.js";
|
|
13
16
|
const USAGE = `usage: b3os app <command>
|
|
14
|
-
status [--file FILE | --app NAME] the application's
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
status [--file FILE | --app NAME] the application's addresses (https://<label>.b3os.io: state, the generation
|
|
18
|
+
each serves, cookies this address did not set that were dropped), its service
|
|
19
|
+
generations (last 7 days), build snapshots and routines with their last runs,
|
|
20
|
+
found by their b3os.app tag; for each running generation its URL, its process,
|
|
21
|
+
its last call to B3OS, when its lease ends, its logs command, and why a
|
|
22
|
+
keepalive recreated it; for a service with none running, what starts it again
|
|
18
23
|
logs [APP] [--service NAME] [--follow]
|
|
19
24
|
a running service's output, each line with its time (UTC); --follow keeps
|
|
20
25
|
reading until the process exits
|
|
@@ -22,8 +27,19 @@ const USAGE = `usage: b3os app <command>
|
|
|
22
27
|
the calls each service made to B3OS (models, scrapes, sandboxes), newest
|
|
23
28
|
first, from its running generation (else its newest); --failed keeps 4xx and
|
|
24
29
|
5xx; needs only sandboxes:read
|
|
25
|
-
|
|
26
|
-
|
|
30
|
+
open [APP] [--service NAME] open the application's address in the browser (a link address with a link
|
|
31
|
+
that ends in 60 s); without a terminal, or when no browser starts, print the
|
|
32
|
+
address. On Windows it starts the browser with rundll32, untested on Windows
|
|
33
|
+
link [APP] [--service NAME [--port N]] [--ttl S] [--rotate] [--yes]
|
|
34
|
+
print a link to the application's own address, or to the address of service
|
|
35
|
+
NAME (--port N when it has more than one), valid --ttl seconds (default
|
|
36
|
+
604800, 7 days; 60 to 7776000): anyone who has it gets in. --rotate first makes
|
|
37
|
+
every link stop working within 6 s (streams and WebSockets already open can run
|
|
38
|
+
up to an hour more), then makes the new link
|
|
39
|
+
down --app NAME [--yes] stop its addresses (each label stays the application's), wait 7 s, then
|
|
40
|
+
delete: each running generation (TERM, up to 30 s to exit, then delete; one
|
|
41
|
+
an address serves again by then is kept), then the routines, then the build
|
|
42
|
+
snapshots
|
|
27
43
|
rollback [APP] [--to DEPLOY] [--yes] [--dry-run]
|
|
28
44
|
deploy again the commit of the last deploy before the current one (the newest
|
|
29
45
|
a running service generation or a routine names) that went live with another
|
|
@@ -41,7 +57,8 @@ const USAGE = `usage: b3os app <command>
|
|
|
41
57
|
to the commit is the rollback that queues behind it
|
|
42
58
|
|
|
43
59
|
The application is the b3os.yaml \`name\` (default: read from ./${MANIFEST_FILE}). b3os apply --keepalive does not
|
|
44
|
-
recreate a generation that was deleted; b3os apply deploys it
|
|
60
|
+
recreate a generation that was deleted (b3os app down), unless an address still serves it; b3os apply deploys it
|
|
61
|
+
again.`;
|
|
45
62
|
function appName(v, required) {
|
|
46
63
|
if (typeof v.app === "string")
|
|
47
64
|
return v.app;
|
|
@@ -160,6 +177,58 @@ function currentDeploy(history, routines) {
|
|
|
160
177
|
current = d;
|
|
161
178
|
return current ?? history[0];
|
|
162
179
|
}
|
|
180
|
+
/** A recreate's cause, as the console says it (apps/web src/lib/app-deploys.ts recreatedWords). */
|
|
181
|
+
const RECREATED_WHY = {
|
|
182
|
+
process: "after a crash",
|
|
183
|
+
crash: "after a crash",
|
|
184
|
+
lease: "after the lease ended",
|
|
185
|
+
probe: "after it failed its readiness probe",
|
|
186
|
+
stopped: "after it stopped",
|
|
187
|
+
};
|
|
188
|
+
/** What a visitor of an address that does not serve gets (review 3, tm17; decision 9): its state's own page. */
|
|
189
|
+
function stateWords(state) {
|
|
190
|
+
if (state === "blocked")
|
|
191
|
+
return BLOCKED_WORDS;
|
|
192
|
+
if (state === "claimed")
|
|
193
|
+
return "it is not live yet: visitors get 503 until a deploy switches it to a generation";
|
|
194
|
+
return "it is stopped: visitors get 503, the app is not running";
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Each service with no running (or paused) generation in the last 7 days, and what starts it again, in one line
|
|
198
|
+
* (DEFECTS 41): how its newest generation ended and when, then the command. A service taken down on purpose is
|
|
199
|
+
* started by b3os apply (keepalive leaves it down); one that hit its spend cap stops again until the cap is raised.
|
|
200
|
+
* With an address the address stays; without one a new generation has a new preview URL.
|
|
201
|
+
*/
|
|
202
|
+
function notRunning(sandboxes, rows) {
|
|
203
|
+
const out = [];
|
|
204
|
+
const seen = new Set();
|
|
205
|
+
const newest = [...sandboxes].sort((x, y) => y.created_at.localeCompare(x.created_at));
|
|
206
|
+
for (const x of newest) {
|
|
207
|
+
const item = x.metadata?.[TAG.item] ?? "";
|
|
208
|
+
if (!item.startsWith("service/"))
|
|
209
|
+
continue;
|
|
210
|
+
const service = item.slice(8);
|
|
211
|
+
if (seen.has(service))
|
|
212
|
+
continue;
|
|
213
|
+
seen.add(service);
|
|
214
|
+
if (newest.some((y) => y.metadata?.[TAG.item] === item && (y.status === "running" || y.status === "paused")))
|
|
215
|
+
continue;
|
|
216
|
+
const at = x.stopped_at ? ` at ${clockOf(x.stopped_at)}` : "";
|
|
217
|
+
const address = rows.find((h) => h.service === service && h.state !== "blocked");
|
|
218
|
+
const fresh = address ? `; its address ${address.url.replace(/\/+$/, "")} stays` : ", with a new URL";
|
|
219
|
+
const line = x.stop_reason === "deleted"
|
|
220
|
+
? `nothing runs: ${x.id} was deleted${at} (b3os app down, or by hand); b3os apply starts it again (keepalive leaves it down)`
|
|
221
|
+
: x.stop_reason === "budget"
|
|
222
|
+
? `nothing runs: ${x.id} stopped at its spend cap or for credits${at}; raise grant.spend_cap_usd (or add credits), then b3os apply`
|
|
223
|
+
: `nothing runs: ${x.stop_reason === "timeout"
|
|
224
|
+
? `the lease ended${at}`
|
|
225
|
+
: x.status === "failed" || x.stop_reason === "failed"
|
|
226
|
+
? `its microVM crashed${at}`
|
|
227
|
+
: `${x.id} is ${x.status}${x.stop_reason ? ` (${x.stop_reason})` : ""}${at}`}; b3os apply --keepalive starts a new generation${fresh}`;
|
|
228
|
+
out.push({ service, sandbox: x.id, stopped_at: x.stopped_at ?? null, line });
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
163
232
|
/** "12 s ago", "4 min ago", "2 h 5 min ago", "3 d ago": how long before now `iso` was. */
|
|
164
233
|
function ago(iso, now = Date.now()) {
|
|
165
234
|
const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
|
|
@@ -220,20 +289,25 @@ function stamped(write) {
|
|
|
220
289
|
write(out);
|
|
221
290
|
};
|
|
222
291
|
}
|
|
292
|
+
/** The options of every `b3os app` subcommand, beside the global ones (also the name check's, test/names.test.ts). */
|
|
293
|
+
const APP_OPTIONS = {
|
|
294
|
+
app: { type: "string" },
|
|
295
|
+
file: { type: "string", short: "f" },
|
|
296
|
+
service: { type: "string" },
|
|
297
|
+
follow: { type: "boolean" },
|
|
298
|
+
failed: { type: "boolean" },
|
|
299
|
+
limit: { type: "string" },
|
|
300
|
+
to: { type: "string" },
|
|
301
|
+
"dry-run": { type: "boolean" },
|
|
302
|
+
"no-record": { type: "boolean" },
|
|
303
|
+
"allow-secret-files": { type: "boolean" },
|
|
304
|
+
ttl: { type: "string" },
|
|
305
|
+
rotate: { type: "boolean" },
|
|
306
|
+
port: { type: "string" },
|
|
307
|
+
};
|
|
223
308
|
async function app(ctx, argv) {
|
|
224
309
|
const [sub, rest] = splitSub(argv);
|
|
225
|
-
const a = parse(rest,
|
|
226
|
-
app: { type: "string" },
|
|
227
|
-
file: { type: "string", short: "f" },
|
|
228
|
-
service: { type: "string" },
|
|
229
|
-
follow: { type: "boolean" },
|
|
230
|
-
failed: { type: "boolean" },
|
|
231
|
-
limit: { type: "string" },
|
|
232
|
-
to: { type: "string" },
|
|
233
|
-
"dry-run": { type: "boolean" },
|
|
234
|
-
"no-record": { type: "boolean" },
|
|
235
|
-
"allow-secret-files": { type: "boolean" },
|
|
236
|
-
});
|
|
310
|
+
const a = parse(rest, APP_OPTIONS);
|
|
237
311
|
ctx.applyGlobals(a.values);
|
|
238
312
|
if (!sub || a.values.help) {
|
|
239
313
|
ctx.out(USAGE);
|
|
@@ -266,9 +340,33 @@ async function app(ctx, argv) {
|
|
|
266
340
|
procs.set(x.id, await processesOf(b3, x.id).catch(why));
|
|
267
341
|
calls.set(x.id, await lastCall(b3, x.id).catch(why));
|
|
268
342
|
}
|
|
343
|
+
// The addresses (null: this API has none yet; a string: why they could not be read).
|
|
344
|
+
const hosts = await listHosts(b3, name).catch(why);
|
|
345
|
+
// The application's own address first (the edge's `primary` when it sends it), then the rest as listed.
|
|
346
|
+
const listed = Array.isArray(hosts) ? hosts : [];
|
|
347
|
+
const own = ownAddress(listed);
|
|
348
|
+
const rows = own ? [own, ...listed.filter((h) => h !== own)] : listed;
|
|
349
|
+
// The status of the sandbox a serving address points at: an address whose generation stopped answers 503.
|
|
350
|
+
const statusOf = (id) => id === null ? null : (sandboxes.find((x) => x.id === id)?.status ?? "gone");
|
|
269
351
|
const doc = {
|
|
270
352
|
object: "app_status",
|
|
271
353
|
app: name,
|
|
354
|
+
addresses: rows.map((h) => ({
|
|
355
|
+
label: h.label,
|
|
356
|
+
url: h.url,
|
|
357
|
+
service: h.service,
|
|
358
|
+
port: h.port,
|
|
359
|
+
access: h.access,
|
|
360
|
+
cookies: h.cookies,
|
|
361
|
+
state: h.state,
|
|
362
|
+
/** The application's own address (the edge's `primary`; from an edge before it, `base_label` null). */
|
|
363
|
+
primary: h === own,
|
|
364
|
+
sandbox: h.sandbox_id,
|
|
365
|
+
/** The served sandbox's status (`gone`: not among the application's sandboxes of the last 7 days). */
|
|
366
|
+
sandbox_status: statusOf(h.sandbox_id),
|
|
367
|
+
dropped_cookies: h.dropped_cookies ?? [],
|
|
368
|
+
})),
|
|
369
|
+
...(typeof hosts === "string" ? { addresses_error: hosts } : {}),
|
|
272
370
|
services: sandboxes
|
|
273
371
|
.filter((x) => (x.metadata?.[TAG.item] ?? "").startsWith("service/"))
|
|
274
372
|
.map((x) => {
|
|
@@ -288,6 +386,8 @@ async function app(ctx, argv) {
|
|
|
288
386
|
stop_reason: x.stop_reason,
|
|
289
387
|
rev: x.metadata?.[TAG.rev] ?? null,
|
|
290
388
|
deploy: x.metadata?.[TAG.deploy] ?? null,
|
|
389
|
+
/** Why a keepalive made this generation (its `b3os.recreated` tag, DEFECTS 38), or null. */
|
|
390
|
+
recreated: parseRecreated(x.metadata?.[TAG.recreated]),
|
|
291
391
|
spec: x.metadata?.[TAG.spec] ?? null,
|
|
292
392
|
created_at: x.created_at,
|
|
293
393
|
expires_at: x.status === "running" ? x.expires_at : null,
|
|
@@ -333,6 +433,8 @@ async function app(ctx, argv) {
|
|
|
333
433
|
created_at: x.created_at,
|
|
334
434
|
expires_at: x.expires_at,
|
|
335
435
|
})),
|
|
436
|
+
/** Each service with no running generation, and what starts it again (DEFECTS 41). */
|
|
437
|
+
not_running: notRunning(sandboxes, listed),
|
|
336
438
|
routines: routines.map((r) => ({
|
|
337
439
|
routine: r.name,
|
|
338
440
|
id: r.id,
|
|
@@ -345,13 +447,40 @@ async function app(ctx, argv) {
|
|
|
345
447
|
};
|
|
346
448
|
ctx.result(doc, () => {
|
|
347
449
|
ctx.out(`application ${name}`);
|
|
450
|
+
if (doc.addresses.length || typeof hosts === "string") {
|
|
451
|
+
ctx.out("addresses");
|
|
452
|
+
if (typeof hosts === "string")
|
|
453
|
+
ctx.out(` not read: ${hosts}`);
|
|
454
|
+
for (const h of doc.addresses) {
|
|
455
|
+
ctx.out(` ${h.url} ${h.state}${h.sandbox ? ` ${h.sandbox}` : ""} (${h.service} port ${h.port}, access ${h.access}, cookies ${h.cookies.mode})`);
|
|
456
|
+
if (h.state === "serving" && h.sandbox && h.sandbox_status !== "running")
|
|
457
|
+
ctx.out(` serving ${h.sandbox}, which is ${h.sandbox_status}: the address answers 503; b3os apply or b3os apply --keepalive recreates it`);
|
|
458
|
+
if (h.state === "claimed")
|
|
459
|
+
ctx.out(" claimed: the next b3os apply switches it to the service's generation");
|
|
460
|
+
if (h.state === "stopped")
|
|
461
|
+
ctx.out(` stopped: the address answers 503; the next b3os apply switches it to the service's generation if b3os.yaml still gives port ${h.port} an address (access, or public: true)`);
|
|
462
|
+
if (h.state === "blocked")
|
|
463
|
+
ctx.out(` ${BLOCKED_WORDS}`);
|
|
464
|
+
// Cookies the app's server never got (cookies: isolated), by name, never a value: the edge counts every
|
|
465
|
+
// name this address did not set, a page script's or one another b3os.io site set for the whole domain.
|
|
466
|
+
for (const d of h.dropped_cookies)
|
|
467
|
+
ctx.out(` the cookie ${d.name}, not set by this address, was dropped on ${d.requests} ${d.requests === 1 ? "request" : "requests"} in the last 7 days; list it under cookies.script only if your own page script sets it`);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
348
470
|
ctx.out("services (newest generation first, last 7 days)");
|
|
349
471
|
// STATUS is the service's: `down (exited TERM)` when the sandbox runs and its process does not.
|
|
350
472
|
ctx.table(doc.services.map((x) => ({ ...x, status: x.exit ? `down (exited ${x.exit.how})` : x.status })), ["service", "sandbox", "status", "stop_reason", "rev", "deploy", "expires_at"]);
|
|
473
|
+
for (const n of doc.not_running)
|
|
474
|
+
ctx.out(`${n.service}: ${n.line}`);
|
|
351
475
|
for (const x of doc.services) {
|
|
352
476
|
if (x.status !== "running")
|
|
353
477
|
continue;
|
|
354
478
|
ctx.out(`${x.service} (${x.sandbox})`);
|
|
479
|
+
if (x.recreated)
|
|
480
|
+
ctx.out(` recreated ${RECREATED_WHY[x.recreated.cause]} ${ago(x.created_at)}: ${x.recreated.reason}${x.recreated.by ? ` (keepalive ${x.recreated.by})` : ""}`);
|
|
481
|
+
for (const h of doc.addresses)
|
|
482
|
+
if (h.state === "serving" && h.sandbox === x.sandbox)
|
|
483
|
+
ctx.out(` address ${h.url}`);
|
|
355
484
|
for (const u of x.urls)
|
|
356
485
|
ctx.out(` public URL ${u}`);
|
|
357
486
|
if ("process" in x)
|
|
@@ -388,7 +517,12 @@ async function app(ctx, argv) {
|
|
|
388
517
|
const name = a.positionals[0] ?? appName(a.values, false);
|
|
389
518
|
const running = runningByService(await listTagged(b3, { [TAG.app]: name }));
|
|
390
519
|
if (!running.size) {
|
|
391
|
-
|
|
520
|
+
// What starts it again, in one line (DEFECTS 41).
|
|
521
|
+
const all = await listTagged(b3, { [TAG.app]: name });
|
|
522
|
+
const rows = await listHosts(b3, name).catch(() => null);
|
|
523
|
+
const wanted = typeof a.values.service === "string" ? a.values.service : undefined;
|
|
524
|
+
const lines = notRunning(all, rows ?? []).filter((n) => !wanted || n.service === wanted);
|
|
525
|
+
ctx.warn(`${name} has no running generation${lines.length ? `: ${lines.map((n) => (lines.length > 1 ? `${n.service}: ${n.line}` : n.line)).join("; ")}` : ": b3os app status lists its generations"}`);
|
|
392
526
|
return EXIT.NOT_FOUND;
|
|
393
527
|
}
|
|
394
528
|
const names = [...running.keys()];
|
|
@@ -453,24 +587,76 @@ async function app(ctx, argv) {
|
|
|
453
587
|
const live = (await listTagged(b3, { [TAG.app]: name })).filter((x) => x.status === "running" || x.status === "paused");
|
|
454
588
|
const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
|
|
455
589
|
const snapshots = (await all(b3.sandboxes.listSnapshots({ limit: 100 }), 200)).filter((x) => x.metadata?.[TAG.app] === name);
|
|
590
|
+
// The addresses serving now (none on an API without them). The edge refuses to delete a sandbox one points at.
|
|
591
|
+
const hosts = await listHosts(b3, name);
|
|
592
|
+
const serving = (hosts ?? []).filter((h) => h.state === "serving" && h.sandbox_id);
|
|
456
593
|
const n = live.length + routines.length + snapshots.length;
|
|
457
|
-
if (!n) {
|
|
594
|
+
if (!n && !serving.length) {
|
|
458
595
|
ctx.info(`nothing tagged b3os.app ${name} in this project`);
|
|
459
596
|
return EXIT.OK;
|
|
460
597
|
}
|
|
598
|
+
for (const h of serving)
|
|
599
|
+
ctx.info(`address ${h.url} serves ${h.sandbox_id}: it stops, and the label stays ${name}'s`);
|
|
461
600
|
for (const x of live)
|
|
462
601
|
ctx.info(`sandbox ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
|
|
463
602
|
for (const r of routines)
|
|
464
603
|
ctx.info(`routine ${r.id} ${r.name}`);
|
|
465
604
|
for (const x of snapshots)
|
|
466
605
|
ctx.info(`snapshot ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
|
|
467
|
-
|
|
606
|
+
const what = serving.length
|
|
607
|
+
? `Stop ${serving.length === 1 ? "this address" : `these ${serving.length} addresses`} and delete these ${n} objects of ${name}?`
|
|
608
|
+
: `Delete these ${n} objects of ${name}?`;
|
|
609
|
+
if (!(await ctx.confirm(what))) {
|
|
468
610
|
ctx.warn("Nothing was deleted.");
|
|
469
611
|
return EXIT.OK;
|
|
470
612
|
}
|
|
471
613
|
const done = [];
|
|
614
|
+
if (serving.length) {
|
|
615
|
+
// Every label to nothing at once (compare-and-swap on what was read), then the apps Worker's cache time and
|
|
616
|
+
// a margin before any TERM, so no request already on its way meets a stopping server.
|
|
617
|
+
await routeHosts(b3, name, {
|
|
618
|
+
targets: serving.map((h) => ({ label: h.label, sandbox_id: null, port: h.port })),
|
|
619
|
+
if_current: Object.fromEntries(serving.map((h) => [h.label, h.sandbox_id])),
|
|
620
|
+
});
|
|
621
|
+
for (const h of serving) {
|
|
622
|
+
done.push({ kind: "address", id: h.label, how: "stopped" });
|
|
623
|
+
ctx.info(`stopped ${h.url} (it served ${h.sandbox_id})`);
|
|
624
|
+
}
|
|
625
|
+
if (serving.some((h) => live.some((x) => x.id === h.sandbox_id))) {
|
|
626
|
+
ctx.info(`waiting ${ROUTE_SETTLE_MS / 1000} s before TERM`);
|
|
627
|
+
await sleep(ROUTE_SETTLE_MS);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Each TERM after a second read of the addresses (FOLLOWUPS 19, as retire, extras and prune do): an apply that
|
|
631
|
+
// ran meanwhile may have switched a label back to one of these, and a sandbox an address serves is kept.
|
|
632
|
+
const kept = [];
|
|
472
633
|
for (const x of live) {
|
|
473
|
-
|
|
634
|
+
if (hosts !== null) {
|
|
635
|
+
const now = await listHosts(b3, name).then((r) => r ?? [], (e) => (e instanceof Error ? e : new Error(String(e))));
|
|
636
|
+
const label = now instanceof Error ? undefined : now.find((h) => h.state === "serving" && h.sandbox_id === x.id)?.label;
|
|
637
|
+
if (now instanceof Error || label) {
|
|
638
|
+
const why = label ? `kept ${x.id}, which serves ${label}` : `kept ${x.id}: the addresses could not be read`;
|
|
639
|
+
kept.push({ id: x.id, why, ...(label ? { label } : {}) });
|
|
640
|
+
ctx.warn(why);
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
// Without the address routes (they answered off) a generation made for an address may still serve one
|
|
645
|
+
// (review 3, T5): it is deleted first, so the edge's delete guard answers before anything stops it. A refused
|
|
646
|
+
// delete keeps the sandbox, in the edge's words, and app down goes on with the rest.
|
|
647
|
+
const first = hosts === null && (x.ports ?? []).some((p) => p.addressed === true) ? "delete" : "term";
|
|
648
|
+
let how;
|
|
649
|
+
try {
|
|
650
|
+
how = await retire(b3, x, 30, 1000, undefined, first);
|
|
651
|
+
}
|
|
652
|
+
catch (e) {
|
|
653
|
+
if (!(e instanceof StepError) || e.code !== "sandbox_routed")
|
|
654
|
+
throw e;
|
|
655
|
+
const why = `kept ${x.id}: the edge refused its delete: ${e.message.replace(/^\S+ was not deleted: /, "")}`;
|
|
656
|
+
kept.push({ id: x.id, why });
|
|
657
|
+
ctx.warn(why);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
474
660
|
done.push({ kind: "sandbox", id: x.id, how });
|
|
475
661
|
ctx.info(`deleted ${x.id} (${how})`);
|
|
476
662
|
}
|
|
@@ -484,7 +670,98 @@ async function app(ctx, argv) {
|
|
|
484
670
|
done.push({ kind: "snapshot", id: x.id, how: "deleted" });
|
|
485
671
|
ctx.info(`deleted snapshot ${x.id}`);
|
|
486
672
|
}
|
|
487
|
-
|
|
673
|
+
const stopped = done.filter((d) => d.kind === "address").length;
|
|
674
|
+
ctx.result({
|
|
675
|
+
object: "app_down",
|
|
676
|
+
app: name,
|
|
677
|
+
deleted: done.filter((d) => d.kind !== "address"),
|
|
678
|
+
stopped: done.filter((d) => d.kind === "address"),
|
|
679
|
+
kept,
|
|
680
|
+
}, () => ctx.out(`${name}: ${stopped ? `stopped ${stopped} ${stopped === 1 ? "address" : "addresses"}, ` : ""}deleted ${done.length - stopped} objects${kept.length ? `; ${kept.map((k) => k.why).join("; ")}` : ""}`));
|
|
681
|
+
return EXIT.OK;
|
|
682
|
+
}
|
|
683
|
+
case "open": {
|
|
684
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
685
|
+
const hosts = await listHosts(b3, name);
|
|
686
|
+
if (hosts === null) {
|
|
687
|
+
ctx.warn(`this API has no app addresses yet: b3os app status prints each running generation's URL`);
|
|
688
|
+
return EXIT.NOT_FOUND;
|
|
689
|
+
}
|
|
690
|
+
const svc = typeof a.values.service === "string" ? a.values.service : undefined;
|
|
691
|
+
const mine = hosts.filter((h) => !svc || h.service === svc);
|
|
692
|
+
const row = ownAddress(mine) ?? mine[0];
|
|
693
|
+
if (!row) {
|
|
694
|
+
ctx.warn(`${name} has no address${svc ? ` for service ${svc}` : ""}: b3os apply claims one for a port with access (or public: true)`);
|
|
695
|
+
return EXIT.NOT_FOUND;
|
|
696
|
+
}
|
|
697
|
+
// What a visitor gets there now, by the state's own page (review 3, tm17; decision 9).
|
|
698
|
+
if (row.state !== "serving")
|
|
699
|
+
ctx.warn(`${row.url}: ${stateWords(row.state)}`);
|
|
700
|
+
if (ctx.json || !ctx.isTTY) {
|
|
701
|
+
ctx.result({ object: "app_address", app: name, url: row.url, state: row.state, access: row.access }, () => ctx.out(row.url));
|
|
702
|
+
if (row.access === "link")
|
|
703
|
+
ctx.info("a link address lets in only people with a link: b3os app link prints one");
|
|
704
|
+
return EXIT.OK;
|
|
705
|
+
}
|
|
706
|
+
// A link address lets the owner in with a link of 60 s (its cookie then lasts 30 days); the link is never
|
|
707
|
+
// printed, and it is on the opener's argument list for that minute only. The URL is the address itself, checked
|
|
708
|
+
// here: never a string the server chose as it is, and never through a shell.
|
|
709
|
+
const clean = `https://${row.label}.${APP_DOMAIN}`;
|
|
710
|
+
const url = row.access === "link" ? (await createLink(b3, name, { label: row.label, ttl_s: 60 })).url : `${clean}/`;
|
|
711
|
+
if (!openable(url, row.label))
|
|
712
|
+
throw new CliError(`the edge answered a URL that is not ${clean}/ with a link: not opened`, {
|
|
713
|
+
code: "unexpected_url",
|
|
714
|
+
exit: EXIT.SERVER,
|
|
715
|
+
hint: "b3os app link prints a link to the address",
|
|
716
|
+
});
|
|
717
|
+
if (process.platform === "win32")
|
|
718
|
+
ctx.info(WINDOWS_OPENER_NOTE);
|
|
719
|
+
if (!(await openBrowser(url))) {
|
|
720
|
+
ctx.out(clean);
|
|
721
|
+
ctx.info("no browser started here: b3os app link prints a link");
|
|
722
|
+
return EXIT.OK;
|
|
723
|
+
}
|
|
724
|
+
ctx.info(`opened ${clean}${row.access === "link" ? " with a link that ends in 60 s" : ""}`);
|
|
725
|
+
return EXIT.OK;
|
|
726
|
+
}
|
|
727
|
+
case "link": {
|
|
728
|
+
const name = a.positionals[0] ?? appName(a.values, false);
|
|
729
|
+
const ttl = intFlag(a.values.ttl, "--ttl") ?? 604_800;
|
|
730
|
+
if (ttl < 60 || ttl > 7_776_000)
|
|
731
|
+
throw new UsageError("--ttl is 60 to 7776000 seconds (90 days)");
|
|
732
|
+
const rotate = a.values.rotate === true;
|
|
733
|
+
// Review 2, sm19: the edge ends no stream it already let in; an open one runs until its hour is up.
|
|
734
|
+
const rotation = `Rotating makes every link to ${name} stop working within ${ROUTE_STALE_MAX_MS / 1000} s; streams and WebSockets already open can run up to an hour more.`;
|
|
735
|
+
if (rotate) {
|
|
736
|
+
ctx.warn(rotation);
|
|
737
|
+
if (!(await ctx.confirm(`Rotate the link secret of ${name}?`))) {
|
|
738
|
+
ctx.warn("Nothing was changed.");
|
|
739
|
+
return EXIT.OK;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const label = await linkLabel(b3, name, a.values);
|
|
743
|
+
if (label === null) {
|
|
744
|
+
ctx.warn("this API has no app addresses yet, so there is no link to make");
|
|
745
|
+
return EXIT.NOT_FOUND;
|
|
746
|
+
}
|
|
747
|
+
let link;
|
|
748
|
+
try {
|
|
749
|
+
link = await createLink(b3, name, {
|
|
750
|
+
...(label ? { label } : {}),
|
|
751
|
+
ttl_s: ttl,
|
|
752
|
+
...(rotate ? { rotate: true } : {}),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
catch (e) {
|
|
756
|
+
if (!noHostsRoutes(e))
|
|
757
|
+
throw e;
|
|
758
|
+
ctx.warn("this API has no app addresses yet, so there is no link to make");
|
|
759
|
+
return EXIT.NOT_FOUND;
|
|
760
|
+
}
|
|
761
|
+
ctx.result(rotate ? { ...link, warning: rotation } : link, () => {
|
|
762
|
+
ctx.out(link.url);
|
|
763
|
+
ctx.info(`a link to https://${link.label}.b3os.io until ${link.expires_at}${link.rotated ? ", made after the rotation" : ""}: anyone who has it gets in, so send it only to the people it is for`);
|
|
764
|
+
});
|
|
488
765
|
return EXIT.OK;
|
|
489
766
|
}
|
|
490
767
|
case "rollback": {
|
|
@@ -520,9 +797,15 @@ async function app(ctx, argv) {
|
|
|
520
797
|
}
|
|
521
798
|
const served = history.filter((h) => h.served && h.commit);
|
|
522
799
|
const listed = served.map((h) => `${h.deploy} (${h.commit?.slice(0, 7)})`).join(", ");
|
|
523
|
-
const
|
|
800
|
+
const picked = to
|
|
524
801
|
? served.find((h) => h.deploy === to)
|
|
525
802
|
: served.find((h) => current && deployAfter(current.deploy, h.deploy) && h.commit !== current.commit);
|
|
803
|
+
// The deploy that shipped that commit (DEFECTS 39): the oldest of the deploys before it that ran the same commit
|
|
804
|
+
// one after another, not a keepalive's recreate of it. --to is the exact deploy named.
|
|
805
|
+
let target = picked;
|
|
806
|
+
if (!to && picked)
|
|
807
|
+
for (let i = served.indexOf(picked) + 1; served[i]?.commit === picked.commit; i++)
|
|
808
|
+
target = served[i];
|
|
526
809
|
if (!target) {
|
|
527
810
|
if (to)
|
|
528
811
|
throw new UsageError(`${to} is not a deploy of ${name} that went live in the last 7 days: ${listed}`);
|
|
@@ -536,6 +819,21 @@ async function app(ctx, argv) {
|
|
|
536
819
|
exit: EXIT.NOT_FOUND,
|
|
537
820
|
hint: `fetch it (git fetch origin, or git fetch --unshallow in a shallow clone), then run b3os app rollback again; nothing was changed`,
|
|
538
821
|
});
|
|
822
|
+
// HEAD reverts the target when its tree (the application's folder) is the target's parent's (DEFECTS 39): the
|
|
823
|
+
// rollback then deploys again what HEAD took out, and the plan's first line says so.
|
|
824
|
+
const head = git.resolveCommit(root, "HEAD");
|
|
825
|
+
const parent = git.resolveCommit(root, `${commit}^`);
|
|
826
|
+
const dirRel = git.inRepo(root, dirname(file));
|
|
827
|
+
const reverts = (() => {
|
|
828
|
+
if (!head || !parent || head === commit)
|
|
829
|
+
return false;
|
|
830
|
+
try {
|
|
831
|
+
return git.treeHash(root, head, dirRel) === git.treeHash(root, parent, dirRel);
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
})();
|
|
539
837
|
const ac = new AbortController();
|
|
540
838
|
const options = {
|
|
541
839
|
mode: a.values["dry-run"] === true ? "dry-run" : "apply",
|
|
@@ -550,6 +848,7 @@ async function app(ctx, argv) {
|
|
|
550
848
|
liveAt: target.liveAt,
|
|
551
849
|
startedAt: target.liveAt ? null : target.startedAt,
|
|
552
850
|
from: current?.commit?.slice(0, 7) ?? null,
|
|
851
|
+
...(reverts && head ? { revertedBy: head.slice(0, 7) } : {}),
|
|
553
852
|
}, ctx.credential().baseUrl, options);
|
|
554
853
|
if ("problem" in planned) {
|
|
555
854
|
ctx.warn(`${planned.problem}; nothing was changed`);
|
|
@@ -566,12 +865,58 @@ async function app(ctx, argv) {
|
|
|
566
865
|
throw new UsageError(`unknown app command "${sub}"\n${USAGE}`);
|
|
567
866
|
}
|
|
568
867
|
}
|
|
868
|
+
/**
|
|
869
|
+
* Whether `url` is what `b3os app open` may hand a browser: exactly `https://<label>.<app domain>/`, with at most a
|
|
870
|
+
* `?b3os_link=` of a link token's shape (apps/edge/src/apphosts/link.ts LINK_TOKEN).
|
|
871
|
+
*/
|
|
872
|
+
export function openable(url, label) {
|
|
873
|
+
if (!LABEL.test(label))
|
|
874
|
+
return false;
|
|
875
|
+
const host = `${label}.${APP_DOMAIN}`.replace(/[.]/g, "\\.");
|
|
876
|
+
return new RegExp(`^https://${host}/(\\?b3os_link=(0|[1-9][0-9]{0,11})\\.[A-Za-z0-9_-]{43})?$`).test(url);
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* The label `b3os app link` asks for: undefined for the application's own (the edge picks it), the address of
|
|
880
|
+
* `--service` (and `--port`), or null when the API has no addresses.
|
|
881
|
+
*/
|
|
882
|
+
async function linkLabel(b3, app, v) {
|
|
883
|
+
const service = typeof v.service === "string" ? v.service : undefined;
|
|
884
|
+
const port = intFlag(v.port, "--port");
|
|
885
|
+
const rows = await listHosts(b3, app);
|
|
886
|
+
if (rows === null)
|
|
887
|
+
return null;
|
|
888
|
+
// No flag: the application's own address, the edge's `primary` row when it says which (else the edge picks).
|
|
889
|
+
if (service === undefined && port === undefined)
|
|
890
|
+
return rows.some((h) => h.primary !== undefined) ? ownAddress(rows)?.label : undefined;
|
|
891
|
+
const mine = rows.filter((h) => (service === undefined || h.service === service) && (port === undefined || h.port === port));
|
|
892
|
+
const what = `${service ? `service ${service}` : app}${port !== undefined ? ` port ${port}` : ""}`;
|
|
893
|
+
if (!mine.length)
|
|
894
|
+
throw new UsageError(`${app} has no address for ${what}: ${rows.map((h) => `${h.service} port ${h.port}`).join(", ") || "none yet"}`);
|
|
895
|
+
if (mine.length === 1)
|
|
896
|
+
return mine[0].label;
|
|
897
|
+
// The service holds the application's own label: that one, as b3os app link without --service gives.
|
|
898
|
+
const own = ownAddress(mine);
|
|
899
|
+
if (own)
|
|
900
|
+
return own.label;
|
|
901
|
+
throw new UsageError(`${what} has ${mine.length} addresses (ports ${mine.map((h) => h.port).join(", ")}): pass --port`);
|
|
902
|
+
}
|
|
903
|
+
/** `POST /v1/apps/{app}/hosts/link`: a link to one of the application's link addresses (its own by default). */
|
|
904
|
+
function createLink(b3, app, body) {
|
|
905
|
+
return b3.request({
|
|
906
|
+
method: "POST",
|
|
907
|
+
path: `/v1/apps/${encodeURIComponent(app)}/hosts/link`,
|
|
908
|
+
body,
|
|
909
|
+
edge: true,
|
|
910
|
+
timeoutMs: 15_000,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
569
913
|
export const commands = [
|
|
570
914
|
{
|
|
571
915
|
name: "app",
|
|
572
|
-
summary: "Status,
|
|
916
|
+
summary: "Status, address, logs and rollback of an app (status, open, link, logs, requests, rollback, down)",
|
|
573
917
|
order: 245,
|
|
574
918
|
run: app,
|
|
919
|
+
options: APP_OPTIONS,
|
|
575
920
|
},
|
|
576
921
|
];
|
|
577
922
|
//# sourceMappingURL=app.js.map
|