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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (294) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +109 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +642 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/loadtest.md +264 -0
  12. package/data/docs/troubleshooting.md +203 -0
  13. package/data/docs/upgrading.md +84 -0
  14. package/data/docs/voice.md +253 -0
  15. package/data/iam/engineer-policy.json +11 -0
  16. package/data/iam/engineer-rbac.yaml +42 -0
  17. package/data/iam/operator-policy.json +211 -0
  18. package/data/loadtest/badbot.js +22 -0
  19. package/data/loadtest/common.js +170 -0
  20. package/data/loadtest/custom.js +20 -0
  21. package/data/loadtest/journey.js +58 -0
  22. package/data/loadtest/login.js +18 -0
  23. package/data/loadtest/messages.js +13 -0
  24. package/data/loadtest/mixed.js +57 -0
  25. package/data/loadtest/read.js +12 -0
  26. package/data/loadtest/webhook.js +20 -0
  27. package/data/monitoring/houston-logs.json +98 -0
  28. package/data/monitoring/k6-loadtest.json +610 -0
  29. package/data/monitoring/mongodb-exporter.json +3007 -0
  30. package/data/monitoring/node-exporter-full.json +16114 -0
  31. package/data/monitoring/rocketchat-metrics.json +6471 -0
  32. package/data/presets/airgapped.yaml +16 -0
  33. package/data/presets/default.yaml +9 -0
  34. package/data/seed/avatar-0.png +0 -0
  35. package/data/seed/avatar-1.png +0 -0
  36. package/data/seed/avatar-2.png +0 -0
  37. package/data/seed/avatar-3.png +0 -0
  38. package/data/seed/avatar-4.png +0 -0
  39. package/data/seed/avatar-5.png +0 -0
  40. package/data/seed/avatar-6.png +0 -0
  41. package/data/seed/avatar-7.png +0 -0
  42. package/data/seed/seed-metrics.csv +3 -0
  43. package/data/seed/seed-preview.png +0 -0
  44. package/data/seed/seed-report.pdf +32 -0
  45. package/data/seed/seed-runbook.txt +3 -0
  46. package/data/skill/SKILL.md +399 -0
  47. package/data/versions.yaml +55 -0
  48. package/data/voice/freeswitch/drachtio.xml +52 -0
  49. package/data/voice/freeswitch/public.xml +87 -0
  50. package/data/webui/app.css +2003 -0
  51. package/data/webui/index.html +678 -0
  52. package/data/webui/js/api.js +561 -0
  53. package/data/webui/js/boot.js +44 -0
  54. package/data/webui/js/clusters-tail.js +1377 -0
  55. package/data/webui/js/clusters.js +896 -0
  56. package/data/webui/js/create.js +276 -0
  57. package/data/webui/js/detail.js +507 -0
  58. package/data/webui/js/jobs.js +636 -0
  59. package/data/webui/js/logs.js +634 -0
  60. package/data/webui/js/main.js +14 -0
  61. package/data/webui/js/options.js +408 -0
  62. package/data/webui/js/people.js +438 -0
  63. package/data/webui/js/perf.js +303 -0
  64. package/data/webui/js/render.js +438 -0
  65. package/data/webui/js/shared.js +3 -0
  66. package/data/webui/js/state.js +583 -0
  67. package/data/webui/js/theme.js +123 -0
  68. package/data/webui/js/util.js +584 -0
  69. package/dist/cli/app.js +593 -0
  70. package/dist/cli/capabilities.js +76 -0
  71. package/dist/cli/cell-widths.js +495 -0
  72. package/dist/cli/entry.js +10 -0
  73. package/dist/cli/error-panel.js +492 -0
  74. package/dist/cli/handlers/actor.js +84 -0
  75. package/dist/cli/handlers/https.js +614 -0
  76. package/dist/cli/handlers/prompt.js +299 -0
  77. package/dist/cli/handlers/users.js +226 -0
  78. package/dist/cli/handlers.js +3694 -0
  79. package/dist/cli/help.js +183 -0
  80. package/dist/cli/index.js +15 -0
  81. package/dist/cli/perf.js +814 -0
  82. package/dist/cli/render.js +254 -0
  83. package/dist/cli/serve.js +858 -0
  84. package/dist/cli/spec-data.js +2599 -0
  85. package/dist/cli/spec-types.js +8 -0
  86. package/dist/cli/usage-error.js +520 -0
  87. package/dist/cli/wire.js +70 -0
  88. package/dist/core/audit.js +346 -0
  89. package/dist/core/backup-compat.js +85 -0
  90. package/dist/core/backup.js +1639 -0
  91. package/dist/core/cluster.js +1398 -0
  92. package/dist/core/configimport.js +345 -0
  93. package/dist/core/data.js +267 -0
  94. package/dist/core/database-of.js +82 -0
  95. package/dist/core/diagnose.js +159 -0
  96. package/dist/core/doctor.js +1518 -0
  97. package/dist/core/edge/acme.js +338 -0
  98. package/dist/core/edge/engine.js +500 -0
  99. package/dist/core/edge/networks.js +174 -0
  100. package/dist/core/edge/paths.js +107 -0
  101. package/dist/core/edge/routes.js +251 -0
  102. package/dist/core/edge/routeyml.js +195 -0
  103. package/dist/core/edge/runtime.js +493 -0
  104. package/dist/core/edge/spec.js +305 -0
  105. package/dist/core/edge/types.js +202 -0
  106. package/dist/core/eks-docs.js +135 -0
  107. package/dist/core/eks.js +2240 -0
  108. package/dist/core/envvars.js +562 -0
  109. package/dist/core/eventlog.js +541 -0
  110. package/dist/core/firstrun.js +153 -0
  111. package/dist/core/journal.js +694 -0
  112. package/dist/core/kube/ask.js +231 -0
  113. package/dist/core/kube/capabilities.js +269 -0
  114. package/dist/core/kube/certmanager.js +452 -0
  115. package/dist/core/kube/chart.js +413 -0
  116. package/dist/core/kube/cluster.js +196 -0
  117. package/dist/core/kube/context.js +545 -0
  118. package/dist/core/kube/endpoints.js +448 -0
  119. package/dist/core/kube/exec.js +195 -0
  120. package/dist/core/kube/forward.js +732 -0
  121. package/dist/core/kube/grafana-ingress.js +110 -0
  122. package/dist/core/kube/ingress.js +218 -0
  123. package/dist/core/kube/manifests.js +361 -0
  124. package/dist/core/kube/monitoring.js +768 -0
  125. package/dist/core/kube/names.js +237 -0
  126. package/dist/core/kube/namespace.js +678 -0
  127. package/dist/core/kube/operator.js +941 -0
  128. package/dist/core/kube/probe.js +202 -0
  129. package/dist/core/kube/reachability.js +163 -0
  130. package/dist/core/kube/release.js +439 -0
  131. package/dist/core/kube/replicaset.js +180 -0
  132. package/dist/core/kube/scale.js +398 -0
  133. package/dist/core/kube/status.js +633 -0
  134. package/dist/core/kube/tools.js +238 -0
  135. package/dist/core/kube/transfer.js +173 -0
  136. package/dist/core/kube/workspace.js +423 -0
  137. package/dist/core/lifecycle/admin.js +64 -0
  138. package/dist/core/lifecycle/create-docker.js +1549 -0
  139. package/dist/core/lifecycle/create-k8s.js +960 -0
  140. package/dist/core/lifecycle/destroy.js +339 -0
  141. package/dist/core/lifecycle/inspect.js +636 -0
  142. package/dist/core/lifecycle/naming.js +298 -0
  143. package/dist/core/lifecycle/notes.js +862 -0
  144. package/dist/core/lifecycle/ownership.js +313 -0
  145. package/dist/core/lifecycle/payload.js +401 -0
  146. package/dist/core/lifecycle/ports.js +388 -0
  147. package/dist/core/lifecycle/preconditions.js +367 -0
  148. package/dist/core/lifecycle/pruning.js +551 -0
  149. package/dist/core/lifecycle/ready.js +818 -0
  150. package/dist/core/lifecycle/request.js +510 -0
  151. package/dist/core/lifecycle/seeding.js +281 -0
  152. package/dist/core/lifecycle/sizing.js +392 -0
  153. package/dist/core/lifecycle/state.js +286 -0
  154. package/dist/core/lifecycle/tlsplan.js +704 -0
  155. package/dist/core/lifecycle/types.js +232 -0
  156. package/dist/core/loadtest.js +1051 -0
  157. package/dist/core/migrate.js +612 -0
  158. package/dist/core/monitor.js +494 -0
  159. package/dist/core/postready.js +976 -0
  160. package/dist/core/promote.js +804 -0
  161. package/dist/core/rcapi.js +1336 -0
  162. package/dist/core/recovery.js +75 -0
  163. package/dist/core/runner/engine.js +394 -0
  164. package/dist/core/runner/host.js +298 -0
  165. package/dist/core/runner/locks.js +129 -0
  166. package/dist/core/runner/paths.js +173 -0
  167. package/dist/core/runner/ports.js +172 -0
  168. package/dist/core/runner/queries.js +612 -0
  169. package/dist/core/runner/record.js +563 -0
  170. package/dist/core/scaleseed.js +271 -0
  171. package/dist/core/seed-db.js +208 -0
  172. package/dist/core/sessions.js +472 -0
  173. package/dist/core/skill.js +326 -0
  174. package/dist/core/sso-identities.js +172 -0
  175. package/dist/core/sso.js +703 -0
  176. package/dist/core/tls-local.js +311 -0
  177. package/dist/core/tls.js +878 -0
  178. package/dist/core/topology.js +482 -0
  179. package/dist/core/upgrade.js +877 -0
  180. package/dist/core/users.js +739 -0
  181. package/dist/lib/audit.js +100 -0
  182. package/dist/lib/close-matches.js +238 -0
  183. package/dist/lib/compose.js +672 -0
  184. package/dist/lib/config.js +1398 -0
  185. package/dist/lib/context.js +18 -0
  186. package/dist/lib/errors.js +305 -0
  187. package/dist/lib/events.js +208 -0
  188. package/dist/lib/float-text.js +126 -0
  189. package/dist/lib/format.js +1320 -0
  190. package/dist/lib/home.js +325 -0
  191. package/dist/lib/journal.js +122 -0
  192. package/dist/lib/json-text.js +733 -0
  193. package/dist/lib/jsonout.js +382 -0
  194. package/dist/lib/lock.js +516 -0
  195. package/dist/lib/login-name.js +202 -0
  196. package/dist/lib/map-limit.js +29 -0
  197. package/dist/lib/mkdir-parents.js +90 -0
  198. package/dist/lib/mongo-kernel.js +67 -0
  199. package/dist/lib/monitoring.js +492 -0
  200. package/dist/lib/platform-name.js +59 -0
  201. package/dist/lib/presets/common.js +390 -0
  202. package/dist/lib/presets/composite.js +326 -0
  203. package/dist/lib/presets/e2ee.js +143 -0
  204. package/dist/lib/presets/email.js +172 -0
  205. package/dist/lib/presets/guides.js +27 -0
  206. package/dist/lib/presets/index.js +490 -0
  207. package/dist/lib/presets/keycloak.js +371 -0
  208. package/dist/lib/presets/ldap.js +1285 -0
  209. package/dist/lib/presets/livechat.js +220 -0
  210. package/dist/lib/presets/multi-instance.js +124 -0
  211. package/dist/lib/presets/oidc.js +161 -0
  212. package/dist/lib/presets/public.js +496 -0
  213. package/dist/lib/presets/registry.js +64 -0
  214. package/dist/lib/presets/s3-minio.js +300 -0
  215. package/dist/lib/presets/saml.js +149 -0
  216. package/dist/lib/presets/scenario.js +51 -0
  217. package/dist/lib/presets/types.js +86 -0
  218. package/dist/lib/presets/voice-pbx.js +320 -0
  219. package/dist/lib/presets/voice.js +345 -0
  220. package/dist/lib/presets/webhooks.js +182 -0
  221. package/dist/lib/redact.js +106 -0
  222. package/dist/lib/seed-options.js +68 -0
  223. package/dist/lib/seed-profiles.js +59 -0
  224. package/dist/lib/targz.js +1383 -0
  225. package/dist/lib/teammode.js +25 -0
  226. package/dist/lib/tempdir.js +162 -0
  227. package/dist/lib/unicode-tables.js +2335 -0
  228. package/dist/lib/version-spec.js +357 -0
  229. package/dist/lib/versions.js +463 -0
  230. package/dist/lib/yaml-dump.js +1361 -0
  231. package/dist/perf/baseline.js +168 -0
  232. package/dist/perf/constrain.js +299 -0
  233. package/dist/perf/k6.js +235 -0
  234. package/dist/perf/mongoprof.js +171 -0
  235. package/dist/perf/rcmetrics.js +191 -0
  236. package/dist/perf/report.js +386 -0
  237. package/dist/perf/resources.js +236 -0
  238. package/dist/perf/slo.js +111 -0
  239. package/dist/perf/timeline.js +187 -0
  240. package/dist/perf/timings.js +85 -0
  241. package/dist/perf/verdict.js +201 -0
  242. package/dist/seams/aws-cli.js +126 -0
  243. package/dist/seams/docker-cli.js +280 -0
  244. package/dist/seams/exec.js +861 -0
  245. package/dist/seams/fs/lock.js +528 -0
  246. package/dist/seams/kubectl.js +83 -0
  247. package/dist/seams/rc-http.js +921 -0
  248. package/dist/seed/apply.js +190 -0
  249. package/dist/seed/assets.js +76 -0
  250. package/dist/seed/check.js +391 -0
  251. package/dist/seed/client.js +172 -0
  252. package/dist/seed/executor.js +726 -0
  253. package/dist/seed/history.js +281 -0
  254. package/dist/seed/kinds.js +91 -0
  255. package/dist/seed/plan.js +432 -0
  256. package/dist/seed/receipt.js +339 -0
  257. package/dist/seed/repairs.js +75 -0
  258. package/dist/seed/verification.js +363 -0
  259. package/dist/seed/wording.js +248 -0
  260. package/dist/web/app.js +326 -0
  261. package/dist/web/jobs.js +510 -0
  262. package/dist/web/route-deps.js +211 -0
  263. package/dist/web/route-table.js +213 -0
  264. package/dist/web/routes/backup.js +244 -0
  265. package/dist/web/routes/clusters.js +303 -0
  266. package/dist/web/routes/data.js +187 -0
  267. package/dist/web/routes/edge.js +82 -0
  268. package/dist/web/routes/index.js +63 -0
  269. package/dist/web/routes/jobs.js +95 -0
  270. package/dist/web/routes/logs.js +297 -0
  271. package/dist/web/routes/meta.js +191 -0
  272. package/dist/web/routes/people.js +151 -0
  273. package/dist/web/routes/perf.js +95 -0
  274. package/dist/web/routes/repros.js +550 -0
  275. package/dist/web/routes/session.js +361 -0
  276. package/dist/web/routes/spa.js +198 -0
  277. package/dist/web/security.js +475 -0
  278. package/dist/web/signin.js +246 -0
  279. package/package.json +70 -32
  280. package/.eslintrc +0 -94
  281. package/.swcrc +0 -18
  282. package/dist/bin.js +0 -3
  283. package/dist/cli.js +0 -184
  284. package/dist/commands/createBranch.js +0 -194
  285. package/dist/outputCI.js +0 -59
  286. package/src/bin.js +0 -4
  287. package/src/cli.ts +0 -25
  288. package/src/commands/createBranch.ts +0 -28
  289. package/src/outputCI.ts +0 -12
  290. package/src-old/logs.js +0 -323
  291. package/src-old/md.js +0 -191
  292. package/src-old/release-table.js +0 -60
  293. package/src-old/set-version.js +0 -614
  294. package/src-old/utils.js +0 -15
@@ -0,0 +1,1051 @@
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.DEFAULT_DEPS = exports.GUI_SCENARIOS = void 0;
37
+ exports.depsWith = depsWith;
38
+ exports.loadtestReq = loadtestReq;
39
+ exports.installJournalRepairs = installJournalRepairs;
40
+ exports.repairConstraints = repairConstraints;
41
+ exports.repairMetrics = repairMetrics;
42
+ exports.rcServicesIn = rcServicesIn;
43
+ exports.loadtestTarget = loadtestTarget;
44
+ exports.short = short;
45
+ exports.loginSeedUsers = loginSeedUsers;
46
+ exports.sessionLimitWarning = sessionLimitWarning;
47
+ exports.requireComposeForPerf = requireComposeForPerf;
48
+ exports.newLoadRun = newLoadRun;
49
+ exports.putEverythingBack = putEverythingBack;
50
+ exports.armAndRun = armAndRun;
51
+ exports.loadtestVerdict = loadtestVerdict;
52
+ exports.refuseABadDuration = refuseABadDuration;
53
+ exports.loadtestPreflight = loadtestPreflight;
54
+ exports.runLoadtest = runLoadtest;
55
+ exports.runPreparedLoadtest = runPreparedLoadtest;
56
+ exports.capacityReq = capacityReq;
57
+ exports.newCapacitySearch = newCapacitySearch;
58
+ exports.stepFloats = stepFloats;
59
+ exports.capacityVerdict = capacityVerdict;
60
+ exports.capacityPreflight = capacityPreflight;
61
+ exports.putTheWorkspaceBack = putTheWorkspaceBack;
62
+ exports.searchForCapacity = searchForCapacity;
63
+ exports.runCapacity = runCapacity;
64
+ exports.runPreparedCapacity = runPreparedCapacity;
65
+ /**
66
+ * Load-test service for the web GUI (a focused subset of the CLI `loadtest`).
67
+ *
68
+ * Supports the common options — scenario, vus, duration, users, slo, constrain, diag, stats,
69
+ * live — with the SAME safety-critical restore-in-`finally` as the CLI (rate limiter,
70
+ * Prometheus setting, resource caps, and the users.json token file are always
71
+ * restored/cleaned up, even on failure). Returns a structured result.
72
+ *
73
+ * The CLI reuses the same transaction through the prepared-run seams below, adding its
74
+ * ramp/spike/custom controls and post-run artifacts without duplicating restoration.
75
+ *
76
+ * THE DEPENDENCY BAG. The private steps take `constrain`, `k6`, `mongoprof`, the metrics
77
+ * sampler and the analysis modules as PARAMETERS, so a spec passes stand-ins through. This
78
+ * module keeps that shape as `LoadtestDeps`, which is also what lets a spec drive the
79
+ * restore ordering with scripted modules instead of containers.
80
+ */
81
+ const fs = __importStar(require("node:fs/promises"));
82
+ const config = __importStar(require("../lib/config"));
83
+ const errors_1 = require("../lib/errors");
84
+ const events_1 = require("../lib/events");
85
+ const home_1 = require("../lib/home");
86
+ const format_1 = require("../lib/format");
87
+ const monitoring = __importStar(require("../lib/monitoring"));
88
+ const constrainModule = __importStar(require("../perf/constrain"));
89
+ const k6Module = __importStar(require("../perf/k6"));
90
+ const mongoprofModule = __importStar(require("../perf/mongoprof"));
91
+ const rcmetricsModule = __importStar(require("../perf/rcmetrics"));
92
+ const resourcesModule = __importStar(require("../perf/resources"));
93
+ const sloModule = __importStar(require("../perf/slo"));
94
+ const timelineModule = __importStar(require("../perf/timeline"));
95
+ const verdictModule = __importStar(require("../perf/verdict"));
96
+ const exec_1 = require("../seams/exec");
97
+ const admin_1 = require("./lifecycle/admin");
98
+ const inspect_1 = require("./lifecycle/inspect");
99
+ const naming_1 = require("./lifecycle/naming");
100
+ const preconditions_1 = require("./lifecycle/preconditions");
101
+ const journal = __importStar(require("./journal"));
102
+ const rcapi_1 = require("./rcapi");
103
+ const record_1 = require("./runner/record");
104
+ const paths = __importStar(require("./runner/paths"));
105
+ const queries_1 = require("./runner/queries");
106
+ const wording_1 = require("../seed/wording");
107
+ const topology = __importStar(require("./topology"));
108
+ exports.GUI_SCENARIOS = Object.freeze([
109
+ 'messages',
110
+ 'login',
111
+ 'read',
112
+ 'mixed',
113
+ 'journey',
114
+ 'badbot',
115
+ ]);
116
+ exports.DEFAULT_DEPS = {
117
+ constrain: constrainModule,
118
+ k6: k6Module,
119
+ mongoprof: mongoprofModule,
120
+ monitoring,
121
+ resources: resourcesModule,
122
+ rcmetrics: rcmetricsModule,
123
+ slo: sloModule,
124
+ timeline: timelineModule,
125
+ verdict: verdictModule,
126
+ };
127
+ /** The default modules, any of them replaced by `overrides`. */
128
+ function depsWith(overrides = {}) {
129
+ return { ...exports.DEFAULT_DEPS, ...overrides };
130
+ }
131
+ /**
132
+ * A cap that could not be applied: the job's DockerError, or the CLI's plain error
133
+ * `could not apply --constrain: <why>` -- REPRO_ERROR, exit 1, and the flag's own name.
134
+ */
135
+ function constrainFailure(cli, exc) {
136
+ return cli === null
137
+ ? new errors_1.DockerError(`could not apply constrain: ${(0, errors_1.errorText)(exc)}`)
138
+ : new errors_1.ReproError(`could not apply --constrain: ${(0, errors_1.errorText)(exc)}`);
139
+ }
140
+ /** A request with the established defaults filled in. */
141
+ function loadtestReq(values) {
142
+ return {
143
+ scenario: 'messages',
144
+ vus: 10,
145
+ duration: '30s',
146
+ usersN: 10,
147
+ slo: '',
148
+ constrain: '',
149
+ diag: true,
150
+ stats: false,
151
+ live: false,
152
+ slowms: 100,
153
+ ramp: null,
154
+ spike: null,
155
+ extraEnv: null,
156
+ quiet: true,
157
+ setupWarnings: false,
158
+ ...values,
159
+ };
160
+ }
161
+ /** Restore the profiler a killed run left armed — the note's own kind, not this file's. */
162
+ function installJournalRepairs() {
163
+ journal.registerRepair(journal.CONSTRAINTS_APPLIED, repairConstraints);
164
+ journal.registerRepair(journal.RC_METRICS_ON, repairMetrics);
165
+ }
166
+ async function repairConstraints(entry, _emit, _login) {
167
+ const applied = (Array.isArray(entry.detail.applied) ? entry.detail.applied : []).map((a) => ({ ...a }));
168
+ // `not restore(...)`, where restore returns a PROBLEM LIST: an array is always truthy
169
+ // here, so `!restore(...)` would report every failed restore as repaired.
170
+ return (await constrainModule.restore(applied)).length === 0;
171
+ }
172
+ async function repairMetrics(entry, _emit, login_) {
173
+ if (login_ === null || login_ === undefined)
174
+ return false;
175
+ const meta = await (0, record_1.readMeta)(entry.workspace);
176
+ const auth = await login_(meta);
177
+ if (auth === null || auth === undefined)
178
+ return false;
179
+ return await (0, rcapi_1.setSetting)(meta.rootUrl, auth, (0, record_1.adminPass)(meta), monitoring.RC_METRICS_SETTING, false);
180
+ }
181
+ function bagOf(value) {
182
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
183
+ return {};
184
+ return value;
185
+ }
186
+ function rcServicesIn(doc) {
187
+ return Object.keys(bagOf(doc.services)).filter((service) => service === 'rocketchat' || service.startsWith('rocketchat-'));
188
+ }
189
+ function loadtestTarget(doc) {
190
+ const svcs = bagOf(doc.services);
191
+ if ('traefik' in svcs)
192
+ return 'http://traefik:80';
193
+ const rc = rcServicesIn(doc);
194
+ if (rc.includes('rocketchat'))
195
+ return 'http://rocketchat:3000';
196
+ return rc.length > 0 ? `http://${rc[0]}:3000` : 'http://rocketchat:3000';
197
+ }
198
+ function short(full, reproName) {
199
+ const prefix = `${config.PROJECT_PREFIX}${reproName}-`;
200
+ const s = full.startsWith(prefix) ? full.slice(prefix.length) : full;
201
+ return s.replace(/-\d+$/u, '');
202
+ }
203
+ /**
204
+ * Log in the seeded users so VUs carry real identity.
205
+ *
206
+ * This once posted to `/api/v1/login` directly — one of the three recorded `rcapi`
207
+ * bypasses — and now reaches the same endpoint through `rcapi`, which is where the
208
+ * dependency policy says HTTP lives.
209
+ */
210
+ async function loginSeedUsers(rootUrl, count) {
211
+ const users = [];
212
+ for (let i = 0; i < count; i += 1) {
213
+ const uname = (0, wording_1.username)(i);
214
+ let entry;
215
+ try {
216
+ entry = await (0, rcapi_1.loginUser)(rootUrl, uname);
217
+ }
218
+ catch {
219
+ break;
220
+ }
221
+ if (entry !== null && (0, format_1.isTruthy)(entry.authToken)) {
222
+ users.push({
223
+ username: uname,
224
+ password: uname,
225
+ token: entry.authToken,
226
+ uid: entry.userId,
227
+ });
228
+ }
229
+ }
230
+ return users;
231
+ }
232
+ /**
233
+ * The warning for `journey` past 50 VUs per user, or null.
234
+ *
235
+ * Each journey iteration logs its VU in afresh (as the VU's seeded user, or the admin) and
236
+ * uses that session to its last step. Rocket.Chat keeps a user's newest 50 sessions and
237
+ * deletes the rest, so past 50 VUs per user it deletes sessions still in use, and their
238
+ * later steps fail with 4xx that are not the server's.
239
+ */
240
+ function sessionLimitWarning(scenario, vus, users) {
241
+ const most = 50 * Math.max(1, users);
242
+ if (scenario !== 'journey' || vus <= most)
243
+ return null;
244
+ const who = users > 0 ? `${String(users)} seeded user${users === 1 ? '' : 's'}` : 'the admin';
245
+ return (`journey at ${String(vus)} VUs is more than ${String(most)}, 50 per user for ${who}: ` +
246
+ `Rocket.Chat keeps 50 sessions per user and deletes the older ones while they are ` +
247
+ `still in use, so some steps fail with 4xx that are not the server's. Use fewer VUs, ` +
248
+ `or seed more users (houston seed --profile standard makes 20) and use them all`);
249
+ }
250
+ /**
251
+ * Refuse a load test or capacity search on a Kubernetes workspace, and say why.
252
+ *
253
+ * Not merely "unimplemented". The number would be WRONG in a way that reads as a result:
254
+ * a Kubernetes workspace is reached through `kubectl port-forward`, which is a single
255
+ * userspace relay — it saturates, serialises and drops connections far below what
256
+ * Rocket.Chat itself would, so every figure the run produced would be a measurement of
257
+ * the forward. A plausible wrong number is the one failure mode this tool cannot afford
258
+ * in a report a support engineer sends to a customer.
259
+ */
260
+ async function requireComposeForPerf(name, operation) {
261
+ const target = await (0, naming_1.resolveName)(name);
262
+ if ((await topology.ofRepro(target)) !== topology.KUBERNETES) {
263
+ return;
264
+ }
265
+ let version = '';
266
+ try {
267
+ version = (await (0, record_1.readMeta)(target)).rcVersion;
268
+ }
269
+ catch {
270
+ // the refusal matters more than the example
271
+ }
272
+ throw new errors_1.ValidationError(`${operation} is Compose-only. A Kubernetes workspace is reached through a ` +
273
+ '`kubectl port-forward`, which is a single userspace relay: it saturates and ' +
274
+ 'drops connections long before Rocket.Chat does, so every number this ' +
275
+ 'produced would be measuring the forward. Run it against a Compose ' +
276
+ `workspace on the same version instead — \`houston up --version ` +
277
+ `${version || '<version>'} --name perf\` — where the client talks to the ` +
278
+ 'container directly.');
279
+ }
280
+ function newLoadRun() {
281
+ return {
282
+ appliedConstraints: [],
283
+ limiterWasOff: true,
284
+ limiterNote: '',
285
+ constrainNote: '',
286
+ metricsNote: '',
287
+ mongoNote: '',
288
+ metricsChanged: false,
289
+ mongoPrior: null,
290
+ sampler: null,
291
+ mon: null,
292
+ resources: null,
293
+ summary: null,
294
+ rcmReport: {},
295
+ sinceMs: 0,
296
+ restartsBefore: -1,
297
+ };
298
+ }
299
+ /**
300
+ * Put a setting back, and say whether it went back.
301
+ *
302
+ * `setSetting` answers false rather than throwing, and that answer was dropped: the warning
303
+ * in the `catch` could never fire, and the journal note was cleared either way. The login,
304
+ * mixed and journey scenarios log the admin in hundreds of times, and Rocket.Chat keeps 50
305
+ * login tokens (MAX_RESUME_LOGIN_TOKENS) -- so the session this run started with was
306
+ * pruned before it ended, the restore was refused, and the rate limiter stayed OFF with
307
+ * nothing said. Every later run then read it as "was off" and left it. A refused restore
308
+ * logs in afresh and tries once more.
309
+ */
310
+ async function restoreSetting(m, auth, settingId, value) {
311
+ if (await (0, rcapi_1.setSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), settingId, value))
312
+ return true;
313
+ let fresh;
314
+ try {
315
+ fresh = await (0, admin_1.login)(m);
316
+ }
317
+ catch (error) {
318
+ if (error instanceof exec_1.Interrupted)
319
+ throw error;
320
+ return false;
321
+ }
322
+ return await (0, rcapi_1.setSetting)(m.rootUrl, fresh, (0, record_1.adminPass)(m), settingId, value);
323
+ }
324
+ /** Undo every side effect this run armed, whichever way it ended. */
325
+ async function putEverythingBack({ auth, cli = null, deps, emit, m, run, }) {
326
+ // The job's event, or the restore's warning in the CLI's words.
327
+ const restoreWarning = (job, words) => {
328
+ if (cli === null)
329
+ (0, events_1.warn)(emit, job, { phase: 'restore' });
330
+ else
331
+ cli.warn(words);
332
+ };
333
+ // users.json holds live seeded-user auth tokens — delete it FIRST, so no later restore
334
+ // step failing can leave credentials on disk.
335
+ await fs.rm((0, home_1.joinPath)(paths.workspace(m.name), 'loadtest', 'users.json'), { force: true });
336
+ if (run.sampler !== null) {
337
+ run.rcmReport = await run.sampler.stop();
338
+ }
339
+ if (run.mon !== null) {
340
+ run.resources = await run.mon.stop();
341
+ }
342
+ if (!run.limiterWasOff) {
343
+ if (await restoreSetting(m, auth, config.RC_RATE_LIMITER_SETTING, true)) {
344
+ journal.clear(run.limiterNote);
345
+ }
346
+ else {
347
+ restoreWarning('could not restore the API rate limiter setting', ' ⚠ could not restore the API rate limiter setting');
348
+ }
349
+ }
350
+ if (run.metricsChanged) {
351
+ if (await restoreSetting(m, auth, deps.monitoring.RC_METRICS_SETTING, false)) {
352
+ journal.clear(run.metricsNote);
353
+ }
354
+ else {
355
+ restoreWarning('could not restore the Prometheus metrics setting', ' ⚠ could not restore the Prometheus metrics setting');
356
+ }
357
+ }
358
+ if (run.mongoPrior !== null) {
359
+ // Wrapped like its neighbours: an exception here would skip the resource-cap restore
360
+ // below and leave the containers capped.
361
+ try {
362
+ await deps.mongoprof.stop(m.name, run.mongoPrior);
363
+ journal.clear(run.mongoNote);
364
+ }
365
+ catch {
366
+ restoreWarning('could not restore the Mongo profiler level', ' ⚠ could not restore the Mongo profiler level');
367
+ }
368
+ }
369
+ // CLEARED AFTER, like its three siblings above. Clearing first threw away the note on
370
+ // the one path it exists for: `restore` RETURNS problems rather than raising, and the
371
+ // loop below is there to report them — so a failed restore left the containers capped
372
+ // with the record of their prior values already deleted, which is precisely what
373
+ // CONSTRAINTS_APPLIED carries them for.
374
+ const capProblems = await deps.constrain.restore(run.appliedConstraints);
375
+ for (const problem of capProblems) {
376
+ restoreWarning(`could not restore resource limits - ${problem}`, ` ⚠ could not restore resource limits — ${problem}`);
377
+ }
378
+ if (capProblems.length === 0) {
379
+ journal.clear(run.constrainNote);
380
+ }
381
+ }
382
+ /** Constrain, disable the limiter, turn the diagnostics on, and run k6. */
383
+ async function armAndRun({ auth, cli = null, deps, emit, m, perService, rcServices, req, run, target, token, users, }) {
384
+ if (Object.keys(perService).length > 0) {
385
+ try {
386
+ run.appliedConstraints = await deps.constrain.apply(m.name, perService);
387
+ }
388
+ catch (exc) {
389
+ // `constrain.apply` signals its own failures with a plain Error, and those are what
390
+ // this answers; nothing else is expected from it, so wrapping every failure is no
391
+ // broader a net than the one intended. A Ctrl-C is not one of them.
392
+ if (exc instanceof exec_1.Interrupted)
393
+ throw exc;
394
+ throw constrainFailure(cli, exc);
395
+ }
396
+ // NOTED WITH THE PRIOR VALUES, so a killed run can be undone exactly rather than
397
+ // reset to "unlimited". `restore` runs in the `finally` below; this is what covers
398
+ // the run that never reaches it.
399
+ run.constrainNote = journal.record(journal.CONSTRAINTS_APPLIED, m.name, {
400
+ applied: run.appliedConstraints.map((a) => ({ ...a })),
401
+ });
402
+ run.restartsBefore = await (0, queries_1.rcRestartCount)(m.name);
403
+ if (cli === null) {
404
+ (0, events_1.info)(emit, `constrained: ${deps.constrain.human(perService)} (restored after)`, {
405
+ phase: 'k6',
406
+ });
407
+ }
408
+ else {
409
+ cli.constrained?.(deps.constrain.human(perService));
410
+ }
411
+ }
412
+ run.limiterWasOff =
413
+ (await (0, rcapi_1.getSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), config.RC_RATE_LIMITER_SETTING)) === false;
414
+ if (!run.limiterWasOff) {
415
+ // JOURNALLED BEFORE IT IS TURNED OFF. The `finally` below turns it back on, and a
416
+ // daemon thread killed by a restart or an OOM runs no `finally` at all — so the note
417
+ // on disk is what survives to say the API rate limiter is off on this workspace and
418
+ // nobody meant to leave it that way.
419
+ run.limiterNote = journal.record(journal.RATE_LIMITER_OFF, m.name);
420
+ const changed = await (0, rcapi_1.setSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), config.RC_RATE_LIMITER_SETTING, false);
421
+ if (!changed) {
422
+ // NEVER TURNED OFF, so there is nothing to put back: restoring it anyway now says
423
+ // "could not restore" about a setting this run never changed.
424
+ run.limiterWasOff = true;
425
+ journal.clear(run.limiterNote);
426
+ run.limiterNote = '';
427
+ if (req.setupWarnings) {
428
+ const words = 'could not disable the API rate limiter — results may be throttled (429s)';
429
+ if (cli === null)
430
+ (0, events_1.warn)(emit, words, { phase: 'k6' });
431
+ else
432
+ cli.warn(` ⚠ ${words}`);
433
+ }
434
+ }
435
+ }
436
+ // The banner: after the caps and the limiter, before the diagnostics are armed.
437
+ cli?.armed?.();
438
+ if (req.diag) {
439
+ if ((await (0, rcapi_1.getSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), deps.monitoring.RC_METRICS_SETTING)) !== true) {
440
+ // Journalled like its two neighbours. Both of these are restored in the `finally`
441
+ // below, which is precisely the block a SIGKILL does not run — so without a note a
442
+ // killed --diag run leaves Rocket.Chat's metrics endpoint open and the profiler
443
+ // armed, with nothing on disk saying so.
444
+ run.metricsNote = journal.record(journal.RC_METRICS_ON, m.name);
445
+ run.metricsChanged = await (0, rcapi_1.setSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), deps.monitoring.RC_METRICS_SETTING, true);
446
+ }
447
+ run.mongoPrior = await deps.mongoprof.start(m.name, req.slowms);
448
+ if (run.mongoPrior === null && req.setupWarnings) {
449
+ const words = 'Mongo slow-query capture unavailable (profiler could not be enabled)';
450
+ if (cli === null)
451
+ (0, events_1.warn)(emit, words, { phase: 'k6' });
452
+ else
453
+ cli.warn(` ⚠ ${words}`);
454
+ }
455
+ else if (run.mongoPrior !== null) {
456
+ // Carrying the PRIOR level, because `mongoprof.stop` restores to a value rather
457
+ // than to off, and a workspace that already had profiling on must keep it. Same
458
+ // distinction CONSTRAINTS_APPLIED already draws.
459
+ run.mongoNote = journal.record(journal.MONGO_PROFILER_ON, m.name, {
460
+ prior: run.mongoPrior,
461
+ });
462
+ }
463
+ }
464
+ run.mon = req.stats ? new deps.resources.ResourceMonitor(m.name).start() : null;
465
+ run.sinceMs = Date.now();
466
+ if (req.diag) {
467
+ run.sampler = new deps.rcmetrics.RCMetricsSampler(m.name, rcServices).start();
468
+ }
469
+ // The job's narration only: the CLI announced its own banner above, and an event would
470
+ // reach the event log's sink even with no emitter.
471
+ if (cli === null) {
472
+ const who = users.length > 0 ? `${String(users.length)} seeded users` : 'admin token';
473
+ (0, events_1.info)(emit, `running k6: ${req.scenario} @ ${String(req.vus)} VUs for ${req.duration} -> ${target}` +
474
+ ` (${who})`, { phase: 'k6' });
475
+ }
476
+ run.summary = await deps.k6.run(m.name, req.scenario, {
477
+ vus: req.vus,
478
+ duration: req.duration,
479
+ ramp: req.ramp,
480
+ token,
481
+ uid: auth.userId,
482
+ target,
483
+ users: users.length > 0 ? [...users] : null,
484
+ password: (0, record_1.adminPass)(m),
485
+ ...(req.extraEnv === null ? {} : { extraEnv: req.extraEnv }),
486
+ quiet: req.quiet,
487
+ timeline: req.diag || req.spike !== null,
488
+ spike: req.spike,
489
+ live: req.live,
490
+ });
491
+ }
492
+ /**
493
+ * What the run proved: the SLO, the diagnosis, and where to look at it.
494
+ *
495
+ * `timeline` and `mongo` are read from the workspace only here, after the run has been
496
+ * put back, so the point file that k6 wrote is consumed exactly once.
497
+ */
498
+ async function loadtestVerdict({ cli = null, deps, emit, m, req, rules, run, }) {
499
+ const mongoSlow = req.diag && run.mongoPrior !== null ? await deps.mongoprof.collect(m.name, run.sinceMs) : null;
500
+ let tl = null;
501
+ if (req.diag || req.spike !== null) {
502
+ const points = (0, home_1.joinPath)(paths.workspace(m.name), 'loadtest', 'points.json');
503
+ tl = deps.timeline.parse(points);
504
+ await fs.rm(points, { force: true });
505
+ }
506
+ const sloResults = rules.length > 0 ? deps.slo.evaluate(rules, run.summary ?? {}) : [];
507
+ // An EMPTY resources object counts as none, and that is a real case: the sampler
508
+ // ran but the workspace had no container to sample. Reporting `{}` where the established
509
+ // answer is null would say "we measured nothing" in a different shape.
510
+ const shortStats = run.resources !== null && Object.keys(run.resources).length > 0
511
+ ? Object.fromEntries(Object.entries(run.resources).map(([key, value]) => [short(key, m.name), value]))
512
+ : null;
513
+ const verdictLines = req.diag
514
+ ? deps.verdict.analyze(run.summary ?? {}, {
515
+ rcmetrics: Object.keys(run.rcmReport).length > 0 ? run.rcmReport : null,
516
+ // The collectors' interfaces carry no index signature, which is a TypeScript
517
+ // shape rather than a data difference: both are plain JSON objects on the wire.
518
+ mongo: mongoSlow,
519
+ resources: shortStats,
520
+ timeline: tl,
521
+ })
522
+ : [];
523
+ const passed = sloResults.length === 0 || sloResults.every((r) => r.ok);
524
+ // A CAP THAT KILLED IT, said. Under a memory cap the kernel can restart Rocket.Chat while
525
+ // the load runs, and the run then measures the restart -- it reported 100% errors as a
526
+ // load result with no word about why.
527
+ if (run.restartsBefore >= 0) {
528
+ const restarts = (await (0, queries_1.rcRestartCount)(m.name)) - run.restartsBefore;
529
+ if (restarts > 0) {
530
+ const words = `Rocket.Chat restarted ${String(restarts)}x during the run under --constrain: ` +
531
+ 'these numbers are its restart, not its load. Give it more memory.';
532
+ verdictLines.unshift(words);
533
+ if (cli === null)
534
+ (0, events_1.warn)(emit, words, { phase: 'k6' });
535
+ else
536
+ cli.warn(` ⚠ ${words}`);
537
+ }
538
+ }
539
+ const grafana = req.live ? (0, inspect_1.grafanaUrlOf)(m) : null;
540
+ const summary = run.summary ?? {};
541
+ // The job's closing event. The CLI renders its own result, and the event would reach the
542
+ // event log's sink with `passed` redacted as a secret.
543
+ if (cli === null) {
544
+ (0, events_1.info)(emit, `done: p95 ${(0, format_1.formatFixed)(Number(summary.p95 ?? 0), 0)}ms at ` +
545
+ `${(0, format_1.formatFixed)(Number(summary.rps ?? 0), 1)} req/s, ` +
546
+ `${(0, format_1.formatFixed)(Number(summary.error_rate ?? 0) * 100, 2)}% errors` +
547
+ (passed ? '' : ' - SLO FAIL'),
548
+ // The detail is one key named `data` inside the event's data, so it nests; the wire
549
+ // keeps that shape.
550
+ { phase: 'done', data: { data: { passed } } });
551
+ }
552
+ return { grafana, mongoSlow, passed, shortStats, sloResults, tl, verdictLines };
553
+ }
554
+ /**
555
+ * A duration k6 takes: a Go duration (`30s`, `1m30s`, `500ms`, `1.5h`) or a bare number of
556
+ * milliseconds. Checked here because houston passed any word to k6, which started and then
557
+ * failed: `loadtest --duration forever` ran, exited 1 and said why only in k6's own output.
558
+ */
559
+ function refuseABadDuration(value, flag) {
560
+ if (/^(\d+(\.\d+)?|(\d+(\.\d+)?(ns|us|µs|ms|s|m|h))+)$/u.test(value.trim()))
561
+ return;
562
+ throw new errors_1.ValidationError(`bad ${flag}: '${value}' is not a duration (e.g. 30s, 2m, 1m30s)`);
563
+ }
564
+ async function loadtestPreflight(deps, req) {
565
+ await (0, preconditions_1.requireDocker)();
566
+ if (!exports.GUI_SCENARIOS.includes(req.scenario)) {
567
+ throw new errors_1.ValidationError(`scenario must be one of ${exports.GUI_SCENARIOS.join(', ')}`);
568
+ }
569
+ if (req.vus < 1) {
570
+ throw new errors_1.ValidationError('vus must be >= 1');
571
+ }
572
+ refuseABadDuration(req.duration, 'duration');
573
+ // Refused here rather than at the top, so a bad --scenario is still named before a bad
574
+ // --name: the request's own shape is cheaper to check and is what the caller most
575
+ // likely got wrong. But BEFORE `readCompose`, which threw a bare ENOENT
576
+ // naming a compose file a Kubernetes workspace does not have — outside the ReproError
577
+ // contract, so the GUI answered 500 to a request that is merely unsupported. The same
578
+ // defect the env tab had, in a second place.
579
+ await requireComposeForPerf(req.name, 'loadtest');
580
+ const m = await (0, record_1.readMeta)(await (0, naming_1.resolveName)(req.name));
581
+ const doc = await (0, record_1.readCompose)(m.name);
582
+ const target = loadtestTarget(doc);
583
+ const rcServices = rcServicesIn(doc);
584
+ const services = rcServices.length > 0 ? rcServices : ['rocketchat'];
585
+ if (req.live) {
586
+ if (!(0, format_1.isTruthy)(bagOf(m.extra).monitoring)) {
587
+ throw new errors_1.ValidationError('live streaming needs monitoring attached first');
588
+ }
589
+ const promCmd = bagOf(bagOf(doc.services).prometheus).command;
590
+ if (!(Array.isArray(promCmd) ? promCmd : []).some((c) => String(c).includes('remote-write-receiver'))) {
591
+ throw new errors_1.ValidationError('live needs Prometheus with remote-write - re-attach monitoring');
592
+ }
593
+ }
594
+ let rules;
595
+ try {
596
+ rules = (0, format_1.isTruthy)(req.slo) ? deps.slo.parse(req.slo) : [];
597
+ }
598
+ catch (exc) {
599
+ throw new errors_1.ValidationError(`bad slo: ${(0, errors_1.errorText)(exc)}`);
600
+ }
601
+ let perService = {};
602
+ if (req.constrain) {
603
+ try {
604
+ perService = deps.constrain.resolveServices(deps.constrain.parse(req.constrain), Object.keys(bagOf(doc.services)));
605
+ }
606
+ catch (exc) {
607
+ throw new errors_1.ValidationError(`bad constrain: ${(0, errors_1.errorText)(exc)}`);
608
+ }
609
+ }
610
+ let auth;
611
+ let token;
612
+ try {
613
+ auth = await (0, admin_1.login)(m);
614
+ token = await (0, rcapi_1.generatePat)(m.rootUrl, auth, (0, record_1.adminPass)(m), {
615
+ tokenName: 'houston-loadtest',
616
+ bypass2fa: true,
617
+ workspace: m.name,
618
+ });
619
+ }
620
+ catch (exc) {
621
+ throw new errors_1.NotReadyError(`could not authenticate (ready?): ${(0, errors_1.errorText)(exc)}`);
622
+ }
623
+ const users = req.usersN > 0 ? await loginSeedUsers(m.rootUrl, req.usersN) : [];
624
+ return { auth, m, perService, rcServices: services, rules, target, token, users };
625
+ }
626
+ async function runLoadtest(req, emit = events_1.nullEmit, deps = exports.DEFAULT_DEPS) {
627
+ const prepared = await loadtestPreflight(deps, req);
628
+ const { m, perService, target, users } = prepared;
629
+ const { run, verdict } = await runPreparedLoadtest(req, prepared, emit, deps);
630
+ const { grafana, mongoSlow, passed, shortStats, sloResults, tl, verdictLines } = verdict;
631
+ return {
632
+ ctx: {
633
+ name: m.name,
634
+ scenario: req.scenario,
635
+ vus: req.vus,
636
+ duration: req.duration,
637
+ users: users.length,
638
+ target,
639
+ constrained: Object.keys(perService).length > 0 ? deps.constrain.human(perService) : '',
640
+ },
641
+ summary: run.summary,
642
+ slo: sloResults,
643
+ passed,
644
+ verdict: verdictLines,
645
+ diag: req.diag ? { rcmetrics: run.rcmReport, mongo: mongoSlow, timeline: tl } : null,
646
+ resources: shortStats !== null
647
+ ? Object.fromEntries(Object.entries(shortStats).map(([key, value]) => [key, { ...value }]))
648
+ : null,
649
+ grafana_url: grafana,
650
+ };
651
+ }
652
+ async function runPreparedLoadtest(req, prepared, emit = events_1.nullEmit, deps = exports.DEFAULT_DEPS, cli = null) {
653
+ const { auth, m, perService, rcServices, rules, target, token, users } = prepared;
654
+ const shape = req.spike ?? req.ramp ?? '';
655
+ const peak = shape !== '' ? Math.max(...shape.split(':').map(Number)) : req.vus;
656
+ const words = sessionLimitWarning(req.scenario, peak, users.length);
657
+ if (words !== null) {
658
+ if (cli === null)
659
+ (0, events_1.warn)(emit, words, { phase: 'k6' });
660
+ else
661
+ cli.warn(` ⚠ ${words}`);
662
+ }
663
+ const run = newLoadRun();
664
+ // UNWOUND by a Ctrl-C: the wait on k6 raises Interrupted and the restore runs as cleanup,
665
+ // so what the run changed goes back as it does when the run fails. Without the unwind, a
666
+ // Ctrl-C ended the process with nothing put back.
667
+ await (0, exec_1.unwindsOnInterrupt)(async () => {
668
+ try {
669
+ await armAndRun({
670
+ auth,
671
+ cli,
672
+ deps,
673
+ emit,
674
+ m,
675
+ perService,
676
+ rcServices,
677
+ req,
678
+ run,
679
+ target,
680
+ token,
681
+ users,
682
+ });
683
+ }
684
+ catch (exc) {
685
+ if (exc instanceof exec_1.Interrupted)
686
+ throw exc;
687
+ // The ReproError taxonomy passes through and anything else is converted; every
688
+ // failure `armAndRun` can raise on its own is a bad-input-or-engine one, and the
689
+ // deliberate refusals above keep their own types.
690
+ if (exc instanceof errors_1.ReproError)
691
+ throw exc;
692
+ if (cli === null)
693
+ throw new errors_1.DockerError((0, errors_1.errorText)(exc));
694
+ // The CLI's plain error: k6's unreadable or missing summary is REPRO_ERROR, exit 1. A
695
+ // request that failed is a transport failure, which is not converted, so it goes on to
696
+ // the contract's last line as it is.
697
+ if (exc instanceof Error && exc.name === 'RequestFailed')
698
+ throw exc;
699
+ throw new errors_1.ReproError((0, errors_1.errorText)(exc));
700
+ }
701
+ finally {
702
+ await (0, exec_1.cleanup)(async () => {
703
+ await putEverythingBack({ auth, cli, deps, emit, m, run });
704
+ });
705
+ }
706
+ });
707
+ const verdict = await loadtestVerdict({ cli, deps, emit, m, req, rules, run });
708
+ return { run, verdict };
709
+ }
710
+ function capacityReq(values) {
711
+ return {
712
+ scenario: 'journey',
713
+ usersN: 10,
714
+ slo: 'p95=500ms,error=2%',
715
+ start: 10,
716
+ maxVus: 640,
717
+ stepDuration: '20s',
718
+ constrain: '',
719
+ ...values,
720
+ };
721
+ }
722
+ function newCapacitySearch() {
723
+ return {
724
+ applied: [],
725
+ limiterWasOff: true,
726
+ limiterNote: '',
727
+ constrainNote: '',
728
+ metricsNote: '',
729
+ metricsChanged: false,
730
+ steps: [],
731
+ lastPass: null,
732
+ firstFail: null,
733
+ };
734
+ }
735
+ /**
736
+ * The members of each capacity step that are held as FLOATS: `lag_max_s` always (`0.0`,
737
+ * or an RC metric read as a float), and `rps`, `p95` or `error_rate` where k6's summary had
738
+ * no such key and the row took the default `0.0`. A value the
739
+ * summary did carry is left as the summary spelled it.
740
+ *
741
+ * Kept BESIDE the row rather than in it, because the row is also the GUI job's result, which
742
+ * the web's serializer writes: only the CLI's envelope writer knows a `JsonFloat`.
743
+ */
744
+ const STEP_FLOATS = new WeakMap();
745
+ function stepFloats(row) {
746
+ return STEP_FLOATS.get(row) ?? [];
747
+ }
748
+ /** Where the SLO broke, and what broke it. */
749
+ function capacityVerdict(emit, req, search) {
750
+ const { result, why } = capacityWords(req, search);
751
+ // Nested one level, a key named `data` inside the event's data, as it always has been.
752
+ (0, events_1.info)(emit, `capacity: ${result}`, {
753
+ phase: 'done',
754
+ data: { data: { capacity_vus: search.lastPass } },
755
+ });
756
+ return { result, why };
757
+ }
758
+ /** The verdict's words alone, for the CLI's run, which says nothing through events. */
759
+ function capacityWords(req, search) {
760
+ let result;
761
+ if (search.lastPass === null) {
762
+ result = `breaches the SLO even at ${String(req.start)} VUs - start lower`;
763
+ }
764
+ else if (search.firstFail === null) {
765
+ result = `holds the SLO up to ${String(search.lastPass)} VUs (never breached; raise max to push further)`;
766
+ }
767
+ else {
768
+ result = `~${String(search.lastPass)} concurrent VUs (holds at ${String(search.lastPass)}, breaks at ${String(search.firstFail)})`;
769
+ }
770
+ const breach = search.firstFail !== null
771
+ ? search.steps.find((r) => r.vus === search.firstFail)
772
+ : search.steps.find((r) => !(0, format_1.isTruthy)(r.ok));
773
+ let why = '';
774
+ if (breach !== undefined) {
775
+ const lag = Number(breach.lag_max_s ?? 0);
776
+ why =
777
+ lag >= 0.5
778
+ ? `at ${String(breach.vus)} VUs the RC event loop saturated (lag peaked ` +
779
+ `at ${(0, format_1.formatFixed)(lag * 1000, 0)}ms)`
780
+ : `at ${String(breach.vus)} VUs: ${(Array.isArray(breach.breached) ? breach.breached : []).join('; ')}`;
781
+ }
782
+ return { result, why };
783
+ }
784
+ async function capacityPreflight(deps, req) {
785
+ await (0, preconditions_1.requireDocker)();
786
+ if (!exports.GUI_SCENARIOS.includes(req.scenario)) {
787
+ throw new errors_1.ValidationError(`scenario must be one of ${exports.GUI_SCENARIOS.join(', ')}`);
788
+ }
789
+ let rules;
790
+ try {
791
+ rules = deps.slo.parse(req.slo);
792
+ }
793
+ catch (exc) {
794
+ throw new errors_1.ValidationError(`bad slo: ${(0, errors_1.errorText)(exc)}`);
795
+ }
796
+ if (req.start < 1 || req.maxVus < req.start) {
797
+ throw new errors_1.ValidationError('start must be >= 1 and max >= start');
798
+ }
799
+ refuseABadDuration(req.stepDuration, 'step duration');
800
+ await requireComposeForPerf(req.name, 'capacity'); // see runLoadtest for the why
801
+ const m = await (0, record_1.readMeta)(await (0, naming_1.resolveName)(req.name));
802
+ const doc = await (0, record_1.readCompose)(m.name);
803
+ const target = loadtestTarget(doc);
804
+ const rcServices = rcServicesIn(doc);
805
+ const services = rcServices.length > 0 ? rcServices : ['rocketchat'];
806
+ let perService = {};
807
+ if (req.constrain) {
808
+ try {
809
+ perService = deps.constrain.resolveServices(deps.constrain.parse(req.constrain), Object.keys(bagOf(doc.services)));
810
+ }
811
+ catch (exc) {
812
+ throw new errors_1.ValidationError(`bad constrain: ${(0, errors_1.errorText)(exc)}`);
813
+ }
814
+ }
815
+ let auth;
816
+ let token;
817
+ try {
818
+ auth = await (0, admin_1.login)(m);
819
+ token = await (0, rcapi_1.generatePat)(m.rootUrl, auth, (0, record_1.adminPass)(m), {
820
+ tokenName: 'houston-loadtest',
821
+ bypass2fa: true,
822
+ workspace: m.name,
823
+ });
824
+ }
825
+ catch (exc) {
826
+ throw new errors_1.NotReadyError(`could not authenticate (ready?): ${(0, errors_1.errorText)(exc)}`);
827
+ }
828
+ const users = req.usersN > 0 ? await loginSeedUsers(m.rootUrl, req.usersN) : [];
829
+ return { auth, m, perService, rcServices: services, rules, target, token, users };
830
+ }
831
+ /** Undo every side effect the search armed, whichever way it ended. */
832
+ async function putTheWorkspaceBack({ auth, cli = null, deps, emit, m, search, }) {
833
+ // The job's event, or the restore's warning line: its own words, with the lead and
834
+ // the em dash the service's line does not have.
835
+ const restoreWarning = (job, words) => {
836
+ if (cli === null)
837
+ (0, events_1.warn)(emit, job, { phase: 'restore' });
838
+ else
839
+ cli.warn(words);
840
+ };
841
+ if (!search.limiterWasOff) {
842
+ if (await restoreSetting(m, auth, config.RC_RATE_LIMITER_SETTING, true)) {
843
+ journal.clear(search.limiterNote);
844
+ }
845
+ else {
846
+ restoreWarning('could not restore the API rate limiter setting', ' ⚠ could not restore the API rate limiter setting');
847
+ }
848
+ }
849
+ if (search.metricsChanged) {
850
+ if (await restoreSetting(m, auth, deps.monitoring.RC_METRICS_SETTING, false)) {
851
+ journal.clear(search.metricsNote);
852
+ }
853
+ else {
854
+ restoreWarning('could not restore the Prometheus metrics setting', ' ⚠ could not restore the Prometheus metrics setting');
855
+ }
856
+ }
857
+ // See run_loadtest: cleared only when the restore actually succeeded.
858
+ const capProblems = await deps.constrain.restore(search.applied);
859
+ for (const problem of capProblems) {
860
+ restoreWarning(`could not restore resource limits - ${problem}`, ` ⚠ could not restore resource limits — ${problem}`);
861
+ }
862
+ if (capProblems.length === 0) {
863
+ journal.clear(search.constrainNote);
864
+ }
865
+ await fs.rm((0, home_1.joinPath)(paths.workspace(m.name), 'loadtest', 'users.json'), { force: true });
866
+ }
867
+ /** Double until the SLO breaks, then bisect between the last pass and the first fail. */
868
+ async function searchForCapacity({ auth, cli = null, deps, emit, m, perService, req, runStep, search, }) {
869
+ if (Object.keys(perService).length > 0) {
870
+ try {
871
+ search.applied = await deps.constrain.apply(m.name, perService);
872
+ }
873
+ catch (exc) {
874
+ if (exc instanceof exec_1.Interrupted)
875
+ throw exc;
876
+ throw constrainFailure(cli, exc);
877
+ }
878
+ // NOTED WITH THE PRIOR VALUES, so a killed run can be undone exactly rather than
879
+ // reset to "unlimited". `restore` runs in the `finally` below; this is what covers
880
+ // the run that never reaches it.
881
+ search.constrainNote = journal.record(journal.CONSTRAINTS_APPLIED, m.name, {
882
+ applied: search.applied.map((a) => ({ ...a })),
883
+ });
884
+ }
885
+ search.limiterWasOff =
886
+ (await (0, rcapi_1.getSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), config.RC_RATE_LIMITER_SETTING)) === false;
887
+ if (!search.limiterWasOff) {
888
+ search.limiterNote = journal.record(journal.RATE_LIMITER_OFF, m.name);
889
+ if (!(await (0, rcapi_1.setSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), config.RC_RATE_LIMITER_SETTING, false))) {
890
+ // Never turned off, so nothing to put back (as in `armAndRun`).
891
+ search.limiterWasOff = true;
892
+ journal.clear(search.limiterNote);
893
+ search.limiterNote = '';
894
+ }
895
+ }
896
+ if ((await (0, rcapi_1.getSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), deps.monitoring.RC_METRICS_SETTING)) !== true) {
897
+ search.metricsNote = journal.record(journal.RC_METRICS_ON, m.name);
898
+ search.metricsChanged = await (0, rcapi_1.setSetting)(m.rootUrl, auth, (0, record_1.adminPass)(m), deps.monitoring.RC_METRICS_SETTING, true);
899
+ }
900
+ // The CLI's header, once everything above is armed. An event would reach the event log's
901
+ // sink even with no emitter, where the CLI's search has never written one.
902
+ if (cli === null) {
903
+ (0, events_1.info)(emit, `capacity search: ${req.scenario}, SLO ${req.slo}, steps of ${req.stepDuration}`, {
904
+ phase: 'k6',
905
+ });
906
+ }
907
+ else {
908
+ cli.armed?.();
909
+ }
910
+ let n = req.start;
911
+ while (n <= req.maxVus) {
912
+ const row = await runStep(n);
913
+ if ((0, format_1.isTruthy)(row.ok)) {
914
+ search.lastPass = n;
915
+ n *= 2;
916
+ }
917
+ else {
918
+ search.firstFail = n;
919
+ break;
920
+ }
921
+ }
922
+ if (search.firstFail !== null && search.lastPass !== null) {
923
+ let lo = search.lastPass;
924
+ let hi = search.firstFail;
925
+ for (let round = 0; round < 2; round += 1) {
926
+ const mid = Math.floor((lo + hi) / 2);
927
+ if (mid <= lo || mid >= hi) {
928
+ break;
929
+ }
930
+ const row = await runStep(mid, ' (bisect)');
931
+ if ((0, format_1.isTruthy)(row.ok)) {
932
+ lo = mid;
933
+ search.lastPass = mid;
934
+ }
935
+ else {
936
+ hi = mid;
937
+ search.firstFail = mid;
938
+ }
939
+ }
940
+ }
941
+ }
942
+ async function runCapacity(req, emit = events_1.nullEmit, deps = exports.DEFAULT_DEPS) {
943
+ const prepared = await capacityPreflight(deps, req);
944
+ const { m, perService } = prepared;
945
+ const { search, result, why } = await runPreparedCapacity(req, prepared, emit, deps);
946
+ return {
947
+ ctx: {
948
+ name: m.name,
949
+ scenario: req.scenario,
950
+ slo: req.slo,
951
+ constrained: Object.keys(perService).length > 0 ? deps.constrain.human(perService) : '',
952
+ },
953
+ steps: search.steps,
954
+ capacity_vus: search.lastPass,
955
+ breach_vus: search.firstFail,
956
+ result,
957
+ why,
958
+ };
959
+ }
960
+ async function runPreparedCapacity(req, prepared, emit = events_1.nullEmit, deps = exports.DEFAULT_DEPS, cli = null) {
961
+ const { auth, m, perService, rcServices, rules, target, token, users } = prepared;
962
+ const search = newCapacitySearch();
963
+ let warned = false;
964
+ const runStep = async (n, tag = '') => {
965
+ // Said once, at the first step that crosses it: the rows from there on are suspect.
966
+ const words = warned ? null : sessionLimitWarning(req.scenario, n, users.length);
967
+ if (words !== null) {
968
+ warned = true;
969
+ if (cli === null)
970
+ (0, events_1.warn)(emit, words, { phase: 'k6' });
971
+ else
972
+ cli.warn(` ⚠ ${words}`);
973
+ }
974
+ const sampler = new deps.rcmetrics.RCMetricsSampler(m.name, rcServices).start();
975
+ let s;
976
+ let rcm;
977
+ try {
978
+ s = await deps.k6.run(m.name, req.scenario, {
979
+ vus: n,
980
+ duration: req.stepDuration,
981
+ ramp: null,
982
+ token,
983
+ uid: auth.userId,
984
+ target,
985
+ users: users.length > 0 ? [...users] : null,
986
+ password: (0, record_1.adminPass)(m),
987
+ quiet: true,
988
+ });
989
+ }
990
+ finally {
991
+ rcm = await sampler.stop();
992
+ }
993
+ const res = deps.slo.evaluate(rules, s);
994
+ let lagMax = 0.0;
995
+ for (const sm of Object.values(rcm)) {
996
+ // The first key's summary wins even if its `max` is zero: the fallback is decided on
997
+ // the summary, not on the number.
998
+ const lag = sm.eventloop_lag_max_s ?? sm.eventloop_lag_s;
999
+ if (lag !== undefined && (0, format_1.isTruthy)(lag))
1000
+ lagMax = Math.max(lagMax, Number(lag.max));
1001
+ }
1002
+ const row = {
1003
+ vus: n,
1004
+ rps: s.rps ?? 0.0,
1005
+ p95: s.p95 ?? 0.0,
1006
+ error_rate: s.error_rate ?? 0.0,
1007
+ ok: res.every((r) => r.ok),
1008
+ lag_max_s: lagMax,
1009
+ breached: res
1010
+ .filter((r) => !r.ok)
1011
+ .map((r) => `${r.key} ${r.op} ${r.raw} (actual ${deps.slo.fmtActual(r.key, r.actual)})`),
1012
+ };
1013
+ STEP_FLOATS.set(row, [
1014
+ ...['rps', 'p95', 'error_rate'].filter((key) => s[key] === undefined),
1015
+ 'lag_max_s',
1016
+ ]);
1017
+ search.steps.push(row);
1018
+ if (cli === null) {
1019
+ (0, events_1.info)(emit, `${String(n)} VUs${tag}: ${(0, format_1.formatFixed)(Number(row.rps), 1)} req/s, ` +
1020
+ `p95 ${(0, format_1.formatFixed)(Number(row.p95), 0)}ms, ${(0, format_1.isTruthy)(row.ok) ? 'PASS' : 'FAIL'}`, { phase: 'k6' });
1021
+ }
1022
+ else {
1023
+ // Each row is printed the moment it is measured, tag and all.
1024
+ cli.step?.(row, tag);
1025
+ }
1026
+ return row;
1027
+ };
1028
+ // UNWOUND by a Ctrl-C, as `runPreparedLoadtest` is.
1029
+ await (0, exec_1.unwindsOnInterrupt)(async () => {
1030
+ try {
1031
+ await searchForCapacity({
1032
+ auth,
1033
+ cli,
1034
+ deps,
1035
+ emit,
1036
+ m,
1037
+ perService,
1038
+ req,
1039
+ runStep,
1040
+ search,
1041
+ });
1042
+ }
1043
+ finally {
1044
+ await (0, exec_1.cleanup)(async () => {
1045
+ await putTheWorkspaceBack({ auth, cli, deps, emit, m, search });
1046
+ });
1047
+ }
1048
+ });
1049
+ const { result, why } = cli === null ? capacityVerdict(emit, req, search) : capacityWords(req, search);
1050
+ return { search, result, why };
1051
+ }