@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,814 @@
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_PERF_DEPS = void 0;
37
+ exports.perfDeps = perfDeps;
38
+ exports.parseEndpoint = parseEndpoint;
39
+ exports.parseRamp = parseRamp;
40
+ exports.runLoadtestCli = runLoadtestCli;
41
+ exports.runCapacityCli = runCapacityCli;
42
+ /** CLI-only performance orchestration over the shared load-test service. */
43
+ const os = __importStar(require("node:os"));
44
+ const audit_1 = require("../core/audit");
45
+ const coreLoadtest = __importStar(require("../core/loadtest"));
46
+ const lifecycleAdmin = __importStar(require("../core/lifecycle/admin"));
47
+ const inspect_1 = require("../core/lifecycle/inspect");
48
+ const lifecycleNaming = __importStar(require("../core/lifecycle/naming"));
49
+ const lifecyclePreconditions = __importStar(require("../core/lifecycle/preconditions"));
50
+ const rcapi = __importStar(require("../core/rcapi"));
51
+ const runnerHost = __importStar(require("../core/runner/host"));
52
+ const runnerRecord = __importStar(require("../core/runner/record"));
53
+ const errors_1 = require("../lib/errors");
54
+ const events_1 = require("../lib/events");
55
+ const jsonout_1 = require("../lib/jsonout");
56
+ const format_1 = require("../lib/format");
57
+ const platform_name_1 = require("../lib/platform-name");
58
+ const baseline = __importStar(require("../perf/baseline"));
59
+ const constrain = __importStar(require("../perf/constrain"));
60
+ const report = __importStar(require("../perf/report"));
61
+ const timeline = __importStar(require("../perf/timeline"));
62
+ const timings_1 = require("../perf/timings");
63
+ const verdict = __importStar(require("../perf/verdict"));
64
+ /** One line of prose on stdout: a warning, a note or a plain echo. */
65
+ function say(io, message) {
66
+ io.writeOut(`${message}\n`);
67
+ }
68
+ exports.DEFAULT_PERF_DEPS = {
69
+ core: coreLoadtest,
70
+ baseline,
71
+ constrain,
72
+ report,
73
+ timeline,
74
+ verdict,
75
+ requireDocker: lifecyclePreconditions.requireDocker,
76
+ resolveName: lifecycleNaming.resolveName,
77
+ readMeta: runnerRecord.readMeta,
78
+ readCompose: runnerRecord.readCompose,
79
+ adminPass: runnerRecord.adminPass,
80
+ login: lifecycleAdmin.login,
81
+ generatePat: rcapi.generatePat,
82
+ createIncomingWebhook: rcapi.createIncomingWebhook,
83
+ call: rcapi.call,
84
+ dockerServerVersion: runnerHost.dockerServerVersion,
85
+ composeVersion: runnerHost.composeVersion,
86
+ now: () => new Date(),
87
+ platform: platform_name_1.platformName,
88
+ cpuCount: () => os.cpus().length,
89
+ };
90
+ function perfDeps(overrides = {}) {
91
+ return { ...exports.DEFAULT_PERF_DEPS, ...overrides };
92
+ }
93
+ function asBag(value) {
94
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
95
+ }
96
+ /**
97
+ * A copy of `row` in which each of `keys` holding a number is marked a FLOAT, so the
98
+ * envelope writes `5.0`, as it always has, rather than `5`.
99
+ *
100
+ * For the --json envelope only: the renderer, the report and the GUI's job read the plain
101
+ * numbers, and the web's serializer does not know a `JsonFloat`.
102
+ */
103
+ function floatSpellings(row, keys) {
104
+ const out = { ...asBag(row) };
105
+ for (const key of keys) {
106
+ const value = out[key];
107
+ if (typeof value === 'number')
108
+ out[key] = new jsonout_1.JsonFloat(value);
109
+ }
110
+ return out;
111
+ }
112
+ /** Every value of a `{name: row}` map through `floatSpellings`. */
113
+ function eachFloatSpelling(map, keys) {
114
+ return Object.fromEntries(Object.entries(asBag(map)).map(([k, v]) => [k, floatSpellings(v, keys)]));
115
+ }
116
+ /**
117
+ * The loadtest envelope's computed numbers, marked as the floats the envelope has always
118
+ * carried: the SLO's `threshold` and `actual`, a compare row's `before`, `after` and `pct`
119
+ * (and `0.0` against a zero baseline), the timeline's `span_s` and each bucket's `p50`,
120
+ * `p95` and `max`, the spike's two p95s, each RC metric's `mean`, `max` and `last` (read
121
+ * from the exposition text), and every field of a container's resource cost. What k6's
122
+ * summary and the profiler wrote is left as read.
123
+ */
124
+ function loadtestEnvelopeFloats(data) {
125
+ const out = {
126
+ ...data,
127
+ slo: data.slo.map((r) => floatSpellings(r, ['threshold', 'actual'])),
128
+ };
129
+ if (data.diag !== undefined) {
130
+ const diag = asBag(data.diag);
131
+ const tl = diag.timeline;
132
+ out.diag = {
133
+ ...diag,
134
+ rcmetrics: Object.fromEntries(Object.entries(asBag(diag.rcmetrics)).map(([service, series]) => [
135
+ service,
136
+ eachFloatSpelling(series, ['mean', 'max', 'last']),
137
+ ])),
138
+ timeline: tl === null
139
+ ? null
140
+ : {
141
+ ...floatSpellings(tl, ['span_s']),
142
+ buckets: tl.buckets.map((b) => floatSpellings(b, ['p50', 'p95', 'max'])),
143
+ },
144
+ spike: diag.spike === null ? null : floatSpellings(diag.spike, ['baseline_p95', 'spike_p95']),
145
+ };
146
+ }
147
+ if (data.resources !== undefined) {
148
+ out.resources = eachFloatSpelling(data.resources, [
149
+ 'idle_cpu',
150
+ 'peak_cpu',
151
+ 'idle_mem',
152
+ 'peak_mem',
153
+ 'limit_mem',
154
+ 'peak_cpu_t',
155
+ ]);
156
+ }
157
+ if (data.compare !== undefined) {
158
+ const comparison = asBag(data.compare);
159
+ out.compare = {
160
+ ...comparison,
161
+ rows: comparison.rows.map((r) => floatSpellings(r, ['before', 'after', 'pct'])),
162
+ };
163
+ }
164
+ return out;
165
+ }
166
+ function stamp(date) {
167
+ return date.toISOString().replaceAll('-', '').replaceAll(':', '').slice(0, 15);
168
+ }
169
+ function isoSeconds(date) {
170
+ return `${date.toISOString().slice(0, 19)}+00:00`;
171
+ }
172
+ /** A warning for `--json`: the message trimmed, its leading `⚠` and spaces gone. */
173
+ function stripWarning(message) {
174
+ return message.trim().replace(/^[⚠ ]+/u, '');
175
+ }
176
+ function authenticationFailure(meta, error) {
177
+ const message = (0, errors_1.errorText)(error);
178
+ if (error instanceof Error && error.name === 'RequestFailed') {
179
+ throw new errors_1.NotReadyError(`'${meta.name}' is not answering yet, so the load test cannot sign in — wait for it with ` +
180
+ `\`houston ready --name ${meta.name}\``);
181
+ }
182
+ if (message.includes('429') || message.includes('Too Many Requests')) {
183
+ throw new errors_1.NotReadyError(`Rocket.Chat is rate-limiting token creation on '${meta.name}', so the load test ` +
184
+ 'cannot sign in yet. Its limiter resets in about a minute — try again then.');
185
+ }
186
+ throw new errors_1.ReproError(`the load test cannot sign in: ${message}`);
187
+ }
188
+ async function performanceIdentity(deps, meta) {
189
+ try {
190
+ const auth = await deps.login(meta);
191
+ const token = await deps.generatePat(meta.rootUrl, auth, deps.adminPass(meta), {
192
+ tokenName: 'houston-loadtest',
193
+ bypass2fa: true,
194
+ workspace: meta.name,
195
+ });
196
+ return { auth, token };
197
+ }
198
+ catch (error) {
199
+ authenticationFailure(meta, error);
200
+ }
201
+ }
202
+ /*
203
+ * A FLAG THAT IS WRONG IS A ValidationError -- VALIDATION_FAILED, exit 2 -- in the option
204
+ * checks, the capacity checks, the live-monitoring check and the constraints alike: the class
205
+ * the GUI's own preflight in core/loadtest.ts raises for the same refusals. They were plain
206
+ * ReproErrors, exit 1, so `loadtest --scenario frob` exited 1 where `--duration forever` and
207
+ * every other command's bad flag exit 2. A `--compare` naming no saved baseline is the
208
+ * baseline's own NotFoundError, exit 4. What is left as a plain ReproError, exit 1, is a
209
+ * refusal of no more specific kind: Rocket.Chat refusing the webhook, or the API call.
210
+ */
211
+ function parseEndpoint(endpoint) {
212
+ const value = endpoint.trim();
213
+ if (value === '')
214
+ throw new errors_1.ValidationError('bad --endpoint: empty endpoint');
215
+ const parts = value.split(/\s+/u, 2);
216
+ let method = 'GET';
217
+ let target = value;
218
+ if (parts.length === 2 && /^[A-Za-z]+$/u.test(parts[0])) {
219
+ method = parts[0].toUpperCase();
220
+ const allowed = ['DELETE', 'GET', 'PATCH', 'POST', 'PUT'];
221
+ if (!allowed.includes(method)) {
222
+ throw new errors_1.ValidationError(`bad --endpoint: unsupported method '${parts[0]}' (use ${allowed.join(', ')})`);
223
+ }
224
+ target = value.slice(parts[0].length).trim();
225
+ }
226
+ if (!target.startsWith('/')) {
227
+ throw new errors_1.ValidationError(`bad --endpoint: path must start with '/': '${target}'`);
228
+ }
229
+ return [method, target];
230
+ }
231
+ function parseRamp(value, flag) {
232
+ const cells = value.split(':');
233
+ if (cells.length !== 2) {
234
+ throw new errors_1.ValidationError(`bad ${flag}: ramp must be START:END, e.g. 10:200`);
235
+ }
236
+ if (!cells.every((cell) => /^-?\d+$/u.test(cell))) {
237
+ throw new errors_1.ValidationError(`bad ${flag}: ramp START and END must be integers, e.g. 10:200`);
238
+ }
239
+ const start = Number(cells[0]);
240
+ const end = Number(cells[1]);
241
+ if (start < 0 || end < 1) {
242
+ throw new errors_1.ValidationError(`bad ${flag}: ramp needs START >= 0 and END >= 1, e.g. 10:200`);
243
+ }
244
+ // A spike is measured against its base, so a base of 0 VUs leaves nothing to compare.
245
+ if (flag === '--spike' && start < 1) {
246
+ throw new errors_1.ValidationError('bad --spike: the base must be at least 1 VU, e.g. 10:100');
247
+ }
248
+ if (flag === '--spike' && end <= start) {
249
+ throw new errors_1.ValidationError(`--spike peak must exceed base ('${value}')`);
250
+ }
251
+ return [start, end];
252
+ }
253
+ function customEnvironment(options) {
254
+ if (options.scenario !== 'custom') {
255
+ if (options.endpoint !== '' || options.body !== '') {
256
+ throw new errors_1.ValidationError('--endpoint/--body only apply to --scenario custom');
257
+ }
258
+ return { extraEnv: null, method: '', path: '' };
259
+ }
260
+ if (options.endpoint === '') {
261
+ throw new errors_1.ValidationError('--scenario custom needs --endpoint, e.g. --endpoint "GET /api/v1/channels.list"');
262
+ }
263
+ const [method, path] = parseEndpoint(options.endpoint);
264
+ if (options.body !== '' && ['GET', 'DELETE'].includes(method)) {
265
+ throw new errors_1.ValidationError(`--body is not sent with a ${method} request`);
266
+ }
267
+ return {
268
+ extraEnv: { RC_METHOD: method, RC_PATH: path, RC_BODY: options.body || null },
269
+ method,
270
+ path,
271
+ };
272
+ }
273
+ function validateLoadtest(options, deps, warn) {
274
+ if (!deps.core.DEFAULT_DEPS.k6.SCENARIOS.includes(options.scenario)) {
275
+ throw new errors_1.ValidationError(`unknown scenario '${options.scenario}' (choose: ${deps.core.DEFAULT_DEPS.k6.SCENARIOS.join(', ')})`);
276
+ }
277
+ const custom = customEnvironment(options);
278
+ if (options.vus < 1)
279
+ throw new errors_1.ValidationError('--vus must be >= 1');
280
+ coreLoadtest.refuseABadDuration(options.duration, '--duration');
281
+ if (options.usersN < 0)
282
+ throw new errors_1.ValidationError('--users must be >= 0');
283
+ if (options.ramp !== '' && options.spike !== '') {
284
+ throw new errors_1.ValidationError('--ramp and --spike are mutually exclusive load shapes');
285
+ }
286
+ for (const [flag, value] of [
287
+ ['--ramp', options.ramp],
288
+ ['--spike', options.spike],
289
+ ]) {
290
+ if (value === '')
291
+ continue;
292
+ parseRamp(value, flag);
293
+ if (options.vus !== 10)
294
+ warn(` note: --vus is ignored when ${flag} is given`);
295
+ }
296
+ for (const label of [options.save, options.compare]) {
297
+ if (label !== '')
298
+ deps.baseline.sanitizeLabel(label);
299
+ }
300
+ let constraints = {};
301
+ let rules = [];
302
+ try {
303
+ if (options.constrain !== '')
304
+ constraints = deps.constrain.parse(options.constrain);
305
+ }
306
+ catch (error) {
307
+ throw new errors_1.ValidationError(`bad --constrain: ${(0, errors_1.errorText)(error)}`);
308
+ }
309
+ try {
310
+ if (options.slo !== '')
311
+ rules = deps.core.DEFAULT_DEPS.slo.parse(options.slo);
312
+ }
313
+ catch (error) {
314
+ throw new errors_1.ValidationError(`bad --slo: ${(0, errors_1.errorText)(error)}`);
315
+ }
316
+ return { ...custom, constraints, rules };
317
+ }
318
+ async function hostDetails(deps) {
319
+ return {
320
+ os: deps.platform(),
321
+ cpu: deps.cpuCount() || '?',
322
+ docker: (await deps.dockerServerVersion()) || '?',
323
+ compose: (await deps.composeVersion()) || '?',
324
+ };
325
+ }
326
+ async function workspaceSnapshot(deps, meta, auth, instances) {
327
+ const snapshot = {
328
+ rc_version: meta.rcVersion,
329
+ preset: meta.preset,
330
+ instances,
331
+ };
332
+ try {
333
+ const [status, body] = await deps.call(meta.rootUrl, 'GET', '/api/v1/statistics?refresh=true', {
334
+ auth,
335
+ });
336
+ if (status === 200) {
337
+ const parsed = asBag(JSON.parse(body));
338
+ for (const [key, source] of [
339
+ ['users', 'totalUsers'],
340
+ ['rooms', 'totalRooms'],
341
+ ['messages', 'totalMessages'],
342
+ ]) {
343
+ if (parsed[source] !== null && parsed[source] !== undefined)
344
+ snapshot[key] = parsed[source];
345
+ }
346
+ }
347
+ }
348
+ catch {
349
+ // A report snapshot is best-effort and must never fail the measurement.
350
+ }
351
+ return snapshot;
352
+ }
353
+ function loadShape(ctx) {
354
+ if (ctx.spike !== null && ctx.spike !== undefined && String(ctx.spike) !== '') {
355
+ return `spike ${String(ctx.spike)}`;
356
+ }
357
+ if (ctx.ramp !== null && ctx.ramp !== undefined && String(ctx.ramp) !== '') {
358
+ return `ramp ${String(ctx.ramp)}`;
359
+ }
360
+ return `${String(ctx.vus ?? '?')} VUs`;
361
+ }
362
+ function capacityCliVerdict(options, search) {
363
+ let result;
364
+ if (search.lastPass === null) {
365
+ result = `breaches the SLO even at ${String(options.start)} VUs — start lower (--start)`;
366
+ }
367
+ else if (search.firstFail === null) {
368
+ result =
369
+ `holds the SLO up to ${String(search.lastPass)} VUs ` +
370
+ '(never breached; raise --max to push further)';
371
+ }
372
+ else {
373
+ result =
374
+ `~${String(search.lastPass)} concurrent VUs (holds at ${String(search.lastPass)}, ` +
375
+ `breaks at ${String(search.firstFail)})`;
376
+ }
377
+ const breach = search.firstFail !== null
378
+ ? search.steps.find((row) => row.vus === search.firstFail)
379
+ : search.steps.find((row) => !(0, format_1.isTruthy)(row.ok));
380
+ if (breach === undefined)
381
+ return { result, why: '' };
382
+ const lag = Number(breach.lag_max_s ?? 0);
383
+ const why = lag >= 0.5
384
+ ? `at ${String(breach.vus)} VUs the RC event loop saturated ` +
385
+ `(lag peaked at ${(0, timings_1.fmtMs)(lag * 1000)})`
386
+ : `at ${String(breach.vus)} VUs: ` +
387
+ (Array.isArray(breach.breached) ? breach.breached.map(String).join('; ') : '');
388
+ return { result, why };
389
+ }
390
+ /**
391
+ * `loadtest`, as it has always run: its banner and its warnings said as the run goes, and
392
+ * nothing of the GUI job's narration.
393
+ *
394
+ * It ran the job's transaction with the CLI emitter, so the service spoke for it: a
395
+ * ' running k6: <scenario> @ <vus> VUs ...' line in place of the bold 'Load test: ...' banner
396
+ * and its blank line (wrong for --spike, --ramp and custom), no live-dashboard hint under
397
+ * --live, every warning gathered up and printed at the END on stderr as 'warning: ...', and
398
+ * the job's 'k6' and 'done' events in the event log, the done event's `passed` redacted as a
399
+ * secret. A warning now: under --json it is collected for `data.warnings`, otherwise it is a
400
+ * warning line, on stdout, the moment it happens; and the job runs with the CLI's hooks and
401
+ * raises no event.
402
+ *
403
+ * `render` is the result renderer, which the CLI's registry supplies: it draws the result
404
+ * once the run is measured and before any output is saved, and each output written is then
405
+ * announced as that function announces it.
406
+ */
407
+ async function runLoadtestCli(options, io, deps = exports.DEFAULT_PERF_DEPS, render = () => undefined) {
408
+ const warnings = [];
409
+ const prose = !options.json;
410
+ const warn = (message) => {
411
+ if (prose)
412
+ say(io, message);
413
+ else
414
+ warnings.push(stripWarning(message));
415
+ };
416
+ // `loadtest` asks for the engine first (`requireDocker`), then validates, as it always has:
417
+ // a bad --vus on a box whose engine answers is refused after `docker info` and `docker
418
+ // compose version`, not before them.
419
+ await deps.requireDocker();
420
+ const checked = validateLoadtest(options, deps, warn);
421
+ // Resolved as the CLI's actor first, then guarded (`requireComposeForPerf`).
422
+ const resolved = await deps.resolveName(options.name, (0, audit_1.actor)());
423
+ await deps.core.requireComposeForPerf(resolved, 'loadtest');
424
+ const meta = await deps.readMeta(resolved);
425
+ const compose = await deps.readCompose(meta.name);
426
+ const target = deps.core.loadtestTarget(compose);
427
+ const rcServices = deps.core.rcServicesIn(compose);
428
+ const services = rcServices.length > 0 ? rcServices : ['rocketchat'];
429
+ if (options.live) {
430
+ if (!(0, format_1.isTruthy)(asBag(meta.extra).monitoring)) {
431
+ throw new errors_1.ValidationError(`--live needs the monitoring stack — attach it first: houston monitor --name ${meta.name}`);
432
+ }
433
+ const command = asBag(asBag(compose.services).prometheus).command;
434
+ if (!(Array.isArray(command) ? command : []).some((part) => String(part).includes('remote-write-receiver'))) {
435
+ throw new errors_1.ValidationError("--live needs Prometheus with remote-write enabled, but this workspace's monitoring " +
436
+ `predates it. Re-attach it: houston monitor --name ${meta.name} --off && ` +
437
+ `houston monitor --name ${meta.name}`);
438
+ }
439
+ }
440
+ let perService = {};
441
+ try {
442
+ if (Object.keys(checked.constraints).length > 0) {
443
+ perService = deps.constrain.resolveServices(checked.constraints, Object.keys(asBag(compose.services)));
444
+ }
445
+ }
446
+ catch (error) {
447
+ throw new errors_1.ValidationError(`bad --constrain: ${(0, errors_1.errorText)(error)}`);
448
+ }
449
+ let base = null;
450
+ if (options.compare !== '') {
451
+ try {
452
+ base = deps.baseline.load(options.compare);
453
+ }
454
+ catch (error) {
455
+ // The baseline's own NotFoundError (exit 4) passes; an unreadable one is a plain refusal.
456
+ if (error instanceof errors_1.ReproError)
457
+ throw error;
458
+ throw new errors_1.ReproError((0, errors_1.errorText)(error));
459
+ }
460
+ }
461
+ const { auth, token } = await performanceIdentity(deps, meta);
462
+ const users = options.usersN > 0 && options.scenario !== 'custom'
463
+ ? await deps.core.loginSeedUsers(meta.rootUrl, options.usersN)
464
+ : [];
465
+ if (options.usersN > 0 && options.scenario !== 'custom' && users.length === 0) {
466
+ warn(' ⚠ no seeded users could log in — using the admin token ' +
467
+ '(run `houston seed` first for realistic multi-user load)');
468
+ }
469
+ let extraEnv = checked.extraEnv;
470
+ if (options.scenario === 'webhook') {
471
+ const hook = await deps.createIncomingWebhook(meta.rootUrl, auth, deps.adminPass(meta));
472
+ if (!hook) {
473
+ throw new errors_1.ReproError('could not create the incoming webhook integration (check admin permissions)');
474
+ }
475
+ extraEnv = { ...(extraEnv ?? {}), RC_HOOK_PATH: hook };
476
+ }
477
+ const snapshot = await workspaceSnapshot(deps, meta, auth, Math.max(1, rcServices.length));
478
+ if (Object.keys(perService).length > 0)
479
+ snapshot.constraints = deps.constrain.human(perService);
480
+ const req = deps.core.loadtestReq({
481
+ name: meta.name,
482
+ scenario: options.scenario,
483
+ vus: options.vus,
484
+ duration: options.duration,
485
+ usersN: options.usersN,
486
+ slo: options.slo,
487
+ constrain: options.constrain,
488
+ diag: options.diag,
489
+ stats: options.stats,
490
+ live: options.live,
491
+ slowms: options.slowms,
492
+ ramp: options.ramp || null,
493
+ spike: options.spike || null,
494
+ extraEnv,
495
+ quiet: options.json,
496
+ setupWarnings: true,
497
+ });
498
+ const prepared = {
499
+ auth,
500
+ m: meta,
501
+ perService,
502
+ rcServices: services,
503
+ rules: checked.rules,
504
+ target,
505
+ token,
506
+ users,
507
+ };
508
+ const label = options.scenario === 'custom' ? `custom ${checked.method} ${checked.path}` : options.scenario;
509
+ const shape = options.spike !== ''
510
+ ? `spike ${options.spike}`
511
+ : options.ramp !== ''
512
+ ? `ramp ${options.ramp}`
513
+ : `${String(options.vus)} VUs`;
514
+ const identity = users.length > 0 ? `${String(users.length)} seeded users` : 'admin token';
515
+ const hooks = {
516
+ warn,
517
+ constrained: (human) => {
518
+ if (prose)
519
+ say(io, ` constrained: ${human} (restored after the test)`);
520
+ },
521
+ // The banner, once the settings are armed.
522
+ armed: () => {
523
+ if (!prose)
524
+ return;
525
+ say(io, `Load test: ${label} @ ${shape} for ${options.duration} as ${identity} -> ${target} ` +
526
+ `(via k6 on ${(0, format_1.shownValue)(meta.name)}'s network)\n`);
527
+ if (options.live) {
528
+ say(io, ' live: k6 metrics streaming into Prometheus — open the ' +
529
+ `'k6 Load Test' dashboard in Grafana (${(0, inspect_1.grafanaUrlOf)(meta)}), ` +
530
+ 'or Explore -> k6_*');
531
+ }
532
+ },
533
+ };
534
+ const { run, verdict: measured } = await deps.core.runPreparedLoadtest(req, prepared, events_1.nullEmit, deps.core.DEFAULT_DEPS, hooks);
535
+ const ctx = {
536
+ name: meta.name,
537
+ version: meta.rcVersion,
538
+ scenario: options.scenario,
539
+ vus: options.vus,
540
+ duration: options.duration,
541
+ ramp: options.ramp,
542
+ spike: options.spike,
543
+ target,
544
+ label,
545
+ users: users.length,
546
+ constrained: snapshot.constraints ?? '',
547
+ };
548
+ const summary = run.summary ?? {};
549
+ const compareRows = base === null ? [] : deps.baseline.compare({ summary }, base);
550
+ if (base !== null) {
551
+ const baseCtx = asBag(base.ctx);
552
+ if (baseCtx.scenario !== null &&
553
+ baseCtx.scenario !== undefined &&
554
+ baseCtx.scenario !== options.scenario) {
555
+ warn(` ⚠ baseline '${options.compare}' was a '${String(baseCtx.scenario)}' run — ` +
556
+ 'comparing across scenarios');
557
+ }
558
+ if (loadShape(baseCtx) !== loadShape(ctx)) {
559
+ warn(` ⚠ baseline '${options.compare}' ran a different load shape ` +
560
+ `(${loadShape(baseCtx)} vs ${loadShape(ctx)}) — ` +
561
+ 'deltas reflect the offered load, not just the workspace');
562
+ }
563
+ const oldConstraints = asBag(base.snapshot).constraints;
564
+ if (oldConstraints !== snapshot.constraints) {
565
+ const oldDisplay = oldConstraints === null || oldConstraints === undefined || oldConstraints === ''
566
+ ? 'none'
567
+ : String(oldConstraints);
568
+ const currentDisplay = snapshot.constraints === null ||
569
+ snapshot.constraints === undefined ||
570
+ snapshot.constraints === ''
571
+ ? 'none'
572
+ : String(snapshot.constraints);
573
+ warn(` ⚠ baseline '${options.compare}' ran under different resource constraints ` +
574
+ `(${oldDisplay} vs ${currentDisplay}) — ` +
575
+ 'deltas reflect the hardware change');
576
+ }
577
+ }
578
+ const spike = options.spike !== '' && measured.tl !== null ? deps.timeline.spikeRecovery(measured.tl) : null;
579
+ const soak = run.mon === null ? null : run.mon.memSlopes();
580
+ const verdictLines = options.diag
581
+ ? deps.verdict.analyze(summary, {
582
+ rcmetrics: Object.keys(run.rcmReport).length > 0 ? run.rcmReport : null,
583
+ mongo: measured.mongoSlow,
584
+ resources: measured.shortStats,
585
+ timeline: measured.tl,
586
+ soak,
587
+ spike: spike,
588
+ })
589
+ : [];
590
+ const diag = options.diag
591
+ ? {
592
+ rcmetrics: run.rcmReport,
593
+ mongo: measured.mongoSlow,
594
+ timeline: measured.tl,
595
+ spike,
596
+ verdict: verdictLines,
597
+ }
598
+ : null;
599
+ // The result is rendered, then the outputs saved: the result is drawn BEFORE anything is
600
+ // saved, so a baseline that cannot be written still leaves the run's answer on screen, and
601
+ // each saved output is announced as it is written.
602
+ if (prose) {
603
+ render({
604
+ name: meta.name,
605
+ ctx,
606
+ summary,
607
+ slo: measured.sloResults,
608
+ spike,
609
+ diag: diag,
610
+ compare: compareRows,
611
+ base,
612
+ resources: run.resources ?? {},
613
+ });
614
+ }
615
+ const artifacts = {};
616
+ if (options.save !== '') {
617
+ const clean = deps.baseline.sanitizeLabel(options.save);
618
+ artifacts.baseline = deps.baseline.save(options.save, {
619
+ label: clean,
620
+ saved_at: isoSeconds(deps.now()),
621
+ ctx,
622
+ summary,
623
+ snapshot,
624
+ });
625
+ if (prose) {
626
+ say(io, '');
627
+ say(io, `✓ saved baseline ${(0, format_1.shownValue)(clean)} (compare later with --compare ${clean})`);
628
+ }
629
+ }
630
+ if (options.report || options.reportPath !== '') {
631
+ artifacts.report = deps.report.writeLoadtest(ctx, summary, measured.sloResults, measured.shortStats, await hostDetails(deps), stamp(deps.now()), options.reportPath || null, {
632
+ snapshot,
633
+ compare: base === null ? null : { label: base.label, saved_at: base.saved_at, rows: compareRows },
634
+ diag,
635
+ });
636
+ if (prose) {
637
+ say(io, '');
638
+ say(io, `✓ wrote ${artifacts.report}`);
639
+ }
640
+ }
641
+ const data = {
642
+ ctx,
643
+ summary,
644
+ slo: measured.sloResults,
645
+ passed: measured.passed,
646
+ snapshot,
647
+ warnings,
648
+ };
649
+ if (diag !== null)
650
+ data.diag = diag;
651
+ if (run.resources !== null && Object.keys(run.resources).length > 0) {
652
+ data.resources = measured.shortStats;
653
+ }
654
+ if (base !== null)
655
+ data.compare = { baseline: base.label, rows: compareRows };
656
+ if (artifacts.baseline !== undefined)
657
+ data.saved_baseline = artifacts.baseline;
658
+ if (artifacts.report !== undefined)
659
+ data.report = artifacts.report;
660
+ return {
661
+ data: loadtestEnvelopeFloats(data),
662
+ exitCode: measured.passed ? 0 : 1,
663
+ warnings,
664
+ artifacts,
665
+ };
666
+ }
667
+ /**
668
+ * One capacity step's row: the VUs right-aligned in 4, the tag left-aligned in 9, req/s
669
+ * with 1 decimal in 7, p95 in 7, the error percentage with 2 decimals in 5, and the mark,
670
+ * where a failure always carries its parentheses.
671
+ */
672
+ function capacityRow(row, tag) {
673
+ const breached = Array.isArray(row.breached) ? row.breached.map(String) : [];
674
+ const mark = (0, format_1.isTruthy)(row.ok) ? 'PASS' : `FAIL (${breached.join('; ')})`;
675
+ return (` ${String(row.vus).padStart(4)} VUs${tag.padEnd(9)} ` +
676
+ `${(0, format_1.formatFixed)(Number(row.rps), 1).padStart(7)} req/s ` +
677
+ `p95 ${(0, timings_1.fmtMs)(Number(row.p95)).padStart(7)} ` +
678
+ `err ${(0, format_1.formatFixed)(Number(row.error_rate) * 100, 2).padStart(5)}% ${mark}`);
679
+ }
680
+ /**
681
+ * `capacity`, rendered AS IT RUNS.
682
+ *
683
+ * The search is the GUI job's transaction (`runPreparedCapacity`), but the CLI does not
684
+ * borrow the job's narration. It handed the job the CLI emitter and drew its table after the
685
+ * fact, so a search printed a 'capacity search:' line and every step twice -- once as an
686
+ * event, before the header, and again in the table -- recorded each as an event in the log,
687
+ * lost the bisect tag and `fmtMs`'s seconds, said 'as N user(s)' with no constrained suffix,
688
+ * never said where the report went, and warned of a restore that failed in the service's
689
+ * words on stderr, or not at all under --json. The job now runs with no emitter and the CLI's
690
+ * hooks: the header once the search is prepared, each row as the step is measured, the
691
+ * restore's warning line on stdout (on stderr under --json), then the closing lines before
692
+ * the report is written.
693
+ */
694
+ async function runCapacityCli(options, io, deps = exports.DEFAULT_PERF_DEPS) {
695
+ await deps.requireDocker();
696
+ const allowed = deps.core.DEFAULT_DEPS.k6.SCENARIOS.filter((scenario) => scenario !== 'custom' && scenario !== 'webhook');
697
+ if (!allowed.includes(options.scenario)) {
698
+ throw new errors_1.ValidationError('capacity supports the built-in scenarios (journey/messages/read/mixed/login/badbot)');
699
+ }
700
+ let rules;
701
+ try {
702
+ rules = deps.core.DEFAULT_DEPS.slo.parse(options.slo);
703
+ }
704
+ catch (error) {
705
+ throw new errors_1.ValidationError(`bad --slo: ${(0, errors_1.errorText)(error)}`);
706
+ }
707
+ if (options.start < 1 || options.maxVus < options.start) {
708
+ throw new errors_1.ValidationError('--start must be >= 1 and --max >= --start');
709
+ }
710
+ coreLoadtest.refuseABadDuration(options.stepDuration, '--step-duration');
711
+ let constraints = {};
712
+ try {
713
+ if (options.constrain !== '')
714
+ constraints = deps.constrain.parse(options.constrain);
715
+ }
716
+ catch (error) {
717
+ throw new errors_1.ValidationError(`bad --constrain: ${(0, errors_1.errorText)(error)}`);
718
+ }
719
+ // Resolved as the CLI's actor first, then guarded (`requireComposeForPerf`).
720
+ const resolved = await deps.resolveName(options.name, (0, audit_1.actor)());
721
+ await deps.core.requireComposeForPerf(resolved, 'capacity');
722
+ const meta = await deps.readMeta(resolved);
723
+ const compose = await deps.readCompose(meta.name);
724
+ const target = deps.core.loadtestTarget(compose);
725
+ const foundServices = deps.core.rcServicesIn(compose);
726
+ const rcServices = foundServices.length > 0 ? foundServices : ['rocketchat'];
727
+ let perService = {};
728
+ try {
729
+ if (Object.keys(constraints).length > 0) {
730
+ perService = deps.constrain.resolveServices(constraints, Object.keys(asBag(compose.services)));
731
+ }
732
+ }
733
+ catch (error) {
734
+ throw new errors_1.ValidationError(`bad --constrain: ${(0, errors_1.errorText)(error)}`);
735
+ }
736
+ const { auth, token } = await performanceIdentity(deps, meta);
737
+ const users = options.usersN > 0 ? await deps.core.loginSeedUsers(meta.rootUrl, options.usersN) : [];
738
+ const req = deps.core.capacityReq({
739
+ name: meta.name,
740
+ scenario: options.scenario,
741
+ usersN: options.usersN,
742
+ slo: options.slo,
743
+ start: options.start,
744
+ maxVus: options.maxVus,
745
+ stepDuration: options.stepDuration,
746
+ constrain: options.constrain,
747
+ });
748
+ const prepared = {
749
+ auth,
750
+ m: meta,
751
+ perService,
752
+ rcServices,
753
+ rules,
754
+ target,
755
+ token,
756
+ users,
757
+ };
758
+ const prose = !options.json;
759
+ const hooks = {
760
+ // A warning line: stdout, or stderr once --json owns stdout.
761
+ warn: (message) => (prose ? say(io, message) : io.writeErr(`${message}\n`)),
762
+ armed: () => {
763
+ if (!prose)
764
+ return;
765
+ const identity = users.length > 0 ? `${String(users.length)} seeded users` : 'admin token';
766
+ const suffix = Object.keys(perService).length > 0
767
+ ? `, constrained ${deps.constrain.human(perService)}`
768
+ : '';
769
+ say(io, `Capacity search: ${options.scenario} as ${identity}, SLO ${options.slo} ` +
770
+ `(steps of ${options.stepDuration}${suffix})\n`);
771
+ },
772
+ step: (row, tag) => {
773
+ if (prose)
774
+ say(io, capacityRow(row, tag));
775
+ },
776
+ };
777
+ const { search } = await deps.core.runPreparedCapacity(req, prepared, events_1.nullEmit, deps.core.DEFAULT_DEPS, hooks);
778
+ const ctx = {
779
+ name: prepared.m.name,
780
+ version: prepared.m.rcVersion,
781
+ scenario: options.scenario,
782
+ slo: options.slo,
783
+ users: prepared.users.length,
784
+ step_duration: options.stepDuration,
785
+ target: prepared.target,
786
+ constrained: Object.keys(prepared.perService).length > 0 ? deps.constrain.human(prepared.perService) : '',
787
+ };
788
+ const { result, why } = capacityCliVerdict(options, search);
789
+ if (prose) {
790
+ say(io, '');
791
+ say(io, `Capacity: ${result}`);
792
+ if (why !== '')
793
+ say(io, ` why it broke: ${why}`);
794
+ }
795
+ const artifacts = {};
796
+ if (options.report || options.reportPath !== '') {
797
+ artifacts.report = deps.report.writeCapacity(ctx, search.steps, result, why, await hostDetails(deps), stamp(deps.now()), options.reportPath || null);
798
+ if (prose) {
799
+ say(io, '');
800
+ say(io, `✓ wrote ${artifacts.report}`);
801
+ }
802
+ }
803
+ const data = {
804
+ ctx,
805
+ // Each step's floats: `lag_max_s` always, and the `0.0` a summary without the key
806
+ // defaults to.
807
+ steps: search.steps.map((row) => floatSpellings(row, coreLoadtest.stepFloats(row))),
808
+ capacity_vus: search.lastPass,
809
+ breach_vus: search.firstFail,
810
+ result,
811
+ why,
812
+ };
813
+ return { data, exitCode: 0, warnings: [], artifacts };
814
+ }