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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +108 -15
  3. package/bin/houston +62 -0
  4. package/data/docs/ARCHITECTURE.md +387 -0
  5. package/data/docs/automation.md +107 -0
  6. package/data/docs/e2ee.md +76 -0
  7. package/data/docs/eks.md +258 -0
  8. package/data/docs/gui.md +282 -0
  9. package/data/docs/guide.md +669 -0
  10. package/data/docs/kubernetes.md +138 -0
  11. package/data/docs/troubleshooting.md +193 -0
  12. package/data/docs/upgrading.md +84 -0
  13. package/data/docs/voice.md +253 -0
  14. package/data/iam/engineer-policy.json +11 -0
  15. package/data/iam/engineer-rbac.yaml +42 -0
  16. package/data/iam/operator-policy.json +211 -0
  17. package/data/loadtest/badbot.js +22 -0
  18. package/data/loadtest/common.js +168 -0
  19. package/data/loadtest/custom.js +20 -0
  20. package/data/loadtest/journey.js +58 -0
  21. package/data/loadtest/login.js +18 -0
  22. package/data/loadtest/messages.js +13 -0
  23. package/data/loadtest/mixed.js +39 -0
  24. package/data/loadtest/read.js +12 -0
  25. package/data/loadtest/webhook.js +20 -0
  26. package/data/monitoring/houston-logs.json +98 -0
  27. package/data/monitoring/k6-loadtest.json +610 -0
  28. package/data/monitoring/mongodb-exporter.json +3007 -0
  29. package/data/monitoring/node-exporter-full.json +16114 -0
  30. package/data/monitoring/rocketchat-metrics.json +6471 -0
  31. package/data/presets/airgapped.yaml +16 -0
  32. package/data/presets/default.yaml +9 -0
  33. package/data/seed/avatar-0.png +0 -0
  34. package/data/seed/avatar-1.png +0 -0
  35. package/data/seed/avatar-2.png +0 -0
  36. package/data/seed/avatar-3.png +0 -0
  37. package/data/seed/avatar-4.png +0 -0
  38. package/data/seed/avatar-5.png +0 -0
  39. package/data/seed/avatar-6.png +0 -0
  40. package/data/seed/avatar-7.png +0 -0
  41. package/data/seed/seed-metrics.csv +3 -0
  42. package/data/seed/seed-preview.png +0 -0
  43. package/data/seed/seed-report.pdf +32 -0
  44. package/data/seed/seed-runbook.txt +3 -0
  45. package/data/skill/SKILL.md +399 -0
  46. package/data/versions.yaml +55 -0
  47. package/data/voice/freeswitch/drachtio.xml +52 -0
  48. package/data/voice/freeswitch/public.xml +87 -0
  49. package/data/webui/app.css +2003 -0
  50. package/data/webui/index.html +678 -0
  51. package/data/webui/js/api.js +561 -0
  52. package/data/webui/js/boot.js +44 -0
  53. package/data/webui/js/clusters-tail.js +1377 -0
  54. package/data/webui/js/clusters.js +896 -0
  55. package/data/webui/js/create.js +276 -0
  56. package/data/webui/js/detail.js +507 -0
  57. package/data/webui/js/jobs.js +636 -0
  58. package/data/webui/js/logs.js +634 -0
  59. package/data/webui/js/main.js +14 -0
  60. package/data/webui/js/options.js +408 -0
  61. package/data/webui/js/people.js +438 -0
  62. package/data/webui/js/perf.js +303 -0
  63. package/data/webui/js/render.js +438 -0
  64. package/data/webui/js/shared.js +3 -0
  65. package/data/webui/js/state.js +583 -0
  66. package/data/webui/js/theme.js +123 -0
  67. package/data/webui/js/util.js +584 -0
  68. package/dist/cli/app.js +593 -0
  69. package/dist/cli/capabilities.js +76 -0
  70. package/dist/cli/cell-widths.js +495 -0
  71. package/dist/cli/entry.js +10 -0
  72. package/dist/cli/error-panel.js +492 -0
  73. package/dist/cli/handlers/actor.js +84 -0
  74. package/dist/cli/handlers/https.js +614 -0
  75. package/dist/cli/handlers/prompt.js +299 -0
  76. package/dist/cli/handlers/users.js +226 -0
  77. package/dist/cli/handlers.js +3678 -0
  78. package/dist/cli/help.js +183 -0
  79. package/dist/cli/index.js +15 -0
  80. package/dist/cli/perf.js +810 -0
  81. package/dist/cli/render.js +254 -0
  82. package/dist/cli/serve.js +858 -0
  83. package/dist/cli/spec-data.js +2593 -0
  84. package/dist/cli/spec-types.js +8 -0
  85. package/dist/cli/usage-error.js +520 -0
  86. package/dist/cli/wire.js +70 -0
  87. package/dist/core/audit.js +346 -0
  88. package/dist/core/backup-compat.js +85 -0
  89. package/dist/core/backup.js +1639 -0
  90. package/dist/core/cluster.js +1398 -0
  91. package/dist/core/configimport.js +344 -0
  92. package/dist/core/data.js +267 -0
  93. package/dist/core/database-of.js +82 -0
  94. package/dist/core/diagnose.js +159 -0
  95. package/dist/core/doctor.js +1518 -0
  96. package/dist/core/edge/acme.js +338 -0
  97. package/dist/core/edge/engine.js +500 -0
  98. package/dist/core/edge/networks.js +174 -0
  99. package/dist/core/edge/paths.js +107 -0
  100. package/dist/core/edge/routes.js +251 -0
  101. package/dist/core/edge/routeyml.js +195 -0
  102. package/dist/core/edge/runtime.js +493 -0
  103. package/dist/core/edge/spec.js +305 -0
  104. package/dist/core/edge/types.js +202 -0
  105. package/dist/core/eks-docs.js +135 -0
  106. package/dist/core/eks.js +2240 -0
  107. package/dist/core/envvars.js +562 -0
  108. package/dist/core/eventlog.js +541 -0
  109. package/dist/core/firstrun.js +153 -0
  110. package/dist/core/journal.js +691 -0
  111. package/dist/core/kube/ask.js +231 -0
  112. package/dist/core/kube/capabilities.js +269 -0
  113. package/dist/core/kube/certmanager.js +452 -0
  114. package/dist/core/kube/chart.js +413 -0
  115. package/dist/core/kube/cluster.js +196 -0
  116. package/dist/core/kube/context.js +545 -0
  117. package/dist/core/kube/endpoints.js +448 -0
  118. package/dist/core/kube/exec.js +195 -0
  119. package/dist/core/kube/forward.js +732 -0
  120. package/dist/core/kube/grafana-ingress.js +110 -0
  121. package/dist/core/kube/ingress.js +218 -0
  122. package/dist/core/kube/manifests.js +361 -0
  123. package/dist/core/kube/monitoring.js +768 -0
  124. package/dist/core/kube/names.js +237 -0
  125. package/dist/core/kube/namespace.js +678 -0
  126. package/dist/core/kube/operator.js +941 -0
  127. package/dist/core/kube/probe.js +202 -0
  128. package/dist/core/kube/reachability.js +163 -0
  129. package/dist/core/kube/release.js +439 -0
  130. package/dist/core/kube/replicaset.js +180 -0
  131. package/dist/core/kube/scale.js +398 -0
  132. package/dist/core/kube/status.js +633 -0
  133. package/dist/core/kube/tools.js +238 -0
  134. package/dist/core/kube/transfer.js +173 -0
  135. package/dist/core/kube/workspace.js +423 -0
  136. package/dist/core/lifecycle/admin.js +64 -0
  137. package/dist/core/lifecycle/create-docker.js +1533 -0
  138. package/dist/core/lifecycle/create-k8s.js +939 -0
  139. package/dist/core/lifecycle/destroy.js +339 -0
  140. package/dist/core/lifecycle/inspect.js +635 -0
  141. package/dist/core/lifecycle/naming.js +298 -0
  142. package/dist/core/lifecycle/notes.js +726 -0
  143. package/dist/core/lifecycle/ownership.js +313 -0
  144. package/dist/core/lifecycle/payload.js +401 -0
  145. package/dist/core/lifecycle/ports.js +388 -0
  146. package/dist/core/lifecycle/preconditions.js +367 -0
  147. package/dist/core/lifecycle/pruning.js +551 -0
  148. package/dist/core/lifecycle/ready.js +753 -0
  149. package/dist/core/lifecycle/request.js +525 -0
  150. package/dist/core/lifecycle/seeding.js +281 -0
  151. package/dist/core/lifecycle/sizing.js +392 -0
  152. package/dist/core/lifecycle/state.js +286 -0
  153. package/dist/core/lifecycle/tlsplan.js +704 -0
  154. package/dist/core/lifecycle/types.js +232 -0
  155. package/dist/core/loadtest.js +995 -0
  156. package/dist/core/migrate.js +612 -0
  157. package/dist/core/monitor.js +494 -0
  158. package/dist/core/postready.js +969 -0
  159. package/dist/core/promote.js +804 -0
  160. package/dist/core/rcapi.js +1285 -0
  161. package/dist/core/recovery.js +75 -0
  162. package/dist/core/runner/engine.js +394 -0
  163. package/dist/core/runner/host.js +298 -0
  164. package/dist/core/runner/locks.js +129 -0
  165. package/dist/core/runner/paths.js +173 -0
  166. package/dist/core/runner/ports.js +172 -0
  167. package/dist/core/runner/queries.js +612 -0
  168. package/dist/core/runner/record.js +563 -0
  169. package/dist/core/scaleseed.js +271 -0
  170. package/dist/core/seed-db.js +208 -0
  171. package/dist/core/sessions.js +472 -0
  172. package/dist/core/skill.js +326 -0
  173. package/dist/core/sso-identities.js +172 -0
  174. package/dist/core/sso.js +703 -0
  175. package/dist/core/tls-local.js +311 -0
  176. package/dist/core/tls.js +878 -0
  177. package/dist/core/topology.js +482 -0
  178. package/dist/core/upgrade.js +868 -0
  179. package/dist/core/users.js +739 -0
  180. package/dist/lib/audit.js +100 -0
  181. package/dist/lib/close-matches.js +238 -0
  182. package/dist/lib/compose.js +672 -0
  183. package/dist/lib/config.js +1398 -0
  184. package/dist/lib/context.js +18 -0
  185. package/dist/lib/errors.js +305 -0
  186. package/dist/lib/events.js +208 -0
  187. package/dist/lib/float-text.js +126 -0
  188. package/dist/lib/format.js +1320 -0
  189. package/dist/lib/home.js +325 -0
  190. package/dist/lib/journal.js +122 -0
  191. package/dist/lib/json-text.js +733 -0
  192. package/dist/lib/jsonout.js +382 -0
  193. package/dist/lib/lock.js +516 -0
  194. package/dist/lib/login-name.js +202 -0
  195. package/dist/lib/map-limit.js +29 -0
  196. package/dist/lib/mkdir-parents.js +90 -0
  197. package/dist/lib/mongo-kernel.js +67 -0
  198. package/dist/lib/monitoring.js +492 -0
  199. package/dist/lib/platform-name.js +59 -0
  200. package/dist/lib/presets/common.js +390 -0
  201. package/dist/lib/presets/composite.js +326 -0
  202. package/dist/lib/presets/e2ee.js +143 -0
  203. package/dist/lib/presets/email.js +172 -0
  204. package/dist/lib/presets/guides.js +27 -0
  205. package/dist/lib/presets/index.js +490 -0
  206. package/dist/lib/presets/keycloak.js +369 -0
  207. package/dist/lib/presets/ldap.js +1285 -0
  208. package/dist/lib/presets/livechat.js +220 -0
  209. package/dist/lib/presets/multi-instance.js +124 -0
  210. package/dist/lib/presets/oidc.js +161 -0
  211. package/dist/lib/presets/public.js +496 -0
  212. package/dist/lib/presets/registry.js +64 -0
  213. package/dist/lib/presets/s3-minio.js +300 -0
  214. package/dist/lib/presets/saml.js +149 -0
  215. package/dist/lib/presets/scenario.js +51 -0
  216. package/dist/lib/presets/types.js +86 -0
  217. package/dist/lib/presets/voice-pbx.js +320 -0
  218. package/dist/lib/presets/voice.js +345 -0
  219. package/dist/lib/presets/webhooks.js +182 -0
  220. package/dist/lib/redact.js +106 -0
  221. package/dist/lib/seed-options.js +68 -0
  222. package/dist/lib/seed-profiles.js +59 -0
  223. package/dist/lib/targz.js +1383 -0
  224. package/dist/lib/teammode.js +25 -0
  225. package/dist/lib/tempdir.js +162 -0
  226. package/dist/lib/unicode-tables.js +2335 -0
  227. package/dist/lib/version-spec.js +357 -0
  228. package/dist/lib/versions.js +463 -0
  229. package/dist/lib/yaml-dump.js +1361 -0
  230. package/dist/perf/baseline.js +168 -0
  231. package/dist/perf/constrain.js +296 -0
  232. package/dist/perf/k6.js +235 -0
  233. package/dist/perf/mongoprof.js +171 -0
  234. package/dist/perf/rcmetrics.js +178 -0
  235. package/dist/perf/report.js +386 -0
  236. package/dist/perf/resources.js +224 -0
  237. package/dist/perf/slo.js +111 -0
  238. package/dist/perf/timeline.js +187 -0
  239. package/dist/perf/timings.js +85 -0
  240. package/dist/perf/verdict.js +201 -0
  241. package/dist/seams/aws-cli.js +126 -0
  242. package/dist/seams/docker-cli.js +280 -0
  243. package/dist/seams/exec.js +861 -0
  244. package/dist/seams/fs/lock.js +528 -0
  245. package/dist/seams/kubectl.js +83 -0
  246. package/dist/seams/rc-http.js +921 -0
  247. package/dist/seed/apply.js +190 -0
  248. package/dist/seed/assets.js +76 -0
  249. package/dist/seed/check.js +391 -0
  250. package/dist/seed/client.js +172 -0
  251. package/dist/seed/executor.js +726 -0
  252. package/dist/seed/history.js +281 -0
  253. package/dist/seed/kinds.js +91 -0
  254. package/dist/seed/plan.js +432 -0
  255. package/dist/seed/receipt.js +339 -0
  256. package/dist/seed/repairs.js +75 -0
  257. package/dist/seed/verification.js +363 -0
  258. package/dist/seed/wording.js +248 -0
  259. package/dist/web/app.js +326 -0
  260. package/dist/web/jobs.js +510 -0
  261. package/dist/web/route-deps.js +211 -0
  262. package/dist/web/route-table.js +213 -0
  263. package/dist/web/routes/backup.js +244 -0
  264. package/dist/web/routes/clusters.js +303 -0
  265. package/dist/web/routes/data.js +187 -0
  266. package/dist/web/routes/edge.js +82 -0
  267. package/dist/web/routes/index.js +63 -0
  268. package/dist/web/routes/jobs.js +95 -0
  269. package/dist/web/routes/logs.js +297 -0
  270. package/dist/web/routes/meta.js +191 -0
  271. package/dist/web/routes/people.js +151 -0
  272. package/dist/web/routes/perf.js +95 -0
  273. package/dist/web/routes/repros.js +550 -0
  274. package/dist/web/routes/session.js +361 -0
  275. package/dist/web/routes/spa.js +198 -0
  276. package/dist/web/security.js +475 -0
  277. package/dist/web/signin.js +246 -0
  278. package/package.json +67 -32
  279. package/.eslintrc +0 -94
  280. package/.swcrc +0 -18
  281. package/dist/bin.js +0 -3
  282. package/dist/cli.js +0 -184
  283. package/dist/commands/createBranch.js +0 -194
  284. package/dist/outputCI.js +0 -59
  285. package/src/bin.js +0 -4
  286. package/src/cli.ts +0 -25
  287. package/src/commands/createBranch.ts +0 -28
  288. package/src/outputCI.ts +0 -12
  289. package/src-old/logs.js +0 -323
  290. package/src-old/md.js +0 -191
  291. package/src-old/release-table.js +0 -60
  292. package/src-old/set-version.js +0 -614
  293. package/src-old/utils.js +0 -15
@@ -0,0 +1,235 @@
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.PROM_RW_URL = exports.SCENARIOS = exports.K6_IMAGE = void 0;
37
+ exports.k6Command = k6Command;
38
+ exports.stageScenario = stageScenario;
39
+ exports.run = run;
40
+ /**
41
+ * Drive HTTP load at a repro with k6, run as a throwaway container.
42
+ *
43
+ * k6 joins the repro's own compose network (`houston-<name>_default`) and targets the
44
+ * INTERNAL service address (`rocketchat:3000` / `traefik:80`) -- so there is no host-port
45
+ * round trip and it works even when the repro binds to loopback only. Scenario scripts ship
46
+ * in `data/loadtest/` and are copied into the repro's workspace, mounted at `/k6`; the
47
+ * script's `handleSummary` writes `/k6/summary.json`, which is read back.
48
+ */
49
+ const fs = __importStar(require("node:fs"));
50
+ const config = __importStar(require("../lib/config"));
51
+ const home_1 = require("../lib/home");
52
+ const record_1 = require("../core/runner/record");
53
+ const host_1 = require("../core/runner/host");
54
+ const paths_1 = require("../core/runner/paths");
55
+ const exec_1 = require("../seams/exec");
56
+ /** arm64/amd64 multi-arch (native on Apple Silicon) -- pinned for reproducibility. */
57
+ exports.K6_IMAGE = 'grafana/k6:0.55.0';
58
+ exports.SCENARIOS = Object.freeze([
59
+ 'messages',
60
+ 'login',
61
+ 'read',
62
+ 'mixed',
63
+ 'journey',
64
+ 'webhook',
65
+ 'badbot',
66
+ 'custom',
67
+ ]);
68
+ /** In-network address of the monitor stack's Prometheus (`loadtest --live`). */
69
+ exports.PROM_RW_URL = 'http://prometheus:9090/api/v1/write';
70
+ /** Passed via an 0600 `--env-file` rather than the argv (see `run`). */
71
+ const SECRET_ENV = Object.freeze(['RC_TOKEN', 'RC_PASS']);
72
+ /**
73
+ * The `docker run` this becomes, with the secrets in a file rather than in argv.
74
+ *
75
+ * `RC_TOKEN` is a bypass-2FA PAT and `RC_PASS` the admin password. Passed as `-e K=V` they
76
+ * sit in the argv, readable by any local user via `ps` or `/proc/<pid>/cmdline` for the
77
+ * whole run and via `docker inspect` afterwards. An 0600 env file in the already
78
+ * bind-mounted directory avoids that.
79
+ *
80
+ * ONLY THOSE TWO go in the file: everything else is harmless, and a user-supplied value (a
81
+ * custom scenario's `RC_BODY`) could contain a newline, which the KEY=VALUE file format
82
+ * cannot represent.
83
+ */
84
+ async function k6Command(dest, env, live, name, scenario, timeline) {
85
+ const secretEnv = Object.entries(env).filter(([k]) => SECRET_ENV.includes(k));
86
+ const plainEnv = Object.entries(env).filter(([k]) => !SECRET_ENV.includes(k));
87
+ const network = `${await (0, record_1.projectName)(name)}_default`;
88
+ const cmd = ['docker', 'run', '--rm', '--network', network, '-v', `${dest}:/k6`];
89
+ const found = await (0, host_1.engine)();
90
+ const podman = found !== null && found.kind === 'podman';
91
+ // Run as the host user so k6 can write /k6/summary.json into the bind-mounted directory.
92
+ // On Linux, bind-mount permissions are enforced and the image's non-root user otherwise
93
+ // cannot write there ("permission denied"); Docker Desktop ignores this but the flag is
94
+ // harmless there. (POSIX only.) Rootless Podman maps the host user to the container's
95
+ // ROOT, and the host uid to a subuid that cannot write the mount: there it is 0:0.
96
+ if (podman && found.rootless) {
97
+ cmd.push('--user', '0:0');
98
+ }
99
+ else if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
100
+ cmd.push('--user', `${String(process.getuid())}:${String(process.getgid())}`);
101
+ }
102
+ for (const [k, v] of plainEnv)
103
+ cmd.push('-e', `${k}=${v}`);
104
+ const envfile = (0, home_1.joinPath)(dest, 'k6.env');
105
+ fs.rmSync(envfile, { force: true });
106
+ if (secretEnv.length > 0) {
107
+ fs.writeFileSync(envfile, secretEnv.map(([k, v]) => `${k}=${v}\n`).join(''), {
108
+ encoding: 'utf8',
109
+ });
110
+ fs.chmodSync(envfile, 0o600);
111
+ cmd.push('--env-file', envfile);
112
+ }
113
+ // Podman resolves no short names without asking, and nothing here can answer.
114
+ cmd.push(podman ? `docker.io/${exports.K6_IMAGE}` : exports.K6_IMAGE, 'run');
115
+ // Stream every measurement so houston can build latency-over-time buckets.
116
+ if (timeline)
117
+ cmd.push('--out', 'json=/k6/points.json');
118
+ // Push metrics into the monitor stack's Prometheus as the test runs.
119
+ if (live)
120
+ cmd.push('--out', 'experimental-prometheus-rw');
121
+ cmd.push(`/k6/${scenario}.js`);
122
+ return [cmd, envfile];
123
+ }
124
+ /** Put the script, its users and its environment where the container will find them. */
125
+ function stageScenario(options) {
126
+ const { duration, extraEnv, live, name, password, ramp, scenario, spike, target, token, uid, user, users, vus, } = options;
127
+ const ws = (0, paths_1.workspace)(name);
128
+ const dest = (0, home_1.joinPath)(ws, 'loadtest');
129
+ fs.mkdirSync(dest, { recursive: true });
130
+ for (const fn of [`${scenario}.js`, 'common.js']) {
131
+ fs.writeFileSync((0, home_1.joinPath)(dest, fn), fs.readFileSync(config.dataPath('loadtest', fn), 'utf8'), {
132
+ encoding: 'utf8',
133
+ });
134
+ }
135
+ // A stale result from a prior run must not be mistaken for this one.
136
+ const summary = (0, home_1.joinPath)(dest, 'summary.json');
137
+ fs.rmSync(summary, { force: true });
138
+ // Ditto for the timeline point stream.
139
+ fs.rmSync((0, home_1.joinPath)(dest, 'points.json'), { force: true });
140
+ const env = {
141
+ RC_URL: target,
142
+ RC_TOKEN: token,
143
+ RC_UID: uid,
144
+ RC_USER: user,
145
+ RC_PASS: password,
146
+ DURATION: duration,
147
+ };
148
+ if (spike)
149
+ env.SPIKE = spike;
150
+ else if (ramp)
151
+ env.RAMP = ramp;
152
+ else
153
+ env.VUS = String(vus);
154
+ if (live) {
155
+ env.K6_PROMETHEUS_RW_SERVER_URL = exports.PROM_RW_URL;
156
+ env.K6_PROMETHEUS_RW_TREND_STATS = 'p(95),p(99),avg';
157
+ }
158
+ const ufile = (0, home_1.joinPath)(dest, 'users.json');
159
+ if (users !== null && users !== undefined && users.length > 0) {
160
+ fs.writeFileSync(ufile, JSON.stringify(users), { encoding: 'utf8' });
161
+ env.RC_USERS_FILE = '/k6/users.json';
162
+ }
163
+ else {
164
+ // A stale user list from a prior run -- this run is admin-only.
165
+ fs.rmSync(ufile, { force: true });
166
+ }
167
+ if (extraEnv !== null && extraEnv !== undefined) {
168
+ for (const [k, v] of Object.entries(extraEnv)) {
169
+ if (v !== null && v !== undefined)
170
+ env[k] = v;
171
+ }
172
+ }
173
+ return { dest, env, summary };
174
+ }
175
+ /**
176
+ * Run `scenario` against `target` (an in-network URL) and return the summary.
177
+ *
178
+ * `users` is an optional list of pre-authenticated seeded users ({username, password,
179
+ * token, uid}) -- VUs round-robin over them so load carries real per-user identity instead
180
+ * of one shared admin token.
181
+ *
182
+ * Streams k6's live progress to the terminal. Throws if k6 produced no summary (for
183
+ * example it could not reach the target).
184
+ */
185
+ async function run(name, scenario, options) {
186
+ const { vus, duration, ramp = null, token, uid, target, user = config.ADMIN_USERNAME, password = config.ADMIN_PASSWORD, extraEnv = null, users = null, quiet = false, timeline = false, spike = null, live = false, } = options;
187
+ const { dest, env, summary } = stageScenario({
188
+ duration,
189
+ extraEnv,
190
+ live,
191
+ name,
192
+ password,
193
+ ramp,
194
+ scenario,
195
+ spike,
196
+ target,
197
+ token,
198
+ uid,
199
+ user,
200
+ users,
201
+ vus,
202
+ });
203
+ const [cmd, envfile] = await k6Command(dest, env, live, name, scenario, timeline);
204
+ try {
205
+ // k6 writes its banner and progress to stdout. `quiet` (--json mode) reroutes it to
206
+ // STDERR so stdout stays a single parseable JSON object for CI and scripts -- the
207
+ // `--json` contract is that stdout carries the envelope and nothing else.
208
+ if (quiet) {
209
+ await (0, exec_1.stream)(cmd, {
210
+ onStdout: (chunk) => process.stderr.write(chunk),
211
+ onStderr: (chunk) => process.stderr.write(chunk),
212
+ encoding: 'utf8',
213
+ });
214
+ }
215
+ else {
216
+ await (0, exec_1.inherit)(cmd);
217
+ }
218
+ }
219
+ finally {
220
+ // Never leave the PAT on disk.
221
+ fs.rmSync(envfile, { force: true });
222
+ }
223
+ if (!fs.existsSync(summary)) {
224
+ throw new Error('k6 produced no summary (see output above) — could it reach the target, and is ' +
225
+ `the image available? (\`docker pull ${exports.K6_IMAGE}\`)`);
226
+ }
227
+ try {
228
+ return JSON.parse(fs.readFileSync(summary, 'utf8'));
229
+ }
230
+ catch (error) {
231
+ // Truncated or corrupt summary (killed mid-write, disk full).
232
+ throw new Error(`k6 summary was unreadable (${error instanceof Error ? error.message : String(error)}) — ` +
233
+ 'the run likely did not finish', { cause: error });
234
+ }
235
+ }
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DB = void 0;
4
+ exports.dbOf = dbOf;
5
+ exports.lastJson = lastJson;
6
+ exports.asInt = asInt;
7
+ exports.start = start;
8
+ exports.stop = stop;
9
+ exports.collect = collect;
10
+ exports.installJournalRepairs = installJournalRepairs;
11
+ /**
12
+ * Capture MongoDB slow queries during a load test.
13
+ *
14
+ * Turns on Mongo's query profiler (level 1: log ops slower than `slowms`) for the duration of
15
+ * the run, then reads `system.profile` back: the slowest queries, and whether they COLLSCAN
16
+ * -- "slow because there is no index on X" is the single most useful line of evidence a perf
17
+ * ticket can carry.
18
+ *
19
+ * Everything runs through `docker compose exec` on the repro's mongodb container (mongosh,
20
+ * falling back to the legacy `mongo` shell for old pairings), is version-tolerant, and is
21
+ * strictly best-effort: any failure degrades to "slow-query capture unavailable" without
22
+ * affecting the test.
23
+ */
24
+ const database_of_1 = require("../core/database-of");
25
+ const journal_1 = require("../core/journal");
26
+ const engine_1 = require("../core/runner/engine");
27
+ /**
28
+ * The DEFAULT database, kept only as the fallback when the workspace's own `MONGO_URL`
29
+ * cannot be read.
30
+ *
31
+ * `env --set MONGO_URL=...` is a supported and documented override, and hardcoding this
32
+ * meant the bulk insert (or the profiler) addressed a database Rocket.Chat was not reading
33
+ * -- reporting `inserted: 50000` while the directory stayed empty, and `--clear-scale`
34
+ * then reporting it had removed them, so the round trip was internally consistent and
35
+ * externally wrong.
36
+ */
37
+ exports.DB = 'rocketchat';
38
+ /**
39
+ * The database this workspace's Rocket.Chat actually uses.
40
+ *
41
+ * The shared lookup lives in `core/database-of.ts`, below both this module and backup, so
42
+ * there is no upward edge to defer and one implementation rather than two. The fallback to
43
+ * `DB` is kept: a lookup must never fail the run.
44
+ */
45
+ async function dbOf(name) {
46
+ return (await (0, database_of_1.databaseOf)(name)) || exports.DB;
47
+ }
48
+ async function uriFor(name) {
49
+ return `mongodb://localhost:27017/${await dbOf(name)}`;
50
+ }
51
+ /**
52
+ * Run JS in the repro's mongodb container; mongosh first, the legacy `mongo` shell as the
53
+ * fallback. Returns stdout, or null if neither shell worked.
54
+ */
55
+ async function evalJs(name, js) {
56
+ const uri = await uriFor(name);
57
+ for (const shell of ['mongosh', 'mongo']) {
58
+ const [rc, out] = await (0, engine_1.composeExecCapture)(name, 'mongodb', [
59
+ shell,
60
+ '--quiet',
61
+ uri,
62
+ '--eval',
63
+ js,
64
+ ]);
65
+ if (rc === 0 && out.trim())
66
+ return out;
67
+ }
68
+ return null;
69
+ }
70
+ /** The last stdout line that parses as JSON (shells may print banners first). */
71
+ function lastJson(out) {
72
+ const lines = out.trim().split('\n');
73
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
74
+ const line = lines[i].trim();
75
+ if (line.startsWith('{') || line.startsWith('[')) {
76
+ try {
77
+ return JSON.parse(line);
78
+ }
79
+ catch {
80
+ continue;
81
+ }
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+ /**
87
+ * Coerce a value parsed out of a shell's stdout.
88
+ *
89
+ * `null`, a missing key, or a shell that serialised a NumberLong as an object must not
90
+ * throw here -- this runs inside the callers' `finally`.
91
+ */
92
+ function asInt(value, fallback) {
93
+ if (typeof value === 'boolean')
94
+ return value ? 1 : 0;
95
+ if (typeof value === 'number')
96
+ return Number.isFinite(value) ? Math.trunc(value) : fallback;
97
+ if (typeof value !== 'string')
98
+ return fallback;
99
+ const text = value.trim();
100
+ if (!/^[+-]?\d+$/u.test(text))
101
+ return fallback;
102
+ return Number.parseInt(text, 10);
103
+ }
104
+ /**
105
+ * Enable profiling (level 1, > slowms) on the workspace's database.
106
+ *
107
+ * Returns the state `stop` needs, or null if nothing was changed. NOTE THE ORDERING:
108
+ * `setProfilingLevel` has ALREADY taken effect by the time the output is read, so an
109
+ * unparseable prior state still returns a marker (assuming the default level 0). Returning
110
+ * null there would leave the profiler running for the life of the repro, writing an entry
111
+ * for every slow op.
112
+ */
113
+ async function start(name, slowms = 100) {
114
+ const js = 'var prev = db.getProfilingStatus();' +
115
+ // A numeric argument works in old shells too.
116
+ `db.setProfilingLevel(1, ${String(Math.trunc(slowms))});` +
117
+ 'print(JSON.stringify({was: prev.was, slowms: prev.slowms}));';
118
+ const out = await evalJs(name, js);
119
+ // No usable shell -> the enable never ran, so there is nothing to undo.
120
+ if (out === null)
121
+ return null;
122
+ const prior = lastJson(out);
123
+ if (typeof prior === 'object' && prior !== null && 'was' in prior)
124
+ return prior;
125
+ return { was: 0, slowms: 100, prior_unknown: true };
126
+ }
127
+ /** Restore the prior profiling level (best-effort). */
128
+ async function stop(name, prior) {
129
+ if (prior === null || prior === undefined || Object.keys(prior).length === 0)
130
+ return;
131
+ const js = `db.setProfilingLevel(${String(asInt(prior.was, 0))}, ` +
132
+ `${String(asInt(prior.slowms, 100))});`;
133
+ await evalJs(name, js);
134
+ }
135
+ /** Slow ops profiled since `sinceEpochMs`. */
136
+ async function collect(name, sinceEpochMs, limit = 5) {
137
+ const database = await dbOf(name);
138
+ const js = `var q = {ts: {$gte: new Date(${String(Math.trunc(sinceEpochMs))})},` +
139
+ ` ns: {$ne: "${database}.system.profile"}};` +
140
+ 'var docs = db.system.profile.find(q).sort({millis: -1}).limit(200).toArray();' +
141
+ 'var out = {total: docs.length, collscan: 0, slow: []};' +
142
+ 'for (var i = 0; i < docs.length; i++) {' +
143
+ ' var d = docs[i];' +
144
+ " var plan = d.planSummary || '';" +
145
+ " if (plan.indexOf('COLLSCAN') >= 0) out.collscan++;" +
146
+ ` if (out.slow.length < ${String(Math.trunc(limit))}) {` +
147
+ " var cmd = '';" +
148
+ ' try { cmd = JSON.stringify(d.command || d.query || {}).slice(0, 160); } catch (e) {}' +
149
+ " out.slow.push({ns: d.ns || '', op: d.op || '', millis: d.millis || 0," +
150
+ ' plan: plan, docs: d.docsExamined || 0, keys: d.keysExamined || 0,' +
151
+ ' ret: d.nreturned || 0, cmd: cmd});' +
152
+ ' }' +
153
+ '}' +
154
+ 'print(JSON.stringify(out));';
155
+ const out = await evalJs(name, js);
156
+ const parsed = out === null ? null : lastJson(out);
157
+ return typeof parsed === 'object' && parsed !== null && 'slow' in parsed
158
+ ? parsed
159
+ : null;
160
+ }
161
+ /** Restore the profiler a killed run left armed. */
162
+ async function repairProfiler(entry) {
163
+ const prior = entry.detail.prior;
164
+ if (prior === null || prior === undefined)
165
+ return false;
166
+ await stop(entry.workspace, prior);
167
+ return true;
168
+ }
169
+ function installJournalRepairs() {
170
+ (0, journal_1.registerRepair)(journal_1.MONGO_PROFILER_ON, repairProfiler);
171
+ }
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RCMetricsSampler = exports.ServiceSeries = exports.FETCH_JS = exports.METRICS = void 0;
4
+ exports.parseProm = parseProm;
5
+ /**
6
+ * Sample Rocket.Chat's own Prometheus metrics during a load test.
7
+ *
8
+ * RC (a Node app) exposes prom-client metrics on :9458 inside the container when
9
+ * `Prometheus_Enabled` is on -- including EVENT-LOOP LAG, the saturation signal for a Node
10
+ * process: once the event loop lags, every request queues behind it. The port is not
11
+ * published to the host, so each sample runs `node -e` inside the RC container (Node ships
12
+ * with RC by definition) -- no extra images, no Grafana.
13
+ */
14
+ const engine_1 = require("../core/runner/engine");
15
+ /**
16
+ * Unlabeled gauges worth tracking, verified against a live RC `/metrics` dump and the
17
+ * official dashboard.
18
+ *
19
+ * The lag HISTOGRAM gauges (`_max`/`_p99`, reset per scrape) matter more than the
20
+ * instantaneous `nodejs_eventloop_lag_seconds`, which samples BETWEEN stalls and reads
21
+ * near-zero even while requests queue for seconds.
22
+ */
23
+ exports.METRICS = Object.freeze({
24
+ nodejs_eventloop_lag_seconds: 'eventloop_lag_s',
25
+ nodejs_eventloop_lag_max_seconds: 'eventloop_lag_max_s',
26
+ nodejs_eventloop_lag_p99_seconds: 'eventloop_lag_p99_s',
27
+ nodejs_heap_size_used_bytes: 'heap_used_bytes',
28
+ rocketchat_ddp_connected_users: 'ddp_users',
29
+ rocketchat_oplog_queue: 'oplog_queue',
30
+ });
31
+ const LINE_RE = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{[^}]*\})?\s+([0-9.eE+-]+)\s*$/u;
32
+ /**
33
+ * `require('http')` instead of `fetch()`: works on every Node version RC ever shipped.
34
+ *
35
+ * `setTimeout` bounds the request, because a saturated event loop -- exactly what this
36
+ * sampler exists to detect -- can accept the connection and then never finish the
37
+ * response, which would hang `node` and the exec around it indefinitely.
38
+ */
39
+ exports.FETCH_JS = "var q=require('http').get('http://localhost:9458/metrics',function(r){" +
40
+ "var d='';r.on('data',function(c){d+=c});r.on('end',function(){console.log(d)})" +
41
+ "}).on('error',function(){process.exit(1)});" +
42
+ 'q.setTimeout(5000,function(){q.destroy();process.exit(1)})';
43
+ /** Belt to the JS timeout's braces: bound the exec itself too. */
44
+ const SAMPLE_TIMEOUT_S = 15.0;
45
+ /**
46
+ * Prometheus exposition text -> {metric name: value}.
47
+ *
48
+ * Labeled series of the same name are SUMMED; the tracked metrics are unlabeled gauges
49
+ * anyway, so this only matters for anything else a future RC exposes.
50
+ */
51
+ function parseProm(text) {
52
+ const out = {};
53
+ for (const raw of text.split('\n')) {
54
+ if (!raw || raw.startsWith('#'))
55
+ continue;
56
+ const m = LINE_RE.exec(raw.trim());
57
+ if (m === null)
58
+ continue;
59
+ const value = Number(m[3]);
60
+ // A malformed number skips the line; `Number` answers NaN, so the check is explicit.
61
+ if (Number.isNaN(value))
62
+ continue;
63
+ const name = m[1];
64
+ out[name] = (out[name] ?? 0.0) + value;
65
+ }
66
+ return out;
67
+ }
68
+ /** One service's samples, keyed by the short name `METRICS` maps to. */
69
+ class ServiceSeries {
70
+ constructor() {
71
+ this.samples = {};
72
+ }
73
+ add(parsed) {
74
+ var _a;
75
+ for (const [promName, key] of Object.entries(exports.METRICS)) {
76
+ if (promName in parsed) {
77
+ ((_a = this.samples)[key] ?? (_a[key] = [])).push(parsed[promName]);
78
+ }
79
+ }
80
+ }
81
+ summary() {
82
+ const out = {};
83
+ for (const [key, vals] of Object.entries(this.samples)) {
84
+ if (vals.length > 0) {
85
+ out[key] = {
86
+ mean: vals.reduce((a, b) => a + b, 0) / vals.length,
87
+ max: Math.max(...vals),
88
+ last: vals[vals.length - 1],
89
+ n: vals.length,
90
+ };
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ }
96
+ exports.ServiceSeries = ServiceSeries;
97
+ /**
98
+ * Polls every RC instance's `/metrics` while a test runs.
99
+ *
100
+ * Mirrors the resource monitor's lifecycle: `start()` -> workload -> `stop()` -> report.
101
+ *
102
+ * A sampler on a THREAD would guard its series with a lock, because a wait with a timeout
103
+ * can leave the worker live when `stop` reads. Here it is cooperative asynchronous
104
+ * concurrency instead: there is one loop, it observes a stop flag, and `stop()` AWAITS it
105
+ * -- so there is no concurrent reader to guard against and no change during iteration to
106
+ * prevent.
107
+ */
108
+ class RCMetricsSampler {
109
+ constructor(name, services, interval = 2.0) {
110
+ this.series = new Map();
111
+ this.stopping = false;
112
+ this.running = null;
113
+ this.name = name;
114
+ this.services = services;
115
+ this.interval = interval;
116
+ }
117
+ start() {
118
+ this.stopping = false;
119
+ this.running = this.run();
120
+ return this;
121
+ }
122
+ async run() {
123
+ while (!this.stopping) {
124
+ for (const svc of this.services) {
125
+ // The seam takes MILLISECONDS; `SAMPLE_TIMEOUT_S` is seconds.
126
+ const [rc, text] = await (0, engine_1.composeExecCapture)(this.name, svc, ['node', '-e', exports.FETCH_JS], SAMPLE_TIMEOUT_S * 1000);
127
+ if (rc === 0 && text) {
128
+ let entry = this.series.get(svc);
129
+ if (entry === undefined) {
130
+ entry = new ServiceSeries();
131
+ this.series.set(svc, entry);
132
+ }
133
+ entry.add(parseProm(text));
134
+ }
135
+ }
136
+ await this.wait(this.interval);
137
+ }
138
+ }
139
+ /** `Event.wait(interval)` -- returns early when `stop()` is called. */
140
+ wait(seconds) {
141
+ return new Promise((resolve) => {
142
+ if (this.stopping) {
143
+ resolve();
144
+ return;
145
+ }
146
+ const timer = setTimeout(() => {
147
+ clearInterval(poll);
148
+ resolve();
149
+ }, seconds * 1000);
150
+ const poll = setInterval(() => {
151
+ if (this.stopping) {
152
+ clearTimeout(timer);
153
+ clearInterval(poll);
154
+ resolve();
155
+ }
156
+ }, 25);
157
+ });
158
+ }
159
+ /**
160
+ * `{service: {eventloop_lag_s: {mean,max,last,n}, …}}` -- empty if the endpoint never
161
+ * answered (metrics off, or an RC too old to expose them).
162
+ */
163
+ async stop() {
164
+ this.stopping = true;
165
+ if (this.running !== null) {
166
+ await this.running;
167
+ this.running = null;
168
+ }
169
+ const out = {};
170
+ for (const [svc, s] of this.series) {
171
+ const summary = s.summary();
172
+ if (Object.keys(summary).length > 0)
173
+ out[svc] = summary;
174
+ }
175
+ return out;
176
+ }
177
+ }
178
+ exports.RCMetricsSampler = RCMetricsSampler;