@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,1639 @@
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.DROP_EVERY_COLLECTION = exports.Quiesced = exports.NOFILE_MIN = exports.databaseOf = exports.DEFAULT_DATABASE = exports.PROBE_TIMEOUT = exports.DUMP_TIMEOUT = exports.MONGO_SERVICE = exports.FILES_DIR = exports.RECORD = exports.COMPOSE = exports.ARCHIVE = exports.MANIFEST = exports.SUFFIX = exports.SCHEMA = void 0;
37
+ exports.repairStopped = repairStopped;
38
+ exports.installJournalRepairs = installJournalRepairs;
39
+ exports.backupsDir = backupsDir;
40
+ exports.utcStamp = utcStamp;
41
+ exports.sha256File = sha256File;
42
+ exports.kube = kube;
43
+ exports.mongoAuth = mongoAuth;
44
+ exports.requireMongoTools = requireMongoTools;
45
+ exports.warnLowFdLimit = warnLowFdLimit;
46
+ exports.rcServicesOf = rcServicesOf;
47
+ exports.stopWriters = stopWriters;
48
+ exports.create = create;
49
+ exports.expandUser = expandUser;
50
+ exports.createLocked = createLocked;
51
+ exports.ourVersion = ourVersion;
52
+ exports.sidecarVolumes = sidecarVolumes;
53
+ exports.copyPresetFiles = copyPresetFiles;
54
+ exports.serialiseManifest = serialiseManifest;
55
+ exports.human = human;
56
+ exports.bundlePath = bundlePath;
57
+ exports.readManifest = readManifest;
58
+ exports.listBackups = listBackups;
59
+ exports.requireMayDestroy = requireMayDestroy;
60
+ exports.restoreNew = restoreNew;
61
+ exports.restore = restore;
62
+ exports.bundleOwner = bundleOwner;
63
+ exports.dropDatabase = dropDatabase;
64
+ exports.deriveNewName = deriveNewName;
65
+ exports.createFromManifest = createFromManifest;
66
+ exports.unpackArchive = unpackArchive;
67
+ exports.restoreArchive = restoreArchive;
68
+ exports.loadFromBundle = loadFromBundle;
69
+ exports.restoreLocked = restoreLocked;
70
+ exports.deleteBackup = deleteBackup;
71
+ exports.retargetSiteUrl = retargetSiteUrl;
72
+ /**
73
+ * Back up and restore a repro's Rocket.Chat database — shared by CLI and web API.
74
+ *
75
+ * Built on `mongodump --archive` / `mongorestore --archive`, the procedure the official docs
76
+ * describe for Docker deployments, with three deliberate changes:
77
+ *
78
+ * --drop the docs omit it, so a restore MERGES into the existing collections and
79
+ * leaves a hybrid of two databases that looks fine and behaves wrongly.
80
+ * --db scopes the dump to Rocket.Chat's own database, so `admin`/`local` never
81
+ * travel and the target's replica-set configuration is left alone.
82
+ * --gzip a seeded repro's dump is large; roughly a 10x saving for one flag.
83
+ *
84
+ * Rocket.Chat is also STOPPED for the duration of both operations. `mongodump` is
85
+ * not point-in-time consistent across collections, so a dump taken while RC writes
86
+ * can capture a half-finished state; and dropping collections under a live writer
87
+ * is what --drop exists to prevent. Mongo itself keeps running throughout.
88
+ *
89
+ * A backup is a BUNDLE, not a bare dump. Restoring an 8.5 database into a 6.x
90
+ * workspace fails in ways that are hard to trace, so the manifest travels with the
91
+ * archive and `restore` refuses or warns before touching anything.
92
+ */
93
+ const node_crypto_1 = require("node:crypto");
94
+ const fs = __importStar(require("node:fs"));
95
+ const path = __importStar(require("node:path"));
96
+ const config = __importStar(require("../lib/config"));
97
+ const errors_1 = require("../lib/errors");
98
+ const events_1 = require("../lib/events");
99
+ const home_1 = require("../lib/home");
100
+ const jsonout_1 = require("../lib/jsonout");
101
+ const format_1 = require("../lib/format");
102
+ const json_text_1 = require("../lib/json-text");
103
+ const mkdir_parents_1 = require("../lib/mkdir-parents");
104
+ const tempdir_1 = require("../lib/tempdir");
105
+ const versions_1 = require("../lib/versions");
106
+ const composite_1 = require("../lib/presets/composite");
107
+ const exec_1 = require("../seams/exec");
108
+ const targz_1 = require("../lib/targz");
109
+ const audit = __importStar(require("./audit"));
110
+ const backup_compat_1 = require("./backup-compat");
111
+ const journal = __importStar(require("./journal"));
112
+ const names_1 = require("./kube/names");
113
+ const admin_1 = require("./lifecycle/admin");
114
+ const create_docker_1 = require("./lifecycle/create-docker");
115
+ const naming_1 = require("./lifecycle/naming");
116
+ const ownership_1 = require("./lifecycle/ownership");
117
+ const preconditions_1 = require("./lifecycle/preconditions");
118
+ const ready_1 = require("./lifecycle/ready");
119
+ const types_1 = require("./lifecycle/types");
120
+ const rcapi_1 = require("./rcapi");
121
+ const engine_1 = require("./runner/engine");
122
+ const paths_1 = require("./runner/paths");
123
+ const database_of_1 = require("./database-of");
124
+ const paths_2 = require("./runner/paths");
125
+ const record_1 = require("./runner/record");
126
+ const queries_1 = require("./runner/queries");
127
+ const topology = __importStar(require("./topology"));
128
+ /** Bundle layout. `schema` is checked on read. */
129
+ exports.SCHEMA = 1;
130
+ exports.SUFFIX = '.rcbak';
131
+ exports.MANIFEST = 'manifest.json';
132
+ exports.ARCHIVE = 'mongo.archive.gz';
133
+ exports.COMPOSE = 'compose.yml';
134
+ exports.RECORD = 'repro.json';
135
+ exports.FILES_DIR = 'files';
136
+ exports.MONGO_SERVICE = 'mongodb';
137
+ exports.DUMP_TIMEOUT = 3600.0;
138
+ exports.PROBE_TIMEOUT = 30.0;
139
+ function bagOf(value) {
140
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
141
+ return {};
142
+ return value;
143
+ }
144
+ /** Stop Rocket.Chat dead; the note is what a killed process leaves behind. */
145
+ async function repairStopped(entry, _emit, _login) {
146
+ const context = String(entry.detail.context ?? '');
147
+ if (context !== '') {
148
+ const { restoreRocketchatReplicas, scaleRocketchat } = await Promise.resolve().then(() => __importStar(require('./kube/scale')));
149
+ if (entry.detail.deployment_replicas !== undefined) {
150
+ const counts = entry.detail.deployment_replicas;
151
+ if (counts === null || typeof counts !== 'object' || Array.isArray(counts))
152
+ return false;
153
+ return ((await restoreRocketchatReplicas(entry.workspace, counts, {
154
+ context,
155
+ })) === 0);
156
+ }
157
+ // Older notes carry one count. Missing/falsy legacy values still mean one, but zero
158
+ // is a real stopped state rather than permission to start a writer.
159
+ const recorded = entry.detail.replicas;
160
+ const replicas = recorded === 0 ? 0 : (0, format_1.isTruthy)(recorded) ? (0, format_1.toInt)(recorded) : 1;
161
+ return ((await scaleRocketchat(entry.workspace, {
162
+ replicas,
163
+ context,
164
+ selector: names_1.MONOLITH_SELECTOR,
165
+ })) === 0);
166
+ }
167
+ const services = entry.detail.services;
168
+ if (!Array.isArray(services) ||
169
+ services.some((service) => typeof service !== 'string' || service.trim() === '')) {
170
+ return false;
171
+ }
172
+ return (services.length === 0 || (await (0, engine_1.startServices)(entry.workspace, services)) === 0);
173
+ }
174
+ function installJournalRepairs() {
175
+ journal.registerRepair(journal.ROCKETCHAT_STOPPED, repairStopped);
176
+ }
177
+ function backupsDir() {
178
+ // `config.home() / "backups"`, and every workspace path below joined the same way:
179
+ // `path.join` folded a `..` in the home that the kernel resolves through a symlink, so a
180
+ // backup went into a directory `backups` never lists.
181
+ const dir = (0, home_1.joinPath)(config.home(), 'backups');
182
+ // Made with its parents, the mode 0700 on the leaf only.
183
+ (0, mkdir_parents_1.mkdirParents)(dir, 0o700);
184
+ return dir;
185
+ }
186
+ /** The current UTC time as `YYYYMMDD-HHMMSS`. */
187
+ function utcStamp(now = new Date()) {
188
+ const pad = (value) => String(value).padStart(2, '0');
189
+ return (`${String(now.getUTCFullYear())}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}` +
190
+ `-${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`);
191
+ }
192
+ function sha256File(file) {
193
+ const hash = (0, node_crypto_1.createHash)('sha256');
194
+ const handle = fs.openSync(file, 'r');
195
+ try {
196
+ const buffer = Buffer.alloc(1024 * 1024);
197
+ for (;;) {
198
+ const read = fs.readSync(handle, buffer, 0, buffer.length, null);
199
+ if (read <= 0)
200
+ break;
201
+ hash.update(buffer.subarray(0, read));
202
+ }
203
+ }
204
+ finally {
205
+ fs.closeSync(handle);
206
+ }
207
+ return hash.digest('hex');
208
+ }
209
+ /**
210
+ * The database this workspace uses, hoisted to `core/database-of.ts` so `mongoprof`
211
+ * and `scaleseed` can reach it without an upward edge. Re-exported here so it stays
212
+ * reachable as `backup.databaseOf`.
213
+ */
214
+ var database_of_2 = require("./database-of");
215
+ Object.defineProperty(exports, "DEFAULT_DATABASE", { enumerable: true, get: function () { return database_of_2.DEFAULT_DATABASE; } });
216
+ Object.defineProperty(exports, "databaseOf", { enumerable: true, get: function () { return database_of_2.databaseOf; } });
217
+ /**
218
+ * The kube context for a Kubernetes workspace, or '' if it is a Compose one.
219
+ *
220
+ * One question asked in one place. backup's LOGIC -- the bundle format, the manifest,
221
+ * the safety checks -- is runtime-agnostic and stays shared; only the five places that
222
+ * actually touch a container differ, and each consults this.
223
+ */
224
+ async function kube(name) {
225
+ if ((await topology.ofRepro(name)) !== topology.KUBERNETES)
226
+ return '';
227
+ const meta = await (0, record_1.readMeta)(name);
228
+ const extra = bagOf(meta.extra);
229
+ const { CONTEXT } = await Promise.resolve().then(() => __importStar(require('./kube/names')));
230
+ return String((0, format_1.isTruthy)(extra[config.EXTRA_CONTEXT]) ? extra[config.EXTRA_CONTEXT] : CONTEXT);
231
+ }
232
+ /**
233
+ * A timeout in SECONDS, as the constants here state it, for a compose seam that takes
234
+ * MILLISECONDS. `PROBE_TIMEOUT` (30.0) and `DUMP_TIMEOUT` (3600.0) reached
235
+ * `composeExecCapture` / `composeExecToFile` / `composeExecFromFile` unconverted, so the tools
236
+ * probe, the `ulimit -n` probe and the drop were killed after 30 ms and every mongodump and
237
+ * mongorestore after 3.6 s: on a real engine every compose backup, restore, rollback and
238
+ * pre-upgrade backup was refused, and a rollback had already rewritten the workspace to the old
239
+ * version when it was. Converted here, at the call into the seam, so the constants keep
240
+ * their established names and values; the Kubernetes branch converts in `kube/transfer.ts`.
241
+ */
242
+ function composeTimeoutMs(timeout) {
243
+ return timeout === undefined ? undefined : timeout * 1000;
244
+ }
245
+ // `input` goes on stdin ahead of anything else, and only on Kubernetes: it carries the
246
+ // operator's password (`mongoAuth`), and a Compose MongoDB has none.
247
+ async function execCapture(name, argv, timeout, input = '') {
248
+ const context = await kube(name);
249
+ if (context !== '') {
250
+ const { execCapture: kubeExecCapture } = await Promise.resolve().then(() => __importStar(require('./kube/transfer')));
251
+ return await kubeExecCapture(name, argv, {
252
+ context,
253
+ input,
254
+ ...(timeout !== undefined ? { timeout } : {}),
255
+ });
256
+ }
257
+ return await (0, engine_1.composeExecCapture)(name, exports.MONGO_SERVICE, argv, composeTimeoutMs(timeout));
258
+ }
259
+ async function execToFile(name, argv, dest, timeout, input = '') {
260
+ const context = await kube(name);
261
+ if (context !== '') {
262
+ const { execToFile: kubeExecToFile } = await Promise.resolve().then(() => __importStar(require('./kube/transfer')));
263
+ return await kubeExecToFile(name, argv, dest, {
264
+ context,
265
+ input,
266
+ ...(timeout !== undefined ? { timeout } : {}),
267
+ });
268
+ }
269
+ return await (0, engine_1.composeExecToFile)(name, exports.MONGO_SERVICE, argv, dest, composeTimeoutMs(timeout));
270
+ }
271
+ async function execFromFile(name, argv, src, timeout, input = '') {
272
+ const context = await kube(name);
273
+ if (context !== '') {
274
+ const { execFromFile: kubeExecFromFile } = await Promise.resolve().then(() => __importStar(require('./kube/transfer')));
275
+ return await kubeExecFromFile(name, argv, src, {
276
+ context,
277
+ input,
278
+ ...(timeout !== undefined ? { timeout } : {}),
279
+ });
280
+ }
281
+ return await (0, engine_1.composeExecFromFile)(name, exports.MONGO_SERVICE, argv, src, composeTimeoutMs(timeout));
282
+ }
283
+ /**
284
+ * The database tools' password, '' unless the operator manages this MongoDB.
285
+ *
286
+ * The hand-written StatefulSet runs without authentication, so both paths existed and
287
+ * only one was exercised until an audit ran the operator too.
288
+ */
289
+ async function mongoAuth(name) {
290
+ const context = await kube(name);
291
+ if (context === '')
292
+ return '';
293
+ const meta = await (0, record_1.readMeta)(name);
294
+ if (bagOf(meta.extra).mongo_managed_by !== 'operator')
295
+ return '';
296
+ const { mongoToolAuth } = await Promise.resolve().then(() => __importStar(require('./kube/operator')));
297
+ return await mongoToolAuth(name, { context });
298
+ }
299
+ /** A database tool's argv and its stdin, authenticated where the operator manages MongoDB. */
300
+ async function toolCommand(name, argv) {
301
+ const password = await mongoAuth(name);
302
+ if (password === '')
303
+ return [[...argv], ''];
304
+ const { toolAuthenticated } = await Promise.resolve().then(() => __importStar(require('./kube/operator')));
305
+ return toolAuthenticated(argv, password);
306
+ }
307
+ /**
308
+ * What a failed database tool said, for an error: the END of its output, where the reason
309
+ * is -- mongodump opens with a line per collection, and the first 600 characters were all
310
+ * progress -- and that it was killed, when its exit says so. A tool the kernel kills for
311
+ * memory says nothing about it: in the MongoDB operator's pod the dump runs inside mongod's
312
+ * own memory limit.
313
+ */
314
+ function toolFailure(rc, output, limit) {
315
+ const tail = output.trim().slice(-limit);
316
+ if (rc !== 137)
317
+ return tail;
318
+ return `it was killed (exit 137), most likely for running out of memory${tail === '' ? '' : `; it last said: ${tail}`}`;
319
+ }
320
+ /**
321
+ * Fail early and clearly if the Mongo image has no database tools.
322
+ *
323
+ * Verified present in mongodb/mongodb-community-server; checked rather than assumed
324
+ * because the bitnami-legacy flavor is a different image and a missing binary would
325
+ * otherwise surface as an empty archive.
326
+ */
327
+ async function requireMongoTools(name) {
328
+ const [rc] = await execCapture(name, ['sh', '-c', 'command -v mongodump && command -v mongorestore'], exports.PROBE_TIMEOUT);
329
+ if (rc !== 0) {
330
+ throw new errors_1.NotReadyError(`the mongodb for ${(0, format_1.quotedText)(name)} has no mongodump/mongorestore, or is ` +
331
+ 'not running. Start the workspace (`houston start`) and try again.');
332
+ }
333
+ }
334
+ /** mongod's own recommended minimum. Below this a big restore risks EMFILE. */
335
+ exports.NOFILE_MIN = 64000;
336
+ async function warnLowFdLimit(name, emit = events_1.nullEmit) {
337
+ const [rc, out] = await execCapture(name, ['sh', '-c', 'ulimit -n'], exports.PROBE_TIMEOUT);
338
+ let limit;
339
+ try {
340
+ // The first line, trimmed, read by `toInt`, which throws for both an empty string and
341
+ // a line that is not a decimal integer.
342
+ const first = out.trim().split(/\r?\n/u)[0];
343
+ limit = (0, format_1.toInt)(first);
344
+ }
345
+ catch {
346
+ return 0;
347
+ }
348
+ if (rc === 0 && limit < exports.NOFILE_MIN) {
349
+ (0, events_1.warn)(emit, `this workspace's mongodb can open only ${String(limit)} files ` +
350
+ `(MongoDB asks for ${String(exports.NOFILE_MIN)}). Restoring anyway, one collection ` +
351
+ `at a time. Recreate it with \`houston up --force --name ${name}\` to ` +
352
+ 'pick up the raised limit.', { phase: 'restore' });
353
+ }
354
+ return limit;
355
+ }
356
+ async function rcServicesOf(name) {
357
+ // On Kubernetes there is no compose file to read service names out of, and none is
358
+ // needed: `Quiesced` scales by label instead. The list is a Compose concept, so it
359
+ // is empty there rather than faked.
360
+ if ((await kube(name)) !== '')
361
+ return [];
362
+ const svcs = await (0, record_1.rcServices)(name);
363
+ if (svcs.length === 0) {
364
+ throw new errors_1.DockerError(`${(0, format_1.quotedText)(name)} has no rocketchat service in its compose file`);
365
+ }
366
+ return svcs;
367
+ }
368
+ /**
369
+ * Stop Rocket.Chat for the duration, and start it again no matter what.
370
+ *
371
+ * A failed dump that leaves the workspace stopped is a worse outcome than the failure
372
+ * itself -- the user came back to a repro that silently is not serving.
373
+ */
374
+ class Quiesced {
375
+ constructor(name, services, emit, skip = false) {
376
+ this.name = name;
377
+ this.services = services;
378
+ this.emit = emit;
379
+ this.skip = skip;
380
+ this.note = '';
381
+ this.context = '';
382
+ this.replicas = null;
383
+ this.runningServices = [];
384
+ }
385
+ async enter() {
386
+ if (this.skip) {
387
+ (0, events_1.warn)(this.emit, '--live: Rocket.Chat keeps running, so the dump may catch a ' +
388
+ 'half-written state. Prefer the default for anything you ' +
389
+ 'intend to restore.', { phase: 'backup' });
390
+ return this;
391
+ }
392
+ (0, events_1.info)(this.emit, 'stopping Rocket.Chat so the dump is consistent (Mongo keeps running)', {
393
+ phase: 'backup',
394
+ pct: 10,
395
+ });
396
+ this.context = await kube(this.name);
397
+ if (this.context !== '') {
398
+ const { rocketchatReplicas } = await Promise.resolve().then(() => __importStar(require('./kube/scale')));
399
+ this.replicas = await rocketchatReplicas(this.name, { context: this.context });
400
+ }
401
+ else {
402
+ this.runningServices = await (0, queries_1.runningWriterServices)(this.name, this.services);
403
+ }
404
+ // BEFORE it goes down, and carrying what will bring it back. `exit` starts it again
405
+ // "no matter what" -- except the one case where nothing runs at all: a daemon job
406
+ // thread killed by a restart or an OOM. This note is what lets a later `serve` or
407
+ // `doctor` see it and fix it.
408
+ this.note = journal.record(journal.ROCKETCHAT_STOPPED, this.name, {
409
+ context: this.context,
410
+ replicas: this.replicas === null ? 1 : Object.values(this.replicas)[0],
411
+ ...(this.replicas === null ? {} : { deployment_replicas: this.replicas }),
412
+ services: [...this.runningServices],
413
+ });
414
+ try {
415
+ if (this.context !== '') {
416
+ const { scaleRocketchat } = await Promise.resolve().then(() => __importStar(require('./kube/scale')));
417
+ // ONLY Rocket.Chat. `stopWorkspace` would take MongoDB with it, and a dump needs
418
+ // the database up and only its writers quiesced.
419
+ const stopped = await scaleRocketchat(this.name, { replicas: 0, context: this.context });
420
+ if (stopped !== 0)
421
+ throw new errors_1.DockerError(`could not stop Rocket.Chat writers for '${this.name}' (exit ${String(stopped)}); refusing to access the database`);
422
+ const meta = await (0, record_1.readMeta)(this.name);
423
+ const pid = bagOf(meta.extra).port_forward_pid;
424
+ if ((0, format_1.isTruthy)(pid)) {
425
+ const { namespaceFor } = await Promise.resolve().then(() => __importStar(require('./kube/namespace')));
426
+ const { stopPortForward } = await Promise.resolve().then(() => __importStar(require('./lifecycle/ready')));
427
+ // `toInt(pid)`: a recorded pid that is not an integer throws rather than silently
428
+ // becoming 0.
429
+ await stopPortForward((0, format_1.toInt)(pid), { namespace: await namespaceFor(this.name) });
430
+ await (0, record_1.updateMeta)(this.name, (m) => {
431
+ delete bagOf(m.extra).port_forward_pid;
432
+ });
433
+ }
434
+ }
435
+ else {
436
+ await stopWriters(this.name, this.services);
437
+ }
438
+ }
439
+ catch (error) {
440
+ // Callers enter before their finally. A partially failed entry must restore its
441
+ // own original state, and keep the durable note if that recovery also fails.
442
+ try {
443
+ await this.exit();
444
+ }
445
+ catch (recoveryError) {
446
+ (0, events_1.warn)(this.emit, `could not restore Rocket.Chat after failed quiescence: ${(0, errors_1.errorText)(recoveryError)}`, { phase: 'backup' });
447
+ }
448
+ throw error;
449
+ }
450
+ return this;
451
+ }
452
+ /**
453
+ * The way out, which runs on the way out of an Interrupted too: a Ctrl-C in the dump
454
+ * starts Rocket.Chat again, clears the note and waits for it to serve, as it always has,
455
+ * where this build's `process.exit(130)` left the workspace STOPPED, its
456
+ * `rocketchat_stopped` note on disk for `doctor` to warn about, and mongodump running.
457
+ * A `cleanup`, so its waits -- `compose start rocketchat` among them -- start after the
458
+ * interrupt.
459
+ */
460
+ async exit() {
461
+ if (this.skip || this.note === '')
462
+ return;
463
+ await (0, exec_1.cleanup)(async () => await this.restart());
464
+ }
465
+ async restart() {
466
+ let failed;
467
+ let serving;
468
+ if (this.context !== '' && this.replicas !== null) {
469
+ const { restoreRocketchatReplicas } = await Promise.resolve().then(() => __importStar(require('./kube/scale')));
470
+ failed =
471
+ (await restoreRocketchatReplicas(this.name, this.replicas, { context: this.context })) !==
472
+ 0;
473
+ serving = Object.values(this.replicas).some((count) => count > 0);
474
+ }
475
+ else {
476
+ failed =
477
+ this.runningServices.length > 0 &&
478
+ (await (0, engine_1.startServices)(this.name, this.runningServices)) !== 0;
479
+ serving = this.runningServices.length > 0;
480
+ }
481
+ if (failed) {
482
+ throw new errors_1.DockerError(`Rocket.Chat's prior state could not be restored on ${(0, format_1.quotedText)(this.name)}; ` +
483
+ 'the recovery note is retained with the original replica/service counts');
484
+ }
485
+ journal.clear(this.note);
486
+ this.note = '';
487
+ if (!serving)
488
+ return;
489
+ // Rocket.Chat has been STARTED, which is not the same as serving. `waitServing` is
490
+ // runtime-aware and re-establishes the forward, so one call covers both runtimes.
491
+ try {
492
+ await (0, ready_1.waitServing)(await (0, record_1.readMeta)(this.name), this.emit, 300.0);
493
+ }
494
+ catch (exc) {
495
+ // Any failure but a Ctrl-C: an Interrupted in the wait leaves `exit` here, and
496
+ // the bundle is never packed. Caught, it was this warning, then "packing the bundle",
497
+ // a bundle written and "✓ backed up", then exit 130.
498
+ if (exc instanceof exec_1.Interrupted)
499
+ throw exc;
500
+ (0, events_1.warn)(this.emit, `the dump is complete, but ${(0, format_1.quotedText)(this.name)} is not serving on its ` +
501
+ `published port again (${(0, errors_1.errorText)(exc)}). Run ` +
502
+ `\`houston ready --name ${this.name}\` to bring it back.`, { phase: 'backup' });
503
+ }
504
+ }
505
+ }
506
+ exports.Quiesced = Quiesced;
507
+ /** Verify a successful Compose stop really left no writers, before touching MongoDB. */
508
+ async function stopWriters(name, services) {
509
+ const stopped = await (0, engine_1.stopServices)(name, services);
510
+ if (stopped !== 0) {
511
+ throw new errors_1.DockerError(`could not stop Rocket.Chat writers for '${name}' (exit ${String(stopped)}); refusing to access the database`);
512
+ }
513
+ if ((await (0, queries_1.runningWriterServices)(name, services)).length > 0) {
514
+ throw new errors_1.DockerError(`Rocket.Chat writers are still running for '${name}'; refusing to access the database`);
515
+ }
516
+ }
517
+ // --- create -------------------------------------------------------------------
518
+ /** Dump a repro's database into a bundle. Returns {path, bytes, manifest}. */
519
+ async function create(name, { out = '', note = '', live = false, emit = events_1.nullEmit, } = {}) {
520
+ const target = await (0, naming_1.resolveName)(name);
521
+ // Docker is required only when Docker is what runs it. Everything below this is
522
+ // runtime-agnostic: the bundle, the manifest and the safety checks are the same on
523
+ // both, and only the five places that touch a container differ.
524
+ const context = await kube(target);
525
+ if (context === '')
526
+ await (0, preconditions_1.requireDocker)();
527
+ else
528
+ await (await Promise.resolve().then(() => __importStar(require('./kube/namespace')))).requireOwnNamespace(target, { context });
529
+ const { reproLock } = await Promise.resolve().then(() => __importStar(require('./runner/locks')));
530
+ // UNWOUND by a Ctrl-C: through `Quiesced.exit`, the staging directory's removal and the
531
+ // lock's release. `composeExecToFile` passes the interrupted dump's Interrupted on
532
+ // rather than answering it as a failed dump, so it reaches the `finally` that is the
533
+ // cleanup and then `runCli`, which answers it as the interrupt it is.
534
+ return await (0, exec_1.unwindsOnInterrupt)(async () => await reproLock(target, async () => {
535
+ // AGAIN UNDER THE LOCK: it quiesces and dumps what is in the namespace by name.
536
+ if (context !== '') {
537
+ await (await Promise.resolve().then(() => __importStar(require('./kube/namespace')))).requireOwnNamespace(target, { context });
538
+ }
539
+ return await createLocked(target, { out, note, live, emit });
540
+ }));
541
+ }
542
+ /**
543
+ * The path with a leading `~` or `~name` expanded, and spelled as `pathExpandUser` spells
544
+ * it: every caller-supplied bundle and `--out` goes through it before anything touches the
545
+ * filesystem. It replaced a leading `~` with the home by `path.join`, so `~bob/x` was the
546
+ * current user's `bob/x`, a trailing `/` and a doubled one printed where the established
547
+ * spelling has neither, a path with no `~` was not normalised at all, and a HOME holding
548
+ * `..` was folded.
549
+ */
550
+ function expandUser(value) {
551
+ return (0, home_1.pathExpandUser)(value);
552
+ }
553
+ async function dumpToBundle({ database, dest, emit, live, meta, note, services, target, ws, }) {
554
+ // A fresh `houston-backup-` directory in the temporary directory `tempRoot` settles
555
+ // on, not in `$TMPDIR` as given -- a TMPDIR that is gone was an ENOENT stack where the
556
+ // established behaviour falls back to /tmp.
557
+ const staging = (0, tempdir_1.makeTempDir)('houston-backup-');
558
+ try {
559
+ const archive = path.join(staging, exports.ARCHIVE);
560
+ let dump;
561
+ let started = 0;
562
+ let recoveryFailure = null;
563
+ const quiesced = new Quiesced(target, services, emit, live);
564
+ await quiesced.enter();
565
+ try {
566
+ (0, events_1.info)(emit, `dumping database ${(0, format_1.quotedText)(database)}`, { phase: 'backup', pct: 30 });
567
+ started = performance.now();
568
+ const [argv, input] = await toolCommand(target, [
569
+ 'mongodump',
570
+ '--archive',
571
+ '--gzip',
572
+ '--db',
573
+ database,
574
+ ]);
575
+ const result = await execToFile(target, argv, archive, exports.DUMP_TIMEOUT, input);
576
+ dump = { result };
577
+ }
578
+ catch (error) {
579
+ dump = { error };
580
+ }
581
+ finally {
582
+ try {
583
+ await quiesced.exit();
584
+ }
585
+ catch (error) {
586
+ recoveryFailure = { error };
587
+ }
588
+ }
589
+ if (recoveryFailure !== null && recoveryFailure.error instanceof exec_1.Interrupted) {
590
+ throw recoveryFailure.error;
591
+ }
592
+ if ('error' in dump)
593
+ throw dump.error;
594
+ const [rc, err] = dump.result;
595
+ if (rc !== 0) {
596
+ throw new errors_1.DockerError(`mongodump failed for ${(0, format_1.quotedText)(target)}: ${toolFailure(rc, err, 600)}`);
597
+ }
598
+ if (!fs.existsSync(archive) || fs.statSync(archive).size === 0) {
599
+ throw new errors_1.DockerError(`mongodump produced an empty archive for database ${(0, format_1.quotedText)(database)} - ` +
600
+ 'is this workspace seeded, and is MONGO_URL correct?');
601
+ }
602
+ const manifest = {
603
+ schema: exports.SCHEMA,
604
+ created_at: new Date().toISOString().replace(/\.\d{3}Z$/u, '+00:00'),
605
+ houston_version: ourVersion(),
606
+ repro: target,
607
+ label: note,
608
+ database,
609
+ rc_version: meta.rcVersion,
610
+ rc_image: meta.rcImage,
611
+ mongo_tag: meta.mongoTag,
612
+ mongo_flavor: meta.mongoFlavor,
613
+ preset: meta.preset,
614
+ params: bagOf(meta.extra).params ?? {},
615
+ // A composed workspace's list and params; absent for one preset, whose manifest is
616
+ // unchanged.
617
+ ...(bagOf(meta.extra).presets === undefined
618
+ ? {}
619
+ : {
620
+ presets: bagOf(meta.extra).presets,
621
+ preset_params: bagOf(meta.extra).preset_params ?? {},
622
+ }),
623
+ runtime: topology.ofMeta(meta),
624
+ deployment: bagOf(meta.extra)[config.EXTRA_DEPLOYMENT] ?? '',
625
+ // A Kubernetes workspace's cluster and whether the operator runs its MongoDB: a
626
+ // `restore --new` rebuilt on the default context with a plain StatefulSet, and said
627
+ // "the MongoDB operator is opt-in" about a copy of one that ran it. Absent for Compose.
628
+ ...(topology.ofMeta(meta) === topology.KUBERNETES
629
+ ? {
630
+ context: String(bagOf(meta.extra)[config.EXTRA_CONTEXT] ?? ''),
631
+ mongo_operator: bagOf(meta.extra).mongo_managed_by === 'operator',
632
+ }
633
+ : {}),
634
+ env_overrides: bagOf(meta.extra).env ?? {},
635
+ sidecar_volumes: await sidecarVolumes(target),
636
+ archive_sha256: sha256File(archive),
637
+ archive_bytes: fs.statSync(archive).size,
638
+ // Seconds on a monotonic clock, rounded to 1 place, half to even.
639
+ dump_seconds: (0, format_1.roundSeconds)(performance.now() - started),
640
+ live,
641
+ };
642
+ fs.writeFileSync(path.join(staging, exports.MANIFEST), serialiseManifest(manifest), 'utf8');
643
+ // `copyWithMetadata`, which keeps the file's mode and times: `copyFileSync` kept the mode and
644
+ // made every copy's mtime "now", so the bundle recorded the time of the backup for the
645
+ // compose file, the record and every preset file.
646
+ const times = new Map();
647
+ for (const [src, dst] of [
648
+ [(0, home_1.joinPath)(ws, 'docker-compose.yml'), exports.COMPOSE],
649
+ [(0, home_1.joinPath)(ws, 'repro.json'), exports.RECORD],
650
+ ]) {
651
+ if (fs.existsSync(src))
652
+ copyWithMetadata(src, path.join(staging, dst), times);
653
+ }
654
+ // THE REGISTRATION TOKEN STAYS HOME. It is a real licence, and a bundle is exactly what
655
+ // gets attached to a support case -- the guide says never to paste one there, and that
656
+ // backups leave the licence out. Nothing restores from this copy of the compose file
657
+ // (`restore --new` rebuilds from the manifest), so the copy says only that one was set.
658
+ const bundled = path.join(staging, exports.COMPOSE);
659
+ if (fs.existsSync(bundled)) {
660
+ const text = fs.readFileSync(bundled, 'utf8');
661
+ const kept = text.replace(/^(\s*REG_TOKEN:)[^\n]*$/gmu, "$1 ''");
662
+ if (kept !== text) {
663
+ fs.writeFileSync(bundled, kept, 'utf8');
664
+ copyMetadata((0, home_1.joinPath)(ws, 'docker-compose.yml'), bundled, times);
665
+ }
666
+ }
667
+ copyPresetFiles(ws, path.join(staging, exports.FILES_DIR), times);
668
+ (0, events_1.info)(emit, 'packing the bundle', { phase: 'backup', pct: 85 });
669
+ await (0, targz_1.writeTarGzFromDir)(staging, dest, { mtimeNs: times });
670
+ if (recoveryFailure !== null) {
671
+ // The dump succeeded. Preserve that usable artifact while reporting the failed
672
+ // workspace recovery truthfully instead of saying the entire operation succeeded.
673
+ fs.chmodSync(dest, 0o600);
674
+ throw new errors_1.DockerError(`backup saved at ${dest}, but ${(0, errors_1.errorText)(recoveryFailure.error)}`);
675
+ }
676
+ return manifest;
677
+ }
678
+ finally {
679
+ fs.rmSync(staging, { recursive: true, force: true });
680
+ }
681
+ }
682
+ async function createLocked(target, { out = '', note = '', live = false, emit = events_1.nullEmit, } = {}) {
683
+ const meta = await (0, record_1.readMeta)(target);
684
+ await requireMongoTools(target);
685
+ const database = await (0, database_of_1.databaseOf)(target);
686
+ const services = await rcServicesOf(target);
687
+ let dest = out !== '' ? expandUser(out) : (0, home_1.joinPath)(backupsDir(), `${target}-${utcStamp()}${exports.SUFFIX}`);
688
+ if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) {
689
+ dest = (0, home_1.joinPath)(dest, `${target}-${utcStamp()}${exports.SUFFIX}`);
690
+ }
691
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
692
+ if (fs.existsSync(dest)) {
693
+ throw new errors_1.ConflictError(`${dest} already exists; pass a different --out`);
694
+ }
695
+ const ws = (0, paths_2.workspace)(target);
696
+ const manifest = await dumpToBundle({
697
+ database,
698
+ dest,
699
+ emit,
700
+ live,
701
+ meta,
702
+ note,
703
+ services,
704
+ target,
705
+ ws,
706
+ });
707
+ fs.chmodSync(dest, 0o600); // the dump contains every message and credential hash
708
+ const size = fs.statSync(dest).size;
709
+ (0, events_1.info)(emit, `backup written to ${dest} (${human(size)})`, { phase: 'done', pct: 100 });
710
+ return { name: target, path: dest, bytes: size, manifest };
711
+ }
712
+ /**
713
+ * The version this build reports as its own.
714
+ *
715
+ * This build has no installed-package metadata to read until it is packaged, so it
716
+ * reports `jsonout`'s registry value, which the front door sets from the package and
717
+ * which defaults to the placeholder.
718
+ */
719
+ function ourVersion() {
720
+ return (0, jsonout_1.getHoustonVersion)();
721
+ }
722
+ async function sidecarVolumes(name) {
723
+ let doc;
724
+ try {
725
+ doc = await (0, record_1.readCompose)(name);
726
+ }
727
+ catch {
728
+ return [];
729
+ }
730
+ return Object.keys(bagOf(doc.volumes))
731
+ .filter((volume) => volume !== 'mongodb_data')
732
+ .sort();
733
+ }
734
+ /**
735
+ * A file's times, then its mode, copied onto its copy. The times should be exact to the
736
+ * nanosecond; `utimes` here keeps microseconds, so the exact mtime is also put in `times`,
737
+ * keyed by the copy, for `writeTarGzFromDir` to record as the copy's.
738
+ */
739
+ function copyMetadata(src, dst, times) {
740
+ const st = fs.statSync(src, { bigint: true });
741
+ fs.utimesSync(dst, Number(st.atimeNs) / 1e9, Number(st.mtimeNs) / 1e9);
742
+ times.set(dst, st.mtimeNs);
743
+ fs.chmodSync(dst, Number(st.mode) & 0o7777);
744
+ }
745
+ /** A file copied with its status: the bytes, then `copyMetadata`. */
746
+ function copyWithMetadata(src, dst, times) {
747
+ fs.copyFileSync(src, dst);
748
+ copyMetadata(src, dst, times);
749
+ }
750
+ /** Every entry `copyTree` could not copy, as `(src, dst, why)` triples; `why` names the file. */
751
+ class TreeCopyError extends Error {
752
+ constructor(failures) {
753
+ super(`could not copy ${failures.map((row) => row[2]).join('; ')}`);
754
+ this.failures = failures;
755
+ this.name = 'Error';
756
+ }
757
+ }
758
+ /**
759
+ * A tree copied into `dst`, which may already exist: a link is copied as what it points to,
760
+ * a directory recursively, a file with `copyWithMetadata`, and the directory itself gets `copyMetadata`
761
+ * LAST, after its entries were written -- so its mode and mtime are the source's.
762
+ * `fs.cpSync` left every directory at the umask's mode and "now". A failure is collected
763
+ * and the rest still copied, then thrown together as one `TreeCopyError`.
764
+ */
765
+ function copyTree(src, dst, times) {
766
+ const entries = fs.readdirSync(src, { withFileTypes: true });
767
+ fs.mkdirSync(dst, { recursive: true });
768
+ const failures = [];
769
+ const collect = (error, from, to) => {
770
+ if (error instanceof TreeCopyError)
771
+ failures.push(...error.failures);
772
+ else if (typeof error.errno === 'number') {
773
+ failures.push([from, to, (0, format_1.fileErrorText)(error, from)]);
774
+ }
775
+ else
776
+ throw error;
777
+ };
778
+ for (const entry of entries) {
779
+ const srcname = path.join(src, entry.name);
780
+ const dstname = path.join(dst, entry.name);
781
+ try {
782
+ const directory = entry.isSymbolicLink() ? (0, format_1.pathIsDir)(srcname) : entry.isDirectory();
783
+ if (directory)
784
+ copyTree(srcname, dstname, times);
785
+ else
786
+ copyWithMetadata(srcname, dstname, times);
787
+ }
788
+ catch (error) {
789
+ collect(error, srcname, dstname);
790
+ }
791
+ }
792
+ try {
793
+ copyMetadata(src, dst, times);
794
+ }
795
+ catch (error) {
796
+ collect(error, src, dst);
797
+ }
798
+ if (failures.length > 0)
799
+ throw new TreeCopyError(failures);
800
+ }
801
+ /**
802
+ * Copy preset-generated workspace files (traefik/dynamic.yml, LDIF, ...).
803
+ *
804
+ * Deliberately excludes `import/`: those are customers' uploaded settings dumps,
805
+ * transient by design, and a backup is not where they should accumulate.
806
+ *
807
+ * `times` collects the exact mtime of every copy (see `copyMetadata`).
808
+ */
809
+ function copyPresetFiles(ws, dest, times = new Map()) {
810
+ const skip = new Set(['docker-compose.yml', 'repro.json', 'import']);
811
+ for (const item of fs.readdirSync(ws)) {
812
+ if (skip.has(item) || item.startsWith('.'))
813
+ continue;
814
+ const source = (0, home_1.joinPath)(ws, item);
815
+ fs.mkdirSync(dest, { recursive: true });
816
+ // `pathIsDir`, which follows a link and is false for one that dangles.
817
+ if ((0, format_1.pathIsDir)(source)) {
818
+ copyTree(source, path.join(dest, item), times);
819
+ }
820
+ else {
821
+ copyWithMetadata(source, path.join(dest, item), times);
822
+ }
823
+ }
824
+ }
825
+ /**
826
+ * The manifest as bundles have always carried it: indented by 2, keys sorted.
827
+ *
828
+ * The shared renderer in `lib/jsonout` does the hard parts -- recursive key sorting,
829
+ * escaping everything past ASCII -- so this and the `--json` envelope cannot drift. What is
830
+ * left here is the one thing a manifest knows that a JSON encoder cannot: `dump_seconds`
831
+ * is a float, and an integral one is written with its `.0`.
832
+ */
833
+ function serialiseManifest(manifest) {
834
+ const value = { ...manifest };
835
+ if ('dump_seconds' in value) {
836
+ value.dump_seconds = new jsonout_1.JsonFloat(Number(value.dump_seconds ?? 0));
837
+ }
838
+ return (0, jsonout_1.dumpsIndented)(value, 2);
839
+ }
840
+ function human(n) {
841
+ // The `.0f` / `.1f` formats round half to EVEN; `toFixed` is half AWAY FROM ZERO.
842
+ // Measured: 1280 bytes has always read `1.2 KB`, and was `1.3 KB` here.
843
+ // `formatFixed` is the one implementation of those format specs.
844
+ let value = n;
845
+ for (const unit of ['B', 'KB', 'MB', 'GB']) {
846
+ if (value < 1024 || unit === 'GB') {
847
+ return unit === 'B' ? `${(0, format_1.formatFixed)(value, 0)} ${unit}` : `${(0, format_1.formatFixed)(value, 1)} ${unit}`;
848
+ }
849
+ value /= 1024.0;
850
+ }
851
+ return `${(0, format_1.formatFixed)(value, 1)} GB`;
852
+ }
853
+ // --- read / list ----------------------------------------------------------------
854
+ /**
855
+ * A caller-supplied bundle path, as a path that is safe to stat.
856
+ *
857
+ * The path reaches here from a CLI argument or a JSON body, so every filesystem call
858
+ * on it has to be guarded: a 300-character name raises ENAMETOOLONG and an unreadable
859
+ * file raises EPERM, and both used to escape as a 500 rather than the "that is not a
860
+ * bundle" this is.
861
+ */
862
+ function bundlePath(bundle) {
863
+ // Outside the `try`: a NotFoundError and an OS error are all it catches, so a `~name`
864
+ // nobody has is an unhandled `HomeUnknown`, not "not a usable path".
865
+ const resolved = expandUser(bundle);
866
+ try {
867
+ if (!pathExists(resolved)) {
868
+ throw new errors_1.NotFoundError(`no backup bundle at ${resolved}`);
869
+ }
870
+ return resolved;
871
+ }
872
+ catch (error) {
873
+ if (error instanceof errors_1.NotFoundError)
874
+ throw error;
875
+ throw new errors_1.ValidationError(`${(0, format_1.quotedText)(String(bundle).slice(0, 120))} is not a usable path: ${(0, format_1.fileErrorText)(error)}`);
876
+ }
877
+ }
878
+ /**
879
+ * Whether a path exists: false only for the errors that mean "not there" (ENOENT, ENOTDIR,
880
+ * EBADF, ELOOP), and any other thrown.
881
+ *
882
+ * `fs.existsSync` answers false for EVERY failure, so a 300-character name -- ENAMETOOLONG
883
+ * -- was reported as a missing bundle (404, exit 4) where the established answer refuses it
884
+ * as a path that cannot be used (400, exit 2), which is what it is.
885
+ */
886
+ function pathExists(target) {
887
+ try {
888
+ fs.statSync(target);
889
+ return true;
890
+ }
891
+ catch (error) {
892
+ const code = String(error.code ?? '');
893
+ if (['ENOENT', 'ENOTDIR', 'EBADF', 'ELOOP'].includes(code))
894
+ return false;
895
+ throw error;
896
+ }
897
+ }
898
+ /** The manifest of a bundle, without unpacking the archive. */
899
+ async function readManifest(bundle) {
900
+ const target = bundlePath(bundle);
901
+ let raw;
902
+ try {
903
+ raw = await (0, targz_1.readMember)(target, exports.MANIFEST);
904
+ }
905
+ catch (error) {
906
+ // The unsafe-entry check throws its own refusal out of `readManifest` untouched -- it
907
+ // is not an archive error, an OS error or a JSON error -- so this is not wrapped in the
908
+ // "not a readable bundle" prose either. `UnsafeBundleEntry` already IS the
909
+ // established `ValidationError`, message included.
910
+ if (error instanceof targz_1.UnsafeBundleEntry)
911
+ throw error;
912
+ const message = (0, errors_1.errorText)(error);
913
+ const gzip = (0, targz_1.gzipFailure)(error);
914
+ if (gzip?.truncated === true) {
915
+ throw new errors_1.ValidationError(`${target} ends part-way through: it is truncated, or still being written. ` +
916
+ `(${gzip.text})`);
917
+ }
918
+ if (gzip !== null) {
919
+ // An archive that cannot be read: not gzip at all, or corrupt data inside it.
920
+ throw new errors_1.ValidationError(`${target} is not a readable backup bundle: ${gzip.text}`);
921
+ }
922
+ if (error.code !== undefined) {
923
+ // A filesystem error -- unreadable, a directory, a device node: "not a bundle", not a bug.
924
+ throw new errors_1.ValidationError(`${target} cannot be read as a backup bundle: ${(0, format_1.strerrorText)(error, target)}`);
925
+ }
926
+ throw new errors_1.ValidationError(`${target} is not a readable backup bundle: ${message}`);
927
+ }
928
+ if (raw === null) {
929
+ throw new errors_1.ValidationError(`${target} has no ${exports.MANIFEST}; is it an houston backup?`);
930
+ }
931
+ let data;
932
+ try {
933
+ // `loads`, the shared decoder with the established messages: a malformed manifest is
934
+ // refused in the words it has always been refused in, and `Unexpected end of JSON
935
+ // input` is not that sentence.
936
+ data = (0, json_text_1.loads)(raw.toString('utf8'));
937
+ }
938
+ catch (error) {
939
+ throw new errors_1.ValidationError(`${target} has a malformed ${exports.MANIFEST}: ${(0, errors_1.errorText)(error)}`);
940
+ }
941
+ const manifest = data;
942
+ const schema = manifest.schema;
943
+ // The schema compares with `true` equal to 1: a manifest carrying `"schema": true` has
944
+ // always been accepted, so it is accepted here rather than refused for a shape never
945
+ // objected to before. The message quotes with `shownValue`, so a string schema reads
946
+ // `'2'`, as it always has.
947
+ const schemaMatches = schema === exports.SCHEMA || (typeof schema === 'boolean' && Number(schema) === exports.SCHEMA);
948
+ if (!schemaMatches) {
949
+ throw new errors_1.ValidationError(`${target} uses bundle schema ${(0, format_1.shownValue)(schema)}, this houston reads ${String(exports.SCHEMA)}. ` +
950
+ 'Use the version of houston that wrote it.');
951
+ }
952
+ return manifest;
953
+ }
954
+ /**
955
+ * Bundles in the managed directory, newest first.
956
+ *
957
+ * A bundle whose manifest cannot be read is still listed, marked with `error`:
958
+ * silently hiding it is how a corrupt backup gets discovered at the worst moment.
959
+ */
960
+ /**
961
+ * The `*.rcbak` bundles in `backupsDir()`: in DIRECTORY order, as the directory hands them
962
+ * over -- the listing's mtime sort is stable, so bundles of one mtime keep it, where a
963
+ * sorted readdir put them in name order -- and none from a directory that cannot be read,
964
+ * which lists as empty (an EACCES here was a stack and exit 1 where the established answer
965
+ * is "no backups yet"). Names are read as BYTES and stat'ed as bytes: a file name that is
966
+ * not UTF-8 decoded to a U+FFFD that named no file, and the stat of it crashed. Its
967
+ * manifest is still read by the decoded name, so such a bundle is listed UNREADABLE ("no
968
+ * backup bundle at ..."), where the previous implementation reads it; a JavaScript string
969
+ * cannot carry the byte back out.
970
+ */
971
+ function bundleFiles() {
972
+ // `opendirSync`, not `readdirSync`: libuv's scandir SORTS the names it returns, where
973
+ // opendir reads them in the order the directory holds them.
974
+ // Decoded as latin1, one character per byte, so the bytes come back whole.
975
+ const entries = [];
976
+ try {
977
+ const handle = fs.opendirSync(backupsDir(), { encoding: 'latin1' });
978
+ try {
979
+ for (let entry = handle.readSync(); entry !== null; entry = handle.readSync()) {
980
+ entries.push(Buffer.from(entry.name, 'latin1'));
981
+ }
982
+ }
983
+ finally {
984
+ handle.closeSync();
985
+ }
986
+ }
987
+ catch (error) {
988
+ if (typeof error.errno !== 'number')
989
+ throw error;
990
+ return [];
991
+ }
992
+ const dir = Buffer.from(`${backupsDir()}${path.sep}`);
993
+ return entries
994
+ .filter((entry) => entry.toString('latin1').endsWith(exports.SUFFIX))
995
+ .map((entry) => {
996
+ const full = Buffer.concat([dir, entry]);
997
+ return { full, shown: full.toString('utf8') };
998
+ });
999
+ }
1000
+ /** The manifest's value for `key`, or "" when it has none: a held null stays null. */
1001
+ function field(m, key) {
1002
+ return Object.hasOwn(m, key) ? m[key] : '';
1003
+ }
1004
+ async function listBackups(name = '') {
1005
+ const out = [];
1006
+ for (const { full, shown } of bundleFiles()) {
1007
+ const stat = fs.statSync(full);
1008
+ const row = { path: shown, bytes: stat.size, mtime: stat.mtimeMs / 1000 };
1009
+ try {
1010
+ const m = await readManifest(shown);
1011
+ Object.assign(row, {
1012
+ repro: field(m, 'repro'),
1013
+ label: field(m, 'label'),
1014
+ rc_version: field(m, 'rc_version'),
1015
+ created_at: field(m, 'created_at'),
1016
+ mongo_tag: field(m, 'mongo_tag'),
1017
+ preset: field(m, 'preset'),
1018
+ error: '',
1019
+ });
1020
+ }
1021
+ catch (error) {
1022
+ if (!(error instanceof errors_1.ValidationError) && !(error instanceof errors_1.NotFoundError))
1023
+ throw error;
1024
+ Object.assign(row, {
1025
+ repro: '',
1026
+ label: '',
1027
+ rc_version: '',
1028
+ created_at: '',
1029
+ mongo_tag: '',
1030
+ preset: '',
1031
+ error: String(error.message),
1032
+ });
1033
+ }
1034
+ if (name !== '' && row.repro !== name)
1035
+ continue;
1036
+ out.push(row);
1037
+ }
1038
+ // Bundles OUTLIVE the workspace they came from, but they are matched to one by NAME,
1039
+ // and houston derives names from the version -- so recreating a workspace reliably
1040
+ // produces the same name as a destroyed one. They are still listed, and marked.
1041
+ let born = '';
1042
+ if (name !== '') {
1043
+ try {
1044
+ born = String((await (0, record_1.readMeta)(name)).createdAt || '');
1045
+ }
1046
+ catch {
1047
+ born = '';
1048
+ }
1049
+ }
1050
+ for (const row of out) {
1051
+ row.predates_workspace = predates(row.created_at, born);
1052
+ }
1053
+ return out.sort((left, right) => Number(right.mtime) - Number(left.mtime));
1054
+ }
1055
+ // --- restore -----------------------------------------------------------------------
1056
+ /**
1057
+ * Refuse a restore over somebody else's workspace, and record the refusal.
1058
+ *
1059
+ * One helper because `restore` learns its target two ways -- from `name`, before
1060
+ * anything is read, and from the bundle's manifest afterwards.
1061
+ */
1062
+ async function requireMayDestroy(target) {
1063
+ const [allowed, why] = await (0, ownership_1.mayDestroy)(target, audit.actor());
1064
+ if (!allowed) {
1065
+ audit.record('restore', target, { outcome: 'denied' });
1066
+ throw new errors_1.ConflictError(why);
1067
+ }
1068
+ }
1069
+ /** Create the bundle's workspace, then explain clearly if its load fails. */
1070
+ async function restoreNew(target, bundle, manifest, emit, { allowUpgrade, force }) {
1071
+ const { reproLock } = await Promise.resolve().then(() => __importStar(require('./runner/locks')));
1072
+ return await reproLock(target, async () => {
1073
+ await createFromManifest(target, manifest, emit, bundle);
1074
+ try {
1075
+ return await restoreLocked(target, bundle, manifest, emit, {
1076
+ allowUpgrade,
1077
+ force,
1078
+ created: true,
1079
+ });
1080
+ }
1081
+ catch (error) {
1082
+ if (!(error instanceof errors_1.ReproError))
1083
+ throw error;
1084
+ // The workspace was created before the load failed, so it exists and is EMPTY.
1085
+ // Left unsaid, that reads as "the command did nothing".
1086
+ const Cartridge = error.constructor;
1087
+ throw new Cartridge(`${error.message}\n note: ${(0, format_1.quotedText)(target)} was created and is running, ` +
1088
+ `but empty. Retry with \`houston restore <bundle> --name ${target}\`, or remove ` +
1089
+ `it with \`houston down --name ${target} --volumes --yes\`.`);
1090
+ }
1091
+ });
1092
+ }
1093
+ /**
1094
+ * Restore a bundle into a repro.
1095
+ *
1096
+ * Three target modes: in place (`restore(b)`), new (`restore(b, { new: true })`), other
1097
+ * (`restore(b, { name: 'other' })`).
1098
+ */
1099
+ async function restore(bundle, { name = '', new: isNew = false, allowUpgrade = false, force = false, emit = events_1.nullEmit, } = {}) {
1100
+ const existing = name !== '' && !isNew ? await (0, naming_1.resolveName)(name) : '';
1101
+ // As `down` refuses it: `--name test` while your own `alice-test` is there, and the `test`
1102
+ // that answers is not yours, would drop the wrong workspace's collections.
1103
+ if (existing !== '')
1104
+ await (0, naming_1.refuseAmbiguous)(name, existing, audit.actor());
1105
+ // Authorisation FIRST, when the target is already known.
1106
+ if (existing !== '')
1107
+ await requireMayDestroy(existing);
1108
+ const bundleFile = expandUser(bundle);
1109
+ const manifest = await readManifest(bundleFile);
1110
+ // Docker only when Docker is what runs the TARGET, which the bundle names when `--name`
1111
+ // does not: asked before it was read, a restore into a Kubernetes workspace by the
1112
+ // bundle's own name, or as new from a Kubernetes bundle, demanded Docker on a box with none.
1113
+ if (!(await restoresOnKubernetes(isNew, existing, manifest)))
1114
+ await (0, preconditions_1.requireDocker)();
1115
+ if (isNew) {
1116
+ // THE NAME THE CREATE WILL SETTLE ON, owner prefix and all: the create puts
1117
+ // `<actor>-` in front, and the load went to the bare name -- a member's restore as new
1118
+ // left `mem-x` running empty and failed on `x`, "half-written".
1119
+ const newName = name !== ''
1120
+ ? (0, naming_1.sanitize)((0, naming_1.ownerPrefix)((0, naming_1.sanitize)(name), audit.actor()))
1121
+ : await deriveNewName(manifest, audit.actor());
1122
+ return await restoreNew(newName, bundleFile, manifest, emit, { allowUpgrade, force });
1123
+ }
1124
+ const wanted = name !== '' ? name : String(manifest.repro ?? '');
1125
+ let resolved;
1126
+ try {
1127
+ resolved = await (0, naming_1.resolveName)(wanted);
1128
+ }
1129
+ catch (error) {
1130
+ if (!(error instanceof errors_1.NotFoundError))
1131
+ throw error;
1132
+ throw new errors_1.NotFoundError(`${error.message} - pass --new to create it from the bundle instead`);
1133
+ }
1134
+ await requireMayDestroy(resolved);
1135
+ const { reproLock } = await Promise.resolve().then(() => __importStar(require('./runner/locks')));
1136
+ return await reproLock(resolved, async () => {
1137
+ // AGAIN UNDER THE LOCK: handed over while this waited, it is somebody else's data now.
1138
+ await requireMayDestroy(resolved);
1139
+ if (name === '')
1140
+ await refuseANewerNamesake(resolved, manifest, bundleFile);
1141
+ // Recorded before its collections are dropped, as `down --volumes` is before its work.
1142
+ audit.record('restore', resolved);
1143
+ return await restoreLocked(resolved, bundleFile, manifest, emit, {
1144
+ allowUpgrade,
1145
+ force,
1146
+ created: false,
1147
+ });
1148
+ });
1149
+ }
1150
+ /** Whether a bundle made at `madeAt` is older than a workspace born at `born` (ISO times). */
1151
+ function predates(madeAt, born) {
1152
+ return born !== '' && madeAt !== undefined && madeAt !== '' && String(madeAt) < born;
1153
+ }
1154
+ /**
1155
+ * A bundle restored in place by its own name goes back to "the repro it came from" -- and a
1156
+ * derived name comes back every time a workspace of that version is made again, so the
1157
+ * workspace holding the name now can be a newer one whose data the restore would replace.
1158
+ * `--name` says the caller means it; `--new` makes the bundle's own workspace again.
1159
+ */
1160
+ async function refuseANewerNamesake(target, manifest, bundle) {
1161
+ const born = String((await (0, record_1.readMeta)(target)).createdAt || '');
1162
+ // NOR AN OLDER ONE THAT ONLY SHARES THE NAME. A bundle made today from a colleague's
1163
+ // `rc8-5-1` passed the check below over your own `rc8-5-1` of last week, and dropped its
1164
+ // data. The bundle carries its workspace's record, and a workspace keeps its birth across a
1165
+ // rebuild, so a different birth is a different workspace.
1166
+ const source = await sourceBirth(bundle);
1167
+ if (source !== '' && born !== '' && source !== born) {
1168
+ throw new errors_1.ConflictError(`${(0, format_1.quotedText)(target)} is not the workspace this backup was taken from (that one was ` +
1169
+ `made ${source}, this one ${born}), and restoring would replace this one's data. ` +
1170
+ `Restore with --new to bring the backup back as its own workspace, or --name ${target} ` +
1171
+ "to replace this one's data anyway.");
1172
+ }
1173
+ if (!predates(manifest.created_at, born))
1174
+ return;
1175
+ throw new errors_1.ConflictError(`${(0, format_1.quotedText)(target)} was made after this backup (backup ${String(manifest.created_at)}, ` +
1176
+ `workspace ${born}), so it is a newer workspace with the same name, and restoring would ` +
1177
+ `replace its data. Restore with --new to bring the backup back as its own workspace, or ` +
1178
+ `--name ${target} to replace this one's data anyway.`);
1179
+ }
1180
+ /** Whose a bundle's data is, from the record it carries; '' when it names nobody or cannot say. */
1181
+ async function bundleOwner(bundle) {
1182
+ try {
1183
+ const raw = await (0, targz_1.readMember)(bundle, exports.RECORD);
1184
+ if (raw === null)
1185
+ return '';
1186
+ const extra = JSON.parse(raw.toString('utf8')).extra;
1187
+ const owner = (0, format_1.isTruthy)(extra?.owner) ? extra?.owner : extra?.created_by;
1188
+ return typeof owner === 'string' ? owner : '';
1189
+ }
1190
+ catch {
1191
+ return '';
1192
+ }
1193
+ }
1194
+ /** When the bundle's own workspace was made, from the record it carries; '' when it says not. */
1195
+ async function sourceBirth(bundle) {
1196
+ try {
1197
+ const raw = await (0, targz_1.readMember)(bundle, exports.RECORD);
1198
+ if (raw === null)
1199
+ return '';
1200
+ const born = JSON.parse(raw.toString('utf8')).created_at;
1201
+ return typeof born === 'string' ? born : '';
1202
+ }
1203
+ catch {
1204
+ return ''; // a record it cannot read decides nothing; the check above still runs
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Every collection dropped, not the database: the MongoDB operator's application user holds
1209
+ * `readWrite`, which may drop a collection and may NOT run `dropDatabase`, so every restore
1210
+ * into an operator workspace warned "could not drop" and merged. The same end -- nothing the
1211
+ * bundle lacks survives -- under the role every flavour's user has. A failure is PRINTED,
1212
+ * because only stdout comes back and the shell writes its errors to stderr: the warning's
1213
+ * reason read "()". ES5 for the legacy `mongo` shell of MongoDB before 5.0.
1214
+ */
1215
+ exports.DROP_EVERY_COLLECTION = 'try { db.getCollectionNames().forEach(function (n) { ' +
1216
+ "if (n.indexOf('system.') !== 0) db.getCollection(n).drop(); }); } " +
1217
+ "catch (e) { print('drop failed: ' + e); quit(1); }";
1218
+ /**
1219
+ * Empty the target database so the restore is exact, not a merge.
1220
+ *
1221
+ * Uses the shell the repro's own Mongo image ships (mongosh from 5.0; `mongo` before
1222
+ * that), so this works on both flavors.
1223
+ */
1224
+ async function dropDatabase(name, database, emit = events_1.nullEmit) {
1225
+ const meta = await (0, record_1.readMeta)(name);
1226
+ let shell = 'mongosh';
1227
+ try {
1228
+ // `toInt` of the tag's major part, which keeps the default `mongosh` when the tag does
1229
+ // not parse (`4x` throws, where `parseInt` would answer 4).
1230
+ const major = (0, format_1.toInt)(String(meta.mongoTag).split('.')[0] ?? '');
1231
+ if (major < 5)
1232
+ shell = 'mongo';
1233
+ }
1234
+ catch {
1235
+ /* not a version; mongosh is the default */
1236
+ }
1237
+ (0, events_1.info)(emit, `dropping database ${(0, format_1.quotedText)(database)} so the restore is exact`, {
1238
+ phase: 'restore',
1239
+ pct: 40,
1240
+ });
1241
+ // A WRITABLE HOME, or the shell's own ~/.mongodb warning fills the output in the MongoDB
1242
+ // operator's pod, whose user's home is not writable.
1243
+ const password = await mongoAuth(name);
1244
+ const [argv, input] = password === ''
1245
+ ? [['env', 'HOME=/tmp', shell, database, '--quiet', '--eval', exports.DROP_EVERY_COLLECTION], '']
1246
+ : (await Promise.resolve().then(() => __importStar(require('./kube/operator')))).shellAuthenticated(database, exports.DROP_EVERY_COLLECTION, password);
1247
+ const [rc, out] = await execCapture(name, argv, exports.PROBE_TIMEOUT, input);
1248
+ if (rc !== 0) {
1249
+ // Not fatal: --drop below still clears every collection the bundle carries.
1250
+ (0, events_1.warn)(emit, `could not drop ${(0, format_1.quotedText)(database)} first (${toolFailure(rc, out, 200)}); ` +
1251
+ 'collections absent from the bundle may survive', { phase: 'restore' });
1252
+ }
1253
+ }
1254
+ async function deriveNewName(manifest, actor = '') {
1255
+ const base = (0, naming_1.sanitize)((0, naming_1.ownerPrefix)((0, naming_1.sanitize)(`${String(manifest.repro ?? '') || 'restored'}-restored`), actor));
1256
+ let candidate = base;
1257
+ let n = 2;
1258
+ while (await (0, paths_1.exists)(candidate)) {
1259
+ candidate = `${base}-${n}`;
1260
+ n += 1;
1261
+ }
1262
+ return candidate;
1263
+ }
1264
+ /**
1265
+ * An archive that recorded its axes rebuilds from them; an older one falls back to
1266
+ * inferring them from the preset name. The preset comes from the manifest in BOTH branches.
1267
+ */
1268
+ function manifestAxes(manifest) {
1269
+ const deployment = manifest.deployment;
1270
+ return deployment !== undefined && deployment !== null && String(deployment) !== ''
1271
+ ? {
1272
+ runtime: String(manifest.runtime ?? ''),
1273
+ deployment: String(deployment),
1274
+ preset: String(manifest.preset ?? '') || 'default',
1275
+ context: String(manifest.context ?? ''),
1276
+ mongoOperator: manifest.mongo_operator === true,
1277
+ }
1278
+ : { preset: String(manifest.preset ?? '') || 'default' };
1279
+ }
1280
+ /**
1281
+ * Whether the restore lands on Kubernetes: the workspace restored in place, by `--name` or
1282
+ * by the bundle's own name, or -- as new -- the runtime the bundle recorded.
1283
+ */
1284
+ async function restoresOnKubernetes(isNew, existing, manifest) {
1285
+ if (isNew) {
1286
+ try {
1287
+ return topology.normalize(manifestAxes(manifest).runtime) === topology.KUBERNETES;
1288
+ }
1289
+ catch {
1290
+ return false; // an unknown runtime: the create refuses it by name
1291
+ }
1292
+ }
1293
+ let into = existing;
1294
+ if (into === '') {
1295
+ try {
1296
+ into = await (0, naming_1.resolveName)(String(manifest.repro ?? ''));
1297
+ }
1298
+ catch {
1299
+ return false; // nothing to restore into: said below, after the engine
1300
+ }
1301
+ }
1302
+ return (await kube(into)) !== '';
1303
+ }
1304
+ /**
1305
+ * The files a person edits (`Preset.keepFiles`: a voice lab's dialplans) from the bundle, put
1306
+ * where the create finds them: it writes a kept file only when absent, so the rebuilt
1307
+ * workspace starts with the edits it was backed up with, not the files as shipped.
1308
+ * Returns the folder when this made it, for a failed create to take away again.
1309
+ */
1310
+ async function placeKeptFiles(bundle, req) {
1311
+ if (bundle === '' || req.runtime === topology.KUBERNETES)
1312
+ return '';
1313
+ const plan = (0, create_docker_1.createPlan)({ req, emit: events_1.nullEmit });
1314
+ (0, create_docker_1.loadPreset)(plan);
1315
+ const ws = (0, paths_2.workspace)((0, naming_1.deriveFor)(req));
1316
+ const made = !pathExists(ws);
1317
+ // shortcut: one pass over the bundle per kept file, fine for a lab's few small files; read
1318
+ // them in one pass if a preset ever keeps many, or a large database makes it slow.
1319
+ for (const relative of plan.pre?.keepFiles ?? []) {
1320
+ const content = await (0, targz_1.readMember)(bundlePath(bundle), `${exports.FILES_DIR}/${relative}`);
1321
+ if (content === null)
1322
+ continue;
1323
+ const file = (0, home_1.joinPath)(ws, relative);
1324
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1325
+ fs.writeFileSync(file, content);
1326
+ }
1327
+ return made && pathExists(ws) ? ws : '';
1328
+ }
1329
+ /** Materialise a workspace matching the bundle, then leave it ready to load. */
1330
+ async function createFromManifest(target, manifest, emit, bundle = '') {
1331
+ if (await (0, paths_1.exists)(target)) {
1332
+ throw new errors_1.ConflictError(`${(0, format_1.quotedText)(target)} already exists; drop --new to restore into it, or pass ` +
1333
+ '--name for a different one');
1334
+ }
1335
+ (0, events_1.info)(emit, `creating ${(0, format_1.quotedText)(target)} at Rocket.Chat ${String(manifest.rc_version ?? '')} ` +
1336
+ `(preset ${String(manifest.preset ?? '') || 'default'})`, { phase: 'create', pct: 5 });
1337
+ const axes = manifestAxes(manifest);
1338
+ const req = (0, types_1.createReq)({
1339
+ version: String(manifest.rc_version ?? ''),
1340
+ name: target,
1341
+ ...axes,
1342
+ mongo: String(manifest.mongo_tag ?? ''),
1343
+ params: manifest.preset_params === undefined
1344
+ ? bagOf(manifest.params)
1345
+ : (0, composite_1.qualifiedParams)(bagOf(manifest.preset_params)),
1346
+ env: bagOf(manifest.env_overrides),
1347
+ // A CI build's own image: its recorded `.dev0` version names no release image.
1348
+ rcImage: String(manifest.rc_image ?? '').startsWith(`${versions_1.BUILD_IMAGE}:`)
1349
+ ? String(manifest.rc_image)
1350
+ : '',
1351
+ // WHO restores it owns it, as who creates a workspace does: from the GUI's Backups page
1352
+ // a restored workspace had no owner at all, though the audit named the admin who made it.
1353
+ actor: audit.actor(),
1354
+ wait: true,
1355
+ });
1356
+ const placed = await placeKeptFiles(bundle, req);
1357
+ try {
1358
+ await (0, create_docker_1.createRepro)(req, emit);
1359
+ }
1360
+ catch (error) {
1361
+ // Left in a folder with no record, the next workspace of that name would take the
1362
+ // files up as if someone had edited them there.
1363
+ if (placed !== '' && !(await (0, paths_1.exists)((0, naming_1.deriveFor)(req)))) {
1364
+ fs.rmSync(placed, { recursive: true, force: true });
1365
+ }
1366
+ throw error;
1367
+ }
1368
+ }
1369
+ /**
1370
+ * Safely unpack and checksum the Mongo archive before touching the target.
1371
+ *
1372
+ * GUARDED, where an early version was not: a file truncated AFTER the manifest
1373
+ * member passes `readManifest` and fails here, and an unwrapped gzip error leaves the
1374
+ * ReproError contract. Nothing is lost either way -- this is still the staging step.
1375
+ */
1376
+ async function unpackArchive(bundle, staging, manifest) {
1377
+ const truncationMessage = `${bundle} ends part-way through: it is truncated, or still being written`;
1378
+ try {
1379
+ await (0, targz_1.extractTarGz)(bundle, staging);
1380
+ }
1381
+ catch (error) {
1382
+ // Same as `readManifest`: the unsafe-entry refusal is not caught -- it is not an
1383
+ // archive error, not an OS error and not a JSON error -- so it reads the same here, with
1384
+ // no "could not be unpacked" wrapper.
1385
+ if (error instanceof targz_1.UnsafeBundleEntry)
1386
+ throw error;
1387
+ // Nor is `BadGzip` -- a trailer read past the end of the deflate data whose CRC
1388
+ // disagrees, or a second member that is not gzip: an OS error, which the unpack does
1389
+ // not catch either, so it is an unhandled error, as it always was.
1390
+ if (error instanceof targz_1.BadGzip)
1391
+ throw error;
1392
+ const message = (0, errors_1.errorText)(error);
1393
+ const gzip = (0, targz_1.gzipFailure)(error);
1394
+ if (gzip?.truncated === true) {
1395
+ throw new errors_1.ValidationError(`${truncationMessage}. Nothing has been restored. (${gzip.text})`);
1396
+ }
1397
+ throw new errors_1.ValidationError(`${bundle} could not be unpacked: ${gzip?.text ?? message}. Nothing has been restored.`);
1398
+ }
1399
+ const archive = path.join(staging, exports.ARCHIVE);
1400
+ if (!fs.existsSync(archive)) {
1401
+ throw new errors_1.ValidationError(`${bundle} has no ${exports.ARCHIVE}; is it an houston backup?`);
1402
+ }
1403
+ const expected = String(manifest.archive_sha256 ?? '');
1404
+ if (expected !== '' && sha256File(archive) !== expected) {
1405
+ throw new errors_1.ValidationError(`${bundle} is corrupt: the archive does not match its recorded checksum`);
1406
+ }
1407
+ return archive;
1408
+ }
1409
+ /**
1410
+ * Drop and load the database while Rocket.Chat is durably quiesced.
1411
+ *
1412
+ * `--numParallelCollections=1`: the default of 4 builds four collections' indexes at
1413
+ * once, and on a repro whose mongod still has Docker's default 1024 open-file limit
1414
+ * that hit EMFILE inside WiredTiger -- which PANICS and aborts mongod rather than
1415
+ * failing the one operation, leaving the restore half-applied.
1416
+ */
1417
+ async function restoreArchive({ database, emit, manifest, bundle, services, target, archive, }) {
1418
+ const sourceDb = String(manifest.database ?? '') || database_of_1.DEFAULT_DATABASE;
1419
+ // One collection at a time keeps old repros with Docker's 1024 fd limit alive.
1420
+ const tool = ['mongorestore', '--archive', '--gzip', '--drop', '--numParallelCollections=1'];
1421
+ if (sourceDb !== database) {
1422
+ tool.push(`--nsFrom=${sourceDb}.*`, `--nsTo=${database}.*`);
1423
+ (0, events_1.info)(emit, `remapping database ${(0, format_1.quotedText)(sourceDb)} -> ${(0, format_1.quotedText)(database)}`, {
1424
+ phase: 'restore',
1425
+ });
1426
+ }
1427
+ const [argv, input] = await toolCommand(target, tool);
1428
+ const quiesced = new Quiesced(target, services, emit);
1429
+ await quiesced.enter();
1430
+ let restored;
1431
+ let recoveryFailure = null;
1432
+ try {
1433
+ // --drop is NOT enough on its own: a collection that exists here but is absent
1434
+ // from the bundle survives. NOTED BEFORE THE DROP: between here and mongorestore
1435
+ // returning, the workspace has NO data, and `Quiesced` only journals
1436
+ // ROCKETCHAT_STOPPED.
1437
+ const dropNote = journal.record(journal.DATABASE_DROPPED, target, {
1438
+ bundle,
1439
+ database,
1440
+ });
1441
+ await dropDatabase(target, database, emit);
1442
+ (0, events_1.info)(emit, `restoring into database ${(0, format_1.quotedText)(database)}`, {
1443
+ phase: 'restore',
1444
+ pct: 50,
1445
+ });
1446
+ const started = performance.now();
1447
+ const [rc, out] = await execFromFile(target, argv, archive, exports.DUMP_TIMEOUT, input);
1448
+ const elapsed = (0, format_1.roundSeconds)(performance.now() - started);
1449
+ restored = { rc, out, elapsed };
1450
+ if (rc === 0) {
1451
+ journal.clear(dropNote);
1452
+ }
1453
+ }
1454
+ catch (error) {
1455
+ restored = { error };
1456
+ }
1457
+ finally {
1458
+ try {
1459
+ await quiesced.exit();
1460
+ }
1461
+ catch (recoveryError) {
1462
+ recoveryFailure = { error: recoveryError };
1463
+ }
1464
+ }
1465
+ if (recoveryFailure !== null) {
1466
+ if (!('error' in restored) || !(restored.error instanceof exec_1.Interrupted)) {
1467
+ throw recoveryFailure.error;
1468
+ }
1469
+ (0, events_1.warn)(emit, `restore was stopped; recovery also failed: ${(0, errors_1.errorText)(recoveryFailure.error)}`, {
1470
+ phase: 'restore',
1471
+ });
1472
+ }
1473
+ if ('error' in restored)
1474
+ throw restored.error;
1475
+ if (restored.rc !== 0) {
1476
+ throw new errors_1.DockerError(`mongorestore failed for ${(0, format_1.quotedText)(target)}: ${toolFailure(restored.rc, restored.out, 800)}`);
1477
+ }
1478
+ return restored.elapsed;
1479
+ }
1480
+ /** Unpack the bundle and restore the database over the running workspace. */
1481
+ async function loadFromBundle({ database, emit, manifest, bundle, services, target, }) {
1482
+ // A fresh `houston-restore-` directory, under `tempRoot()` as the backup's is.
1483
+ const staging = (0, tempdir_1.makeTempDir)('houston-restore-');
1484
+ try {
1485
+ (0, events_1.info)(emit, 'unpacking the bundle', { phase: 'restore', pct: 20 });
1486
+ const archive = await unpackArchive(bundle, staging, manifest);
1487
+ return await restoreArchive({
1488
+ database,
1489
+ emit,
1490
+ manifest,
1491
+ bundle,
1492
+ services,
1493
+ target,
1494
+ archive,
1495
+ });
1496
+ }
1497
+ finally {
1498
+ fs.rmSync(staging, { recursive: true, force: true });
1499
+ }
1500
+ }
1501
+ /**
1502
+ * The restored database holds the SOURCE's admin, so the record takes the password the
1503
+ * bundle's own record gives for it. Kept, the target's own was the password, and every login
1504
+ * answered 401: the Site_Url retarget below, `api`, `token`, `seed`. A bundle without a
1505
+ * readable record changes nothing.
1506
+ */
1507
+ async function adoptSourcePassword(target, bundle, emit) {
1508
+ let source;
1509
+ try {
1510
+ const raw = await (0, targz_1.readMember)(bundlePath(bundle), exports.RECORD);
1511
+ source = raw === null ? undefined : JSON.parse(raw.toString('utf8')).admin_password;
1512
+ }
1513
+ catch {
1514
+ return;
1515
+ }
1516
+ if (typeof source !== 'string')
1517
+ return;
1518
+ let was = '';
1519
+ const meta = await (0, record_1.updateMeta)(target, (m) => {
1520
+ was = m.adminPassword;
1521
+ m.adminPassword = source;
1522
+ });
1523
+ // A public workspace's generated password gives way to the source's shared one.
1524
+ if (source === '' && was !== '') {
1525
+ (0, events_1.warn)(emit, `${(0, format_1.quotedText)(target)} now signs in with the admin password its source was made with, ` +
1526
+ `${(0, record_1.adminPass)(meta)}: the restored database holds it. Change it in Rocket.Chat if this ` +
1527
+ 'workspace is reachable from other machines.', { phase: 'restore' });
1528
+ }
1529
+ }
1530
+ async function restoreLocked(target, bundle, manifest, emit, { allowUpgrade, force, created }) {
1531
+ const meta = await (0, record_1.readMeta)(target);
1532
+ // Into this workspace's own namespace only: by name, a restore once dropped the
1533
+ // collections of a namespace another home had made in its place.
1534
+ const context = await kube(target);
1535
+ if (context !== '') {
1536
+ await (await Promise.resolve().then(() => __importStar(require('./kube/namespace')))).requireOwnNamespace(target, { context });
1537
+ }
1538
+ const compat = (0, backup_compat_1.compatibility)(manifest, meta);
1539
+ if (!compat.allowed && !force) {
1540
+ throw new errors_1.ValidationError(compat.blocked_reason + ' Pass --force to try anyway.');
1541
+ }
1542
+ if (compat.requires_flag === 'allow_upgrade' && !(allowUpgrade || force)) {
1543
+ throw new errors_1.ValidationError(`${compat.warnings[0] ?? ''} Pass --allow-upgrade if that is what you want.`);
1544
+ }
1545
+ for (const line of compat.warnings) {
1546
+ (0, events_1.warn)(emit, line, { phase: 'restore' });
1547
+ }
1548
+ await requireMongoTools(target);
1549
+ await warnLowFdLimit(target, emit);
1550
+ const database = await (0, database_of_1.databaseOf)(target);
1551
+ const services = await rcServicesOf(target);
1552
+ const elapsed = await loadFromBundle({
1553
+ database,
1554
+ emit,
1555
+ manifest,
1556
+ bundle,
1557
+ services,
1558
+ target,
1559
+ });
1560
+ // A duration rounded to one place is always written with its decimal point, so an
1561
+ // integral one is `0.0s` / `5.0s`; `String` of the same JavaScript number printed `0s`,
1562
+ // about one real restore in ten.
1563
+ (0, events_1.info)(emit, `restored in ${(0, format_1.floatString)(elapsed)}s; waiting for Rocket.Chat`, {
1564
+ phase: 'restore',
1565
+ pct: 85,
1566
+ });
1567
+ await adoptSourcePassword(target, bundle, emit);
1568
+ const result = await (0, ready_1.waitAndFinalize)(await (0, record_1.readMeta)(target), emit, 300.0, false);
1569
+ await retargetSiteUrl(target, emit);
1570
+ (0, events_1.info)(emit, `${(0, format_1.quotedText)(target)} restored from ${path.basename(bundle)}`, {
1571
+ phase: 'done',
1572
+ pct: 100,
1573
+ });
1574
+ return {
1575
+ name: target,
1576
+ bundle,
1577
+ created,
1578
+ database,
1579
+ restore_seconds: elapsed,
1580
+ from_version: compat.from_version,
1581
+ to_version: compat.to_version,
1582
+ direction: compat.direction,
1583
+ warnings: compat.warnings,
1584
+ url: result.url ?? '',
1585
+ };
1586
+ }
1587
+ async function deleteBackup(bundle) {
1588
+ const target = bundlePath(bundle);
1589
+ // Compared UNRESOLVED on purpose: traversal is rejected by this either way, and
1590
+ // resolving would refuse a symlink sitting in the backups directory -- a reasonable
1591
+ // way to keep bundles on another disk, whose unlink removes only the link.
1592
+ if (path.dirname(target) !== backupsDir()) {
1593
+ throw new errors_1.ValidationError(`${target} is not in the managed backup directory; delete it yourself`);
1594
+ }
1595
+ try {
1596
+ fs.unlinkSync(target);
1597
+ }
1598
+ catch (error) {
1599
+ throw new errors_1.ValidationError(`could not delete ${target}: ${(0, format_1.strerrorText)(error, target)}`);
1600
+ }
1601
+ return { deleted: target };
1602
+ }
1603
+ /**
1604
+ * Point a restored workspace's Site_Url at ITSELF.
1605
+ *
1606
+ * A restore is a full mongorestore, so the bundle's `Site_Url` comes with it and
1607
+ * ROOT_URL does not override a stored setting. Rocket.Chat derives email links,
1608
+ * OAuth/SAML/OIDC redirect URIs, integration callbacks and mobile deep links from it,
1609
+ * so a restored workspace advertising the SOURCE's URL sends every one of them to the
1610
+ * wrong place. Best-effort: a restore that worked must not fail because one setting
1611
+ * could not be rewritten.
1612
+ */
1613
+ async function retargetSiteUrl(target, emit = events_1.nullEmit) {
1614
+ try {
1615
+ const meta = await (0, record_1.readMeta)(target);
1616
+ // externalUrl: a proxied workspace's restore set Site_Url to houston's loopback address.
1617
+ const want = (0, record_1.externalUrl)(meta);
1618
+ if (want === '')
1619
+ return;
1620
+ const auth = await (0, admin_1.login)(meta);
1621
+ const current = await (0, rcapi_1.getSetting)(meta.rootUrl, auth, (0, record_1.adminPass)(meta), 'Site_Url');
1622
+ if (typeof current === 'string' && current.replace(/\/+$/u, '') === want.replace(/\/+$/u, '')) {
1623
+ return;
1624
+ }
1625
+ if (await (0, rcapi_1.setSetting)(meta.rootUrl, auth, (0, record_1.adminPass)(meta), 'Site_Url', want)) {
1626
+ (0, events_1.info)(emit, `Site_Url retargeted from ${(0, format_1.quotedText)(String(current))} to ${(0, format_1.quotedText)(want)} - ` +
1627
+ `the bundle carried the source workspace's address`, { phase: 'restore' });
1628
+ }
1629
+ else {
1630
+ (0, events_1.warn)(emit, `Site_Url still reads ${(0, format_1.quotedText)(String(current))}, which is the workspace this ` +
1631
+ 'bundle came from - Rocket.Chat builds email links and OAuth ' +
1632
+ 'redirects from it. Set it in Admin > General.', { phase: 'restore' });
1633
+ }
1634
+ }
1635
+ catch (exc) {
1636
+ (0, events_1.warn)(emit, `could not check Site_Url after the restore (${(0, errors_1.errorText)(exc)}); if this ` +
1637
+ `bundle came from another workspace it still names that one`, { phase: 'restore' });
1638
+ }
1639
+ }