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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -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 +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -194
  284. package/dist/outputCI.js +0 -59
  285. package/src/bin.js +0 -4
  286. package/src/cli.ts +0 -25
  287. package/src/commands/createBranch.ts +0 -28
  288. package/src/outputCI.ts +0 -12
  289. package/src-old/logs.js +0 -323
  290. package/src-old/md.js +0 -191
  291. package/src-old/release-table.js +0 -60
  292. package/src-old/set-version.js +0 -614
  293. package/src-old/utils.js +0 -15
@@ -0,0 +1,1533 @@
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.createPlan = createPlan;
37
+ exports.clearTheUnfinishedNote = clearTheUnfinishedNote;
38
+ exports.createUnderTheLock = createUnderTheLock;
39
+ exports.createRepro = createRepro;
40
+ exports.reuse = reuse;
41
+ exports.carryRecordedAxes = carryRecordedAxes;
42
+ exports.resolveAxesStep = resolveAxesStep;
43
+ exports.resolvePairing = resolvePairing;
44
+ exports.loadPreset = loadPreset;
45
+ exports.settleName = settleName;
46
+ exports.claimPorts = claimPorts;
47
+ exports.refuseNamesTheEdgeCannotReach = refuseNamesTheEdgeCannotReach;
48
+ exports.warnAboutTheBind = warnAboutTheBind;
49
+ exports.warnAboutHostsOnPodman = warnAboutHostsOnPodman;
50
+ exports.warnAboutTheBrowserHost = warnAboutTheBrowserHost;
51
+ exports.buildDocument = buildDocument;
52
+ exports.buildRecord = buildRecord;
53
+ exports.attachMonitoring = attachMonitoring;
54
+ exports.refuseMongoFamilyChange = refuseMongoFamilyChange;
55
+ exports.replaceExisting = replaceExisting;
56
+ exports.writeLicense = writeLicense;
57
+ exports.writeTheWorkspace = writeTheWorkspace;
58
+ exports.startTheWorkspace = startTheWorkspace;
59
+ exports.finish = finish;
60
+ exports.refuseAForeignEdge = refuseAForeignEdge;
61
+ exports.issueCertificate = issueCertificate;
62
+ exports.startTheEdge = startTheEdge;
63
+ exports.registerTheName = registerTheName;
64
+ exports.recordTls = recordTls;
65
+ exports.prepareEdge = prepareEdge;
66
+ exports.refuseTheOtherRuntime = refuseTheOtherRuntime;
67
+ exports.createReproLocked = createReproLocked;
68
+ /**
69
+ * Creating a workspace on Docker Compose, and the front door both runtimes come in by.
70
+ *
71
+ * Tier 5. `createRepro` takes the lock and dispatches; `createReproLocked` is the Compose
72
+ * path, and it is a PLAN plus a sequence of named steps rather than one function.
73
+ *
74
+ * It was 503 lines at cyclomatic complexity 99, and the cost was not aesthetic: the order
75
+ * of those lines is load-bearing in about a dozen places, every one of them recorded in a
76
+ * comment saying what broke when it was somewhere else. Each step names what it does, and
77
+ * the order is visible in one screen at the bottom of this module.
78
+ */
79
+ const seed_options_1 = require("../../lib/seed-options");
80
+ const fs = __importStar(require("node:fs/promises"));
81
+ const compose = __importStar(require("../../lib/compose"));
82
+ const config = __importStar(require("../../lib/config"));
83
+ const errors_1 = require("../../lib/errors");
84
+ const events_1 = require("../../lib/events");
85
+ const monitoring_1 = require("../../lib/monitoring");
86
+ const format_1 = require("../../lib/format");
87
+ const home_1 = require("../../lib/home");
88
+ const redact_1 = require("../../lib/redact");
89
+ const common_1 = require("../../lib/presets/common");
90
+ const presets = __importStar(require("../../lib/presets/index"));
91
+ const composite_1 = require("../../lib/presets/composite");
92
+ const ldap_1 = require("../../lib/presets/ldap");
93
+ const public_1 = require("../../lib/presets/public");
94
+ const seed_profiles_1 = require("../../lib/seed-profiles");
95
+ const versions_1 = require("../../lib/versions");
96
+ const audit_1 = require("../audit");
97
+ const e2ee_1 = require("../../lib/presets/e2ee");
98
+ const voice_1 = require("../../lib/presets/voice");
99
+ const diagnose_1 = require("../diagnose");
100
+ const networks_1 = require("../edge/networks");
101
+ const acme_1 = require("../edge/acme");
102
+ const engine_1 = require("../edge/engine");
103
+ const runtime_1 = require("../edge/runtime");
104
+ const routes_1 = require("../edge/routes");
105
+ const host_1 = require("../runner/host");
106
+ const engine = __importStar(require("../runner/engine"));
107
+ const locks_1 = require("../runner/locks");
108
+ const paths = __importStar(require("../runner/paths"));
109
+ const portSeam = __importStar(require("../runner/ports"));
110
+ const record = __importStar(require("../runner/record"));
111
+ const queries_1 = require("../runner/queries");
112
+ const topology = __importStar(require("../topology"));
113
+ const tls_1 = require("../tls");
114
+ const create_k8s_1 = require("./create-k8s");
115
+ const inspect = __importStar(require("./inspect"));
116
+ const naming = __importStar(require("./naming"));
117
+ const ownership = __importStar(require("./ownership"));
118
+ const ports = __importStar(require("./ports"));
119
+ const preconditions = __importStar(require("./preconditions"));
120
+ const ready_1 = require("./ready");
121
+ const request = __importStar(require("./request"));
122
+ const seeding = __importStar(require("./seeding"));
123
+ const sizing = __importStar(require("./sizing"));
124
+ const tlsplan = __importStar(require("./tlsplan"));
125
+ const mongo_kernel_1 = require("../../lib/mongo-kernel");
126
+ const types_1 = require("./types");
127
+ const journal_1 = require("../journal");
128
+ function bag(value) {
129
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
130
+ ? value
131
+ : {};
132
+ }
133
+ function isTruthy(value) {
134
+ if (value === null || value === undefined || value === false)
135
+ return false;
136
+ if (typeof value === 'string')
137
+ return value !== '';
138
+ if (typeof value === 'number')
139
+ return value !== 0;
140
+ if (Array.isArray(value))
141
+ return value.length > 0;
142
+ if (typeof value === 'object')
143
+ return Object.keys(value).length > 0;
144
+ return true;
145
+ }
146
+ function createPlan(values) {
147
+ return {
148
+ streamOutput: false,
149
+ monitorAttach: request.missingMonitorAttach,
150
+ cfg: {},
151
+ resolved: null,
152
+ pre: null,
153
+ presetParams: null,
154
+ typedParams: { ...values.req.params },
155
+ wait: false,
156
+ reproName: '',
157
+ hostPort: 0,
158
+ sidePorts: {},
159
+ monitorPorts: [],
160
+ root: '',
161
+ token: '',
162
+ bindHost: '',
163
+ tlsspec: null,
164
+ public: '',
165
+ envOverrides: {},
166
+ adminPassword: '',
167
+ spec: null,
168
+ doc: null,
169
+ meta: null,
170
+ previousMeta: null,
171
+ files: [],
172
+ ...values,
173
+ };
174
+ }
175
+ /**
176
+ * EVERY note for this workspace, not just the one just written.
177
+ *
178
+ * An earlier create that failed left its own, and clearing only ours left that one
179
+ * claiming a finished workspace had never finished.
180
+ *
181
+ * UNLESS THE CALLER STILL HAS WORK TO DO. With `seedHere` the CLI runs the seed after the
182
+ * create returns, so clearing here would delete the note in the window it exists for.
183
+ */
184
+ function clearTheUnfinishedNote(req, name, note) {
185
+ if (!req.seedHere) {
186
+ (0, journal_1.clear)(note);
187
+ (0, journal_1.clearKind)(journal_1.CREATE_UNFINISHED, naming.deriveFor(req) || name);
188
+ }
189
+ }
190
+ /**
191
+ * The create itself, plus the write-ahead note that says it may not have finished.
192
+ *
193
+ * A CREATE THAT NEVER FINISHES LEAVES A WORKSPACE THAT LOOKS FINE. Measured by killing one
194
+ * mid-flight: `docker compose up -d` has already detached, so the containers come up on
195
+ * their own and `list` reports it `running` -- which is true. What is lost is everything
196
+ * after readiness: the preset's self-configuration, the seed, the edge route.
197
+ *
198
+ * Advisory rather than repaired automatically: finishing it means waiting for Rocket.Chat
199
+ * to serve and then running post_ready, which can take the full readiness timeout, and
200
+ * `serve`'s startup must not hold the GUI shut for that.
201
+ */
202
+ async function createUnderTheLock(req, name, emit, { streamOutput, monitorAttach, versionFetcher, }) {
203
+ return await (0, locks_1.reproLock)(name, async () => {
204
+ // WHAT THE NOTE HAS TO CARRY. `ready` is the command the note tells people to run, and
205
+ // it could not finish a seed because the request that asked for one died with the
206
+ // process -- `req.seed` lives in a CreateReq nobody can read any more.
207
+ const detail = {
208
+ seed: Boolean(req.seed),
209
+ seed_here: Boolean(req.seedHere),
210
+ seed_profile: String(req.seedProfile),
211
+ seed_stats: Boolean(req.stats),
212
+ seed_scenarios: req.seedScenarios,
213
+ seed_history_days: req.seedHistoryDays,
214
+ };
215
+ let note = (0, journal_1.record)(journal_1.CREATE_UNFINISHED, name, detail);
216
+ let out;
217
+ try {
218
+ out = await createReproLocked(req, emit, {
219
+ streamOutput,
220
+ monitorAttach,
221
+ ...(versionFetcher === undefined ? {} : { versionFetcher }),
222
+ });
223
+ }
224
+ catch (error) {
225
+ // A REFUSAL CREATED NOTHING, so it must leave nothing. Without this the note
226
+ // survived every kind of refusal -- a bad version, a taken port, a capacity
227
+ // preflight -- one per attempt, and `doctor` then warned about a workspace that
228
+ // does not exist while telling the reader to run `houston ready` on it.
229
+ (0, journal_1.clear)(note);
230
+ throw error;
231
+ }
232
+ // RE-KEYED TO THE WORKSPACE THAT EXISTS. The note is recorded under the name derived
233
+ // BEFORE `resolveAxes` ran, and `--deployment multi-instance` without a `--name` renames
234
+ // the workspace on the way (`rc8-5-1` becomes `rc8-5-1-multi-instance`). With `seedHere`
235
+ // the note is the CALLER's to close, by the name it is handed back -- so the one under
236
+ // the old name was never cleared, and `doctor` reported an unfinished create for a
237
+ // workspace that does not exist. Moved rather than dropped: until the caller's seed
238
+ // lands, a kill must still leave a note, for the right name. The previous
239
+ // implementation moves it the same way.
240
+ const created = isTruthy(out.name) ? String(out.name) : name;
241
+ if (req.seedHere && created !== name) {
242
+ (0, journal_1.clear)(note);
243
+ note = (0, journal_1.record)(journal_1.CREATE_UNFINISHED, created, detail);
244
+ }
245
+ clearTheUnfinishedNote(req, name, note);
246
+ return out;
247
+ });
248
+ }
249
+ /**
250
+ * Create-or-reuse a repro. Returns a result object (meta + boot/seed info).
251
+ *
252
+ * `streamOutput=true` streams docker's line output through `emit` (for the web job log);
253
+ * false leaves docker's own progress on the terminal (CLI default). Serialised per repro,
254
+ * like every other mutating operation.
255
+ */
256
+ async function createRepro(req, emit = events_1.nullEmit, { streamOutput = false, monitorAttach = request.missingMonitorAttach, versionFetcher, } = {}) {
257
+ // ONE SPELLING of a set, whichever front-end sent it: the GUI's `preset: "ldap+email"` and
258
+ // a restored manifest reach here as typed. Empty stays empty -- it means "as recorded".
259
+ if (req.preset !== '')
260
+ req.preset = (0, composite_1.compositeName)((0, composite_1.namesOf)(req.preset));
261
+ // A SEED PROFILE THAT DOES NOT EXIST, refused before anything is made. The planner refused
262
+ // it only after the whole workspace had been pulled, built and started -- exit 1 over a
263
+ // running workspace, for a typo.
264
+ if (req.seed && req.seedProfile !== '' && !Object.hasOwn(seed_profiles_1.PROFILES, req.seedProfile)) {
265
+ throw new errors_1.ValidationError(`unknown seed profile ${(0, format_1.quotedText)(req.seedProfile)} ` +
266
+ `(want ${Object.keys(seed_profiles_1.PROFILES).join(' | ')})`);
267
+ }
268
+ if (!req.seed && (req.seedScenarios.length > 0 || req.seedHistoryDays !== null))
269
+ throw new errors_1.ValidationError('seed scenarios and history days require --seed');
270
+ if (req.seed) {
271
+ const selection = (0, seed_options_1.seedSelection)(req.seedScenarios, req.seedHistoryDays);
272
+ req.seedScenarios = [...selection.scenarios];
273
+ req.seedHistoryDays = selection.historyDays;
274
+ }
275
+ // ONCE, HERE, before anything reads it. `runtime` is consulted at a dozen places
276
+ // downstream and inferring it at each would be a dozen chances to disagree; after this
277
+ // `req.runtime` means what the caller meant rather than only what they typed.
278
+ const typedRuntime = String(req.runtime).trim();
279
+ // Before the first `deriveFor`: a typed name that is an existing workspace this actor may
280
+ // act on means that workspace, not a new `<actor>-<name>` beside it.
281
+ await ownership.claimTypedName(req);
282
+ // A workspace brought back goes to its recorded cluster: carried before anything says
283
+ // where this is going, or that would name the box's default instead.
284
+ await carryRecordedAxes(req, naming.deriveFor(req));
285
+ req.runtime = request.inferRuntime(req);
286
+ request.sayWhereThisIsGoing(req, typedRuntime, emit);
287
+ // SAID, not dropped: these two mean nothing to Compose, and a Docker workspace came up
288
+ // without a word that the operator (or the ingress class) asked for was not there.
289
+ if (req.runtime !== topology.KUBERNETES) {
290
+ const ignored = [
291
+ req.mongoOperator ? '--mongo-operator' : '',
292
+ req.ingressClass !== '' ? '--ingress-class' : '',
293
+ ].filter((flag) => flag !== '');
294
+ if (ignored.length > 0) {
295
+ (0, events_1.warn)(emit, `${ignored.join(' and ')}: Kubernetes only, ignored on Docker`, {
296
+ phase: 'plan',
297
+ });
298
+ }
299
+ }
300
+ const name = naming.deriveFor(req);
301
+ if (!name) {
302
+ throw new errors_1.ValidationError(`name '${req.name}' contains no usable characters (want a-z, 0-9, '-')`);
303
+ }
304
+ // The workspace's public name, from the cluster's zone, once the name is known.
305
+ await request.defaultDomainFromZone(req, name, emit);
306
+ naming.requireValidName(name);
307
+ return await createUnderTheLock(req, name, emit, {
308
+ streamOutput,
309
+ monitorAttach,
310
+ ...(versionFetcher === undefined ? {} : { versionFetcher }),
311
+ });
312
+ }
313
+ /**
314
+ * The rest of what a reuse does not apply, each only when it was asked for and differs from the
315
+ * record, so re-running the command that made the workspace says nothing of these (the licence
316
+ * and registration token are never recorded, so `reuse` names them whenever given). All of these went
317
+ * unmentioned: `up --name existing --bind 0.0.0.0` (or --set, --root-url, --rc-image, --mongo,
318
+ * --https, --domain, --env) came back exactly as before and said it was fine (live 2026-10-30).
319
+ */
320
+ function ignoredSettings(req, meta, resolved, presetName, typed) {
321
+ const out = [];
322
+ const extra = bag(meta.extra);
323
+ const bound = String(extra.bind_host ?? '') || config.DEFAULT_BIND_HOST;
324
+ if (req.bind && req.bind !== bound)
325
+ out.push(`bind address ${req.bind} (existing: ${bound})`);
326
+ const advertised = String(extra.advertised_url ?? '') || meta.publicUrl || meta.rootUrl;
327
+ if (req.rootUrl && req.rootUrl.replace(/\/$/u, '') !== advertised.replace(/\/$/u, '')) {
328
+ out.push(`root URL ${req.rootUrl} (existing: ${advertised})`);
329
+ }
330
+ // As compose names them: the record keeps the repository, and the tag is the release.
331
+ if (req.rcImage && resolved !== null) {
332
+ const image = compose.imageRef(resolved.rcImage, resolved.rcVersion);
333
+ const running = compose.imageRef(meta.rcImage, meta.rcVersion);
334
+ if (image !== running)
335
+ out.push(`image ${image} (existing: ${running})`);
336
+ }
337
+ if (req.mongo && resolved !== null && resolved.mongoTag !== meta.mongoTag) {
338
+ out.push(`MongoDB ${resolved.mongoTag} (existing: ${meta.mongoTag})`);
339
+ }
340
+ if (req.domain) {
341
+ // As TLS reads it (`https://RC.Example.com/` is `rc.example.com`), which runs after this.
342
+ const asked = attempt(() => (0, tls_1.normalizeDomain)(req.domain)[0], req.domain.toLowerCase());
343
+ const host = attempt(() => new URL(meta.publicUrl).hostname, meta.publicUrl);
344
+ if (asked !== host)
345
+ out.push(`domain ${asked} (existing: ${host || 'none, plain HTTP'})`);
346
+ }
347
+ else if ((req.https || req.acmeEmail) && !meta.publicUrl) {
348
+ out.push('HTTPS (existing: plain HTTP)');
349
+ }
350
+ const instances = Number(extra.instances ?? 0);
351
+ // A typed `--set instances=N` is named with the other params below.
352
+ if (instances > 1 &&
353
+ req.replicas &&
354
+ req.replicas !== instances &&
355
+ !Object.hasOwn(typed, topology.LEGACY_REPLICA_PARAM)) {
356
+ out.push(`--replicas ${String(req.replicas)} (existing: ${String(instances)})`);
357
+ }
358
+ // Only what was typed: a host derived from the root URL, or the record's own params carried
359
+ // back, is not a request.
360
+ const preset = presetName || meta.preset;
361
+ const names = (0, composite_1.namesOf)(preset);
362
+ const [asked, kept] = names.length > 1
363
+ ? [
364
+ (0, composite_1.qualifiedParams)(request.paramsByPreset(names, typed)),
365
+ (0, composite_1.qualifiedParams)(bag(extra.preset_params)),
366
+ ]
367
+ : [request.unqualifiedParams(preset, typed), bag(extra.params)];
368
+ const params = Object.entries(asked)
369
+ .filter(([key, value]) => !Object.hasOwn(kept, key) || String(kept[key]) !== String(value))
370
+ .map(([key, value]) => `${key}=${(0, redact_1.redactEnv)(key, String(value))}`);
371
+ if (params.length > 0)
372
+ out.push(`--set ${params.join(' ')}`);
373
+ const env = bag(extra.env);
374
+ // Keys only: a value can be a secret.
375
+ const keys = Object.entries(req.env)
376
+ .filter(([key, value]) => !Object.hasOwn(env, key) || String(env[key]) !== String(value))
377
+ .map(([key]) => key);
378
+ if (keys.length > 0) {
379
+ out.push(`environment ${keys.join(', ')} (\`houston env --set\` changes it in place)`);
380
+ }
381
+ return out;
382
+ }
383
+ function attempt(read, fallback) {
384
+ try {
385
+ return read();
386
+ }
387
+ catch {
388
+ return fallback;
389
+ }
390
+ }
391
+ /** Reuse an existing workspace exactly as recorded, saying so when that ignores a flag. */
392
+ async function reuse(name, wait, req, emit, { streamOutput, resolved = null, presetName = '', typedParams = req.params, } = {
393
+ streamOutput: false,
394
+ }) {
395
+ const meta = await record.readMeta(name);
396
+ // An existing repro is reused EXACTLY as recorded. Say so when the request asked for
397
+ // something else: `up --version 9.9.9 --name existing` silently booted the old version,
398
+ // which is fatal for a tool whose whole premise is version matching.
399
+ const mismatch = [];
400
+ if (resolved !== null && resolved.rcVersion !== meta.rcVersion) {
401
+ mismatch.push(`version ${resolved.rcVersion} (existing: ${meta.rcVersion})`);
402
+ }
403
+ if (presetName && presetName !== meta.preset) {
404
+ mismatch.push(`preset '${presetName}' (existing: '${meta.preset}')`);
405
+ }
406
+ if (req.monitor && !isTruthy(meta.extra.monitoring)) {
407
+ mismatch.push('monitoring (existing: not attached)');
408
+ }
409
+ if (req.license !== '')
410
+ mismatch.push('the license');
411
+ if (req.port && req.port !== meta.hostPort) {
412
+ mismatch.push(`port ${String(req.port)} (existing: ${String(meta.hostPort)})`);
413
+ }
414
+ if (req.regToken !== '')
415
+ mismatch.push('the registration token');
416
+ mismatch.push(...ignoredSettings(req, meta, resolved, presetName, typedParams));
417
+ if (mismatch.length > 0) {
418
+ // A rebuild onto another preset removes what the old one kept -- an s3_minio workspace's
419
+ // uploads -- so that is said where --force is offered, not discovered after it.
420
+ const dropsData = presetName !== '' && presetName !== meta.preset && (meta.preset || 'default') !== 'default'
421
+ ? ` (a --force rebuild as '${presetName}' removes the data '${meta.preset}' kept)`
422
+ : '';
423
+ // A VERSION is not a --force: that skips the upgrade's backup and lets a downgrade
424
+ // through. `upgrade` backs up first and refuses one.
425
+ const newVersion = resolved !== null && resolved.rcVersion !== meta.rcVersion ? resolved.rcVersion : '';
426
+ const others = mismatch.length > (newVersion === '' ? 0 : 1);
427
+ const msg = `'${name}' already exists and is reused as-is, ignoring requested ` +
428
+ mismatch.join('; ') +
429
+ '.' +
430
+ (newVersion === ''
431
+ ? ''
432
+ : ` To move it to ${newVersion} and keep its data: houston upgrade --name ${name} ` +
433
+ `--to ${newVersion} (it backs up first, and refuses a downgrade); for a separate ` +
434
+ 'workspace on that version, use another --name.') +
435
+ (others ? ` Use --force to rebuild it${dropsData}.` : '') +
436
+ ' --fresh rebuilds it empty.';
437
+ (0, events_1.warn)(emit, msg, {
438
+ phase: 'create',
439
+ code: 'VERSION_IGNORED_ON_REUSE',
440
+ data: {
441
+ requested: resolved?.rcVersion ?? '',
442
+ running: meta.rcVersion,
443
+ ignored: mismatch,
444
+ },
445
+ });
446
+ // AND IN THE ENVELOPE. In prose this is loud; under `--json` it was an NDJSON progress
447
+ // event and the envelope still said `ok: true, warnings: []`.
448
+ }
449
+ // --pin IS APPLIED, NOT DROPPED. It was not even among the flags said to be ignored, so
450
+ // `up --pin` on an existing workspace answered `pinned: false` -- and the next `prune`
451
+ // deleted, data and all, the one workspace its owner had just asked to keep. As a
452
+ // create does, it also becomes the default.
453
+ if (req.pin) {
454
+ if (!isTruthy(meta.pinned)) {
455
+ await record.updateMeta(name, (m) => {
456
+ m.pinned = true;
457
+ });
458
+ meta.pinned = true;
459
+ (0, events_1.info)(emit, `'${name}' is pinned now — \`prune\` keeps it`, { phase: 'create' });
460
+ }
461
+ await (0, locks_1.updateConfig)((cfg) => {
462
+ cfg.default_repro = name;
463
+ });
464
+ }
465
+ const state = await (0, queries_1.rcState)(name);
466
+ if (state === 'running') {
467
+ (0, events_1.info)(emit, `'${name}' is already running.`, { phase: 'create' });
468
+ }
469
+ else {
470
+ (0, events_1.info)(emit, `'${name}' already exists - bringing it back up.`, { phase: 'create' });
471
+ if ((await (0, ready_1.upCompose)(name, { pull: false, emit, streamOutput })) !== 0) {
472
+ throw new errors_1.DockerError('`docker compose up` failed');
473
+ }
474
+ }
475
+ // A reused workspace gets its https name back. This path never resolved TLS -- it reuses
476
+ // the record as-is -- so after a `down`, `up` printed "URL https://…" from that record
477
+ // while the name served nothing at all: the route was removed by the teardown and never
478
+ // rewritten.
479
+ await (0, ready_1.restoreRoute)(meta, emit);
480
+ const result = await inspect.summary(meta);
481
+ result.reused = true;
482
+ result.waited = wait;
483
+ if (wait)
484
+ Object.assign(result, await (0, ready_1.waitAndFinalize)(meta, emit));
485
+ // NOT when the caller seeds. `seedHere` means the CLI runs it after this returns, so
486
+ // seeding here as well would seed the workspace twice -- the manifest only ever adds, so
487
+ // the readback would report rooms holding more than planned.
488
+ if (req.seed && !req.seedHere) {
489
+ result.seed = await seeding.runSeedInline(meta, req.seedProfile, req.stats, emit, {
490
+ scenarios: req.seedScenarios,
491
+ historyDays: req.seedHistoryDays,
492
+ });
493
+ }
494
+ return result;
495
+ }
496
+ /**
497
+ * An existing workspace's recorded deployment, instance count, cluster and MongoDB operator,
498
+ * for whichever of them this run left out, as the GUI's Start rebuilds it: an empty --deployment resolved to
499
+ * Kubernetes' default, so `up --name X` brought a monolith back as microservices, and an
500
+ * empty --context could send it to another cluster. Only on the runtime it was recorded on:
501
+ * the shape of one runtime means nothing on the other.
502
+ */
503
+ async function carryRecordedAxes(req, name) {
504
+ if (!name || !(await paths.exists(name)))
505
+ return;
506
+ let meta;
507
+ let was;
508
+ try {
509
+ meta = await record.readMeta(name);
510
+ was = topology.axesOfMeta(meta);
511
+ }
512
+ catch {
513
+ return; // a half-written record: nothing to keep
514
+ }
515
+ if (req.runtime && topology.normalize(req.runtime) !== was.runtime)
516
+ return;
517
+ if (!req.deployment) {
518
+ req.deployment = String(was.deployment ?? '');
519
+ // The count belongs to that shape; with a --deployment typed it is the user's to give, and
520
+ // so is a typed `--set instances=N` -- carried here, the record's count would beat it.
521
+ if (!req.replicas && req.params[topology.LEGACY_REPLICA_PARAM] === undefined) {
522
+ req.replicas = Number(was.replicas) || 0;
523
+ }
524
+ }
525
+ req.context || (req.context = String(was.context ?? ''));
526
+ req.mongoOperator || (req.mongoOperator = was.mongoOperator === true);
527
+ // Its monitoring too, as a Kubernetes re-up keeps it: `up --force` without --monitor
528
+ // dropped Prometheus and Grafana without a word. `houston monitor --off` drops them.
529
+ req.monitor || (req.monitor = isTruthy(meta.extra.monitoring));
530
+ // And the address Rocket.Chat advertises: `up --force` put ROOT_URL back to loopback under
531
+ // a proxied workspace, leaving Site_Url on the old name. Not from a workspace houston served
532
+ // over HTTPS (that URL is its TLS name), nor into a rebuild that asks for TLS -- which
533
+ // `--email` does too, on the name the record holds (`resolveTls`).
534
+ if (!req.rootUrl && !meta.publicUrl && !req.https && !req.domain && !req.acmeEmail) {
535
+ req.rootUrl = String(meta.extra.advertised_url ?? '');
536
+ }
537
+ }
538
+ /** Runtime x deployment x scenario, decided before anything else reads the request. */
539
+ async function resolveAxesStep(plan) {
540
+ // An existing workspace's RECORDED runtime beats the flag default. Without this,
541
+ // `houston up -v 8.5.1 --name X` on a Kubernetes workspace defaulted to docker and ran
542
+ // `docker compose up` against a workspace with no compose file.
543
+ //
544
+ // Read BEFORE resolveAxes: it normalises an empty --runtime to "docker", after which
545
+ // `!req.runtime` is never true and this could not fire.
546
+ const existing = naming.deriveFor(plan.req);
547
+ if (!plan.req.runtime && existing && (await paths.exists(existing))) {
548
+ plan.req.runtime = await topology.ofRepro(existing);
549
+ }
550
+ await carryRecordedAxes(plan.req, existing);
551
+ // No --preset at all: rebuild ITS presets (and their params, when no --set is given), not a
552
+ // vanilla one that silently drops them. On Kubernetes dropping it re-installed Rocket.Chat
553
+ // without the preset's settings while the preset's own objects stayed in the namespace; on
554
+ // Compose a one-preset workspace was rebuilt vanilla, and the preset's volumes -- MinIO's,
555
+ // holding every upload of an s3_minio workspace -- were then removed as left over. Only a
556
+ // preset ASKED FOR replaces the recorded one.
557
+ if (plan.req.preset === '' && existing && (await paths.exists(existing))) {
558
+ try {
559
+ const meta = await record.readMeta(existing);
560
+ const composed = (0, composite_1.namesOf)(meta.preset).length > 1;
561
+ const kept = (meta.preset || 'default') !== 'default';
562
+ if (kept) {
563
+ plan.req.preset = meta.preset;
564
+ if (Object.keys(plan.req.params).length === 0) {
565
+ plan.req.params = composed
566
+ ? (0, composite_1.qualifiedParams)(bag(meta.extra.preset_params))
567
+ : { ...bag(meta.extra.params) };
568
+ }
569
+ (0, events_1.info)(plan.emit, `'${existing}' is a ${meta.preset} workspace — keeping those presets`, {
570
+ phase: 'plan',
571
+ });
572
+ }
573
+ }
574
+ catch {
575
+ // a half-written record: nothing to keep
576
+ }
577
+ }
578
+ const axes = topology.resolveAxes({
579
+ runtime: plan.req.runtime,
580
+ deployment: plan.req.deployment,
581
+ replicas: plan.req.replicas,
582
+ preset: plan.req.preset,
583
+ params: plan.req.params,
584
+ });
585
+ topology.requireRegistered(axes.runtime);
586
+ for (const hint of axes.hints)
587
+ (0, events_1.info)(plan.emit, hint, { phase: 'plan' });
588
+ plan.req.preset = axes.preset;
589
+ plan.req.params = request.unqualifiedParams(axes.preset, axes.params);
590
+ plan.req.runtime = axes.runtime;
591
+ plan.req.deployment = axes.deployment;
592
+ plan.req.replicas = axes.replicas;
593
+ // ABOVE THE RUNTIME DISPATCH, deliberately: it started life below it, so `--root-url`
594
+ // derived an IdP host on Compose and derived nothing at all on Kubernetes. Both runtimes
595
+ // resolve the preset from `req.params`, so one call site above the fork covers both.
596
+ request.deriveIdpHost(plan.req, plan.emit);
597
+ }
598
+ /** Which Rocket.Chat and which MongoDB, and whether this engine can run the pair. */
599
+ async function resolvePairing(plan) {
600
+ await preconditions.requireDocker();
601
+ plan.cfg = config.loadConfig();
602
+ // HERE, where the release lookup has always gone online: after the engine preflight and
603
+ // the name checks, not ahead of them.
604
+ const fetcher = await request.releaseFetcher(plan.req.version, plan.req.offline, plan.versionFetcher);
605
+ try {
606
+ plan.resolved = (0, versions_1.resolve)(plan.req.version, {
607
+ offline: plan.req.offline,
608
+ ...(fetcher === undefined ? {} : { fetcher }),
609
+ });
610
+ }
611
+ catch (error) {
612
+ throw new errors_1.ValidationError((0, errors_1.errorText)(error));
613
+ }
614
+ // SAID BEFORE THE BUILD, not discovered after it. `resolve()` already knows when
615
+ // releases.rocket.chat answered 404 -- it stamps `source` -- and the create path ignored
616
+ // it, so `up --version 99.99.99` built the whole compose document, created containers and
617
+ // failed at the pull with docker's own "not found", ~90 seconds later.
618
+ if (plan.resolved.source === 'map (no such release)') {
619
+ (0, events_1.warn)(plan.emit, `releases.rocket.chat has no ${plan.req.version} — the pairing below ` +
620
+ 'comes from the shipped map, and the image pull will fail unless ' +
621
+ `this tag really exists (\`houston versions ${plan.req.version}\`).`, { phase: 'resolve' });
622
+ }
623
+ // The flag, then -- for a workspace rebuilt on the release it runs -- the image it was built
624
+ // from, as a Kubernetes re-up keeps it: `--force` swapped an `--rc-image` for the default
625
+ // repository's. Another release is another image, so that one is resolved afresh.
626
+ const name = naming.deriveFor(plan.req);
627
+ const before = name !== '' && (await paths.exists(name))
628
+ ? await record.readMeta(name).catch(() => null)
629
+ : null;
630
+ const kept = before !== null && before.rcVersion === plan.resolved.rcVersion ? before.rcImage : '';
631
+ request.chooseImage(plan.resolved, plan.req.rcImage || kept, plan.cfg.rc_image);
632
+ if (plan.req.mongo)
633
+ (0, versions_1.applyMongoOverride)(plan.resolved, plan.req.mongo);
634
+ // Before any docker work: this pairing cannot boot on this engine, and mongod says so by
635
+ // exiting with a message that reads like a permission fault. The rule is a leaf; this
636
+ // caller supplies the engine probe.
637
+ const conflict = (0, mongo_kernel_1.mongoKernelConflict)(plan.resolved.mongoTag, await (0, host_1.dockerKernelVersion)());
638
+ if (conflict)
639
+ throw new errors_1.PreflightError(conflict);
640
+ }
641
+ /**
642
+ * The preset, its parameters, and whether this create has to wait for readiness. `ports` is
643
+ * the workspace's side ports (`claimPorts` builds it again on the ones it was given); the
644
+ * default, every preferred port, is what the ports are allocated FROM.
645
+ */
646
+ function loadPreset(plan, ports = {}) {
647
+ const names = (0, composite_1.namesOf)(plan.req.preset);
648
+ if (names.length > 1) {
649
+ // Several presets: params routed to each, then one Preset merged from them. A key the
650
+ // user sets with --env/--setting is theirs to decide when two presets disagree on it.
651
+ const byPreset = request.paramsByPreset(names, plan.req.params);
652
+ plan.presetParams = byPreset;
653
+ plan.pre = presets.loadMany(names, byPreset, 'docker', new Set(Object.keys(plan.req.env)), ports);
654
+ (0, e2ee_1.refuseEnforcedBefore880)(plan.pre, plan.resolved?.rcVersion ?? '');
655
+ (0, voice_1.refuseVoiceBefore800)(plan.pre, plan.resolved?.rcVersion ?? '');
656
+ plan.wait = plan.req.wait || plan.pre.postReady.length > 0 || plan.req.seed;
657
+ return;
658
+ }
659
+ try {
660
+ plan.pre = presets.load(plan.req.preset, plan.req.params, ports);
661
+ }
662
+ catch (error) {
663
+ throw new errors_1.ValidationError(error instanceof Error ? error.message : String(error));
664
+ }
665
+ request.refuseUnknownParams(plan.req.params, plan.pre, plan.req.preset);
666
+ (0, e2ee_1.refuseEnforcedBefore880)(plan.pre, plan.resolved?.rcVersion ?? '');
667
+ (0, voice_1.refuseVoiceBefore800)(plan.pre, plan.resolved?.rcVersion ?? '');
668
+ plan.wait = plan.req.wait || plan.pre.postReady.length > 0 || plan.req.seed;
669
+ }
670
+ /** The workspace's name, and every refusal that depends on having one. */
671
+ async function settleName(plan) {
672
+ plan.reproName = naming.deriveFor(plan.req);
673
+ naming.warnNameCoerced(plan.req, plan.emit);
674
+ naming.announceName(plan.req, plan.reproName, plan.emit);
675
+ // Before any docker work, and only for a workspace that does not exist yet: `up` on an
676
+ // existing one reuses its containers and adds nothing.
677
+ // `--force` is NOT a reason to skip this. `checkCapacity` has its own force branch that
678
+ // warns loudly and proceeds -- written because "this is the guard that exists after an
679
+ // OOM took out a 10 GB host: overriding it has to stay visible". Excluding force HERE
680
+ // made that branch unreachable for a new workspace, so the loud override became a silent
681
+ // one: the function was never called at all.
682
+ if (!(await paths.exists(naming.deriveFor(plan.req)))) {
683
+ await sizing.checkCapacity(plan.req, plan.req.preset, plan.emit);
684
+ }
685
+ if (!plan.reproName) {
686
+ throw new errors_1.ValidationError(`name '${plan.req.name}' contains no usable characters (want a-z, 0-9, '-')`);
687
+ }
688
+ // sanitize() fixes the CHARACTERS but not the length, and the first thing below is a
689
+ // stat on the derived path -- which throws ENAMETOOLONG rather than returning false for
690
+ // an over-long name.
691
+ naming.requireValidName(plan.reproName);
692
+ if (plan.req.port && !(plan.req.port >= 1024 && plan.req.port <= 65535)) {
693
+ throw new errors_1.ValidationError(`--port ${String(plan.req.port)} is out of range (want 1024-65535)`);
694
+ }
695
+ }
696
+ /**
697
+ * Whether a workspace's recorded port is still its own to keep.
698
+ *
699
+ * `pickHostPort` skips the probe for a workspace's own recorded ports, which is right while
700
+ * its containers hold them; a stopped workspace's port taken by something else since went
701
+ * unnoticed until compose failed to bind it. So: free, or held by its own running Rocket.Chat.
702
+ * ponytail: the front door only, a multi-instance replica port taken alone still fails at bind.
703
+ */
704
+ async function stillOwnPort(name, port) {
705
+ if (await portSeam.portFree(port))
706
+ return true;
707
+ return ['running', 'restarting'].includes(await (0, queries_1.rcState)(name));
708
+ }
709
+ /**
710
+ * The side and monitoring ports, then the host port, the URL houston will call itself by, and
711
+ * the TLS plan.
712
+ */
713
+ async function claimPorts(plan) {
714
+ await preconditions.guardProjectCollision(plan.reproName);
715
+ // Preferred first; a port another workspace holds is given the next free one, and the record
716
+ // keeps what this got. A rebuild keeps its own while its containers still hold them.
717
+ const span = plan.pre.instances > 1 ? plan.pre.instances + 1 : 1;
718
+ const claim = await ports.claimSidePorts(plan.reproName, plan.pre, (given) => {
719
+ loadPreset(plan, given);
720
+ return plan.pre;
721
+ }, {
722
+ monitoring: plan.req.monitor ? ['prometheus', 'grafana'] : [],
723
+ reserve: plan.req.port
724
+ ? Array.from({ length: span }, (_, offset) => plan.req.port + offset)
725
+ : [],
726
+ // Free, or published by one of its own running containers. Rocket.Chat's state alone is not
727
+ // enough: after a failed boot it is `created` while its own Mailpit still holds 8025.
728
+ stillHeld: async (port) => (await portSeam.portFree(port)) || (await engine.publishedPorts(plan.reproName)).has(port),
729
+ });
730
+ plan.pre = claim.pre;
731
+ plan.sidePorts = claim.side;
732
+ plan.monitorPorts = claim.monitoring;
733
+ for (const [whose, was, now] of claim.moved) {
734
+ (0, events_1.warn)(plan.emit, `${whose}'s port ${String(was)} is no longer free, so '${plan.reproName}' publishes it ` +
735
+ `on ${String(now)}`, { phase: 'plan' });
736
+ }
737
+ const pre = claim.pre;
738
+ const allocation = { ...pre, ports: [...pre.ports, ...plan.monitorPorts] };
739
+ // A rebuild keeps its recorded port, as a Kubernetes re-up does: allocating afresh moved
740
+ // it to the lowest free one (3301 to 3000), and every link to it went dead. Only while
741
+ // nothing else has taken that port; then it gets a new one, as before.
742
+ const was = plan.req.port
743
+ ? 0
744
+ : await record.readMeta(plan.reproName).then((meta) => Number(meta.hostPort) || 0, () => 0);
745
+ const recorded = was !== 0 && (await stillOwnPort(plan.reproName, was)) ? was : 0;
746
+ plan.hostPort = await ports
747
+ .pickHostPort(plan.req.port || recorded, allocation, plan.reproName)
748
+ .catch(async (error) => {
749
+ if (recorded === 0 || !(error instanceof errors_1.ConflictError))
750
+ throw error;
751
+ return await ports.pickHostPort(0, allocation, plan.reproName);
752
+ });
753
+ // Said, not only shown in the new URL: every link to the old port stops working.
754
+ if (was !== 0 && plan.hostPort !== was) {
755
+ (0, events_1.warn)(plan.emit, `port ${String(was)} is no longer free, so '${plan.reproName}' moves to ` +
756
+ `${String(plan.hostPort)}`, { phase: 'plan' });
757
+ }
758
+ // ALWAYS the published local port, never an override. `--root-url` says what Rocket.Chat
759
+ // should ADVERTISE, and it still does that through the compose spec below -- but `root`
760
+ // is what houston calls itself, and Metadata's own docstring makes that a contract.
761
+ //
762
+ // Letting the override through broke that contract, and readiness is where it showed:
763
+ // `ready` polls meta.rootUrl, so a workspace whose root_url held a public https name
764
+ // reported "Rocket.Chat did not become ready within 300s" while /api/info on the local
765
+ // port answered 200 the whole time.
766
+ plan.bindHost = request.requestedBindHost(plan.req);
767
+ // ...on the address the port is published on, which is loopback unless one other
768
+ // address was asked for (`request.callHost`).
769
+ plan.root = `http://${request.callHost(plan.bindHost)}:${String(plan.hostPort)}`;
770
+ plan.token = plan.req.regToken || (0, format_1.toText)(plan.cfg.reg_token);
771
+ plan.tlsspec = await tlsplan.resolveTls(plan.req, plan.reproName, plan.bindHost, plan.reproName, plan.emit);
772
+ // After the TLS decision, which the record can make too, and before
773
+ // anything is written: `resolveTls` only reads, and certificates are issued later.
774
+ await refuseNamesTheEdgeCannotReach(plan);
775
+ }
776
+ /**
777
+ * Refuse, before any certificate or container, a name the HTTPS edge could not reach.
778
+ *
779
+ * The edge routes to CONTAINER names (`backendContainer`), and a name is a DNS label: 63
780
+ * characters at most. A longer one does not resolve, so its route answers 502 while the
781
+ * workspace looks healthy. A GUI workspace with five presets was named so: Mailpit and
782
+ * Keycloak answered under their paths, phpLDAPadmin and the demo page answered Bad
783
+ * Gateway. Rocket.Chat itself goes the same way past a 42-character name.
784
+ */
785
+ async function refuseNamesTheEdgeCannotReach(plan) {
786
+ if (plan.tlsspec === null)
787
+ return;
788
+ const pre = plan.pre;
789
+ const routed = [
790
+ ...compose.rcServiceNames(pre.instances),
791
+ ...(plan.req.monitor ? ['grafana'] : []),
792
+ ...(0, public_1.publicPathsOf)((0, public_1.withPublicUrl)(pre, 'https://name.invalid', topology.DOCKER).extra).map((p) => p.service),
793
+ ];
794
+ for (const service of routed) {
795
+ const container = await (0, networks_1.backendContainer)(plan.reproName, service);
796
+ if (container.length <= DNS_LABEL_MAX)
797
+ continue;
798
+ const max = plan.reproName.length - (container.length - DNS_LABEL_MAX);
799
+ throw new errors_1.ValidationError(`'${plan.reproName}' is too long to serve over HTTPS: the edge reaches ${service} as ` +
800
+ `${container}, ${String(container.length)} characters, and a DNS name holds ` +
801
+ `${String(DNS_LABEL_MAX)}. Give it a shorter name: ` +
802
+ `${naming.typedRoom(plan.req, plan.reproName, max)}.`);
803
+ }
804
+ }
805
+ /** The longest label a DNS name, and so a container the edge resolves, may have. */
806
+ const DNS_LABEL_MAX = 63;
807
+ /** What publishing this workspace off loopback exposes, said once, at create time. */
808
+ function warnAboutTheBind(plan) {
809
+ if (plan.req.bindPublic && plan.bindHost !== '0.0.0.0' && plan.bindHost !== '::') {
810
+ // Derived from the challenge (see resolveTls), not requested.
811
+ plan.bindHost = '0.0.0.0';
812
+ (0, events_1.warn)(plan.emit, `binding 0.0.0.0 so Let's Encrypt can reach this host for the ` +
813
+ `${plan.req.acmeChallenge} challenge - that exposes the workspace, and ` +
814
+ 'it runs the fixed admin/admin123 credentials. `houston down` when ' +
815
+ 'you are finished.', { phase: 'tls' });
816
+ }
817
+ else if (!types_1.LOOPBACK_BINDS.includes(plan.bindHost)) {
818
+ // THE SAME EXPOSURE, ASKED FOR RATHER THAN DERIVED, AND IT WAS SILENT. The warning
819
+ // above fires only when houston widened the bind ITSELF for an ACME challenge; `up
820
+ // --bind 0.0.0.0` typed by hand got the normal panel and nothing else.
821
+ const side = plan.req.preset in types_1.PRESET_LINKS ? plan.req.preset : '';
822
+ const sideText = side ? `${side}:${String((0, common_1.presetPort)(side, 0, plan.sidePorts))}` : '';
823
+ // WHAT THE PANEL DOES NOT ALREADY SAY, and nothing else. The Rocket.Chat admin is
824
+ // generated for a workspace bound this wide and printed two lines below, so repeating
825
+ // it here is a sentence people learn to scroll past.
826
+ const weak = [];
827
+ if (sideText)
828
+ weak.push(`the ${plan.req.preset} UI on ${sideText}`);
829
+ if (plan.req.monitor)
830
+ weak.push('Grafana on admin/admin');
831
+ if (plan.req.seed)
832
+ weak.push('seeded users, whose password is their username');
833
+ // The voice preset's PBX lab, alone or composed: read from what the create builds.
834
+ if (plan.pre?.services.pbx !== undefined) {
835
+ weak.push("the PBX lab's softphone accounts, whose password is their number, and FreeSWITCH's " +
836
+ 'external SIP port 5080, which asks none');
837
+ }
838
+ (0, events_1.warn)(plan.emit, `--bind ${plan.bindHost} publishes this workspace ` +
839
+ (request.bindsEverywhere(plan.bindHost)
840
+ ? 'on every interface'
841
+ : `to everyone who can reach ${plan.bindHost}`) +
842
+ (weak.length > 0 ? ` — and ${weak.join(', ')}` : '') +
843
+ '. Only do this on a trusted network.', { phase: 'create' });
844
+ }
845
+ else {
846
+ // A PRESET'S OWN OPENING, on a loopback bind: voice publishes its call ports on every
847
+ // address once voip_domain names one, so phones and browsers elsewhere reach them. Said as
848
+ // a wide bind is, since nothing else at create said those ports left this machine.
849
+ const opened = Object.values(plan.pre?.services ?? {})
850
+ .flatMap((svc) => (Array.isArray(svc.ports) ? svc.ports.map(String) : []))
851
+ .filter((port) => port.startsWith('0.0.0.0:'))
852
+ .map((port) => {
853
+ const rest = port.slice('0.0.0.0:'.length);
854
+ const proto = rest.includes('/') ? rest.slice(rest.lastIndexOf('/')) : '';
855
+ return `${rest.split(':')[0] ?? ''}${proto}`;
856
+ });
857
+ if (opened.length > 0) {
858
+ (0, events_1.warn)(plan.emit, `voip_domain opens the call ports ${opened.join(', ')} on every interface` +
859
+ (plan.pre?.services.pbx !== undefined
860
+ ? " — and the PBX lab's softphone accounts, whose password is their number"
861
+ : '') +
862
+ `. Rocket.Chat itself stays on ${plan.bindHost}. Only do this on a trusted network.`, { phase: 'create' });
863
+ }
864
+ }
865
+ // RC advertises the https URL (links, OAuth callbacks, CORS all derive from ROOT_URL);
866
+ // `root` stays http so houston's own API calls need no CA.
867
+ }
868
+ /**
869
+ * On Podman, a hosts line the notes ask for reaches the workspace's own containers too.
870
+ *
871
+ * Podman copies this machine's /etc/hosts into every container, so following houston's own
872
+ * advice -- `127.0.0.1 minio`, `127.0.0.1 keycloak` -- made `minio-init` and Rocket.Chat
873
+ * resolve those names to their OWN loopback: the bucket was never created and every upload
874
+ * failed `ECONNREFUSED 127.0.0.1:9000`. Docker gives containers their own DNS and is not
875
+ * affected. Said where the advice is given, with the way round that needs no hosts line.
876
+ */
877
+ async function warnAboutHostsOnPodman(plan) {
878
+ const asks = plan.pre.notes.some((line) => line.includes('/etc/hosts'));
879
+ if (!asks || (await (0, host_1.engine)())?.kind !== 'podman')
880
+ return;
881
+ (0, events_1.warn)(plan.emit, "Podman copies this machine's /etc/hosts into every container, so the hosts line the " +
882
+ "notes ask for would make the workspace's own services resolve those names to " +
883
+ 'themselves (a bucket never created, an IdP Rocket.Chat cannot reach). On Podman add ' +
884
+ "no hosts line: give the browser this host's address instead, with " +
885
+ '`--set idp_host=<address>` or `--set s3_host=<address>`.', { phase: 'create' });
886
+ }
887
+ /** An IdP preset whose own service still names the BROWSER's machine, not this one. */
888
+ function warnAboutTheBrowserHost(plan) {
889
+ plan.public = plan.tlsspec === null ? '' : (0, tls_1.rootUrl)(plan.tlsspec);
890
+ // SAID AT CREATE TIME, because it cannot be discovered afterwards. The IdP presets send
891
+ // the BROWSER to a hostname baked into Rocket.Chat's settings, and the default names
892
+ // this machine -- `localhost:8081` for SAML, `keycloak:8085` for OIDC. From anywhere
893
+ // else both of those addresses are the visitor's own laptop: the SAML button bounces
894
+ // off nothing and returns to the login page, and the OIDC popup opens a name that does
895
+ // not resolve and renders blank.
896
+ // EACH MEMBER of a set: looked up by the combined name (`email+saml`), this never fired
897
+ // for a combination, while `doctor` (which reads the members) did.
898
+ //
899
+ // NOT OVER HTTPS: there the browser reaches Keycloak at <name>/keycloak/ and Rocket.Chat
900
+ // proxies downloads (`withPublicUrl`), so neither address below is the browser's to
901
+ // follow; presigned links over HTTPS have a warning of their own.
902
+ if (plan.tlsspec !== null)
903
+ return;
904
+ const names = (0, composite_1.namesOf)(plan.req.preset);
905
+ const presigned = plan.pre?.env.OVERWRITE_SETTING_FileUpload_S3_Proxy_Uploads === 'false';
906
+ for (const name of names) {
907
+ const browserParam = types_1.BROWSER_HOST_PARAM[name];
908
+ if (browserParam === undefined)
909
+ continue;
910
+ // MinIO only in presigned mode: in the default proxy mode the browser never reaches it.
911
+ if (name === 's3_minio' && !presigned)
912
+ continue;
913
+ const key = names.length > 1 ? `${name}.${browserParam}` : browserParam;
914
+ if (isTruthy(plan.req.params[key]) || isTruthy(plan.req.params[browserParam]))
915
+ continue;
916
+ warnAboutOneBrowserHost(plan, name, key);
917
+ }
918
+ }
919
+ /** The warning for one IdP-style member whose service still names the browser's machine. */
920
+ function warnAboutOneBrowserHost(plan, preset, key) {
921
+ const defaultHost = {
922
+ saml: 'localhost',
923
+ oidc: 'keycloak',
924
+ s3_minio: 'minio',
925
+ };
926
+ const servicePort = (0, common_1.presetPort)(preset, 0, plan.sidePorts);
927
+ const advertised = plan.req.rootUrl || plan.req.domain;
928
+ let why = '';
929
+ if (!types_1.LOOPBACK_BINDS.includes(plan.bindHost)) {
930
+ why =
931
+ `this '${preset}' workspace is bound to ${plan.bindHost}, so ` +
932
+ 'somebody will open it from another machine';
933
+ }
934
+ else if (advertised) {
935
+ // DELIBERATELY NOT DERIVED. Pointing the service at {advertised} while its port is on
936
+ // loopback would break Rocket.Chat's own access to it as well -- measured: a container
937
+ // cannot reach a 127.0.0.1-published port by the host's address.
938
+ why =
939
+ `this '${preset}' workspace advertises ${advertised}, but its ` +
940
+ `ports are published on ${plan.bindHost || config.DEFAULT_BIND_HOST} ` +
941
+ 'where nothing off this box can reach them';
942
+ }
943
+ if (why) {
944
+ (0, events_1.warn)(plan.emit, `${why} — and its own service still points the browser at ` +
945
+ `${defaultHost[preset] ?? ''}:${String(servicePort)}, which names that browser's OWN ` +
946
+ 'machine. SAML returns to the login page, OIDC opens a blank ' +
947
+ 'window, presigned previews fail. None of them logs an error.', { phase: 'create' });
948
+ (0, events_1.warn)(plan.emit, ' Both halves have to move. Re-create with:\n' +
949
+ ` --bind 0.0.0.0 --port ${String(plan.hostPort)} ` +
950
+ `--root-url http://<host>:${String(plan.hostPort)} ` +
951
+ `--set ${key}=<host>\n` +
952
+ ' where <host> is the name people actually type.', { phase: 'create' });
953
+ }
954
+ }
955
+ /** Carried-forward env, the admin password, and the compose document itself. */
956
+ async function buildDocument(plan) {
957
+ // Overrides already on this repro are carried forward: `up --force` rebuilds the compose
958
+ // file from the spec, so without this a rebuild would silently drop env the user had
959
+ // set. Anything named on THIS run wins.
960
+ plan.envOverrides = {};
961
+ plan.previousMeta = null;
962
+ if (await paths.exists(plan.reproName)) {
963
+ try {
964
+ plan.previousMeta = await record.readMeta(plan.reproName);
965
+ const prev = bag(plan.previousMeta.extra.env);
966
+ plan.envOverrides = { ...prev };
967
+ }
968
+ catch {
969
+ // half-written record; nothing to carry
970
+ }
971
+ }
972
+ Object.assign(plan.envOverrides, plan.req.env);
973
+ // THE ADMIN PASSWORD, decided here because this is where both halves of "reachable from
974
+ // off this box" are finally known. Generated for a public workspace and left empty --
975
+ // meaning the shared `admin123` -- for a loopback one. A rebuild that keeps the data keeps
976
+ // the password its database holds; `--fresh` empties the database, so it gets a new one.
977
+ const kept = plan.req.fresh ? null : await record.keptAdminPassword(plan.reproName);
978
+ const reachable = preconditions.reachableBeyondLoopback({
979
+ tlsspec: plan.tlsspec,
980
+ bindHost: plan.bindHost,
981
+ });
982
+ plan.adminPassword = kept ?? (reachable ? config.generateAdminPassword() : '');
983
+ const shared = request.keptSharedPasswordWarning(plan.reproName, kept, reachable);
984
+ if (shared !== '')
985
+ (0, events_1.warn)(plan.emit, shared, { phase: 'create' });
986
+ const resolved = plan.resolved;
987
+ // A directory served over LDAPS or StartTLS gets houston's certificate here, before the
988
+ // document that mounts it is built.
989
+ if (plan.pre.extra.directory_tls !== undefined) {
990
+ plan.pre = (0, ldap_1.withCertificate)(plan.pre, await tlsplan.issueDirectoryCertificate((0, ldap_1.directoryHost)(plan.pre.extra)), topology.DOCKER);
991
+ }
992
+ // Over HTTPS a preset's own UIs (Mailpit, Keycloak, the demo page) are served at paths of
993
+ // the workspace's name, as Grafana is; the edge routes them (`registerTheName`).
994
+ if (plan.tlsspec !== null) {
995
+ plan.pre = (0, public_1.withPublicUrl)(plan.pre, (0, tls_1.rootUrl)(plan.tlsspec), topology.DOCKER);
996
+ const presigned = (0, public_1.presignedOverHttps)(plan.pre);
997
+ if (presigned)
998
+ (0, events_1.warn)(plan.emit, presigned, { phase: 'tls' });
999
+ }
1000
+ plan.spec = compose.spec({
1001
+ projectName: await record.projectName(plan.reproName),
1002
+ rcImage: resolved.rcImage,
1003
+ rcTag: resolved.rcVersion,
1004
+ mongoTag: resolved.mongoTag,
1005
+ mongoFlavor: resolved.mongoFlavor,
1006
+ mongoShell: resolved.mongoShell,
1007
+ oplog: resolved.oplog,
1008
+ rootUrl: plan.req.rootUrl || plan.public || plan.root,
1009
+ publicUrl: plan.public,
1010
+ hostPort: plan.hostPort,
1011
+ regToken: plan.token || null,
1012
+ // This run's licence, or the one an earlier `up --license` left: `up --force` keeps it.
1013
+ licensed: plan.req.license !== '' ||
1014
+ (await fs.stat((0, home_1.joinPath)(paths.workspace(plan.reproName), compose.LICENSE_ENV_FILE)).then(() => true, () => false)),
1015
+ preset: plan.pre,
1016
+ bindHost: plan.bindHost,
1017
+ monitoring: plan.req.monitor,
1018
+ monitorPorts: plan.monitorPorts,
1019
+ envOverrides: plan.envOverrides,
1020
+ });
1021
+ plan.spec.adminPassword = plan.adminPassword;
1022
+ const premium = request.premiumAuthWarning([plan.pre.name], resolved.rcVersion, plan.spec.licensed, plan.token);
1023
+ if (premium !== '')
1024
+ (0, events_1.warn)(plan.emit, premium, { phase: 'create' });
1025
+ const voice = request.voiceLicenceWarning([plan.pre.name], plan.spec.licensed, plan.token);
1026
+ if (voice !== '')
1027
+ (0, events_1.warn)(plan.emit, voice, { phase: 'create' });
1028
+ const samlEmail = request.samlEmailWarning(plan.pre, resolved.rcVersion, new Set(Object.keys(plan.envOverrides)));
1029
+ if (samlEmail !== '')
1030
+ (0, events_1.warn)(plan.emit, samlEmail, { phase: 'create' });
1031
+ try {
1032
+ plan.doc = compose.build(plan.spec);
1033
+ }
1034
+ catch (error) {
1035
+ // e.g. a preset naming an entry_service it doesn't define.
1036
+ throw new errors_1.ValidationError(error instanceof Error ? error.message : String(error));
1037
+ }
1038
+ }
1039
+ /** `repro.json`: everything a later command needs that the compose file does not say. */
1040
+ function buildRecord(plan) {
1041
+ const resolved = plan.resolved;
1042
+ const pre = plan.pre;
1043
+ const spec = plan.spec;
1044
+ plan.meta = record.metadata({
1045
+ name: plan.reproName,
1046
+ project: spec.projectName,
1047
+ rcVersion: resolved.rcVersion,
1048
+ rcImage: resolved.rcImage,
1049
+ mongoTag: resolved.mongoTag,
1050
+ mongoFlavor: resolved.mongoFlavor,
1051
+ preset: pre.name,
1052
+ rootUrl: plan.root,
1053
+ hostPort: plan.hostPort,
1054
+ versionSource: resolved.source,
1055
+ // A rebuilt workspace stays pinned, as on Kubernetes: `--force` unpinned it, and the
1056
+ // next `prune` would have deleted it.
1057
+ pinned: plan.req.pin || isTruthy(plan.previousMeta?.pinned),
1058
+ publicUrl: plan.public,
1059
+ adminPassword: plan.adminPassword,
1060
+ // Kept by a `--force` rebuild, which keeps the data; `--fresh` starts it again.
1061
+ createdAt: (!plan.req.fresh && plan.previousMeta?.createdAt) ||
1062
+ new Date().toISOString().slice(0, 19) + '+00:00',
1063
+ });
1064
+ // Stamped on every create, compose included, so "absent" keeps meaning exactly one
1065
+ // thing: a workspace older than the key.
1066
+ topology.stamp(plan.meta.extra, plan.req.runtime || topology.DOCKER);
1067
+ plan.meta.extra[config.EXTRA_DEPLOYMENT] = plan.req.deployment || topology.MONOLITH;
1068
+ // Recorded so a reader can be told the truth about reaching this workspace from another
1069
+ // machine. It was only ever written INTO the compose port mappings.
1070
+ plan.meta.extra.bind_host = plan.bindHost;
1071
+ // WHAT ROCKET.CHAT ADVERTISES, when that is not what houston calls it. `rootUrl` on the
1072
+ // record is deliberately the plain loopback URL that houston's own API calls use, and
1073
+ // `publicUrl` is set only by TLS -- so `--root-url http://box:3007` was written into the
1074
+ // compose ROOT_URL and recorded nowhere, and anything generated FOR THE BROWSER then got
1075
+ // loopback.
1076
+ if (spec.rootUrl && spec.rootUrl !== plan.root) {
1077
+ plan.meta.extra.advertised_url = spec.rootUrl;
1078
+ }
1079
+ if (pre.postReady.length > 0)
1080
+ plan.meta.extra.post_ready = pre.postReady;
1081
+ if (pre.notes.length > 0)
1082
+ plan.meta.extra.notes = pre.notes;
1083
+ if (pre.instances > 1)
1084
+ plan.meta.extra.instances = pre.instances;
1085
+ if (Object.keys(pre.extra).length > 0)
1086
+ Object.assign(plan.meta.extra, pre.extra);
1087
+ if (pre.ports.length > 0)
1088
+ plan.meta.extra.sidecar_ports = pre.ports;
1089
+ // Only what moved: a workspace on the preferred ports reads as every earlier one does.
1090
+ if (Object.keys(plan.sidePorts).length > 0)
1091
+ plan.meta.extra.side_ports = plan.sidePorts;
1092
+ if (Object.keys(plan.envOverrides).length > 0)
1093
+ plan.meta.extra.env = plan.envOverrides;
1094
+ if (spec.licensed)
1095
+ plan.meta.extra.licensed = true;
1096
+ if (plan.req.actor) {
1097
+ // Who owns this. Shown by `list` and the GUI card.
1098
+ plan.meta.extra.created_by = plan.req.actor;
1099
+ }
1100
+ if (plan.presetParams !== null) {
1101
+ // A composed workspace: `preset` stays ONE string (`email+ldap`), which earlier releases
1102
+ // refuse loudly as a preset name rather than silently building one of the presets; the
1103
+ // list and each preset's params ride in `extra`, which every release keeps.
1104
+ plan.meta.extra.presets = (0, composite_1.namesOf)(pre.name);
1105
+ plan.meta.extra.preset_params = structuredClone(plan.presetParams);
1106
+ }
1107
+ else if (Object.keys(plan.req.params).length > 0) {
1108
+ // Recorded so a repro can be rebuilt exactly: `backup` copies these into its manifest,
1109
+ // and `restore --new` would otherwise recreate an s3_minio repro with the DEFAULT
1110
+ // bucket rather than the one whose data it is loading.
1111
+ plan.meta.extra.params = { ...plan.req.params };
1112
+ }
1113
+ ownership.carryOwnership(plan.previousMeta, plan.meta);
1114
+ }
1115
+ /** Prometheus and Grafana, when asked for. */
1116
+ function attachMonitoring(plan) {
1117
+ if (!plan.req.monitor)
1118
+ return;
1119
+ const meta = plan.meta;
1120
+ const targets = compose.rcServiceNames(plan.pre.instances);
1121
+ plan.files.push(...(0, monitoring_1.files)(targets, plan.spec.projectName));
1122
+ meta.extra.monitoring = true;
1123
+ meta.extra.monitoring_ports = [...plan.monitorPorts];
1124
+ const notes = Array.isArray(meta.extra.notes) ? [...meta.extra.notes] : [];
1125
+ meta.extra.notes = [
1126
+ ...notes,
1127
+ ...(0, monitoring_1.notes)((0, monitoring_1.grafanaUrl)(plan.public, !!plan.public, record.grafanaPortOf(meta)), record.prometheusPortOf(meta)),
1128
+ ];
1129
+ }
1130
+ /** Where each MongoDB image family keeps its data inside the shared `mongodb_data` volume. */
1131
+ const MONGO_DATA_DIR = {
1132
+ 'bitnami-legacy': '/bitnami/mongodb',
1133
+ official: '/data/db',
1134
+ };
1135
+ /**
1136
+ * A rebuild that would change the MongoDB image FAMILY under the same volume. Bitnami keeps
1137
+ * its data in /bitnami/mongodb and the official image in /data/db, so the new mongod finds an
1138
+ * empty directory and Rocket.Chat boots on a blank database. The data is still in the volume,
1139
+ * where nothing reads it. Refused unless `--fresh` says an empty database is what is wanted.
1140
+ */
1141
+ async function refuseMongoFamilyChange(plan) {
1142
+ if (plan.req.fresh || !(await paths.exists(plan.reproName)))
1143
+ return;
1144
+ let meta;
1145
+ try {
1146
+ meta = await record.readMeta(plan.reproName);
1147
+ }
1148
+ catch {
1149
+ return; // half-written record: no data to protect
1150
+ }
1151
+ if (topology.ofMeta(meta) !== topology.DOCKER || meta.mongoTag === '')
1152
+ return;
1153
+ const was = meta.mongoFlavor || (0, versions_1.flavor)(meta.mongoTag);
1154
+ const resolved = plan.resolved;
1155
+ if (was === resolved.mongoFlavor)
1156
+ return;
1157
+ const name = plan.reproName;
1158
+ throw new errors_1.ConflictError(`'${name}' keeps its data in MongoDB ${meta.mongoTag} (${was}, ` +
1159
+ `${MONGO_DATA_DIR[was] ?? was}); this rebuild would start MongoDB ${resolved.mongoTag} ` +
1160
+ `(${resolved.mongoFlavor}, ${MONGO_DATA_DIR[resolved.mongoFlavor] ?? resolved.mongoFlavor}) ` +
1161
+ 'on the same volume, which finds no data there, so Rocket.Chat would boot on an empty ' +
1162
+ `database. To carry the data across: houston backup --name ${name}, then ` +
1163
+ `houston up --version ${resolved.rcVersion} --name ${name}-new, then houston restore ` +
1164
+ `<bundle> --name ${name}-new --allow-upgrade. Or add --fresh to rebuild it empty.`);
1165
+ }
1166
+ /** Taking down what is already there, and the gate on destroying its data. */
1167
+ async function replaceExisting(plan) {
1168
+ if (!(await paths.exists(plan.reproName)))
1169
+ return;
1170
+ // `--fresh` DELETES THE DATA VOLUME, which is the same irreversible act `down --volumes`
1171
+ // is gated on -- and this branch consulted nobody. Checked only for `--fresh`: a plain
1172
+ // overwrite recreates containers and leaves the volume alone.
1173
+ if (plan.req.fresh) {
1174
+ const [allowed, why] = await ownership.mayDestroy(plan.reproName, (0, audit_1.actor)());
1175
+ if (!allowed) {
1176
+ (0, audit_1.record)('up-fresh', plan.reproName, { outcome: 'denied' });
1177
+ throw new errors_1.ConflictError(why);
1178
+ }
1179
+ // And when it goes ahead: only the refusals were recorded, so a wiped database had no
1180
+ // trace of who wiped it.
1181
+ (0, audit_1.record)('up-fresh', plan.reproName);
1182
+ }
1183
+ // Volumes the OLD compose file declared but the new one doesn't (switching preset with
1184
+ // --force, dropping --monitor) would be orphaned: `down -v` only removes what the file
1185
+ // declares, so once it's rewritten nothing can ever reach them again.
1186
+ let stale = [];
1187
+ if (!plan.req.fresh) {
1188
+ try {
1189
+ const oldDoc = await record.readCompose(plan.reproName);
1190
+ const oldVolumes = new Set(Object.keys(bag(oldDoc.volumes)));
1191
+ const newVolumes = new Set(Object.keys(plan.doc.volumes));
1192
+ stale = [...oldVolumes].filter((name) => !newVolumes.has(name));
1193
+ }
1194
+ catch {
1195
+ // unreadable old file: nothing to reconcile
1196
+ stale = [];
1197
+ }
1198
+ }
1199
+ if ((await engine.down(plan.reproName, { volumes: plan.req.fresh })) !== 0) {
1200
+ throw new errors_1.DockerError(`could not tear down the existing '${plan.reproName}'; not overwriting it`);
1201
+ }
1202
+ if (stale.length > 0) {
1203
+ // SAID AND RECORDED: these hold the data of a preset this rebuild was asked to drop.
1204
+ (0, events_1.warn)(plan.emit, `removing ${stale.sort().join(', ')}: the data of what '${plan.reproName}' no longer ` +
1205
+ 'has, which nothing could reach once its compose file is rewritten', { phase: 'create' });
1206
+ (0, audit_1.record)('volumes-removed', plan.reproName);
1207
+ }
1208
+ for (const bad of await (0, queries_1.removeVolumes)(plan.reproName, stale.sort())) {
1209
+ (0, events_1.warn)(plan.emit, `could not remove ${bad}, left over from the previous preset`, {
1210
+ phase: 'create',
1211
+ });
1212
+ }
1213
+ }
1214
+ /**
1215
+ * This run's licence into the workspace's env file, which the compose document names and never
1216
+ * holds. 0600 from the first byte, in the 0700 workspace; a dotfile, so `backup` leaves it out.
1217
+ */
1218
+ async function writeLicense(plan) {
1219
+ if (plan.req.license === '')
1220
+ return;
1221
+ const file = (0, home_1.joinPath)(paths.workspace(plan.reproName), compose.LICENSE_ENV_FILE);
1222
+ await fs.writeFile(file, `ROCKETCHAT_LICENSE=${plan.req.license}\n`, { mode: 0o600 });
1223
+ await fs.chmod(file, 0o600);
1224
+ }
1225
+ /** Publish the full allocation and generated files while the port lock is held. */
1226
+ async function writeTheWorkspace(plan) {
1227
+ const meta = plan.meta;
1228
+ await record.write(plan.reproName, compose.toYaml(compose.forEngine(plan.doc, await (0, host_1.engine)())), meta, plan.files, new Set(plan.pre.keepFiles ?? []));
1229
+ await writeLicense(plan);
1230
+ }
1231
+ /** Bring up a published workspace, then attach the edge. */
1232
+ async function startTheWorkspace(plan, { recordWritten = false } = {}) {
1233
+ const resolved = plan.resolved;
1234
+ if (!recordWritten)
1235
+ await writeTheWorkspace(plan);
1236
+ if (plan.req.pin) {
1237
+ await (0, locks_1.updateConfig)((cfg) => {
1238
+ cfg.default_repro = plan.reproName;
1239
+ });
1240
+ }
1241
+ (0, events_1.info)(plan.emit, `creating '${plan.reproName}' - RC ${resolved.rcVersion}, ` +
1242
+ `Mongo ${resolved.mongoTag} (${resolved.mongoFlavor}), ` +
1243
+ `preset ${(0, composite_1.presetsLabel)(plan.pre.name)}`,
1244
+ // Nested, as it always has been: the event's detail is ONE key named `data`, so it is
1245
+ // `{"data": {"name": ...}}` on the NDJSON stream and in houston.log. `jsonout` calls
1246
+ // removing a key breaking, so the wire keeps the established shape.
1247
+ { phase: 'create', data: { data: { name: plan.reproName } } });
1248
+ const rc = await (0, ready_1.upCompose)(plan.reproName, {
1249
+ pull: !plan.req.noPull,
1250
+ emit: plan.emit,
1251
+ streamOutput: plan.streamOutput,
1252
+ });
1253
+ if (rc !== 0) {
1254
+ const cause = await (0, diagnose_1.diagnoseFailure)(plan.reproName);
1255
+ const head = cause ? `\`docker compose up\` failed - ${cause}` : '`docker compose up` failed.';
1256
+ throw new errors_1.DockerError(`${head} Workspace kept for inspection - retry with --force, or discard: ` +
1257
+ `houston down --name ${plan.reproName} --volumes`);
1258
+ }
1259
+ // AFTER the workspace is up, because attaching needs the network `docker compose up` has
1260
+ // only just created. Registering during the build wrote a correct route to a backend the
1261
+ // edge could not resolve, so the name answered 502 -- and 502 is not an error anyone
1262
+ // sees, it just looks like a broken workspace. Idempotent: register() attaches too.
1263
+ if (plan.tlsspec !== null) {
1264
+ await (0, networks_1.attach)(plan.reproName);
1265
+ }
1266
+ }
1267
+ /** The summary the caller gets back, plus waiting and seeding when asked. */
1268
+ async function finish(plan) {
1269
+ const meta = plan.meta;
1270
+ const result = await inspect.summary(meta);
1271
+ result.reused = false;
1272
+ result.waited = plan.wait;
1273
+ if (plan.wait)
1274
+ Object.assign(result, await (0, ready_1.waitAndFinalize)(meta, plan.emit));
1275
+ // NOT when the caller seeds, for the reason `reuse` records.
1276
+ if (plan.req.seed && !plan.req.seedHere) {
1277
+ result.seed = await seeding.runSeedInline(meta, plan.req.seedProfile, plan.req.stats, plan.emit, { scenarios: plan.req.seedScenarios, historyDays: plan.req.seedHistoryDays });
1278
+ }
1279
+ return result;
1280
+ }
1281
+ /** An edge belonging to another HOUSTON_HOME, refused before anything is written. */
1282
+ async function refuseAForeignEdge() {
1283
+ // REFUSED BEFORE ANYTHING IS WRITTEN. `edge.up()` checks `foreignEdge()` -- an edge
1284
+ // belonging to a DIFFERENT HOUSTON_HOME, which compose would silently replace because
1285
+ // every home keys the project by the same name -- and it did so only after the local CA,
1286
+ // the certificate, the route file and the whole edge project had been written.
1287
+ const stolen = await (0, engine_1.foreignEdge)();
1288
+ if (stolen) {
1289
+ const home = stolen.replace(/\/edge\/?$/u, '');
1290
+ throw new errors_1.ConflictError(`the shared edge on this machine belongs to another houston home (${home}), usually ` +
1291
+ 'houston run with sudo or as another user. Starting one from here would REPLACE it ' +
1292
+ 'and take down every https name it serves, because compose keys the project by name ' +
1293
+ `and both homes use the same one. Run this the same way (or with HOUSTON_HOME=${home}), ` +
1294
+ 'or stop that edge first.');
1295
+ }
1296
+ }
1297
+ /** A local certificate, or the private directory Traefik needs before it mounts it. */
1298
+ async function issueCertificate(plan, local) {
1299
+ const tlsspec = plan.tlsspec;
1300
+ if (tlsspec === null)
1301
+ return;
1302
+ if (local) {
1303
+ (0, events_1.info)(plan.emit, `issuing a local certificate for ${tlsspec.host}`, { phase: 'tls' });
1304
+ await (0, acme_1.issueLocalCert)(tlsspec.host);
1305
+ }
1306
+ else {
1307
+ // Traefik writes acme.json here; it must exist and be private BEFORE the container
1308
+ // mounts it, or Traefik refuses to use it.
1309
+ await fs.mkdir((0, tls_1.acmeDir)(), { recursive: true });
1310
+ await fs.chmod((0, tls_1.acmeDir)(), 0o700);
1311
+ }
1312
+ }
1313
+ /** Started lazily, by the first workspace that needs a name -- never at install or by `serve`. */
1314
+ async function startTheEdge(plan, local) {
1315
+ const tlsspec = plan.tlsspec;
1316
+ if (tlsspec === null)
1317
+ return;
1318
+ // Started HERE, not in resolveTls. Lazily, by the first workspace that needs a name --
1319
+ // not at install, not by `serve`, since whether the GUI has a public hostname is an
1320
+ // unrelated question. It has to happen where docker work legitimately happens, though:
1321
+ // putting it in resolveTls made a resolve function start containers, and the TEST SUITE
1322
+ // then started a real edge that held :443 and broke a live run. A running edge whose
1323
+ // challenge `acme.challenge` has since changed goes through it too: skipped here, the
1324
+ // change never reached the container (measured behind a tunnel: TLS-ALPN kept).
1325
+ if (!(await (0, engine_1.running)()) || (!local && (!(0, acme_1.hasAcme)() || (0, runtime_1.challengeStale)()))) {
1326
+ (0, events_1.info)(plan.emit, 'starting the edge (one Traefik, :80 and :443 for every name)', {
1327
+ phase: 'tls',
1328
+ });
1329
+ const started = await (0, runtime_1.ensureRunning)({
1330
+ acmeEmail: local ? '' : tlsspec.acmeEmail,
1331
+ acmeStaging: tlsspec.acmeStaging,
1332
+ });
1333
+ if (!started.ok) {
1334
+ const holder = await (0, engine_1.portHolder)(443);
1335
+ const because = holder
1336
+ ? ` — ${holder} is holding :443`
1337
+ : started.why
1338
+ ? ` — ${started.why}`
1339
+ : '';
1340
+ (0, events_1.warn)(plan.emit, `the edge did not start${because}, so ${tlsspec.host} will ` +
1341
+ 'not answer yet. The workspace itself is unaffected; free ' +
1342
+ 'the port and `houston edge start`.', { phase: 'tls' });
1343
+ }
1344
+ }
1345
+ }
1346
+ /** The route, and the certificate request it may or may not imply. */
1347
+ async function registerTheName(plan, local) {
1348
+ const tlsspec = plan.tlsspec;
1349
+ if (tlsspec === null)
1350
+ return;
1351
+ const needsCert = await (0, routes_1.register)(plan.reproName, tlsspec.host, {
1352
+ instances: plan.pre.instances || 1,
1353
+ local,
1354
+ grafana: plan.req.monitor,
1355
+ publicPaths: (0, public_1.publicPathsOf)(plan.pre.extra),
1356
+ });
1357
+ if (local) {
1358
+ // nothing further: the certificate was issued above
1359
+ }
1360
+ else if (needsCert) {
1361
+ // No reachability checks. Whether the domain resolves here, and how traffic gets to
1362
+ // this host, is the operator's business -- houston cannot see a tunnel, a
1363
+ // port-forward or a firewall from in here.
1364
+ (0, events_1.info)(plan.emit, `requesting a certificate from Let's Encrypt ` +
1365
+ `(${tlsspec.acmeStaging ? 'staging' : 'production'}) ` +
1366
+ `for ${tlsspec.host}, which must resolve to the machine running houston — the edge ` +
1367
+ 'does this in the background; ' +
1368
+ `confirm with \`houston tls-status -n ${plan.reproName}\``, { phase: 'tls' });
1369
+ // Counted BEFORE the warning, so the name being created is included -- the useful
1370
+ // number is "after this one", not "before it".
1371
+ (0, tls_1.recordIssuance)(tlsspec.host);
1372
+ const budget = (0, tls_1.budgetWarning)(tlsspec.host);
1373
+ if (budget)
1374
+ (0, events_1.warn)(plan.emit, budget, { phase: 'tls' });
1375
+ }
1376
+ else {
1377
+ (0, events_1.info)(plan.emit,
1378
+ // The wildcard is a CERTIFICATE; it was read as a DNS record, which it is not.
1379
+ `registering ${tlsspec.host} — the edge's wildcard certificate covers it, no ` +
1380
+ 'certificate request; the name must still resolve to the machine running houston ' +
1381
+ '(one wildcard DNS record covers every such name)', {
1382
+ phase: 'tls',
1383
+ });
1384
+ }
1385
+ }
1386
+ /** What the record has to say so `tls-status` and the panel can tell the truth. */
1387
+ function recordTls(plan, local) {
1388
+ const tlsspec = plan.tlsspec;
1389
+ const meta = plan.meta;
1390
+ if (tlsspec === null || meta === null)
1391
+ return;
1392
+ meta.extra.tls = tlsspec.mode;
1393
+ meta.extra.edge = true;
1394
+ // Deliberately NO tls_ports: usedPorts() feeds port allocation, and claiming a port this
1395
+ // workspace does not publish would make every later workspace route around one it never
1396
+ // held.
1397
+ if (!local) {
1398
+ meta.extra.tls_staging = tlsspec.acmeStaging;
1399
+ meta.extra.tls_email = tlsspec.acmeEmail;
1400
+ }
1401
+ const notes = Array.isArray(meta.extra.notes) ? [...meta.extra.notes] : [];
1402
+ meta.extra.notes = [
1403
+ ...notes,
1404
+ `served by the edge at https://${tlsspec.host}`,
1405
+ 'the edge holds :443 for the whole box; this workspace publishes none',
1406
+ ];
1407
+ }
1408
+ /** The shared Traefik edge: refuse a foreign one, get a certificate, route the name. */
1409
+ async function prepareEdge(plan) {
1410
+ plan.files = [...plan.pre.files];
1411
+ if (plan.tlsspec === null)
1412
+ return;
1413
+ // ONE path, whether the name is a real domain or a .houston.localhost one. The only
1414
+ // difference is where the certificate comes from, and that is the edge's business -- so
1415
+ // no tls/ files are written here, no port is claimed, and nothing about this workspace's
1416
+ // containers depends on it.
1417
+ const local = plan.tlsspec.mode === tls_1.MODE_LOCAL;
1418
+ await refuseAForeignEdge();
1419
+ await issueCertificate(plan, local);
1420
+ await startTheEdge(plan, local);
1421
+ await registerTheName(plan, local);
1422
+ recordTls(plan, local);
1423
+ }
1424
+ /**
1425
+ * A name is one workspace, on one runtime. 8.5.1 on Docker and then 8.5.1 on Kubernetes
1426
+ * derived the same name, and each runtime took the other's workspace for its own to bring
1427
+ * back: Kubernetes rewrote the Docker record and left its containers running with nothing
1428
+ * pointing at them, and Docker ran `compose up` on a workspace with no compose file.
1429
+ * Refused before anything is written, `--force` included. A record that cannot be read is
1430
+ * left to the existence checks downstream, as it always was.
1431
+ */
1432
+ async function refuseTheOtherRuntime(req) {
1433
+ const name = naming.deriveFor(req);
1434
+ if (!name || !(await paths.exists(name)))
1435
+ return;
1436
+ let was;
1437
+ try {
1438
+ was = topology.ofMeta(await record.readMeta(name));
1439
+ }
1440
+ catch {
1441
+ return;
1442
+ }
1443
+ if (was === req.runtime)
1444
+ return;
1445
+ throw new errors_1.ConflictError(`'${name}' is already a ${topology.label(was)} workspace. A ${topology.label(req.runtime)} ` +
1446
+ 'one needs its own name (Name in the dialog, or --name), or delete this one first: ' +
1447
+ `\`houston down --name ${name} --volumes\`.`);
1448
+ }
1449
+ /**
1450
+ * The Compose create, as a plan and the steps that fill it in.
1451
+ *
1452
+ * The ORDER below is the specification. Each step's own docstring and comments say why it
1453
+ * sits where it does; several of them record a defect caused by sitting somewhere else.
1454
+ */
1455
+ async function createReproLocked(req, emit = events_1.nullEmit, { streamOutput = false, monitorAttach = request.missingMonitorAttach, versionFetcher, } = {}) {
1456
+ const plan = createPlan({
1457
+ req,
1458
+ emit,
1459
+ streamOutput,
1460
+ monitorAttach,
1461
+ ...(versionFetcher === undefined ? {} : { versionFetcher }),
1462
+ });
1463
+ // Before anything, on either runtime: the format check is also what keeps the licence to
1464
+ // one line of the env file it is written to.
1465
+ if (req.license !== '')
1466
+ req.license = request.requireLicense(req.license);
1467
+ await resolveAxesStep(plan);
1468
+ // THE NAME RESOLVING SETTLED ON is the one locked and asked about. `--deployment
1469
+ // multi-instance` and a kept set of presets rename a derived name after the caller locked
1470
+ // it, so the create held one name, asked who owned it, and built another: a member rebuilt
1471
+ // a workspace handed to somebody else, and nothing kept a `down` or a second create off it.
1472
+ // Re-entrant, so the name the caller already holds costs nothing.
1473
+ return await (0, locks_1.reproLock)(naming.deriveFor(req), async () => await createSettled(plan));
1474
+ }
1475
+ /** The create, once its name is settled and held. */
1476
+ async function createSettled(plan) {
1477
+ const { req, emit } = plan;
1478
+ // AGAIN UNDER THE LOCK, on either runtime: `claimTypedName` looked before it, and a
1479
+ // hand-over while this request waited would have it rebuild somebody else's workspace.
1480
+ // Whatever name it derives, not only an exact one: a member's own prefix (`bob-x`) is
1481
+ // somebody else's once it is handed over, and a create there starts, pins or rebuilds it.
1482
+ // A name nothing holds yet has no owner, so a new workspace always passes.
1483
+ const [allowed, why] = await ownership.mayDestroy(naming.deriveFor(req), (0, audit_1.actor)());
1484
+ if (!allowed)
1485
+ throw new errors_1.ConflictError(why);
1486
+ if (req.bringBack && !(await paths.exists(naming.deriveFor(req)))) {
1487
+ throw new errors_1.NotFoundError(`'${naming.deriveFor(req)}' was deleted while this waited its turn, so there is nothing ` +
1488
+ 'to bring up - create it again instead');
1489
+ }
1490
+ await refuseTheOtherRuntime(req);
1491
+ if (req.runtime === topology.KUBERNETES) {
1492
+ // A PARALLEL path, not a branch woven through this function. Everything below is
1493
+ // compose-shaped -- host ports, a compose document, `docker compose up` -- and two
1494
+ // front-ends depend on it behaving exactly as it does. Handing Kubernetes off here
1495
+ // keeps the Docker default byte-identical and puts the Kubernetes sequence in the
1496
+ // module that owns it.
1497
+ //
1498
+ // TLS is refused rather than ignored. `resolveTls` runs BELOW this line, so `--https`
1499
+ // on a Kubernetes workspace did nothing at all and said nothing about it.
1500
+ preconditions.refuseUnsupportedOnKubernetes(req);
1501
+ return await (0, create_k8s_1.createKubernetes)(req, emit, {
1502
+ monitorAttach: plan.monitorAttach,
1503
+ ...(plan.versionFetcher === undefined ? {} : { versionFetcher: plan.versionFetcher }),
1504
+ });
1505
+ }
1506
+ await resolvePairing(plan);
1507
+ loadPreset(plan);
1508
+ await settleName(plan);
1509
+ if ((await paths.exists(plan.reproName)) && !plan.req.force && !plan.req.fresh) {
1510
+ return await reuse(plan.reproName, plan.wait, plan.req, plan.emit, {
1511
+ streamOutput: plan.streamOutput,
1512
+ resolved: plan.resolved,
1513
+ presetName: plan.pre.name,
1514
+ typedParams: plan.typedParams,
1515
+ });
1516
+ }
1517
+ await refuseMongoFamilyChange(plan);
1518
+ await ports.withPortPublication(async () => {
1519
+ await claimPorts(plan);
1520
+ warnAboutTheBind(plan);
1521
+ warnAboutTheBrowserHost(plan);
1522
+ await buildDocument(plan);
1523
+ await warnAboutHostsOnPodman(plan);
1524
+ await preconditions.refuseHealthWaitsTheEngineCannotRun(plan.doc, plan.req.force, plan.emit);
1525
+ buildRecord(plan);
1526
+ await prepareEdge(plan);
1527
+ attachMonitoring(plan);
1528
+ await replaceExisting(plan);
1529
+ await writeTheWorkspace(plan);
1530
+ });
1531
+ await startTheWorkspace(plan, { recordWritten: true });
1532
+ return await finish(plan);
1533
+ }