@rocket.chat/houston 0.27.0-next.3 → 2.1.9

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 (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,1398 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PREFLIGHT_REUSE_MS = exports.STAGES = exports.STATUS_WORKERS = exports.BILLABLE = exports.INSTANCE_USD_HR = exports.LOADBALANCER_USD_HR = exports.HOURS_PER_MONTH = exports.EBS_GP3_USD_GB_MONTH = exports.NODE_VOLUME_GB = exports.NAT_GATEWAY_USD_HR = exports.EKS_EXTENDED_CONTROL_PLANE_USD_HR = exports.EKS_CONTROL_PLANE_USD_HR = void 0;
37
+ exports.eksControlPlaneRate = eksControlPlaneRate;
38
+ exports.oldestNodeAgeHours = oldestNodeAgeHours;
39
+ exports.claimedGb = claimedGb;
40
+ exports.nodeInventory = nodeInventory;
41
+ exports.providerOf = providerOf;
42
+ exports.regionOf = regionOf;
43
+ exports.estimateUsdHr = estimateUsdHr;
44
+ exports.round4 = round4;
45
+ exports.whereOf = whereOf;
46
+ exports.knownContexts = knownContexts;
47
+ exports.nextStep = nextStep;
48
+ exports.resolveName = resolveName;
49
+ exports.resolveAddresses = resolveAddresses;
50
+ exports.status = status;
51
+ exports.overview = overview;
52
+ /**
53
+ * The cluster ledger: what a cluster is holding, and what that is costing.
54
+ *
55
+ * Read-only and free. Nothing here mutates a cluster, spends money or needs a cloud
56
+ * credential, which is why it can be the first thing built and why it is useful on a kind
57
+ * cluster and an adopted k3s as well as on a managed one.
58
+ *
59
+ * **The failure this module is written against.** A ledger whose job is "make a forgotten
60
+ * cluster impossible to forget" is worse than useless if it reports an unreadable cluster
61
+ * as an empty one: "0 workspaces, nothing costing you money" is exactly the sentence that
62
+ * lets a bill run. So every fact here is `null` when it could not be read, never `0`, and
63
+ * `unreadable` names which ones -- the same three-answer discipline `kube/ask`'s `Answer`
64
+ * exists for, applied to a screen instead of a delete.
65
+ *
66
+ * `kube/` is the Kubernetes seam and stays it: everything below asks through it.
67
+ */
68
+ const config = __importStar(require("../lib/config"));
69
+ const promises_1 = require("node:dns/promises");
70
+ const events_1 = require("../lib/events");
71
+ const format_1 = require("../lib/format");
72
+ const map_limit_1 = require("../lib/map-limit");
73
+ const eks = __importStar(require("./eks"));
74
+ const journal = __importStar(require("./journal"));
75
+ const ask_1 = require("./kube/ask");
76
+ const cluster_1 = require("./kube/cluster");
77
+ const context_1 = require("./kube/context");
78
+ const endpoints_1 = require("./kube/endpoints");
79
+ const capabilities_1 = require("./kube/capabilities");
80
+ const monitoring_1 = require("./kube/monitoring");
81
+ const names_1 = require("./kube/names");
82
+ const namespace_1 = require("./kube/namespace");
83
+ const operator_1 = require("./kube/operator");
84
+ const reachability_1 = require("./kube/reachability");
85
+ const tools_1 = require("./kube/tools");
86
+ /**
87
+ * Estimated USD/hour, us-east-1 on-demand.
88
+ *
89
+ * ONE table, because the ledger and the spend gate that will gate `cluster create` must
90
+ * quote the same number -- `lifecycle.runtimeCost` already states the rule for RAM: "the
91
+ * same constants, not a second set written for the screen: a card that quotes 1.1 GB while
92
+ * the preflight reserves something else is a card that will be contradicted by the refusal
93
+ * it was meant to prevent". An hourly rate quoted at create and a different one in the
94
+ * ledger is that bug in dollars.
95
+ *
96
+ * Deliberately small. An instance type that is not here is COUNTED and reported as unpriced
97
+ * rather than guessed at or silently omitted -- a total that quietly drops the nodes it did
98
+ * not recognise is the same lie as a zero for an unreadable cluster.
99
+ */
100
+ exports.EKS_CONTROL_PLANE_USD_HR = 0.1;
101
+ exports.EKS_EXTENDED_CONTROL_PLANE_USD_HR = 0.6;
102
+ exports.NAT_GATEWAY_USD_HR = 0.045;
103
+ /** Published EKS standard-support end dates, UTC; older offered versions are extended. */
104
+ const EKS_STANDARD_END = Object.freeze({
105
+ '1.31': '2025-11-26',
106
+ '1.32': '2026-03-23',
107
+ '1.33': '2026-07-29',
108
+ '1.34': '2026-12-02',
109
+ '1.35': '2027-03-27',
110
+ '1.36': '2027-08-02',
111
+ '1.37': '2027-12-01',
112
+ });
113
+ function eksControlPlaneRate(version, now = Date.now()) {
114
+ const end = EKS_STANDARD_END[version];
115
+ if (end !== undefined)
116
+ return now >= Date.parse(`${end}T00:00:00Z`)
117
+ ? exports.EKS_EXTENDED_CONTROL_PLANE_USD_HR
118
+ : exports.EKS_CONTROL_PLANE_USD_HR;
119
+ return exports.EKS_CONTROL_PLANE_USD_HR;
120
+ }
121
+ /**
122
+ * A node's DISK, which `INSTANCE_USD_HR` cannot express because a disk is not an instance
123
+ * type -- so it was not underpriced, it was UNCOUNTED, and the "unpriced types are
124
+ * reported" safeguard could not see it either.
125
+ *
126
+ * MEASURED live: an eksctl node group with no `volumeSize` resolves to 80 GB gp3, and
127
+ * `describe-volumes` on a running cluster showed exactly that beside the workspace's own 8
128
+ * GB. Still an assumption in the sense that a node group asking for something else is not
129
+ * read back, and the basis string says which.
130
+ */
131
+ exports.NODE_VOLUME_GB = 80;
132
+ exports.EBS_GP3_USD_GB_MONTH = 0.08;
133
+ exports.HOURS_PER_MONTH = 730.0;
134
+ /**
135
+ * A LoadBalancer Service provisions a real load balancer and bills by the hour.
136
+ *
137
+ * The ledger has always COUNTED them -- "1 LoadBalancer(s) — each one is billed on a
138
+ * managed cluster" is printed one line above the total -- and never priced them, which is
139
+ * the same failure as the node disks one layer along: a figure arrived at honestly,
140
+ * believable, and low. us-east-1 classic/NLB hourly; an ALB differs and capacity units are
141
+ * not modelled.
142
+ */
143
+ exports.LOADBALANCER_USD_HR = 0.0225;
144
+ exports.INSTANCE_USD_HR = Object.freeze({
145
+ 't3.medium': 0.0416,
146
+ 't3.large': 0.0832, // what Launchpad names as the minimum
147
+ 't3.xlarge': 0.1664,
148
+ 'm5.large': 0.096,
149
+ 'm5.xlarge': 0.192,
150
+ });
151
+ /**
152
+ * Distributions that cost money to keep running.
153
+ *
154
+ * A kind cluster on a laptop and a k3s in a VM you already pay for are both free as far as
155
+ * houston is concerned; quoting dollars for them would be noise, and quoting zero would be
156
+ * a claim about somebody else's infrastructure bill.
157
+ */
158
+ exports.BILLABLE = Object.freeze(['eks', 'gke', 'aks']);
159
+ function metadataOf(item) {
160
+ const meta = item.metadata;
161
+ return typeof meta === 'object' && meta !== null ? meta : {};
162
+ }
163
+ /**
164
+ * Hours since the oldest node appeared, as a proxy for the cluster's age.
165
+ *
166
+ * A proxy because nothing asks the control plane when it was created: EKS knows, kind does
167
+ * not, and the answer has to mean the same thing on both. The oldest node is close enough
168
+ * for "this has been up for eleven days" and is readable everywhere.
169
+ */
170
+ function oldestNodeAgeHours(list, now = Date.now()) {
171
+ const stamps = [];
172
+ for (const it of list) {
173
+ const raw = String(metadataOf(it).creationTimestamp ?? '');
174
+ if (raw === '')
175
+ continue;
176
+ const at = parseInstant(raw);
177
+ if (at === null)
178
+ continue;
179
+ stamps.push(at);
180
+ }
181
+ if (stamps.length === 0)
182
+ return null;
183
+ return Math.max(0.0, (now - Math.min(...stamps)) / 3600000);
184
+ }
185
+ /**
186
+ * An ISO-8601 instant, or null -- and `Date.parse` is not that.
187
+ *
188
+ * `Date.parse` accepts a pile of things that have always been rejected here: `"2026"` is a
189
+ * year to it, and `"Mar 5 2020"` parses in JavaScript. A node whose
190
+ * `creationTimestamp` is any of them would then be counted as the oldest and set the
191
+ * cluster's whole reported age.
192
+ *
193
+ * TWO DELIBERATE DIFFERENCES REMAIN, both unreachable from a real cluster: `metav1.Time`
194
+ * marshals as RFC 3339, so `creationTimestamp` is always `YYYY-MM-DDTHH:MM:SSZ`.
195
+ *
196
+ * An offset is REQUIRED here and optional in the previous implementation, which reads a
197
+ * stamp without one as a NAIVE time, and its subtraction against the current UTC time then
198
+ * throws a TypeError -- out of the age computation, out of `status()`, and out of the
199
+ * report.
200
+ * Skipping the stamp is what the rest of this function already does with one it cannot
201
+ * read, and a ledger that reports an unknown age is the whole point of this module.
202
+ *
203
+ * Basic-format ISO (`20260916T100000Z`) parses there and not here. That direction is the
204
+ * safe one -- it yields a null age rather than a wrong one -- and buying it would cost a
205
+ * second grammar plus a rewrite step, which is a new place to be wrong about a shape
206
+ * Kubernetes does not emit.
207
+ */
208
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/u;
209
+ function parseInstant(raw) {
210
+ if (!ISO_INSTANT.test(raw))
211
+ return null;
212
+ const at = Date.parse(raw.replace(' ', 'T'));
213
+ return Number.isNaN(at) ? null : at;
214
+ }
215
+ /**
216
+ * Gigabytes claimed by these PVCs, or null if the cluster would not say.
217
+ *
218
+ * null rather than 0.0 for a refused read, for the reason the whole module exists: an
219
+ * unreadable volume list priced at nothing is a bill that looks free.
220
+ */
221
+ function claimedGb(answer) {
222
+ if ((0, ask_1.refused)(answer))
223
+ return null;
224
+ let total = 0.0;
225
+ for (const it of (0, ask_1.items)(answer)) {
226
+ const spec = (it.spec ?? {});
227
+ const resources = (spec.resources ?? {});
228
+ const requests = (resources.requests ?? {});
229
+ const raw = String(requests.storage ?? '');
230
+ if (raw === '')
231
+ continue;
232
+ // The numeric head read as a float, so a malformed value is skipped rather than counted
233
+ // as a zero -- which would read as a volume that exists and costs nothing.
234
+ const head = (suffix) => {
235
+ const text = raw.slice(0, -suffix.length);
236
+ if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/u.test(text.trim()))
237
+ return null;
238
+ return Number(text);
239
+ };
240
+ if (raw.endsWith('Gi')) {
241
+ const value = head('Gi');
242
+ if (value !== null)
243
+ total += value;
244
+ }
245
+ else if (raw.endsWith('Mi')) {
246
+ const value = head('Mi');
247
+ if (value !== null)
248
+ total += value / 1024.0;
249
+ }
250
+ else if (raw.endsWith('Ti')) {
251
+ const value = head('Ti');
252
+ if (value !== null)
253
+ total += value * 1024.0;
254
+ }
255
+ }
256
+ return total;
257
+ }
258
+ /**
259
+ * Instance type -> how many. `""` for a node that does not say.
260
+ *
261
+ * THROUGH A `Map`, because the key is a label a cluster chose and a JavaScript object
262
+ * already has keys. A node typed `toString` read `Object.prototype.toString` as its running
263
+ * count and produced `"function toString() { [native code] }1"`; one typed `__proto__`
264
+ * would have set the prototype instead of a count. A Map has neither problem, and
265
+ * `Object.fromEntries` gives the plain object every caller downstream expects.
266
+ */
267
+ function nodeInventory(list) {
268
+ const counts = new Map();
269
+ for (const it of list) {
270
+ const labels = (metadataOf(it).labels ?? {});
271
+ const kind = String(labels['node.kubernetes.io/instance-type'] ?? '');
272
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
273
+ }
274
+ return Object.fromEntries(counts);
275
+ }
276
+ /**
277
+ * The distribution, by a route that does not require a node to exist.
278
+ *
279
+ * `kube.distribution()` reads a NODE's providerID, which is the most reliable signal there
280
+ * is -- when there is a node. A managed cluster with zero of them is not an edge case: it
281
+ * is every cluster mid-create, mid-delete, or with its node group scaled to nothing.
282
+ *
283
+ * MEASURED against a real EKS cluster whose node group was being deleted: `distribution`
284
+ * answered "unknown", so it did not match BILLABLE, so the ledger priced a control plane
285
+ * that was very much running at nothing at all. That is the failure this module was
286
+ * written against, rebuilt one layer up.
287
+ *
288
+ * The context name settles what the nodes cannot: `aws eks update-kubeconfig` writes the
289
+ * cluster ARN as the context name, and an ARN names its own service.
290
+ */
291
+ function providerOf(context, dist) {
292
+ if (dist !== '' && dist !== 'unknown')
293
+ return dist;
294
+ if (context.startsWith('arn:aws:eks:'))
295
+ return 'eks';
296
+ return dist;
297
+ }
298
+ /**
299
+ * The region inside a context name, or "".
300
+ *
301
+ * Beside `providerOf` and for the same reason: the context name carries facts the cluster
302
+ * cannot always be asked for, and both shapes AWS writes contain this one --
303
+ * `aws eks update-kubeconfig` writes `arn:aws:eks:<region>:<account>:cluster/<name>` and
304
+ * `eksctl` writes `<user>@<name>.<region>.eksctl.io`.
305
+ *
306
+ * Wanted so a picker can say `chatrepo (us-east-1)` instead of sixty characters of ARN.
307
+ * Which region a cluster is in is the half of an ARN a person actually needs; the account
308
+ * id is the half they do not.
309
+ */
310
+ function regionOf(context) {
311
+ if (context.startsWith('arn:aws:eks:')) {
312
+ const bits = context.split(':');
313
+ return bits.length > 4 ? bits[3] : '';
314
+ }
315
+ if (context.endsWith('.eksctl.io')) {
316
+ // `<user>@<name>.<region>.eksctl.io` -> the part before `.eksctl.io`, last dot.
317
+ const stem = context.slice(0, -'.eksctl.io'.length);
318
+ return stem.includes('.') ? stem.split('.').pop() : '';
319
+ }
320
+ return '';
321
+ }
322
+ /**
323
+ * What this cluster costs per hour, or null when the question does not apply.
324
+ *
325
+ * Everything the ledger can SEE is priced, because everything it can see is on the screen
326
+ * already: the row above the total says "1 LoadBalancer(s) — each one is billed on a
327
+ * managed cluster" and then the total left it out. Counting a thing and not pricing it is
328
+ * the most convincing way to be wrong, since the reader can see you noticed.
329
+ *
330
+ * `unpriced` and `incomplete` are separate answers. An instance type that is not in the
331
+ * table is a gap in this build's knowledge; a count that came back null is a read that
332
+ * FAILED, and the difference matters because only one of them gets better by adding a row
333
+ * to a table.
334
+ */
335
+ function estimateUsdHr(dist, inventory, options = {}) {
336
+ const { loadbalancers = 0, volumeGb = 0.0, version = '' } = options;
337
+ // A managed cluster may bill without sharing EKS's control-plane, NAT or node rates.
338
+ // Report GKE/AKS as unpriced until their own model exists.
339
+ if (dist !== 'eks')
340
+ return null;
341
+ const supportTierKnown = Object.hasOwn(EKS_STANDARD_END, version);
342
+ const controlPlaneRate = supportTierKnown
343
+ ? eksControlPlaneRate(version)
344
+ : exports.EKS_CONTROL_PLANE_USD_HR;
345
+ let total = controlPlaneRate + exports.NAT_GATEWAY_USD_HR;
346
+ // `Object.hasOwn` and a `Map`, for the reason `nodeInventory` builds one: the key is a
347
+ // label the cluster chose. `INSTANCE_USD_HR['toString']` is a FUNCTION, so the rate was
348
+ // not undefined, the type was not reported as unpriced, and the total became NaN.
349
+ const unpricedCounts = new Map();
350
+ const incomplete = [];
351
+ if (Object.hasOwn(options, 'version') && !supportTierKnown) {
352
+ incomplete.push(version === ''
353
+ ? 'EKS support tier (Kubernetes version unavailable)'
354
+ : `EKS support tier (Kubernetes ${version} not in this rate table)`);
355
+ }
356
+ for (const [kind, count] of Object.entries(inventory)) {
357
+ const rate = Object.hasOwn(exports.INSTANCE_USD_HR, kind) ? exports.INSTANCE_USD_HR[kind] : undefined;
358
+ if (rate === undefined) {
359
+ unpricedCounts.set(kind, count);
360
+ continue;
361
+ }
362
+ total += rate * count;
363
+ }
364
+ const unpriced = Object.fromEntries(unpricedCounts);
365
+ // Node disks, counted for EVERY node including the ones whose type could not be priced --
366
+ // an unrecognised instance type still has a volume attached to it.
367
+ const nodes = Object.values(inventory).reduce((sum, n) => sum + n, 0);
368
+ total += (nodes * exports.NODE_VOLUME_GB * exports.EBS_GP3_USD_GB_MONTH) / exports.HOURS_PER_MONTH;
369
+ if (loadbalancers === null)
370
+ incomplete.push('load balancers');
371
+ else
372
+ total += loadbalancers * exports.LOADBALANCER_USD_HR;
373
+ if (volumeGb === null)
374
+ incomplete.push('workspace volumes');
375
+ else
376
+ total += (volumeGb * exports.EBS_GP3_USD_GB_MONTH) / exports.HOURS_PER_MONTH;
377
+ return {
378
+ usd_hr: round4(total),
379
+ unpriced,
380
+ incomplete,
381
+ basis: `us-east-1 on-demand: ${supportTierKnown
382
+ ? `EKS ${version} ${controlPlaneRate === exports.EKS_EXTENDED_CONTROL_PLANE_USD_HR ? 'extended' : 'standard'} support `
383
+ : Object.hasOwn(options, 'version')
384
+ ? `EKS ${version || 'version unavailable'}; standard support assumed as a lower bound for `
385
+ : ''}` +
386
+ 'control plane, NAT gateway, nodes, ' +
387
+ `${String(exports.NODE_VOLUME_GB)} GB gp3 per node (eksctl's default, not read ` +
388
+ 'back), load balancers and workspace volumes',
389
+ estimate: true,
390
+ };
391
+ }
392
+ /**
393
+ * `value` rounded to 4 places, a tie going to EVEN, which `toFixed` does not do.
394
+ *
395
+ * ON THE DOUBLE'S EXACT VALUE, which is why this is arithmetic on integers rather than
396
+ * `value * 10_000`. Multiplying first rounds once before the rounding, so a value that is
397
+ * slightly ABOVE a half lands exactly on it and then gets the tie-break -- and the
398
+ * tie-break goes the other way. Measured against the established rounding over 200,000
399
+ * inputs of the form `(k + 0.5) / 10_000`: 86,162 of them disagreed. A double is a dyadic
400
+ * rational, so reading its mantissa and exponent gives the exact value and the comparison
401
+ * against a half is then decidable rather than approximate.
402
+ */
403
+ function round4(value) {
404
+ if (!Number.isFinite(value))
405
+ return value;
406
+ const view = new DataView(new ArrayBuffer(8));
407
+ view.setFloat64(0, value);
408
+ const bits = view.getBigUint64(0);
409
+ const negative = bits >> 63n === 1n;
410
+ const exponent = Number((bits >> 52n) & 0x7ffn);
411
+ const fraction = bits & 0xfffffffffffffn;
412
+ // |value| == mantissa / 2**shift, exactly.
413
+ const mantissa = exponent === 0 ? fraction : fraction | 0x10000000000000n;
414
+ const shift = exponent === 0 ? 1074 : 1075 - exponent;
415
+ // No fractional bits at all: already an integer, and rounding one to 4 places is a no-op.
416
+ if (shift <= 0)
417
+ return value;
418
+ const scaled = mantissa * 10000n;
419
+ const denominator = 1n << BigInt(shift);
420
+ const whole = scaled / denominator;
421
+ const remainder = scaled % denominator;
422
+ const twice = remainder * 2n;
423
+ let rounded;
424
+ if (twice > denominator)
425
+ rounded = whole + 1n;
426
+ else if (twice < denominator)
427
+ rounded = whole;
428
+ else
429
+ rounded = whole % 2n === 0n ? whole : whole + 1n;
430
+ const magnitude = Number(rounded) / 10000;
431
+ return negative ? -magnitude : magnitude;
432
+ }
433
+ /** Context names local tools write for clusters that run on this machine. */
434
+ const LOCAL_CONTEXT = /^(?:kind-|k3d-)|^(?:minikube|docker-desktop|rancher-desktop|orbstack)$/u;
435
+ /**
436
+ * Where a cluster lives, from its context name and its API server, without asking it.
437
+ *
438
+ * AWS by the shape of the name or of the EKS endpoint; this machine for houston's own kind
439
+ * cluster, a name a local tool writes, or a server on the loopback; anywhere else is
440
+ * elsewhere. A k3s on another machine is not this machine, whatever its distribution.
441
+ * `ponytail:` the loopback is judged by NAME and never resolved, so a tunnel to 127.0.0.1
442
+ * reads as local; resolve the host if that ever matters.
443
+ */
444
+ function whereOf(context, server = '') {
445
+ if (context.startsWith('arn:aws:eks:') || context.endsWith('.eksctl.io'))
446
+ return 'aws';
447
+ let host;
448
+ try {
449
+ host = new URL(server).hostname.toLowerCase();
450
+ }
451
+ catch {
452
+ host = '';
453
+ }
454
+ if (host.endsWith('.eks.amazonaws.com'))
455
+ return 'aws';
456
+ if ((0, names_1.isOurs)(context) || LOCAL_CONTEXT.test(context))
457
+ return 'local';
458
+ if (host === 'localhost' ||
459
+ host === '::1' ||
460
+ host === '[::1]' ||
461
+ host.startsWith('127.') ||
462
+ host.endsWith('.docker.internal'))
463
+ return 'local';
464
+ return 'elsewhere';
465
+ }
466
+ /** One row per context: whose it is, and whether it can be reached at all. */
467
+ async function contextRows(aliases, byDefault, names, servers) {
468
+ // THE ONE PROBE, and only in one situation. houston writes its OWN kubeconfig when it
469
+ // builds its own cluster and never removes that entry -- so a cluster that has been
470
+ // deleted outside houston, or whose `kind` was uninstalled and the container removed by
471
+ // hand, leaves a context for something that does not exist. It then showed on every
472
+ // screen for ever, unusable, unreclaimable and impossible to clear.
473
+ //
474
+ // It is NOT enough to drop it whenever `kind` is missing. `planCluster` records what that
475
+ // costs: uninstalling the binary while the cluster still ran made the cluster invisible,
476
+ // "containers holding memory that nothing in houston could see or remove". A running
477
+ // cluster stays listed however little houston can do with it -- `status()` says it can no
478
+ // longer be removed and how to remove it anyway.
479
+ //
480
+ // So the question is whether the cluster is THERE, which costs one probe, bounded: our
481
+ // own context only, and only when the binary that would manage it is absent.
482
+ const drop = new Set();
483
+ const oursCtx = await (0, context_1.clusterContext)();
484
+ if (oursCtx !== '' && names.includes(oursCtx) && (0, tools_1.which)('kind') === '') {
485
+ if (!(0, reachability_1.reachOk)(await (0, reachability_1.reach)(oursCtx)))
486
+ drop.add(oursCtx);
487
+ }
488
+ // The build note, read once for the whole list: `made_by_houston` here never probes.
489
+ const builtHere = new Set(eks.remembered().map((entry) => `${String(entry.name ?? '')}@${String(entry.region ?? '')}`));
490
+ const rows = [];
491
+ for (const name of names) {
492
+ if (drop.has(name))
493
+ continue;
494
+ const provider = providerOf(name, '');
495
+ rows.push({
496
+ context: name,
497
+ // WHAT TO SHOW, decided here rather than in JavaScript -- the same reason `billable`
498
+ // is: a rule the service owns should not get a second copy in the front end. A picker
499
+ // rendering the full context put ninety-five characters of ARN plus two suffixes into
500
+ // one `<option>`, which a native select cannot shrink, and the text ran out of its box.
501
+ short: (0, context_1.shortName)(name),
502
+ region: regionOf(name),
503
+ // The other names this same cluster answers to, so a caller that sees one of them in a
504
+ // kubeconfig can tell it is not a second cluster.
505
+ aliases: Object.hasOwn(aliases, name) ? aliases[name] : [],
506
+ ours: (0, names_1.isOurs)(name),
507
+ // "" means "not knowable from the name" -- kind and k3s and minikube all look alike
508
+ // here, and guessing would put a distribution on a card that `status()` then
509
+ // contradicts.
510
+ provider,
511
+ billable: exports.BILLABLE.includes(provider),
512
+ is_default: name === byDefault,
513
+ made_by_houston: builtHere.has(`${(0, context_1.shortName)(name)}@${regionOf(name)}`),
514
+ where: whereOf(name, servers.get(name) ?? ''),
515
+ });
516
+ }
517
+ return rows;
518
+ }
519
+ /** Contexts that are different names for the same API server. */
520
+ async function contextAliases() {
521
+ const [allNames, unreadable] = await (0, context_1.contexts)();
522
+ const byDefault = config.defaultKubeContext();
523
+ // ONE ROW PER CLUSTER, not one per context. `eksctl create cluster` writes
524
+ // `<iam-user>@<cluster>.<region>.eksctl.io` and `aws eks update-kubeconfig` writes the
525
+ // ARN, so a cluster built with one and adopted with the other has both -- and a list of
526
+ // CONTEXTS then shows it twice and prices it twice. Reported from a real screen: "Costing
527
+ // money 2 · ~$16.87/day" for a single cluster costing $8.44. A ledger whose whole job is
528
+ // to make spend visible must not double it.
529
+ //
530
+ // The API server settles it with no probe: two contexts naming the same server are the
531
+ // same cluster whatever they are called. The ARN is kept as the name to show, because it
532
+ // says which account and which region -- the two facts the eksctl alias leaves out and the
533
+ // two that matter when acting on the wrong cluster.
534
+ const [servers] = await (0, context_1.contextServers)();
535
+ // MAPS, not objects, all the way through: a kubeconfig context may be called anything,
536
+ // and `'constructor' in servers` is true of an object that has never heard of it.
537
+ const serverOf = new Map(Object.entries(servers));
538
+ const aliasesOf = new Map();
539
+ let names = [...allNames];
540
+ if (serverOf.size > 0) {
541
+ const byServer = new Map();
542
+ for (const name of names) {
543
+ const url = serverOf.get(name);
544
+ if (url !== undefined && url !== '') {
545
+ const group = byServer.get(url) ?? [];
546
+ group.push(name);
547
+ byServer.set(url, group);
548
+ }
549
+ }
550
+ const keep = new Set();
551
+ for (const group of byServer.values()) {
552
+ const sorted = [...group].sort();
553
+ const best = sorted.find((g) => g.startsWith('arn:aws:eks:')) ?? sorted[0];
554
+ keep.add(best);
555
+ if (group.length > 1)
556
+ aliasesOf.set(best, sorted.filter((n) => n !== best));
557
+ }
558
+ names = names.filter((n) => !serverOf.has(n) || keep.has(n));
559
+ }
560
+ return {
561
+ aliases: Object.fromEntries(aliasesOf),
562
+ byDefault,
563
+ names,
564
+ unreadable,
565
+ servers: serverOf,
566
+ };
567
+ }
568
+ /**
569
+ * Every cluster this box could talk to, without talking to any of them but one.
570
+ *
571
+ * Deliberately cheap and deliberately incomplete. `status()` is six or more probes per
572
+ * cluster and one that is refusing spends the whole timeout, so a caller that wanted a list
573
+ * of three clusters would wait on the slowest -- and a front end that fetches this first can
574
+ * draw the cards immediately and fill each one in as its own `status()` returns. A cluster
575
+ * nobody can reach then costs one slow card rather than a slow page.
576
+ *
577
+ * Nothing here is a claim about a cluster's health, and none of these fields comes from a
578
+ * probe: the context names are the kubeconfig's, `ours` is which kubeconfig they came from,
579
+ * and `provider` is read from the shape of the name. A caller that needs to know whether a
580
+ * cluster is up asks `status()`, which is the function that goes and finds out.
581
+ */
582
+ async function knownContexts() {
583
+ const { aliases, byDefault, names, unreadable, servers } = await contextAliases();
584
+ return {
585
+ contexts: await contextRows(aliases, byDefault, names, servers),
586
+ unreadable,
587
+ default: byDefault,
588
+ };
589
+ }
590
+ /**
591
+ * How many cluster reads `status` keeps in flight.
592
+ *
593
+ * Bounded on purpose: each one is a kubectl subprocess, and a cluster holding twenty
594
+ * workspaces would otherwise fork sixty at once on a laptop that is already running other
595
+ * stacks. Eight covers the six independent top-level reads in one go and keeps the
596
+ * per-namespace wave moving.
597
+ */
598
+ exports.STATUS_WORKERS = 8;
599
+ exports.STAGES = ['Tools', 'Approve', 'Build', 'DNS', 'Run workspaces', 'Tear down'];
600
+ /**
601
+ * The next thing to do, decided once for the CLI, the GUI stepper and the docs.
602
+ *
603
+ * ONE TABLE, FIRST MATCH WINS, in the order a person meets these: what stops everything
604
+ * (tools, approval) before what stops a cluster (a build, DNS), and what costs money
605
+ * (an expiry, an idle cluster) before the happy path. Pure: it reads what it is given and
606
+ * touches nothing, which is what lets both front-ends show the same sentence.
607
+ */
608
+ function nextStep(input) {
609
+ const failed = input.failed.find((build) => build.present !== false);
610
+ if (failed !== undefined) {
611
+ return {
612
+ stage: 6,
613
+ cluster: failed.name,
614
+ title: `The build of ${failed.name} failed part-way and may be billing — delete what it left`,
615
+ why: 'eksctl may have built a VPC, a NAT gateway and a control plane before it failed, and ' +
616
+ 'houston does not destroy them on its own. Delete proves ownership by the tag in the ' +
617
+ 'config eksctl was handed, then checks AWS for anything left behind.',
618
+ command: `houston cluster delete ${failed.name} --region ${failed.region}`,
619
+ };
620
+ }
621
+ const building = input.building[0];
622
+ if (building !== undefined) {
623
+ return {
624
+ stage: 3,
625
+ cluster: building,
626
+ title: `Building ${building} — about twenty minutes`,
627
+ why: 'Billing started when the build started. When it finishes, point a DNS name at the ' +
628
+ 'address it prints (stage 4).',
629
+ command: '',
630
+ };
631
+ }
632
+ const ordered = [...input.clusters].sort((a, b) => {
633
+ const ad = a.context === input.default_context ? 0 : 1;
634
+ const bd = b.context === input.default_context ? 0 : 1;
635
+ return ad - bd;
636
+ });
637
+ const usable = ordered.filter((c) => !c.gone);
638
+ if (usable.length === 0) {
639
+ // What stops a BUILD matters only when there is nothing to use yet: a box with a
640
+ // working cluster (kind, or a colleague's) is not told to install eksctl or approve
641
+ // an account it will never build in.
642
+ if (!input.tools_ok) {
643
+ // ONLY THE SIGN-IN (or the region) MISSING is its own sentence. `eks.blockers` lists
644
+ // no identity problem while a tool is absent, so a list with no tool in it means
645
+ // every tool is there -- and "Install the four tools" sent somebody with an expired
646
+ // SSO token looking for software they already had.
647
+ const blockers = input.blockers ?? [];
648
+ const toolMissing = blockers.some((line) => / is not installed$| is older than /u.test(line));
649
+ if (blockers.length > 0 && !toolMissing) {
650
+ const signIn = blockers.some((line) => line.startsWith('not signed in to AWS'));
651
+ return {
652
+ stage: 1,
653
+ cluster: '',
654
+ title: signIn ? 'Sign in to AWS on this machine' : 'Set an AWS region on this machine',
655
+ why: blockers.join(' '),
656
+ command: 'houston doctor',
657
+ };
658
+ }
659
+ return {
660
+ stage: 1,
661
+ cluster: '',
662
+ title: 'Install the four tools and sign in to AWS on this machine',
663
+ why: 'aws, eksctl, kubectl and helm, plus an AWS identity and a region. `houston doctor` ' +
664
+ 'names whichever is missing; a cluster is not built until all of them are there, ' +
665
+ 'because kubectl and helm are needed to prepare it after the money is spent.',
666
+ command: 'houston doctor',
667
+ };
668
+ }
669
+ if (!input.approved) {
670
+ const account = input.account === '' ? '<account id>' : input.account;
671
+ return {
672
+ stage: 2,
673
+ cluster: '',
674
+ title: `Approve AWS account ${account} for spending on this box`,
675
+ why: 'houston will not build a cluster in an account until an admin names it here. It is a ' +
676
+ 'deliberate gate on money, and no flag skips it.',
677
+ command: `houston config set cluster.approved_accounts ${account}`,
678
+ };
679
+ }
680
+ return {
681
+ stage: 3,
682
+ cluster: '',
683
+ title: 'Build a cluster',
684
+ why: 'About twenty minutes, and it bills from the first minute whether or not anything runs ' +
685
+ 'in it. Give it the DNS zone your workspace names will live under.',
686
+ command: 'houston cluster create support --region us-east-1 --zone <your zone>',
687
+ };
688
+ }
689
+ const dnsPending = usable.find((c) => c.zone !== '' && c.ready !== null && c.ready.dns_answers === false);
690
+ if (dnsPending !== undefined) {
691
+ const target = dnsPending.ready?.cname_target ?? '';
692
+ return {
693
+ stage: 4,
694
+ cluster: dnsPending.name,
695
+ title: `Point *.${dnsPending.zone} at ${target}, once`,
696
+ why: `The name does not answer yet. Until it does, a workspace on ${dnsPending.name} is ` +
697
+ 'reachable only by a port-forward. Add the record at your DNS provider (a CNAME, ' +
698
+ 'not an A record: the address changes), then check it.',
699
+ command: `*.${dnsPending.zone} CNAME ${target}`,
700
+ };
701
+ }
702
+ // ONLY ONCE IT IS DUE. A build is often given a reminder a day or two out, and warning
703
+ // from three days before flagged every new cluster the minute it was ready -- above the
704
+ // DNS record it actually needed. The date itself stays on the cluster's details.
705
+ const expiring = usable.find((c) => c.expires_in_days !== null && c.expires_in_days <= 0);
706
+ if (expiring !== undefined) {
707
+ const days = expiring.expires_in_days ?? 0;
708
+ return {
709
+ stage: 6,
710
+ cluster: expiring.name,
711
+ title: days < 0
712
+ ? `${expiring.name} passed its expiry date ${String(-days)} d ago — keep it or delete it`
713
+ : `${expiring.name} reaches its expiry date today — keep it or delete it`,
714
+ why: 'The date is a reminder tag and nothing deletes on it. Move it if the cluster is still ' +
715
+ 'needed; delete the cluster when it is not, because it bills either way.',
716
+ command: `houston cluster keep ${expiring.name} --days 7`,
717
+ };
718
+ }
719
+ const idle = usable.find((c) => c.reachable &&
720
+ c.made_by_houston === true &&
721
+ c.workspaces !== null &&
722
+ c.workspaces.length === 0 &&
723
+ c.cost !== null);
724
+ if (idle !== undefined) {
725
+ const perDay = idle.cost === null ? '' : ` ~$${(idle.cost.usd_hr * 24).toFixed(2)}/day`;
726
+ return {
727
+ stage: 6,
728
+ cluster: idle.name,
729
+ title: `${idle.name} holds nothing and bills${perDay} — delete it when you are done`,
730
+ why: 'Removing workspaces does not lower the rate; only deleting the cluster stops it. ' +
731
+ 'Delete releases the load balancer, removes the cluster and checks AWS for leftovers.',
732
+ command: `houston cluster delete ${idle.name}`,
733
+ };
734
+ }
735
+ const ready = usable.find((c) => c.reachable);
736
+ if (ready !== undefined) {
737
+ return {
738
+ stage: 5,
739
+ cluster: ready.name,
740
+ title: `Run a workspace on ${ready.name}`,
741
+ why: `In the GUI: click New workspace and pick ${ready.name} under Where it runs` +
742
+ (ready.zone !== ''
743
+ ? `; its public name is pre-filled from ${ready.zone}.`
744
+ : ready.where !== 'aws'
745
+ ? '.'
746
+ : '. Without a DNS zone it is reachable only by a port-forward; ' +
747
+ `\`houston cluster prepare ${ready.name} --zone <zone>\` sets one.`),
748
+ command: `houston up --version <version> --name <ticket> --context ${ready.name}`,
749
+ };
750
+ }
751
+ const down = usable[0];
752
+ return {
753
+ stage: 5,
754
+ cluster: down.name,
755
+ title: `${down.name} is not answering — ${down.reach_why || 'it could not be read'}`,
756
+ why: 'Nothing about it could be read, which is not a report that it is empty or free. ' +
757
+ (down.reach_advice || 'Check the credentials and the network, then read it again.'),
758
+ command: `houston cluster status ${down.name}`,
759
+ };
760
+ }
761
+ /**
762
+ * Set `gone` when AWS says this EKS cluster does not exist. Never throws.
763
+ *
764
+ * Split out of `status` because it is the one place a REPORT asks AWS anything, and the
765
+ * rule it has to obey is narrow enough to want stating on its own: a cluster is marked gone
766
+ * only when `describeCluster` returns ABSENT. Anything else -- REFUSED, a malformed ARN, an
767
+ * exception on the way -- leaves the cluster listed and the reader told it could not be read.
768
+ */
769
+ /**
770
+ * The AWS account the AWS CLI answers as, or '' when it cannot say. Asked once per five
771
+ * minutes (`ponytail:` a process-wide memo; a credential switched mid-serve is seen within
772
+ * that window).
773
+ */
774
+ let callerMemo = null;
775
+ function callerAccount() {
776
+ if (callerMemo === null || Date.now() - callerMemo.at > 300000) {
777
+ callerMemo = {
778
+ at: Date.now(),
779
+ account: eks.aws.whoami().then((who) => who.account, () => ''),
780
+ };
781
+ }
782
+ return callerMemo.account;
783
+ }
784
+ async function askAwsAboutIt(out, context) {
785
+ if (!context.startsWith('arn:aws:eks:'))
786
+ return;
787
+ const bits = context.split(':');
788
+ const name = context.split('/').pop() ?? '';
789
+ if (bits.length < 6 || name === '')
790
+ return;
791
+ // ONLY IN THE CALLER'S OWN ACCOUNT. describe-cluster answers from the account the AWS
792
+ // CLI is signed in to, so a cluster in another account -- a colleague's, another
793
+ // profile's -- comes back "not found", and that was reported as gone: nothing billing,
794
+ // Forget offered, for a cluster that was running. Another account is "could not ask".
795
+ const caller = await callerAccount();
796
+ if (caller === '' || caller !== bits[4])
797
+ return;
798
+ let seen;
799
+ try {
800
+ seen = await eks.aws.describeCluster(name, bits[3]);
801
+ }
802
+ catch {
803
+ // a report must not raise on a lookup
804
+ return;
805
+ }
806
+ if ((0, ask_1.present)(seen)) {
807
+ // THE SAME DOCUMENT carries the tags `cluster create` wrote and the creation time, so
808
+ // who built it and when it expires are read here, on every machine, for nothing extra.
809
+ const doc = seen.doc;
810
+ const tags = (doc.tags ?? {});
811
+ out.made_by_houston = tags[eks.OWNED_TAG_KEY] === eks.OWNED_TAG_VALUE;
812
+ const expires = tags[eks.EXPIRY_TAG_KEY];
813
+ if (typeof expires === 'string')
814
+ out.expires = expires;
815
+ const zone = tags[eks.ZONE_TAG_KEY];
816
+ if (typeof zone === 'string')
817
+ out.zone = zone;
818
+ if (typeof doc.createdAt === 'string')
819
+ out.created_at = doc.createdAt;
820
+ if (typeof doc.version === 'string')
821
+ out.kubernetes_version = doc.version;
822
+ return;
823
+ }
824
+ if (seen.state !== ask_1.ABSENT)
825
+ return;
826
+ out.gone = true;
827
+ out.reach_advice =
828
+ 'AWS says this cluster no longer exists, so it is not costing anything. The ' +
829
+ 'kubeconfig entry naming it is left over -- `houston cluster forget ' +
830
+ `${name}\` removes it, or \`kubectl config delete-context ${context}\`.`;
831
+ }
832
+ /** The workspaces on this cluster, and what each one is holding. */
833
+ async function workspaceRows(ctx, spaces, out, volumeGb) {
834
+ if (spaces === null) {
835
+ out.unreadable.push('workspaces');
836
+ return volumeGb;
837
+ }
838
+ // Wave two: three reads per namespace, all in flight together under the same bound.
839
+ const per = await (0, map_limit_1.mapLimit)(spaces, exports.STATUS_WORKERS, async (ns) => {
840
+ const name = ns.startsWith(names_1.NAMESPACE_PREFIX) ? ns.slice(names_1.NAMESPACE_PREFIX.length) : ns;
841
+ const [owner, held, pvc] = await Promise.all([
842
+ (0, namespace_1.namespaceOwner)(ns, { context: ctx }),
843
+ (0, namespace_1.workspacePvcs)(name, { context: ctx }).then((v) => ({ ok: true, value: v }), () => ({ ok: false, value: [] })),
844
+ (0, ask_1.askList)('pvc', { context: ctx, namespace: ns }),
845
+ ]);
846
+ return { ns, name, owner, held, pvc };
847
+ });
848
+ const rows = [];
849
+ let pvcsTotal = 0;
850
+ let pvcsUnreadable = false;
851
+ let running = volumeGb;
852
+ for (const { ns, name, owner, held, pvc } of per) {
853
+ // one unreadable workspace is not zero
854
+ if (!held.ok)
855
+ pvcsUnreadable = true;
856
+ pvcsTotal += held.value.length;
857
+ const gb = claimedGb(pvc);
858
+ if (gb === null) {
859
+ pvcsUnreadable = true;
860
+ running = null;
861
+ }
862
+ else if (running !== null) {
863
+ running += gb;
864
+ }
865
+ rows.push({
866
+ namespace: ns,
867
+ name,
868
+ owner: owner ?? '',
869
+ owner_readable: owner !== null,
870
+ pvcs: held.value.length,
871
+ });
872
+ }
873
+ out.workspaces = rows;
874
+ out.pvcs = pvcsUnreadable ? null : pvcsTotal;
875
+ if (pvcsUnreadable)
876
+ out.unreadable.push('pvcs');
877
+ return running;
878
+ }
879
+ /** Every read the ledger needs, asked concurrently because each is a round trip. */
880
+ async function askTheClusterEverything(ctx, out, volumeGb) {
881
+ // READ CONCURRENTLY, in two waves. Every read below is an independent kubectl round trip
882
+ // and none of them writes, but they ran one after another -- about a dozen calls for a
883
+ // cluster holding two workspaces, and on a managed cluster each one is a second or two
884
+ // over the network.
885
+ //
886
+ // MEASURED against a live EKS cluster: 18.15 seconds for one card, while the same box
887
+ // answered the cheap LIST in 0.31. The GUI draws a card per cluster and fills each in from
888
+ // its own request, so this number is exactly how long somebody sits looking at `?`.
889
+ //
890
+ // The SECOND wave depends on the first: which namespaces exist has to come back before
891
+ // their owners and volumes can be asked for. Within a wave nothing depends on anything
892
+ // else, and results are assembled in a fixed order afterwards so the document does not
893
+ // vary with which call happened to finish first.
894
+ const [dist, nodes, spaces, lbs, oper, mon, storage, ingress, certApi, lbService] = await Promise.all([
895
+ (0, context_1.distribution)(ctx),
896
+ (0, ask_1.askList)('nodes', { context: ctx }),
897
+ (0, capabilities_1.workspaceNamespaces)(ctx),
898
+ (0, ask_1.askList)('svc', { context: ctx, allNamespaces: true }),
899
+ (0, operator_1.operatorPresence)(ctx),
900
+ (0, monitoring_1.monitoringInstalled)(ctx),
901
+ // The four things `cluster prepare` leaves behind, so a page can say which stage a
902
+ // cluster is at without anybody re-running prepare to find out.
903
+ (0, capabilities_1.storageClasses)(ctx),
904
+ (0, capabilities_1.ingressClasses)(ctx),
905
+ (0, ask_1.askObject)('customresourcedefinition', 'certificates.cert-manager.io', { context: ctx }),
906
+ (0, endpoints_1.loadbalancerService)(ctx),
907
+ ]);
908
+ out.distribution = providerOf(ctx, dist);
909
+ if (out.distribution === 'eks')
910
+ out.where = 'aws';
911
+ out.ready = {
912
+ storage_class: storage === null ? null : storage[1],
913
+ ingress_class: ingress === null ? null : (ingress[0] ?? ''),
914
+ cert_manager: (0, ask_1.refused)(certApi) ? null : (0, ask_1.present)(certApi),
915
+ cname_target: lbService[1],
916
+ dns_answers: await dnsAnswers(out.zone, lbService[1]),
917
+ };
918
+ out.provider = out.distribution === 'kind' ? names_1.PROVIDER_KIND : names_1.PROVIDER_EXTERNAL;
919
+ if ((0, ask_1.refused)(nodes)) {
920
+ out.unreadable.push('nodes');
921
+ }
922
+ else {
923
+ const list = (0, ask_1.items)(nodes);
924
+ out.nodes = list.length;
925
+ out.age_hours = oldestNodeAgeHours(list);
926
+ out.instance_types = nodeInventory(list);
927
+ }
928
+ const running = await workspaceRows(ctx, spaces, out, volumeGb);
929
+ if ((0, ask_1.refused)(lbs)) {
930
+ out.unreadable.push('loadbalancers');
931
+ }
932
+ else {
933
+ out.loadbalancers = (0, ask_1.items)(lbs).filter((it) => String((it.spec ?? {}).type ?? '') === 'LoadBalancer').length;
934
+ }
935
+ // PRESENCE, not ownership. The card's question is "does this cluster have a MongoDB
936
+ // operator", and since `ensureOperator` adopts a foreign one rather than installing beside
937
+ // it, asking about houston's own release would report "no operator" for a cluster that has
938
+ // a perfectly good one and would use it.
939
+ out.operator = (0, ask_1.present)(oper);
940
+ out.monitoring = mon;
941
+ return running;
942
+ }
943
+ /** What houston's own cluster is, when the tool that made it is still here. */
944
+ async function describeOurCluster(ctx, out) {
945
+ out.ours = (0, names_1.isOurs)(ctx);
946
+ // A CLUSTER HOUSTON MADE AND CAN NO LONGER REMOVE. `deleteCluster`, `clusterReclaimable`
947
+ // and `prune` all open with `if (which('kind') === '') return false`, so uninstalling the
948
+ // kind BINARY leaves the cluster running, reachable, holding memory -- and silently
949
+ // unreclaimable, because those functions answer "there was nothing to delete" rather than
950
+ // "I cannot delete it". The module docstring's rule applies to a control as much as to a
951
+ // count: reporting nothing where the honest answer is "I cannot" is how a thing gets
952
+ // forgotten.
953
+ if (out.ours && (0, tools_1.which)('kind') === '') {
954
+ out.manageable = false;
955
+ out.unmanageable_why =
956
+ 'houston built this cluster and can no longer remove it: kind is not ' +
957
+ 'installed. It keeps running and holding memory until something takes it ' +
958
+ 'away. Reinstall kind and `houston prune`, or remove its container ' +
959
+ `directly with \`docker rm -f ${names_1.CLUSTER_NAME}-control-plane\`.`;
960
+ }
961
+ if (out.ours) {
962
+ // houston's OWN cluster is reached through houston's OWN kubeconfig, and a fresh
963
+ // HOUSTON_HOME has not got one yet -- so a cluster that is up and visible in `kubectl
964
+ // config get-contexts` answers "not answering" here.
965
+ //
966
+ // `ensureKubeconfig` exists for exactly this and its docstring names the case: "With a
967
+ // kind cluster already up and a fresh home, every command failed ... and could not
968
+ // self-heal". That was fixed for `up`, and this command reintroduced it by probing
969
+ // without calling it.
970
+ //
971
+ // Best effort: a status report must not fail because an export did not work. If it does
972
+ // not, `reachable` below answers false and says so honestly.
973
+ try {
974
+ await (0, cluster_1.ensureKubeconfig)({ context: ctx, distribution: 'kind', create: false });
975
+ }
976
+ catch {
977
+ // a report must not raise on a repair
978
+ }
979
+ }
980
+ }
981
+ /** The shape of the answer, filled in as far as a context that may not exist allows. */
982
+ function emptyLedger(ctx) {
983
+ return {
984
+ context: ctx,
985
+ distribution: '',
986
+ provider: '',
987
+ ours: false,
988
+ reachable: false,
989
+ unreadable: [],
990
+ // DECLARED HERE, not only where they are set. Every caller reads this document -- the
991
+ // CLI renderer, the `--json` envelope, and fixture-style test doubles -- so a key
992
+ // that appears only on some paths is the payload-shape trap this repo already has a name
993
+ // for.
994
+ reach_status: reachability_1.REACH_DOWN,
995
+ reach_why: '',
996
+ reach_advice: '',
997
+ // Whether houston can still TAKE THIS CLUSTER AWAY, which is not the same question as
998
+ // whether it can use it.
999
+ manageable: true,
1000
+ unmanageable_why: '',
1001
+ // AWS asserting the cluster is not there, which is not the same as it not answering.
1002
+ // Only ever set from a definite ABSENT.
1003
+ gone: false,
1004
+ nodes: null,
1005
+ age_hours: null,
1006
+ instance_types: null,
1007
+ workspaces: null,
1008
+ pvcs: null,
1009
+ loadbalancers: null,
1010
+ operator: null,
1011
+ monitoring: null,
1012
+ cost: null,
1013
+ name: (0, context_1.shortName)(ctx),
1014
+ region: regionOf(ctx),
1015
+ made_by_houston: null,
1016
+ created_at: '',
1017
+ expires: '',
1018
+ expires_in_days: null,
1019
+ spend_usd: null,
1020
+ ready: null,
1021
+ zone: '',
1022
+ where: whereOf(ctx),
1023
+ };
1024
+ }
1025
+ /**
1026
+ * What the local build note knows, for the fields AWS did not answer.
1027
+ *
1028
+ * The note is written by `cluster create` on the machine that ran it, so it is a fallback
1029
+ * and never the first word: a tag says the same thing on every machine, and AWS saying
1030
+ * "no tag" beats a note saying "I built it".
1031
+ */
1032
+ function describeRecord(out) {
1033
+ const record = eks
1034
+ .remembered()
1035
+ .find((entry) => entry.name === out.name && (out.region === '' || entry.region === out.region));
1036
+ if (record === undefined)
1037
+ return;
1038
+ if (out.made_by_houston === null)
1039
+ out.made_by_houston = true;
1040
+ if (out.created_at === '' && typeof record.created_at === 'string')
1041
+ out.created_at = record.created_at;
1042
+ if (out.expires === '' && typeof record.expires === 'string')
1043
+ out.expires = record.expires;
1044
+ if (out.zone === '' && typeof record.zone === 'string')
1045
+ out.zone = record.zone;
1046
+ }
1047
+ /** What a name resolves to as a CNAME, or [] when it does not; never throws. */
1048
+ async function resolveName(host) {
1049
+ try {
1050
+ return await (0, promises_1.resolveCname)(host);
1051
+ }
1052
+ catch {
1053
+ return [];
1054
+ }
1055
+ }
1056
+ /**
1057
+ * The IPv4 addresses a name answers with, or [] when it answers none; never throws.
1058
+ *
1059
+ * Asked only when a name has no CNAME: a name that answers with addresses but no CNAME is
1060
+ * a record a proxy rewrites -- Cloudflare's default, the orange cloud -- which is a
1061
+ * different fix from a record that is not there at all.
1062
+ */
1063
+ async function resolveAddresses(host) {
1064
+ try {
1065
+ return await (0, promises_1.resolve4)(host);
1066
+ }
1067
+ catch {
1068
+ return [];
1069
+ }
1070
+ }
1071
+ /**
1072
+ * Whether a name under the cluster's zone reaches its load balancer: the wildcard CNAME
1073
+ * the guide asks for, checked with a name nobody uses. null when there is no zone or no
1074
+ * address to compare against; false when the name is missing or points elsewhere.
1075
+ */
1076
+ async function dnsAnswers(zone, target) {
1077
+ if (zone === '' || target === '')
1078
+ return null;
1079
+ let answers;
1080
+ try {
1081
+ answers = await (0, promises_1.resolveCname)(`houston-probe.${zone}`);
1082
+ }
1083
+ catch {
1084
+ return false;
1085
+ }
1086
+ const want = target.toLowerCase().replace(/\.$/u, '');
1087
+ return answers.some((answer) => answer.toLowerCase().replace(/\.$/u, '') === want);
1088
+ }
1089
+ /** The rate times the age, or null when either side is unknown. Never negative. */
1090
+ function spendSoFar(out) {
1091
+ if (out.cost === null || out.created_at === '')
1092
+ return null;
1093
+ const since = Date.parse(out.created_at);
1094
+ if (Number.isNaN(since))
1095
+ return null;
1096
+ const hours = (Date.now() - since) / 3600000;
1097
+ if (hours < 0)
1098
+ return null;
1099
+ return round4(out.cost.usd_hr * hours);
1100
+ }
1101
+ /** What the ledger can still say about a cluster that will not answer. */
1102
+ async function unreachableLedger(ctx, out) {
1103
+ // A CLUSTER THAT AWS SAYS IS GONE. `cluster delete` removes the cluster; it does not reach
1104
+ // into every kubeconfig on the machine and tidy the entries that named it, and `aws eks
1105
+ // update-kubeconfig` and `eksctl` each wrote one. A cluster deleted OUTSIDE houston
1106
+ // therefore keeps a context for ever, and the card for it says only "not answering" --
1107
+ // which reads as a cluster that is down and still billing, the most alarming reading of
1108
+ // the cheapest state.
1109
+ //
1110
+ // HERE AND NOT IN `knownContexts`. This costs an AWS round trip, and the list is the
1111
+ // function whose entire contract is that it probes nothing -- one probe per cloud cluster
1112
+ // on a four-second poll is what made the page slow enough to be reported. `status` is per
1113
+ // card, already spends `reach`, and is only reached at all when that has already failed.
1114
+ //
1115
+ // ONLY ON A DEFINITE NO. `describeCluster` answers PRESENT, ABSENT or REFUSED, and only
1116
+ // ABSENT is AWS asserting the cluster is not there. REFUSED is "I could not ask" --
1117
+ // expired credentials, no route, a permission boundary -- and calling that gone would
1118
+ // report a BILLING cluster as deleted, which is the one mistake this module exists to
1119
+ // prevent.
1120
+ await askAwsAboutIt(out, ctx);
1121
+ finishTheRecord(out);
1122
+ // Everything below needs the API server. Reporting zeros for a cluster that did not answer
1123
+ // is the exact failure this module is written against, so the fields stay null and the
1124
+ // caller is told why.
1125
+ out.unreadable.push('cluster');
1126
+ return out;
1127
+ }
1128
+ /** The API server a context names, from the kubeconfig; '' when it cannot be read. */
1129
+ async function serverOf(ctx) {
1130
+ const [servers] = await (0, context_1.contextServers)();
1131
+ return Object.hasOwn(servers, ctx) ? servers[ctx] : '';
1132
+ }
1133
+ /**
1134
+ * The overview's read of a cluster that does not bill: whether it answers, what it is,
1135
+ * and which workspaces it holds.
1136
+ *
1137
+ * A working install does not change its storage class or its ingress between two looks,
1138
+ * and `up` checks both right before it creates anything, so a page that asked again on
1139
+ * every look paid eleven reads where three answer what it shows. `status` reads the rest
1140
+ * when somebody opens the cluster. What is not read stays null, never a zero or a tick.
1141
+ */
1142
+ async function glance(ctx, where) {
1143
+ const out = emptyLedger(ctx);
1144
+ out.where = where;
1145
+ await describeOurCluster(ctx, out);
1146
+ const got = await (0, reachability_1.reach)(ctx);
1147
+ out.reachable = (0, reachability_1.reachOk)(got);
1148
+ out.reach_status = got.status;
1149
+ out.reach_why = (0, reachability_1.reachWhy)(got);
1150
+ out.reach_advice = (0, reachability_1.reachAdvice)(got, ctx);
1151
+ if (!out.reachable) {
1152
+ out.unreadable.push('cluster');
1153
+ return out;
1154
+ }
1155
+ const [dist, spaces, claims] = await Promise.all([
1156
+ (0, context_1.distribution)(ctx),
1157
+ (0, ask_1.askList)('namespace', { context: ctx, selector: names_1.OWNER_SELECTOR }),
1158
+ (0, ask_1.askList)('pvc', { context: ctx, allNamespaces: true, selector: names_1.OWNER_SELECTOR }),
1159
+ ]);
1160
+ out.distribution = providerOf(ctx, dist);
1161
+ // EKS under a name and a server that do not say so: it bills, so it is read in full.
1162
+ if (out.distribution === 'eks')
1163
+ return await status(ctx);
1164
+ out.provider = out.distribution === 'kind' ? names_1.PROVIDER_KIND : names_1.PROVIDER_EXTERNAL;
1165
+ if ((0, ask_1.refused)(spaces)) {
1166
+ out.unreadable.push('workspaces');
1167
+ return out;
1168
+ }
1169
+ const held = new Map();
1170
+ for (const claim of (0, ask_1.refused)(claims) ? [] : (0, ask_1.items)(claims)) {
1171
+ const ns = String(metadataOf(claim).namespace ?? '');
1172
+ held.set(ns, (held.get(ns) ?? 0) + 1);
1173
+ }
1174
+ const rows = [];
1175
+ for (const space of (0, ask_1.items)(spaces)) {
1176
+ const meta = metadataOf(space);
1177
+ const ns = String(meta.name ?? '');
1178
+ if (ns === '')
1179
+ continue;
1180
+ const labels = (typeof meta.labels === 'object' && meta.labels !== null ? meta.labels : {});
1181
+ rows.push({
1182
+ namespace: ns,
1183
+ name: ns.startsWith(names_1.NAMESPACE_PREFIX) ? ns.slice(names_1.NAMESPACE_PREFIX.length) : ns,
1184
+ owner: String(labels[names_1.OWNER_OF_LABEL] ?? ''),
1185
+ owner_readable: true,
1186
+ pvcs: held.get(ns) ?? 0,
1187
+ });
1188
+ }
1189
+ out.workspaces = rows.sort((a, b) => (0, format_1.compareCodePoints)(a.namespace, b.namespace));
1190
+ if ((0, ask_1.refused)(claims))
1191
+ out.unreadable.push('pvcs');
1192
+ else
1193
+ out.pvcs = [...held.values()].reduce((sum, n) => sum + n, 0);
1194
+ return out;
1195
+ }
1196
+ /**
1197
+ * Everything a cluster is holding, in one read-only pass.
1198
+ *
1199
+ * `context` defaults to the box's configured cluster, so `cluster status` and `up` answer
1200
+ * about the same one -- the same reason `doctor` takes it.
1201
+ */
1202
+ async function status(context = '', _emit = events_1.nullEmit) {
1203
+ let named = context.trim();
1204
+ if (named !== '') {
1205
+ // THE SAME REFUSAL `up --context` GIVES. A context nobody can name is a bad argument,
1206
+ // not a cluster that is down, and calling it "not answering" would send somebody to
1207
+ // check a cluster that does not exist. An unreadable kubeconfig deliberately does not
1208
+ // refuse here either -- see the helper.
1209
+ [named] = await (0, context_1.assertContextKnown)(named);
1210
+ }
1211
+ let ctx = named || config.defaultKubeContext();
1212
+ if (ctx === '') {
1213
+ try {
1214
+ ctx = (await (0, context_1.planCluster)()).context;
1215
+ }
1216
+ catch {
1217
+ // no cluster is a report, not a crash
1218
+ ctx = await (0, context_1.activeContext)();
1219
+ }
1220
+ }
1221
+ let volumeGb = 0.0;
1222
+ const out = emptyLedger(ctx);
1223
+ if (ctx === '') {
1224
+ out.unreadable.push('context');
1225
+ return out;
1226
+ }
1227
+ out.where = whereOf(ctx, await serverOf(ctx));
1228
+ await describeOurCluster(ctx, out);
1229
+ const got = await (0, reachability_1.reach)(ctx);
1230
+ out.reachable = (0, reachability_1.reachOk)(got);
1231
+ // WHY it could not be read, not merely that it could not. A ledger that says "is not
1232
+ // answering" for a cluster that is ACTIVE and merely refusing this credential sends the
1233
+ // reader to check the cluster, which is the one place the problem is not -- measured
1234
+ // against a live EKS cluster, as an IAM user with no access entry.
1235
+ out.reach_status = got.status;
1236
+ out.reach_why = (0, reachability_1.reachWhy)(got);
1237
+ out.reach_advice = (0, reachability_1.reachAdvice)(got, ctx);
1238
+ if (!out.reachable)
1239
+ return await unreachableLedger(ctx, out);
1240
+ // ONE describe per EKS status, on the reachable path too. The unreachable path already
1241
+ // paid it (for `gone`); here it buys who built the cluster and when it expires, read from
1242
+ // the cluster's own tags rather than from a note only the building machine has.
1243
+ await askAwsAboutIt(out, ctx);
1244
+ finishTheRecord(out);
1245
+ volumeGb = await askTheClusterEverything(ctx, out, volumeGb);
1246
+ // LAST, because it prices things read above it. Computing it beside the node inventory --
1247
+ // where it used to be -- meant the load balancers and workspace volumes had not been
1248
+ // counted yet, so a total printed one line under "1 LoadBalancer(s) — each one is billed"
1249
+ // silently excluded it.
1250
+ if (out.instance_types !== null) {
1251
+ out.cost = estimateUsdHr(out.distribution, out.instance_types, {
1252
+ loadbalancers: out.loadbalancers,
1253
+ volumeGb,
1254
+ version: out.kubernetes_version ?? '',
1255
+ });
1256
+ }
1257
+ out.spend_usd = spendSoFar(out);
1258
+ return out;
1259
+ }
1260
+ /** The note's answers for what AWS left blank, then the days to the expiry date. */
1261
+ function finishTheRecord(out) {
1262
+ describeRecord(out);
1263
+ out.expires_in_days = eks.daysUntil(out.expires);
1264
+ }
1265
+ /** How long a server may reuse the AWS tool and identity checks between two overviews. */
1266
+ exports.PREFLIGHT_REUSE_MS = 10 * 60000;
1267
+ let lastPreflight = null;
1268
+ /**
1269
+ * Every known cluster, the totals, and what to do next -- the one answer both front-ends
1270
+ * render, so the CLI and the GUI cannot disagree about what exists or what it costs.
1271
+ *
1272
+ * An AWS cluster is a full `status`, because its numbers are money and they change; any
1273
+ * other is a `glance`. Three at a time (`ponytail:` each status already runs its own reads
1274
+ * eight wide; a wider outer limit only multiplies kubectl processes -- raise it if a box
1275
+ * with many clusters proves slow). A progress line per cluster, because one EKS status is
1276
+ * measured at ~18 s and a page that shows nothing for a minute reads as broken.
1277
+ *
1278
+ * The stages and the totals are the AWS section's: a cluster on this machine has nothing
1279
+ * to approve, build or pay for. `reuse` lets a server keep the AWS tool and identity
1280
+ * checks for `PREFLIGHT_REUSE_MS` -- 1.9 s of a 2.6 s read on a box with only a k3s --
1281
+ * while a Re-check, and every CLI run, asks again.
1282
+ */
1283
+ async function overview(emit = events_1.nullEmit, { building = [], reuse = false, } = {}) {
1284
+ const known = await knownContexts();
1285
+ if (!reuse || lastPreflight === null || Date.now() - lastPreflight.at > exports.PREFLIGHT_REUSE_MS) {
1286
+ lastPreflight = { at: Date.now(), value: await eks.aws.preflight() };
1287
+ }
1288
+ const pre = lastPreflight.value;
1289
+ const blockers = eks.blockers(pre, { toBuild: true });
1290
+ const account = pre.identity.account;
1291
+ const preflight = {
1292
+ tools_ok: blockers.length === 0,
1293
+ blockers,
1294
+ account,
1295
+ identity: pre.identity.arn,
1296
+ region: pre.region,
1297
+ approved: account !== '' && config.approvedAwsAccounts().has(account),
1298
+ };
1299
+ const clusters = await (0, map_limit_1.mapLimit)(known.contexts, 3, async (row) => {
1300
+ (0, events_1.info)(emit, `reading ${row.short}…`, { phase: 'info' });
1301
+ return row.where === 'aws'
1302
+ ? await status(row.context, emit)
1303
+ : await glance(row.context, row.where);
1304
+ });
1305
+ const inAws = clusters.filter((ledger) => ledger.where === 'aws');
1306
+ // Builds that failed part-way: the note the create leaves stays until the cluster is
1307
+ // gone, and AWS is asked whether it is. A refused read is null, never "not there".
1308
+ // Only a build whose process is GONE failed; one still running (a CLI create in another
1309
+ // terminal) is building, and "delete what it left" would have pointed at a live build.
1310
+ const dead = new Set(journal.abandoned().map((entry) => entry.id));
1311
+ const running = new Set(building);
1312
+ const failed = [];
1313
+ for (const entry of journal.openEntries()) {
1314
+ if (entry.kind !== journal.CLUSTER_UNFINISHED)
1315
+ continue;
1316
+ if (!dead.has(entry.id)) {
1317
+ running.add(entry.workspace);
1318
+ continue;
1319
+ }
1320
+ const region = String(entry.detail.region ?? '');
1321
+ let there;
1322
+ try {
1323
+ const seen = await eks.aws.describeCluster(entry.workspace, region);
1324
+ there = seen.state === ask_1.ABSENT ? false : (0, ask_1.present)(seen) ? true : null;
1325
+ }
1326
+ catch {
1327
+ there = null;
1328
+ }
1329
+ failed.push({ name: entry.workspace, region, present: there });
1330
+ }
1331
+ let usd = 0;
1332
+ let priced = 0;
1333
+ let spend = 0;
1334
+ let spent = 0;
1335
+ let workspaces = 0;
1336
+ let billable = 0;
1337
+ let unpriced = 0;
1338
+ let unread = 0;
1339
+ const names = new Set();
1340
+ for (const ledger of inAws) {
1341
+ names.add(ledger.name);
1342
+ if (!ledger.gone) {
1343
+ billable += 1;
1344
+ // A billing cluster whose rate could not be read is money the total leaves out:
1345
+ // counted here so both front-ends can say the figure is partial.
1346
+ if (ledger.cost === null ||
1347
+ ledger.cost.incomplete.length > 0 ||
1348
+ Object.keys(ledger.cost.unpriced).length > 0)
1349
+ unpriced += 1;
1350
+ }
1351
+ if (ledger.cost !== null) {
1352
+ usd += ledger.cost.usd_hr;
1353
+ priced += 1;
1354
+ }
1355
+ if (ledger.spend_usd !== null) {
1356
+ spend += ledger.spend_usd;
1357
+ spent += 1;
1358
+ }
1359
+ if (ledger.workspaces !== null)
1360
+ workspaces += ledger.workspaces.length;
1361
+ else if (!ledger.gone)
1362
+ unread += 1;
1363
+ }
1364
+ // A cluster being built bills from its first minute and has no rate yet.
1365
+ for (const name of running) {
1366
+ if (names.has(name))
1367
+ continue;
1368
+ billable += 1;
1369
+ unpriced += 1;
1370
+ }
1371
+ const totals = {
1372
+ clusters: inAws.length,
1373
+ billable,
1374
+ usd_day: priced === 0 ? null : Math.round(usd * 24 * 100) / 100,
1375
+ spend_usd: spent === 0 ? null : Math.round(spend * 100) / 100,
1376
+ workspaces,
1377
+ unpriced,
1378
+ unread,
1379
+ };
1380
+ return {
1381
+ clusters,
1382
+ failed,
1383
+ preflight,
1384
+ totals,
1385
+ next: nextStep({
1386
+ tools_ok: preflight.tools_ok,
1387
+ blockers,
1388
+ approved: preflight.approved,
1389
+ account,
1390
+ clusters: inAws,
1391
+ building: [...running],
1392
+ failed,
1393
+ default_context: known.default,
1394
+ }),
1395
+ default: known.default,
1396
+ unreadable: known.unreadable,
1397
+ };
1398
+ }