@b3os/cli 0.2.0 → 0.2.2

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.
Files changed (217) hide show
  1. package/README.md +87 -7
  2. package/assets/b3os-run.py +137 -0
  3. package/assets/skill/b3os/SKILL.md +111 -0
  4. package/dist/commands/_agents.d.ts +14 -0
  5. package/dist/commands/_agents.js +33 -0
  6. package/dist/commands/_agents.js.map +1 -0
  7. package/dist/commands/_common.js +6 -2
  8. package/dist/commands/_common.js.map +1 -1
  9. package/dist/commands/_context.d.ts +49 -0
  10. package/dist/commands/_context.js +260 -0
  11. package/dist/commands/_context.js.map +1 -0
  12. package/dist/commands/_next.d.ts +39 -0
  13. package/dist/commands/_next.js +77 -0
  14. package/dist/commands/_next.js.map +1 -0
  15. package/dist/commands/agent.d.ts +42 -0
  16. package/dist/commands/agent.js +218 -0
  17. package/dist/commands/agent.js.map +1 -0
  18. package/dist/commands/app.d.ts +2 -0
  19. package/dist/commands/app.js +559 -54
  20. package/dist/commands/app.js.map +1 -1
  21. package/dist/commands/auth.d.ts +88 -2
  22. package/dist/commands/auth.js +354 -44
  23. package/dist/commands/auth.js.map +1 -1
  24. package/dist/commands/docs.d.ts +54 -0
  25. package/dist/commands/docs.js +202 -0
  26. package/dist/commands/docs.js.map +1 -0
  27. package/dist/commands/doctor.d.ts +23 -0
  28. package/dist/commands/doctor.js +313 -0
  29. package/dist/commands/doctor.js.map +1 -0
  30. package/dist/commands/init.d.ts +38 -1
  31. package/dist/commands/init.js +259 -60
  32. package/dist/commands/init.js.map +1 -1
  33. package/dist/commands/listen.d.ts +30 -0
  34. package/dist/commands/listen.js +194 -0
  35. package/dist/commands/listen.js.map +1 -0
  36. package/dist/commands/manifest.d.ts +13 -1
  37. package/dist/commands/manifest.js +81 -18
  38. package/dist/commands/manifest.js.map +1 -1
  39. package/dist/commands/mcp.d.ts +25 -2
  40. package/dist/commands/mcp.js +120 -11
  41. package/dist/commands/mcp.js.map +1 -1
  42. package/dist/commands/sandbox.d.ts +35 -6
  43. package/dist/commands/sandbox.js +208 -9
  44. package/dist/commands/sandbox.js.map +1 -1
  45. package/dist/commands/setup.d.ts +39 -0
  46. package/dist/commands/setup.js +203 -0
  47. package/dist/commands/setup.js.map +1 -0
  48. package/dist/commands/tool.d.ts +154 -0
  49. package/dist/commands/tool.js +785 -0
  50. package/dist/commands/tool.js.map +1 -0
  51. package/dist/config.d.ts +30 -6
  52. package/dist/config.js +39 -8
  53. package/dist/config.js.map +1 -1
  54. package/dist/ctx.d.ts +5 -45
  55. package/dist/ctx.js +25 -160
  56. package/dist/ctx.js.map +1 -1
  57. package/dist/docs/index.json +1 -0
  58. package/dist/docs/pages/actions/call.md +300 -0
  59. package/dist/docs/pages/actions/catalog/airtable.md +737 -0
  60. package/dist/docs/pages/actions/catalog/arxiv.md +166 -0
  61. package/dist/docs/pages/actions/catalog/chainalysis-sanctions.md +125 -0
  62. package/dist/docs/pages/actions/catalog/coingecko.md +1558 -0
  63. package/dist/docs/pages/actions/catalog/deps-dev.md +465 -0
  64. package/dist/docs/pages/actions/catalog/dexscreener.md +568 -0
  65. package/dist/docs/pages/actions/catalog/discord.md +784 -0
  66. package/dist/docs/pages/actions/catalog/finnhub.md +776 -0
  67. package/dist/docs/pages/actions/catalog/frankfurter.md +438 -0
  68. package/dist/docs/pages/actions/catalog/github.md +1853 -0
  69. package/dist/docs/pages/actions/catalog/gmail.md +575 -0
  70. package/dist/docs/pages/actions/catalog/google-calendar.md +654 -0
  71. package/dist/docs/pages/actions/catalog/google-drive.md +502 -0
  72. package/dist/docs/pages/actions/catalog/google-sheets.md +700 -0
  73. package/dist/docs/pages/actions/catalog/hacker-news.md +542 -0
  74. package/dist/docs/pages/actions/catalog/http.md +824 -0
  75. package/dist/docs/pages/actions/catalog/hyperliquid.md +942 -0
  76. package/dist/docs/pages/actions/catalog/jira.md +920 -0
  77. package/dist/docs/pages/actions/catalog/kalshi.md +917 -0
  78. package/dist/docs/pages/actions/catalog/linear.md +1030 -0
  79. package/dist/docs/pages/actions/catalog/markets.md +21 -0
  80. package/dist/docs/pages/actions/catalog/morpho.md +247 -0
  81. package/dist/docs/pages/actions/catalog/notion.md +1077 -0
  82. package/dist/docs/pages/actions/catalog/nws.md +485 -0
  83. package/dist/docs/pages/actions/catalog/open-meteo.md +559 -0
  84. package/dist/docs/pages/actions/catalog/polymarket.md +1523 -0
  85. package/dist/docs/pages/actions/catalog/pushbullet.md +220 -0
  86. package/dist/docs/pages/actions/catalog/resend.md +307 -0
  87. package/dist/docs/pages/actions/catalog/s3.md +513 -0
  88. package/dist/docs/pages/actions/catalog/sec-edgar.md +487 -0
  89. package/dist/docs/pages/actions/catalog/slack.md +2629 -0
  90. package/dist/docs/pages/actions/catalog/stripe.md +1405 -0
  91. package/dist/docs/pages/actions/catalog/wikipedia.md +379 -0
  92. package/dist/docs/pages/actions/catalog.md +46 -0
  93. package/dist/docs/pages/actions/limits.md +50 -0
  94. package/dist/docs/pages/actions/model-tools.md +225 -0
  95. package/dist/docs/pages/actions/packs.md +148 -0
  96. package/dist/docs/pages/actions/settings.md +69 -0
  97. package/dist/docs/pages/actions/tools.md +244 -0
  98. package/dist/docs/pages/actions/triggers.md +149 -0
  99. package/dist/docs/pages/actions.md +88 -0
  100. package/dist/docs/pages/compat/anthropic.md +168 -0
  101. package/dist/docs/pages/compat/e2b.md +194 -0
  102. package/dist/docs/pages/compat/firecrawl.md +138 -0
  103. package/dist/docs/pages/compat/openai.md +168 -0
  104. package/dist/docs/pages/concepts/auth.md +151 -0
  105. package/dist/docs/pages/concepts/beta.md +55 -0
  106. package/dist/docs/pages/concepts/glossary.md +71 -0
  107. package/dist/docs/pages/concepts/ids.md +98 -0
  108. package/dist/docs/pages/concepts/jobs.md +229 -0
  109. package/dist/docs/pages/concepts/latency.md +138 -0
  110. package/dist/docs/pages/concepts/limits.md +191 -0
  111. package/dist/docs/pages/concepts/stack.md +59 -0
  112. package/dist/docs/pages/concepts/timing.md +86 -0
  113. package/dist/docs/pages/concepts/usage.md +110 -0
  114. package/dist/docs/pages/design/b3os-yaml.md +370 -0
  115. package/dist/docs/pages/design/deploy-from-github.md +122 -0
  116. package/dist/docs/pages/design/observability.md +134 -0
  117. package/dist/docs/pages/errors.md +1824 -0
  118. package/dist/docs/pages/infer/chat.md +570 -0
  119. package/dist/docs/pages/infer/limits.md +55 -0
  120. package/dist/docs/pages/infer/messages.md +185 -0
  121. package/dist/docs/pages/infer/responses.md +173 -0
  122. package/dist/docs/pages/infer/settings.md +154 -0
  123. package/dist/docs/pages/infer/speech.md +323 -0
  124. package/dist/docs/pages/infer.md +154 -0
  125. package/dist/docs/pages/introduction.md +162 -0
  126. package/dist/docs/pages/platform/addresses.md +174 -0
  127. package/dist/docs/pages/platform/call-log.md +99 -0
  128. package/dist/docs/pages/platform/custom-domains.md +104 -0
  129. package/dist/docs/pages/platform/keys.md +79 -0
  130. package/dist/docs/pages/platform/limits.md +57 -0
  131. package/dist/docs/pages/platform/members.md +101 -0
  132. package/dist/docs/pages/platform/requests.md +116 -0
  133. package/dist/docs/pages/platform/settings.md +129 -0
  134. package/dist/docs/pages/platform/webhooks.md +68 -0
  135. package/dist/docs/pages/platform.md +67 -0
  136. package/dist/docs/pages/quickstart/mcp.md +94 -0
  137. package/dist/docs/pages/quickstart/sandbox-agent.md +205 -0
  138. package/dist/docs/pages/quickstart/scrape.md +134 -0
  139. package/dist/docs/pages/quickstart.md +45 -0
  140. package/dist/docs/pages/render/inspections.md +162 -0
  141. package/dist/docs/pages/render/limits.md +72 -0
  142. package/dist/docs/pages/render/screenshots.md +179 -0
  143. package/dist/docs/pages/render/settings.md +431 -0
  144. package/dist/docs/pages/render/styles.md +342 -0
  145. package/dist/docs/pages/render/videos.md +272 -0
  146. package/dist/docs/pages/render.md +118 -0
  147. package/dist/docs/pages/routines/callables.md +174 -0
  148. package/dist/docs/pages/routines/definitions.md +361 -0
  149. package/dist/docs/pages/routines/limits.md +117 -0
  150. package/dist/docs/pages/routines/runs.md +328 -0
  151. package/dist/docs/pages/routines/settings.md +104 -0
  152. package/dist/docs/pages/routines/triggers.md +339 -0
  153. package/dist/docs/pages/routines.md +216 -0
  154. package/dist/docs/pages/sandboxes/agents.md +217 -0
  155. package/dist/docs/pages/sandboxes/commands.md +272 -0
  156. package/dist/docs/pages/sandboxes/images.md +166 -0
  157. package/dist/docs/pages/sandboxes/limits.md +143 -0
  158. package/dist/docs/pages/sandboxes/ports.md +260 -0
  159. package/dist/docs/pages/sandboxes/settings.md +358 -0
  160. package/dist/docs/pages/sandboxes/snapshots.md +423 -0
  161. package/dist/docs/pages/sandboxes/swarms.md +146 -0
  162. package/dist/docs/pages/sandboxes/volumes.md +131 -0
  163. package/dist/docs/pages/sandboxes.md +231 -0
  164. package/dist/docs/pages/sdks/cli.md +121 -0
  165. package/dist/docs/pages/sdks/mcp.md +169 -0
  166. package/dist/docs/pages/sdks/python.md +146 -0
  167. package/dist/docs/pages/sdks/typescript.md +202 -0
  168. package/dist/docs/pages/sdks.md +282 -0
  169. package/dist/docs/pages/settings.md +33 -0
  170. package/dist/docs/pages/vault/limits.md +46 -0
  171. package/dist/docs/pages/vault.md +133 -0
  172. package/dist/docs/pages/vision/agent-browser.md +115 -0
  173. package/dist/docs/pages/vision/crawl.md +333 -0
  174. package/dist/docs/pages/vision/extract.md +152 -0
  175. package/dist/docs/pages/vision/fetcher.md +15 -0
  176. package/dist/docs/pages/vision/limits.md +79 -0
  177. package/dist/docs/pages/vision/profiles.md +111 -0
  178. package/dist/docs/pages/vision/proxy.md +131 -0
  179. package/dist/docs/pages/vision/scrape.md +356 -0
  180. package/dist/docs/pages/vision/sessions.md +311 -0
  181. package/dist/docs/pages/vision/settings.md +656 -0
  182. package/dist/docs/pages/vision.md +175 -0
  183. package/dist/errors.d.ts +129 -0
  184. package/dist/errors.js +326 -0
  185. package/dist/errors.js.map +1 -0
  186. package/dist/main.d.ts +1 -1
  187. package/dist/main.js +26 -13
  188. package/dist/main.js.map +1 -1
  189. package/dist/manifest/apply.d.ts +4 -0
  190. package/dist/manifest/apply.js +2 -0
  191. package/dist/manifest/apply.js.map +1 -1
  192. package/dist/manifest/domains.d.ts +50 -0
  193. package/dist/manifest/domains.js +159 -0
  194. package/dist/manifest/domains.js.map +1 -0
  195. package/dist/manifest/link.d.ts +20 -0
  196. package/dist/manifest/link.js +24 -0
  197. package/dist/manifest/link.js.map +1 -0
  198. package/dist/manifest/record.d.ts +1 -1
  199. package/dist/tool/archive.d.ts +33 -0
  200. package/dist/tool/archive.js +174 -0
  201. package/dist/tool/archive.js.map +1 -0
  202. package/dist/tool/calls.d.ts +46 -0
  203. package/dist/tool/calls.js +274 -0
  204. package/dist/tool/calls.js.map +1 -0
  205. package/dist/tool/checks.d.ts +21 -0
  206. package/dist/tool/checks.js +145 -0
  207. package/dist/tool/checks.js.map +1 -0
  208. package/dist/tool/elf.d.ts +19 -0
  209. package/dist/tool/elf.js +107 -0
  210. package/dist/tool/elf.js.map +1 -0
  211. package/dist/tool/predict.d.ts +8 -0
  212. package/dist/tool/predict.js +38 -0
  213. package/dist/tool/predict.js.map +1 -0
  214. package/dist/tool/ustar.d.ts +5 -0
  215. package/dist/tool/ustar.js +220 -0
  216. package/dist/tool/ustar.js.map +1 -0
  217. package/package.json +6 -5
@@ -1,20 +1,29 @@
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 { appVolumes, BLOCKED_WORDS, clockOf, crashLoopWords, deployAfter, downWords, lastExitWords, listHosts, noHostsRoutes, ownAddress, parseRecreated, restartWords, revCommit, routeHosts, StepError, serviceHealth, serviceProcess, sleep, supervisedEntry, VOLUME_FREE_MS, validDepId, validDeployId, volumeFree, } from "@b3os/deploy";
8
+ import { APP_DOMAIN, 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";
11
+ import { domains } from "../manifest/domains.js";
12
+ import { createLink, openable } from "../manifest/link.js";
9
13
  import { loadManifest, MANIFEST_FILE } from "../manifest/load.js";
10
14
  import * as git from "../manifest/source.js";
15
+ import { openBrowser, WINDOWS_OPENER_NOTE } from "./auth.js";
11
16
  import { runPlanned } from "./manifest.js";
12
17
  import { sandboxRequests } from "./requests.js";
18
+ export { openable };
13
19
  const USAGE = `usage: b3os app <command>
14
- status [--file FILE | --app NAME] the application's service generations (last 7 days), build snapshots and
15
- routines with their last runs, found by their b3os.app tag; for each running
16
- generation its URL, its process, its last call to B3OS, when its lease ends
17
- and its logs command
20
+ status [--file FILE | --app NAME] the application's addresses (https://<label>.b3os.io: state, the generation
21
+ each serves, cookies this address did not set that were dropped), its service
22
+ generations (last 7 days), build snapshots and routines with their last runs,
23
+ found by their b3os.app tag; for each running generation its URL, its process,
24
+ its last call to B3OS, when its lease ends, its logs command, and why a
25
+ keepalive recreated it; for a service with none running, what starts it again;
26
+ its volumes (size, used, which generation holds each)
18
27
  logs [APP] [--service NAME] [--follow]
19
28
  a running service's output, each line with its time (UTC); --follow keeps
20
29
  reading until the process exits
@@ -22,8 +31,32 @@ const USAGE = `usage: b3os app <command>
22
31
  the calls each service made to B3OS (models, scrapes, sandboxes), newest
23
32
  first, from its running generation (else its newest); --failed keeps 4xx and
24
33
  5xx; needs only sandboxes:read
25
- down --app NAME [--yes] delete them: each running generation (TERM, up to 30 s to exit, then
26
- delete), then the routines, then the build snapshots
34
+ open [APP] [--service NAME] open the application's address in the browser (a link address with a link
35
+ that ends in 60 s); without a terminal, or when no browser starts, print the
36
+ address. On Windows it starts the browser with rundll32, untested on Windows
37
+ link [APP] [--service NAME [--port N]] [--ttl S] [--rotate] [--yes]
38
+ print a link to the application's own address, or to the address of service
39
+ NAME (--port N when it has more than one), valid --ttl seconds (default
40
+ 604800, 7 days; 60 to 7776000): anyone who has it gets in. --rotate first makes
41
+ every link stop working within 6 s (streams and WebSockets already open can run
42
+ up to an hour more), then makes the new link
43
+ domains [ls] | add HOSTNAME [--service NAME [--port N]] | verify HOSTNAME | rm HOSTNAME [--yes]
44
+ the application's custom domains (shop.example.com): add prints the DNS record
45
+ to add at your DNS host (a CNAME to the address, or at the root of a zone an
46
+ ALIAS and a TXT record); verify looks for it now (B3OS also looks every 5
47
+ minutes; a domain whose record is not seen within 72 hours is dropped); ls
48
+ prints each one's state; rm stops it serving at once. A domain whose record
49
+ stops naming the address stops serving too
50
+ A domain serves the application's own address, or that of service NAME (--port
51
+ N when it has more than one); the address keeps serving too. Not turned on
52
+ for customers yet: B3 runs custom domains on its own organization first
53
+ down --app NAME [--yes] [--delete-volumes NAME]
54
+ stop its addresses (each label stays the application's), wait 7 s, then
55
+ delete: each running generation (TERM, up to 30 s to exit, then delete; one
56
+ an address serves again by then is kept), then the routines, then the build
57
+ snapshots. Its volumes are kept, with their data, and listed; --delete-volumes
58
+ with the application's name typed again deletes them too (each is restorable
59
+ for 7 days: b3os sandbox volumes restore NAME)
27
60
  rollback [APP] [--to DEPLOY] [--yes] [--dry-run]
28
61
  deploy again the commit of the last deploy before the current one (the newest
29
62
  a running service generation or a routine names) that went live with another
@@ -41,7 +74,12 @@ const USAGE = `usage: b3os app <command>
41
74
  to the commit is the rollback that queues behind it
42
75
 
43
76
  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 again.`;
77
+ recreate a generation that was deleted (b3os app down), unless an address still serves it; b3os apply deploys it
78
+ again.`;
79
+ /** A volume's used bytes: MiB, or GiB from 1 GiB. */
80
+ function mibOrGib(n) {
81
+ return n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(1)} GiB` : `${Math.round(n / 1024 ** 2)} MiB`;
82
+ }
45
83
  function appName(v, required) {
46
84
  if (typeof v.app === "string")
47
85
  return v.app;
@@ -68,6 +106,33 @@ function commandsOf(v, name) {
68
106
  }
69
107
  return out;
70
108
  }
109
+ /** How long `app logs --follow` waits for the node to start a supervised command again (the backoff's cap and more). */
110
+ const RESTART_WAIT_MS = 90_000;
111
+ /**
112
+ * The process the node started in place of `pid` (stay-up C1), waiting through its backoff: null when the sandbox
113
+ * ended, nothing supervises the command, or the supervision stopped, exited or is in a crash loop.
114
+ */
115
+ async function restartedFrom(b3, sandbox, cmd, pid, poll = 500) {
116
+ const until = Date.now() + RESTART_WAIT_MS;
117
+ for (;;) {
118
+ const s = await b3.sandboxes.getSandbox(sandbox).catch(() => null);
119
+ const sup = s?.status === "running" ? supervisedEntry(s.supervised, cmd) : null;
120
+ if (!sup || !["starting", "running", "backoff"].includes(sup.state))
121
+ return null;
122
+ if (sup.pid !== null && sup.pid !== pid && sup.state !== "backoff") {
123
+ const e = sup.last_exit;
124
+ const how = e?.signal
125
+ ? e.signal.replace(/^SIG/, "")
126
+ : e?.exit_code != null
127
+ ? `code ${e.exit_code}`
128
+ : "with no code";
129
+ return { pid: sup.pid, how };
130
+ }
131
+ if (Date.now() >= until)
132
+ return null;
133
+ await sleep(poll);
134
+ }
135
+ }
71
136
  /** A generation's processes (the service's is picked by @b3os/deploy serviceProcess: its command, else the oldest). */
72
137
  async function processesOf(b3, sandbox) {
73
138
  return (await b3.sandboxes.listProcesses(sandbox)).data;
@@ -160,6 +225,58 @@ function currentDeploy(history, routines) {
160
225
  current = d;
161
226
  return current ?? history[0];
162
227
  }
228
+ /** A recreate's cause, as the console says it (apps/web src/lib/app-deploys.ts recreatedWords). */
229
+ const RECREATED_WHY = {
230
+ process: "after a crash",
231
+ crash: "after a crash",
232
+ lease: "after the lease ended",
233
+ probe: "after it failed its readiness probe",
234
+ stopped: "after it stopped",
235
+ };
236
+ /** What a visitor of an address that does not serve gets (review 3, tm17; decision 9): its state's own page. */
237
+ function stateWords(state) {
238
+ if (state === "blocked")
239
+ return BLOCKED_WORDS;
240
+ if (state === "claimed")
241
+ return "it is not live yet: visitors get 503 until a deploy switches it to a generation";
242
+ return "it is stopped: visitors get 503, the app is not running";
243
+ }
244
+ /**
245
+ * Each service with no running (or paused) generation in the last 7 days, and what starts it again, in one line
246
+ * (DEFECTS 41): how its newest generation ended and when, then the command. A service taken down on purpose is
247
+ * started by b3os apply (keepalive leaves it down); one that hit its spend cap stops again until the cap is raised.
248
+ * With an address the address stays; without one a new generation has a new preview URL.
249
+ */
250
+ function notRunning(sandboxes, rows) {
251
+ const out = [];
252
+ const seen = new Set();
253
+ const newest = [...sandboxes].sort((x, y) => y.created_at.localeCompare(x.created_at));
254
+ for (const x of newest) {
255
+ const item = x.metadata?.[TAG.item] ?? "";
256
+ if (!item.startsWith("service/"))
257
+ continue;
258
+ const service = item.slice(8);
259
+ if (seen.has(service))
260
+ continue;
261
+ seen.add(service);
262
+ if (newest.some((y) => y.metadata?.[TAG.item] === item && (y.status === "running" || y.status === "paused")))
263
+ continue;
264
+ const at = x.stopped_at ? ` at ${clockOf(x.stopped_at)}` : "";
265
+ const address = rows.find((h) => h.service === service && h.state !== "blocked");
266
+ const fresh = address ? `; its address ${address.url.replace(/\/+$/, "")} stays` : ", with a new URL";
267
+ const line = x.stop_reason === "deleted"
268
+ ? `nothing runs: ${x.id} was deleted${at} (b3os app down, or by hand); b3os apply starts it again (keepalive leaves it down)`
269
+ : x.stop_reason === "budget"
270
+ ? `nothing runs: ${x.id} stopped at its spend cap or for credits${at}; raise grant.spend_cap_usd (or add credits), then b3os apply`
271
+ : `nothing runs: ${x.stop_reason === "timeout"
272
+ ? `the lease ended${at}`
273
+ : x.status === "failed" || x.stop_reason === "failed"
274
+ ? `its microVM crashed${at}`
275
+ : `${x.id} is ${x.status}${x.stop_reason ? ` (${x.stop_reason})` : ""}${at}`}; b3os apply --keepalive starts a new generation${fresh}`;
276
+ out.push({ service, sandbox: x.id, stopped_at: x.stopped_at ?? null, line });
277
+ }
278
+ return out;
279
+ }
163
280
  /** "12 s ago", "4 min ago", "2 h 5 min ago", "3 d ago": how long before now `iso` was. */
164
281
  function ago(iso, now = Date.now()) {
165
282
  const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));
@@ -220,20 +337,26 @@ function stamped(write) {
220
337
  write(out);
221
338
  };
222
339
  }
340
+ /** The options of every `b3os app` subcommand, beside the global ones (also the name check's, test/names.test.ts). */
341
+ const APP_OPTIONS = {
342
+ app: { type: "string" },
343
+ file: { type: "string", short: "f" },
344
+ service: { type: "string" },
345
+ follow: { type: "boolean" },
346
+ failed: { type: "boolean" },
347
+ limit: { type: "string" },
348
+ to: { type: "string" },
349
+ "dry-run": { type: "boolean" },
350
+ "no-record": { type: "boolean" },
351
+ "allow-secret-files": { type: "boolean" },
352
+ ttl: { type: "string" },
353
+ rotate: { type: "boolean" },
354
+ port: { type: "string" },
355
+ "delete-volumes": { type: "string" },
356
+ };
223
357
  async function app(ctx, argv) {
224
358
  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
- });
359
+ const a = parse(rest, APP_OPTIONS);
237
360
  ctx.applyGlobals(a.values);
238
361
  if (!sub || a.values.help) {
239
362
  ctx.out(USAGE);
@@ -266,15 +389,44 @@ async function app(ctx, argv) {
266
389
  procs.set(x.id, await processesOf(b3, x.id).catch(why));
267
390
  calls.set(x.id, await lastCall(b3, x.id).catch(why));
268
391
  }
392
+ // The addresses (null: this API has none yet; a string: why they could not be read).
393
+ const hosts = await listHosts(b3, name).catch(why);
394
+ // Its volumes (null: this node has none; a string: why they could not be read).
395
+ const vols = await appVolumes(b3, name).catch(why);
396
+ // The application's own address first (the edge's `primary` when it sends it), then the rest as listed.
397
+ const listed = Array.isArray(hosts) ? hosts : [];
398
+ const own = ownAddress(listed);
399
+ const rows = own ? [own, ...listed.filter((h) => h !== own)] : listed;
400
+ // The status of the sandbox a serving address points at: an address whose generation stopped answers 503.
401
+ const statusOf = (id) => id === null ? null : (sandboxes.find((x) => x.id === id)?.status ?? "gone");
269
402
  const doc = {
270
403
  object: "app_status",
271
404
  app: name,
405
+ addresses: rows.map((h) => ({
406
+ label: h.label,
407
+ url: h.url,
408
+ service: h.service,
409
+ port: h.port,
410
+ access: h.access,
411
+ cookies: h.cookies,
412
+ // `down` (B3-7023): routed to a sandbox the node said ended; since when and why beside it.
413
+ state: h.down ? "down" : h.state,
414
+ ...(h.down ? { down_since: h.down.since, down_reason: h.down.reason } : {}),
415
+ /** The application's own address (the edge's `primary`; from an edge before it, `base_label` null). */
416
+ primary: h === own,
417
+ sandbox: h.sandbox_id,
418
+ /** The served sandbox's status (`gone`: not among the application's sandboxes of the last 7 days). */
419
+ sandbox_status: statusOf(h.sandbox_id),
420
+ dropped_cookies: h.dropped_cookies ?? [],
421
+ })),
422
+ ...(typeof hosts === "string" ? { addresses_error: hosts } : {}),
272
423
  services: sandboxes
273
424
  .filter((x) => (x.metadata?.[TAG.item] ?? "").startsWith("service/"))
274
425
  .map((x) => {
275
426
  const service = (x.metadata?.[TAG.item] ?? "").slice(8);
276
427
  const list = procs.get(x.id);
277
- const health = serviceHealth(x.status, Array.isArray(list) ? list : null, commands.get(service));
428
+ // The node's supervisor, when it restarts the command in place (stay-up D7): restarting, crash loop.
429
+ const health = serviceHealth(x.status, Array.isArray(list) ? list : null, commands.get(service), x.supervised);
278
430
  const p = list === undefined ? undefined : typeof list === "string" ? list : health.process;
279
431
  const call = calls.get(x.id);
280
432
  return {
@@ -282,12 +434,21 @@ async function app(ctx, argv) {
282
434
  sandbox: x.id,
283
435
  /** The sandbox's status. */
284
436
  status: x.status,
285
- /** The service's: the sandbox's, or `down` when it runs and the service's process exited. */
437
+ /**
438
+ * The service's: the sandbox's; `down` when it runs and the service's process exited with nothing
439
+ * restarting it; `restarting` or `crash loop` while the node restarts it in place.
440
+ */
286
441
  state: health.state,
287
442
  ...(health.exit ? { exit: health.exit } : {}),
443
+ /** The node's supervision of the service's command (null: none, or a node from before). */
444
+ supervisor: health.supervisor ?? null,
445
+ /** The sandbox's node lease (null: none, or a node from before leases). */
446
+ lease: x.lease ?? null,
288
447
  stop_reason: x.stop_reason,
289
448
  rev: x.metadata?.[TAG.rev] ?? null,
290
449
  deploy: x.metadata?.[TAG.deploy] ?? null,
450
+ /** Why a keepalive made this generation (its `b3os.recreated` tag, DEFECTS 38), or null. */
451
+ recreated: parseRecreated(x.metadata?.[TAG.recreated]),
291
452
  spec: x.metadata?.[TAG.spec] ?? null,
292
453
  created_at: x.created_at,
293
454
  expires_at: x.status === "running" ? x.expires_at : null,
@@ -333,6 +494,26 @@ async function app(ctx, argv) {
333
494
  created_at: x.created_at,
334
495
  expires_at: x.expires_at,
335
496
  })),
497
+ /** Each service with no running generation, and what starts it again (DEFECTS 41). */
498
+ not_running: notRunning(sandboxes, listed),
499
+ /** Its volumes: kept across deploys, rollbacks and b3os app down (null: this node has none). */
500
+ volumes: Array.isArray(vols)
501
+ ? vols.map((v) => {
502
+ const holder = v.attached_to ? sandboxes.find((x) => x.id === v.attached_to?.sandbox_id) : undefined;
503
+ return {
504
+ volume: v.name,
505
+ id: v.id,
506
+ size_gib: v.size_gib,
507
+ used_bytes: v.used_bytes,
508
+ status: v.status,
509
+ sandbox: v.attached_to?.sandbox_id ?? null,
510
+ service: holder ? (holder.metadata?.[TAG.item] ?? "").replace(/^service\//, "") || null : null,
511
+ /** The last stop-first deploy's gap, from the release of the old generation to the switch. */
512
+ gap_ms: Number(v.metadata?.["b3os.gap_ms"]) || null,
513
+ };
514
+ })
515
+ : null,
516
+ ...(typeof vols === "string" ? { volumes_error: vols } : {}),
336
517
  routines: routines.map((r) => ({
337
518
  routine: r.name,
338
519
  id: r.id,
@@ -345,16 +526,61 @@ async function app(ctx, argv) {
345
526
  };
346
527
  ctx.result(doc, () => {
347
528
  ctx.out(`application ${name}`);
529
+ if (doc.addresses.length || typeof hosts === "string") {
530
+ ctx.out("addresses");
531
+ if (typeof hosts === "string")
532
+ ctx.out(` not read: ${hosts}`);
533
+ for (const h of doc.addresses) {
534
+ ctx.out(` ${h.url} ${h.state}${h.sandbox ? ` ${h.sandbox}` : ""} (${h.service} port ${h.port}, access ${h.access}, cookies ${h.cookies.mode})`);
535
+ const down = rows.find((r) => r.label === h.label)?.down;
536
+ if (down)
537
+ ctx.out(` ${downWords(down)}`);
538
+ else if (h.state === "serving" && h.sandbox && h.sandbox_status !== "running")
539
+ ctx.out(` serving ${h.sandbox}, which is ${h.sandbox_status}: the address answers 503; b3os apply or b3os apply --keepalive recreates it`);
540
+ if (h.state === "claimed")
541
+ ctx.out(" claimed: the next b3os apply switches it to the service's generation");
542
+ if (h.state === "stopped")
543
+ 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, public: true, or the default one)`);
544
+ if (h.state === "blocked")
545
+ ctx.out(` ${BLOCKED_WORDS}`);
546
+ // Cookies the app's server never got (cookies: isolated), by name, never a value: the edge counts every
547
+ // name this address did not set, a page script's or one another b3os.io site set for the whole domain.
548
+ for (const d of h.dropped_cookies)
549
+ 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`);
550
+ }
551
+ }
348
552
  ctx.out("services (newest generation first, last 7 days)");
349
- // STATUS is the service's: `down (exited TERM)` when the sandbox runs and its process does not.
350
- 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"]);
553
+ // STATUS is the service's: `down (exited TERM)` when the sandbox runs and its process does not, `restarting` or
554
+ // `crash loop` while the node restarts it in place.
555
+ ctx.table(doc.services.map((x) => ({
556
+ ...x,
557
+ status: x.state === "down" && x.exit
558
+ ? `down (exited ${x.exit.how})`
559
+ : x.state === "restarting" || x.state === "crash loop"
560
+ ? x.state
561
+ : x.status,
562
+ })), ["service", "sandbox", "status", "stop_reason", "rev", "deploy", "expires_at"]);
563
+ for (const n of doc.not_running)
564
+ ctx.out(`${n.service}: ${n.line}`);
351
565
  for (const x of doc.services) {
352
566
  if (x.status !== "running")
353
567
  continue;
354
568
  ctx.out(`${x.service} (${x.sandbox})`);
569
+ if (x.recreated)
570
+ ctx.out(` recreated ${RECREATED_WHY[x.recreated.cause]} ${ago(x.created_at)}: ${x.recreated.reason}${x.recreated.by ? ` (keepalive ${x.recreated.by})` : ""}`);
571
+ for (const h of doc.addresses)
572
+ if ((h.state === "serving" || h.state === "down") && h.sandbox === x.sandbox)
573
+ ctx.out(` address ${h.url}`);
355
574
  for (const u of x.urls)
356
575
  ctx.out(` public URL ${u}`);
357
- if ("process" in x)
576
+ const sup = x.supervisor;
577
+ if (sup && x.state === "crash loop")
578
+ ctx.out(` process ${crashLoopWords(sup)}; see b3os app logs ${name} --service ${x.service}`);
579
+ else if (sup && x.state === "restarting")
580
+ ctx.out(` process restarting in place (restart ${sup.state === "backoff" ? sup.restarts + 1 : sup.restarts})${sup.last_exit ? `; last: ${lastExitWords(sup.last_exit)}` : ""}${sup.next_start_at ? `; next start ${clockOf(sup.next_start_at)}` : ""}`);
581
+ else if (sup && x.state === "running" && sup.pid !== null)
582
+ ctx.out(` process ${sup.pid} running${sup.started_at ? ` since ${clockOf(sup.started_at)}` : ""}${restartWords(sup) ? `; ${restartWords(sup)}` : ""}`);
583
+ else if ("process" in x)
358
584
  ctx.out(` process ${x.exit && x.process
359
585
  ? `${x.exit.pid} exited (${x.exit.how})${x.exit.at ? ` at ${x.exit.at} (${ago(x.exit.at)})` : ""}: ${x.process.cmd}`
360
586
  : x.process
@@ -362,7 +588,7 @@ async function app(ctx, argv) {
362
588
  : x.process_error
363
589
  ? `not read: ${x.process_error}`
364
590
  : "none started"}`);
365
- if (x.exit)
591
+ if (x.state === "down")
366
592
  ctx.out(` down nothing serves${x.urls.length ? " (its URL answers 502)" : ""}; the next b3os apply or b3os apply --keepalive recreates it`);
367
593
  if ("last_call" in x)
368
594
  ctx.out(` last call ${x.last_call
@@ -370,13 +596,27 @@ async function app(ctx, argv) {
370
596
  : x.last_call_error
371
597
  ? `not read: ${x.last_call_error}`
372
598
  : "none in the last 7 days"}`);
373
- if (x.expires_at)
599
+ if (x.lease?.state === "held")
600
+ ctx.out(` lease kept up by B3OS since ${clockOf(x.lease.since)}${x.lease.renewed_at ? ` (renewed ${clockOf(x.lease.renewed_at)})` : ""}; ends on b3os app down, a newer deploy, or the organization's limits`);
601
+ else if (x.expires_at)
374
602
  ctx.out(` lease ends ${x.expires_at} (${fromNow(x.expires_at)}); b3os apply --keepalive renews it, and so does each deploy`);
375
603
  if ("logs_command" in x)
376
604
  ctx.out(` logs ${x.logs_command}`);
377
605
  if ("requests_command" in x)
378
606
  ctx.out(` requests ${x.requests_command}`);
379
607
  }
608
+ if (doc.volumes?.length || typeof vols === "string") {
609
+ ctx.out("volumes (kept across deploys, rollbacks and b3os app down)");
610
+ if (typeof vols === "string")
611
+ ctx.out(` not read: ${vols}`);
612
+ ctx.table((doc.volumes ?? []).map((v) => ({
613
+ ...v,
614
+ size: `${v.size_gib} GiB`,
615
+ used: v.used_bytes === null ? "-" : mibOrGib(v.used_bytes),
616
+ holder: v.sandbox ? `${v.sandbox}${v.service ? ` (${v.service})` : ""}` : "-",
617
+ last_gap: v.gap_ms === null ? "-" : `${(v.gap_ms / 1000).toFixed(1)} s`,
618
+ })), ["volume", "id", "size", "used", "status", "holder", "last_gap"]);
619
+ }
380
620
  ctx.out("builds");
381
621
  ctx.table(doc.builds, ["service", "snapshot", "key", "status", "created_at"]);
382
622
  ctx.out("routines");
@@ -388,8 +628,12 @@ async function app(ctx, argv) {
388
628
  const name = a.positionals[0] ?? appName(a.values, false);
389
629
  const running = runningByService(await listTagged(b3, { [TAG.app]: name }));
390
630
  if (!running.size) {
391
- ctx.warn(`${name} has no running generation: b3os app status lists its generations`);
392
- return EXIT.NOT_FOUND;
631
+ // What starts it again, in one line (DEFECTS 41).
632
+ const all = await listTagged(b3, { [TAG.app]: name });
633
+ const rows = await listHosts(b3, name).catch(() => null);
634
+ const wanted = typeof a.values.service === "string" ? a.values.service : undefined;
635
+ const lines = notRunning(all, rows ?? []).filter((n) => !wanted || n.service === wanted);
636
+ throw new CliError(`${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"}`, { code: "no_running_generation", exit: EXIT.NOT_FOUND });
393
637
  }
394
638
  const names = [...running.keys()];
395
639
  const svc = typeof a.values.service === "string" ? a.values.service : names.length === 1 ? names[0] : undefined;
@@ -398,23 +642,45 @@ async function app(ctx, argv) {
398
642
  const gen = running.get(svc);
399
643
  if (!gen)
400
644
  throw new UsageError(`${name} has no running generation of ${svc} (running: ${names.join(", ")})`);
401
- const p = serviceProcess(await processesOf(b3, gen.id), commandsOf(a.values, name).get(svc));
645
+ const cmd = commandsOf(a.values, name).get(svc);
646
+ const p = serviceProcess(await processesOf(b3, gen.id), cmd, supervisedEntry(gen.supervised, cmd));
402
647
  if (!p) {
403
- ctx.warn(`${svc} (${gen.id}) has no process: apply starts the service's command as a background process`);
404
- return EXIT.NOT_FOUND;
648
+ throw new CliError(`${svc} (${gen.id}) has no process: apply starts the service's command as a background process`, { code: "service_process_not_found", exit: EXIT.NOT_FOUND });
405
649
  }
406
650
  ctx.info(`${svc}: ${gen.id}, process ${p.pid} (${p.status}): ${p.cmd}`);
407
651
  const out = stamped((t) => ctx.io.stdout.write(t));
408
652
  const err = stamped((t) => ctx.io.stderr.write(t));
409
- for await (const ev of b3.sandboxes.streamLogs(gen.id, { pid: p.pid, follow: a.values.follow === true })) {
410
- if (ctx.json)
411
- ctx.printJsonLine(ev);
412
- else if (ev.type === "log.stdout")
413
- out(ev);
414
- else if (ev.type === "log.stderr")
415
- err(ev);
416
- else if (ev.type === "process.exited")
417
- ctx.info(`[process ${ev.pid} exited ${ev.exit_code ?? "by a signal"}]`);
653
+ const follow = a.values.follow === true;
654
+ let pid = p.pid;
655
+ for (;;) {
656
+ let exited = null;
657
+ for await (const ev of b3.sandboxes.streamLogs(gen.id, { pid, follow })) {
658
+ if (ctx.json)
659
+ ctx.printJsonLine(ev);
660
+ else if (ev.type === "log.stdout")
661
+ out(ev);
662
+ else if (ev.type === "log.stderr")
663
+ err(ev);
664
+ if (ev.type === "process.exited") {
665
+ exited = { pid: ev.pid ?? pid, exit_code: ev.exit_code ?? null };
666
+ // Followed: the stream is left for the next process the node starts (stay-up C1).
667
+ if (follow)
668
+ break;
669
+ if (!ctx.json)
670
+ ctx.info(`[process ${ev.pid} exited ${ev.exit_code ?? "by a signal"}]`);
671
+ }
672
+ }
673
+ if (!follow || !exited)
674
+ break;
675
+ const next = await restartedFrom(b3, gen.id, cmd, exited.pid);
676
+ if (!next) {
677
+ if (!ctx.json)
678
+ ctx.info(`[process ${exited.pid} exited ${exited.exit_code ?? "by a signal"}]`);
679
+ break;
680
+ }
681
+ if (!ctx.json)
682
+ ctx.info(`[process ${exited.pid} exited (${next.how}); B3OS started ${next.pid}]`);
683
+ pid = next.pid;
418
684
  }
419
685
  return EXIT.OK;
420
686
  }
@@ -425,8 +691,10 @@ async function app(ctx, argv) {
425
691
  throw new UsageError("--limit is 1 to 100");
426
692
  const gens = generationByService(await listTagged(b3, { [TAG.app]: name }));
427
693
  if (!gens.size) {
428
- ctx.warn(`${name} has no service generation in the last 7 days: b3os app status lists what it has`);
429
- return EXIT.NOT_FOUND;
694
+ throw new CliError(`${name} has no service generation in the last 7 days: b3os app status lists what it has`, {
695
+ code: "app_not_found",
696
+ exit: EXIT.NOT_FOUND,
697
+ });
430
698
  }
431
699
  const wanted = typeof a.values.service === "string" ? a.values.service : undefined;
432
700
  if (wanted && !gens.has(wanted))
@@ -450,27 +718,96 @@ async function app(ctx, argv) {
450
718
  }
451
719
  case "down": {
452
720
  const name = appName(a.values, true);
721
+ // Volumes outlive a take down (rulings 4); deleting them asks for the application's name a second time.
722
+ const delVols = a.values["delete-volumes"];
723
+ if (delVols !== undefined && delVols !== name)
724
+ throw new UsageError(`--delete-volumes takes the application's name typed again (${name}), so a volume is never deleted by a slip; got "${String(delVols)}"`);
725
+ const listed = await appVolumes(b3, name);
726
+ if (delVols !== undefined && !listed)
727
+ throw new UsageError("--delete-volumes: this node has no volumes (a node before release 1118)");
728
+ const vols = listed ?? [];
453
729
  const live = (await listTagged(b3, { [TAG.app]: name })).filter((x) => x.status === "running" || x.status === "paused");
454
730
  const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
455
731
  const snapshots = (await all(b3.sandboxes.listSnapshots({ limit: 100 }), 200)).filter((x) => x.metadata?.[TAG.app] === name);
732
+ // The addresses serving now (none on an API without them). The edge refuses to delete a sandbox one points at.
733
+ const hosts = await listHosts(b3, name);
734
+ const serving = (hosts ?? []).filter((h) => h.state === "serving" && h.sandbox_id);
456
735
  const n = live.length + routines.length + snapshots.length;
457
- if (!n) {
736
+ if (!n && !serving.length && !(delVols !== undefined && vols.length)) {
458
737
  ctx.info(`nothing tagged b3os.app ${name} in this project`);
738
+ for (const v of vols)
739
+ ctx.info(`volume ${v.id} ${v.name}: kept, with its data`);
459
740
  return EXIT.OK;
460
741
  }
742
+ for (const h of serving)
743
+ ctx.info(`address ${h.url} serves ${h.sandbox_id}: it stops, and the label stays ${name}'s`);
461
744
  for (const x of live)
462
745
  ctx.info(`sandbox ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
463
746
  for (const r of routines)
464
747
  ctx.info(`routine ${r.id} ${r.name}`);
465
748
  for (const x of snapshots)
466
749
  ctx.info(`snapshot ${x.id} ${x.metadata?.[TAG.item] ?? ""}`);
467
- if (!(await ctx.confirm(`Delete these ${n} objects of ${name}?`))) {
750
+ for (const v of vols)
751
+ ctx.info(delVols !== undefined
752
+ ? `volume ${v.id} ${v.name}: deleted too (--delete-volumes), restorable for 7 days`
753
+ : `volume ${v.id} ${v.name}: kept, with its data (--delete-volumes ${name} deletes it)`);
754
+ const also = delVols !== undefined && vols.length
755
+ ? ` and ${vols.length === 1 ? "its volume" : `its ${vols.length} volumes`}`
756
+ : "";
757
+ const what = serving.length
758
+ ? `Stop ${serving.length === 1 ? "this address" : `these ${serving.length} addresses`} and delete these ${n} objects of ${name}${also}?`
759
+ : `Delete these ${n} objects of ${name}${also}?`;
760
+ if (!(await ctx.confirm(what))) {
468
761
  ctx.warn("Nothing was deleted.");
469
762
  return EXIT.OK;
470
763
  }
471
764
  const done = [];
765
+ if (serving.length) {
766
+ // Every label to nothing at once (compare-and-swap on what was read), then the apps Worker's cache time and
767
+ // a margin before any TERM, so no request already on its way meets a stopping server.
768
+ await routeHosts(b3, name, {
769
+ targets: serving.map((h) => ({ label: h.label, sandbox_id: null, port: h.port })),
770
+ if_current: Object.fromEntries(serving.map((h) => [h.label, h.sandbox_id])),
771
+ });
772
+ for (const h of serving) {
773
+ done.push({ kind: "address", id: h.label, how: "stopped" });
774
+ ctx.info(`stopped ${h.url} (it served ${h.sandbox_id})`);
775
+ }
776
+ if (serving.some((h) => live.some((x) => x.id === h.sandbox_id))) {
777
+ ctx.info(`waiting ${ROUTE_SETTLE_MS / 1000} s before TERM`);
778
+ await sleep(ROUTE_SETTLE_MS);
779
+ }
780
+ }
781
+ // Each TERM after a second read of the addresses (FOLLOWUPS 19, as retire, extras and prune do): an apply that
782
+ // ran meanwhile may have switched a label back to one of these, and a sandbox an address serves is kept.
783
+ const kept = [];
472
784
  for (const x of live) {
473
- const how = await retire(b3, x, 30, 1000);
785
+ if (hosts !== null) {
786
+ const now = await listHosts(b3, name).then((r) => r ?? [], (e) => (e instanceof Error ? e : new Error(String(e))));
787
+ const label = now instanceof Error ? undefined : now.find((h) => h.state === "serving" && h.sandbox_id === x.id)?.label;
788
+ if (now instanceof Error || label) {
789
+ const why = label ? `kept ${x.id}, which serves ${label}` : `kept ${x.id}: the addresses could not be read`;
790
+ kept.push({ id: x.id, why, ...(label ? { label } : {}) });
791
+ ctx.warn(why);
792
+ continue;
793
+ }
794
+ }
795
+ // Without the address routes (they answered off) a generation made for an address may still serve one
796
+ // (review 3, T5): it is deleted first, so the edge's delete guard answers before anything stops it. A refused
797
+ // delete keeps the sandbox, in the edge's words, and app down goes on with the rest.
798
+ const first = hosts === null && (x.ports ?? []).some((p) => p.addressed === true) ? "delete" : "term";
799
+ let how;
800
+ try {
801
+ how = await retire(b3, x, 30, 1000, undefined, first);
802
+ }
803
+ catch (e) {
804
+ if (!(e instanceof StepError) || e.code !== "sandbox_routed")
805
+ throw e;
806
+ const why = `kept ${x.id}: the edge refused its delete: ${e.message.replace(/^\S+ was not deleted: /, "")}`;
807
+ kept.push({ id: x.id, why });
808
+ ctx.warn(why);
809
+ continue;
810
+ }
474
811
  done.push({ kind: "sandbox", id: x.id, how });
475
812
  ctx.info(`deleted ${x.id} (${how})`);
476
813
  }
@@ -484,9 +821,128 @@ async function app(ctx, argv) {
484
821
  done.push({ kind: "snapshot", id: x.id, how: "deleted" });
485
822
  ctx.info(`deleted snapshot ${x.id}`);
486
823
  }
487
- ctx.result({ object: "app_down", app: name, deleted: done }, () => ctx.out(`${name}: deleted ${done.length} objects`));
824
+ // Volumes: kept, unless --delete-volumes named the application again; then each is deleted (restorable for 7
825
+ // days) once no sandbox holds it, which is a moment after its generation was deleted (its microVM exits first).
826
+ const keptVolumes = [];
827
+ for (const v of vols) {
828
+ if (delVols === undefined) {
829
+ keptVolumes.push({ id: v.id, name: v.name, size_gib: v.size_gib });
830
+ continue;
831
+ }
832
+ if (!(await volumeFree(b3, v.id, VOLUME_FREE_MS))) {
833
+ const why = `kept volume ${v.id} (${v.name}): a sandbox still holds it ${VOLUME_FREE_MS / 1000} s on`;
834
+ keptVolumes.push({ id: v.id, name: v.name, size_gib: v.size_gib, why });
835
+ ctx.warn(why);
836
+ continue;
837
+ }
838
+ const d = await b3.sandboxes.deleteVolume(v.id);
839
+ done.push({ kind: "volume", id: v.id, how: `deleted, restorable until ${d.purge_at ?? "its purge"}` });
840
+ ctx.info(`deleted volume ${v.id} (${v.name}): restorable until ${d.purge_at ?? "its purge"} with b3os sandbox volumes restore ${v.name}`);
841
+ }
842
+ const stopped = done.filter((d) => d.kind === "address").length;
843
+ ctx.result({
844
+ object: "app_down",
845
+ app: name,
846
+ deleted: done.filter((d) => d.kind !== "address"),
847
+ stopped: done.filter((d) => d.kind === "address"),
848
+ kept,
849
+ volumes_kept: keptVolumes,
850
+ }, () => ctx.out(`${name}: ${stopped ? `stopped ${stopped} ${stopped === 1 ? "address" : "addresses"}, ` : ""}deleted ${done.length - stopped} objects${kept.length ? `; ${kept.map((k) => k.why).join("; ")}` : ""}${keptVolumes.length ? `; kept ${keptVolumes.length === 1 ? "volume" : "volumes"} ${keptVolumes.map((v) => v.name).join(", ")} with ${keptVolumes.length === 1 ? "its" : "their"} data` : ""}`));
851
+ return EXIT.OK;
852
+ }
853
+ case "open": {
854
+ const name = a.positionals[0] ?? appName(a.values, false);
855
+ const hosts = await listHosts(b3, name);
856
+ if (hosts === null) {
857
+ throw new CliError(`this API has no app addresses yet: b3os app status prints each running generation's URL`, {
858
+ code: "app_addresses_unavailable",
859
+ exit: EXIT.NOT_FOUND,
860
+ });
861
+ }
862
+ const svc = typeof a.values.service === "string" ? a.values.service : undefined;
863
+ const mine = hosts.filter((h) => !svc || h.service === svc);
864
+ const row = ownAddress(mine) ?? mine[0];
865
+ if (!row) {
866
+ throw new CliError(`${name} has no address${svc ? ` for service ${svc}` : ""}: b3os apply claims one for a port with access (or public: true)`, { code: "app_host_not_found", exit: EXIT.NOT_FOUND });
867
+ }
868
+ // What a visitor gets there now, by the state's own page (review 3, tm17; decision 9).
869
+ if (row.state !== "serving")
870
+ ctx.warn(`${row.url}: ${stateWords(row.state)}`);
871
+ if (ctx.json || !ctx.isTTY) {
872
+ ctx.result({ object: "app_address", app: name, url: row.url, state: row.state, access: row.access }, () => ctx.out(row.url));
873
+ if (row.access === "link")
874
+ ctx.info("a link address lets in only people with a link: b3os app link prints one");
875
+ return EXIT.OK;
876
+ }
877
+ // A link address lets the owner in with a link of 60 s (its cookie then lasts 30 days); the link is never
878
+ // printed, and it is on the opener's argument list for that minute only. The URL is the address itself, checked
879
+ // here: never a string the server chose as it is, and never through a shell.
880
+ const clean = `https://${row.label}.${APP_DOMAIN}`;
881
+ const url = row.access === "link" ? (await createLink(b3, name, { label: row.label, ttl_s: 60 })).url : `${clean}/`;
882
+ if (!openable(url, row.label))
883
+ throw new CliError(`the edge answered a URL that is not ${clean}/ with a link: not opened`, {
884
+ code: "unexpected_url",
885
+ exit: EXIT.SERVER,
886
+ hint: "b3os app link prints a link to the address",
887
+ });
888
+ if (process.platform === "win32")
889
+ ctx.info(WINDOWS_OPENER_NOTE);
890
+ if (!(await openBrowser(url))) {
891
+ ctx.out(clean);
892
+ ctx.info("no browser started here: b3os app link prints a link");
893
+ return EXIT.OK;
894
+ }
895
+ ctx.info(`opened ${clean}${row.access === "link" ? " with a link that ends in 60 s" : ""}`);
896
+ return EXIT.OK;
897
+ }
898
+ case "link": {
899
+ const name = a.positionals[0] ?? appName(a.values, false);
900
+ const ttl = intFlag(a.values.ttl, "--ttl") ?? 604_800;
901
+ if (ttl < 60 || ttl > 7_776_000)
902
+ throw new UsageError("--ttl is 60 to 7776000 seconds (90 days)");
903
+ const rotate = a.values.rotate === true;
904
+ // Review 2, sm19: the edge ends no stream it already let in; an open one runs until its hour is up.
905
+ 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.`;
906
+ if (rotate) {
907
+ ctx.warn(rotation);
908
+ if (!(await ctx.confirm(`Rotate the link secret of ${name}?`))) {
909
+ ctx.warn("Nothing was changed.");
910
+ return EXIT.OK;
911
+ }
912
+ }
913
+ const label = await linkLabel(b3, name, a.values);
914
+ if (label === null) {
915
+ throw new CliError("this API has no app addresses yet, so there is no link to make", {
916
+ code: "app_addresses_unavailable",
917
+ exit: EXIT.NOT_FOUND,
918
+ });
919
+ }
920
+ let link;
921
+ try {
922
+ link = await createLink(b3, name, {
923
+ ...(label ? { label } : {}),
924
+ ttl_s: ttl,
925
+ ...(rotate ? { rotate: true } : {}),
926
+ });
927
+ }
928
+ catch (e) {
929
+ if (!noHostsRoutes(e))
930
+ throw e;
931
+ throw new CliError("this API has no app addresses yet, so there is no link to make", {
932
+ code: "app_addresses_unavailable",
933
+ exit: EXIT.NOT_FOUND,
934
+ });
935
+ }
936
+ ctx.result(rotate ? { ...link, warning: rotation } : link, () => {
937
+ ctx.out(link.url);
938
+ 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`);
939
+ });
488
940
  return EXIT.OK;
489
941
  }
942
+ case "domains": {
943
+ const name = appName(a.values, false);
944
+ return domains(ctx, b3, name, a.positionals, () => linkLabel(b3, name, a.values));
945
+ }
490
946
  case "rollback": {
491
947
  const name = a.positionals[0] ?? appName(a.values, false);
492
948
  const to = typeof a.values.to === "string" ? a.values.to : undefined;
@@ -500,8 +956,10 @@ async function app(ctx, argv) {
500
956
  const manifestInRepo = git.inRepo(root, file);
501
957
  const history = pastDeploys(await listTagged(b3, { [TAG.app]: name }));
502
958
  if (!history.length) {
503
- ctx.warn(`${name} has no service generation in the last 7 days: nothing to roll back to`);
504
- return EXIT.NOT_FOUND;
959
+ throw new CliError(`${name} has no service generation in the last 7 days: nothing to roll back to`, {
960
+ code: "nothing_to_roll_back",
961
+ exit: EXIT.NOT_FOUND,
962
+ });
505
963
  }
506
964
  const routines = (await all(b3.routines.listRoutines({ limit: 100 }))).filter((r) => r.metadata?.[TAG.app] === name);
507
965
  const current = currentDeploy(history, routines);
@@ -520,14 +978,19 @@ async function app(ctx, argv) {
520
978
  }
521
979
  const served = history.filter((h) => h.served && h.commit);
522
980
  const listed = served.map((h) => `${h.deploy} (${h.commit?.slice(0, 7)})`).join(", ");
523
- const target = to
981
+ const picked = to
524
982
  ? served.find((h) => h.deploy === to)
525
983
  : served.find((h) => current && deployAfter(current.deploy, h.deploy) && h.commit !== current.commit);
984
+ // The deploy that shipped that commit (DEFECTS 39): the oldest of the deploys before it that ran the same commit
985
+ // one after another, not a keepalive's recreate of it. --to is the exact deploy named.
986
+ let target = picked;
987
+ if (!to && picked)
988
+ for (let i = served.indexOf(picked) + 1; served[i]?.commit === picked.commit; i++)
989
+ target = served[i];
526
990
  if (!target) {
527
991
  if (to)
528
992
  throw new UsageError(`${to} is not a deploy of ${name} that went live in the last 7 days: ${listed}`);
529
- ctx.warn(`nothing to roll back to: no deploy of ${name} before ${current?.deploy} in the last 7 days went live with another commit${listed ? ` (${listed})` : ""}`);
530
- return EXIT.NOT_FOUND;
993
+ throw new CliError(`nothing to roll back to: no deploy of ${name} before ${current?.deploy} in the last 7 days went live with another commit${listed ? ` (${listed})` : ""}`, { code: "nothing_to_roll_back", exit: EXIT.NOT_FOUND });
531
994
  }
532
995
  const commit = git.resolveCommit(root, target.commit);
533
996
  if (!commit)
@@ -536,6 +999,21 @@ async function app(ctx, argv) {
536
999
  exit: EXIT.NOT_FOUND,
537
1000
  hint: `fetch it (git fetch origin, or git fetch --unshallow in a shallow clone), then run b3os app rollback again; nothing was changed`,
538
1001
  });
1002
+ // HEAD reverts the target when its tree (the application's folder) is the target's parent's (DEFECTS 39): the
1003
+ // rollback then deploys again what HEAD took out, and the plan's first line says so.
1004
+ const head = git.resolveCommit(root, "HEAD");
1005
+ const parent = git.resolveCommit(root, `${commit}^`);
1006
+ const dirRel = git.inRepo(root, dirname(file));
1007
+ const reverts = (() => {
1008
+ if (!head || !parent || head === commit)
1009
+ return false;
1010
+ try {
1011
+ return git.treeHash(root, head, dirRel) === git.treeHash(root, parent, dirRel);
1012
+ }
1013
+ catch {
1014
+ return false;
1015
+ }
1016
+ })();
539
1017
  const ac = new AbortController();
540
1018
  const options = {
541
1019
  mode: a.values["dry-run"] === true ? "dry-run" : "apply",
@@ -550,6 +1028,7 @@ async function app(ctx, argv) {
550
1028
  liveAt: target.liveAt,
551
1029
  startedAt: target.liveAt ? null : target.startedAt,
552
1030
  from: current?.commit?.slice(0, 7) ?? null,
1031
+ ...(reverts && head ? { revertedBy: head.slice(0, 7) } : {}),
553
1032
  }, ctx.credential().baseUrl, options);
554
1033
  if ("problem" in planned) {
555
1034
  ctx.warn(`${planned.problem}; nothing was changed`);
@@ -566,12 +1045,38 @@ async function app(ctx, argv) {
566
1045
  throw new UsageError(`unknown app command "${sub}"\n${USAGE}`);
567
1046
  }
568
1047
  }
1048
+ /**
1049
+ * The label `b3os app link` asks for: undefined for the application's own (the edge picks it), the address of
1050
+ * `--service` (and `--port`), or null when the API has no addresses.
1051
+ */
1052
+ async function linkLabel(b3, app, v) {
1053
+ const service = typeof v.service === "string" ? v.service : undefined;
1054
+ const port = intFlag(v.port, "--port");
1055
+ const rows = await listHosts(b3, app);
1056
+ if (rows === null)
1057
+ return null;
1058
+ // No flag: the application's own address, the edge's `primary` row when it says which (else the edge picks).
1059
+ if (service === undefined && port === undefined)
1060
+ return rows.some((h) => h.primary !== undefined) ? ownAddress(rows)?.label : undefined;
1061
+ const mine = rows.filter((h) => (service === undefined || h.service === service) && (port === undefined || h.port === port));
1062
+ const what = `${service ? `service ${service}` : app}${port !== undefined ? ` port ${port}` : ""}`;
1063
+ if (!mine.length)
1064
+ throw new UsageError(`${app} has no address for ${what}: ${rows.map((h) => `${h.service} port ${h.port}`).join(", ") || "none yet"}`);
1065
+ if (mine.length === 1)
1066
+ return mine[0].label;
1067
+ // The service holds the application's own label: that one, as b3os app link without --service gives.
1068
+ const own = ownAddress(mine);
1069
+ if (own)
1070
+ return own.label;
1071
+ throw new UsageError(`${what} has ${mine.length} addresses (ports ${mine.map((h) => h.port).join(", ")}): pass --port`);
1072
+ }
569
1073
  export const commands = [
570
1074
  {
571
1075
  name: "app",
572
- summary: "Status, logs, calls and rollback of a b3os.yaml app (status | logs | requests | rollback | down)",
1076
+ summary: "An app's status, address and rollback (status, open, link, domains, logs, requests, rollback, down)",
573
1077
  order: 245,
574
1078
  run: app,
1079
+ options: APP_OPTIONS,
575
1080
  },
576
1081
  ];
577
1082
  //# sourceMappingURL=app.js.map